<?php

namespace App\Traits;

use App\Models\Account;
use App\Models\AccountTransaction;
use App\Models\MenuModelPermission;
use App\Models\Purchase\PurchaseOthersTransaction;
use App\Models\TaxMaster;
use App\Models\VoucherMaster;

trait PurchaseBasicTransactionTrait
{
    public function createTransaction(
        $moduleCode,
        $saleInvoiceId,
        $invoiceBatchId,
        $VoucherType,
        $account_id,
        $data,
        $roundOff,
        $discount,
        $spacialDiscount
    ) {
        $roundOff['amount'] = $roundOff['amount'] != '' ? $roundOff['amount'] : 0;
        $discount['amount'] = $discount['amount'] != '' ? $discount['amount']:0;

        $loginFinancialyear = \Session::get('user_financial_year_id') ?? '';
        /*********************  Basic Transaction Insert Into Account Transaction Table ***************/


        # 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);
        //dd($last_voucher_count);
        $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)
        );

        $transaction = AccountTransaction::createTransaction([
            'transactions_no'   => $transactions_no,
            'transaction_date'  => date('Y-m-d'),
            'module_code'       => $moduleCode,
            'voucher_id'        => $saleInvoiceId,
            'batch_id'          => $invoiceBatchId,
            'voucher_type'      => ($VoucherType ?? ''),
            'account_id'        => $account_id,
            'transaction_type'  => 'CREDIT',
            'details_narration' => '',
            'amount'            => $data['amount'] - $discount['amount'] + ($roundOff['amount'] ?? 0),
            'voucher_sub_id'    => '',
            'financial_year_id' => $loginFinancialyear,
            'last_id'           => $last_voucher_count,
        ]);

        $totalTax = 0;
        foreach ($data['products'] as $key => $value) {
            if ($value['tax_flat'] > 0) {
                $totalTax += $value['tax_flat'];
            }
        }

        $purchaseAccount = Account::select('id')->where('code', 'PURCHASE')->first();

        # 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'       => $moduleCode,
            'voucher_id'        => $saleInvoiceId,
            'batch_id'          => $invoiceBatchId,
            'voucher_type'      => ($VoucherType ?? ''),
            'account_id'        => $purchaseAccount->id,
            'transaction_type'  => 'DEBIT',
            'details_narration' => '',
            'amount'            => $data['amount'] - $totalTax + $roundOff['amount'] - $spacialDiscount,
            'voucher_sub_id'    => '',
            'financial_year_id' => $loginFinancialyear,
            'last_id'           => $last_voucher_count,
        ]);

        $groupedArray = [];
        foreach ($data['products'] as $item) {
            $taxPer = $item['tax_per'];
            if (!isset($groupedArray[$taxPer])) {
                $groupedArray[$taxPer] = 0;
            }
            $groupedArray[$taxPer] += $item['tax_flat'];
        }


        foreach ($groupedArray as $key => $value) {
            if ($key != 0) {
                $taxMaster = TaxMaster::where('total_percentage', $key)->first();

                # 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'       => $moduleCode,
                    'voucher_id'        => $saleInvoiceId,
                    'batch_id'          => $invoiceBatchId,
                    'voucher_type'      => ($VoucherType ?? ''),
                    'account_id'        => $taxMaster->account_id,
                    'transaction_type'  => 'DEBIT',
                    'details_narration' => '',
                    'amount'            => $value,
                    'voucher_sub_id'    => '',
                    'financial_year_id' => $loginFinancialyear,
                    'last_id'           => $last_voucher_count,
                ]);
            }
        }

        /********************* End Basic Transaction Insert Into Account Transaction Table */


        /****************************** Discount Store in Account Transaction *************************/
        if ($discount['amount'] != 0 && $discount['mode_id'] != '') {

            # 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'       => $moduleCode,
                'voucher_id'        => $saleInvoiceId,
                'batch_id'          => $invoiceBatchId,
                'voucher_type'      => ($VoucherType ?? ''),
                'account_id'        => $discount['mode_id']  ?? '',
                'transaction_type'  => 'CREDIT',
                'details_narration' => '',
                'amount'            => $discount['amount'],
                'voucher_sub_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'       => $moduleCode,
                'voucher_id'        => $saleInvoiceId,
                'batch_id'          => $invoiceBatchId,
                'voucher_type'      => ($VoucherType ?? ''),
                'account_id'        => $account_id  ?? '',
                'transaction_type'  => 'DEBIT',
                'details_narration' => '',
                'amount'            => $discount['amount'],
                'voucher_sub_id'    => '',
                'financial_year_id' => $loginFinancialyear,
                'last_id'           => $last_voucher_count,
            ]);
        }

        /****************************** Round Off Store in Account Transaction *************************/

        if ($roundOff['amount'] != 0 && $roundOff['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)
            );

            AccountTransaction::createTransaction([
                'transactions_no'   => $transactions_no,
                'transaction_date'  => date('Y-m-d'),
                'module_code'       => $moduleCode,
                'voucher_id'        => $saleInvoiceId,
                'batch_id'          => $invoiceBatchId,
                'voucher_type'      => ($VoucherType ?? ''),
                'account_id'        => $roundOff['mode_id']  ?? '',
                'transaction_type'  => 'CREDIT',
                'details_narration' => '',
                'amount'            => $roundOff['amount'],
                'voucher_sub_id'    => '',
                'financial_year_id' => $loginFinancialyear,
                'last_id'           => $last_voucher_count,
            ]);
        } elseif ($roundOff['amount'] != 0 && $roundOff['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)
            );
            AccountTransaction::createTransaction([
                'transactions_no'   => $transactions_no,
                'transaction_date'  => date('Y-m-d'),
                'module_code'       => $moduleCode,
                'voucher_id'        => $saleInvoiceId,
                'batch_id'          => $invoiceBatchId,
                'voucher_type'      => ($VoucherType ?? ''),
                'account_id'        => $roundOff['mode_id']  ?? '',
                'transaction_type'  => 'DEBIT',
                'details_narration' => '',
                'amount'            => $roundOff['amount'],
                'voucher_sub_id'    => '',
                'financial_year_id' => $loginFinancialyear,
                'last_id'           => $last_voucher_count,
            ]);
        }
    }


    public function updateTransaction(
        $moduleCode,
        $saleInvoiceId,
        $invoiceBatchId,
        $VoucherType,
        $account_id,
        $data,
        $roundOff,
        $discount,
        $spacialDiscount
    ) {

        //dd($account_id);
        $loginFinancialyear = \Session::get('user_financial_year_id') ?? '';
        /********************* Basic Transaction Insert Into Account Transaction Table ****************/

        $mainTransaction = AccountTransaction::updateTransaction(
            [
                'voucher_id'       =>   $saleInvoiceId,
                'batch_id'          =>  $invoiceBatchId,
                'account_id'        =>  $account_id,
                'module_code'       =>  $moduleCode,
                'voucher_type'      => ($VoucherType ?? ''),
            ],
            [
                'amount'            => $data['amount'] - (float)$discount['amount'] + (int)$roundOff['amount'],
                'voucher_sub_id'    => '',
                'financial_year_id' => $loginFinancialyear
            ]
        );

        $totalTax = 0;
        foreach ($data['products'] as $key => $value) {
            if ($value['tax_flat'] > 0) {
                $totalTax += $value['tax_flat'];
            }
        }

        $purchaseAccount = Account::select('id')->where('code', 'PURCHASE')->first();
        
        AccountTransaction::updateTransaction(
            [
                'voucher_id'       =>  $saleInvoiceId,
                'batch_id'          => $invoiceBatchId,
                'account_id'        => $purchaseAccount->id,
                'module_code'       => $moduleCode,
                'voucher_type'      => ($VoucherType ?? ''),
            ],
            [
                'amount'            => $data['amount'] - $totalTax + (int)$roundOff['amount'] - $spacialDiscount,
            ]
        );
       


        $groupedArray = [];
        foreach ($data['products'] as $item) {
            $taxPer = $item['tax_per'];
            if (!isset($groupedArray[$taxPer])) {
                $groupedArray[$taxPer] = 0;
            }
            $groupedArray[$taxPer] += $item['tax_flat'];
        }


        foreach ($groupedArray as $key => $value) {
            if ($key != 0) {
                $taxMaster = TaxMaster::where('total_percentage', $key)
                    ->first();
                    //\DB::enableQueryLog();
                AccountTransaction::updateTransaction(
                    [
                        'voucher_id'       =>  $saleInvoiceId,
                        'batch_id'          =>  $invoiceBatchId,
                        'account_id'        =>  $taxMaster->account_id
                    ],
                    [
                        'transactions_no'   => $mainTransaction->transactions_no,
                        'transaction_date'  => date('Y-m-d'),
                        'module_code'       => $moduleCode,
                        'transaction_type'  => 'DEBIT',
                        'voucher_type'      => ($VoucherType ?? ''),
                        'amount'            => $value,
                        'financial_year_id' => $loginFinancialyear,
                        'voucher_sub_id'    => ''
                    ] 
                );
                //dd(\DB::getQueryLog());
            }
        }

        /*********************End Basic Transaction Insert Into Account Transaction Table ***************/


        /****************************** Discount Store in Account Transaction *************************/
        if ($discount['amount'] != 0 && $discount['mode_id'] != '') {
            $discountTransaction = AccountTransaction::updateTransaction(
                [
                    'voucher_id'       =>  $saleInvoiceId,
                    'batch_id'          => $invoiceBatchId,
                    'account_id'        => $discount['mode_id'],
                    'transaction_type'  => 'CREDIT',
                ],
                [
                    'amount'            => $discount['amount'],
                ]
            );

            // $discountTransaction = AccountTransaction::updateTransaction(
            //     [
            //         'voucher_id'       =>  $saleInvoiceId,
            //         'batch_id'          => $invoiceBatchId,
            //         'account_id'        => $discount['mode_id'],
            //         'transaction_type'  => 'CREDIT',
            //     ],
            //     [
            //       'amount'            => $discount['amount'],
            //     ]);

            // AccountTransaction::createTransaction([
            //     'transactions_no'   => $transactions_no,
            //     'transaction_date'  => date('Y-m-d'),
            //     'module_code'       => $moduleCode,
            //     'voucher_id'        => $saleInvoiceId,
            //     'batch_id'          => $invoiceBatchId,
            //     'voucher_type'      => ($VoucherType ?? ''),
            //     'account_id'        => $account_id  ?? '',
            //     'transaction_type'  => 'CREDIT',
            //     'details_narration' => '',
            //     'amount'            => $discount['amount'],
            //     'voucher_sub_id'    => '',
            //     'financial_year_id' => $loginFinancialyear,
            //     'last_id'           => $last_voucher_count,
            // ]);
        }

        /****************************** Round Off Store in Account Transaction *************************/

        if ($roundOff['amount'] != 0 && $roundOff['amount'] < 0) {

            AccountTransaction::updateTransaction(
                [
                    'voucher_id'       =>  $saleInvoiceId,
                    'batch_id'          => $invoiceBatchId,
                    'account_id'        => $roundOff['mode_id'],
                    'transactions_no'   => $mainTransaction->transactions_no,
                ],
                [

                    'transaction_date'  => date('Y-m-d'),
                    'module_code'       => $moduleCode,
                    'voucher_type'      => ($VoucherType ?? ''),
                    'transaction_type'  => 'CREDIT',
                    'details_narration' => '',
                    'amount'            => $roundOff['amount'],
                    'voucher_sub_id'    => '',
                    'financial_year_id' => $loginFinancialyear
                ]
            );
        } elseif ($roundOff['amount'] != 0 && $roundOff['amount'] > 0) {
            AccountTransaction::updateTransaction(
                [
                    'voucher_id'       =>  $saleInvoiceId,
                    'batch_id'          => $invoiceBatchId,
                    'account_id'        => $roundOff['mode_id'],
                    'transactions_no'   => $mainTransaction->transactions_no,
                ],
                [
                    'transaction_date'  => date('Y-m-d'),
                    'module_code'       => $moduleCode,
                    'voucher_type'      => ($VoucherType ?? ''),
                    'transaction_type'  => 'DEBIT',
                    'details_narration' => '',
                    'amount'            => $roundOff['amount'],
                    'voucher_sub_id'    => '',
                    'financial_year_id' => $loginFinancialyear
                ]
            );
        }
    }


    public function PurchaseOthersTransaction(
        $purchase_invoice_id,
        $transactions_no,
        $module_code,
        $account_id,
        $price,
        $purchase_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 ?? '';

        $getPurchaseAdditionalData = PurchaseOthersTransaction::where(
            [
                'voucher_type'   => $module_code,
                'purchase_invoice_id' => $purchase_invoice_id,
                'account_id'      => $account_id
            ]
        )->first();
        if (empty($getPurchaseAdditionalData)) {
            PurchaseOthersTransaction::create([
                'purchase_invoice_id'       => $purchase_invoice_id,
                'purchase_invoice_batch_id' => $purchase_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'      => 'DEBIT',
                '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 {
            $getPurchaseAdditionalData->update(['price' => $price]);
        }


        return true;
    }
}
