<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\IpdAdmission;
use App\Models\DeathRegister;
use App\Models\Gender;
use App\Models\VoucherType;
use Illuminate\Support\Facades\Auth;
use App\Models\Account;
use App\Models\Company;
use App\Models\BirthRegister;
use Carbon\Carbon;
use App\Exports\DeathRegisterStatementExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\SymptomClassification;
use App\Models\Symptom;
use App\Models\EnquirySource;
use App\Models\MasterType;
use App\Models\ProductCategory;
use App\Models\Surgery;
use App\Models\BodyVital;
use App\Models\IpdBodyVitalHistory;
use App\Models\IpdSymptomHistory;
use App\Models\IpdBedHistory;
use App\Models\BedGroup;
use App\Models\Bed;
use App\Models\IpdConsultantHistory;
use App\Models\MaritalStatus;
use App\Models\BloodGroup;
use App\Models\AccountTransaction;
use App\Models\AcReceipt;
use App\Models\AcReceiptDetail;
use App\Models\DischargeType;
use App\Models\OpdBookings;
use App\Models\SaleInvoice;
use App\Models\SaleInvoiceDetail;
use App\Models\VoucherCollection;
use App\Models\VoucherCollectionDetail;
use App\Models\IpdDischarge;
use App\Models\IpdDischargeTypeSetting;
use App\Models\IpdDischargeDetail;
use App\Models\SaleInvoiceBatch;
use App\Models\DepartmentCLearanceSetting;
use App\Models\Sales\SaleReturns;
use Illuminate\Support\Facades\DB;
use App\Models\LabBillingReport;
use App\Exports\IpdBillingStatementExport;
use App\Models\SaleInvoiceSubDetails;
use App\Traits\TransactionSummeryTrait;
use Carbon\Exceptions\InvalidFormatException;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;




class DeathRegisterController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
       $death_registers = DeathRegister::select(
            'death_registers.id as death_registers_id',
            'death_registers.ipd_id as ipd_id',
            'ipd_admissions.ipd_admission_no as ipd_admission_case_id',
            'death_registers.death_date as death_date',
            'death_registers.death_time as death_time',
            'death_registers.death_reason as death_reason',
            'death_registers.guardian_name as guardian_name',
            'death_registers.death_report as death_report',
            'death_registers.attachment_name as attachment_name',
            'accounts.name as patient_name',
            'death_registers.file_url as file_url',
            'death_registers.is_active as is_active',
            'ipd_admissions.id',
            'accounts.id',
            'genders.name as gender_name'
        )
        ->leftJoin('ipd_admissions' , 'ipd_admissions.id' , '=' , 'death_registers.ipd_id')
        ->leftJoin('accounts' , 'accounts.id' , '=' , 'ipd_admissions.patient_id')
        ->leftJoin('account_contacts' , 'account_contacts.account_id' , '=' , 'accounts.id')
        ->leftJoin('account_titles' , 'account_titles.id' , '=' , 'accounts.account_title_id')
        ->leftJoin('genders' , 'genders.id' , '=' , 'account_contacts.account_gender_id')
        ->orderBy('accounts.name', 'ASC');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $death_registers = $death_registers->when(!empty($search_query), function ($query) use ($search_query) {
                return $query
                    ->where('accounts.name', 'like', '%'.$search_query.'%')
                    ->orWhere('ipd_admissions.ipd_admission_no', 'like', '%'.$search_query.'%')
                    ->orWhere('death_registers.death_date', 'like', '%'.$search_query.'%')
                    ->orWhere('death_registers.guardian_name', 'like', '%'.$search_query.'%')
                    ->orWhere('death_registers.death_report', 'like', '%'.$search_query.'%')
                    ->orWhere('genders.name', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);


            return view('death-registers.table', compact('death_registers'));
        } else {
            $death_registers = $death_registers->paginate(10);

            return view('death-registers.index' , compact('death_registers'));
            
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $death_registers = DeathRegister::findOrFail($id);


        $ipd_admission = IpdAdmission::leftJoin('death_registers' , 'death_registers.ipd_id' , 'ipd_admissions.id')
        ->leftjoin('genders' , 'death_registers.gender_id' , '='  , 'genders.id')
        ->select(
            'death_registers.id as id' ,
            'ipd_admissions.ipd_admission_no as case_id',
            'genders.id as gender_id' ,
            'genders.name as gender_name',
        )->where('death_registers.id' , $id)
        ->first();        

        $genders = Gender::all();     

        return view('accounts.edit-death-registers', compact('death_registers' , 'ipd_admission' , 'genders'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $death_registers = DeathRegister::findOrFail($id);

        $death_registers->delete();

        return response()->json([
            'success' => true,
            'message' => 'Death Register deleted successfully',
            'data' => [
                'redirect' => '', 
            ]
        ]);
    }

    public function statement(Request $request)
    {
        $companies = Company::select('id', 'name')->get();

        if ($request->ajax()) {
            $company = Company::find(Auth::user()->company_id);
            $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
            $listing_type = $request->listing_type;

            $from_date = $request->from_date ?
                Carbon::createFromFormat($this->companyDateFormate(), $request->from_date)->format('Y-m-d')
                    :date('Y-m-d');
            $to_date   = $request->to_date ?
                Carbon::createFromFormat($this->companyDateFormate(), $request->to_date)->format('Y-m-d')
                    :date('Y-m-d');

            $filters                      = $where        = [];
            $filters['from_date']         = date('Y-m-d', strtotime($from_date));
            $filters['to_date']           = date('Y-m-d', strtotime($to_date));
            $filters['company']           = $request->company != 'null' ? $request->company : '';
            $filters['search_account']    = $request->search_account != 'null' ? $request->search_account : '';
            $filters['listing_type']      = $request->listing_type != 'null' ? $request->listing_type : '';

            $death_registers = DeathRegister::getStatement($where, $filters);
            $fromDate = date('Y-m-d H:i:s',strtotime($from_date));
            $toDate   = date('Y-m-d H:i:s',strtotime($to_date));

            return view('death-registers.statement-table', compact([
                'fromDate',
                'toDate',
                'companyDateFormate',
                'death_registers' ,
            ]));
        }

        return view('death-registers.statement', compact([
            'companies',
        ]));
    }

     public function exportStatement(Request $request)
    {

        $from_date = $request->from_date ?
            Carbon::createFromFormat($this->companyDateFormate(), $request->from_date)->format('Y-m-d')
                :date('Y-m-d');
        $to_date   = $request->to_date ?
            Carbon::createFromFormat($this->companyDateFormate(), $request->to_date)->format('Y-m-d')
                :date('Y-m-d');

            $filters                      = $where        = [];
            $filters['from_date']         = date('Y-m-d', strtotime($from_date));
            $filters['to_date']           = date('Y-m-d', strtotime($to_date));
            $filters['company']           = $request->company != 'null' ? $request->company : '';
            $filters['search_account']    = $request->search_account != 'null' ? $request->search_account : '';
            $filters['listing_type']      = $request->listing_type != 'null' ? $request->listing_type : '';          
  

        $data     = DeathRegister::getStatement([], $filters)->toArray();
        
        $fileName = 'death-Register-Statement'.' From '.$from_date.' To '.$to_date.'.xlsx';

        return Excel::download(new DeathRegisterStatementExport($data), $fileName);
    }


    public function createDeathRegister($id = '')
    {

        $death_registers = DeathRegister::select(
                'death_registers.ipd_id as death_register_ipd_id',
                'ipd_admissions.ipd_admission_no as ipd_admission_case_id',
                'death_registers.death_date as death_date',
                'death_registers.death_time as death_time',
                'death_registers.death_reason as death_reason',
                'death_registers.guardian_name as guardian_name',
                'death_registers.death_report as death_report',
                'death_registers.attachment_name as attachment_name',
                'accounts.name as patient_name',
                'death_registers.file_url as file_url',
                'death_registers.is_active as is_active',
                'genders.name as gender_name' ,
                'genders.id as gender_id' ,

            )
            ->leftJoin('ipd_admissions' , 'ipd_admissions.id' , '=' , 'death_registers.ipd_id')
            ->leftJoin('accounts' , 'accounts.id' , '=' , 'ipd_admissions.patient_id')
            ->leftJoin('account_contacts' , 'account_contacts.account_id' , '=' , 'accounts.id')
            ->leftJoin('genders' , 'genders.id' , '=' , 'account_contacts.account_gender_id')
            ->get();

        $genders = Gender::all();

        $ipd_admission_id = $id;

        return view('accounts.create-death-register', compact('death_registers' , 'ipd_admission_id' , 'genders'));
    }


    public function storeDeathRegister(Request $request , $id = '')
    {
        $validator = \Validator::make($request->all(), [
            'ipd_id'          => 'nullable' ,
            'ipd_case_id'     => 'nullable',
            'death_date'      => 'required',
            'death_time'      => 'required',
            'guardian_name'   => 'required',
            'attachment_name' => 'nullable',
            'death_report'    => 'required',
            'file_url'        => 'required',
            'gender_id'       => 'nullable'
            
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => 'death-registers.index'],
            ]);
        }

        $death_register = [
            'ipd_id'          => $id ?? '',
            'ipd_case_id'     => $request->ipd_case_id,
            'death_date'      => $request->death_date,
            'death_time'      => $request->death_time,
            'guardian_name'   => $request->guardian_name,
            'death_report'    => $request->death_report,
            'attachment_name' => $request->attachment_name,
            'file_url'        => $request->file_url,
            'gender_id'       => $request->gender_id ?? ''
        ];

        $death_register = DeathRegister::create($death_register);

        return response()->json([
            'success'  => true,
            'message'  => 'Death Register created successfully',
            'data'     => [
            'redirect' => 'Death-registers.index', 
            ]
        ]);
    }


    public function updateDeathRegister(Request $request, $id)
    {
        // Validate the request data
        $validator = \Validator::make($request->all(), [
            'ipd_case_id'     => 'nullable',
            'death_date'      => 'required',
            'death_time'      => 'required',
            'guardian_name'   => 'required',
            'attachment_name' => 'nullable',
            'death_report'    => 'required',
            'file_url'        => 'required',
        ]);

        // Handle validation errors
        if ($validator->fails()) {
            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                    'redirect' => 'death-registers.index'
                ],
            ]);
        }

        $death_register = DeathRegister::findOrFail($id);

        // Update the DeathRegister with the new data
        $death_register->update([
            'ipd_case_id'     => $request->ipd_case_id,
            'death_date'      => $request->death_date,
            'death_time'      => $request->death_time,
            'guardian_name'   => $request->guardian_name,
            'death_report'    => $request->death_report,
            'attachment_name' => $request->attachment_name,
            'file_url'        => $request->file_url,
        ]);

        // Return a success response
        return response()->json([
            'success'  => true,
            'message'  => 'Death Register updated successfully',
            'data'     => [
                'redirect' => 'death-registers.index',
            ]
        ]);
    }


    public function deathRegisters($id){

        $death_registers = DeathRegister::select(
            'death_registers.id as id',
            'death_registers.ipd_id as death_register_ipd_id',
            'ipd_admissions.ipd_admission_no as ipd_admission_case_id',
            'death_registers.death_date as death_date',
            'death_registers.death_time as death_time',
            'death_registers.death_reason as death_reason',
            'death_registers.guardian_name as guardian_name',
            'death_registers.death_report as death_report',
            'death_registers.attachment_name as attachment_name',
            'accounts.name as patient_name',
            'death_registers.file_url as file_url',
            'death_registers.is_active as is_active',
            'ipd_admissions.id as ipd_admission_id',
            'genders.name as gender_name'
        )
        ->leftJoin('ipd_admissions' , 'ipd_admissions.id' , '=' , 'death_registers.ipd_id')
        ->leftJoin('accounts' , 'accounts.id' , '=' , 'ipd_admissions.patient_id')
        ->leftJoin('account_contacts' , 'account_contacts.account_id' , '=' , 'accounts.id')
        ->leftJoin('genders' , 'genders.id' , '=' , 'account_contacts.account_gender_id')
        ->where('death_registers.ipd_id' , $id)
        ->get();

    $ipd_admission_id = $id;


    $genders = Gender::all();

    return view('ipd-admission-death-registers.table', compact('death_registers' , 'genders' , 'ipd_admission_id'));

    }


}
