<?php

namespace App\Traits;

use App\Models\VoucherCollectionDetail;
use App\Models\MenuModelPermission;
use App\Models\AccountTransaction;
use App\Models\VoucherCollection;
use App\Models\AcReceiptDetail;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use App\Models\AcReceipt;
use App\Models\Sales\SaleReturnOthersTransactions;
use Carbon\Carbon;

trait ReturnAccountLaggerTransactionTrait
{

    public function createAcReceiptAndTransaction(
        $payment_mode_id,
        $account_id,
        $amount,
        $transaction_id,
        $voucher_id,
        $module_code,
        $paymentMode,
        $paymentType,
    ) {

        if ($paymentType == 'advance') {
            $advanceReceived        = 'Yes';
            $settlementStatus       = 'No';
        } else {
            $advanceReceived        = 'No';
            $settlementStatus       = 'Yes';
        }
        $module   = VoucherType::select('id', 'code')
        ->with('voucherSeries')
        ->where('code', $module_code)
        ->first();

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

        $voucher_type = VoucherType::select('id', 'code')
            ->with('voucherSeries')
            ->where('code', 'RECEIPT')
            ->first();

        # last voucher count for main receipt number
        $voucher_count      = AcReceipt::select('last_voucher_count', 'last_voucher_type_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);

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

        # last voucher count for main voucher type receipt number
        $voucher_type_count = isset($voucher_count) && isset($voucher_count->last_voucher_type_count) ? $voucher_count->last_voucher_type_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);

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

        $loginFinancialyear = \Session::get('user_financial_year_id') ?? '';

        $receipt = AcReceipt::create([
            'receipt_no'              => ($receipt_no ?? ''),
            'overall_receipt_no'      => ($overall_receipt_no ?? ''),
            'receipt_date'            => date('Y-m-d'),
            'company_id'              => \Auth::user()->company_id ?? '',
            'created_by'              => \Auth::id() ?? '',
            'voucher_id'              => $voucher_id, // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_status'          => true,
            'last_voucher_count'      => $last_voucher_count,
            'last_voucher_type_count' => $voucher_type_count,
            'financial_year_id'       => $loginFinancialyear,
            'module_code'             => $module->code,
            'receipt_time'            => Carbon::now(),
            'advance_received'        => $advanceReceived,
            'settlement_status'       => $settlementStatus
        ]);


        $item1 = [
            'module_id'           => $module->id,
            'voucher_type'        => ($module_code ?? ''),
            'voucher_master_id'   => $voucher_master->id ?? '',
            'voucher_id'          => ($receipt->id ?? ''),
            'account_id'          => ($account_id ?? ''),
            'transaction_type'    => 'DEBIT',
            'details_narration'   => "",
            'amount'              => $amount,
            'created_by'          => \Auth::user()->id ?? '',
            'company_id'          => \Auth::user()->company_id ?? '',
            'financial_year_id'   => $loginFinancialyear,
            'transaction_date'    => date('Y-m-d'),
            'transactions_status' => true,
            'transaction_mode_id' => '7',
            'payment_mode_id'     => '1',
        ];
        $receipt_details_credit = AcReceiptDetail::create($item1);


        $voucher_collection = VoucherCollection::create([
            'collection_date'   => date('Y-m-d'),
            'module_code'       => 'RECEIPT',
            'voucher_master_id' => ($voucher_master->id ?? ''),
            'voucher_id'        => $receipt_no, // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_type'      => 'SALE_RETURN', // SALE, PURCHASE, PAYMENT
            'money_receipt_id'  => $receipt->id,
            'created_by'        => \Auth::user()->id,
        ]);
        


        if ($receipt) {
            if (isset($paymentMode) && count($paymentMode) > 0) {
                foreach ($paymentMode as $key => $item) {
                    if ($item['amount'] > 0) {

                    # last voucher count for main Transaction number
                    $transaction_voucher_count      = AccountTransaction::select('last_id')->orderBy('created_at', 'DESC')->first();
                    $transaction_voucher_master     = VoucherMaster::select('id')
                        ->with('voucherSeries')
                        ->where('voucher_code', 'TRANSACTION')
                        ->where(['status' => 1])
                        ->first();
                    $last_voucher_count = isset($transaction_voucher_count) && isset($transaction_voucher_count->last_id) ? $transaction_voucher_count->last_id + 1 : (isset($transaction_voucher_master) && $transaction_voucher_master->voucherSeries->start_from + 1 ?? 1);

                    $transactions_no = $this->generateCode(
                        $last_voucher_count,
                        ($transaction_voucher_master->voucherSeries->prefix ?? 'TRN'),
                        ($transaction_voucher_master->voucherSeries->postfix ?? ''),
                        ($transaction_voucher_master->voucherSeries->separator ?? '-'),
                        ($transaction_voucher_master->voucherSeries->length ?? 5)
                    );

                        $receipt_details = AcReceiptDetail::create([
                            'payment_mode_id'     => $item['mode_id'] ?? '',
                            'voucher_master_id'   => ($voucher_master->id  ?? ''),
                            'voucher_id'          => ($receipt->id ?? ''),
                            'voucher_type'        => ($module_code ?? ''),
                            'module_id'           => ($module->id ?? ''),
                            'account_id'          => $item['mode_id'] ?? '',
                            'transaction_type'    => 'CREDIT',
                            'details_narration'   => "",
                            'amount'              => ($item['amount'] ?? ''),
                            'transaction_referrence' => $item['transaction_referrence'] ?? '',
                            'transaction_mode_id'    => $item['transaction_mode_id'] ?? $item['mode_id'],
                            'created_by'          => \Auth::id() ?? '',
                            'company_id'          => \Auth::user()->company_id ?? '',
                            'transactions_status' => true,
                            'ac_receipt_id'       => $receipt->id,
                            'transaction_date'    => date('Y-m-d'),
                        ]);


                      


                        AccountTransaction::createTransaction([
                            'transactions_no'   => $transactions_no,
                            'transaction_date'  => date('Y-m-d'),
                            'module_code'       => $module_code,
                            'voucher_id'        => $receipt->id,
                            'voucher_type'      => ($voucher_type->code ?? ''),
                            'account_id'        => $item['mode_id']  ?? '',
                            'transaction_type'  => 'CREDIT',
                            'details_narration' => '',
                            'amount'            => $item['amount'],
                            'voucher_sub_id'    => $receipt_details_credit->id,
                            'financial_year_id' => $loginFinancialyear,
                            'last_id'           => $last_voucher_count,
                        ]);


                          # last voucher count for main Transaction number
                          $transaction_voucher_count      = AccountTransaction::select('last_id')->orderBy('created_at', 'DESC')->first();
                          $transaction_voucher_master     = VoucherMaster::select('id')
                              ->with('voucherSeries')
                              ->where('voucher_code', 'TRANSACTION')
                              ->where(['status' => 1])
                              ->first();
                              $last_voucher_count = isset($transaction_voucher_count) && isset($transaction_voucher_count->last_id) ? $transaction_voucher_count->last_id + 1 : (isset($transaction_voucher_master) && $transaction_voucher_master->voucherSeries->start_from + 1 ?? 1);
  
                          $transactions_no = $this->generateCode(
                              $last_voucher_count,
                              ($transaction_voucher_master->voucherSeries->prefix ?? 'TRN'),
                              ($transaction_voucher_master->voucherSeries->postfix ?? ''),
                              ($transaction_voucher_master->voucherSeries->separator ?? '-'),
                              ($transaction_voucher_master->voucherSeries->length ?? 5)
                          );

                        AccountTransaction::createTransaction([
                            'transactions_no'   => $transactions_no,
                            'transaction_date'  => date('Y-m-d'),
                            'module_code'       => $module_code,
                            'voucher_id'        => $receipt->id,
                            'voucher_type'      => ($voucher_type->code ?? ''),
                            'account_id'        => $account_id,
                            'transaction_type'  => 'DEBIT',
                            'details_narration' => '',
                            'amount'            => $item['amount'],
                            'voucher_sub_id'    => $receipt_details->id,
                            'financial_year_id' => $loginFinancialyear,
                            'last_id'           => $last_voucher_count,
                        ]);
                    }
                }
            }
        }

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

        return $receipt->id;
    }







    /*******************************Update Transaction all*************************/

    public function UpdateAcReceiptAndTransaction(
        $payment_mode_id,
        $account_id,
        $amount,
        $transaction_id,
        $voucher_id,
        $module_code,
        $paymentMode,
        $paymentType,
    ) {

        if ($paymentType == 'advance') {
            $advanceReceived        = 'Yes';
            $settlementStatus       = 'No';
        } else {
            $advanceReceived        = 'No';
            $settlementStatus       = 'Yes';
        }
        $module   = VoucherType::select('id', 'code')
        ->with('voucherSeries')
        ->where('code', $module_code)
        ->first();
        $voucher_master = VoucherMaster::select('id')
            ->with('voucherSeries')
            ->where('voucher_code', 'RECEIPT')
            ->where(['status' => 1])
            ->first();

        $voucher_type = VoucherType::select('id', 'code')
            ->with('voucherSeries')
            ->where('code', 'RECEIPT')
            ->first();
    

        # last voucher count for main receipt number
        $voucher_count      = AcReceipt::select('last_voucher_count', 'last_voucher_type_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);

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

        # last voucher count for main voucher type receipt number
        $voucher_type_count = isset($voucher_count) && isset($voucher_count->last_voucher_type_count) ? $voucher_count->last_voucher_type_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);

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

        $loginFinancialyear = \Session::get('user_financial_year_id') ?? '';

        $receipt = AcReceipt::create([
            'receipt_no'              => ($receipt_no ?? ''),
            'overall_receipt_no'      => ($overall_receipt_no ?? ''),
            'receipt_date'            => date('Y-m-d'),
            'company_id'              => \Auth::user()->company_id ?? '',
            'created_by'              => \Auth::id() ?? '',
            'voucher_id'              => $voucher_id, // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_status'          => true,
            'last_voucher_count'      => $last_voucher_count,
            'last_voucher_type_count' => $voucher_type_count,
            'financial_year_id'       => $loginFinancialyear,
            'module_code'             => $module->code,
            'receipt_time'            => Carbon::now(),
            'advance_received'        => $advanceReceived,
            'settlement_status'       => $settlementStatus
        ]);

        // Settlement Advanced Receipt Amount
        $acReceiptDataCheckAdvance = AcReceipt::select('id')->where([
            'voucher_id'        => $voucher_id,
            'module_code'       => $module->code,
            'settlement_status' => 'No'
        ])->get();
        if ($acReceiptDataCheckAdvance) {
            foreach ($acReceiptDataCheckAdvance as $list) {
                AcReceipt::find($list->id)->update([
                    'settlement_status'      => 'Yes',
                    'settlement_voucher_id'  => $voucher_id,
                    'settlement_module_code' => $module_code
                ]);
            }
        }


        $item1 = [
            'module_id'           => $module->id,
            'voucher_type'        => ($module_code ?? ''),
            'voucher_master_id'   => $voucher_master->id ?? '',
            'voucher_id'          => ($receipt->id ?? ''),
            'account_id'          => ($account_id ?? ''),
            'transaction_type'    => 'CREDIT',
            'details_narration'   => "",
            'amount'              => $amount,
            'created_by'          => \Auth::user()->id ?? '',
            'company_id'          => \Auth::user()->company_id ?? '',
            'financial_year_id'   => $loginFinancialyear,
            'transaction_date'    => date('Y-m-d'),
            'transactions_status' => true,
            'transaction_mode_id' => '7',
            'payment_mode_id'     => '1',
        ];
        $receipt_details_credit = AcReceiptDetail::create($item1);


        $voucher_collection = VoucherCollection::create([
            'collection_date'   => date('Y-m-d'),
            'module_code'       => $module->code,
            'voucher_master_id' => ($voucher_master->id ?? ''),
            'voucher_id'        => $receipt_no, // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_type'      => 'SALE_RETURN', // SALE, PURCHASE, PAYMENT
            'money_receipt_id'  => $receipt->id,
            'created_by'        => \Auth::user()->id,
        ]);

        if ($receipt) {

            if (isset($paymentMode) && count($paymentMode) > 0) {
                foreach ($paymentMode as $key => $item) {
                    if ($item['amount'] > 0) {


                        $receipt_details = AcReceiptDetail::create([
                            'payment_mode_id'     => $item['mode_id'] ?? '',
                            'voucher_master_id'   => ($voucher_master->id  ?? ''),
                            'voucher_id'          => ($receipt->id ?? ''),
                            'voucher_type'        => ($module_code ?? ''),
                            'module_id'           => ($module->id ?? ''),
                            'account_id'          => $item['mode_id'] ?? '',
                            'transaction_type'    => 'CREDIT',
                            'details_narration'   => "",
                            'amount'              => ($item['amount'] ?? ''),
                            'transaction_referrence' => $item['transaction_referrence'] ?? '',
                            'transaction_mode_id'    => $item['transaction_mode_id'] ?? '',
                            'created_by'          => \Auth::id() ?? '',
                            'company_id'          => \Auth::user()->company_id ?? '',
                            'transactions_status' => true,
                            'transaction_date'    => date('Y-m-d'),
                        ]);



                    # last voucher count for main Transaction number
                    $transaction_voucher_count      = AccountTransaction::select('last_id')->orderBy('created_at', 'DESC')->first();
                    $transaction_voucher_master     = VoucherMaster::select('id')
                        ->with('voucherSeries')
                        ->where('voucher_code', 'TRANSACTION')
                        ->where(['status' => 1])
                        ->first();
                    $last_voucher_count = isset($transaction_voucher_count) && isset($transaction_voucher_count->last_id) ?
                    $transaction_voucher_count->last_id + 1 : ($transaction_voucher_master->voucherSeries->start_from + 1 ?? 1);

                    $transactions_no = $this->generateCode(
                        $last_voucher_count,
                        ($transaction_voucher_master->voucherSeries->prefix ?? 'TRN'),
                        ($transaction_voucher_master->voucherSeries->postfix ?? ''),
                        ($transaction_voucher_master->voucherSeries->separator ?? '-'),
                        ($transaction_voucher_master->voucherSeries->length ?? 5)
                    );

                        AccountTransaction::createTransaction([
                            'transactions_no'   => $transactions_no,
                            'transaction_date'  => date('Y-m-d'),
                            'module_code'       => $module->code,
                            'voucher_id'        => $receipt->id,
                            'voucher_type'      => ($voucher_type->code ?? ''),
                            'account_id'        => $item['mode_id']  ?? '',
                            'transaction_type'  => 'CREDIT',
                            'details_narration' => '',
                            'amount'            => $item['amount'],
                            'voucher_sub_id'    => $receipt_details_credit->id
                        ]);

                        AccountTransaction::createTransaction([
                            'transactions_no'   => $transactions_no,
                            'transaction_date'  => date('Y-m-d'),
                            'module_code'       => $module->code,
                            'voucher_id'        => $receipt->id,
                            'voucher_type'      => ($voucher_type->code ?? ''),
                            'account_id'        => $account_id,
                            'transaction_type'  => 'DEBIT',
                            'details_narration' => '',
                            'amount'            => $item['amount'],
                            'voucher_sub_id'    => $receipt_details->id
                        ]);
                    }
                }
            }
        }

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

        return true;
    }



    public function SaleOthersTransaction(
        $sale_invoice_id,
        $transactions_no,
        $module_code,
        $account_id,
        $price,
        $sale_invoice_batch_id = ''
    ) {

        $module         = MenuModelPermission::select('id', 'code')->where('code', $module_code)->first();
        $loginFinancialyear = \Session::get('user_financial_year_id') ?? '';
        $company_address = \Session::get('company_data')['companies_addresses'];
        $currency_id     = $company_address->currency_id ?? '';

        $getSaleAdditionalData = SaleReturnOthersTransactions::where(
            [
                'voucher_type'   => $module_code,
                'sale_invoice_id' => $sale_invoice_id,
                'account_id'      => $account_id
            ]
        )->first();
        if (empty($getSaleAdditionalData)) {
            SaleReturnOthersTransactions::create([
                'sale_invoice_id'       => $sale_invoice_id,
                'sale_invoice_batch_id' => $sale_invoice_batch_id,
                'transactions_no'       => $transactions_no,
                'transaction_date'      => date('Y-m-d'),
                'module_id'             => $module->id??'',
                'voucher_type'          => $module_code??'',
                'account_id'            => $account_id ?? '',
                'transaction_type'      => 'CREDIT',
                'details_narration'     => '',
                'price'                 => $price,
                'currency_id'           => $currency_id,
                'created_by'            => \Auth::id() ?? '',
                'company_id'            => \Auth::user()->company_id ?? '',
                'financial_year_id'     => $loginFinancialyear,
                'transactions_status'   => 1
            ]);
        } else {
            $getSaleAdditionalData->update(['price' => $price]);
        }


        return true;
    }
}