<?php

namespace App\Http\Controllers\Services;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\UrlController;
use App\Http\Repository\UtilityRepository;
use App\Models\Settings\CmnBranch;
use App\Models\Services\SchServices;
use App\Models\Employee\SchEmployee;
use App\Models\Employee\SchEmployeeService;
use App\Models\UserManagement\SecUserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use ErrorException;
use Exception;


class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function service()
    {
        $isMOGAdminOrSysAdmin = SecUserRole::where('sec_user_id', auth()->id())
                                ->where(function ($query) {
                                    $query->whereHas('role', function ($roleQuery) {
                                        $roleQuery->where('name', 'MOG Admin');
                                    })
                                    ->orWhereHas('user', function ($userQuery) {
                                        $userQuery->where('is_sys_adm', 1);
                                    });
                                })
                                ->exists();

        return view('services.service', compact('isMOGAdminOrSysAdmin'));
    }


    /**
     * Summary of create department
     * Author: kaysar
     * Date: 08-Aug-2021
     * @param Request $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function serviceStore(Request $data)
    {
        try {

            $validator = Validator::make($data->all(), [
                'title' => ['required', 'string'],
                'title_slug' => ['required', 'string'],
                'price' => ['required'],
                'durationTimeMinute' => ['required'],
                'sch_service_category_id' => ['required'],
                'award_points' => ['nullable', 'boolean'],
                'points' => ['required_if:award_points,1', 'nullable', 'integer'],
                // 'minimum_time_required_to_booking_in_minute' => ['required'],
                //'minimum_time_required_to_cancel_in_minute' => ['required'],
                //'serviceimage' => 'image|mimes:jpeg,png,jpg,gif|max:512|required',
            ]);

            if (!$validator->fails()) {
                $serviceImage = $data->serviceimage;
                if ($serviceImage != null) {
                    $serviceImage = UtilityRepository::saveFile($serviceImage, ['image/png', 'image/png', 'image/jpg', 'image/jpeg']);
                    $data['image'] = $serviceImage;
                }

                $paddingTimeB = $data->padding_time_before_hour . ':' . $data->padding_time_before_minute;
                $paddingTimeA = $data->padding_time_after_hour . ':' . $data->padding_time_after_minute;

                $duration_in_time = $data->durationTimeHour . ':' . $data->durationTimeMinute;
                $minimum_time_required_to_booking_in_time = ($data->minimum_time_required_to_booking_in_hour ?? '00') . ':' . ($data->minimum_time_required_to_booking_in_minute ?? '00');
                $minimum_time_required_to_cancel_in_time = $data->minimum_time_required_to_cancel_in_hour . ':' . $data->minimum_time_required_to_cancel_in_minute;

                $time_slot_in_time = $data->time_slot_in_time_hour . ':' . $data->time_slot_in_time_minute;


                $data['duration_in_time'] = $duration_in_time;
                $data['padding_time_before'] = $paddingTimeB;
                $data['padding_time_after'] = $paddingTimeA;
                $data['time_slot_in_time'] = $time_slot_in_time;
                //$data['minimum_time_required_to_booking_in_time'] = $minimum_time_required_to_booking_in_time;
                //$data['minimum_time_required_to_cancel_in_time'] = $minimum_time_required_to_cancel_in_time;
                $data['id']=null;
                $data['award_points']=$data->award_points ? 1 : 0;
                SchServices::create($data->all());

                $urlController = new UrlController();

                $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/service/'.$data['title_slug'], $data['title_slug'], 'service', '', '');

                $branches = CmnBranch::where('status', 1)->get();

                foreach($branches as $branch) {
                    $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$branch['name_slug'].'/service/'.$data['title_slug'], $branch['name_slug'] .'_'.$data['title_slug'], 'branch.service', '', '');
                }

                return $this->apiResponse(['status' => '1', 'data' => ''], 200);
            }
            return $this->apiResponse(['status' => '500', 'data' => $validator->errors()], 400);
        } catch (ErrorException $ex) {
            return  $this->apiResponse(['status' => '-501', 'data' => $ex->getMessage()], 400);
        }catch (Exception $ex) {
            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }

    /**
     * Summary of update department
     * Author: kaysar
     * Date: 08-Aug-2021
     * @param Request $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function serviceUpdate(Request $data)
    {
        try {
            $validator = Validator::make($data->toArray(), [
                'title' => ['required', 'string'],
                'title_slug' => ['required', 'string'],
                'serviceimage' => 'image|mimes:jpeg,png,jpg,gif|max:512',
                'durationTimeMinute' => ['required'],
                'sch_service_category_id' => ['required'],
                // 'minimum_time_required_to_booking_in_minute' => ['required'],
                // 'minimum_time_required_to_cancel_in_minute' => ['required'],
            ]);

            if (!$validator->fails()) {
                $paddingTimeBefore = $data->padding_time_before_hour . ':' . $data->padding_time_before_minute;
                $paddingTimeAfter = $data->padding_time_after_hour . ':' . $data->padding_time_after_minute;

                $durationTimeHour = $data->durationTimeHour . ':' . $data->durationTimeMinute;
                $minimum_time_required_to_booking_in_time = ($data->minimum_time_required_to_booking_in_hour ?? '00') . ':' . ($data->minimum_time_required_to_booking_in_minute ?? '00');
                $minimum_time_required_to_cancel_in_time = $data->minimum_time_required_to_cancel_in_hour . ':' . $data->minimum_time_required_to_cancel_in_minute;

                $time_slot_in_time = $data->time_slot_in_time_hour . ':' . $data->time_slot_in_time_minute;

                $imagePath = $data->serviceimage;
                if ($imagePath != null) {
                    $imagePath = UtilityRepository::saveFile($imagePath, ['image/png', 'image/png', 'image/jpg', 'image/jpeg']);
                }

                $dataForUpdate = [
                    'title' => $data->title,
                    'title_slug' => $data->title_slug,
                    'sch_service_category_id' => $data->sch_service_category_id,
                    'visibility' => $data->visibility,
                    'price' => $data->price,
                    'duration_in_days' => $data->duration_in_days,
                    'duration_in_time' => $durationTimeHour,
                    'time_slot_in_time' => $time_slot_in_time,
                    'padding_time_before' => $paddingTimeBefore,
                    'padding_time_after' => $paddingTimeAfter,
                    'appoinntment_limit_type' => $data->appoinntment_limit_type,
                    'appoinntment_limit' => $data->appoinntment_limit,
                    // 'minimum_time_required_to_booking_in_days' => $data->minimum_time_required_to_booking_in_days ?? 0,
                    // 'minimum_time_required_to_booking_in_time' => $minimum_time_required_to_booking_in_time ?? ,
                    // 'minimum_time_required_to_cancel_in_days' => $data->minimum_time_required_to_cancel_in_days ?? 0,
                    // 'minimum_time_required_to_cancel_in_time' => $minimum_time_required_to_cancel_in_time ?? '00:00:00',
                    'remarks'=>$data->remarks,
                    'award_points'=>$data->award_points ? 1 : 0,
                    'points'=>$data->points ?? null,
                ];
                if ($imagePath != null || $imagePath != '')
                    $dataForUpdate['image'] = $imagePath;

                SchServices::where('id', $data->id)->update($dataForUpdate);

                $urlController = new UrlController();

                $branches = CmnBranch::where('status', 1)->get(); 

                if ($data['current_title_slug'] && $data['current_title_slug'] != '') {
                    $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/service/'.$data['title_slug'], $data['title_slug'], 'service', config('app.url').'/fireworks-appointment-booking/service/'.$data['current_title_slug'], $data['current_title_slug']);

                    foreach($branches as $branch) {
                        $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$branch['name_slug'].'/service/'.$data['title_slug'], $branch['name_slug'] .'_'.$data['title_slug'], 'branch.service', config('app.url').'/fireworks-appointment-booking/branch/'.$branch['name_slug'].'/service/'.$data['current_title_slug'], $branch['name_slug'].'_'.$data['current_title_slug']);
                    }
                } else {
                    $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/service/'.$data['title_slug'], $data['title_slug'], 'service', '', '');

                    foreach($branches as $branch) {
                        $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$branch['name_slug'].'/service/'.$data['title_slug'], $branch['name_slug'] .'_'.$data['title_slug'], 'branch.service', '', '');
                    }
                }

                return $this->apiResponse(['status' => '1', 'data' => ''], 200);
            }

            return $this->apiResponse(['status' => '500', 'data' => $validator->errors()], 400);
        }catch (ErrorException $ex) {
            return  $this->apiResponse(['status' => '-501', 'data' => $ex->getMessage()], 400);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }


    /**
     * Summary of delete Department
     * Author: Kaysar
     * Date: 8-Aug-2021
     * @param Request $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteService(Request $data)
    {
        try {
            $rtr = SchServices::where('id', $data->id)->delete();

            $urlController = new UrlController();

            $urlController->removeShortenSlugUrl($data->title_slug);

            $branches = CmnBranch::where('status', 1)->get();

            foreach($branches as $branch) {
                $urlController->removeShortenSlugUrl($branch->name_slug.'_'.$data->title_slug);
            }

            return $this->apiResponse(['status' => '1', 'data' => $rtr], 200);
        } catch (Exception $ex) {
            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }

    /**
     * Summary of get brandepartment list
     * Author: Kaysar
     * Date: 8-Aug-2021
     * @return \Illuminate\Http\JsonResponse
     */
    public function getServiceList(Request $request)
    {
        try {
            $userId = auth()->id();
            $userEmail = auth()->user()->email;

            // Check if user is MOG Admin or Sys Admin
            $isMOGAdminOrSysAdmin = SecUserRole::where('sec_user_id', $userId)
                ->where(function ($query) {
                    $query->whereHas('role', function ($roleQuery) {
                        $roleQuery->where('name', 'MOG Admin');
                    })
                    ->orWhereHas('user', function ($userQuery) {
                        $userQuery->where('is_sys_adm', 1);
                    });
                })
                ->exists();

            // Base query
            $query = SchServices::join('sch_service_categories', 'sch_services.sch_service_category_id', '=', 'sch_service_categories.id')
                ->select(
                    'sch_service_categories.name as category',
                    'sch_services.id',
                    'sch_services.title',
                    'sch_services.title_slug',
                    'sch_services.image',
                    'sch_services.sch_service_category_id',
                    'sch_services.visibility',
                    'sch_services.price',
                    'sch_services.duration_in_days',
                    'sch_services.duration_in_time',
                    'sch_services.time_slot_in_time',
                    'sch_services.padding_time_before',
                    'sch_services.padding_time_after',
                    'sch_services.appoinntment_limit_type',
                    'sch_services.appoinntment_limit',
                    'sch_services.minimum_time_required_to_booking_in_days',
                    'sch_services.minimum_time_required_to_booking_in_time',
                    'sch_services.minimum_time_required_to_cancel_in_days',
                    'sch_services.minimum_time_required_to_cancel_in_time',
                    'sch_services.remarks',
                    'sch_services.award_points',
                    'sch_services.points',
                );

            if (!$isMOGAdminOrSysAdmin) {
                // Get user's branch ID by matching email in cmn_branches
                $branch = CmnBranch::where('email', $userEmail)->first();

                if ($branch) {
                    // Get employees in this branch
                    $employeeIds = SchEmployee::where('cmn_branch_id', $branch->id)->pluck('id');

                    // Get distinct service IDs associated with these employees
                    $serviceIds = SchEmployeeService::whereIn('sch_employee_id', $employeeIds)
                        ->distinct()
                        ->pluck('sch_service_id');

                    
                    $query->whereIn('sch_services.id', $serviceIds);
                } else {
                    return $this->apiResponse(['status' => '1', 'data' => []], 200);
                }
            }

            $data = $query->orderByRaw('sch_services.created_at asc')->get();
            return $this->apiResponse(['status' => '1', 'data' => $data], 200);
        } catch (Exception $qx) {
            return $this->apiResponse(['status' => '403', 'data' => $qx], 400);
        }
    }
}
