<?php

namespace App\Http\Controllers\Accounting;

use App\Exports\FinancialAccountVoucher\ReceiptVoucherExport;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CompanyAddress;
use App\Models\Account;
use App\Models\AccountingGroup;
use App\Models\PaymentMode;
use App\Models\SaleInvoice;
use App\Models\AcReceipt;
use App\Models\AcReceiptDetail;
use App\Models\AccountTransaction;
use App\Models\VoucherCollection;
use App\Models\VoucherCollectionDetail;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use App\Models\MenuModelPermission;
use App\Models\Company;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\FacadesAuth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\FacadesSession;
use Maatwebsite\Excel\Facades\Excel;

class AccountingReceiptsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:receipt-voucher-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = AcReceipt::with('accountReceiptDetail');

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

            $data = $data->when(!empty($search_query) && !empty($search_type),
                function ($query) use ($search_query, $search_type) {
                    if ($search_type == 'reciept_no') {
                        $query->where('receipt_no', 'like', '%'.$search_query.'%')
                        ->orWhere('overall_receipt_no', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'received_from') {
                        $query->whereHas('accountReceiptDetail.account', function ($query) use ($search_query, $search_type) {
                            $query->where('accounts.name', 'like', '%'.$search_query.'%');
                        });
                    } else if ($search_type == 'voucher_type') {
                        $query->whereHas('accountReceiptDetail.voucherType', function ($query) use ($search_query, $search_type) {
                            $query->where('voucher_types.name', 'like', '%'.$search_query.'%');
                        });
                    } elseif($search_type == 'ref_voucher_no'){
                        $query->whereHas('salesVoucher', function ($query) use ($search_query, $search_type) {
                            $query->where('sale_invoices.voucher_type_invoice_no','like', '%'.$search_query.'%');
                        });
                        $query->whereHas('opdBooking', function ($query) use ($search_query, $search_type) {
                            $query->where('opd_bookings.booking_no','like', '%'.$search_query.'%');
                        });
                    }
                })
                ->latest()
                ->paginate($sort_by);

            return view('accounting-receipt-vouchers.table', compact('data'));
        }
        else
        {
            $data = $data->latest()->paginate(10);

            return view('accounting-receipt-vouchers.index',compact('data'));
        }
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $accounting_group = Account::with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();

        $financialYears = \Session::get('financialyear');
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $company_address->country_code ?? 'us';

        $transaction_mode = AccountingGroup::where('is_payment_mode',1)->get();
        $payment_mode = PaymentMode::where('status',1)->get();

        return view('accounting-receipt-vouchers.create', compact('accounting_group','financialYears','countryCode','payment_mode','transaction_mode','companyDateFormate'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function receiptVoucherUpdate(Request $request)
    {
        $data = Session::get('receipt_voucher_details') ?? [];

        if (empty($data) || !isset($data['edit_receipt_voucher_entries']) || count($data['edit_receipt_voucher_entries']) < 1) {
            $data = [];
            Session::put('receipt_voucher_details', $data);
            return response()->json([ 'success' => false, 'message'=> 'No Receipt Voucher Entry Found!' ]);
        }

            $item = [
                'reference'            => $request->receipt_no,
                'receipt_date'         => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                'description'          => $request->description,
                'financial_year_id'    => $request->financial_year_id
            ];

            $receiptVoucher = AcReceipt::where('id', '=', $request->id)->update($item);

         if (!empty($data) || isset($data['edit_receipt_voucher_entries']) || count($data['edit_receipt_voucher_entries']) > 0) {
            AcReceiptDetail::where(['voucher_id'=>$request->id])->delete();
            foreach ($data['edit_receipt_voucher_entries'] as $item) {
                $item1 = [
                   'transactions_no'     => $item['transactions_no'],
                   'receipt_date'        => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                   'module_id'           => $item['module_id'],
                   'voucher_id'          => $request->id,
                   'voucher_type'        => $item['voucher_type'],
                   'account_id'          => $item['account_id'],
                   'transaction_type'    => $item['transaction_type'],
                   'details_narration'   => $item['details_narration'],
                   'amount'              => $item['amount'],
                   'currency_id'         => $item['currency_id'],
                   'created_by'          => $item['created_by'],
                   'company_id'          => $item['company_id'],
                   'financial_year_id'   => $item['financial_year_id'],
                   'transactions_status' => true
                ];
                $acReceiptTransaction = AcReceiptDetail::create($item1);

                AccountTransaction::updateTransaction([
                    'module_code'       => 'Receipt_VOUCHER',
                    'voucher_type'     => $item['voucher_type'], // SALE, PURCHASE, PAYMENT
                    'account_id'       => $item['account_id'],
                    'transaction_type' => $item['transaction_type'],
                    'voucher_id'       => $request->id,
                    'voucher_sub_id'   => $item['id'],
                ],[
                    'amount'            => $item['amount']
                ]);
            }
            Session::put('receipt_voucher_details', []);
         }

         return response()->json([ 'success' => true,'message'=> 'Receipt Voucher Updated Successfully!' ]);
        //return redirect()->route('accounting-receipt-vouchers.index')->with('success', 'New Receipt Voucher Created Successfully!');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function receiptVoucherSubmit(Request $request, $id = '')
    {
       
        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'RECEIPT')->where(['status' => 1])->first();
        $voucher_type   = VoucherType::with('voucherSeries')->where('code', 'RECEIPT')->where(['status' => 1])->first();

        $voucher_count      = AcReceipt::select('last_voucher_count')->orderBy('created_at', 'DESC')->first();
        $last_voucher_count = isset($voucher_count) && isset($voucher_count->last_voucher_count) ? $voucher_count->last_voucher_count + 1 : ($voucher_master->voucherSeries->start_from + 1 ?? 1);

        $main_invoice_no = $this->generateCode(
            $last_voucher_count,
            ($voucher_master->voucherSeries->prefix ?? 'RV'),
            ($voucher_master->voucherSeries->postfix ?? ''),
            ($voucher_master->voucherSeries->separator ?? '-'),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        $voucher_type_last_count      = AcReceipt::select('last_voucher_type_count')->orderBy('created_at', 'DESC')->first();
        $voucher_type_count = isset($voucher_type_last_count) && isset($voucher_type_last_count->last_voucher_type_count) ? $voucher_type_last_count->last_voucher_type_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);

        $voucher_type_invoice_no = $this->generateCode(
            $voucher_type_count,
            ($voucher_type->voucherSeries->prefix ?? 'RV'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );

        $module        = MenuModelPermission::where('code','PATHOLOGY_LAB_BILLING')->first();
        $moduleReceipt = MenuModelPermission::where('code','Receipt_VOUCHER')->first();
        $module_id     = ($request->redirect == 'lab-billings') ? ($module->id ?? $moduleReceipt->id) : $moduleReceipt->id;
        $module_code   = ($request->redirect == 'lab-billings') ? ($module->code ?? $moduleReceipt->code) : $moduleReceipt->code;

        $item = [
            'receipt_no'              => $voucher_type_invoice_no,
            'overall_receipt_no'      => $main_invoice_no,
            'receipt_date'            => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
            'company_id'              => Auth::user()->company_id,
            'voucher_status'          => true,
            'remarks'                 => $request->remarks ?? '',
            'created_by'              => Auth::user()->id ?? '',
            'last_voucher_count'      => $last_voucher_count,
            'last_voucher_type_count' => $voucher_type_count,
            'financial_year_id'       => $request->financial_year_id,
            'voucher_id'              => $voucher_master->id,
            'module_code'             => ($module_code),
            'receipt_time'            => Carbon::now(),
        ];
        $receiptVoucher = AcReceipt::create($item);

        $item1 = [
           'module_id'           => $module_id,
           'voucher_type'        => 'RECEIPT',
           'voucher_master_id'   => $voucher_master->id ?? '',
           'voucher_id'          => $receiptVoucher->id ?? '',
           'account_id'          => $request->account_id ?? '',
           'transaction_type'    => 'CREDIT',
           'details_narration'   => "",
           'amount'              => $request->total_amount,
           'created_by'          => Auth::user()->id ?? '',
           'company_id'          => Auth::user()->company_id ?? '',
           'financial_year_id'   => $request->financial_year_id,
           'transaction_date'    => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
           'transactions_status' => true,
           'transaction_mode_id' => '7',
           'payment_mode_id'     => '1',
        ];
        $acReceiptTransaction = AcReceiptDetail::create($item1);

        $voucher_collection = VoucherCollection::create([
            'collection_date'   => date('Y-m-d'),
            'module_code'       => 'Receipt_VOUCHER',
            'voucher_master_id' => $voucher_master->id ?? '',
            'voucher_id'        => $receiptVoucher->id,
            'voucher_type'      => 'RECEIPT',
            'money_receipt_id'  => $receiptVoucher->id,
            'created_by'        => Auth::user()->id,
        ]);

        if (isset($request->payment_mode) && count($request->payment_mode) > 0) {
            foreach ($request->payment_mode as $key => $item) {
                if ($item['amount'] > 0) {
                    $item1 = [
                        'module_id'              => $module_id,
                        'voucher_master_id'      => $voucher_master->id ?? '',
                        'voucher_id'             => $receiptVoucher->id,
                        'voucher_type'           => 'RECEIPT',
                        'account_id'             => $key,
                        'transaction_type'       => 'DEBIT',
                        'details_narration'      => '',
                        'amount'                 => $item['amount'],
                        'created_by'             => Auth::user()->id,
                        'company_id'             => Auth::user()->company_id,
                        'transaction_referrence' => $item['transaction_referrence'] ?? '',
                        'transaction_mode_id'    => $item['transaction_mode_id'] ?? '',
                        'transaction_date'       => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'transactions_status'    => true,
                        'payment_mode_id'        => $key
                    ];

                    $acReceiptTransaction = AcReceiptDetail::create($item1);

                    $transactionsData = $this->generateTransactionNumber();

                    AccountTransaction::createTransaction([
                        'transactions_no'   => $transactionsData['transactions_no'],
                        'transaction_date'  => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $receiptVoucher->id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'RECEIPT',
                        'account_id'        => $request->account_id,
                        'transaction_type'  => 'CREDIT',
                        'details_narration' => '',
                        'financial_year_id' => $request->financial_year_id,
                        'amount'            => $item['amount'],
                        'last_id'           => $transactionsData['last_count'],
                    ]);

                    $transaction = AccountTransaction::createTransaction([
                        'transactions_no'   => $transactionsData['transactions_no'],
                        'transaction_date'  => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $receiptVoucher->id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'RECEIPT',
                        'account_id'        => $key ?? '',
                        'transaction_type'  => 'DEBIT',
                        'details_narration' => '',
                        'financial_year_id' => $request->financial_year_id,
                        'amount'            => $item['amount'],
                        'last_id'           => $transactionsData['last_count'],
                    ]);

                    $voucher_collection_detail = VoucherCollectionDetail::create([
                        'voucher_collection_id' => $voucher_collection->id,
                        'transaction_id'        => $transaction->id,
                    ]);
                }
            }
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Receipt Voucher Created Successfully!',
                'voucher' => $receiptVoucher->id
            ]);
        }

        if ($request->redirect == 'lab-billings') {
            $sale_invoice = SaleInvoice::find($id);

            if ($sale_invoice) {
                $received_amount = $request->total_amount;
                $due = $sale_invoice->billing_amount - $sale_invoice->discount_amount - $received_amount;

                $sale_invoice->update([
                    'due_amount'      => $due,
                    'received_amount' => $received_amount,
                ]);
            }

            return redirect()->route('lab-billings.index')->with('success', 'Collection Updated Successfully');
        } else {
            return redirect()->route('receipt-voucher.index')->with('success', 'Receipt created successfully');
        }

    }

    /**
     * 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)
    {
        $accountReceipt = AcReceipt::with('company','accountReceiptTransaction','accountReceiptTransaction.company','accountReceiptTransaction.user','accountReceiptTransaction.account','accountReceiptTransaction.module')->where(['id'=>$id])->firstorfail();

        return view('accounting-receipt-vouchers.show', compact('accountReceipt'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request,$id)
    {
        $data = AcReceipt::find($id);
        if($data->module_code=="pathology" || $data->module_code=="PATHOLOGY")
        {
            $voucher_type = 'pathology';
            return redirect()->route('billing-collection-edit',['invoice_id'=>$id,'voucher_type'=>$voucher_type]);
        }
        elseif($data->module_code=="ipd-invoice" || $data->module_code=="IPD_INVOICE"){
            $voucher_type = 'ipd-invoice';
            return redirect()->route('billing-collection-edit',['invoice_id'=>$id,'voucher_type'=>$voucher_type]);
        }
        elseif($data->module_code=="opd-booking" || $data->module_code=="OPD_BOOKING")
        {
            $voucher_type = 'opd-booking';
            return redirect()->route('billing-collection-edit',['invoice_id'=>$id,'voucher_type'=>$voucher_type]);
        }
        elseif($data->module_code=="sales" || $data->module_code=="SALES")
        {
            $voucher_type = 'sales';
            $parameters = [
                'invoice_id'   => $id,
                'voucher_type' => $voucher_type,
            ];
            if ($request->has('redirect')) {
                $parameters['redirect'] = $request->input('redirect');
            }
            return redirect()->route('billing-collection-edit',$parameters);
        }

        $creditTransaction = AcReceiptDetail::with('account')
                ->where(['voucher_id' => $id, 'transaction_type' => 'DEBIT'])
                ->get();

        $debitTransaction = AcReceiptDetail::with('account')
                ->where(['voucher_id' => $id, 'transaction_type' => 'CREDIT'])
                ->first();

        $accounting_group = Account::with('chart_of_account_sub_type')
            ->where(function ($query) {
                $query->whereHas('chart_of_account_sub_type', function ($accounting_group) {
                    $accounting_group->where('is_payment_mode', '1');
                });
            })
            ->get();

        $financialYears = \Session::get('financialyear');

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $company_address->country_code ?? 'us';
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

        return view('accounting-receipt-vouchers.edit', compact([
            'data',
            'accounting_group',
            'creditTransaction',
            'debitTransaction',
            'countryCode',
            'financialYears',
            'companyDateFormate'
        ]));
    }

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

        if (!$receiptVoucher) {
            return redirect()->back()->with('error', 'Invalid Receipt Id!');
        }

        $item = [
            'receipt_date'      => date('Y-m-d', strtotime($request->receipt_date)),
            'remarks'           => $request->remarks,
            'financial_year_id' => $request->financial_year_id,
            'updated_by'        => Auth::user()->id,
        ];

        $receiptVoucher->update($item);

        $item1 = [
           'account_id' => $request->account_id ?? '',
           'amount'     => $request->total_amount,
        ];

        $acDEBITReceiptTransaction = AcReceiptDetail::where([
            'transaction_type' => 'CREDIT',
            'voucher_id'       => $id ?? ''
            ])->first();
        $acDEBITReceiptTransaction->update($item1);

        $voucher_collection = VoucherCollection::where([
            'money_receipt_id'  => $receiptVoucher->id,
        ])->first();

        $voucher_collection->update(['updated_by' => Auth::user()->id]);

        $moduleReceipt = MenuModelPermission::where('code','Receipt_VOUCHER')->first();

        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'RECEIPT')->where(['status' => 1])->first();

        if (isset($request->payment_mode) && count($request->payment_mode) > 0) {
            foreach ($request->payment_mode as $key => $item) {
                if ($item['amount'] > 0) {
                    $item1 = [
                        'module_id'              => $moduleReceipt->id ?? '',
                        'voucher_id'             => $id,
                        'voucher_type'           => 'RECEIPT',
                        'account_id'             => $key,
                        'transaction_type'       => 'DEBIT',
                        'details_narration'      => '',
                        'amount'                 => $item['amount'],
                        'transaction_referrence' => $item['transaction_referrence'],
                        'transaction_mode_id'    => $item['transaction_mode_id'],
                        'created_by'             => Auth::user()->id,
                        'company_id'             => Auth::user()->company_id,
                        'transaction_date'       => date('Y-m-d', strtotime($request->receipt_date)),
                        'transactions_status'    => true,
                        'financial_year_id'      => $request->financial_year_id,
                        'voucher_master_id'      => $voucher_master->id ?? '',
                        'payment_mode_id'        => $key
                    ];
                    $acReceiptTransaction = AcReceiptDetail::create($item1);

                    $transactions_no = $this->generateRandomCode();

                    $transaction = AccountTransaction::createTransaction([
                        'transactions_no'   => $transactions_no,
                        'transaction_date'  => date('Y-m-d', strtotime($request->receipt_date)),
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'RECEIPT',
                        'account_id'        => $key ?? '',
                        'transaction_type'  => 'DEBIT',
                        'details_narration' => '',
                        'financial_year_id' => $request->financial_year_id,
                        'amount'            => $item['amount']
                    ]);

                    $transaction = AccountTransaction::createTransaction([
                        'transactions_no'   => $transactions_no,
                        'transaction_date'  => date('Y-m-d', strtotime($request->receipt_date)),
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'RECEIPT',
                        'account_id'        => $request->account_id,
                        'transaction_type'  => 'CREDIT',
                        'details_narration' => '',
                        'financial_year_id' => $request->financial_year_id,
                        'amount'            => $item['amount']
                    ]);

                    $voucher_collection_detail = VoucherCollectionDetail::create([
                        'voucher_collection_id' => $voucher_collection->id,
                        'transaction_id'        => $transaction->id,
                    ]);
                }
            }
        }
        if (isset($request->update_payment_mode) && count($request->update_payment_mode) > 0) {
            foreach ($request->update_payment_mode as $key => $item) {
                if ($item['amount'] > 0) {
                    $item1 = [
                       'module_id'              => $moduleReceipt->id ?? '',
                       'voucher_type'           => 'RECEIPT',
                       'transaction_type'       => 'DEBIT',
                       'details_narration'      => '',
                       'amount'                 => $item['amount'],
                       'created_by'             => Auth::user()->id,
                       'company_id'             => Auth::user()->company_id,
                       'transaction_date'       => date('Y-m-d', strtotime($request->receipt_date)),
                       'transaction_referrence' => $item['transaction_referrence'],
                       'transaction_mode_id'    => $item['transaction_mode_id'],
                       'transactions_status'    => true
                    ];

                    $acReceiptTransaction = AcReceiptDetail::updateOrCreate([
                        'id'         => $key,
                        'voucher_id' => $id
                    ], $item1);

                    $transaction = AccountTransaction::updateTransaction([
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $key,
                        'voucher_type'      => 'RECEIPT',
                        'transaction_type'  => 'DEBIT',
                    ],[
                        'transaction_date'  => date('Y-m-d', strtotime($request->receipt_date)),
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);

                    $value = AccountTransaction::updateTransaction([
                        'module_code'      => 'Receipt_VOUCHER',
                        'voucher_type'     => 'RECEIPT',
                        'account_id'       => $request->account_id,
                        'transaction_type' => 'CREDIT',
                        'transactions_no'  => $transaction->transactions_no,
                    ],[
                        'transaction_date'  => date('Y-m-d', strtotime($request->receipt_date)),
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);
                } else {
                    AcReceiptDetail::where([
                        'id'         => $key,
                        'voucher_id' => $id
                    ])->delete();

                    $transaction = AccountTransaction::where([
                        'module_code'       => 'Receipt_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $key,
                        'voucher_type'      => 'RECEIPT',
                        'transaction_type'  => 'DEBIT',
                    ])->first();

                    AccountTransaction::where([
                        'module_code'      => 'Receipt_VOUCHER',
                        'voucher_type'     => 'RECEIPT',
                        'account_id'       => $request->account_id,
                        'transaction_type' => 'CREDIT',
                        'transactions_no'  => $transaction->transactions_no,
                    ])->delete();

                    $transaction->delete();
                }
            }
        }

        $module = MenuModelPermission::find($acDEBITReceiptTransaction->module_id);

        if ($module->code == 'PATHOLOGY_LAB_BILLING' || $request->redirect == 'lab-billings') {
            $sale_invoice = SaleInvoice::find($receiptVoucher->voucher_id);

            if ($sale_invoice) {
                $received_amount = $request->total_amount;
                $due = $sale_invoice->billing_amount - $sale_invoice->discount_amount - $received_amount;

                $sale_invoice->update([
                    'due_amount'      => $due,
                    'received_amount' => $received_amount,
                ]);
            }
        }

        if ($request->redirect == 'lab-billings') {
            return redirect()->route('lab-billings.index')->with('success', 'Collection Updated Successfully');
        } else {
            return redirect()->route('receipt-voucher.index')->with('success', 'Receipt Updated Successfully');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data            = AcReceipt::find($request->id);
        $module_code     = $data->module_code;
        $sale_invoice_id = $data->voucher_id;
        $data->update(['deleted_by'=>Auth::user()->id]);
        $data->delete();

        AcReceiptDetail::where(['voucher_id' => $request->id])->delete();

        if ($module_code == 'Receipt_VOUCHER' ||
            $module_code == 'PATHOLOGY_LAB_BILLING' ||
            $module_code == 'Pathology' ||
            $module_code == 'PATHOLOGY'
        ) {
            $transactions = AccountTransaction::where([
                    'voucher_id'       => $request->id,
                    'transaction_type' => 'DEBIT',
                ])
                ->where(function($query) {
                    $query->where('module_code', 'Receipt_VOUCHER')
                    ->orWhere('module_code', 'PATHOLOGY_LAB_BILLING')
                    ->orWhere('module_code', 'Pathology')
                    ->orWhere('module_code', 'PATHOLOGY');
                })
                ->sum('amount');

            $sale_invoice = SaleInvoice::find($sale_invoice_id);

            $sale_invoice->update([
                'received_amount' => ($sale_invoice->received_amount - $transactions),
                'due_amount'      => ($sale_invoice->due_amount + $transactions),
            ]);
        }

        AccountTransaction::where([
                'voucher_id'  => $request->id
            ])
            ->where(function($query) {
                $query->where('module_code', 'Receipt_VOUCHER')
                ->orWhere('module_code', 'PATHOLOGY_LAB_BILLING')
                ->orWhere('module_code', 'Pathology')
                ->orWhere('module_code', 'PATHOLOGY');
            })
            ->delete();

        $Redirect = 'receipt-voucher';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function searchAccounts(Request $request)
    {
        $searchTerm = $request->search_text;
        $results    = Account::select(['accounts.id','accounts.name'])
                    ->where('accounts.name', 'LIKE', '%' . $searchTerm . '%')
                    ->get();
        return response()->json(['result' => $results, 'status' => true]);
    }

    public function receiptVoucherEntries(Request $request)
    {
        $page = isset($request->page) && $request->page == 'billing' ? 1 : 0;
        $data = Session::get('receipt_voucher_details') ?? [];
        return view('accounting-receipt-vouchers.receipt-voucher-entries', compact('data', 'page'));
    }

    public function editReceiptVoucherEntries(Request $request)
    {
        $page = isset($request->page) && $request->page == 'billing' ? 1 : 0;
        $data = Session::get('receipt_voucher_details') ?? [];
        return view('accounting-receipt-vouchers.edit-receipt-voucher-entries', compact('data', 'page'));
    }

    public function addReceiptVouchers(Request $request)
    {
        $data = Session::get('receipt_voucher_details') ?? [];
        //dd($request);exit;

        if (!isset($data['receipt_no']) || $data['receipt_no'] == '') {
            $data['receipt_no'] = $request->receipt_no;
        }
        if (!isset($data['receipt_date']) || $data['receipt_date'] == '') {
            $data['receipt_date'] = Carbon::parse($request->receipt_date)->format('Y-m-d');
            
        }

        if (!isset($data['receipt_at_id']) || $data['receipt_at_id'] == '') {
            $data['receipt_at_id'] = $request->receipt_at_id ?? '';
        }

        if (!isset($data['receipt_at']) || $data['receipt_at'] == '') {
            $data['receipt_at'] = $request->receipt_at ?? '';
        }

        if (!isset($data['remarks']) || $data['remarks'] == '') {
            $data['remarks'] = $request->remarks ?? '';
        }

        $created_by = Auth::user()->id ?? '';

        $moduleReceipt = MenuModelPermission::where('code','Receipt_VOUCHER')->first();
        $data['receipt_voucher_entries'][] = [
            'module_id'             => $moduleReceipt->id ?? '',
            'voucher_type'          => 'Receipt Voucher',
            'account_id'            => $request->account_id ?? '',
            'transaction_type'      => 'CREDIT',
            'amount'                => (isset($request->amount) && $request->amount>0 ? $request->amount : 0),
            'created_by'            => Auth::user()->id ?? '',
            'company_id'            => Auth::user()->company_id ?? '',
            'amount'                 => $request->amount ?? '',
            'transactions_status'   => true,
            'account_name'          => $request->account_name ?? '',
        ];
        Session::put('receipt_voucher_details', $data);

        return response()->json([ 'success' => true,'message'=> 'Receipt Voucher Entry Added Successfully!'  ]);
    }

    public function editReceiptVouchers(Request $request)
    {
        $data = Session::get('receipt_voucher_details') ?? [];

        if (!isset($data['receipt_no']) || $data['receipt_no'] == '') {
            $data['receipt_no'] = $request->receipt_no;
        }
        if (!isset($data['receipt_date']) || $data['receipt_date'] == '') {
            $data['receipt_date'] = $request->receipt_date;
        }

        if (!isset($data['financial_year_id']) || $data['financial_year_id'] == '') {
            $data['financial_year_id'] = $request->financial_year_id ?? '';
        }

        if (!isset($data['account_id']) || $data['account_id'] == '') {
            $data['account_id'] = $request->account_id ?? '';
        }

        if (!isset($data['account_name']) || $data['account_name'] == '') {
            $data['account_name'] = $request->account_name ?? '';
        }

        if (!isset($data['debit']) || $data['debit'] == '') {
            $data['debit'] = $request->debit ?? 0;
        }

        if (!isset($data['credit']) || $data['credit'] == '') {
            $data['credit'] = $request->credit ?? '0';
        }

        if (!isset($data['details_narration']) || $data['details_narration'] == '') {
            $data['details_narration'] = $request->details_narration ?? '';
        }

        if (!isset($data['description']) || $data['description'] == '') {
            $data['description'] = $request->description ?? '';
        }

        $company_id      = Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select(

            'countries.code as country_code',
            'companies_addresses.country_id',
            'companies_addresses.state_id',
            'companies_addresses.city_id',
            'country_currencies.id as currency_id',
        )
        ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
        ->leftjoin('country_currencies', 'country_currencies.country_id', 'companies_addresses.country_id')
        ->where('companies_addresses.company_id', $company_id)
        ->first();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCurrencyId = $company_address->currency_id ?? '0';

        $moduleReceipt = MenuModelPermission::where('code','Receipt_VOUCHER')->first();
        $data['edit_receipt_voucher_entries'][] = [
            'transactions_no'     => 0,
            'receipt_date'        => $request->receipt_date ?? '',
            'module_id'           => $moduleReceipt->id ?? '',
            'voucher_type'        => 'Receipt',
            'account_id'          => $request->account_id ?? '',
            'transaction_type'    => (isset($request->debit) && $request->debit>0 ? 'DEBIT': 'CREDIT'),
            'details_narration'   => $request->details_narration ?? '',
            'amount'              => (isset($request->debit) && $request->debit>0 ? $request->debit : $request->credit),
            'created_by'          => Auth::user()->id ?? '',
            'company_id'          => Auth::user()->company_id ?? '',
            'currency_id'         => $countryCurrencyId,
            'financial_year_id'   => $request->financial_year_id ?? '',
            'debit'               => $request->debit ?? '',
            'credit'              => $request->credit ?? '',
            'transactions_status' => true,
            'account_name'        => $request->account_name ?? '',
        ];
        Session::put('receipt_voucher_details', $data);

        return response()->json([ 'success' => true,'message'=> 'New Receipt Voucher Entry Added Successfully!'  ]);
    }

    public function cartProductRemove(Request $request)
    {
        $data = Session::get('billing_products_cart') ?? [];
        $id   = $request->id;

        $amount = $data['amount'];

        $data['products'] = array_filter($data['products'], function ($product) use ($id, &$data, &$amount) {
            if ($product['product_id'] == $id) {
                $amount = $data['amount'] - $product['amount'];
            }

            return $product['product_id'] != $id;
        });

        if (count($data['products']) == 0) {
            $data['amount'] = 0;
        } else {
            $data['amount'] = $amount;
        }

        Session::put('billing_products_cart', $data);

        return response()->json([ 'success' => true ]);
    }

    public function cartProductUpdate(Request $request)
    {
        $data = Session::get('billing_products_cart') ?? [];

        if (isset($request->type) && $request->type == 'billing') {
            if (isset($request->invoice_date)) {
                $data['invoice_date'] = date('Y-m-d', strtotime($request->invoice_date));
            }

            if (isset($request->payment_mode)) {
                $data['payment_mode'] = $request->payment_mode;
            }

            if (isset($request->special_discount)) {
                $data['special_discount'] = $request->special_discount;
            }

            if (isset($request->discount_type)) {
                $data['discount_type'] = $request->discount_type;
            }

            if (isset($request->amount_recieved)) {
                $data['amount_recieved'] = $request->amount_recieved;
            }

            if (isset($request->special_discount) || isset($request->discount_type) || isset($request->amount_recieved)) {
                if ($data['discount_type'] == 'FLAT') {
                    $due_balance_amount = $data['amount'] - $data['special_discount'];
                    $data['due_balance_amount'] = $due_balance_amount - $data['amount_recieved'];
                } else {
                    $flat_discount = ($data['special_discount'] / 100) * $data['amount'];
                    $due_balance_amount = $data['amount'] - $flat_discount;
                    $data['due_balance_amount'] = $due_balance_amount - $data['amount_recieved'];
                }
            }
        } else {
            foreach ($data['products'] as $key => $value) {
                if ($value['product_id'] == $request->id && isset($request->product_details)) {
                    $data['products'][$key]['product_details'] = $request->product_details;
                }
                if ($value['product_id'] == $request->id && isset($request->vial_code)) {
                    $data['products'][$key]['vial_code'] = $request->vial_code;
                }
                if ($value['product_id'] == $request->id && isset($request->product_price)) {
                    $old_price = $data['products'][$key]['amount'];
                    $data['products'][$key]['product_price'] = $request->product_price;

                    $flat_discount   = ($value['per_discount'] / 100) * $request->product_price;
                    $data['products'][$key]['amount'] = $new_price = number_format($request->product_price - $flat_discount, 2, '.', '');
                    $data['products'][$key]['flat_discount'] = number_format($flat_discount, 2, '.', '');
                    $data['amount'] += ($new_price - $old_price);
                    $data['due_balance_amount'] = $data['amount'];
                }
                if ($value['product_id'] == $request->id && isset($request->per_discount)) {
                    $old_price = $data['products'][$key]['amount'];
                    $per_discount = $request->per_discount;
                    $data['products'][$key]['per_discount'] = number_format($per_discount, 2, '.', '');

                    $flat_discount = ($per_discount / 100) * $data['products'][$key]['product_price'];
                    $data['products'][$key]['amount'] = $new_price = number_format($data['products'][$key]['product_price'] - $flat_discount, 2, '.', '');
                    $data['products'][$key]['flat_discount'] = number_format($flat_discount, 2, '.', '');
                    $data['amount'] += ($new_price - $old_price);
                    $data['due_balance_amount'] = $data['amount'];
                }
                if ($value['product_id'] == $request->id && isset($request->flat_discount)) {
                    $old_price = $data['products'][$key]['amount'];
                    $per_discount  = ($request->flat_discount / $data['products'][$key]['product_price']) * 100;
                    $data['products'][$key]['per_discount']  = number_format($per_discount, 2, '.', '');
                    $data['products'][$key]['amount'] = $new_price = number_format($data['products'][$key]['product_price'] - $request->flat_discount, 2, '.', '');
                    $data['products'][$key]['flat_discount'] = number_format($request->flat_discount, 2, '.', '');
                    $data['amount'] += ($new_price - $old_price);
                    $data['due_balance_amount'] = $data['amount'];
                }
            }
        }

        Session::put('billing_products_cart', $data);

        return response()->json([ 'success' => true , 'data' => $data]);
    }
    public function print($id)
    {
        return view('lab-billings.print');
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('voucher_status' => $request->status );
            $Update = AcReceipt::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Receipt Voucher status successfully change'],
                    'data'=>[
                       'redirect'=>'/receipt-voucher/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function receiptVoucherEntryRemove(Request $request)
    {
        $index   = $request->id;
        $event_data_display = Session::get('receipt_voucher_details');
        unset($event_data_display['receipt_voucher_entries'][$index]);
        Session::put('receipt_voucher_details', $event_data_display);

        return response()->json([ 'success' => true,'message'=> 'Receipt Voucher Entry Removed Successfully!']);
    }


    public function editReceiptVoucherEntryRemove(Request $request)
    {
        $index   = $request->id;
        $event_data_display = Session::get('receipt_voucher_details');
        unset($event_data_display['edit_receipt_voucher_entries'][$index]);
        Session::put('receipt_voucher_details', $event_data_display);

        return response()->json([ 'success' => true,'message'=> 'Edit Receipt Voucher Entry Removed Successfully!','data'=>$event_data_display]);
    }

    public function printReceiptVoucher(Request $request, $id)
    {
        $redirect = $request->redirect ?? '';
        $accountReceipt = AcReceipt::with('company','user','accountReceiptDetail','accountReceiptTransaction','accountReceiptTransaction.company','accountReceiptTransaction.user','accountReceiptTransaction.account','accountReceiptTransaction.module')
            ->where(['id'=>$id])
            ->first();

        $redirect = \Session::get('redirect') ?? '';
        \Session::put('redirect', '');

        $company_letter_head = \App\Models\CompanyImage::select('*')
            ->where('company_id', $accountReceipt->company_id)
            ->where('image_type', 'header')
            ->where('status', '1')
            ->first();

        $company_footer = \App\Models\CompanyImage::select('*')
            ->where('company_id', $accountReceipt->company_id)
            ->where('image_type', 'footer')
            ->where('status', '1')
            ->first();

        return view('invoice-formats.receipt-voucher.receipt-voucher', compact('accountReceipt','redirect','company_letter_head','company_footer'));

        $pdfData  = [
            'accountReceipt' => $accountReceipt
        ];

        $pdf = PDF::loadView('invoice-formats.receipt-voucher.receipt-voucher', $pdfData)->set_option("isPhpEnabled", true)
            ->setPaper('a4', 'portrait')
            ->setWarnings(false);

        $filename = "Receipt-voucher_" . date("Y_m_d_i_H") . ".pdf";

        return $pdf->download($filename);

    }

    public function receiptVoucherStatement(Request $request)
    {

        $company = Company::find(Auth::user()->company_id);
        $voucher_type = VoucherType::where('code', 'RECEIPT')->where(['status' => 1])->first();
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        if($request->ajax()) 
        {
            $filters['from_date']           = $from_date       = $request->from_date?Carbon::createFromFormat($this->companyDateFormate(), $request->from_date)->format('Y-m-d'):date('Y-m-d');
            $filters['to_date']             = $to_date         = $request->to_date?Carbon::createFromFormat($this->companyDateFormate(), $request->to_date)->format('Y-m-d'):date('Y-m-d');
            $filters['branch']              = $branch          = $request->branch ?? '';
            $filters['account']             = $account         = $request->account ?? '';
            $filters['paymentMode']         = $paymentMode     = $request->paymentMode ?? '';
            $filters['accountingGroup']     = $accountingGroup = $request->accountingGroup ?? '';
            $filters['created_by']          = $created_by      = $request->created_by??'';
            $filters['voucher_type_search'] = $voucher_type_search    = $request->voucher_type??'';

            $accountReceipt = $this->queryFilterold($request);
            $accountReceipt = AcReceipt::getReceiptVouchers($filters);

            // return view('invoice-formats.receipt-voucher.statement-table', compact( 
            //     'from_date',
            //     'to_date',
            //     'branch',
            //     'account',
            //     'accountReceipt',
            //     'company',
            //     'voucher_type',
            // ));
            return response()->json([
                'status'      => true,
                'from_date'      => $from_date,
                'to_date'        => $to_date,
                'branch'         => $branch,
                'account'        => $account,
                'accountReceipt' => $accountReceipt,
                'company'        => $company,
                'voucher_type'   => $voucher_type,
            ]);

            return view('invoice-formats.receipt-voucher.statement-table', compact( 
                'from_date',
                'to_date',
                'branch',
                'account',
                'accountReceipt',
                'company',
                'voucher_type',
            ));
        }

        return view('invoice-formats.receipt-voucher.statement', compact(
            'company',
            'voucher_type',
            'companyDateFormate',
        ));
    }


    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');
        $data = $this->queryFilter($request);
        $fileName = 'Receipt-Voucher-Statements'.' From '.$from_date.' To '.$to_date.'.xlsx';
        return Excel::download(new ReceiptVoucherExport($data->toArray()), $fileName);
    }
    function queryFilter(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');
            $branch          = $request->branch ?? '';
            $account         = $request->account ?? '';
            $paymentMode     = $request->payment_mode ?? '';
            $created_by      = $request->created_by??'';
            $voucher_type_search    = $request->voucher_type??'';
            // \DB::enableQueryLog();
            $accountReceipt  = AcReceipt::
                select(['ac_receipts.receipt_no',
                        'ac_receipts.receipt_date',
                        'ac_receipts.company_id',
                        'ac_receipts.voucher_id',
                        'ac_receipts.module_code',
                        'ac_receipts.receipt_time',
                        'ac_receipts.id',
                        'U.prepared_by',
                        'ac_details.amount',
                        'ac_details.transaction_type',
                        'voucher_types.name as voucher_type_name',
                        'payment_modes.mode',
                        'transaction_account.name as transaction_account_name'
                ])
                ->leftJoin('users as U','U.id','=','ac_receipts.created_by')
                ->leftJoin('ac_receipt_details as ac_details','ac_details.voucher_id','=','ac_receipts.id')
                ->leftJoin('accounts as transaction_account','transaction_account.id','=','ac_details.account_id')
                ->leftJoin('voucher_types','voucher_types.code','=','ac_details.voucher_type')
                ->leftJoin('payment_modes','payment_modes.id','=','ac_details.transaction_mode_id')
                
            //     ->with(
            //     // 'accountReceiptDetail',
            //     // 'accountReceiptDetail.transaction_mode',
            //     'accountReceiptTransaction',
            //     'accountReceiptTransaction.account',
            // )
            ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
                $query->whereBetween('ac_receipts.receipt_date', [
                    date('Y-m-d', strtotime($from_date)),
                    date('Y-m-d', strtotime($to_date))
                ]);
            })
            ->when($branch != '', function($query) use($branch) {
                $query->where('ac_receipts.company_id', $branch);
            })
            ->when($account != '', function($query) use($account) {
                // $query->whereHas('accountReceiptDetail', function ($query) use ($account) {
                    $query->where('ac_details.account_id', $account);
                // });
            })

            ->when($created_by != '', function($query) use($created_by) {
                    $query->where('ac_receipts.created_by', $created_by);
            })

            ->when($voucher_type_search != '', function($query) use($voucher_type_search) {
                // $query->whereHas('accountReceiptDetail', function ($query) use ($voucher_type_search) {
                    $query->where('ac_details.voucher_type', $voucher_type_search);
                // });
            })

            ->when($paymentMode != '', function($query) use($paymentMode) {
                // $query->whereHas('accountReceiptDetail', function ($query) use ($paymentMode) {
                    $query->where('ac_details.transaction_mode_id', $paymentMode);
                // });
            })
            
            ->get();
            // dd($accountReceipt); 
            //  dd(\DB::getQueryLog()); 

            return $accountReceipt;

    }

    function queryFilterold(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');
            $branch          = $request->branch ?? '';
            $account         = $request->account ?? '';
            $paymentMode     = $request->payment_mode ?? '';
            $created_by      = $request->created_by??'';
            $voucher_type_search    = $request->voucher_type??'';
            // \DB::enableQueryLog();
            $accountReceipt  = AcReceipt::
                select(['ac_receipts.receipt_no',
                        'ac_receipts.receipt_date',
                        'ac_receipts.company_id',
                        'ac_receipts.voucher_id',
                        'ac_receipts.module_code',
                        'ac_receipts.receipt_time',
                        'ac_receipts.id',
                        'U.prepared_by',
                ])
                ->leftJoin('users as U','U.id','=','ac_receipts.created_by')
                
                ->with(
                'accountReceiptDetail',
                'accountReceiptDetail.transaction_mode',
                'accountReceiptTransaction',
                'accountReceiptTransaction.account',
            )
            ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
                $query->whereBetween('ac_receipts.receipt_date', [
                    date('Y-m-d', strtotime($from_date)),
                    date('Y-m-d', strtotime($to_date))
                ]);
            })
            ->when($branch != '', function($query) use($branch) {
                $query->where('ac_receipts.company_id', $branch);
            })
            ->when($account != '', function($query) use($account) {
                $query->whereHas('accountReceiptDetail', function ($query) use ($account) {
                    $query->where('ac_receipt_details.account_id', $account);
                });
            })

            ->when($created_by != '', function($query) use($created_by) {
                    $query->where('ac_receipts.created_by', $created_by);
            })

            ->when($voucher_type_search != '', function($query) use($voucher_type_search) {
                $query->whereHas('accountReceiptDetail', function ($query) use ($voucher_type_search) {
                    $query->where('ac_receipt_details.voucher_type', $voucher_type_search);
                });
            })

            ->when($paymentMode != '', function($query) use($paymentMode) {
                $query->whereHas('accountReceiptDetail', function ($query) use ($paymentMode) {
                    $query->where('ac_receipt_details.transaction_mode_id', $paymentMode);
                });
            })
            
            ->get();
            // dd($accountReceipt); 
            //  dd(\DB::getQueryLog()); 

            return $accountReceipt;

    }


    public function searchAccount(Request $request)
    {
        $searchTerm = $request->search_text;
        $results    = Account::select([
            'accounts.id',
            'accounts.code',
            \DB::raw("
                CONCAT(
                    COALESCE(account_titles.name, ''),
                    CASE WHEN account_titles.name IS NOT NULL AND accounts.name IS NOT NULL THEN ' ' ELSE '' END,
                    COALESCE(accounts.name, '')
                ) AS name
                "),
            \DB::raw("account_contacts.phone_no as phone_no"),
            \DB::raw("genders.name as gender"),
            \DB::raw("account_contacts.date_of_birth")
        ])
            ->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')
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->whereIN('account_types.type_code', ['CUSTOMER','PATIENT','DOCTOR'])
            ->where(function ($query) use ($searchTerm) {
                $query->where('accounts.name', 'LIKE', '%' .$searchTerm . '%')
                    ->orWhere('account_contacts.phone_no', 'LIKE','%' . $searchTerm . '%')
                    ->orWhere('accounts.code', 'LIKE','%' . $searchTerm . '%');
            })
            ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }

}
