<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\DischargeModel;
use App\Models\DischargetreatmentModel;
use App\Http\Controllers\MasterController;
use App\Http\Controllers\TreatmentController;
use App\Models\ConsultantTreatmentModel;
use App\Models\ConsultantModel;
use App\Http\Controllers\OptoController;
use App\Models\OTModel;
use App\Models\OTNoteOtherModel;
use Session;
class DischargeController extends Controller
{
    function dischargeCard(){
        return view('/ipd/view-dischargecard');
    }

    function ipdMaxNo(){
        $IpdNo = DischargeModel::select()->max('IpdNo');
        if($IpdNo == '' || $IpdNo == 0 || $IpdNo == NULL){
            $IpdNo = 1;
        }
        else{
            $IpdNo = $IpdNo+1;
        }
        return $IpdNo;
    }
    function dischargePatientList(){
        $result = DischargeModel::select()->orderBy('id','desc')->get();
        return $result;
    }
    function addDischargeCard(){
        //$patientList = (new MasterController)->patientList();
        $patientList = $this->dischargePatientList();
        $treatments = (new TreatmentController)->getTreatmentList('Ipd');
        if($treatments == null || !is_array($treatments)){
            $treatments = [];
        }
        $consultantList = (new MasterController)->consultantList();
        $drugList = (new MasterController)->drugList();
        $durationList = (new MasterController)->durationList();
        $IpdNo = $this->ipdMaxNo();
        return view('/ipd/add-dischargecard',['durationList'=>$durationList,'drugList'=>$drugList,'consultantList'=>$consultantList,'IpdNo'=>$IpdNo,'patientList'=>$patientList,'treatments'=>$treatments]);
    }

    function addDischargeCard2($mrdno,$otid){
        //return $otid;
        //$patientList = (new MasterController)->patientList();
       $treatments = (new TreatmentController)->getTreatmentList2('Ipd');
       //return $treatments;
       // $consultantList = (new MasterController)->consultantList();
        $drugList = (new MasterController)->drugList();
        //$IpdNo = $this->ipdMaxNo();
       // $otdetails = $this->otDetails($otid);
        $otdetails = OTModel::select('Remarks','PatientName','Age','Gender','Phone','Address','AdmissionDate','SurgeryDate','Diagnosis','SurgeryName')->where('id',$otid)->first();
        //return $otdetails;
        $durationList = (new MasterController)->durationList();
        $pomspecinstList = (new SpecInstController)->SpecInstList('Instruction');
        return view('/ipd/add-dischargecard2',['treatments'=>$treatments,'pomspecinstList'=>$pomspecinstList,'otdetails'=>$otdetails,'consellingid'=>$otid,'durationList'=>$durationList,'MrdNo'=>$mrdno,'drugList'=>$drugList]);
    }
    function otDetails($id){
        $otdetails = OTNoteOtherModel::select()->where('CounselingId',$id)->first();
        return $otdetails;
    }

    function editDischargeCard($id){
        $patientList = (new MasterController)->patientList();
        $result = DischargeModel::select()->where(['id'=>$id])->first();
        $treatments = (new TreatmentController)->getTreatmentList2('Ipd');
        $consultantList = (new MasterController)->consultantList();
        $drugList = (new MasterController)->drugList();
        $data3 = DischargetreatmentModel::select()->where(['PostId'=>$id])->get();
        return view('/ipd/edit-dischargecard',['drugList'=>$drugList,'data3'=>$data3,'patientList'=>$patientList,'consultantList'=>$consultantList,'treatments'=>$treatments,'data2'=>$result]);
    }
    function viewDischargeCard(Request $req){
        $CurrDate = date('Y-m-d');
        if(!empty($req->FromDate))
            {
                $result =  DB::table('tbl_dischargecards as td')
                ->leftJoin('tbl_patients as tc', 'tc.MrdNo', '=', 'td.MrdNo')
                ->whereBetween('td.DischargeDate', array($req->FromDate, $req->ToDate))
                ->where(['td.Status'=>'1'])
                ->select('td.*','tc.Address')->get();
            }
            else{
                $result =  DB::table('tbl_dischargecards as td')
                ->leftJoin('tbl_patients as tc', 'tc.MrdNo', '=', 'td.MrdNo')
                ->where(['td.Status'=>'1'])
                ->select('td.*','tc.Address')->get();
                
        //$result = DischargeModel::select()->where(['Status'=>'1'])->get();
            }
            //return $result;exit();
        return view('ipd/incdischargecards',['data'=>$result]);
    }

    function saveDischargeCard(Request $req){
            if($req->actionvalue == 'Save'){
            $Discharge = new DischargeModel;
            $DischargetreatmentModel = new DischargetreatmentModel;
            }
            else{
            $Discharge = DischargeModel::find($req->saveid);
            $DischargetreatmentModel = DischargetreatmentModel::firstWhere(['PostId'=>$req->saveid]);
            if(!$DischargetreatmentModel){
                $DischargetreatmentModel = new DischargetreatmentModel;
            }
            }
            $Discharge->IpdNo = $req->IpdNo ? $req->IpdNo : ''; 
            $Discharge->MrdNo = $req->MrdNo ? $req->MrdNo : ''; 
            $Discharge->PatientName = $req->PatientName ? $req->PatientName : ''; 
            if($req->Age && $req->Gender) {
                $Discharge->AgeGender = $req->Age . '/' . $req->Gender;
            } else {
                $Discharge->AgeGender = $req->AgeGender;
            }
            $Discharge->Mobile = $req->Mobile ? $req->Mobile : ''; 
            $Discharge->Address = $req->Address ? $req->Address : '';
            $Discharge->OperationDate = ($req->OperationDate && $req->OperationDate != '') ? $req->OperationDate : null; 
            $Discharge->OperationTime = $req->OperationTime ? $req->OperationTime : '';
            $Discharge->AdmissionDate = ($req->AdmissionDate && $req->AdmissionDate != '') ? $req->AdmissionDate : null; 
            $Discharge->AdmissionTime = $req->AdmissionTime ? $req->AdmissionTime : '';
            $Discharge->DischargeDate = ($req->DischargeDate && $req->DischargeDate != '') ? $req->DischargeDate : null; 
            $Discharge->DischargeTime = $req->DischargeTime ? $req->DischargeTime : '';
            $Discharge->FollowUpDate1 = ($req->FollowUpDate1 && $req->FollowUpDate1 != '') ? $req->FollowUpDate1 : null; 
            $Discharge->FollowUpDate2 = ($req->FollowUpDate2 && $req->FollowUpDate2 != '') ? $req->FollowUpDate2 : null; 
            $Discharge->OtNotes = $req->OtNotes; $Discharge->OptEye = $req->OptEye;
            $Discharge->SurgeryPerformed = $req->SurgeryPerformed; $Discharge->Diagnosis = $req->Diagnosis;
            $Discharge->CondDischarge = $req->CondDischarge; $Discharge->cmbbsrandom = $req->cmbbsrandom;
            $Discharge->txtbsfasting = $req->txtbsfasting; $Discharge->cmbusrandom = $req->cmbusrandom;
            $Discharge->txtusfasting = $req->txtusfasting; $Discharge->cmbhbsag = $req->cmbhbsag;
            $Discharge->txtbp = $req->txtbp; $Discharge->cmbbspostmeal = $req->cmbbspostmeal;
            $Discharge->txtbspostmeal = $req->txtbspostmeal; $Discharge->cmbuspostmeal = $req->cmbuspostmeal;
            $Discharge->txtuspostmeal = $req->txtuspostmeal; $Discharge->cmbecg = $req->cmbecg;
            $Discharge->cmbhiv = $req->cmbhiv; $Discharge->CylToric = $req->CylToric;

            $Discharge->Multifocal = $req->Multifocal; $Discharge->txtfitnessby = $req->txtfitnessby;
            $Discharge->txtother = $req->txtother; $Discharge->IolPower = $req->IolPower;
            $Discharge->Axis = $req->Axis; $Discharge->Constant = $req->Constant;
            $Discharge->IopRe = $req->IopRe; $Discharge->IopLe = $req->IopLe;
            $Discharge->txtremark = $req->txtremark;
            $Discharge->OperationNotes = $req->OperationNotes;
            $Discharge->SlitLamp = $req->SlitLamp;
            $Discharge->IolPowerRe = $req->IolPowerRe;
            $Discharge->IolPowerLe = $req->IolPowerLe;

            $Discharge->TreatmentGiven = $req->TreatmentGiven;
            
            $Discharge->CounselingId = $req->CounselingId ? $req->CounselingId : 0;
            $Discharge->InvLabel1 = $req->InvLabel1;
            $Discharge->InvValue1 = $req->InvValue1;
            $Discharge->InvLabel2 = $req->InvLabel2;
            $Discharge->InvValue2 = $req->InvValue2;
            $Discharge->InvLabel3 = $req->InvLabel3;
            $Discharge->InvValue3 = $req->InvValue3;
            $Discharge->InvLabel4 = $req->InvLabel4;
            $Discharge->InvValue4 = $req->InvValue4;
            $Discharge->InvLabel5 = $req->InvLabel5;
            $Discharge->InvValue5 = $req->InvValue5;
            $Discharge->InvLabel6 = $req->InvLabel6;
            $Discharge->InvValue6 = $req->InvValue6;
            $Discharge->SurgeryInstruction = $req->SurgeryInstruction;
            $Discharge->Language = $req->Language ? $req->Language : 'Marathi';
            
            // New fields from image - assign directly (Laravel will ignore non-existent columns)
            $Discharge->UhidNo = $req->UhidNo ? $req->UhidNo : null;
            $Discharge->WtOnAdm = $req->WtOnAdm ? $req->WtOnAdm : null;
            $Discharge->BirthDate = ($req->BirthDate && $req->BirthDate != '') ? $req->BirthDate : null;
            $Discharge->BirthWt = $req->BirthWt ? $req->BirthWt : null;
            $Discharge->ConsultantName = $req->ConsultantName ? $req->ConsultantName : null;
            $Discharge->ParentOccupation = $req->ParentOccupation ? $req->ParentOccupation : null;
            $Discharge->Ventilation = $req->Ventilation ? $req->Ventilation : null;
            $Discharge->Oxygen = $req->Oxygen ? $req->Oxygen : null;
            $Discharge->HeadCircumference = $req->HeadCircumference ? $req->HeadCircumference : null;
            $Discharge->Height = $req->Height ? $req->Height : null;
            $Discharge->BloodGroup = $req->BloodGroup ? $req->BloodGroup : null;
            $Discharge->WtOnDischarge = $req->WtOnDischarge ? $req->WtOnDischarge : null;
            $Discharge->MotherBloodGroup = $req->MotherBloodGroup ? $req->MotherBloodGroup : null;
            $Discharge->ContactToDoctor = $req->ContactToDoctor ? $req->ContactToDoctor : null;
            $Discharge->ModeOfDelivery = $req->ModeOfDelivery ? $req->ModeOfDelivery : null;
            $Discharge->MaternalRiskFactor = $req->MaternalRiskFactor ? $req->MaternalRiskFactor : null;
            $Discharge->ChiefComplaints = $req->ChiefComplaints ? $req->ChiefComplaints : null;
            $Discharge->BirthHistory = $req->BirthHistory ? $req->BirthHistory : null;
            $Discharge->PastHistory = $req->PastHistory ? $req->PastHistory : null;
            $Discharge->FamilyHistory = $req->FamilyHistory ? $req->FamilyHistory : null;
            $Discharge->ImmunizationHistory = $req->ImmunizationHistory ? $req->ImmunizationHistory : null;
            $Discharge->CourseDuringAdmission = $req->CourseDuringAdmission ? $req->CourseDuringAdmission : null;
            $Discharge->ConditionOnAdm = $req->ConditionOnAdm ? $req->ConditionOnAdm : null;
            $Discharge->ProcedureDone = $req->ProcedureDone ? $req->ProcedureDone : null;
            $Discharge->ReasonOfAdm = $req->ReasonOfAdm ? $req->ReasonOfAdm : null;
            $Discharge->DevHistory = $req->DevHistory ? $req->DevHistory : null;
            $Discharge->InvestigationDone = $req->InvestigationDone ? $req->InvestigationDone : null;
            $Discharge->SpecialAdvice = $req->SpecialAdvice ? $req->SpecialAdvice : null;
            $Discharge->DischargeCardType = $req->DischargeCardType ? $req->DischargeCardType : null;
            $Discharge->DischargeStatus = $req->DischargeStatus ? $req->DischargeStatus : null;
            $Discharge->PlaceOfDelivery = $req->PlaceOfDelivery ? $req->PlaceOfDelivery : null;

            $Discharge->Status = 1;
            $Discharge->CreatedBy = Session::get('UserId') ? Session::get('UserId') : 19;
            $Discharge->ModifiedBy = Session::get('UserId') ? Session::get('UserId') : 19;
            $Discharge->CreatedTime = $req->CreatedTime ? $req->CreatedTime : '';
            if($req->StickerPrint == 1){
                $Discharge->StickerPrint = 1;
                }
                else{
                  $Discharge->StickerPrint = 0;
                }
            try {
                $Discharge->save();
                $PostId = $Discharge->id;
            } catch (\Exception $e) {
                \Log::error('Discharge save error: ' . $e->getMessage());
                return response()->json(['error' => 'Failed to save discharge card: ' . $e->getMessage()], 500);
            }

            $DischargetreatmentModel->PostId = $PostId;
            $DischargetreatmentModel->Eye = $req->OptEye ? $req->OptEye : '';
            $DischargetreatmentModel->MrdNo = $req->MrdNo;
            $DischargetreatmentModel->Treatment = $req->Treatment ? $req->Treatment : '';
            $DischargetreatmentModel->TreatChk1 = $req->TreatChk1 ? $req->TreatChk1 : '0';$DischargetreatmentModel->TreatType1 = $req->TreatType1 ? $req->TreatType1 : '';
            $DischargetreatmentModel->TreatName1 = $req->TreatName1 ? $req->TreatName1 : '';$DischargetreatmentModel->TreatDose1 = $req->TreatDose1 ? $req->TreatDose1 : '';
            $DischargetreatmentModel->TreatFreq1 = $req->TreatFreq1 ? $req->TreatFreq1 : '';$DischargetreatmentModel->TreatDur1 = $req->TreatDur1 ? $req->TreatDur1 : '';
            $DischargetreatmentModel->TreatEye1 = $req->TreatEye1 ? $req->TreatEye1 : '';$DischargetreatmentModel->TreatDate1 = ($req->TreatDate1 && $req->TreatDate1 != '') ? $req->TreatDate1 : null;
     
            $DischargetreatmentModel->TreatChk2 = $req->TreatChk2 ? $req->TreatChk2 : '0';$DischargetreatmentModel->TreatType2 = $req->TreatType2 ? $req->TreatType2 : '';
            $DischargetreatmentModel->TreatName2 = $req->TreatName2 ? $req->TreatName2 : '';$DischargetreatmentModel->TreatDose2 = $req->TreatDose2 ? $req->TreatDose2 : '';
            $DischargetreatmentModel->TreatFreq2 = $req->TreatFreq2 ? $req->TreatFreq2 : '';$DischargetreatmentModel->TreatDur2 = $req->TreatDur2 ? $req->TreatDur2 : '';
            $DischargetreatmentModel->TreatEye2 = $req->TreatEye2 ? $req->TreatEye2 : '';$DischargetreatmentModel->TreatDate2 = ($req->TreatDate2 && $req->TreatDate2 != '') ? $req->TreatDate2 : null;
     
            $DischargetreatmentModel->TreatChk3 = $req->TreatChk3 ? $req->TreatChk3 : '0';$DischargetreatmentModel->TreatType3 = $req->TreatType3 ? $req->TreatType3 : '';
            $DischargetreatmentModel->TreatName3 = $req->TreatName3 ? $req->TreatName3 : '';$DischargetreatmentModel->TreatDose3 = $req->TreatDose3 ? $req->TreatDose3 : '';
            $DischargetreatmentModel->TreatFreq3 = $req->TreatFreq3 ? $req->TreatFreq3 : '';$DischargetreatmentModel->TreatDur3 = $req->TreatDur3 ? $req->TreatDur3 : '';
            $DischargetreatmentModel->TreatEye3 = $req->TreatEye3 ? $req->TreatEye3 : '';$DischargetreatmentModel->TreatDate3 = ($req->TreatDate3 && $req->TreatDate3 != '') ? $req->TreatDate3 : null;
     
            $DischargetreatmentModel->TreatChk4 = $req->TreatChk4 ? $req->TreatChk4 : '0';$DischargetreatmentModel->TreatType4 = $req->TreatType4 ? $req->TreatType4 : '';
            $DischargetreatmentModel->TreatName4 = $req->TreatName4 ? $req->TreatName4 : '';$DischargetreatmentModel->TreatDose4 = $req->TreatDose4 ? $req->TreatDose4 : '';
            $DischargetreatmentModel->TreatFreq4 = $req->TreatFreq4 ? $req->TreatFreq4 : '';$DischargetreatmentModel->TreatDur4 = $req->TreatDur4 ? $req->TreatDur4 : '';
            $DischargetreatmentModel->TreatEye4 = $req->TreatEye4 ? $req->TreatEye4 : '';$DischargetreatmentModel->TreatDate4 = ($req->TreatDate4 && $req->TreatDate4 != '') ? $req->TreatDate4 : null;
     
            $DischargetreatmentModel->TreatChk5 = $req->TreatChk5 ? $req->TreatChk5 : '0';$DischargetreatmentModel->TreatType5 = $req->TreatType5 ? $req->TreatType5 : '';
            $DischargetreatmentModel->TreatName5 = $req->TreatName5 ? $req->TreatName5 : '';$DischargetreatmentModel->TreatDose5 = $req->TreatDose5 ? $req->TreatDose5 : '';
            $DischargetreatmentModel->TreatFreq5 = $req->TreatFreq5 ? $req->TreatFreq5 : '';$DischargetreatmentModel->TreatDur5 = $req->TreatDur5 ? $req->TreatDur5 : '';
            $DischargetreatmentModel->TreatEye5 = $req->TreatEye5 ? $req->TreatEye5 : '';$DischargetreatmentModel->TreatDate5 = ($req->TreatDate5 && $req->TreatDate5 != '') ? $req->TreatDate5 : null;
     
            $DischargetreatmentModel->TreatChk6 = $req->TreatChk6 ? $req->TreatChk6 : '0';$DischargetreatmentModel->TreatType6 = $req->TreatType6 ? $req->TreatType6 : '';
            $DischargetreatmentModel->TreatName6 = $req->TreatName6 ? $req->TreatName6 : '';$DischargetreatmentModel->TreatDose6 = $req->TreatDose6 ? $req->TreatDose6 : '';
            $DischargetreatmentModel->TreatFreq6 = $req->TreatFreq6 ? $req->TreatFreq6 : '';$DischargetreatmentModel->TreatDur6 = $req->TreatDur6 ? $req->TreatDur6 : '';
            $DischargetreatmentModel->TreatEye6 = $req->TreatEye6 ? $req->TreatEye6 : '';$DischargetreatmentModel->TreatDate6 = ($req->TreatDate6 && $req->TreatDate6 != '') ? $req->TreatDate6 : null;
     
            $DischargetreatmentModel->TreatChk7 = $req->TreatChk7 ? $req->TreatChk7 : '0';$DischargetreatmentModel->TreatType7 = $req->TreatType7 ? $req->TreatType7 : '';
            $DischargetreatmentModel->TreatName7 = $req->TreatName7 ? $req->TreatName7 : '';$DischargetreatmentModel->TreatDose7 = $req->TreatDose7 ? $req->TreatDose7 : '';
            $DischargetreatmentModel->TreatFreq7 = $req->TreatFreq7 ? $req->TreatFreq7 : '';$DischargetreatmentModel->TreatDur7 = $req->TreatDur7 ? $req->TreatDur7 : '';
            $DischargetreatmentModel->TreatEye7 = $req->TreatEye7 ? $req->TreatEye7 : '';$DischargetreatmentModel->TreatDate7 = ($req->TreatDate7 && $req->TreatDate7 != '') ? $req->TreatDate7 : null;
     
            $DischargetreatmentModel->TreatChk8 = $req->TreatChk8 ? $req->TreatChk8 : '0';$DischargetreatmentModel->TreatType8 = $req->TreatType8 ? $req->TreatType8 : '';
            $DischargetreatmentModel->TreatName8 = $req->TreatName8 ? $req->TreatName8 : '';$DischargetreatmentModel->TreatDose8 = $req->TreatDose8 ? $req->TreatDose8 : '';
            $DischargetreatmentModel->TreatFreq8 = $req->TreatFreq8 ? $req->TreatFreq8 : '';$DischargetreatmentModel->TreatDur8 = $req->TreatDur8 ? $req->TreatDur8 : '';
            $DischargetreatmentModel->TreatEye8 = $req->TreatEye8 ? $req->TreatEye8 : '';$DischargetreatmentModel->TreatDate8 = ($req->TreatDate8 && $req->TreatDate8 != '') ? $req->TreatDate8 : null;
     
            $DischargetreatmentModel->TreatChk9 = $req->TreatChk9 ? $req->TreatChk9 : '0';$DischargetreatmentModel->TreatType9 = $req->TreatType9 ? $req->TreatType9 : '';
            $DischargetreatmentModel->TreatName9 = $req->TreatName9 ? $req->TreatName9 : '';$DischargetreatmentModel->TreatDose9 = $req->TreatDose9 ? $req->TreatDose9 : '';
            $DischargetreatmentModel->TreatFreq9 = $req->TreatFreq9 ? $req->TreatFreq9 : '';$DischargetreatmentModel->TreatDur9 = $req->TreatDur9 ? $req->TreatDur9 : '';
            $DischargetreatmentModel->TreatEye9 = $req->TreatEye9 ? $req->TreatEye9 : '';$DischargetreatmentModel->TreatDate9 = ($req->TreatDate9 && $req->TreatDate9 != '') ? $req->TreatDate9 : null;
     
            $DischargetreatmentModel->TreatChk10 = $req->TreatChk10 ? $req->TreatChk10 : '0';$DischargetreatmentModel->TreatType10 = $req->TreatType10 ? $req->TreatType10 : '';
            $DischargetreatmentModel->TreatName10 = $req->TreatName10 ? $req->TreatName10 : '';$DischargetreatmentModel->TreatDose10 = $req->TreatDose10 ? $req->TreatDose10 : '';
            $DischargetreatmentModel->TreatFreq10 = $req->TreatFreq10 ? $req->TreatFreq10 : '';$DischargetreatmentModel->TreatDur10 = $req->TreatDur10 ? $req->TreatDur10 : '';
            $DischargetreatmentModel->TreatEye10 = $req->TreatEye10 ? $req->TreatEye10 : '';$DischargetreatmentModel->TreatDate10 = ($req->TreatDate10 && $req->TreatDate10 != '') ? $req->TreatDate10 : null;

            $DischargetreatmentModel->Tapchk1 = $req->Tapchk1 ? $req->Tapchk1 : null;$DischargetreatmentModel->Tapchk2 = $req->Tapchk2 ? $req->Tapchk2 : null;
            $DischargetreatmentModel->Tapchk3 = $req->Tapchk3 ? $req->Tapchk3 : null;$DischargetreatmentModel->Tapchk4 = $req->Tapchk4 ? $req->Tapchk4 : null;
            $DischargetreatmentModel->Tapchk5 = $req->Tapchk5 ? $req->Tapchk5 : null;$DischargetreatmentModel->Tapchk6 = $req->Tapchk6 ? $req->Tapchk6 : null;
            $DischargetreatmentModel->Tapchk7 = $req->Tapchk7 ? $req->Tapchk7 : null;$DischargetreatmentModel->Tapchk8 = $req->Tapchk8 ? $req->Tapchk8 : null;
            $DischargetreatmentModel->Tapchk9 = $req->Tapchk9 ? $req->Tapchk9 : null;$DischargetreatmentModel->Tapchk10 = $req->Tapchk10 ? $req->Tapchk10 : null;
            $DischargetreatmentModel->Tapchk11 = $req->Tapchk11 ? $req->Tapchk11 : null;$DischargetreatmentModel->Tapchk12 = $req->Tapchk12 ? $req->Tapchk12 : null;
            $DischargetreatmentModel->Tapchk13 = $req->Tapchk13 ? $req->Tapchk13 : null;
            $DischargetreatmentModel->Language = $req->Language ? $req->Language : 'Marathi';

            try {
                $DischargetreatmentModel->save();
                //return redirect('/editDischargeCard/'.$PostId);
                return $PostId;
            } catch (\Exception $e) {
                \Log::error('Treatment save error: ' . $e->getMessage());
                return response()->json(['error' => 'Failed to save treatment: ' . $e->getMessage()], 500);
            }
    }

    function deletDischargeCard(Request $req){
        DischargeModel::find($req->id)->delete();
        DischargetreatmentModel::firstWhere(['PostId'=>$req->id])->delete();
        return 1;
    }

    function getPatientTreatment(Request $req){
        $id = $req->id;
        $visitno = ConsultantTreatmentModel::where('MrdNo',$id)->max('VisitNo');
        $result = ConsultantTreatmentModel::where(['VisitNo'=>$visitno,'MrdNo'=>$id])->first();
        $result2 = ConsultantModel::select('Diagnosis')->where(['VisitNo'=>$visitno,'MrdNo'=>$id])->first();
        return json_encode(array('data'=>$result,'Diagnosis'=>$result2->Diagnosis));
    }

    function printDischargeCard($id){
        $result = DischargeModel::find($id);
        //$result2 = DischargetreatmentModel::firstWhere(['PostId'=>$id])->toSql();
        $result2 = DischargetreatmentModel::where('PostId',$id)->get();
        //return $result2;
        $Treat_Name1 = (new OptoController)->convertMarathi($result2[0]->TreatType1,$result2[0]->TreatDose1,
                                            $result2[0]->TreatFreq1,$result2[0]->TreatDur1,$result2[0]->TreatEye1,$result2[0]->Language);
        $Treat_Name2 = (new OptoController)->convertMarathi($result2[0]->TreatType2,$result2[0]->TreatDose2,
                                            $result2[0]->TreatFreq2,$result2[0]->TreatDur2,$result2[0]->TreatEye2,$result2[0]->Language);
        $Treat_Name3 = (new OptoController)->convertMarathi($result2[0]->TreatType3,$result2[0]->TreatDose3,
                                            $result2[0]->TreatFreq3,$result2[0]->TreatDur3,$result2[0]->TreatEye3,$result2[0]->Language);
        $Treat_Name4 = (new OptoController)->convertMarathi($result2[0]->TreatType4,$result2[0]->TreatDose4,
                                            $result2[0]->TreatFreq4,$result2[0]->TreatDur4,$result2[0]->TreatEye4,$result2[0]->Language);
        $Treat_Name5 = (new OptoController)->convertMarathi($result2[0]->TreatType5,$result2[0]->TreatDose5,
                                            $result2[0]->TreatFreq5,$result2[0]->TreatDur5,$result2[0]->TreatEye5,$result2[0]->Language);
        $Treat_Name6 = (new OptoController)->convertMarathi($result2[0]->TreatType6,$result2[0]->TreatDose6,
                                            $result2[0]->TreatFreq6,$result2[0]->TreatDur6,$result2[0]->TreatEye6,$result2[0]->Language);
        $Treat_Name7 = (new OptoController)->convertMarathi($result2[0]->TreatType7,$result2[0]->TreatDose7,
                                            $result2[0]->TreatFreq7,$result2[0]->TreatDur7,$result2[0]->TreatEye7,$result2[0]->Language);
        $Treat_Name8 = (new OptoController)->convertMarathi($result2[0]->TreatType8,$result2[0]->TreatDose8,
                                            $result2[0]->TreatFreq8,$result2[0]->TreatDur8,$result2[0]->TreatEye8,$result2[0]->Language);
        $Treat_Name9 = (new OptoController)->convertMarathi($result2[0]->TreatType9,$result2[0]->TreatDose9,
                                            $result2[0]->TreatFreq9,$result2[0]->TreatDur9,$result2[0]->TreatEye9,$result2[0]->Language);
        $Treat_Name10 = (new OptoController)->convertMarathi($result2[0]->TreatType10,$result2[0]->TreatDose10,
                                            $result2[0]->TreatFreq10,$result2[0]->TreatDur10,$result2[0]->TreatEye10,$result2[0]->Language);
        return view('/ipd/print-discharge-card',['data'=>$result,'data2'=>$result2,'TreatName1'=>$Treat_Name1
        ,'TreatName2'=>$Treat_Name2,'TreatName3'=>$Treat_Name3,'TreatName4'=>$Treat_Name4
        ,'TreatName5'=>$Treat_Name5,'TreatName6'=>$Treat_Name6,'TreatName7'=>$Treat_Name7
        ,'TreatName8'=>$Treat_Name8,'TreatName9'=>$Treat_Name9,'TreatName10'=>$Treat_Name10]);
    }

    function checkDcPatient(Request $req){
        $val = $req->id;
        $seperate = explode(" / ", $val);
        $mrdno = $seperate[0];
        $eye = $req->eye;
        $otid = $req->otid;
        $otdetails = $this->otDetails($otid);
        $result = DischargeModel::where(['MrdNo'=>$mrdno,'IpdNo'=>$otid])->first();
        $cnt = DischargeModel::where(['MrdNo'=>$mrdno,'IpdNo'=>$otid])->count();
        if($cnt > 0){
            return json_encode(array('Status'=>1,'result'=>$result));
        }
        else{
            
            return json_encode(array('Status'=>0,'result'=>$otdetails));
        }
    }

    function checkDcPatient2(Request $req){
        $val = $req->id;
        // Extract discharge card ID from dropdown value format: "id / MrdNo / PatientName / Phone"
        $separate = explode(" / ", $val);
        $dischargeCardId = $separate[0]; // First part is the discharge card ID
        $mrdNo = isset($separate[1]) ? $separate[1] : '';
        
        // First try to find by discharge card ID (since patientList contains discharge cards)
        $result = DischargeModel::where('id', $dischargeCardId)->first();
        
        if($result){
            // Convert model to array to ensure all fields are included
            // Use getAttributes() to get all attributes including null values
            $resultArray = $result->getAttributes();
            // Also add any accessors/relationships if needed
            return json_encode(array('Status'=>1,'result'=>$resultArray), JSON_UNESCAPED_UNICODE);
        }
        else{
            // If not found by ID, try to find by MrdNo (latest discharge card)
            if($mrdNo != ''){
                $result = DischargeModel::where('MrdNo', $mrdNo)->orderBy('id', 'desc')->first();
                if($result){
                    // Convert model to array to ensure all fields are included
                    // Use getAttributes() to get all attributes including null values
                    $resultArray = $result->getAttributes();
                    return json_encode(array('Status'=>1,'result'=>$resultArray), JSON_UNESCAPED_UNICODE);
                }
            }
            // If no discharge card found, get patient details for new entry
            // Use MasterController to get patient details by MrdNo
            if($mrdNo != ''){
                $masterController = new MasterController();
                $patientRequest = new Request(['id' => $mrdNo]);
                $patientDetailsJson = $masterController->getPatientDetails($patientRequest);
                $patientDetails = json_decode($patientDetailsJson, true);
                if($patientDetails){
                    return json_encode(array('Status'=>0,'result'=>$patientDetails));
                }
            }
            // Return empty result if nothing found
            return json_encode(array('Status'=>0,'result'=>null));
        }
    }

    function getPatientTreatment2(Request $req){
        $id = $req->id;
        $result = DischargetreatmentModel::where('PostId',$id)->first();
       
        return json_encode(array('data'=>$result));
    }

    function getFollowupDate(Request $req){
        $val = 'days';
        $ReviewDay = 2;
        $valid_period = "+ ".$ReviewDay." ".$val;
        $dt = strtotime($req->DischargeDate);
        $reviewdt = date("Y-m-d", strtotime("+$valid_period", $dt));
        $dayname = date('D', strtotime($reviewdt));

        $ReviewDay2 = 21;
        $valid_period2 = "+ ".$ReviewDay2." ".$val;
        $dt2 = strtotime($req->DischargeDate);
        $reviewdt2 = date("Y-m-d", strtotime("+$valid_period2", $dt2));
        $dayname2 = date('D', strtotime($reviewdt2));
        return json_encode(array('dayname'=>$dayname,'date'=>$reviewdt,'dayname2'=>$dayname2,'date2'=>$reviewdt2));
    }
}