<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\BirthRegister;
use App\Models\Gender;
use App\Models\IpdAdmission;
use App\Models\Company;
use App\Models\ProductCategory;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Exports\BirthRegisterStatementExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\SymptomClassification;
use App\Models\Symptom;
use App\Models\EnquirySource;
use App\Models\MasterType;
use App\Models\Account;
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\VoucherType;
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 BirthRegisterController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
       $birth_registers = BirthRegister::select(
            'birth_registers.id as birth_registers_id',
            'birth_registers.ipd_id as ipd_id',
            'birth_registers.child_name as child_name',
            'birth_registers.child_image as child_image',
            'birth_registers.gender_id as gender_id',
            'birth_registers.birth_date as birth_date',
            'birth_registers.birth_time as birth_time',
            'birth_registers.weight as weight',
            'birth_registers.mother_name as mother_name',
            'birth_registers.mother_image as mother_image',
            'birth_registers.father_name as father_name',
            'birth_registers.father_image as father_image',
            'birth_registers.contact as contact',
            'birth_registers.birth_report as birth_report',
            'birth_registers.document as document',
            'birth_registers.present_address as present_address',
            'birth_registers.permanent_address as permanent_address',
            'birth_registers.is_active as is_active',
            'genders.name  as gender_name' 
        )
        ->leftJoin('genders' , 'birth_registers.gender_id' , '=' , 'genders.id')
        ->orderBy('birth_registers.child_name', 'ASC');

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

            $birth_registers = $birth_registers->when(!empty($search_query), function ($query) use ($search_query) {
                return $query
                ->where('birth_registers.child_name', 'like', '%'.$search_query.'%')
                ->orWhere('birth_registers.mother_name', 'like', '%'.$search_query.'%')
                ->orWhere('birth_registers.father_name', 'like', '%'.$search_query.'%')
                ->orWhere('birth_registers.birth_date', 'like', '%'.$search_query.'%')
                ->orWhere('birth_registers.birth_time', 'like', '%'.$search_query.'%')
                ->orWhere('birth_registers.birth_report', 'like', '%'.$search_query.'%')
                ->orWhere('genders.name', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

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

            return view('birth-registers.index', compact('birth_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)
    {
        $birth_registers = BirthRegister::findOrFail($id);

        $genders = Gender::all();

        return view('accounts.edit-birth-registers', compact('birth_registers' , '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)
    {
        $birth_registers = BirthRegister::findOrFail($id);
        $birth_registers->delete();

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

    public function createBirthRegister($id = '')
    {
       $birth_registers = BirthRegister::select(
            'birth_registers.id as birth_registers_id',
            'birth_registers.ipd_id as ipd_id',
            'birth_registers.child_name as child_name',
            'birth_registers.gender_id as gender_id',
            'birth_registers.birth_date as birth_date' ,
            'birth_registers.birth_time as birth_time' ,
            'birth_registers.mother_name as mother_name',
            'birth_registers.father_name as father_name',
            'birth_registers.birth_report as birth_report',
            'birth_registers.is_active as is_active',
            'genders.name  as gender_name' ,
            'accounts.id',
            'account_types.id',
            'account_addresses.id',
        )
        ->leftJoin('genders' , 'birth_registers.gender_id' , '=' , 'genders.id')
        ->leftJoin('accounts' , 'birth_registers.id' , '=' , 'accounts.id')

        ->leftJoin('account_types' , 'account_types.id' , '=' , 'accounts.account_type_id')
        ->leftJoin('account_addresses' , 'account_addresses.account_id' , '=' , 'accounts.id')
        ->get();

    $genders = Gender::all();

    $ipd_admission_id = $id;

    $birth_registers_id =  BirthRegister::select('birth_registers.id as birth_registers_id')
    ->get();

    return view('accounts.create-birth-register', compact('birth_registers' , 'birth_registers_id' , 'genders' , 'ipd_admission_id'));
    }

    public function storeBirthRegister(Request $request , $id = '')
    {
        $validator = \Validator::make($request->all(), [
            'child_name'         => 'required',
            'birth_registers_id' => 'required',
            'gender_id'          => 'required',
            'birth_date'         => 'required',
            'birth_time'         => 'required',
            'mother_name'        => 'required',
            'father_name'        => 'required',
            'birth_report'       => 'required',
        ]);

        if ($validator->fails()) {

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

        $birth_registers = [
            'child_name'         => $request->child_name,
            'birth_registers_id' => $request->birth_registers_id,
            'ipd_id'             => $id ?? '',
            'gender_id'          => $request->gender_id,
            'birth_date'         => $request->birth_date,
            'birth_time'         => $request->birth_time,
            'mother_name'        => $request->mother_name,
            'father_name'        => $request->father_name,
            'birth_report'       => $request->birth_report,
        ];
        
        BirthRegister::create($birth_registers);

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

    public function updateBirthRegister(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'child_name'         => 'required',
            'birth_registers_id' => 'required',
            'gender_id'          => 'required',
            'birth_date'         => 'required',
            'birth_time'         => 'required',
            'mother_name'        => 'required',
            'father_name'        => 'required',
            'birth_report'       => 'required',
        ]);

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


        // Find the existing DeathRegister entry by ID
        $birth_registers = BirthRegister::findOrFail($id);

        // Update the DeathRegister with the new data
        $birth_registers->update([
            'child_name'   => $request->child_name,
            'gender_id'    => $request->gender_id,
            'mother_name'  => $request->mother_name,
            'father_name'  => $request->father_name,
            'birth_date'   => $request->birth_date,
            'birth_time'   => $request->birth_time,
            'birth_report' => $request->birth_report,
        ]);

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

    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 : '';

            $birth_registers = BirthRegister::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('birth-registers.statement-table', compact([
                'fromDate',
                'toDate',
                'companyDateFormate',
                'birth_registers' ,
            ]));
        }

        return view('birth-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     = BirthRegister::getStatement([], $filters)->toArray();
        
        $fileName = 'Birth-Register-Statement'.' From '.$from_date.' To '.$to_date.'.xlsx';

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



    public function birthRegisters($id){

        $birth_registers = BirthRegister::leftjoin('ipd_admissions' , 'ipd_admissions.id' , '=' , 'birth_registers.ipd_id')
            ->leftjoin('accounts' , 'accounts.id' , '=' , 'ipd_admissions.patient_id')
            ->leftjoin('account_contacts' , 'account_contacts.account_id' , '=' , 'accounts.id')
            ->leftjoin('genders' , 'genders.id' , '=' , 'birth_registers.gender_id')
            ->whereRaw('TIMESTAMPDIFF(YEAR, account_contacts.date_of_birth, CURDATE()) >= 12') 
            ->where('birth_registers.ipd_id', $id ?? '')
            ->select(
                'birth_registers.id as id' ,
                'birth_registers.gender_id',
                'genders.name as gender_name',
                'birth_registers.child_name as child_name',
                'birth_registers.birth_date as birth_date',
                'birth_registers.birth_time as birth_time',
                'birth_registers.mother_name as mother_name',
                'birth_registers.father_name as father_name',
                'birth_registers.birth_report as birth_report',
                'ipd_admissions.id as ipd_admission_id' ,
            )
            ->get();

        return view('ipd-admission-birth-registers.table', compact('birth_registers'));
    }

}
