<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Models\Account;
use App\Models\AppointmentDoctorFees;
use App\Models\AppointmentDoctorSchedule;
use App\Models\AppointmentDoctorShift;
use App\Models\AppointmentDoctorShiftDay;
use App\Models\AppointmentShift;
use App\Models\Doctor;
use App\Models\Language;
use App\Models\OpdScheduleType;
use App\Models\OrganizationDepartment;
use App\Http\Controllers\Controller;
use App\Models\DoctorChamber;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class DoctorControllers extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:doctor-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->checkPermission('doctor-list')) {
            return redirect()->back()->with('info', 'You don\'t have enough permission to access this page.');
        }

        $data = Doctor::select([
            'doctors.id',
            'doctors.account_id',
            'doctors.qualification',
            'doctors.organization_department_id',
            'doctors.opd_schedule_types_id',
            'doctors.shift_id',
            'doctors.specialist_in',
            'doctors.medical_license_no',
            'doctors.api_salt_key',
            'doctors.priority',
            'doctors.default',
            'doctors.status',
            'doctors.web_booking',
            'doctors.app_booking'
        ])
            ->with('getAccount')
            ->with('getOrganizatioDepartment')
            ->with('getOpdSchedule')
            ->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('getAccount', function ($accountQuery) use ($search_query) {
                    $accountQuery->where('name', 'like', '%' . $search_query . '%');
                });
            })
            ->paginate($sort_by);

            return view('doctor.table', compact('data'));
        } else {
            $data = $data->paginate(10);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority           = Doctor::max('priority');
        $priority           = $priority != '' ? $priority : 0;
        $account            = Account::select('id', 'name')->where('status', 1)->get();
        $department         = OrganizationDepartment::select('id', 'name')->where('status', 1)->get();
        $opd                = OpdScheduleType::select('id', 'name')->where('status', 1)->get();
        $languages          = Language::select(['id', 'name'])->get();
        $appointment_shifts = AppointmentShift::select('id', 'name')->where('status', 1)->get();
        $chambers           = DoctorChamber::select(['id', 'name', 'is_default'])->where('status', '1')->get();

        return view('doctor.create', compact('opd', 'department', 'account', 'priority', 'appointment_shifts', 'languages', 'chambers'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $doctor_id = $request->account_id;
        $doctors_chamber_id = $request->doctors_chamber_id;

        $validator = \Validator::make($request->all(), [
            'account_id' =>[
                'required',
                Rule::unique('doctors')->where(function ($query) use ($doctor_id, $doctors_chamber_id) {
                    return $query->where('account_id', $doctor_id)
                        ->where('doctors_chamber_id', $doctors_chamber_id);
                }),
            ],
            // 'organization_department_id' => 'required',
            'opd_schedule_types_id' => 'required',
            // 'qualification' => 'required',
            'shift_id' => 'required',
            'day_id'  => 'required'

        ], [
            'shift_id.required' => 'The shift field is required.',
            'day_id.required'   => 'The Day field is 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',
            'product_id',
            'shift_id',
            'day_id',
        ]);

        // foreach ($request->organization_department_id as $key => $value) {
        //     $data['organization_department_id'] = $value;

        // }
        $data['organization_department_id'] = $request->organization_department_id ? implode(',', $request->organization_department_id) : '';
        $Shifts = AppointmentShift::first();
        $doctor = Doctor::create($data);

        if ($request->shift_id) {

            foreach ($request->shift_id as $shift_id) {
                $sifts = AppointmentShift::find($shift_id);
                AppointmentDoctorShift::updateOrCreate(
                    [
                        'shift_id'          => $shift_id,
                        'doctor_id'         => $doctor->id
                    ],
                    [
                        'status'            => 1,
                        'patient_quantity'  => $sifts->patient_quantity ? $sifts->patient_quantity : 25,
                        'time_from'         => $sifts->time_from ?? '',
                        'time_to'           => $sifts->time_to ?? '',
                        'chamber_id'        => $request->doctors_chamber_id,
                    ]
                );

                foreach ($request->day_id as $day_id) {
                    $doctor_days = ([
                        'doctor_id'     => $doctor->id,
                        'shift_id'      => $shift_id,
                        'day_id'        => $day_id,
                        'chamber_id'    => $request->doctors_chamber_id,
                    ]);

                    $day = AppointmentDoctorShiftDay::updateOrCreate($doctor_days);
                }

                if(isset($request->product_id))
                {
                    foreach($request->product_id as $product_id)
                    {
                        $dataFee['doctor_id'] = $doctor->id;
                        $dataFee['shift_id'] = $shift_id;
                        $dataFee['product_id'] = $product_id;
                        $dataFee['chamber_id'] = $request->doctors_chamber_id;


                        $schedule = AppointmentDoctorFees::create($dataFee);
                    }
                    
                }

            }
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Doctor Created Successfully',
                'data' => $doctor
            ]);
        }
        return redirect()->route('doctor.index')
            ->with('success', 'Doctor 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)
    {

        $doc                    = Doctor::find($id);
        $account                = Account::select('id', 'name')->where('status', 1)->get();
        $department             = OrganizationDepartment::select('id', 'name')->where('status', 1)->get();
        $opd                    = OpdScheduleType::select('id', 'name')->where('status', 1)->get();
        $appointment_shifts     = AppointmentShift::select('id', 'name')->where('status', 1)->get();
        $appointFees            = AppointmentDoctorFees::where('doctor_id', $id)->groupBy('product_id')->get();
        $languages              = Language::select(['id', 'name'])->get();
        $doctor_shifts          = AppointmentDoctorShift::select(
            '*',
            \DB::raw("(GROUP_CONCAT(shift_id SEPARATOR ',')) as `shifts`"),
        )
            ->where('doctor_id', $id)
            ->first();

        $doctor_days = AppointmentDoctorShiftDay::select(
            '*',
            \DB::raw("(GROUP_CONCAT(day_id SEPARATOR ',')) as `days`"),
        )
            ->where('doctor_id', $id)
            ->first();
        $chambers           = DoctorChamber::select(['id', 'name', 'is_default'])->where('status', '1')->get();
        return view('doctor.edit', compact(
            'opd',
            'department',
            'account',
            'doc',
            'appointment_shifts',
            'appointFees',
            'doctor_shifts',
            'doctor_days',
            'languages',
            'chambers'
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            // 'account_id'                        => 'required',
            // 'organization_department_id' => 'required',
            'opd_schedule_types_id' => 'required',
            // 'qualification' => 'required',
            'shift_id' => 'required',
            'day_id'  => 'required'

        ], [
            'shift_id.required' => 'The shift field is required.',
            'day_id.required'   => 'The Day field is 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',
            'product_id',
            'shift_id',
            'day_id',
        ]);

        $doc = Doctor::find($id);

        if (!$doc) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Doctor Type not found!",
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', "Doctor not found!");
        }
        // foreach ($request->organization_department_id as $key => $value) {
        //     $data['organization_department_id'] = $value;
        // }
        $data['organization_department_id'] = $request->organization_department_id ? implode(',', $request->organization_department_id) : '';
        $data['convert_to_sale'] = $request->convert_to_sale == 1 ? 1 : 0;
        $doc->update($data);

        AppointmentDoctorShift::where(['doctor_id' => $id])->delete();
        AppointmentDoctorShiftDay::where(['doctor_id' => $id])->delete();

        if ($request->shift_id) {
            foreach ($request->shift_id as $shift_id) {

                $sifts = AppointmentShift::find($shift_id);
                AppointmentDoctorShift::updateOrCreate(
                    [
                        'shift_id'         => $shift_id,
                        'doctor_id'         => $id
                    ],
                    [
                        'status'            => 1,
                        'patient_quantity'  => $sifts->patient_quantity ? $sifts->patient_quantity : 25,
                        'time_from'         => $sifts->time_from ?? '',
                        'time_to'           => $sifts->time_to ?? '',
                        'chamber_id'        => $request->doctors_chamber_id,
                    ]
                );

                foreach ($request->day_id as $day_id) {
                    $doctor_days = ([
                        'doctor_id' => $id,
                        'shift_id'  => $shift_id,
                        'day_id'    => $day_id,
                        'chamber_id'        => $request->doctors_chamber_id,
                    ]);

                    $day = AppointmentDoctorShiftDay::updateOrCreate($doctor_days);
                }

                if($request->product_id)
                {
                    AppointmentDoctorFees::where(['doctor_id'=>$id,'shift_id'=>$shift_id,'chamber_id'=>$request->doctors_chamber_id])->delete();
                    foreach($request->product_id as $product_id)
                    {
                        
                        $dataFee['doctor_id']  = $id;
                        $dataFee['shift_id']   = $shift_id;
                        $dataFee['product_id'] = $product_id;
                        $dataFee['chamber_id'] = $request->doctors_chamber_id;


                        $schedule = AppointmentDoctorFees::updateOrCreate($dataFee);
                    }
                    // $dataFee['doctor_id'] = $id;
                    // $dataFee['shift_id'] =  $shift_id;
                    // $dataFee['product_id'] = $request->product_id;
                    // $dataFee['chamber_id'] = $request->doctors_chamber_id;

                    //$schedule = AppointmentDoctorFees::updateOrCreate($dataFee);
                }

            }
        }

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

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

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

        Doctor::find($request->id)->delete();
        AppointmentDoctorShift::where(['doctor_id' => $request->id])->delete();
        AppointmentDoctorShiftDay::where(['doctor_id' => $request->id])->delete();
        AppointmentDoctorFees::where(['doctor_id' => $request->id])->delete();

        $Redirect = 'doctor';

        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 = Doctor::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 getAccounts(Request $request)
    {
        $data = [];
        if ($request->has('q')) {
            $search = $request->q;
            $data = Account::select(["accounts.id", "accounts.name"])
                ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
                ->where('account_types.type_code', 'DOCTOR')
                ->where('accounts.name', 'LIKE', "%$search%")
                ->get();
        }

        return response()->json($data);
    }
    public function addDoctorSchedule($id)
    {
        $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')
            ->where('appointment_doctor_schedules.doctor_id', '=', $id)->paginate(5);
        // $AppointmentShift = AppointmentShift::select('id', 'name')->get();
        // $priority = AppointmentDoctorSchedule::max('priority');
        // $priority = $priority != '' ? $priority : 0;
        return view(
            'appointment-doctor-schedule.index',
            [
                'doctor_id' => $id,
                'data' => $data,
                // 'AppointmentShift' => $AppointmentShift,
                // 'priority' => $priority,
            ]
        );
    }



    public function WebBookingStatus(Request $request)
    {
        $doctor_id = $request->input('id') ?? '';
        $shift_id = $request->input('shift_id') ?? '';
        $status = $request->input('status') ?? '';


        if ($status == '1') {
            // \DB::enableQueryLog();
            Doctor::updateOrCreate(
                ['id' => $doctor_id],
                ['web_booking' => '1']
            );
            // dd(\DB::getQueryLog());
        } elseif ($status == '0') {
            Doctor::updateOrCreate(
                ['id' => $doctor_id],
                ['web_booking' => '0']
            );
        }


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Web Booking Status successfully',
            ]);
        }

        return redirect()->back()->with('success', 'Web Booking Status Changed Successfully');
    }


    public function AppBookingStatus(Request $request)
    {
        $doctor_id = $request->input('id') ?? '';
        $shift_id = $request->input('shift_id') ?? '';
        $status = $request->input('status') ?? '';


        if ($status == '1') {
            // \DB::enableQueryLog();
            Doctor::updateOrCreate(
                ['id' => $doctor_id],
                ['app_booking' => '1']
            );
            // dd(\DB::getQueryLog());
        } elseif ($status == '0') {
            Doctor::updateOrCreate(
                ['id' => $doctor_id],
                ['app_booking' => '0']
            );
        }


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'App Booking Status successfully',
            ]);
        }

        return redirect()->back()->with('success', 'App Booking Status Changed Successfully');
    }
}
