<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Models\Account;
use App\Models\AppointmentDoctorSchedule;
use App\Models\AppointmentShift;
use App\Models\Doctor;
use App\Models\OpdScheduleType;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use SebastianBergmann\Type\VoidType;

class AppointmentDoctorScheduleController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:appointment-doctor-schedule-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = AppointmentDoctorSchedule::select([
            'appointment_doctor_schedules.id',
            'appointment_doctor_schedules.doctor_id',
            DB::raw("(GROUP_CONCAT(appointment_doctor_schedules.day SEPARATOR ',')) as `day`"),
            'appointment_doctor_schedules.type',
            'appointment_doctor_schedules.shift_id',
            'appointment_doctor_schedules.priority',
            'appointment_doctor_schedules.status',
        ])
            ->groupBy('appointment_doctor_schedules.doctor_id')
            ->groupBy('appointment_doctor_schedules.shift_id')
            ->with('getDoctor')
            ->with('getType')
            ->with('getShift');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->whereHas('getDoctor', function ($accountQuery) use ($search_query) {
                        $accountQuery->where('name', 'like', '%' . $search_query . '%');
                    });
                })
                ->paginate($sort_by);

                return view('appointment-doctor-schedule.table', compact('data'));
        } else {

            $data = $data->paginate(10);

            return view('appointment-doctor-schedule.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority         = AppointmentDoctorSchedule::max('priority');
        $priority         = $priority != '' ? $priority : 0;
        $account          = Doctor::with('getAccount')->get();
        $AppointmentShift = AppointmentShift::select('id', 'name')->get();

        return view('appointment-doctor-schedule.create', compact('account','priority','AppointmentShift'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        $doctor_id = $request->doctor_id;

        $validator = \Validator::make($request->all(), [
            'doctor_id'             => 'required',
            'shift_id'              => 'required',
            // 'day'                   => [
            //     'required',
            //     Rule::unique('appointment_doctor_schedules')->where(function ($query) use ($doctor_id) {
            //         return $query->where('doctor_id', $doctor_id)
            //             ->where('deleted_at', NULL);
            //     }),
            // ],
        ]);
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            // 'day'
        ]);
        // foreach ($request->day as $key => $value) {
        //     $data['day'] = $value;
        //     $schedule = AppointmentDoctorSchedule::create($data);

        // }
        $schedule = AppointmentDoctorSchedule::create($data);
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Appointment Doctor schedule Created Successfully',
                'data' => $schedule
            ]);
        }
        return redirect()->route('appointment-doctor-schedule.index')
            ->with('success', 'Appointment Doctor schedule Created Successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $doctor_schedule = AppointmentDoctorSchedule::select
        ([
            'appointment_doctor_schedules.*',
            DB::raw("(GROUP_CONCAT(appointment_doctor_schedules.day SEPARATOR ',')) as `day`")
        ])
        ->where('doctor_id','=',$id)->first();
        $account = Doctor::with('getAccount')->get();
        $shift = AppointmentShift::select('id', 'name')->get();
        return view('appointment-doctor-schedule.edit', compact( 'account', 'doctor_schedule','shift'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $doctor_id = $request->doctor_id;

        $validator = \Validator::make($request->all(), [
            'shift_id'     => 'required',
            'day'           => 'required',
        ]);


        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'day'
        ]);


            $schedule = AppointmentDoctorSchedule::whereNotIn('day',$request->day)->where('doctor_id','=',$id)->delete();
            foreach ($request->day as $key => $value) {
            $day['day'] = $value;

            $schedule = AppointmentDoctorSchedule::updateOrCreate(['doctor_id' => $id, 'day' => $value], $data);
        }


        if (!$data) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Appointment Doctor schedule Type not found!",
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', "Appointment Doctor schedule not found!");
        }

        $schedule->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Appointment Doctor schedule has been created successfully',
            ]);
        }

        return redirect()->route('appointment-doctor-schedule.index')
            ->with('success', 'Appointment Doctor schedule updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $doctorId = $request->id;
        // dd($doctorId);


        $dat = AppointmentDoctorSchedule::where('doctor_id', $doctorId)->delete();


        $Redirect = 'appointment-doctor-schedule';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' =>
                [
                    'redirect' => $Redirect,
                ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = AppointmentDoctorSchedule::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Doctor status successfully change'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function searchDoctors(Request $request)
    {
        $searchTerm = $request->search_text;
        $results = Doctor::join('accounts', 'doctors.account_id', '=', 'accounts.id')
        ->where('accounts.name', 'LIKE', '%' . $searchTerm . '%')
        ->select('doctors.id','accounts.name')
        ->get();
        return response()->json(['result' => $results, 'status' => true]);
    }
    // public function addDays()
    // {
    //     $priority = AppointmentDoctorSchedule::max('priority');
    //     $priority = $priority != '' ? $priority : 0;
    //     $account = Doctor::with('getAccount')->get();
    //     $AppointmentShift = AppointmentShift::select('id', 'name')->get();
    //     return view('appointment-doctor-schedule.days', compact('account','priority','AppointmentShift'));
    // }
    public function storeDays(Request $request)
        {
            $validator = \Validator::make($request->all(), [
                'day' => 'required',
            ]);
            if ($validator->fails()) {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $validator->getMessageBag()->first(),
                        'data' => []
                    ]);
                }
                return redirect()->back()->with('error', $validator->getMessageBag()->first());
            }

            $data = $request->except([
                '_token',
                '_method',
                'day'
            ]);

            foreach ($request->day as $key => $value) {
                $data['day'] = $value;
                $schedule = AppointmentDoctorSchedule::create($data);

            }
            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Days Created Successfully',
                    'data' => $schedule
                ]);
            }
            return redirect()->route('appointment-doctor-schedule.index')
                ->with('success', 'Days Created Successfully');

    }
    public function updateDays()
    {

    }
    public function addDays(Request $request)
    {
        $data = AppointmentDoctorSchedule::select([
                DB::raw("(GROUP_CONCAT(day SEPARATOR ',')) as `days`"),
            ])
            ->groupBy('doctor_id')
            ->groupBy('shift_id')
            ->where('doctor_id', '=', $request->doctor_id)
            ->where('shift_id', '=', $request->shift_id)
            ->first();

            return view('appointment-doctor-schedule.days',compact('data'));
    }

}
// getAppointmentSchedule
