<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Http\Controllers\Controller;
use App\Models\AppointmentShift;
use App\Models\Company;
use App\Models\Doctor;
use App\Models\DoctorChamber;
use App\Models\OpdBookings;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;

class QueueManagerController extends Controller
{
    public function index(Request $request)
    {
        $doctors = Doctor::with('getAccount')
            ->with('getOrganizatioDepartment')
            ->with('getDoctorAppointmentshift')
            ->where('status', '=', '1');
        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 20;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $doctors = $doctors->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('queue-manager.doctor-table', compact('doctors'));
        } else {
            $doctors = $doctors->paginate(20);
            return view('queue-manager.index', compact('doctors'));
        }
    }

    public function doctorDisplay($doctor_id, Request $request)
    {
        $shifts  = AppointmentShift::select('id', 'name')->get();
        $doctors = Doctor::with('getAccount')->select('account_id')->where('id', $doctor_id)->get();
        $doctor  = Doctor::with('getAccount')->select('account_id')->where('id', $doctor_id)->first();
        $company   = Company::find(Auth::user()->company_id);
        $companies = Company::get();
        $chambers   = DoctorChamber::get(['id', 'name', 'is_default']);
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        $data = [];


       
        $date = $request->date?Carbon::createFromFormat($this->companyDateFormate(), $request->date)->format('Y-m-d') : date('Y-m-d');
        //$date = Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d');
        $status = $request->status ?? 'Pending';
        $doctorId = $request->doctor_ac_id ?? $doctor->account_id;

        $totalAppointment = OpdBookings::where('appointment_status', 'Done')
            ->where('doctor_ac_id',  $doctorId)
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->count();
        $totalDoneAppointment = OpdBookings::where('appointment_status', 'Done')->where('service_status', 'Done')
            ->where('doctor_ac_id',  $doctorId)
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->count();
        // \DB::enableQueryLog();
        $totalCheckIn = OpdBookings::where('doctor_ac_id',  $doctorId)->where('appointment_status', 'Done')
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->count();
        // dd(\DB::getQueryLog());
        $totalCheckInDone = OpdBookings::where('check_in_status', 1)->where('appointment_status', 'Done')
            ->where('doctor_ac_id',  $doctorId)
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->count();
        $totalVisit = OpdBookings::where('appointment_status', 'Done')
            ->where('doctor_ac_id',  $doctorId)
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->count();
        $totalVisitDone = OpdBookings::where('appointment_status', 'Done')
            ->where('doctor_ac_id',  $doctorId)
            ->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)))
            ->where('service_status', 'Done')->count();

       
        $data = OpdBookings::with(['getShiftNames', 'getPatient'])
            ->select('*')->where('appointment_status', 'Done');
        if ($status) {
            $data = $data->where('service_status', $status);
        }
        if ($request->shift_id && $request->shift_id != 'all') {
            $data = $data->where('shift_id', $request->shift_id);
        }
        if ($doctorId &&  $doctorId != 'all') {
            $data = $data->where('doctor_ac_id',  $doctorId);
        }
        if ($request->chamber_id != '') {
            $data = $data->where('chamber_id', $request->chamber_id);
        }
        if ($date) {
            $data = $data->whereDate('appointment_date_time', '=', date('Y-m-d', strtotime($date)));
        }
        $data = $data->orderBy('appointment_serial_no', 'asc')->get();
        $shiftAvailable = $data->groupBy('shift_id');

        if ($request->ajax()) {

            $fromDate = date('Y-m-d H:i:s', strtotime($date));
            if ($request->shift_id && $request->shift_id != 'all') {
                $shift = AppointmentShift::select('name')->find($request->shift_id);
                $shiftName = $shift->name;
            } else {
                $shiftName = "All";
            }

            if ($doctorId &&  $doctorId != 'all') {
                $doctor = Doctor::with('getAccount')->select('account_id')->where('account_id',  $doctorId)->first();
                $doctorName = $doctor->getAccount->name ?? '';
            } else {
                $doctorName = "All";
            }

            return view('queue-manager.doctor-display-table', compact(
                'data',
                'doctor',
                'companies',
                'company',
                'chambers',
                'fromDate',
                'shiftName',
                'doctorName',
                'totalAppointment',
                'totalDoneAppointment',
                'totalCheckIn',
                'totalCheckInDone',
                'totalVisit',
                'totalVisitDone',
                'shiftAvailable',
                'status',
                'date'
            ));
        }
        return view('queue-manager.doctor-display', compact(
            'shifts',
            'doctors',
            'doctor',
            'data',
            'companies',
            'company',
            'chambers',
            'totalAppointment',
            'totalDoneAppointment',
            'totalCheckIn',
            'totalCheckInDone',
            'totalVisit',
            'totalVisitDone',
            'shiftAvailable',
            'companyDateFormate',
            'status',
            'date'
        ));
    }

    public function consultationStart($booking_id, Request $request)
    {

        if ($request->ajax()) {
            $opdBooking = OpdBookings::find($booking_id);
            if($request->status==1)
            {
             $opdBooking->update(['appointment_status' => 'Done', 'consultation_start_date_time' => date('Y-m-d H:i:s', time())]);
            }
            else
            {
              $opdBooking->update(['appointment_status' => 'Done', 'consultation_start_date_time' => null]);
            }

            if ($opdBooking) {
                return response()->json([
                    'success' => true,
                    'message' => ['Consultation start is Successfully'],
                    'data' => [
                        'redirect' => '',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function visitDone($booking_id, Request $request)
    {

        if ($request->ajax()) {
            $opdBooking = OpdBookings::find($booking_id);
            $opdBooking->update(['appointment_status' => 'Done', 'service_status' => 'Done','checkout_date_time'=>date('Y-m-d H:i:s', time())]);

            if ($opdBooking) {
                return response()->json([
                    'success' => true,
                    'message' => ['Service is Done Successfully'],
                    'data' => [
                        'redirect' => '',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function visitUndo($booking_id, Request $request)
    {

        if ($request->ajax()) {
            $opdBooking = OpdBookings::find($booking_id);
            $opdBooking->update(['appointment_status' => 'Done', 'service_status' => 'Pending','checkout_date_time'=>null]);

            if ($opdBooking) {
                return response()->json([
                    'success' => true,
                    'message' => ['Service is Done Successfully'],
                    'data' => [
                        'redirect' => '',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
}
