<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Admin\Area;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Helpers\Response;
use Illuminate\Support\Carbon;
use App\Models\Admin\ParlourList;
use App\Http\Controllers\Controller;
use App\Models\Admin\ParlourHasService;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin\ParlourListHasSchedule;
use App\Models\Vendor\Manager;
use Illuminate\Validation\ValidationException;
use App\Constants\GlobalConst;

class ParlourListController extends Controller
{
    /**
     * Method for show parlour list page
     * @return view
     */
    public function index(){
        $page_title     = "Salon List";
        $parlour_lists = ParlourList::whereNot('status',GlobalConst::STATUSPENDING)
        ->orderByDesc('id')
        ->get();

        return view('admin.sections.parlour-list.index',compact(
            'page_title',
            'parlour_lists'
        ));
    }
     /**
     * Method for show parlour list page
     * @return view
     */
    public function parlourRequest(){
        $page_title     = "Salon Request";
        $parlour_lists = ParlourList::where('status',GlobalConst::STATUSPENDING)
        ->orderByDesc('id')
        ->get();

        return view('admin.sections.parlour-list.parlour-request',compact(
            'page_title',
            'parlour_lists'
        ));
    }
    /**
     * Method for show doctor-care create page
     * @param string $slug
     * @param \Illuminate\Http\Request  $request
    */
    public function create(){
        $page_title      = "Salon Create";
        $areas           = Area::where('status',true)->get();
        $todayDate       = Carbon::now()->format('d F, Y');
        return view('admin.sections.parlour-list.create',compact(
            'page_title',
            'areas',
            'todayDate',

        ));
    }
    public function getScheduleDays(){

        return view('admin.components.parlour-list.schedule-item');
    }
    public function getService(){

        return view('admin.components.parlour-list.service-item');
    }
    /**
     * Method for store parlour list information
     * @param \Illuminate\Http\Request $request
     */
    public function store(Request $request){
        $validator = Validator::make($request->all(),[
            'area'             => 'required|integer',
            'name'             => 'required|string|max:50',
            'manager_name'     => 'nullable|string',
            'experience'       => 'required|string|max:100',
            'speciality'       => 'nullable',
            'contact'          => 'required',
            'address'          => 'nullable',
            'off_days'         => 'required|array',
            'number_of_dates'  => 'required|integer',
            'service_name'     => 'required|array',
            'service_name.*'   => 'required|string',
            'price'            => 'required|array',
            'price.*'          => 'required|string',
            'from_time'        => 'required|array',
            'from_time.*'      => 'required|string',
            'to_time'          => 'required|array',
            'to_time.*'        => 'required|string',
            'max_client'       => 'required|array',
            'max_client.*'     => 'required|integer',
            'image'            => 'nullable',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput($request->all());
        }

        $validated          = $validator->validate();
        $validated['slug']  = Str::uuid();
        $validated['area_id']        = $validated['area'];
        $validated['active_status']  = GlobalConst::STATUSUNFREEZE;
        $validated['status']          = GlobalConst::STATUSSUCCESS;
        if(ParlourList::where('contact',$validated['contact'])->exists()){
            throw ValidationException::withMessages([
                'name'  => "Salon already exists!",
            ]);
        }

        if($request->hasFile("image")){
            $validated['image'] = $this->imageValidate($request,"image",null);
        }
        $offDaysArray = $request->input('off_days', []);

        $offDaysString = implode(',', $offDaysArray);

        $validated['off_days']     = $offDaysString;

        $service_name   = $validated['service_name'];
        $price          = $validated['price'];
        $from_time      = $validated['from_time'];
        $to_time        = $validated['to_time'];
        $max_client     = $validated['max_client'];
        $validated      = Arr::except($validated,['service_name','price','from_time','to_time','max_client','area']);
        try{
            $parlour_list = ParlourList::create($validated);
            if(count($from_time) > 0){
                $days_shedule = [];
                foreach($from_time as $key => $day_id){
                    $days_shedule[] = [
                        'parlour_list_id'   => $parlour_list->id,
                        'from_time'         => $from_time[$key],
                        'to_time'           => $to_time[$key],
                        'max_client'        => $max_client[$key],
                        'created_at'        => now(),
                    ];
                }
                ParlourListHasSchedule::insert($days_shedule);
            }
            if(count($service_name) > 0){
                $services = [];
                foreach($service_name as $key => $day_id){
                    $services[] = [
                        'parlour_list_id'   => $parlour_list->id,
                        'service_name'      => $service_name[$key],
                        'price'             => $price[$key],
                        'created_at'        => now(),
                    ];
                }
                ParlourHasService::insert($services);
            }
        }catch(Exception $e){
            return back()->with(['error' => ["Something went wrong.Please try again."]]);
        }
        return redirect()->route('admin.parlour.list.index')->with(['success' => ["Salon Created Successfully!"]]);
    }
    /**
     * Method for show the edit parlour list page
     * @param $slug
     * @param \Illuminate\Http\Request $request
     */
    public function edit($slug){
        $page_title             = "Salon Edit";
        $parlour_list           = ParlourList::where('slug',$slug)->first();
        if(!$parlour_list) return back()->with(['error' =>  ['Salon List Not Exists!']]);
        $areas                  = Area::where('status',true)->get();
        $parlour_has_schedule   = ParlourListHasSchedule::where('parlour_list_id',$parlour_list->id)->get();
        $parlour_has_service    = ParlourHasService::where('parlour_list_id',$parlour_list->id)->get();

        return view('admin.sections.parlour-list.edit',compact(
            'page_title',
            'parlour_list',
            'areas',
            'parlour_has_schedule',
            'parlour_has_service'
        ));
    }
    /**
     * Method for update the parlour list information
     * @param $slug
     * @param \Illuminate\Http\Request $request
     */
    public function update(Request $request, $slug){
        $parlour_list = ParlourList::where('slug', $slug)->first();
        $validator = Validator::make($request->all(), [
            'area'             => 'required',
            'name'             => 'required|string|max:50',
            'manager_name'     => 'nullable|string',
            'experience'       => 'required|string|max:100',
            'speciality'       => 'nullable',
            'contact'          => 'required',
            'address'          => 'nullable',
            'off_days'         => 'required|string',
            'number_of_dates'  => 'required|integer',
            'service_name'     => 'required|array',
            'service_name.*'   => 'required|string',
            'price'            => 'required|array',
            'price.*'          => 'required|string',
            'from_time'        => 'required|array',
            'from_time.*'      => 'required|string',
            'to_time'          => 'required|array',
            'to_time.*'        => 'required|string',
            'max_client'       => 'required|array',
            'max_client.*'     => 'required|integer',
            'image'            => 'nullable',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput($request->all());
        }

        $validated = $validator->validate();
        $validated['area_id'] = $validated['area'];

        if (ParlourList::where('contact', $validated['contact'])->where('id', '!=', $parlour_list->id)->exists()) {
            throw ValidationException::withMessages([
                'name' => "Salon already exists!",
            ]);
        }

        if ($request->hasFile('image')) {
            $validated['image'] = $this->imageValidate($request, "image", null);
        }

        $service_name = $validated['service_name'];
        $price = $validated['price'];
        $from_time = $validated['from_time'];
        $to_time = $validated['to_time'];
        $max_client = $validated['max_client'];
        $validated = Arr::except($validated, ['service_name', 'price', 'from_time', 'to_time', 'max_client', 'area']);

        try {
            $parlour_list->update($validated);

            $existing_schedules     = $parlour_list->schedules()->pluck('id')->all();

            // Initialize an array to track the new schedule IDs that will be processed
            $processed_schedule_ids = [];

            foreach ($from_time as $key => $value) {
                $scheduleData       = [
                    'from_time'     => $from_time[$key],
                    'to_time'       => $to_time[$key],
                    'max_client'    => $max_client[$key],
                    'updated_at'    => now(),
                ];

                if (isset($existing_schedules[$key])) {
                    // Update existing schedule and track its ID
                    ParlourListHasSchedule::where('id', $existing_schedules[$key])->update($scheduleData);
                    $processed_schedule_ids[]           = $existing_schedules[$key];
                } else {
                    // Create new schedule
                    $scheduleData['parlour_list_id']    = $parlour_list->id;
                    $scheduleData['created_at']         = now();
                    $new_schedule                       = ParlourListHasSchedule::create($scheduleData);
                    $processed_schedule_ids[]           = $new_schedule->id;
                }
            }

            // Delete schedules that were removed (not processed in the current request)
            $removed_schedules = array_diff($existing_schedules, $processed_schedule_ids);
            if (!empty($removed_schedules)) {
                ParlourListHasSchedule::whereIn('id', $removed_schedules)->delete();
            }

            $existing_services = $parlour_list->services()->pluck('id')->all();

            // Initialize an array to track the new service IDs that will be processed
            $processed_service_ids  = [];

            foreach ($service_name as $key => $value) {
                $serviceData = [
                    'service_name'  => $service_name[$key],
                    'price'         => $price[$key],
                    'updated_at'    => now(),
                ];

                if (isset($existing_services[$key])) {
                    ParlourHasService::where('id', $existing_services[$key])->update($serviceData);
                    $processed_service_ids[]        = $existing_services[$key];
                } else {
                    $serviceData['parlour_list_id'] = $parlour_list->id;
                    $serviceData['created_at']      = now();
                    $new_service                    = ParlourHasService::create($serviceData);
                    $processed_service_ids[]        = $new_service->id;
                }
            }

            $removed_services = array_diff($existing_services, $processed_service_ids);
            if (!empty($removed_services)) {
                ParlourHasService::whereIn('id', $removed_services)->delete();
            }
        } catch (Exception $e) {
            return back()->with(['error' => ['Something went wrong! Please try again.']]);
        }

        return redirect()->route('admin.parlour.list.index')->with(['success' => ['Salon Updated Successfully!']]);
    }



     /**
     * Method for booking log details
     * @param $trx_id
     * @param \Illuminate\Http\Request $request
     */
    public function details(Request $request,$id){
        $page_title     = "Salon Details";
        $data           = ParlourList::with(['schedules','stuff','services','area','vendor','manager'])->where('id',$id)->first();

        if(!$data) return back()->with(['error' => ['Data Not Found!']]);

        return view('admin.sections.parlour-list.details',compact(
            'page_title',
            'data',
        ));
    }


    /**
     * Method for update doctor status
     * @param \Illuminate\Http\Request  $request
     */
    public function statusUpdate(Request $request){

        $validator = Validator::make($request->all(),[
            'data_target'  => 'required|numeric|exists:parlour_lists,id',
            'status'       => 'required|numeric',
        ]);

        $validated = $validator->validate();
        $doctors = ParlourList::find($validated['data_target']);

        try {
            $doctors->update([
                'status'   => $validated['status'],
                'remarks'   => $request->reason,
            ]);
        } catch (Exception $e) {
             return back()->with(['error'    =>  ['Something went wrong. Please try again!']]);
        }
        return redirect()->route('admin.parlour.list.index')->with(['success' => ["Salon list Updated successfully!"]]);
    }
    /**
     * Method for delete the parlour list information
     * @param \Illuminate\Http\Request $request
     */
    public function delete(Request $request){
        $validator = Validator::make($request->all(),[
            'target'    => 'required|numeric',
        ]);

        $parlour_list   = ParlourList::find($request->target);
        try{
            $parlour_list->delete();
        }catch(Exception $e){
            return back()->with(['error'    =>  ['Something went wrong. Please try again!']]);
        }
        return back()->with(['success'  =>  ['Salon list deleted successfully.']]);

    }
    /**
     * Method for image validate
     * @param string $slug
     * @param \Illuminate\Http\Request  $request
    */
    public function imageValidate($request,$input_name,$old_image = null) {
        if($request->hasFile($input_name)) {
            $image_validated = Validator::make($request->only($input_name),[
                $input_name         => "image|mimes:png,jpg,webp,jpeg,svg",
            ])->validate();

            $image = get_files_from_fileholder($request,$input_name);
            $upload = upload_files_from_path_dynamic($image,'site-section',$old_image);
            return $upload;
        }
        return false;
    }
}
