<?php

namespace App\Http\Controllers\IpdAdmission;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DischargeType;
use App\Models\IpdAdmission;
use App\Models\Account;
use App\Models\BloodGroup;
use App\Models\IpdAdmissionReferralDischarged;
use App\Models\IpdAdmissionDeathDischarged;
use App\Models\VoucherType;
use App\Models\SaleInvoice;
use App\Models\Company;
use App\Models\ProductBrand;
use App\Models\ProductCategory;
use App\Models\IpdDischarge;
use Carbon\Carbon;
use Session;
use Barryvdh\DomPDF\Facade\Pdf;

use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\IpdDischargedStatementExport;



class IpdDischargedController extends Controller
{
    function __construct()
    {

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        \Session::forget('ipd_billing_products_cart');

        //\DB::enableQueryLog();
        $data = IpdAdmission::select([
            'ipd_admissions.id',
            'ipd_admissions.ipd_admission_no',
            'ipd_admissions.ipd_file_no',
            'ipd_admissions.tpa_account_id',
            'ipd_admissions.casualty',
            'ipd_admissions.admission_date_time',
            'ipd_admissions.referal_from',
            'ipd_admissions.note',
            'ipd_admissions.sale_invoice_id',
            'enquiry_sources.enquiry_source_name',
            'ipd_admissions.patient_id as patient_id',
            'sale_invoices.id as sale_invoices_name',
            'sale_invoices.operator_id',
            'ipd_discharges.id as ipd_admission_discharged_id',
            'users.prepared_by',
            'floors.name as floor_name'
        ])
        ->selectRaw('GROUP_CONCAT(beds.name) as bed')
        ->leftjoin('ipd_consultant_histories', 'ipd_consultant_histories.ipd_admission_id', 'ipd_admissions.id')
        ->leftjoin('enquiry_sources', 'enquiry_sources.id', 'ipd_admissions.patient_source_id')
        ->leftjoin('ipd_bed_histories', 'ipd_bed_histories.ipd_admission_id', 'ipd_admissions.id')
        ->leftjoin('ipd_discharges', 'ipd_discharges.ipd_admission_id', 'ipd_admissions.id')
        ->leftjoin('beds', 'beds.id', 'ipd_bed_histories.bed_no_id')
        ->leftjoin('floors', 'floors.id', 'beds.floor_id')
        ->leftjoin('sale_invoices', function ($join) {
            $join->on('ipd_admissions.patient_id', '=', 'sale_invoices.patient_id')
                ->where('sale_invoices.invoice_type', '=', 'ipd-billings');
        })
        ->leftjoin('users', 'users.id', 'sale_invoices.operator_id')
        ->with('contacts', 'consultantHistory','getTpa')
        ->where('ipd_consultant_histories.is_main_dr', 1)
        ->whereNull('ipd_admissions.deleted_at')
        ->whereNotNull('ipd_discharges.id')
        ->when(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
            $query->where(function($where) {
                $where->where('ipd_admissions.created_by', \Auth()->id());
            })
            ->where('ipd_admissions.company_id', \Auth()->user()->company_id);
        })
        ->when(in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
            $query->where('ipd_admissions.company_id', \Auth()->user()->company_id);
        })
        ->groupBy('ipd_admissions.id')
        ->orderBy('ipd_admissions.ipd_admission_no', 'DESC');
        


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

            $data = $data->when(!empty($search_query) && !empty($search_type),
                function ($query) use ($search_query, $search_type) {
                    if ($search_type == 'patient_title') {
                        $query->whereHas('contacts.account_title', function ($contacts) use ($search_query) {
                            $contacts->where('name', 'like', '%' . $search_query . '%');
                        });
                    } else if ($search_type == 'patient_name') {
                        $query->whereHas('contacts', function ($contacts) use ($search_query) {
                            $contacts->where('name', 'like', '%' . $search_query . '%');
                        });
                    } else if ($search_type == 'patient_code') {
                        $query->whereHas('contacts', function ($contacts) use ($search_query) {
                            $contacts->where('code', 'like', '%' . $search_query . '%');
                        });
                    } else if ($search_type == 'consultant_title') {
                        $query->whereHas('consultantHistory.consultants.account_title', function ($contacts) use ($search_query) {
                            $contacts->where('name', 'like', '%' . $search_query . '%');
                        });
                    } else if ($search_type == 'consultant_name') {
                        $query->whereHas('consultantHistory.consultants', function ($contacts) use ($search_query) {
                            $contacts->where('name', 'like', '%' . $search_query . '%');
                        });
                    } else if ($search_type == 'ipd_admission_no') {
                        $query->where('ipd_admissions.ipd_admission_no', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'ipd_file_no') {
                        $query->where('ipd_admissions.ipd_file_no', 'like', '%'.$search_query.'%');
                    }
                })
                ->paginate($sort_by);

                return view('ipd-discharged.table', compact('data'));
        }
        else
        {
            $patient_type = 'discharged';
            $data = $data->paginate(10);

            return view('ipd-discharged.index', compact('data','patient_type'));
        }
        $data = IpdDischarge::select(['ipd_discharges.*','users.prepared_by'])
                ->with('get_admission_details', 'consultantHistory')
                ->leftjoin('users', 'users.id', 'ipd_discharges.created_by_id')
                ->latest();

        // echo "<pre>";
        // print_r($data->get()->toArray());
        // die();

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

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where(function ($query) use ($search_query) {
                    $query->Where('ipd_discharge.discharge_date_time', 'like', '%' . $search_query . '%');
                });
            })
            ->paginate($sort_by);

            return view('ipd-discharged.table', compact('data'));
           
        }
        else
        {
            $data = $data->paginate(10);

            return view('ipd-discharged.index', compact('data'));
        }
    }






    public function statement(Request $request)
    {

        $companies = Company::select('id', 'name')->get();
        $users     = SaleInvoice::select('users.id', 'users.name', 'users.email')
            ->leftjoin('users', 'users.id','sale_invoices.operator_id')
            ->groupBy('sale_invoices.operator_id')
            ->get();
        $discharge_type = DischargeType::select('id','code')->get();
        if ($request->ajax()) {
            $company = Company::find(Auth::user()->company_id);
            $collection_status  = $request->collection_status;
            $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

            $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['from_date']                     = date('Y-m-d', strtotime($from_date));
            $filters['to_date']                       = date('Y-m-d', strtotime($to_date));
            $filters['discharge_type']                = $request->discharge_type != 'null' ? $request->discharge_type : '';
            $filters['company']                       = $request->company != 'null' ? $request->company : '';
            $filters['created_by']                    = $request->created_by != 'null' ? $request->created_by : '';
            $filters['search_account']                = $request->search_account != 'null' ? $request->search_account : '';
           
            $ipd_admissions = IpdAdmission::getStatementIpdAdmission($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('ipd-discharged.statement.statement-table', compact([
                'ipd_admissions',
                'fromDate',
                'toDate',
                'companyDateFormate',
                'collection_status',
                'discharge_type'
            ]));
        }

        $brands          = ProductBrand::select(['id', 'name', 'is_default'])->where(['status' => 1])->get();
        $productCategory = ProductCategory::select(['id', 'name', 'is_default'])->where(['status' => 1])->get();

        return view('ipd-discharged.statement.statement', compact([
            'brands',
            'companies',
            'productCategory',
            'users',
            "discharge_type",
        ]));
    }


    public function exportStatement(Request $request)
    {
        $from_date = $request->from_date ;                
        $to_date   = $request->to_date ;

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

        $data = IpdAdmission::getStatementIpdAdmission($filters)->toArray();

        $fileName = 'Discharged-Statements'.' From '.$from_date.' To '.$to_date.'.xlsx';

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




    /**
     * 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)
    {
        $data                = IpdDischarge::find($id);
        $discharge_types     = DischargeType::select('id', 'name', 'code')->where('status', 1)->get();
        $admission           = IpdAdmission::where('id', $data->ipd_admission_id)->with('contacts', 'consultantHistory')->first();
        $tpa_account         = Account::select('name')->where('account_type_id', $admission->tpa_account_id)->first();
        $blood_group         = BloodGroup::where('id', $admission->contacts->account_contact->blood_group_id)->first();
        $referral_discharged = IpdAdmissionReferralDischarged::where('ipd_admission_id', $data->ipd_admission_id)->first();
        $death_discharged    = IpdAdmissionDeathDischarged::where('ipd_admission_id', $data->ipd_admission_id)->first();

        return view('ipd-discharged.edit', compact(
            'discharge_types',
            'admission',
            'tpa_account',
            'blood_group',
            'data',
            'referral_discharged',
            'death_discharged'
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'discharge_date_time' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first())->withInput();
        }

        $ipd_discharge = IpdDischarge::find($id);

        $ipd_discharge->update([
            'discharge_type_id'   => $request->discharge_type_id,
            'operation'           => $request->operation,
            'diagnosis'           => $request->diagnosis,
            'investigation'       => $request->investigation,
            'note'                => $request->note,
            'treatment_at_home'   => $request->treatment_at_home,
            'next_follow_up_date' => $request->next_follow_up_date,
            'discharge_date_time' => $request->discharge_date_time
        ]);

        $discharge_type = DischargeType::find($request->discharge_type_id);

        if (($request->referral_date_time != '') && ($request->referral_hospital_name != '')) {
            if ($discharge_type->code == 'REFERRAL') {

                IpdAdmissionReferralDischarged::updateOrCreate([
                    'ipd_admission_id' => $ipd_discharge->ipd_admission_id,
                ], [
                    'referral_date_time'     => $request->referral_date_time,
                    'referral_hospital_name' => $request->referral_hospital_name,
                    'reason_for_referral'    => $request->reason_for_referral
                ]);
            } else {
                IpdAdmissionReferralDischarged::where('ipd_admission_id', $ipd_discharge->ipd_admission_id)->delete();
            }
        }

        if (($request->death_date_time != '') && ($request->guardian_name != '')) {
            if ($discharge_type->code == 'DEATH') {

                if ($request->death_file_attachment != '') {

                    $death_discharged = IpdAdmissionDeathDischarged::where('ipd_admission_id', $ipd_discharge->ipd_admission_id)->first();
                    $old_image = $death_discharged->file_attachment ?? '';

                    $path     = "death_discharged";
                    $response = uploadImage($path,$request->death_file_attachment,$old_image);

                    if ($response['status'] == true) {
                        $death_discharged_file_path = $response['file_name'];

                        IpdAdmissionDeathDischarged::updateOrCreate([
                            'ipd_admission_id' => $ipd_discharge->ipd_admission_id,
                        ], [
                            'death_date_time' => $request->death_date_time,
                            'guardian_name'   => $request->guardian_name,
                            'death_report'    => $request->death_report,
                            'file_attachment' => $death_discharged_file_path
                        ]);
                    } else {
                        if ($request->ajax()) {
                            return response()->json([
                                'success' => false,
                                'message' => $response['message'],
                                'data'    => []
                            ]);
                        }
                        return redirect()->back()->with('error', $response['message']);
                    }
                }

                IpdAdmissionDeathDischarged::updateOrCreate([
                    'ipd_admission_id' => $ipd_discharge->ipd_admission_id,
                ], [
                    'death_date_time' => $request->death_date_time,
                    'guardian_name'   => $request->guardian_name,
                    'death_report'    => $request->death_report
                ]);
            } else {
                $death_discharged = IpdAdmissionDeathDischarged::where('ipd_admission_id', $ipd_discharge->ipd_admission_id)->first();

                if (isset($death_discharged) && ($death_discharged->file_attachment != '')) {
                    deleteImage($death_discharged->file_attachment);
                    $death_discharged->delete();
                }
            }
        }

        return redirect()->route('ipd-discharged.index')->with('success','Patient discharged updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function dischargeInvoice($id)
    {
        $voucher_type = VoucherType::with('voucherSeries')->where('code', 'PATHOLOGY')->first();

        $discharge_invoice = IpdDischarge::where('ipd_admission_id', $id)->with('get_admission_details')->first();

        $sale_invoice = SaleInvoice::select('*')->with('getSaleInvoiceDetails')
        ->with('getSaleInvoiceDelivery')
        ->with('getPatient')
        ->with('getPaymentTerm')
        ->with('getCompany')
        ->find($id);
        // dd($discharge_invoice);

        return view('invoice-formats.ipd.discharged-invoice', compact('voucher_type', 'sale_invoice', 'discharge_invoice'));
    }
}
