<?php

namespace App\Http\Controllers\Accounting;

use App\Exports\FinancialAccountVoucher\PaymentVoucherExport;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CompanyAddress;
use App\Models\Account;
use App\Models\ProductBrand;
use App\Models\Product;
use App\Models\PaymentMode;
use App\Models\SaleInvoice;
use App\Models\SaleInvoiceType;
use App\Models\SaleInvoiceDetail;
use App\Models\ProductPrice;
use App\Models\ProductTestPackage;
use App\Models\SaleInvoiceSubDetails;
use App\Models\SpecialCase;
use App\Models\FinancialYear;
use App\Models\AcReceipt;
use App\Models\PaymentVoucher;
use App\Models\PaymentVoucherDetail;
use App\Models\AccountTransaction;
use App\Models\VoucherCollection;
use App\Models\VoucherCollectionDetail;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use App\Models\Company;
use App\Models\MenuModelPermission;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class PaymentVouchersController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:payment-voucher-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('PAYMENT_VOUCHER')) {
            abort(404);
        }

        $data = PaymentVoucher::with('paymentVoucherDetail');

        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 == 'paid_to') {
                        $query->whereHas('paymentVoucherDetail.account', function ($query) use ($search_query, $search_type) {
                            $query->where('accounts.name', 'like', '%'.$search_query.'%');
                        });
                    }
                })
                ->latest()
                ->paginate($sort_by);

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

            return view('payment-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');

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

        return view('payment-vouchers.create', compact('accounting_group','financialYears','countryCode','companyDateFormate'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function receiptVoucherSubmit(Request $request, $id = '')
    {
        $validator = \Validator::make($request->all(), [
            'financial_year_id'    => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'PAYMENT')->where(['status' => 1])->first();
        $voucher_type   = VoucherType::with('voucherSeries')->where('code', 'PAYMENT')->where(['status' => 1])->first();

        # last voucher count for main invoice number
        $voucher_count      = PaymentVoucher::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 ?? 'PV'),
            ($voucher_master->voucherSeries->postfix ?? ''),
            ($voucher_master->voucherSeries->separator ?? '-'),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        # last voucher count for main voucher type invoice number
        $voucher_type_last_count      = PaymentVoucher::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 ?? 'PV'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );

        $module      = MenuModelPermission::where('code','PAYMENT_VOUCHER')->first();
        $module_id   = ($module->id ?? '');
        $module_code = ($module->code ?? 'PAYMENT_VOUCHER');

        $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'              => $id,
            'module_code'             => $module_code,
            'receipt_time'            => Carbon::now(),
        ];

        $receiptVoucher = PaymentVoucher::create($item);

        $item1 = [
           'module_code'         => $module_code,
           'voucher_type'        => 'PAYMENT',
           'voucher_master_id'   => $voucher_master->id ?? '',
           'voucher_id'          => $receiptVoucher->id ?? '',
           'account_id'          => $request->account_id ?? '',
           'transaction_type'    => 'DEBIT',
           'details_narration'   => "",
           'amount'              => $request->total_amount,
           'created_by'          => Auth::user()->id ?? '',
           'company_id'          => Auth::user()->company_id ?? '',
           'transaction_date'    => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
           'financial_year_id'   => $request->financial_year_id,
           'transactions_status' => true
        ];
        $acReceiptTransaction = PaymentVoucherDetail::create($item1);
        $transactions_no = $this->generateRandomCode();

        $voucher_collection = VoucherCollection::create([
            'collection_date'   => date('Y-m-d'),
            'module_code'       => 'PAYMENT_VOUCHER',
            'voucher_master_id' => $voucher_master->id ?? '',
            'voucher_id'        => $receiptVoucher->id,
            'voucher_type'      => 'PAYMENT',
            '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_code'            => $module_code,
                       'voucher_id'             => $receiptVoucher->id,
                       'voucher_master_id'      => $voucher_master->id ?? '',
                       'voucher_type'           => 'PAYMENT',
                       'account_id'             => $key,
                       'payment_mode_id'        => $key,
                       'transaction_type'       => 'CREDIT',
                       'details_narration'      => '',
                       'amount'                 => $item['amount'],
                       'created_by'             => Auth::user()->id,
                       'company_id'             => Auth::user()->company_id,
                       'transaction_referrence' => $item['transaction_referrence'],
                       'transaction_date'       => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                       'transaction_mode_id'    => $item['transaction_mode_id'] ?? '',
                       'transactions_status'    => true,
                       'financial_year_id'   => $request->financial_year_id,
                    ];
                    $acReceiptTransaction = PaymentVoucherDetail::create($item1);

                    $transactions_no = $this->generateRandomCode();
                    $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'       => 'PAYMENT_VOUCHER',
                        'voucher_id'        => $receiptVoucher->id,
                        'voucher_type'      => 'PAYMENT',
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'account_id'        => $request->account_id,
                        'transaction_type'  => 'DEBIT',
                        'details_narration' => '',
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                        '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'       => 'PAYMENT_VOUCHER',
                        'voucher_id'        => $receiptVoucher->id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'PAYMENT',
                        'account_id'        => $key ?? '',
                        'transaction_type'  => 'CREDIT',
                        'details_narration' => '',
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                        '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'=> 'Payment 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');
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $paymentVoucher = PaymentVoucher::with(
                'company',
                'paymentVoucherDetails',
                'paymentVoucherDetails.company',
                'paymentVoucherDetails.user',
                'paymentVoucherDetails.account',
                'paymentVoucherDetails.module'
            )
            ->where(['id' => $id])->first();

        return view('payment-vouchers.show', compact('paymentVoucher'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data              = PaymentVoucher::find($id);
        $creditTransaction = PaymentVoucherDetail::with('account')
                ->where(['voucher_id' => $id, 'transaction_type' => 'CREDIT'])
                ->get();

        $debitTransaction = PaymentVoucherDetail::with('account')
                ->where(['voucher_id' => $id, 'transaction_type' => 'DEBIT'])
                ->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('payment-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 = PaymentVoucher::find($id);

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

        $item = [
            'receipt_date'      => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
            '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,
           'transaction_date'       => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
        ];

        $acDEBITReceiptTransaction = PaymentVoucherDetail::where([
                'transaction_type' => 'DEBIT',
                '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]);

        $module      = MenuModelPermission::where('code','PAYMENT_VOUCHER')->first();
        $module_id   = ($module->id ?? '');
        $module_code = ($module->code ?? 'PAYMENT_VOUCHER');
        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'PAYMENT')->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_code'            => $module_code,
                        'voucher_id'             => $id,
                        'voucher_type'           => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'account_id'             => $key,
                        'transaction_type'       => 'CREDIT',
                        'details_narration'      => '',
                        'amount'                 => $item['amount'],
                        'transaction_referrence' => $item['transaction_referrence'],
                        'created_by'             => Auth::user()->id,
                        'company_id'             => Auth::user()->company_id,
                        'transaction_date'       => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'transactions_status'    => true,
                        'voucher_master_id'      => $voucher_master->id ?? '',
                        'financial_year_id'      => $request->financial_year_id,
                        'transaction_mode_id'    => $item['transaction_mode_id'] ?? '',
                    ];
                    $acReceiptTransaction = PaymentVoucherDetail::create($item1);

                    $transactions_no = $this->generateRandomCode();

                    $transaction = AccountTransaction::createTransaction([
                        'transactions_no'   => $transactions_no,
                        'transaction_date'  => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'module_code'       => 'PAYMENT_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'account_id'        => $key ?? '',
                        'transaction_type'  => 'CREDIT',
                        'details_narration' => '',
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);

                    $transaction = AccountTransaction::createTransaction([
                        'transactions_no'   => $transactions_no,
                        'transaction_date'  => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'module_code'       => 'PAYMENT_VOUCHER',
                        'voucher_id'        => $id,
                        'voucher_sub_id'    => $acReceiptTransaction->id,
                        'voucher_type'      => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'account_id'        => $request->account_id ?? '',
                        'transaction_type'  => 'DEBIT',
                        'details_narration' => '',
                        'amount'            => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);

                    $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_code'            => $module_code,
                        'voucher_type'           => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'transaction_type'       => 'CREDIT',
                        'details_narration'      => '',
                        'amount'                 => $item['amount'],
                        'created_by'             => Auth::user()->id,
                        'company_id'             => Auth::user()->company_id,
                        'transaction_date'       => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'transaction_referrence' => $item['transaction_referrence'],
                        'transactions_status'    => true,
                        'voucher_master_id'      => $voucher_master->id ?? '',
                        'transaction_mode_id'    => $item['transaction_mode_id'] ?? '',
                    ];

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

                    $transaction = AccountTransaction::updateTransaction([
                        'module_code'      => 'PAYMENT_VOUCHER',
                        'voucher_id'       => $id,
                        'voucher_sub_id'   => $key,
                        'voucher_type'     => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'transaction_type' => 'CREDIT',
                    ],[
                        'transaction_date' => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'amount'           => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);

                    AccountTransaction::updateTransaction([
                        'module_code'      => 'PAYMENT_VOUCHER',
                        'voucher_id'       => $id,
                        'voucher_type'     => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'transactions_no'  => $transaction->transactions_no,
                        'transaction_type' => 'DEBIT',
                        'account_id'        => $request->account_id ?? '',
                    ],[
                        'transaction_date' => Carbon::createFromFormat($this->companyDateFormate(), $request->receipt_date)->format('Y-m-d'),
                        'amount'           => $item['amount'],
                        'financial_year_id' => $request->financial_year_id,
                    ]);

                } else {
                    PaymentVoucherDetail::where([
                        'id'         => $key,
                        'voucher_id' => $id
                    ])->delete();

                    $transaction = AccountTransaction::where([
                        'module_code'      => 'PAYMENT_VOUCHER',
                        'voucher_id'       => $id,
                        'voucher_sub_id'   => $key,
                        'voucher_type'     => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'transaction_type' => 'CREDIT',
                    ])->first();

                    AccountTransaction::where([
                        'module_code'      => 'PAYMENT_VOUCHER',
                        'voucher_id'       => $id,
                        'voucher_type'     => 'PAYMENT', // SALE, PURCHASE, PAYMENT
                        'transactions_no'  => $transaction->transactions_no,
                        'transaction_type' => 'DEBIT',
                        'account_id'       => $request->account_id ?? '',
                    ])->delete();

                    $transaction->delete();
                }
            }
        }

        return redirect()->route('payment-voucher.index')->with('success', 'Payment Voucher Updated Successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = PaymentVoucher::find($request->id);
        $data->delete();

        PaymentVoucherDetail::where(['voucher_id' => $request->id])->delete();
        AccountTransaction::where([
                'module_code' => 'PAYMENT_VOUCHER',
                'voucher_id'  => $request->id
            ])->delete();

        $Redirect = 'payment-voucher';

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

    public function printPaymentVoucher($id)
    {
        $paymentVoucher = PaymentVoucher::with(
                'company',
                'paymentVoucherDetail',
                'paymentVoucherDetails.company',
                'paymentVoucherDetails.user',
                'paymentVoucherDetails.account',
                'paymentVoucherDetails.module'
            )
            ->where(['id' => $id])
            ->first();

        return view('invoice-formats.payment-voucher.payment-voucher', compact('paymentVoucher'));

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

        $pdf = PDF::loadView('invoice-formats.payment-voucher.payment-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 paymentVoucherStatement(Request $request)
    {
        $company = Company::find(Auth::user()->company_id);
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        if ($request->ajax()) {
        $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 ?? '';
        $created_by      = $request->created_by??'';
        $paymentVoucher = $this->queryFilter($request);
            return view('invoice-formats.payment-voucher.statement-table', compact('from_date','to_date','paymentVoucher','company'));
        }

        
        $voucher_type = VoucherType::where('code', 'PAYMENT')->where(['status' => 1])->first();

        return view('invoice-formats.payment-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 = 'Payment-Voucher-Statements'.' From '.$from_date.' To '.$to_date.'.xlsx';
        return Excel::download(new PaymentVoucherExport($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 ?? '';
        $created_by      = $request->created_by??'';
        $voucher_type_search    = $request->voucher_type??'';
        $payment_mode    = $request->payment_mode??'';

        $paymentVoucher = PaymentVoucher::with(
                'company',
                'paymentVoucherDetail',
                'paymentVoucherDetails.company',
                'paymentVoucherDetails.user',
                'paymentVoucherDetails.account',
                'paymentVoucherDetails.module'
            )
            ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
                $query->whereBetween('payment_vouchers.receipt_date', [
                    date('Y-m-d', strtotime($from_date)),
                    date('Y-m-d', strtotime($to_date))
                ]);
            })
            ->when($branch != '', function($query) use($branch) {
                $query->where('payment_vouchers.company_id', $branch);
            })
            ->when($created_by != '', function($query) use($created_by) {
                $query->where('created_by', $created_by);
            })
            ->when($payment_mode != '', function($query) use($payment_mode) {
                $query->whereHas('paymentVoucherDetails', function ($query) use ($payment_mode) {
                    $query->where('payment_voucher_details.transaction_mode_id', $payment_mode);
                });
            })
            ->when($account != '', function($query) use($account) {
                $query->whereHas('paymentVoucherDetails', function ($query) use ($account) {
                    $query->where('payment_voucher_details.account_id', 'like', '%'.$account.'%');
                });
            })
            ->groupBy('payment_vouchers.id')
            ->get();
        return $paymentVoucher;
    }
}
