<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\MasterController;
use App\Http\Controllers\OtScheduledController;
use App\Models\OtScheduledModel;
use App\Models\OTModel;
use App\Models\ConsultantModel;
use App\Models\LenseModel;
use App\Http\Controllers\PackageController;
use App\Http\Controllers\ConsentController;

use Session;
class OTNoteController extends Controller
{
    function otNotes(){
        return view('/ipd/view-otnotes');
    }
    function addOtNotes(){
        //$patientList = (new MasterController)->patientList();
        $patientList = (new OtScheduledController)->getOtSchId();
        //$optometristList = (new MasterController)->optometristList2();
       // $packagelist = (new PackageController)->packageList();
        $consultantList = (new MasterController)->surgeonList();
        //$otpatientList = OTModel::select()->where(['Roll'=>1])->orderBy('id','desc')->get();
        //$projectList = (new MasterController)->descriptionList('Project');
        $consentList = (new ConsentController)->getConsentList();
        return view('/ipd/add-otnotes',['consentList'=>$consentList,'consultantList'=>$consultantList,'patientList'=>$patientList]);
    }
    function addOtNotes2($mrdno){
        $patientList = (new MasterController)->patientList();
        $optometristList = (new MasterController)->optometristList2();
        $packagelist = (new PackageController)->packageList();
        return view('/ipd/add-otnotes2',['packagelist'=>$packagelist,'optometristList'=>$optometristList,'patientList'=>$patientList,'MrdNo'=>$mrdno]);
    }

    function saveOtNotes(Request $req){
        if($req->action == 'Save'){
        $OtNote = new OTModel;
        }
        else{
        $OtNote = OTModel::find($req->saveid);   
        }
        $OtNote->PatientId = $req->PatientId; 
        $OtNote->OtPatientId = $req->OtPatientId;
        $OtNote->MrdNo = $req->MrdNo;
        $OtNote->PatientName = $req->PatientName; 
        $OtNote->Age = $req->Age;
        $OtNote->Phone = $req->Phone;
        $OtNote->Address = $req->Address; 
        $OtNote->Gender = $req->Gender;
        $OtNote->Eye = $req->Eye;
        $OtNote->Diagnosis = $req->Diagnosis;
        $OtNote->Bs = $req->Bs; 
        $OtNote->Bp = $req->Bp;
        $OtNote->IopRe = $req->IopRe;
        $OtNote->IopLe = $req->IopLe; 
        $OtNote->Other = $req->Other;
        $OtNote->Category = $req->Category;
        $OtNote->K1Re = $req->K1Re; 
        $OtNote->K1Le = $req->K1Le;
        $OtNote->K2Re = $req->K2Re;
        $OtNote->K2Le = $req->K2Le;
        $OtNote->AL = $req->AL; 
        $OtNote->Acd = $req->Acd;
        $OtNote->IolPower = $req->IolPower;
        $OtNote->Formula = $req->Formula; 
        $OtNote->Aconstant = $req->Aconstant;
        $OtNote->Surgeon = $req->Surgeon;
        $OtNote->Assistant = $req->Assistant; 
        $OtNote->Anaethetist = $req->Anaethetist;
        $OtNote->Package = $req->Package;
        $OtNote->SurgeryPerformed = $req->SurgeryPerformed;
        $OtNote->DilatedBy = $req->DilatedBy; 
        $OtNote->AnesthesiaType = $req->AnesthesiaType;
        $OtNote->Draping = $req->Draping;
        $OtNote->Speculum = $req->Speculum; 
        $OtNote->ConjunctivalWash = $req->ConjunctivalWash;
        $OtNote->SideportIncision = $req->SideportIncision;
        $OtNote->Viscoelastic = $req->Viscoelastic; 
        $OtNote->ccc = $req->ccc;
        $OtNote->CapStaining = $req->CapStaining;
        $OtNote->IrrigationSol = $req->IrrigationSol;
        $OtNote->Hydroscetion = $req->Hydroscetion; 
        $OtNote->Nucleus = $req->Nucleus;
        $OtNote->CorticalWash = $req->CorticalWash;
        $OtNote->Lri = $req->Lri; 
        $OtNote->WoundHydration = $req->WoundHydration;
        $OtNote->Intracameral = $req->Intracameral;
        $OtNote->PkgAmt = $req->PkgAmt; 
        $OtNote->InsComp = $req->InsComp;
        $OtNote->ReqAmt = $req->ReqAmt;
        $OtNote->SanctAmt = $req->SanctAmt;
        $OtNote->AddAmt = $req->AddAmt; 
        $OtNote->SettleAmt = $req->SettleAmt;
        $OtNote->SettleDate = $req->SettleDate;
        $OtNote->UtrNo = $req->UtrNo; 
        $OtNote->ProcedureComments = $req->ProcedureComments;
        $OtNote->Remarks = $req->Remarks;
        $OtNote->IolName = $req->IolName;
        $OtNote->IolType = $req->IolType;
        $OtNote->RefundAmt = $req->RefundAmt;
        $OtNote->RefundDate = $req->RefundDate;
        $OtNote->SrNo = $req->SrNo;
        //$OtNote->StudyPatient = $req->StudyPatient;
        if($req->StudyPatient == 1){
            $OtNote->StudyPatient = 1;
            }
            else{
                $OtNote->StudyPatient = 0;
            }
        $OtNote->ConfirmOpto = $req->ConfirmOpto;
        $OtNote->Cyl = $req->Cyl;
        $OtNote->NearAdd = $req->NearAdd;
        $OtNote->PackageAmount = $req->PackageAmount;
        $OtNote->Status = 1;
        $OtNote->Roll = 1;
        $OtNote->CreatedBy = Session::get('UserId'); 
        $OtNote->CreatedDate = $req->CreatedDate;
        $OtNote->CreatedTime = $req->CreatedTime;
        $OtNote->Project = $req->Project;

        $OtNote->AdmissionDate = $req->AdmissionDate;
        $OtNote->CounsellingDate = $req->CounsellingDate;
        $OtNote->SurgeryDate = $req->SurgeryDate;
        $OtNote->SurgeryName = $req->SurgeryName;
        $OtNote->SurgeonName = $req->SurgeonName;
        $OtNote->Anaesthetist = $req->Anaesthetist;
        $OtNote->SurgeryPkg = $req->SurgeryPkg;
        $OtNote->LaGa = $req->LaGa;
        $OtNote->CounsellingDoneBy = $req->CounsellingDoneBy;
        $OtNote->Iol = $req->Iol;
        $OtNote->Diopter = $req->Diopter;
        $OtNote->IpdNo = $req->IpdNo;
        $OtNote->ConfirmSurgery = $req->ConfirmSurgery;
        $OtNote->SurgeryCharges = $req->SurgeryCharges;
        $OtNote->Payment1 = $req->Payment1;
        $OtNote->Amount1 = $req->Amount1;
        $OtNote->Payment2 = $req->Payment2;
        $OtNote->Amount2 = $req->Amount2;
        $OtNote->Payment3 = $req->Payment3;
        $OtNote->Amount3 = $req->Amount3;
        $OtNote->Payment4 = $req->Payment4;
        $OtNote->Amount4 = $req->Amount4;
        $OtNote->Remarks = $req->Remarks;
        $OtNote->RelativeName1 = $req->RelativeName1;
        $OtNote->Relation1 = $req->Relation1;
        $OtNote->ContactNo1 = $req->ContactNo1;
        $OtNote->RelativeName2 = $req->RelativeName2;
        $OtNote->Relation2 = $req->Relation2;
        $OtNote->ContactNo2 = $req->ContactNo2;
        $OtNote->ConsentId = $req->ConsentId;
        $OtNote->payment_type1=$req->payment_type1;
        $OtNote->payment_type2=$req->payment_type2;
        $OtNote->payment_type3=$req->payment_type3;
        $OtNote->payment_type4=$req->payment_type4;
        $OtNote->payment_type5=$req->payment_type5;
        $OtNote->save();
       
        return $OtNote->id;

    }

    function checkOtPatient(Request $req){
        $val = $req->id;
        $seperate = explode(" / ", $val);
        $otid = $seperate[0];
        //$eye = $req->eye;
        $result = OTModel::where(['id'=>$otid])->first();
        $cnt = OTModel::where(['id'=>$otid])->count();
        if($cnt > 0){
            return json_encode(array('Status'=>1,'result'=>$result));
        }
        else{
            return json_encode(array('Status'=>0));
        }
    }

    function printOtNotes($id){
        $result = OTModel::find($id);
        return view('/ipd/view-print-ot-notes',['data'=>$result]);
    }

    function printIpdSticker($id){
        $result = OTModel::find($id);
        return view('/ipd/view-print-ipd-sticker',['data'=>$result]);
    }

    function getPrevVisitDetails(Request $req){
        $MrdNo = $req->MrdNo;
        $visitno = ConsultantModel::where('MrdNo',$MrdNo)->max('VisitNo');
        $result2 =  DB::table('tbl_optometrist as topt')
        ->join('tbl_consultants as tc',function($join){
                $join->on("topt.MrdNo","=","tc.MrdNo")
                    ->on("topt.VisitNo","=","tc.VisitNo");
            })
        ->where(['topt.MrdNo'=>$MrdNo,'topt.VisitNo'=>$visitno])
->select('topt.RefK1Re','topt.RefK1Le','topt.RefK2Re','topt.RefK2Le','topt.RefDiffRe','tc.Diagnosis','tc.BP',
        'topt.IopNctRe','topt.IopReTime','topt.IopNctLe','topt.IopLeTime','tc.Advice')
->first();

        //$result2 = ConsultantModel::where(['VisitNo'=>$visitno,'MrdNo'=>$MrdNo])->first();
        return json_encode($result2);
    }

    function checkLastOtPatient(Request $req){
        $MrdNo = $req->id;
        $cnt = OTModel::where('MrdNo',$MrdNo)->count();
        if($cnt > 0){
            $maxid = OTModel::select('id')->where('MrdNo',$MrdNo)->orderBy('CreatedDate','desc')->first();
            $id = $maxid->id;
            $result = OTModel::where('id',$id)->first();
            //return $result;
            return json_encode($result);
        }
        else{
            return 0;
        }
    }

    function opdOtNotesReport($mrdno){
        $result = OTModel::where('MrdNo',$mrdno)->orderBy('CreatedDate','desc')->get();
        return view('/ipd/view-ot-notes-report',['data'=>$result]);
    }

    function viewOtNoteLists(){
       return view('/ipd/view-ot-note-list');
    }

    function otNoteLists(Request $req){
        if(!empty($req->FromDate))
        {
        $result = OTModel::where(['CreatedDate'=>$req->FromDate])->get();
        }
        return view('/ipd/inc-ot-note-list',['data'=>$result]);
    }

    function addOtNotes3($id){
        $result = OtScheduledModel::where('id',$id)->first();
        $optometristList = (new MasterController)->optometristList();
        $packagelist = (new PackageController)->packageList();
        return view('/ipd/add-otnotes3',['id'=>$id,'data'=>$result,'packagelist'=>$packagelist,'optometristList'=>$optometristList]);
    }

    function searchCounsellingList(){
        return view('/ipd/search-counselling-list');
    }

    function counsellingList($fromdate,$todate){
        $result = OTModel::whereBetween('CounsellingDate', array($fromdate, $todate))->get();
        return view('/ipd/view-counselling-list',['data'=>$result,'fromdate'=>$fromdate]);
    }

    function searchOtList(){
        return view('/ipd/search-ot-list');
    }

    function counsellingotList($fromdate,$todate){
        $result = OTModel::whereBetween('SurgeryDate', array($fromdate, $todate))->where(['ConfirmSurgery'=>'Yes'])->get();
        return view('/ipd/view-ot-list',['data'=>$result,'fromdate'=>$fromdate]);
    }

    function opdCounsellingList(){
        $result = ConsultantModel::select('id', 'CouncRemark', 'MrdNo', 'VisitDate', 'PatientName')
            ->where('CouncRemark', '!=', '')
            ->where(function($query) {
                $query->whereNull('ReCornea')
                      ->orWhere('ReCornea', '!=', '1');
            })
            ->get();
                return view('/ipd/view-opd-counselling-list',['data'=>$result]);
            }

    function getCounsellingList(Request $req){
        $search = $req->RefBy;
        $data = OTModel::where(function($query) use ($search) {
            $query->where('PatientName', 'LIKE', "%{$search}%")
                  ->orWhere('MrdNo', 'LIKE', "%{$search}%")
                  ->orWhere('Phone', 'LIKE', "%{$search}%")
                  ->orWhere('id', 'LIKE', "%{$search}%");
        })
        ->where('Roll', 1)
        ->orderBy('id', 'desc')
        ->limit(10)
        ->get(); // You can return ID + name if needed

     // Add custom full patient name field
     foreach ($data as $item) {
        $item->PatientNameFull = $item->id . ' / ' . $item->MrdNo . ' / ' . $item->PatientName
            . (!empty($item->Phone) ? ' / ' . $item->Phone : '')
            . ' / ' . $item->Address;
    }

    return response()->json($data); // Now PatientNameFull will be available in frontend
      
    }

    function deleteCounsellingRecord(Request $req){
        OTModel::find($req->id)->delete();
        return 1;
    }

    public function saveCounsellingRemark(Request $req){
        $record = ConsultantModel::find($req->id);
         $record->CouncRemark = $req->CouncRemark;
         $record->save();
         return 1;
     }
 
     public function counsellingPtOut(Request $req){
         $record = ConsultantModel::find($req->id);
         $record->ReCornea = 1;
         $record->save();
         return 1;
     }
}