<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\VisitModel;
use App\Models\OptoModel;
use App\Models\PatientModel;
use App\Models\ConsultantModel;
use App\Models\TreatmentModel;
use App\Models\QueueManagement;
use App\Http\Controllers\MasterController;
use App\Http\Controllers\SpecInstController;
use App\Http\Controllers\TreatmentController;
use App\Models\ConsultantTreatmentModel;
use App\Models\OTModel;
use App\Models\UserMaster;
use App\Models\SpecialityModel;
use Illuminate\Support\Facades\Storage;
use App\Models\TempQueueManagement;
use App\Http\Controllers\ReferedByController;
use App\Models\AppointmentModel;
use App\Models\InvestigationModel2;
use Illuminate\Support\Carbon;
use Session;
class OptoController extends Controller
{
    function optoform($mrdno,$date,$visitno){
        DB::table('tbl_temp_treatments')->where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno,'VisitDate'=>$date])->delete();
        $FolderName = $mrdno;
        $FolderName2 = $date;

        $ptdata = Storage::disk('local')->get($FolderName."/patient_details.txt");
        $queuedata = Storage::disk('local')->get($FolderName."/".$FolderName2."/queue.txt");
        $optodata = Storage::disk('local')->get($FolderName."/".$FolderName2."/opto.txt");
        $consultdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant.txt");
        $consult_treatdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant_treatment.txt");
        $visitlist = Storage::disk('local')->get($FolderName."/visitlist.txt");

        //$PtBal = (new QueueController)->getPatientBal($mrdno);
        //$totalPatient = (new QueueController)->totalPatient();
        //$totalCheckPatient = (new QueueController)->totalCheckPatient();
        //$totalUncheckPatient = $totalPatient - $totalCheckPatient;
        $PtBal = 0;
        $totalPatient = 0;
        $totalCheckPatient = 0;
        $totalUncheckPatient = 0;
        //$refbylist = OptoModel::select('RefBy')->distinct()->get();
        $consultantList = (new MasterController)->consultantList();
        $optometristList = (new MasterController)->optometristList();
        $pomspecinstList = (new SpecInstController)->SpecInstList('PlanOfMang');
        $remarkspecinstList = (new SpecInstController)->SpecInstList('Remark');
        $referedbyList = (new ReferedByController)->referedbyList();
        
        $consult_data = json_decode($consultdata,true);
        $clinicname = $consult_data['items']['ClinicName'];
        if($clinicname == ''){
            $clinicname2 = 'Non Of Above';
        }
        else{
            $clinicname2 = $clinicname;
        }
        $clinicnameList = (new SpecialityController)->getSpecClinicName();
        $clinicdocnameList = (new SpecialityController)->getSpecConsultant2($clinicname2);
        $treatmentlist = (new TreatmentController)->getTreatmentList2('Opd');
       // $youtubelinkList = (new YoutubeController)->getNoteName();
        //$compDays = (new MasterController)->compDays();
        //$files = Storage::disk('local')->files();
        $queue_data = json_decode($queuedata,true);
 $pttype = $queue_data['items']['PatientType'];
 if($pttype == 'New'){
$LastVisitDate = '1st Visit';
$TotalDays = 0;
$Last400VisitDate = 'Today';
$Total400Days = 0;
 }
 else{
        $lastvisitdetails = DB::table('tbl_queue_managements')
    ->select('InDate', DB::raw('DATEDIFF(CURDATE(), DATE(InDate)) as DaysAgo'))
    ->where('MrdNo', $mrdno)
    ->whereDate('InDate', '<', now()->toDateString())
    ->orderByDesc('InDate')
    ->limit(1)
    ->first();
        // 2. Get last 400 payment date
        $last400Date = DB::table('tbl_queue_managements')
            ->where('MrdNo', $mrdno)
            ->where('Amount', 400)
            ->orderByDesc('InDate')
            ->value('InDate');
    
        // 2. Format or label the last 400 date
if ($last400Date) {
    $Last400VisitDate = Carbon::parse($last400Date)->format('d/m/Y');
    $Total400Days = Carbon::parse($last400Date)->diffInDays(Carbon::today());
} else {
    $Last400VisitDate = 'Still Not Paid';
    $Total400Days = '0';
}
$LastVisitDate = date("d/m/Y", strtotime(str_replace('-', '/',$lastvisitdetails->InDate)));
$TotalDays = $lastvisitdetails->DaysAgo;
 }

        return view('opd/editoptoform',['LastVisitDate'=>$LastVisitDate,
            'TotalDays'=>$TotalDays, 'Last400VisitDate'=>$Last400VisitDate,
            'Total400Days'=>$Total400Days,'treatmentlist'=>$treatmentlist,'referedbyList'=>$referedbyList,'remarkspecinstList'=>$remarkspecinstList,'pomspecinstList'=>$pomspecinstList,'clinicdocnameList'=>$clinicdocnameList,'clinicnameList'=>$clinicnameList,'optometristList'=>$optometristList,'consultantList'=>$consultantList,'visitlist'=>$visitlist,'optodata'=>$optodata,'consultdata'=>$consultdata,'consult_treatdata'=>$consult_treatdata
                    ,'MrdNo'=>$mrdno,'VisitDate'=>$date,'VisitNo'=>$visitno,'ptdata'=>$ptdata,'PtBal'=>$PtBal,'queuedata'=>$queuedata
                    ,'totalPatient'=>$totalPatient,'totalCheckPatient'=>$totalCheckPatient,'totalUncheckPatient'=>$totalUncheckPatient]); 
      
        
       
    }

    function saveOpto(Request $req){
       
       
       if($req->action == 'Save'){
        $OptoModel = new OptoModel;
        $ConsultantModel = new ConsultantModel;
        $QueueManagementModel = new QueueManagement;
        $TempQueueManagementModel = new TempQueueManagement;
        
       
        }
        else{
        $OptoModel = OptoModel::find($req->id);
        $ConsultantModel = ConsultantModel::find($req->consid);
        $ConsultantTreatmentModel = ConsultantTreatmentModel::firstWhere(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo]);
        $QueueManagementModel = QueueManagement::firstWhere(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo]);
        $TempQueueManagementModel = TempQueueManagement::firstWhere(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo]);
       
    }
       $OptoModel->MrdNo = $req->MrdNo; $OptoModel->VisitNo = $req->VisitNo;
       $OptoModel->VisitDate = $req->VisitDate; $OptoModel->PatientName = $req->PatientName;
       $OptoModel->Age = $req->Age; $OptoModel->Gender = $req->Gender;
       $OptoModel->Complaint1 = $req->Complaint1; $OptoModel->Complaint2 = $req->Complaint2;
       $OptoModel->Complaint3 = $req->Complaint3; $OptoModel->CompDays1 = $req->CompDays1;
       $OptoModel->CompDays2 = $req->CompDays2;$OptoModel->CompDays3 = $req->CompDays3;
       $OptoModel->CompEyes1 = $req->CompEyes1;$OptoModel->CompEyes2 = $req->CompEyes2;
       $OptoModel->CompEyes3 = $req->CompEyes3;$OptoModel->PastHistory = $req->PastHistory;
       $OptoModel->ChkDm = $req->ChkDm;$OptoModel->ChkHt = $req->ChkHt;
       $OptoModel->ChkCad = $req->ChkCad;$OptoModel->ChkProst = $req->ChkProst;
       $OptoModel->ChkCopd = $req->ChkCopd;$OptoModel->ChkOther = $req->ChkOther;
       $OptoModel->TxtOther = $req->TxtOther;$OptoModel->DmFrom = $req->DmFrom;
       $OptoModel->HtFrom = $req->HtFrom;$OptoModel->CadFrom = $req->CadFrom;
       $OptoModel->ProstFrom = $req->ProstFrom;$OptoModel->CopdFrom = $req->CopdFrom;
       $OptoModel->OtherFrom = $req->OtherFrom;$OptoModel->DmPeriod = $req->DmPeriod;
       $OptoModel->HtPeriod = $req->HtPeriod;$OptoModel->CadPeriod = $req->CadPeriod;
       $OptoModel->ProstPeriod = $req->ProstPeriod;$OptoModel->CopdPeriod = $req->CopdPeriod;
       $OptoModel->OtherPeriod = $req->OtherPeriod;$OptoModel->AllergyHistory = $req->AllergyHistory;
       $OptoModel->MedicalHistory = $req->MedicalHistory;$OptoModel->Addictions = $req->Addictions;
       $OptoModel->VaRe = $req->VaRe;$OptoModel->VaPhRe = $req->VaPhRe;
       $OptoModel->OgRe = $req->OgRe;$OptoModel->VaLe = $req->VaLe;
       $OptoModel->VaPhLe = $req->VaPhLe;$OptoModel->OgLe = $req->OgLe;
       $OptoModel->PgSphRe = $req->PgSphRe;$OptoModel->PgCylRe = $req->PgCylRe;
       $OptoModel->PgAxisRe = $req->PgAxisRe;$OptoModel->PgNearAddRe = $req->PgNearAddRe;
       $OptoModel->PgSphLe = $req->PgSphLe;$OptoModel->PgCylLe = $req->PgCylLe;
       $OptoModel->PgAxisLe = $req->PgAxisLe;$OptoModel->PgNearAddLe = $req->PgNearAddLe;
       $OptoModel->RetHorzRe = $req->RetHorzRe;$OptoModel->RetHorzReAxis = $req->RetHorzReAxis;
       $OptoModel->RetVertRe = $req->RetVertRe;$OptoModel->RetVertReAxis = $req->RetVertReAxis;
       $OptoModel->RetHorzLe = $req->RetHorzLe;$OptoModel->RetHorzLeAxis = $req->RetHorzLeAxis;
       $OptoModel->RetVertLe = $req->RetVertLe;$OptoModel->RetVertLeAxis = $req->RetVertLeAxis;
       $OptoModel->SrSphRe = $req->SrSphRe;$OptoModel->SrCylRe = $req->SrCylRe;
       $OptoModel->SrAxisRe = $req->SrAxisRe;$OptoModel->SrNearAddRe = $req->SrNearAddRe;
       $OptoModel->SrVaGlassRe = $req->SrVaGlassRe;$OptoModel->SrNvRe = $req->SrNvRe;
       $OptoModel->SrSphLe = $req->SrSphLe;$OptoModel->SrCylLe = $req->SrCylLe;
       $OptoModel->SrAxisLe = $req->SrAxisLe;$OptoModel->SrNearAddLe = $req->SrNearAddLe;
       $OptoModel->SrVaGlassLe = $req->SrVaGlassLe;$OptoModel->SrNvLe = $req->SrNvLe;
       $OptoModel->SrPinRe = $req->SrPinRe;$OptoModel->SrPinLe = $req->SrPinLe;
       $OptoModel->GlassType = $req->GlassType;$OptoModel->Uses = $req->Uses;
    //    if($req->GlassType == ''){
    //     $OptoModel->GlassType = '';
    //    }
    //    else{
    //     $OptoModel->GlassType = implode(",",$req->GlassType);
    //    }
    //    if($req->GlassType == ''){
    //     $OptoModel->Uses = '';
    //    }
    //    else{
    //     $OptoModel->Uses = implode(",",$req->Uses);
    //    }
       
       $OptoModel->Remarks = $req->Remarks;$OptoModel->ChkDilate = $req->ChkDilate;
       $OptoModel->SlRe = $req->SlRe;$OptoModel->SlLe = $req->SlLe;
       $OptoModel->PresentIllness = $req->PresentIllness;$OptoModel->OptNotes = $req->OptNotes;

       $OptoModel->RefBy = $req->RefBy;$OptoModel->Category = $req->Category;
       $OptoModel->Dialated = $req->Dialated;$OptoModel->DiaEye = $req->DiaEye;
       $OptoModel->OtPatient = $req->OtPatient;$OptoModel->ColorVision = $req->ColorVision;
       $OptoModel->IopNctRe = $req->IopNctRe;$OptoModel->IopNctLe = $req->IopNctLe;
       $OptoModel->IopAtRe = $req->IopAtRe;$OptoModel->IopAtLe = $req->IopAtLe;

       $OptoModel->RefSphRe = $req->RefSphRe;$OptoModel->RefCylRe = $req->RefCylRe;
       $OptoModel->RefAxisRe = $req->RefAxisRe;$OptoModel->RefK1Re = $req->RefK1Re;
       $OptoModel->RefK1AxisRe = $req->RefK1AxisRe;$OptoModel->RefK2Re = $req->RefK2Re;
       $OptoModel->RefK2AxisRe = $req->RefK2AxisRe;$OptoModel->RefDiffRe = $req->RefDiffRe;
       $OptoModel->RefSphLe = $req->RefSphLe;$OptoModel->RefCylLe = $req->RefCylLe;
       $OptoModel->RefAxisLe = $req->RefAxisLe;$OptoModel->RefK1Le = $req->RefK1Le;
       $OptoModel->RefK1AxisLe = $req->RefK1AxisLe;$OptoModel->RefK2Le = $req->RefK2Le;
       $OptoModel->RefK2AxisLe = $req->RefK2AxisLe;$OptoModel->RefDiffLe = $req->RefDiffLe;

       $OptoModel->VaLeNear = $req->VaLeNear;$OptoModel->VaReNear = $req->VaReNear;
       $OptoModel->ConfirmConsult = $req->ConfirmConsult;
       $OptoModel->PrintGls = $req->PrintGls;
       $OptoModel->CrSrSphRe = $req->CrSrSphRe; $OptoModel->CrSrCylRe = $req->CrSrCylRe;
       $OptoModel->CrSrAxisRe = $req->CrSrAxisRe; $OptoModel->CrSrNearAddRe = $req->CrSrNearAddRe;
       $OptoModel->CrSrVaGlassRe = $req->CrSrVaGlassRe; $OptoModel->CrSrNvRe = $req->CrSrNvRe;
       $OptoModel->CrSrSphLe = $req->CrSrSphLe; $OptoModel->CrSrCylLe = $req->CrSrCylLe;
       $OptoModel->CrSrAxisLe = $req->CrSrAxisLe; $OptoModel->CrSrNearAddLe = $req->CrSrNearAddLe;
       $OptoModel->CrSrVaGlassLe = $req->CrSrVaGlassLe; $OptoModel->CrSrNvLe = $req->CrSrNvLe;
       $OptoModel->PrintCrRef = $req->PrintCrRef;

       $OptoModel->IopReTime = $req->IopReTime;
       $OptoModel->IopLeTime = $req->IopLeTime;
       $OptoModel->ConfirmOpto = $req->ConfirmOpto;
       $OptoModel->IopAtRe2 = $req->IopAtRe2;
       $OptoModel->IopAtLe2 = $req->IopAtLe2;
       $OptoModel->ArSrSphRe = $req->ArSrSphRe;
       $OptoModel->ArSrCylRe = $req->ArSrCylRe;
       $OptoModel->ArSrAxisRe = $req->ArSrAxisRe;
       $OptoModel->ArSrSphLe = $req->ArSrSphLe;
       $OptoModel->ArSrCylLe = $req->ArSrCylLe;
       $OptoModel->ArSrAxisLe = $req->ArSrAxisLe;

       
    //    if($req->ConfirmOpto == ''){
    //         $OptoModel->ConfirmOpto = '';
    //         }
    //         else{
    //          $OptoModel->ConfirmOpto = implode(",",$req->ConfirmOpto);
    //         }
           

       $OptoModel->CreatedBy = Session::get('UserId'); 
       $OptoModel->ModifiedBy = Session::get('UserId'); 
       $OptoModel->save();
       if($req->ConfirmOpto == 0){
        $OptoName = "None";
       }
       else{
        $result = UserMaster::select('Name')->where('id',$req->ConfirmOpto)->first();
        $OptoName = $result->Name;
       }

       if($req->ConfirmConsult == 0){
        $ConsultName = "None";
       }
       else{
        $result2 = UserMaster::select('Name')->where('id',$req->ConfirmConsult)->first();
        $ConsultName = $result2->Name;
       }

        
        QueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])
                        ->update(['OptoId'=>$req->ConfirmOpto,'ConfirmOpto'=>$OptoName,'Consultant'=>$req->ConfirmConsult,'ConsultantName'=>$ConsultName]);
        TempQueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])
                        ->update(['OptoId'=>$req->ConfirmOpto,'ConfirmOpto'=>$OptoName,'Consultant'=>$req->ConfirmConsult,'ConsultantName'=>$ConsultName]);

       if($req->Dialated == 1){
        QueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['Dilated'=>1]);
        TempQueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['Dilated'=>1]);
        ConsultantModel::where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['ConsDialated'=>1,'ConsDiaEye'=>$req->DiaEye]);
       }
       else{
        QueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['Dilated'=>0]);
        TempQueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['Dilated'=>0]); 
        ConsultantModel::where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->update(['ConsDialated'=>0,'ConsDiaEye'=>$req->DiaEye]);
       }

       if($req->action == 'Save'){
       $ConsultantModel->PatientName = $req->PatientName;      
       $ConsultantModel->MrdNo = $req->MrdNo; 
       $ConsultantModel->VisitNo = $req->VisitNo;
       $ConsultantModel->VisitDate = $req->VisitDate;
       $ConsultantModel->CreatedBy = Session::get('UserId'); 
       $ConsultantModel->ModifiedBy = Session::get('UserId'); 
       $ConsultantModel->save();
       }
       else{
        $ConsultantModel->ChkReNormal = $req->ChkReNormal; 
        $ConsultantModel->ChkLeNormal = $req->ChkLeNormal; 
        $ConsultantModel->ReOcMov = $req->ReOcMov;
        $ConsultantModel->LeOcMov = $req->LeOcMov; 
        $ConsultantModel->BeOcMov = $req->TypePatient;
        $ConsultantModel->OrbitalRe = $req->OrbitalRe;
        $ConsultantModel->OrbitalLe = $req->OrbitalLe;
        $ConsultantModel->ReLids = $req->ReLids; 
        $ConsultantModel->LeLids = $req->LeLids; 
        $ConsultantModel->ReConj = $req->ReConj; 
        $ConsultantModel->LeConj = $req->LeConj; 
        $ConsultantModel->ReCornea = $req->ReCornea; 
        $ConsultantModel->LeCornea = $req->LeCornea; 
        $ConsultantModel->ReCorneaRemark = $req->ReCorneaRemark; 
        $ConsultantModel->LeCorneaRemark = $req->LeCorneaRemark; 
        $ConsultantModel->ReAntChamber = $req->ReAntChamber; 
        $ConsultantModel->LeAntChamber = $req->LeAntChamber; 
        $ConsultantModel->ReIris = $req->ReIris; 
        $ConsultantModel->LeIris = $req->LeIris; 
        $ConsultantModel->RePupil = $req->RePupil; 
        $ConsultantModel->LePupil = $req->LePupil; 
        $ConsultantModel->ReIop = $req->ReIop; 
        $ConsultantModel->LeIop = $req->LeIop;
        $ConsultantModel->ReLens = $req->ReLens; 
        $ConsultantModel->LeLens = $req->LeLens;
        $ConsultantModel->ReLens2 = $req->ReLens2; 
        $ConsultantModel->LeLens2 = $req->LeLens2; 
        $ConsultantModel->ReNlp = $req->ReNlp; 
        $ConsultantModel->LeNlp = $req->LeNlp;
        $ConsultantModel->ChkReHazy = $req->ChkReFundus; 
        $ConsultantModel->ChkLeHazy = $req->ChkLeFundus; 
        $ConsultantModel->ReMedia = $req->ReMedia; 
        $ConsultantModel->LeMedia = $req->LeMedia;
        $ConsultantModel->ReOptDisc = $req->ReOptDisc; 
        $ConsultantModel->LeOptDisc = $req->LeOptDisc; 
        $ConsultantModel->ReMacBV = $req->ReMacBV; 
        $ConsultantModel->LeMacBV = $req->LeMacBV; 
        $ConsultantModel->ReMidPerPh = $req->ReMidPerPh; 
        $ConsultantModel->LeMidPerPh = $req->LeMidPerPh; 
        $ConsultantModel->InvStName = $req->InvStName; 
        $ConsultantModel->InvStBy = $req->InvStBy;
        $ConsultantModel->Amount = $req->InvStAmount; 
        $ConsultantModel->CounCellingBy = $req->CounCellingBy; 
        $ConsultantModel->Diagnosis = $req->Diagnosis;
        $ConsultantModel->Advice = $req->Advice; 
        $ConsultantModel->Remark = $req->Remark; 
        $ConsultantModel->CouncRemark = $req->CouncRemark; 
        $ConsultantModel->Checked = $req->Checked;
        $ConsultantModel->ReviewDay = $req->ReviewDay;$ConsultantModel->Review = $req->Review;
        $ConsultantModel->AppointDate = $req->ReviewDate;
 
        $ConsultantModel->AlRe = $req->AlRe; $ConsultantModel->AlLe = $req->AlLe;
        $ConsultantModel->WtwRe = $req->WtwRe; $ConsultantModel->WtwLe = $req->WtwLe;
        $ConsultantModel->PachyRe = $req->PachyRe; $ConsultantModel->PachyLe = $req->PachyLe;
        $ConsultantModel->IOL1 = $req->IOL1; $ConsultantModel->IOL2 = $req->IOL2;
        $ConsultantModel->IOL3 = $req->IOL3; $ConsultantModel->IOL4 = $req->IOL4;
        $ConsultantModel->IOL5 = $req->IOL5; $ConsultantModel->IOL6 = $req->IOL6;
 
        $ConsultantModel->VisionRe = $req->VisionRe; $ConsultantModel->NearRe = $req->NearRe;
        $ConsultantModel->VisionLe = $req->VisionLe; $ConsultantModel->NearLe = $req->NearLe;
        $ConsultantModel->BP = $req->BP; $ConsultantModel->NctRe = $req->NctRe;
        $ConsultantModel->NctLe = $req->NctLe;$ConsultantModel->FundusRemark = $req->FundusRemark;
        $ConsultantModel->ReferTo = $req->ReferTo;
        $ConsultantModel->PrintReLe = $req->PrintReLe;
        $ConsultantModel->DiagnosisRemark = $req->DiagnosisRemark;
        $ConsultantModel->PageBreak = $req->PageBreak;
        $ConsultantModel->FundusDraw = $req->FundusDraw;
        $ConsultantModel->ReBv = $req->ReBv; $ConsultantModel->LeBv = $req->LeBv;
        $ConsultantModel->ConsDialated = $req->ConsDialated;
        $ConsultantModel->ConsDiaEye = $req->ConsDiaEye;
        $ConsultantModel->CostCoated = $req->CostCoated;
        $ConsultantModel->ClinicName = $req->ClinicName;
        $ConsultantModel->SpecDocName = $req->SpecDocName;
        $ConsultantModel->AppTime = $req->AppTime;
        $ConsultantModel->DfFe = 1;
 
        $ConsultantModel->CmbPlanOfMang = $req->CmbPlanOfMang;
        $ConsultantModel->CmbRemark = $req->CmbRemark;
 
        if($req->ClinicName != ''){
         $result = PatientModel::select('PatientName','Phone')->where(['MrdNo'=>$req->MrdNo])->first();
         $result2 = AppointmentModel::where(['MrdNo'=>$req->MrdNo,'AppDate'=>$req->ReviewDate])->count();
         AppointmentModel::where(['MrdNo'=>$req->MrdNo,'AppDate'=>$req->ReviewDate])->delete();
         $Appoint = new AppointmentModel;
         $Appoint->MrdNo = $req->MrdNo; 
         $Appoint->PatientName = $result->PatientName;
         $Appoint->Phone = $result->Phone;
         $Appoint->ReferFor = $req->ClinicName;
         $Appoint->Consultant = $req->SpecDocName;
         $Appoint->AppDate = $req->ReviewDate;
         $Appoint->AppTime = $req->AppTime;
         $Appoint->save();
         
        }
        else{
         AppointmentModel::where(['MrdNo'=>$req->MrdNo,'AppDate'=>$req->ReviewDate])->delete();
        }

        $result = OptoModel::select('ConfirmConsult')->where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->first();
    //    if($result->ConfirmConsult==0){
       $UserType = Session::get('UserType'); 
       if($UserType == 'Consultant') {
        $ConsultId = Session::get('UserId'); 
        $result2 = UserMaster::select('Name')->where('id',$ConsultId)->first();
        $ConsultName = $result2->Name;
        QueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])
        ->update(['Consultant'=>$ConsultId,'ConsultantName'=>$ConsultName]);
        TempQueueManagement::where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])
        ->update(['Consultant'=>$ConsultId,'ConsultantName'=>$ConsultName]);
        OptoModel::where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])
                        ->update(['ConfirmConsult'=>$ConsultId]);
       }
    // }
   
       $ConsultantModel->save();
       }

       $ConsultantTreatmentModel->Treatment = $req->Treatment;
       $ConsultantTreatmentModel->TreatChk1 = $req->TreatChk1;$ConsultantTreatmentModel->TreatType1 = $req->TreatType1;
       $ConsultantTreatmentModel->TreatName1 = $req->TreatName1;$ConsultantTreatmentModel->TreatDose1 = $req->TreatDose1;
       $ConsultantTreatmentModel->TreatFreq1 = $req->TreatFreq1;$ConsultantTreatmentModel->TreatDur1 = $req->TreatDur1;
       $ConsultantTreatmentModel->TreatEye1 = $req->TreatEye1;

       $ConsultantTreatmentModel->TreatChk2 = $req->TreatChk2;$ConsultantTreatmentModel->TreatType2 = $req->TreatType2;
       $ConsultantTreatmentModel->TreatName2 = $req->TreatName2;$ConsultantTreatmentModel->TreatDose2 = $req->TreatDose2;
       $ConsultantTreatmentModel->TreatFreq2 = $req->TreatFreq2;$ConsultantTreatmentModel->TreatDur2 = $req->TreatDur2;
       $ConsultantTreatmentModel->TreatEye2 = $req->TreatEye2;

       $ConsultantTreatmentModel->TreatChk3 = $req->TreatChk3;$ConsultantTreatmentModel->TreatType3 = $req->TreatType3;
       $ConsultantTreatmentModel->TreatName3 = $req->TreatName3;$ConsultantTreatmentModel->TreatDose3 = $req->TreatDose3;
       $ConsultantTreatmentModel->TreatFreq3 = $req->TreatFreq3;$ConsultantTreatmentModel->TreatDur3 = $req->TreatDur3;
       $ConsultantTreatmentModel->TreatEye3 = $req->TreatEye3;

       $ConsultantTreatmentModel->TreatChk4 = $req->TreatChk4;$ConsultantTreatmentModel->TreatType4 = $req->TreatType4;
       $ConsultantTreatmentModel->TreatName4 = $req->TreatName4;$ConsultantTreatmentModel->TreatDose4 = $req->TreatDose4;
       $ConsultantTreatmentModel->TreatFreq4 = $req->TreatFreq4;$ConsultantTreatmentModel->TreatDur4 = $req->TreatDur4;
       $ConsultantTreatmentModel->TreatEye4 = $req->TreatEye4;

       $ConsultantTreatmentModel->TreatChk5 = $req->TreatChk5;$ConsultantTreatmentModel->TreatType5 = $req->TreatType5;
       $ConsultantTreatmentModel->TreatName5 = $req->TreatName5;$ConsultantTreatmentModel->TreatDose5 = $req->TreatDose5;
       $ConsultantTreatmentModel->TreatFreq5 = $req->TreatFreq5;$ConsultantTreatmentModel->TreatDur5 = $req->TreatDur5;
       $ConsultantTreatmentModel->TreatEye5 = $req->TreatEye5;

       $ConsultantTreatmentModel->TreatChk6 = $req->TreatChk6;$ConsultantTreatmentModel->TreatType6 = $req->TreatType6;
       $ConsultantTreatmentModel->TreatName6 = $req->TreatName6;$ConsultantTreatmentModel->TreatDose6 = $req->TreatDose6;
       $ConsultantTreatmentModel->TreatFreq6 = $req->TreatFreq6;$ConsultantTreatmentModel->TreatDur6 = $req->TreatDur6;
       $ConsultantTreatmentModel->TreatEye6 = $req->TreatEye6;

       $ConsultantTreatmentModel->TreatChk7 = $req->TreatChk7;$ConsultantTreatmentModel->TreatType7 = $req->TreatType7;
       $ConsultantTreatmentModel->TreatName7 = $req->TreatName7;$ConsultantTreatmentModel->TreatDose7 = $req->TreatDose7;
       $ConsultantTreatmentModel->TreatFreq7 = $req->TreatFreq7;$ConsultantTreatmentModel->TreatDur7 = $req->TreatDur7;
       $ConsultantTreatmentModel->TreatEye7 = $req->TreatEye7;

       $ConsultantTreatmentModel->TreatChk8 = $req->TreatChk8;$ConsultantTreatmentModel->TreatType8 = $req->TreatType8;
       $ConsultantTreatmentModel->TreatName8 = $req->TreatName8;$ConsultantTreatmentModel->TreatDose8 = $req->TreatDose8;
       $ConsultantTreatmentModel->TreatFreq8 = $req->TreatFreq8;$ConsultantTreatmentModel->TreatDur8 = $req->TreatDur8;
       $ConsultantTreatmentModel->TreatEye8 = $req->TreatEye8;

       $ConsultantTreatmentModel->TreatChk9 = $req->TreatChk9;$ConsultantTreatmentModel->TreatType9 = $req->TreatType9;
       $ConsultantTreatmentModel->TreatName9 = $req->TreatName9;$ConsultantTreatmentModel->TreatDose9 = $req->TreatDose9;
       $ConsultantTreatmentModel->TreatFreq9 = $req->TreatFreq9;$ConsultantTreatmentModel->TreatDur9 = $req->TreatDur9;
       $ConsultantTreatmentModel->TreatEye9 = $req->TreatEye9;

       $ConsultantTreatmentModel->TreatChk10 = $req->TreatChk10;$ConsultantTreatmentModel->TreatType10 = $req->TreatType10;
       $ConsultantTreatmentModel->TreatName10 = $req->TreatName10;$ConsultantTreatmentModel->TreatDose10 = $req->TreatDose10;
       $ConsultantTreatmentModel->TreatFreq10 = $req->TreatFreq10;$ConsultantTreatmentModel->TreatDur10 = $req->TreatDur10;
       $ConsultantTreatmentModel->TreatEye10 = $req->TreatEye10;
       $ConsultantTreatmentModel->Language = $req->Language;
       $ConsultantTreatmentModel->save();

       $TempQueueManagementModel->InvStName = $req->InvStName; 
       $TempQueueManagementModel->save();

       $QueueManagementModel->InvStName = $req->InvStName; 
       $QueueManagementModel->save();


       $InvestigationModel2 = InvestigationModel2::firstWhere([
        'MrdNo' => $req->MrdNo,
        'VisitDate' => $req->VisitDate
    ]);
    
    if ($InvestigationModel2) {
        if ($req->InvStName != '' && $req->InvStAmount != '') {
            // Update existing record
            $InvestigationModel2->ModifiedBy = Session::get('UserId');
            $InvestigationModel2->ModifiedDate = date('Y-m-d');
            $InvestigationModel2->MrdNo = $req->MrdNo;
            $InvestigationModel2->PatientName = $req->PatientName;
            $InvestigationModel2->Phone = $req->Phone;
            $InvestigationModel2->VisitDate = $req->VisitDate;
            $InvestigationModel2->VisitNo = $req->VisitNo;
            $InvestigationModel2->InvStName = $req->InvStName;
            $InvestigationModel2->Amount = $req->InvStAmount;
            $InvestigationModel2->save();
        } else {
            // Delete record if both fields are empty
            $InvestigationModel2->delete();
        }
    } else {
        if ($req->InvStName != '' && $req->InvStAmount != '') {
            // Insert new record
            $InvestigationModel2 = new InvestigationModel2();
            $InvestigationModel2->CreatedBy = Session::get('UserId');
            $InvestigationModel2->CreatedDate = date('Y-m-d');
            $InvestigationModel2->ModifiedBy = 0;
    
            // Common fields
            $InvestigationModel2->MrdNo = $req->MrdNo;
            $InvestigationModel2->PatientName = $req->PatientName;
            $InvestigationModel2->Phone = $req->Phone;
            $InvestigationModel2->VisitDate = $req->VisitDate;
            $InvestigationModel2->VisitNo = $req->VisitNo;
            $InvestigationModel2->InvStName = $req->InvStName;
            $InvestigationModel2->Amount = $req->InvStAmount;
            $InvestigationModel2->InvCheckout = 0;
            $InvestigationModel2->InvMoneyReceived = 0;
            $InvestigationModel2->save();
        }
    }

       
       $FolderName = $req->MrdNo;
       $FolderName2 = $req->VisitDate;
       $opto = "opto.txt";
       $consultant = "consultant.txt";
       $consultant_treatment = "consultant_treatment.txt";

        $opto_result = OptoModel::select()->where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->first();    
        $opto_data = json_encode(array('items' => $opto_result));

        $consult_result = ConsultantModel::select()->where(['id'=>$req->consid])->first();
        $consult_data = json_encode(array('items' => $consult_result));
       
        $consulttreat_result = ConsultantTreatmentModel::select()->where(['MrdNo'=>$req->MrdNo,'VisitDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->first();
        $consulttreat_data = json_encode(array('items' => $consulttreat_result));

        $queue_result = QueueManagement::select()->where(['MrdNo'=>$req->MrdNo,'InDate'=>$req->VisitDate,'VisitNo'=>$req->VisitNo])->first();
        $queue_data = json_encode(array('items' => $queue_result));

        Storage::disk('local')->put($FolderName."/".$FolderName2."/queue.txt", $queue_data);
        Storage::disk('local')->put($FolderName."/".$FolderName2."/".$opto, $opto_data);
        Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant, $consult_data);
        Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant_treatment, $consulttreat_data);
       
        DB::table('tbl_temp_treatments')->where(['MrdNo'=>$req->MrdNo,'VisitNo'=>$req->VisitNo,'VisitDate'=>$req->VisitDate])->delete();
        return json_encode(array('mrdno'=>$req->MrdNo,'visitno'=>$req->VisitNo,'visitdate'=>$req->VisitDate));
     
       //return redirect('/optoform/'.$req->MrdNo.'/'.$req->VisitDate.'/'.$req->VisitNo.'?page=tab1');
    }
    
    function opdDetailPrint($mrdno,$visitno,$visitdate){
        // $ptsummary =  DB::table('tbl_queue_managements as tq')
        // ->join('tbl_patients as tp', 'tp.MrdNo', '=', 'tq.MrdNo')
        // ->join('tbl_optometrist as topt',function($join){
        //     $join->on("topt.MrdNo","=","tq.MrdNo")
        //         ->on("topt.VisitNo","=","tq.VisitNo");
        // })
        // ->join('tbl_consultants as tc',function($join){
        //     $join->on("tc.MrdNo","=","tq.MrdNo")
        //         ->on("tc.VisitNo","=","tq.VisitNo");
        // })
        // ->where(['topt.MrdNo'=>$mrdno,'topt.VisitNo'=>$visitno])
        // ->select('tq.*','tp.City','tp.Age','tp.Gender','tp.Phone','tp.Address','topt.*','tc.*')
        // ->groupBy('tq.InDate')
        // ->get();

        // $ptsummary =  DB::table('tbl_optometrist as topt')
        //             ->join('tbl_patients as tp', 'tp.MrdNo', '=', 'topt.MrdNo')
        //             ->leftjoin('tbl_users as tu', 'tu.id', '=', 'topt.ConfirmConsult')
        //             ->join('tbl_consultants as tc',function($join){
        //                     $join->on("topt.MrdNo","=","tc.MrdNo")
        //                     ->on("topt.VisitDate","=","tc.VisitDate")
        //                         ->on("topt.VisitNo","=","tc.VisitNo");
        //                 })
        //             ->join('tbl_consultant_treatments as tct',function($join){
        //                     $join->on("topt.MrdNo","=","tct.MrdNo")
        //                     ->on("topt.VisitDate","=","tct.VisitDate")
        //                         ->on("topt.VisitNo","=","tct.VisitNo");
        //                 })
        //             ->where(['topt.MrdNo'=>$mrdno,'topt.VisitNo'=>$visitno,'topt.VisitDate'=>$visitdate])
        //  ->select('tu.Name As DocName','tp.City','tp.Age as ptage','tp.Gender as ptgender','tp.Phone','tp.Address','tp.PatientName as ptPatientName','topt.PrintGls as Print_Gls','topt.*','tc.*','tct.*')
        //  ->get();
        //return $ptsummary;exit();
        //$Treat_Name1 = $this->convertMarathi('TAB',1,'O.D.','X 5 DAYS');
        // $TreatType1 = $ptsummary[0]->TreatType1;
        // $TreatDose1 = $ptsummary[0]->TreatDose1;
        // $TreatFreq1 = $ptsummary[0]->TreatFreq1;
        // $TreatDur1 = $ptsummary[0]->TreatDur1;
        $FolderName = $mrdno;
        $FolderName2 = $visitdate;
        $ptdata = Storage::disk('local')->get($FolderName."/patient_details.txt");
        $queuedata = Storage::disk('local')->get($FolderName."/".$FolderName2."/queue.txt");
        $optodata = Storage::disk('local')->get($FolderName."/".$FolderName2."/opto.txt");
        $consultdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant.txt");
        $consult_treatdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant_treatment.txt");
        
       
        $pt_data = json_decode($ptdata,true);
        $queue_data = json_decode($queuedata,true);
        $opto_data = json_decode($optodata,true);
        $consult_data = json_decode($consultdata,true);
        $consult_treat_data = json_decode($consult_treatdata,true);

        $ConfirmConsult = $opto_data['items']['ConfirmConsult'];
       if ($ConfirmConsult === '' || $ConfirmConsult === 0) {
    $DocName = "";
}
        else{
        $result = DB::table('tbl_users')->select('Name')->where('id',$ConfirmConsult)->first();
        $DocName = $result->Name;
        }
        
        $Treat_Name1 = $this->convertMarathi($consult_treat_data['items']['TreatType1'],$consult_treat_data['items']['TreatDose1'],
                                            $consult_treat_data['items']['TreatFreq1'],$consult_treat_data['items']['TreatDur1'],$consult_treat_data['items']['TreatEye1'],$consult_treat_data['items']['Language']);
        $Treat_Name2 = $this->convertMarathi($consult_treat_data['items']['TreatType2'],$consult_treat_data['items']['TreatDose2'],
                                            $consult_treat_data['items']['TreatFreq2'],$consult_treat_data['items']['TreatDur2'],$consult_treat_data['items']['TreatEye2'],$consult_treat_data['items']['Language']);
        $Treat_Name3 = $this->convertMarathi($consult_treat_data['items']['TreatType3'],$consult_treat_data['items']['TreatDose3'],
                                            $consult_treat_data['items']['TreatFreq3'],$consult_treat_data['items']['TreatDur3'],$consult_treat_data['items']['TreatEye3'],$consult_treat_data['items']['Language']);
        $Treat_Name4 = $this->convertMarathi($consult_treat_data['items']['TreatType4'],$consult_treat_data['items']['TreatDose4'],
                                            $consult_treat_data['items']['TreatFreq4'],$consult_treat_data['items']['TreatDur4'],$consult_treat_data['items']['TreatEye4'],$consult_treat_data['items']['Language']);
        $Treat_Name5 = $this->convertMarathi($consult_treat_data['items']['TreatType5'],$consult_treat_data['items']['TreatDose5'],
                                            $consult_treat_data['items']['TreatFreq5'],$consult_treat_data['items']['TreatDur5'],$consult_treat_data['items']['TreatEye5'],$consult_treat_data['items']['Language']);
        $Treat_Name6 = $this->convertMarathi($consult_treat_data['items']['TreatType6'],$consult_treat_data['items']['TreatDose6'],
                                            $consult_treat_data['items']['TreatFreq6'],$consult_treat_data['items']['TreatDur6'],$consult_treat_data['items']['TreatEye6'],$consult_treat_data['items']['Language']);
        $Treat_Name7 = $this->convertMarathi($consult_treat_data['items']['TreatType7'],$consult_treat_data['items']['TreatDose7'],
                                            $consult_treat_data['items']['TreatFreq7'],$consult_treat_data['items']['TreatDur7'],$consult_treat_data['items']['TreatEye7'],$consult_treat_data['items']['Language']);
        $Treat_Name8 = $this->convertMarathi($consult_treat_data['items']['TreatType8'],$consult_treat_data['items']['TreatDose8'],
                                            $consult_treat_data['items']['TreatFreq8'],$consult_treat_data['items']['TreatDur8'],$consult_treat_data['items']['TreatEye8'],$consult_treat_data['items']['Language']);
        $Treat_Name9 = $this->convertMarathi($consult_treat_data['items']['TreatType9'],$consult_treat_data['items']['TreatDose9'],
                                            $consult_treat_data['items']['TreatFreq9'],$consult_treat_data['items']['TreatDur9'],$consult_treat_data['items']['TreatEye9'],$consult_treat_data['items']['Language']);
        $Treat_Name10 = $this->convertMarathi($consult_treat_data['items']['TreatType10'],$consult_treat_data['items']['TreatDose10'],
                                            $consult_treat_data['items']['TreatFreq10'],$consult_treat_data['items']['TreatDur10'],$consult_treat_data['items']['TreatEye10'],$consult_treat_data['items']['Language']);
                                                                         
                                                                            
        return view('/opd/opd-details-print',['DocName'=>$DocName,
        'queue_data'=>$queue_data,'pt_data'=>$pt_data,'opto_data'=>$opto_data,'consult_data'=>$consult_data,
        'consult_treat_data'=>$consult_treat_data,'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 convertMarathi($Type,$Dose,$Freq,$Dur,$Eye,$Lang)
    {
       
        $result = DB::table('tbl_codepresc')->select()->where('Code',$Dose)->get();
        $cnt = $result->count();
        if($cnt > 0){
            if($Lang == 'Marathi'){
            $MarDose = $result[0]->Marathi;
            }
            else if($Lang == 'Hindi'){
                $MarDose = $result[0]->Hindi;   
            }
        }
        else{
            $MarDose = " ";
        }

        $result2 = DB::table('tbl_codepresc')->select()->where('Code',$Type)->get();
        $cnt2 = $result2->count();
        if($cnt2 > 0){
            if($Lang == 'Marathi'){
                $MarType = $result2[0]->Marathi;
                }
                else if($Lang == 'Hindi'){
                    $MarType = $result2[0]->Hindi;
                }
        
        }
        else{
            $MarType = " ";
        }
       

        $result3 = DB::table('tbl_codepresc')->select()->where('Code',$Freq)->get();
        $cnt3 = $result3->count();

        if($cnt3 > 0){
            if($Lang == 'Marathi'){
                $MarFreq = $result3[0]->Marathi;
                }
                else if($Lang == 'Hindi'){
                    $MarFreq = $result3[0]->Hindi;
                }
        
        }
        else{
            $MarFreq = " ";
        }
     

        $result4 = DB::table('tbl_codepresc')->select()->where('Code',$Dur)->get();
        $cnt4 = $result4->count();
        if($cnt4 > 0){
            if($Lang == 'Marathi'){
                $MarDur = $result4[0]->Marathi;
                }
                else if($Lang == 'Hindi'){
                    $MarDur = $result4[0]->Hindi;
                }
        
        }
        else{
            $MarDur = " ";
        }
        
        $result5 = DB::table('tbl_codepresc')->select()->where('Code',$Eye)->get();
        $cnt5 = $result5->count();
        if($cnt5 > 0){
            if($Lang == 'Marathi'){
                $MarEye = $result5[0]->Marathi;
                }
                else if($Lang == 'Hindi'){
                    $MarEye = $result5[0]->Hindi;
                }
        
        }
        else{
            $MarEye = " ";
        }
        $TranslateMarathi = $MarDose." ".$MarType." ".$MarFreq." ".$MarDur." ".$MarEye;
        return $TranslateMarathi;
    }
    
    function patientCheck(Request $req){
        $mrdno = $req->mrdno;
        $visitno = $req->visitno;
        $OutTime = date('H:i:s');
        ConsultantModel::where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno])->update(['Checked'=>1]);
        //VisitModel::where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno])->update(['Checked'=>1]);
        OptoModel::where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno])->update(['Checked'=>1]);
        QueueManagement::where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno])->update(['Checked'=>1,'OutTime'=>$OutTime,'chkstatus'=>1]);
        TempQueueManagement::where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno])->update(['Checked'=>1,'OutTime'=>$OutTime,'chkstatus'=>1]);
        return 1;
    }

    function getMaxVisitNo(Request $req){
        $mrdno = $req->mrdno;
        $visitdate = $req->visitdate;
        $qid = $req->qid;
        $checkstatus = QueueManagement::select('Checked','VisitNo','InDate','PatientName')->where('id',$qid)->first();
        $PatientName = $checkstatus->PatientName;
        $check_status = $checkstatus->Checked;
        $visit_no = $checkstatus->VisitNo;
        //return $visit_no;
        if($visit_no == 0){
            // $result = OptoModel::select('VisitNo')->where(['MrdNo'=>$mrdno,'VisitDate'=>$visitdate])->get();
            // $ctn22 = $result->count();
            // if($ctn22 > 0){
            //     $VisitNo =  $result[0]->VisitNo;
            // //QueueManagement::where(['MrdNo'=>$mrdno,'InDate'=>$visitdate])->update(['VisitNo'=>$VisitNo]);
            // QueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
            // }
            // else{
            // $maxid = OptoModel::select()->where(['MrdNo'=>$mrdno])->max('VisitNo');
            // $VisitNo = $maxid+1;
            // QueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
            // }
            $maxid = OptoModel::select()->where(['MrdNo'=>$mrdno])->max('VisitNo');
            $VisitNo = $maxid+1;
            QueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
            TempQueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
        }
        else if($visit_no != 0){
            $VisitNo = $checkstatus->VisitNo;
        }
        else{
        $result = OptoModel::select()->where(['MrdNo'=>$mrdno,'Checked'=>0,'VisitDate'=>$visitdate])->get();
        $cnt = $result->count();
        if($cnt > 0){
            $VisitNo = $result[0]->VisitNo;
        }
        else{
            $maxid = OptoModel::select()->where(['MrdNo'=>$mrdno])->max('VisitNo');
            $VisitNo = $maxid+1;
            QueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
            TempQueueManagement::where(['id'=>$qid])->update(['VisitNo'=>$VisitNo]);
        }
    }

    
            // $CurrDate = $visitdate;
            // $FolderName = $mrdno;
            // $FolderName2 = $CurrDate;
            // $opto = "opto.txt";
            // $consultant = "consultant.txt";
            // $consultant_treatment = "consultant_treatment.txt";
            // if(Storage::disk('local')->exists($FolderName."/".$FolderName2)) {
            //     //echo "exit";
            // // if(Storage::disk('local')->exists($FolderName."/".$FolderName2."/opto.txt")){}
            // // else{
            // // $opto_result = OptoModel::select()->where(['MrdNo'=>$mrdno,'VisitDate'=>$visitdate])->first();    
            // // $opto_data = json_encode(array('items' => $opto_result));
            // // Storage::disk('local')->put($FolderName."/".$FolderName2."/".$opto, $opto_data);
            // // }

            // // if(Storage::disk('local')->exists($FolderName."/".$FolderName2."/consultant.txt")){}
            // // else{
            // //     $consult_result = ConsultantModel::select()->where(['MrdNo'=>$mrdno,'VisitDate'=>$visitdate])->first();
            // //     $consult_data = json_encode(array('items' => $consult_result));
            // //     Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant, $consult_data);
            // // }

            // // if(Storage::disk('local')->exists($FolderName."/".$FolderName2."/consultant_treatment.txt")){}
            // // else{
            // //     $consulttreat_result = ConsultantTreatmentModel::select()->where(['MrdNo'=>$mrdno,'VisitDate'=>$visitdate])->first();
            // // $consulttreat_data = json_encode(array('items' => $consulttreat_result));
            // // Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant_treatment, $consulttreat_data);
            // // }
            
            // // if(Storage::disk('local')->exists($FolderName."/".$FolderName2."/queue.txt")){}
            // // else{
            // //     $queue_result = QueueManagement::select()->where(['MrdNo'=>$mrdno,'InDate'=>$visitdate])->first();
            // //     $queue_data = json_encode(array('items' => $queue_result));
            // //     Storage::disk('local')->put($FolderName."/".$FolderName2."/queue.txt", $queue_data);
            // // }
            
            // // $visitList = (new MasterController)->getPatientVisit($mrdno);
            // // $visitdate_data = json_encode(array('items' => $visitList));
            // // Storage::disk('local')->put($FolderName."/visitlist.txt", $visitdate_data);
            // }
            // else{
            
            // $Visit = new VisitModel;
            // $Visit->MrdNo = $mrdno;
            // $Visit->PatientName = $PatientName;
            // $Visit->VisitDate = $visitdate;
            // $Visit->VisitNo = $VisitNo;
            // $Visit->save();
            // $VisitPostId = $Visit->id;

            // $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;

            // $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->save();
            // $ConsultantPostId = $ConsultantModel->id;

            // $ConsultantTreatmentModel = new ConsultantTreatmentModel;
            // $ConsultantTreatmentModel->MrdNo = $mrdno; $ConsultantTreatmentModel->VisitNo = $VisitNo;
            // $ConsultantTreatmentModel->VisitDate = $visitdate;
            // $ConsultantTreatmentModel->save();
            // $ConsultantTreatmentPostId = $ConsultantTreatmentModel->id;
            
            // $opto_result = OptoModel::select()->where(['id'=>$OptoPostId])->first();    
            // $opto_data = json_encode(array('items' => $opto_result));

            // $consult_result = ConsultantModel::select()->where(['id'=>$ConsultantPostId])->first();
            // $consult_data = json_encode(array('items' => $consult_result));
            
            // $consulttreat_result = ConsultantTreatmentModel::select()->where(['id'=>$ConsultantTreatmentPostId])->first();
            // $consulttreat_data = json_encode(array('items' => $consulttreat_result));

            // $queue_result = QueueManagement::select()->where(['MrdNo'=>$mrdno,'InDate'=>$visitdate])->first();
            // $queue_data = json_encode(array('items' => $queue_result));
            // Storage::disk('local')->put($FolderName."/".$FolderName2."/queue.txt", $queue_data);
            // Storage::disk('local')->put($FolderName."/".$FolderName2."/".$opto, $opto_data);
            // Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant, $consult_data);
            // Storage::disk('local')->put($FolderName."/".$FolderName2."/".$consultant_treatment, $consulttreat_data);

            // $visitList = (new MasterController)->getPatientVisit($mrdno);
            // $visitdate_data = json_encode(array('items' => $visitList));
            // Storage::disk('local')->put($FolderName."/visitlist.txt", $visitdate_data);
            // }

            // $patient_result = PatientModel::select()->where(['MrdNo'=>$mrdno])->first();
            // $patient_data = json_encode(array('items' => $patient_result));
            // Storage::disk('local')->put($FolderName."/patient_details.txt", $patient_data);
            
            //return $visitList;
            
        return $VisitNo;
    }
    function getVisitNoDate(Request $req){
        $val = $req->val;
        $seperate = explode(" / ", $val);
        $VisitDate = $seperate[0];
        $VisionNo = $seperate[1];
        return json_encode(array('VisitDate'=>$VisitDate,'VisionNo'=>$VisionNo));
    }

    function copyRecord(Request $req){
        $req->session()->put('MrdNo',$req->MrdNo);
        $req->session()->put('VisitNo',$req->VisitNo);
        $req->session()->put('VisitDate',$req->VisitDate);
    }
    function pasteRecord(Request $req){
        $CopyMrdno = Session::get('MrdNo');
        $CopyVisitNo = Session::get('VisitNo');
        $CopyVisitDate = Session::get('VisitDate');

        $result = OptoModel::select()->where(['MrdNo'=>$CopyMrdno,'VisitNo'=>$CopyVisitNo,'VisitDate'=>$CopyVisitDate])->first();
        //$newTask = $result->replicate();
        $result3 = ConsultantModel::select()->where(['MrdNo'=>$CopyMrdno,'VisitNo'=>$CopyVisitNo,'VisitDate'=>$CopyVisitDate])->first();
        $result2 = ConsultantTreatmentModel::select()->where(['MrdNo'=>$CopyMrdno,'VisitNo'=>$CopyVisitNo,'VisitDate'=>$CopyVisitDate])->first();
        session()->pull('MrdNo2');
        session()->pull('VisitNo2');
        session()->pull('VisitDate2');
        return json_encode(array('result'=>$result,'result2'=>$result2,'result3'=>$result3));
     
       
    }

    function opdShortDetailPrint($mrdno,$visitno,$visitdate){
        // $ptsummary =  DB::table('tbl_optometrist as topt')
        //             ->join('tbl_patients as tp', 'tp.MrdNo', '=', 'topt.MrdNo')
        //             ->leftjoin('tbl_users as tu', 'tu.id', '=', 'topt.ConfirmConsult')
                    
        //             ->join('tbl_consultants as tc',function($join){
        //                     $join->on("topt.MrdNo","=","tc.MrdNo")
        //                     ->on("topt.VisitDate","=","tc.VisitDate")
        //                         ->on("topt.VisitNo","=","tc.VisitNo");
        //                 })
        //             ->join('tbl_consultant_treatments as tct',function($join){
        //                     $join->on("topt.MrdNo","=","tct.MrdNo")
        //                     ->on("topt.VisitDate","=","tct.VisitDate")
        //                         ->on("topt.VisitNo","=","tct.VisitNo");
        //                 })
        //             ->where(['topt.MrdNo'=>$mrdno,'topt.VisitNo'=>$visitno,'topt.VisitDate'=>$visitdate])
        //  ->select('tu.Name As DocName','tp.City','tp.Age as ptage','tp.Gender as ptgender','tp.Phone','tp.Address','tp.PatientName as ptPatientName','topt.PrintGls as Print_Gls','topt.*','tc.*','tct.*')
        //  ->get();
        $FolderName = $mrdno;
        $FolderName2 = $visitdate;
        $ptdata = Storage::disk('local')->get($FolderName."/patient_details.txt");
        $queuedata = Storage::disk('local')->get($FolderName."/".$FolderName2."/queue.txt");
        $optodata = Storage::disk('local')->get($FolderName."/".$FolderName2."/opto.txt");
        $consultdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant.txt");
        $consult_treatdata = Storage::disk('local')->get($FolderName."/".$FolderName2."/consultant_treatment.txt");
        
       
        $pt_data = json_decode($ptdata,true);
        $queue_data = json_decode($queuedata,true);
        $opto_data = json_decode($optodata,true);
        $consult_data = json_decode($consultdata,true);
        $consult_treat_data = json_decode($consult_treatdata,true);

        $ConfirmConsult = $opto_data['items']['ConfirmConsult'];
        if($ConfirmConsult == ''){
            $DocName = "";
        }
        else{
        $result = DB::table('tbl_users')->select('Name')->where('id',$ConfirmConsult)->first();
        $DocName = $result->Name;
        }

        $Treat_Name1 = $this->convertMarathi($consult_treat_data['items']['TreatType1'],$consult_treat_data['items']['TreatDose1'],
        $consult_treat_data['items']['TreatFreq1'],$consult_treat_data['items']['TreatDur1'],$consult_treat_data['items']['TreatEye1'],$consult_treat_data['items']['Language']);
        $Treat_Name2 = $this->convertMarathi($consult_treat_data['items']['TreatType2'],$consult_treat_data['items']['TreatDose2'],
            $consult_treat_data['items']['TreatFreq2'],$consult_treat_data['items']['TreatDur2'],$consult_treat_data['items']['TreatEye2'],$consult_treat_data['items']['Language']);
        $Treat_Name3 = $this->convertMarathi($consult_treat_data['items']['TreatType3'],$consult_treat_data['items']['TreatDose3'],
            $consult_treat_data['items']['TreatFreq3'],$consult_treat_data['items']['TreatDur3'],$consult_treat_data['items']['TreatEye3'],$consult_treat_data['items']['Language']);
        $Treat_Name4 = $this->convertMarathi($consult_treat_data['items']['TreatType4'],$consult_treat_data['items']['TreatDose4'],
            $consult_treat_data['items']['TreatFreq4'],$consult_treat_data['items']['TreatDur4'],$consult_treat_data['items']['TreatEye4'],$consult_treat_data['items']['Language']);
        $Treat_Name5 = $this->convertMarathi($consult_treat_data['items']['TreatType5'],$consult_treat_data['items']['TreatDose5'],
            $consult_treat_data['items']['TreatFreq5'],$consult_treat_data['items']['TreatDur5'],$consult_treat_data['items']['TreatEye5'],$consult_treat_data['items']['Language']);
        $Treat_Name6 = $this->convertMarathi($consult_treat_data['items']['TreatType6'],$consult_treat_data['items']['TreatDose6'],
            $consult_treat_data['items']['TreatFreq6'],$consult_treat_data['items']['TreatDur6'],$consult_treat_data['items']['TreatEye6'],$consult_treat_data['items']['Language']);
        $Treat_Name7 = $this->convertMarathi($consult_treat_data['items']['TreatType7'],$consult_treat_data['items']['TreatDose7'],
            $consult_treat_data['items']['TreatFreq7'],$consult_treat_data['items']['TreatDur7'],$consult_treat_data['items']['TreatEye7'],$consult_treat_data['items']['Language']);
        $Treat_Name8 = $this->convertMarathi($consult_treat_data['items']['TreatType8'],$consult_treat_data['items']['TreatDose8'],
            $consult_treat_data['items']['TreatFreq8'],$consult_treat_data['items']['TreatDur8'],$consult_treat_data['items']['TreatEye8'],$consult_treat_data['items']['Language']);
        $Treat_Name9 = $this->convertMarathi($consult_treat_data['items']['TreatType9'],$consult_treat_data['items']['TreatDose9'],
            $consult_treat_data['items']['TreatFreq9'],$consult_treat_data['items']['TreatDur9'],$consult_treat_data['items']['TreatEye9'],$consult_treat_data['items']['Language']);
        $Treat_Name10 = $this->convertMarathi($consult_treat_data['items']['TreatType10'],$consult_treat_data['items']['TreatDose10'],
            $consult_treat_data['items']['TreatFreq10'],$consult_treat_data['items']['TreatDur10'],$consult_treat_data['items']['TreatEye10'],$consult_treat_data['items']['Language']);
                                        
                                            
        return view('/opd/short-opd-print',['DocName'=>$DocName,
    'queue_data'=>$queue_data,'pt_data'=>$pt_data,'opto_data'=>$opto_data,'consult_data'=>$consult_data,
    'consult_treat_data'=>$consult_treat_data,'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 getVisitDetails(Request $req){
        $mrdno = $req->mrdno;
        $visitno = $req->visitno;
        $visitdate = $req->visitdate;
        $FolderName = $mrdno;
        $FolderName2 = $visitdate;
        $optodata = Storage::disk('local')->get($FolderName."/".$FolderName2."/opto.txt");
        $result = json_decode($optodata,true);
        //$result = OptoModel::select()->where(['MrdNo'=>$mrdno,'VisitNo'=>$visitno,'VisitDate'=>$visitdate])->first();
        return $result;
    }

    function fetchData(Request $request){
     if($request->get('query'))
     {
      $query = $request->get('query');
      $result = DB::table('tbl_treatments')->select('Treatment')->where('Treatment', 'LIKE', "{$query}%")->where(['TreatRoll'=>'Opd'])->distinct()->orderBy('Treatment','asc')->limit(5)->get();
      if($result->count() > 0){
      return view('/masters/fetch-data',['data'=>$result]);
      }
      else{

      }
      
     }
    }

    function fetchData2(Request $request){
        if($request->get('query'))
        {
         $query = $request->get('query');
         $srno = $request->get('srno');
         $TreatType = $request->get('TreatType');
         $result = DB::table('tbl_drugs')->where('Name', 'LIKE', "%{$query}%")->where(['Type'=>$TreatType])->limit(5)->get();
         if($result->count() > 0){
         return view('/masters/fetch-data2',['data'=>$result,'srno'=>$srno]);
         }
         else{
           
         }
         
        }
       }

    
}