<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\Appointment;
use App\Models\BaseModel;
use App\Models\ConceptCode;
use App\Models\Patient;
use App\Models\Physician;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class AppointmentController extends Controller
{

    protected $model;
    protected $patientModel;
    protected $baseLabId;

    protected $physicianModel;

    public function __construct(){
        $this->model = new Appointment();
        $this->patientModel = new Patient();
        $this->physicianModel = new Physician();
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_appointment'])) return redirect(url('my-profile'));
        $conceptCodes = $this->model::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->groupBy('appointment_type')->get('appointment_type');
        $patients = $this->patientModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => BaseModel::RECORD_STATUS_ACTIVE])->limit(20)->get();
        $physicians = $this->physicianModel::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $this->baseLabId])->orderBy('name_en', 'ASC')->get();
        $appointments = $this->model::with(['patient', 'doctor'])->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->where('lab_id', $this->baseLabId)
            ->when(!empty($request->appointment_type), function ($query) use($request){
                $query->where('appointment_type', $request->appointment_type);
            })->when(!empty($request->appointment_date), function ($query) use($request) {
                $query->whereDate('appointment_date', date('Y-m-d', strtotime($request->appointment_date)));
            })->orderBy('appointment_date','desc')->paginate(config('labis.pagination.perpage', 10));
        return view('appointment', ['appointments' => $appointments, 'conceptCodes' => $conceptCodes, 'patients' => $patients, 'patient_id' => 0, 'physicians' => $physicians]);
    }

    public function store(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['create_appointment'])) return false;
            $validator = \Validator::make($request->all(), ['patient_id' => 'required', 'appointment_date' => 'required', 'appointment_type' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('appointment.create_fail'), 'errors' => $validator->errors()->all()]);

            $app=new Appointment();
            $app->patient_id=$request->patient_id;
            $app->appointment_date=date('Y-m-d H:i:s', strtotime($request->appointment_date));
            $app->appointment_type=$request->appointment_type;
            $app->description=$request->description;
            $app->doctor_id=$request->doctor_id;
            $app->lab_id=$this->baseLabId;
            $app->save();
            return response()->json(['success' => true, 'message' => __('appointment.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('appointment.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try {
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_appointment'])) return false;
            $validator = \Validator::make($request->all(), ['patient_id' => 'required', 'appointment_date' => 'required', 'appointment_type' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('appointment.update_fail'), 'errors' => $validator->errors()->all()]);
            $app=Appointment::find($request->uid);
            $app->appointment_date=date('Y-m-d H:i:s', strtotime($request->appointment_date));
            $app->appointment_type=$request->appointment_type;
            $app->description=$request->description;
            $app->doctor_id=$request->doctor_id;
            $app->lab_id=$this->baseLabId;
            $app->save();
            return response()->json(['success' => true, 'message' => __('appointment.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('appointment.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $test = $this->model::query()->where(['lab_id' => $this->baseLabId, 'id' => $request->uid])->get()->first();
            return response()->json(['success' => true, 'message' => __('appointment.get_success'), 'data' => $test]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('appointment.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['delete_appointment'])) return false;
            $this->model::query()->where(['id' => $request->uid, 'lab_id' => $this->baseLabId])->update(array(BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('appointment.delete_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('appointment.delete_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function getAlertNofication(){
        try{
            $appointments = $this->model::with(['patient:id,name_en,phone_number', 'doctor:id,name_en'])->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
                ->where('lab_id', $this->baseLabId)
                ->whereBetween('appointment_date', [Carbon::today(), Carbon::today()->addDays(2)])->orderBy('appointment_date','desc')->get();
            $count = $appointments->count();
            return response()->json(['success' => true, 'message' => __('appointment.get_success'), 'data' => $appointments, 'count' => $count]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('appointment.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

}
