<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\QueueManagement;
use App\Models\PatientModel;
use App\Models\VisitModel;
use App\Models\OptoModel;
use App\Models\OTModel;
use App\Models\ConsultantModel;
use App\Models\UserMaster;
use App\Models\PatientBalanceModel;
use App\Models\ConsultantTreatmentModel;
use Session;
use DataTables;
use App\Http\Controllers\MasterController;
use App\Models\InvestigationModel2;
use App\Models\ReferedByModel;
use Illuminate\Support\Facades\Storage;
use App\Models\TempQueueManagement;

class QueueController extends Controller
{
    function maxMrdNo()
    {
        $result = PatientModel::max('MrdNo');
        if ($result == 0) {
            $NewMrdNo = 1;
        } else {
            $NewMrdNo = $result + 1;
        }
        return $NewMrdNo;
    }
    function queuemanagement()
    {
        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        //$queuelist = $this->queuelist();
        $consultantList = (new MasterController)->consultantList();
        $userList = (new MasterController)->receptionList();
        $cityList = (new MasterController)->cityList();
        $stateList = (new MasterController)->stateList();
        $patientList = (new MasterController)->patientList();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $NewMrdNo = $this->maxMrdNo();
        return view('opd/queuemanagement', ['userList'=>$userList,'NewMrdNo' => $NewMrdNo, 'patientList' => $patientList, 'stateList' => $stateList, 'cityList' => $cityList, 'consultantList' => $consultantList, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient]);
    }

    function getPatientList(Request $req)
    {
        $Patient_Name = $req->Patient_Name;
        $query = DB::select("SELECT * FROM tbl_patients WHERE (Fname LIKE '$Patient_Name%' 
                 OR Mname LIKE '$Patient_Name%' 
                 OR Lname LIKE '$Patient_Name%' 
                 OR PatientName LIKE '$Patient_Name%' 
                 OR Phone LIKE '$Patient_Name%')");
        return view('opd/viewoldptlists', ['data' => $query]);
    }
    function viewQueueList(Request $request)
    {
        // $CurrDate = date('Y-m-d');
        // if (!empty($request->FromDate)) {
        //     $result =  DB::table('tbl_queue_managements_temp as tq')
        //         ->leftJoin('tbl_users as tu', 'tu.id', '=', 'tq.Consultant')
        //         ->leftJoin('tbl_patients as tp', 'tp.MrdNo', '=', 'tq.MrdNo')
        //         ->leftJoin('tbl_users as tu2', 'tu2.id', '=', 'tq.ConfirmConsult')
        //         ->leftJoin('tbl_users as tu3', 'tu3.id', '=', 'tq.ConfirmOpto')
        //         ->where('InDate', $request->FromDate)
        //         ->select('tq.*', 'tp.Phone', 'tu2.Name As Consultant', 'tu3.Name As Opto')
        //         ->orderBy('tq.InTime', 'asc')->get();
        // } else {
        //     $result = DB::select("SELECT tq.*,tp.Phone,tu2.Name As Consultant,tu3.Name As Opto FROM tbl_queue_managements_temp tq 
        //             LEFT JOIN tbl_users tu ON tq.Consultant=tu.id 
        //             LEFT JOIN tbl_patients tp ON tp.MrdNo=tq.MrdNo 
        //             LEFT JOIN tbl_users tu2 ON tq.ConfirmConsult=tu2.id 
        //             LEFT JOIN tbl_users tu3 ON tq.ConfirmOpto=tu3.id 
        //             WHERE Checked=0 AND tq.InDate='$CurrDate' ORDER BY tq.InTime");
        // }
        //return $result;

        $CurrDate = date('Y-m-d');

        $result = DB::table('tbl_queue_managements_temp as tq')
        ->leftJoin('tbl_patients as tp', 'tp.MrdNo', '=', 'tq.MrdNo')
        ->leftJoin('tbl_users as tu4', 'tu4.id', '=', 'tq.CreatedBy')
        ->leftJoin('tbl_users as tu', 'tu.id', '=', 'tq.Consultant')
        ->select(
            'tq.id',
            'tq.MrdNo',
            'tq.PatientName',
            'tq.Gender',
            'tq.Age',
            'tq.InDate',
            'tq.InTime',
            'tq.PatientType',
            'tq.Appointment',
            'tq.Dilated',
            'tq.PayMode',
            'tq.Amount',
            'tq.OpdType',
            'tq.chkstatus',
            'tq.CreatedBy',
            'tq.InvStName',
            'tp.Phone',
            'tu4.Username as CreatedByName',
            'tq.ConsultantName',
            'tu.Username as ConsultName'
        )
        ->where('tq.InDate', $CurrDate)
        ->where('tq.Checked', 0)
        ->orderBy('tq.InTime', 'asc')
        ->get();

        return view('opd/viewqueuelists', ['data' => $result]);
    }
    function checkOtPatient($mrdno)
    {
        //return $mrdno;
        // $result =   DB::select("SELECT CreatedDate FROM tbl_ot_notes WHERE MrdNo='$mrdno' ORDER BY id DESC LIMIT 1");
        // $CreatedDate = $result[0]->CreatedDate;
        // if($CreatedDate == ''){
        //     $otdate = "";
        // }
        // else{
        //     $dt = strtotime($result[0]->CreatedDate);
        //     $otdate = date('Y-m-d', strtotime('+2 month', $dt));
        //     //return $result[0]->CreatedDate;
        // }
        // return $otdate;
        $result = OTModel::select('CreatedDate')->where('MrdNo', $mrdno)->orderBy('id', 'DESC')->limit(1)->get();

        $cnt = $result->count();
        if ($cnt > 0) {
            $dt = strtotime($result[0]->CreatedDate);
            $otdate = date('Y-m-d', strtotime('+2 month', $dt));
        } else {
            $otdate = "";
        }
        return $otdate;
    }

    function checkOtOpto($mrdno)
    {
        //$result =  DB::select("SELECT tp.Name AS OptoName FROM tbl_ot_notes tc LEFT JOIN tbl_users tp ON tp.id=tc.ConfirmOpto WHERE tc.MrdNo='$mrdno' ORDER BY tc.id DESC LIMIT 1");
        $result =  DB::table('tbl_ot_notes as tc')
            ->leftJoin('tbl_users as tu', 'tu.id', '=', 'tc.ConfirmOpto')
            ->where('tc.MrdNo', '=', $mrdno)
            ->select('tu.Name AS OptoName')
            ->orderBy('tc.id', 'desc')
            ->limit(1)
            ->get();
        $cnt = $result->count();
        if ($cnt > 0) {
            $OptoName = $result[0]->OptoName;
        } else {
            $OptoName = "N/A";
        }
        return $OptoName;
    }
    function checkOtStudyPatient($mrdno)
    {
        // $result =   DB::select("SELECT StudyPatient FROM tbl_ot_notes WHERE MrdNo='$mrdno' ORDER BY id DESC LIMIT 1");
        // $StudyPatient = $result[0]->StudyPatient;
        // if($StudyPatient == ""){
        //     $study = "";
        // }
        // else{
        //     $study = $result[0]->StudyPatient;
        // }
        // return $study;
        $result = OTModel::select('StudyPatient')->where('MrdNo', $mrdno)->orderBy('id', 'DESC')->limit(1)->get();
        $cnt = $result->count();
        if ($cnt > 0) {
            $study = $result[0]->StudyPatient;
        } else {
            $study = 0;
        }
        return $study;
    }
    function queuelist(Request $request)
    {
        $CurrDate = date('Y-m-d');
        //$query = QueueManagement::select()->where(['InDate'=>$CurrDate])->get();
        //$query = DB::select("SELECT tq.*,tu.Name AS Consultant_Name FROM tbl_queue_managements tq LEFT JOIN tbl_users tu ON tq.Consultant=tu.id WHERE Checked is null AND tq.InDate='$CurrDate'");
        //return $query;
        if ($request->ajax()) {
            if (!empty($request->FromDate)) {
                $data =  DB::table('tbl_queue_managements as tq')
                    ->leftJoin('tbl_users as tu', 'tu.id', '=', 'tq.Consultant')
                    ->whereBetween('InDate', array($request->FromDate, $request->ToDate))
                    ->select('tq.id', 'tq.MrdNo', 'tq.PatientName', 'tq.Gender', 'tq.PatientType', 'tq.PatientType', 'tu.Name AS Consultant_Name', 'tq.InTime', 'tq.Age', 'tq.Amount')
                    ->orderBy('tq.InDate', 'desc')->get();
                // $data = PatientModel::select('id','MrdNo','PatientName','Gender','ConsultantName','Age','Fees')
                // ->whereBetween('created_at', array($request->InDate, $request->InDate))->get();   
            } else {
                $data = DB::select("SELECT tq.id,tq.MrdNo,tq.PatientName,tq.Gender,tq.PatientType,tq.PatientType,tu.Name AS Consultant_Name,tq.InTime,tq.Age,tq.Amount FROM tbl_queue_managements tq LEFT JOIN tbl_users tu ON tq.Consultant=tu.id WHERE Checked is null AND tq.InDate='$CurrDate'");
            }
            //$data = PatientModel::select('id','MrdNo','PatientName','Gender','ConsultantName','Age','Fees')->limit(10000)->get();
            return Datatables::of($data)

                ->addIndexColumn()
                ->addColumn('action', function ($row) {

                    $btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';

                    return $btn;
                })
                ->addColumn('srno')
                ->rawColumns(['action', 'srno'])
                ->make(true);
        }
        return view('opd/queuemanagement');
    }

    function totalPatient()
    {
        $CurrDate = date('Y-m-d');
        $count = TempQueueManagement::select()->where(['InDate' => $CurrDate])->count();
        return $count;
    }
    function totalCheckPatient()
    {
        $CurrDate = date('Y-m-d');
        $count = TempQueueManagement::select()->where(['InDate' => $CurrDate, 'Checked' => '1'])->count();
        return $count;
    }

public function saveQueue(Request $req)
{
    DB::beginTransaction();

    try {

        QueueManagement::where('MrdNo', 0)->delete();
        PatientModel::where('srno', 0)->delete();


        /* ---------------- DUPLICATE CHECK ---------------- */

        $PatientName = trim($req->Fname . ' ' . $req->Mname . ' ' . $req->Lname);

        $exists = PatientModel::where('PatientName', $PatientName)
            ->whereDate('Dob', $req->Dob)
            ->where('Phone', $req->Phone)
            ->count();

        if ($exists > 0) {
            return json_encode([
                'Status' => 0,
                'Error' => 'Patient already exists with same Name, DOB & Mobile'
            ]);
        }


        /* ---------------- PATIENT SAVE ---------------- */

        $patient = new PatientModel;
        $patient->srno = 0;
        $patient->RegDate = $req->RegDate ?? date('Y-m-d');
        $patient->Suffix = $req->Suffix;
        $patient->Fname = $req->Fname;
        $patient->Mname = $req->Mname;
        $patient->Lname = $req->Lname;
        $patient->PatientName = $PatientName;

        $patient->Gender = $req->Gender;
        $patient->Dob = $req->Dob;
        $patient->Age = $req->Age;

        $patient->Phone = $req->Phone;
        $patient->Phone2 = $req->Phone2;
        $patient->City = $req->City;
        $patient->State = $req->State;
        $patient->Address = $req->Address;

        $patient->Consultant = $req->Consultant;
        $consult = UserMaster::find($req->Consultant);
        $patient->ConsultantName = $consult ? $consult->Name : null;

        $patient->Fees = $req->Fees;
        $patient->PayMode = $req->PayMode ?? 'Cash';
        $patient->RefBy = $req->RefBy;

        $patient->Status = 1;
        $patient->CreatedBy = Session::get('UserId');
        $patient->ModifiedBy = Session::get('UserId');
        $patient->CreatedDate = date('Y-m-d');

        $patient->save();


        /* ---------- ASSIGN MRD NO AFTER SAVE ---------- */

        $id = $patient->id;
        $MrdNo = $this->maxMrdNo();

        PatientModel::where('id', $id)->update([
            'MrdNo' => $MrdNo,
            'srno'  => $MrdNo
        ]);


        /* ---------------- QUEUE SAVE ---------------- */

        $queue = new QueueManagement;
        $queue->MrdNo = $MrdNo;
        $queue->PatientName = $PatientName;
        $queue->PatientType = 'New';
        $queue->Age = $req->Age;
        $queue->Gender = $req->Gender;
        $queue->InDate = date('Y-m-d');
        $queue->InTime = date('H:i:s');

        $queue->Consultant = $req->Consultant;
        $queue->ConsultantName = $patient->ConsultantName;

        $queue->Amount = $req->Fees;
        $queue->PayMode = $req->PayMode ?? 'Cash';
        $queue->OpdType = $req->OpdType;

        $queue->Status = 1;
        $queue->CreatedBy = Session::get('UserId');
        $queue->ModifiedBy = Session::get('UserId');

        $queue->save();

        $qid = $queue->id;


        /* -------- COPY TO TEMP TABLE -------- */

        DB::select("
            INSERT INTO tbl_queue_managements_temp 
            SELECT * FROM tbl_queue_managements WHERE id = '$qid'
        ");


        /* -------- COUNTS -------- */

        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $NewMrdNo = $this->maxMrdNo();


        /* -------- STORAGE FOLDERS -------- */

        $CurrDate   = date('Y-m-d');
        $FolderName = $MrdNo;
        $FolderName2 = $CurrDate;

        Storage::disk('local')->makeDirectory($FolderName);
        Storage::disk('local')->makeDirectory($FolderName . '/' . $FolderName2);


        /* -------- SAVE PATIENT FILE -------- */

        $patient_result = PatientModel::where('MrdNo', $MrdNo)->first();

        Storage::disk('local')->put(
            $FolderName . "/patient_details.txt",
            json_encode(['items' => $patient_result])
        );


        /* -------- VISIT / VISIT NO -------- */

        $mrdno = $MrdNo;
        $visitdate = date('Y-m-d');

        $checkstatus = QueueManagement::select('VisitNo', 'PatientName')
            ->where('id', $qid)->first();

        $PatientName = $checkstatus->PatientName;
        $visit_no = $checkstatus->VisitNo;

        if ($visit_no == 0) {
            $maxid = OptoModel::where('MrdNo', $mrdno)->max('VisitNo');
            $VisitNo = ($maxid ?? 0) + 1;

            QueueManagement::where('id', $qid)->update(['VisitNo' => $VisitNo]);
            TempQueueManagement::where('id', $qid)->update(['VisitNo' => $VisitNo]);
        } else {
            $VisitNo = $visit_no;
        }


        /* ======================================================
           ALWAYS CREATE VISIT / OPTO / CONSULTANT + FILES
           ====================================================== */

        /* VISIT */
        $Visit = new VisitModel;
        $Visit->MrdNo = $mrdno;
        $Visit->PatientName = $PatientName;
        $Visit->VisitDate = $visitdate;
        $Visit->VisitNo = $VisitNo;
        $Visit->save();
        $VisitPostId = $Visit->id;


        /* OPTO */
        $OptoModel = new OptoModel;
        $OptoModel->MrdNo = $mrdno;
        $OptoModel->VisitNo = $VisitNo;
        $OptoModel->VisitDate = $visitdate;
        $OptoModel->PatientName = $PatientName;
        $OptoModel->AllergyHistory = 'No history of allergy';
        $OptoModel->CreatedBy = Session::get('UserId');
        $OptoModel->ModifiedBy = Session::get('UserId');
        $OptoModel->save();
        $OptoPostId = $OptoModel->id;


        /* CONSULTANT */
        $ConsultantModel = new ConsultantModel;
        $ConsultantModel->MrdNo = $mrdno;
        $ConsultantModel->VisitNo = $VisitNo;
        $ConsultantModel->VisitDate = $visitdate;
        $ConsultantModel->PatientName = $PatientName;
        $ConsultantModel->CreatedBy = Session::get('UserId');
        $ConsultantModel->ModifiedBy = Session::get('UserId');
        $ConsultantModel->InvCheckout = 0;
        $ConsultantModel->save();
        $ConsultantPostId = $ConsultantModel->id;


        /* CONSULTANT TREATMENT */
        $ConsultantTreatmentModel = new ConsultantTreatmentModel;
        $ConsultantTreatmentModel->MrdNo = $mrdno;
        $ConsultantTreatmentModel->VisitNo = $VisitNo;
        $ConsultantTreatmentModel->VisitDate = $visitdate;
        $ConsultantTreatmentModel->save();
        $ConsultantTreatmentPostId = $ConsultantTreatmentModel->id;


        /* INVESTIGATION */
        $InvestigationModel2 = new InvestigationModel2;
        $InvestigationModel2->CreatedDate = date('Y-m-d');
        $InvestigationModel2->CreatedBy = Session::get('UserId');
        $InvestigationModel2->ModifiedBy = Session::get('UserId');
        $InvestigationModel2->MrdNo = $mrdno;
        $InvestigationModel2->VisitNo = $VisitNo;
        $InvestigationModel2->VisitDate = $visitdate;
        $InvestigationModel2->InvCheckout = 0;
        $InvestigationModel2->InvMoneyReceived = 0;
        $InvestigationModel2->save();


        /* -------- FETCH AND WRITE FILES -------- */

        $queue_result = QueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->first();
        $opto_result  = OptoModel::where('id', $OptoPostId)->first();
        $consult_result = ConsultantModel::where('id', $ConsultantPostId)->first();
        $consulttreat_result = ConsultantTreatmentModel::where('id', $ConsultantTreatmentPostId)->first();

        Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/queue.txt",
            json_encode(['items' => $queue_result]));

        Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/opto.txt",
            json_encode(['items' => $opto_result]));

        Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/consultant.txt",
            json_encode(['items' => $consult_result]));

        Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/consultant_treatment.txt",
            json_encode(['items' => $consulttreat_result]));


        /* -------- VISIT LIST -------- */

        $visitList = (new MasterController)->getPatientVisit($mrdno);

        Storage::disk('local')->put(
            $FolderName . "/visitlist.txt",
            json_encode(['items' => $visitList])
        );


        /* -------- FINAL COMMIT -------- */

        DB::commit();


        return json_encode([
            'MrdNo' => $MrdNo,
            'NewMrdNo' => $NewMrdNo,
            'Status' => 1,
            'totalPatient' => $totalPatient,
            'totalCheckPatient' => $totalCheckPatient,
            'totalUncheckPatient' => $totalUncheckPatient
        ]);


    } catch (\Exception $e) {

        DB::rollBack();

        return json_encode([
            'Status' => 0,
            'Error' => $e->getMessage()
        ]);
    }
}






    function EditQueue(Request $req)
    {
        $Patient = PatientModel::firstWhere(['MrdNo' => $req->Mrd_No]);
        $Patient->Suffix = $req->Suffix;
        $Patient->Fname = $req->Fname;
        $Patient->Mname = $req->Mname;
        $Patient->Lname = $req->Lname;
        $Patient->Gender = $req->Gender;
        $Patient->Dob = $req->Dob;
        $Patient->Age = $req->Age;
        $Patient->Phone = $req->Phone;
        $Patient->Phone2 = $req->Phone2;
        $Patient->City = $req->City;
        $Patient->State = $req->State;
        $Patient->Address = $req->Address;
        //$Patient->Consultant = $req->Consultant;
        //$result = UserMaster::select('Name')->where('id',$req->Consultant)->first();
        //$ConsultantName = $result->Name;
        //$Patient->ConsultantName = $ConsultantName;
        //$Patient->Fees = $req->Fees;
        //$Patient->PayMode = $req->PayMode;
        $Patient->PayMode = 'Cash';
        $Patient->RefBy = $req->RefBy;
        $Patient->Status = 1;
        $Patient->CreatedBy = Session::get('UserId'); 
        $Patient->ModifiedBy = Session::get('UserId'); 
        $Patient->CreatedDate = date('Y-m-d');
        $Patient->PatientName = $req->Fname . " " . $req->Mname . " " . $req->Lname;
        $Patient->save();
        $PatientName = $req->Fname . " " . $req->Mname . " " . $req->Lname;
        $ModifiedBy = Session::get('UserId'); 
        DB::select("UPDATE tbl_queue_managements SET PatientName='$PatientName',Age='$req->Age',Gender='$req->Gender',ModifiedBy='$ModifiedBy' WHERE MrdNo='$req->Mrd_No'");
        DB::select("UPDATE tbl_queue_managements_temp SET PatientName='$PatientName',Age='$req->Age',Gender='$req->Gender',ModifiedBy='$ModifiedBy' WHERE MrdNo='$req->Mrd_No'");
        $visitList = (new MasterController)->getPatientVisit($req->Mrd_No);

        foreach ($visitList as $visit) {
            $FolderName = $req->Mrd_No;
            $FolderName2 = $visit->VisitDate;
            $queue_result = QueueManagement::select()->where(['MrdNo' => $req->Mrd_No, 'InDate' => $visit->VisitDate])->first();
            $queue_data = json_encode(array('items' => $queue_result));
            Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/queue.txt", $queue_data);
        }

        $FolderName = $req->Mrd_No;
        PatientModel::where(['MrdNo' => $req->Mrd_No])->update(['Suffix' => $req->Suffix, 'Mname' => $req->Mname, 'Lname' => $req->Lname, 'Fname' => $req->Fname, 'Age' => $req->Age, 'Gender' => $req->Gender, 'Phone' => $req->Phone, 'Phone2' => $req->Phone2, 'City' => $req->City, 'State' => $req->State, 'Address' => $req->Address]);
        $patient_result = PatientModel::select()->where(['MrdNo' => $req->Mrd_No])->first();
        $patient_data = json_encode(array('items' => $patient_result));
        Storage::disk('local')->put($FolderName . "/patient_details.txt", $patient_data);

        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $NewMrdNo = $this->maxMrdNo();
        return json_encode(array('NewMrdNo' => $NewMrdNo, 'Status' => 1, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient));
    }

    function deletqueue(Request $req)
    {
        $result = QueueManagement::select('MrdNo', 'InDate')->where(['id' => $req->id])->get();
        $MrdNo = $result[0]->MrdNo;
        $VisitDate = $result[0]->InDate;
        $whereArray = array('MrdNo' => $MrdNo, 'VisitDate' => $VisitDate);
        VisitModel::where($whereArray)->delete();
        ConsultantModel::where($whereArray)->delete();
        OptoModel::where($whereArray)->delete();
        QueueManagement::find($req->id)->delete();
        TempQueueManagement::find($req->id)->delete();
        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        return json_encode(array('Status' => 1, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient));
    }

   function saveOldQueue(Request $req)
{
    DB::beginTransaction();

    try {

        $mrdno = $req->MRD_NO;
        $CurrDate = date('Y-m-d');

        /* ---------------- MARK PREVIOUS QUEUE OUT ---------------- */
        QueueManagement::where('MrdNo', $mrdno)
            ->where('Checked', 0)
            ->update([
                'Checked' => 1,
                'OutTime' => date('H:i:s')
            ]);


        /* ---------------- STOP DUPLICATE ENTRY SAME DAY ---------------- */
        $exists = QueueManagement::where([
            'MrdNo' => $mrdno,
            'InDate' => $CurrDate
        ])->count();

        if ($exists > 0) {
            return json_encode(['Status' => 0, 'Message' => 'Already Added In Queue Today']);
        }


        /* ---------------- CREATE NEW QUEUE ENTRY ---------------- */
        $queue = new QueueManagement;
        $queue->MrdNo        = $mrdno;
        $queue->PatientName  = $req->PatientName;
        $queue->PatientType  = 'Old';
        $queue->Age          = $req->PatientAge;
        $queue->Gender       = $req->PatGender;
        $queue->OpdType      = $req->OpdType;
        $queue->InDate       = $CurrDate;
        $queue->InTime       = date('H:i:s');

        $queue->Consultant   = $req->Consultant;
        $doc = UserMaster::find($req->Consultant);
        $queue->ConsultantName = $doc ? $doc->Name : null;

        $queue->Amount       = $req->Fees;
        $queue->PayMode      = 'Cash';

        // NEW VITALS (from your updated form)
        $queue->Weight = $req->Weight ?? null;
        $queue->Height = $req->Height ?? null;
        $queue->Temp   = $req->Temp ?? null;

        $queue->PrevConsultant = '';
        $queue->Status = 1;
        $queue->CreatedBy = Session::get('UserId');
        $queue->ModifiedBy = Session::get('UserId');

        $queue->save();
        $qid = $queue->id;


        /* ---------------- COPY TO TEMP TABLE ---------------- */
        DB::select("
            INSERT INTO tbl_queue_managements_temp 
            SELECT * FROM tbl_queue_managements WHERE id = '$qid'
        ");


        /* ---------------- UPDATE PATIENT RECORD ---------------- */
        PatientModel::where('MrdNo', $mrdno)->update([
            'Age'    => $req->PatientAge,
            'Gender' => $req->PatGender,
            'Address'=> $req->PatientAddress,
            'City'   => $req->PatientCity,
            'Weight' => $req->Weight ?? null,
            'Height' => $req->Height ?? null,
            'Temp'   => $req->Temp ?? null,
        ]);


        /* ---------------- CREATE STORAGE FOLDERS ---------------- */
        Storage::disk('local')->makeDirectory($mrdno);
        Storage::disk('local')->makeDirectory($mrdno . '/' . $CurrDate);


        /* ---------------- SAVE PATIENT JSON FILE ---------------- */
        $patient = PatientModel::where('MrdNo', $mrdno)->first();
        Storage::disk('local')->put(
            $mrdno . "/patient_details.txt",
            json_encode(['items' => $patient])
        );


        /* ---------------- QUEUE COUNTS ---------------- */
        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $NewMrdNo = $this->maxMrdNo();


        /* ---------------- CREATE VISIT NO IF NEEDED ---------------- */
        $visitdate = $CurrDate;
        $visit_no = $queue->VisitNo;

        if ($visit_no == 0) {
            $maxid = OptoModel::where('MrdNo', $mrdno)->max('VisitNo');
            $VisitNo = ($maxid ?? 0) + 1;

            QueueManagement::where('id', $qid)->update(['VisitNo' => $VisitNo]);
            TempQueueManagement::where('id', $qid)->update(['VisitNo' => $VisitNo]);
        } else {
            $VisitNo = $visit_no;
        }


        /* ---------------- ALWAYS CREATE VISIT / OPTO / CONSULTANT ---------------- */

        $Visit = new VisitModel;
        $Visit->MrdNo = $mrdno;
        $Visit->PatientName = $req->PatientName;
        $Visit->VisitDate = $visitdate;
        $Visit->VisitNo = $VisitNo;
        $Visit->save();


        $OptoModel = new OptoModel;
        $OptoModel->MrdNo = $mrdno;
        $OptoModel->VisitNo = $VisitNo;
        $OptoModel->VisitDate = $visitdate;
        $OptoModel->PatientName = $req->PatientName;
        $OptoModel->AllergyHistory = 'No history of allergy';
        $OptoModel->CreatedBy = Session::get('UserId');
        $OptoModel->ModifiedBy = Session::get('UserId');
        $OptoModel->save();


        $ConsultantModel = new ConsultantModel;
        $ConsultantModel->MrdNo = $mrdno;
        $ConsultantModel->VisitNo = $VisitNo;
        $ConsultantModel->VisitDate = $visitdate;
        $ConsultantModel->PatientName = $req->PatientName;
        $ConsultantModel->InvCheckout = 0;
        $ConsultantModel->CreatedBy = Session::get('UserId');
        $ConsultantModel->ModifiedBy = Session::get('UserId');
        $ConsultantModel->save();


        $ConsultantTreatmentModel = new ConsultantTreatmentModel;
        $ConsultantTreatmentModel->MrdNo = $mrdno;
        $ConsultantTreatmentModel->VisitNo = $VisitNo;
        $ConsultantTreatmentModel->VisitDate = $visitdate;
        $ConsultantTreatmentModel->save();


        $InvestigationModel2 = new InvestigationModel2;
        $InvestigationModel2->CreatedDate = $visitdate;
        $InvestigationModel2->CreatedBy = Session::get('UserId');
        $InvestigationModel2->ModifiedBy = Session::get('UserId');
        $InvestigationModel2->MrdNo = $mrdno;
        $InvestigationModel2->VisitNo = $VisitNo;
        $InvestigationModel2->VisitDate = $visitdate;
        $InvestigationModel2->InvCheckout = 0;
        $InvestigationModel2->InvMoneyReceived = 0;
        $InvestigationModel2->PatientName = $req->PatientName;
        $InvestigationModel2->save();


        /* ---------------- WRITE DAILY FILES ---------------- */
        $queue_data = QueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->first();
        $opto_data = OptoModel::where('MrdNo', $mrdno)->where('VisitNo', $VisitNo)->first();
        $consult_data = ConsultantModel::where('MrdNo', $mrdno)->where('VisitNo', $VisitNo)->first();
        $consult_treat_data = ConsultantTreatmentModel::where('MrdNo', $mrdno)->where('VisitNo', $VisitNo)->first();

        Storage::disk('local')->put("$mrdno/$visitdate/queue.txt", json_encode(['items' => $queue_data]));
        Storage::disk('local')->put("$mrdno/$visitdate/opto.txt", json_encode(['items' => $opto_data]));
        Storage::disk('local')->put("$mrdno/$visitdate/consultant.txt", json_encode(['items' => $consult_data]));
        Storage::disk('local')->put("$mrdno/$visitdate/consultant_treatment.txt", json_encode(['items' => $consult_treat_data]));


        /* ---------------- VISIT LIST FILE ---------------- */
        $visitList = (new MasterController)->getPatientVisit($mrdno);
        Storage::disk('local')->put("$mrdno/visitlist.txt", json_encode(['items' => $visitList]));


        /* ---------------- SUCCESS ---------------- */
        DB::commit();

        return json_encode([
            'Status' => 1,
            'NewMrdNo' => $NewMrdNo,
            'totalPatient' => $totalPatient,
            'totalCheckPatient' => $totalCheckPatient,
            'totalUncheckPatient' => $totalUncheckPatient
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return json_encode([
            'Status' => 0,
            'Error' => $e->getMessage()
        ]);
    }
}


    function newpatients(Request $request)
    {
        if ($request->ajax()) {
            if (!empty($request->FromDate)) {
                $data = PatientModel::select('id', 'MrdNo', 'PatientName', 'Gender', 'ConsultantName', 'Age', 'Fees')
                    ->whereBetween('CreatedDate', array($request->FromDate, $request->ToDate))->get();
            } else {
                $data = DB::select("CALL getPatients()");
            }
            //$data = PatientModel::select('id','MrdNo','PatientName','Gender','ConsultantName','Age','Fees')->limit(10000)->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($row) {

                    $btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';

                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        //$result = PatientModel::select()->limit(10)->get();
        //return $result;
        return view('opd/newpatientlists');
    }

    function viewNewPatientList(Request $request)
    {
        $CurrDate = date('Y-m-d');
        if (!empty($request->FromDate)) {
            $result = PatientModel::select('id', 'MrdNo', 'PatientName', 'Gender', 'ConsultantName', 'Age', 'Fees')
                ->whereBetween('CreatedDate', array($request->FromDate, $request->ToDate))->get();
        } else {
            $result = DB::select("CALL getPatients()");
        }
        //return $result;
        return view('opd/viewnewpatientlists', ['data' => $result]);
    }

    function fetchPatientDetails(Request $req)
    {
        $result = PatientModel::select()->where(['MrdNo' => $req->id])->first();
        $result2 = TempQueueManagement::select('Amount','Consultant')->where(['MrdNo' => $req->id])->first();
        // Convert both to arrays
    $resultArray = $result ? $result->toArray() : [];
    $result2Array = $result2 ? $result2->toArray() : [];

    // Merge and return
    return json_encode(array_merge($resultArray, $result2Array));
    }

    function fetchQueuePatientDetails(Request $req)
    {
        $result = QueueManagement::select()->where(['id' => $req->id])->first();
        return json_encode($result);
    }
    function newPatient()
    {
        $consultantList = (new MasterController)->consultantList();
        $cityList = (new MasterController)->cityList();
        $stateList = (new MasterController)->stateList();
        $patientList = (new MasterController)->patientList();
        return view('opd/newpatientlists', ['patientList' => $patientList, 'stateList' => $stateList, 'cityList' => $cityList, 'consultantList' => $consultantList]);
    }

    function deletPatient(Request $req)
    {
        QueueManagement::where(['MrdNo' => $req->id])->delete();
        TempQueueManagement::where(['MrdNo' => $req->id])->delete();
        PatientModel::where(['MrdNo' => $req->id])->delete();
        return 1;
    }

    function patientOut(Request $req)
    {
        $id = $req->id;
        $mrdno = $req->mrdno;
        $indate = $req->indate;
        $OutTime = date('H:i:s');
        QueueManagement::where(['id' => $id])->update(['Checked' => 1, 'OutTime' => $OutTime]);
        TempQueueManagement::where(['id' => $id])->update(['Checked' => 1, 'OutTime' => $OutTime]);
        ConsultantModel::where(['MrdNo' => $mrdno, 'VisitDate' => $indate])->update(['Checked' => 1]);
        VisitModel::where(['MrdNo' => $mrdno, 'VisitDate' => $indate])->update(['Checked' => 1]);
        OptoModel::where(['MrdNo' => $mrdno, 'VisitDate' => $indate])->update(['Checked' => 1]);
        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        return json_encode(array('Status' => 1, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient));
    }

    function updateQueueDetails(Request $req)
    {
        $QueueManagement = QueueManagement::find($req->id2);
        $QueueManagement->Age = $req->Age2;
        $QueueManagement->Gender = $req->Gender2;
        $QueueManagement->Consultant = $req->Consultant2;
        // $result = UserMaster::select('Name')->where('id',$req->Consultant2)->first();
        // $ConsultantName = $result->Name;
        // $QueueManagement->ConsultantName = $ConsultantName;
        $QueueManagement->Amount = $req->Amount2;
        $QueueManagement->PayMode = $req->PayMode2;
        //$QueueManagement->CreatedBy = $req->Createdby2;
        $QueueManagement->save();

        $TempQueueManagement = TempQueueManagement::find($req->id2);
        $TempQueueManagement->Age = $req->Age2;
        $TempQueueManagement->Gender = $req->Gender2;
        $TempQueueManagement->Consultant = $req->Consultant2;
        $TempQueueManagement->Amount = $req->Amount2;
        $TempQueueManagement->PayMode = $req->PayMode2;
       // $TempQueueManagement->CreatedBy = $req->Createdby2;
        $TempQueueManagement->save();

        $queue_result = QueueManagement::select()->where(['id' => $req->id2])->first();
        $FolderName = $queue_result->MrdNo;
        $FolderName2 = $queue_result->InDate;
        $queue_data = json_encode(array('items' => $queue_result));
        Storage::disk('local')->put($FolderName . "/" . $FolderName2 . "/queue.txt", $queue_data);

        PatientModel::where(['MrdNo' => $req->MrdNo2])->update(['Age' => $req->Age2, 'Gender' => $req->Gender2]);
        $patient_result = PatientModel::select()->where(['MrdNo' => $queue_result->MrdNo])->first();
        $patient_data = json_encode(array('items' => $patient_result));
        Storage::disk('local')->put($FolderName . "/patient_details.txt", $patient_data);

        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        return json_encode(array('Status' => 1, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient));
    }

    function changeFees(Request $req)
    {
        $visitno = $req->visitno;
        $visitdate = $req->visitdate;
        $mrdno = $req->mrdno;
        $Fees = $req->Fees;

        $data4 = QueueManagement::select('Amount')->where(['MrdNo' => $mrdno, 'InDate' => $visitdate, 'VisitNo' => $visitno])->get();
        $cntrow4 = $data4->count();
        if ($cntrow4 > 0) {
            QueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate, 'VisitNo' => $visitno])->update(['Amount' => $Fees]);
            TempQueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate, 'VisitNo' => $visitno])->update(['Amount' => $Fees]);
        } else {
            $data5 =  QueueManagement::select('Amount')->where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->get();
            $cntrow5 = $data5->count();
            if ($cntrow5 > 0) {
                QueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->update(['Amount' => $Fees]);
                TempQueueManagement::where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->update(['Amount' => $Fees]);
            } else {
            }
        }


        return 1;
    }

    function refreshQueue()
    {
        $totalPatient = $this->totalPatient();
        $totalCheckPatient = $this->totalCheckPatient();
        $totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $NewMrdNo = $this->maxMrdNo();
        return json_encode(array('NewMrdNo' => $NewMrdNo, 'totalPatient' => $totalPatient, 'totalCheckPatient' => $totalCheckPatient, 'totalUncheckPatient' => $totalUncheckPatient));
    }

    function dailyReport($fromdate)
    {
        $result = QueueManagement::where("InDate", $fromdate)->get();
        $total = $result->count();
        $male = QueueManagement::where(['InDate' => $fromdate, 'Gender' => 'Male'])->count();
        $female = QueueManagement::where(['InDate' => $fromdate, 'Gender' => 'Female'])->count();
        $new = QueueManagement::where(['InDate' => $fromdate, 'PatientType' => 'New'])->count();
        $old = QueueManagement::where(['InDate' => $fromdate, 'PatientType' => 'Old'])->count();
        $free = QueueManagement::where(['InDate' => $fromdate, 'Amount' => '0'])->count();
        $paid = QueueManagement::where(['InDate' => $fromdate])->where('Amount', '>', '0')->count();
        $appointment = QueueManagement::where(['InDate' => $fromdate, 'Appointment' => '1'])->count();
        $dialted = QueueManagement::where(['InDate' => $fromdate, 'Dilated' => '1'])->count();
        return view('/opd/incqueuereport', [
            'data' => $result,
            'total' => $total,
            'male' => $male,
            'female' => $female,
            'new' => $new,
            'old' => $old,
            'free' => $free,
            'paid' => $paid,
            'appointment' => $appointment,
            'dialted' => $dialted
        ]);
    }

    function viewOpdQueue(Request $request)
    {
        $CurrDate = date('Y-m-d');
        $result = DB::select("SELECT tq.* FROM tbl_queue_managements tq LEFT JOIN tbl_users tu ON tq.Consultant=tu.id WHERE Checked=0 AND tq.InDate='$CurrDate' ORDER BY tq.InTime");
        return view('opd/view-opd-queue-list', ['data' => $result]);
    }

    function patientPrevSummary()
    {
        $patientList = (new MasterController)->patientList();
        return view('/opd/view-patient-summary', ['patientList' => $patientList]);
    }

    function getLastVisit(Request $req)
    {
        $mrdno = $req->mrdno;
        $maxvisitno = OptoModel::select()->where(['MrdNo' => $mrdno, 'Checked' => 1])->max('VisitNo');
        return $maxvisitno;
    }

    function getVisitDetails($mrdno)
    {
        //    $result = DB::table('tbl_optometrist as topt')
        //             ->leftJoin('tbl_consultants as tc', 'tc.MrdNo', '=', 'topt.MrdNo')
        //             ->where(['topt.MrdNo'=>$mrdno])
        //             ->select('topt.ConfirmConsult','topt.ConfirmOpto','tc.InvStName')
        //             ->orderBy('topt.VisitNo','desc')->limit(1)->get();
        //     if($result->count() > 0){
        //         return $result;
        //     }
        //     else{
        //         return "";
        //     }

        $cnt = OptoModel::select('ConfirmConsult')->where(['MrdNo' => $mrdno, 'Checked' => 1])->count();
        if ($cnt > 0) {
            //$result = OptoModel::select('ConfirmConsult')->where(['MrdNo'=>$mrdno,'Checked'=>1])->first();
            // $result =  DB::table('tbl_optometrist as topt')
            //         ->leftJoin('tbl_users as tu2', 'tu2.id', '=', 'topt.ConfirmConsult')
            //         ->where(['topt.MrdNo'=>$mrdno,'topt.Checked'=>1])
            //         ->select('tu2.Name As Consultant')
            //         ->orderBy('topt.VisitNo','desc')->first();
            $result = QueueManagement::select('ConsultantName')->where(['MrdNo' => $mrdno, 'Checked' => 1])->orderBy('InDate', 'desc')->limit(1)->first();
            return $result->ConsultantName;
        } else {
            return "";
        }
    }

    function BringBackToQueue()
    {
        return view('/opd/bring-back-to-queue');
    }

    function getLastQueueDetails(Request $req)
    {
        $MrdNo = $req->MrdNo;
        $VisitDate = $req->VisitDate;
        $result =  QueueManagement::where(['MrdNo' => $MrdNo, 'InDate' => $VisitDate])->first();
        return json_encode($result);
    }
    function backToQueue(Request $req)
    {
        $MrdNo = $req->MrdNo;
        $VisitDate = $req->VisitDate;
        TempQueueManagement::where(['MrdNo' => $MrdNo, 'InDate' => $VisitDate])->update(['Checked' => 0]);
        QueueManagement::where(['MrdNo' => $MrdNo, 'InDate' => $VisitDate])->update(['Checked' => 0]);
        ConsultantModel::where(['MrdNo' => $MrdNo, 'VisitDate' => $VisitDate])->update(['Checked' => 0]);
        VisitModel::where(['MrdNo' => $MrdNo, 'VisitDate' => $VisitDate])->update(['Checked' => 0]);
        OptoModel::where(['MrdNo' => $MrdNo, 'VisitDate' => $VisitDate])->update(['Checked' => 0]);
        return 1;
    }

    function getPatientBal($mrdno)
    {
        $Amount2 = PatientBalanceModel::where(['MrdNo' => $mrdno])->sum('Amount');
        if ($Amount2 == '') {
            $Amount = 0;
        } else {
            $Amount = $Amount2;
        }
        return $Amount;
    }

    function stickerPrint($MrdNo)
    {
        // $result =  PatientModel::where(['MrdNo'=>$MrdNo])->first();
        $ptdata = Storage::disk('local')->get($MrdNo . "/patient_details.txt");
        $result = json_decode($ptdata, true);
        return view('/opd/stricker-print', ['pt_data' => $result]);
    }

    function getRefList(Request $req)
    {
        $RefBy = $req->RefBy;
        $data = ReferedByModel::where('Name', 'LIKE', "%{$RefBy}%")
            ->limit(10)
            ->pluck('name'); // You can return ID + name if needed

        return response()->json($data);
    }

    function getSearchPatientList(Request $req)
    {
        $Patient_Name = $req->TopPatientName;
        $data = PatientModel::where(function ($query) use ($Patient_Name) {
            $query->where('Fname', 'LIKE', "%{$Patient_Name}%")
                ->orWhere('Mname', 'LIKE', "%{$Patient_Name}%")
                ->orWhere('Lname', 'LIKE', "%{$Patient_Name}%")
                ->orWhere('PatientName', 'LIKE', "%{$Patient_Name}%")
                ->orWhere('MrdNo', 'LIKE', "%{$Patient_Name}%")
                ->orWhere('Phone', 'LIKE', "%{$Patient_Name}%");
        })
            ->limit(10)
            ->get(['MrdNo', 'PatientName', 'Phone']);

        // Create a new array with only MrdNo and PatientNameFull
        $result = $data->map(function ($item) {
            return [
                'MrdNo' => $item->MrdNo,
                'PatientNameFull' => $item->MrdNo . ' / ' . $item->PatientName
                    . (!empty($item->Phone) ? ' / ' . $item->Phone : ''),
            ];
        });

        return response()->json($result);
    }

    function clearBlankRecord(){
        QueueManagement::where(['MrdNo'=>0])->delete();
        PatientModel::where(['srno'=>0])->delete();
        return 1;
    }

    function getUserName($userid){
        $result = UserMaster::select('Name')->where(['id'=>$userid])->first();
        return $result->Name;
    }

    function todayPatientList($val)
    {
        $CurrDate = date('Y-m-d');

        $query = DB::table('tbl_queue_managements_temp as tq')
            ->leftJoin('tbl_users as tu', 'tq.Consultant', '=', 'tu.id')
            ->leftJoin('tbl_users as tu2', 'tq.CreatedBy', '=', 'tu2.id')
            ->select('tq.*','tu2.Username as CreatedByName','tu.Username as ConsultName') // You can customize/select specific fields here
            ->where('tq.InDate', $CurrDate);

        // Apply filters based on $val
        if ($val == 1) {
            $Label = "Total Patient Lists";
            $query->whereIn('tq.Checked', [0, 1]);
        } elseif ($val == 2) {
            $Label = "Checked Patient Lists";
            $query->where('tq.Checked', 1);
        } elseif ($val == 3) {
            $Label = "Unchecked Patient Lists";
            $query->where('tq.Checked', 0);
        }

        $result = $query->orderBy('tq.InTime')->get();
        return view('opd/view-opd-queue-list', ['data' => $result, 'Label' => $Label]);
    }

    function visitAmount($mrdno,$visitdate){
        $result =  QueueManagement::select('Amount')->where(['MrdNo' => $mrdno, 'InDate' => $visitdate])->first(); 
           return $result->Amount ?? 0;
       }
}
