<?php

namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Http\Resources\GroupResource;
use App\Models\Document;
use App\Models\SegmentConstant;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Transactions\Services\CalculatesTransactionServiceCharge;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\FetchesGroup;
use App\Classes\Modules\Transactions\Services\UpdatesTransaction;
use App\Classes\Modules\Transactions\Services\CalculatesTransactionTransferFee;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Transaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use ErrorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;

class UpdateGroupLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Update Group Transaction',
            'message' => 'You have successfully updated this Group Transaction'
        ];
    }

    /** @var FetchesGroup */
    private $fetchesGroup;

    /** @var FetchesCompany */
    private $fetchesCompany;

    /** @var CalculatesTransactionServiceCharge */
    private $calculatesTransactionServiceCharge;

    /** @var UpdatesTransaction */
    private $updatesTransaction;

    /** @var CalculatesTransactionTransferFee */
    private $calculatesTransactionTransferFee;

    /** @var CreatesDocument */
    private $createsDocument;

    /** @var CreatesFiles */
    private $createsFile;

    /** @var GeneratesTransactionBillNumber */
    private $generatesTransactionBillNumber;

    /**
     * UpdateGroupLogic constructor.
     * @param FetchesGroup $fetchesGroup
     * @param FetchesCompany $fetchesCompany
     * @param CalculatesTransactionServiceCharge $calculatesTransactionServiceCharge
     * @param UpdatesTransaction $updatesTransaction
     * @param CalculatesTransactionTransferFee $calculatesTransactionTransferFee
     * @param CreatesDocument $createsDocument
     * @param CreatesFiles $createsFile
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
     */
    public function __construct(FetchesGroup $fetchesGroup, FetchesCompany $fetchesCompany, CalculatesTransactionServiceCharge $calculatesTransactionServiceCharge, UpdatesTransaction $updatesTransaction, CalculatesTransactionTransferFee $calculatesTransactionTransferFee, CreatesDocument $createsDocument, CreatesFiles $createsFile, GeneratesTransactionBillNumber $generatesTransactionBillNumber)
    {
        $this->fetchesGroup = $fetchesGroup;
        $this->fetchesCompany = $fetchesCompany;
        $this->calculatesTransactionServiceCharge = $calculatesTransactionServiceCharge;
        $this->updatesTransaction = $updatesTransaction;
        $this->calculatesTransactionTransferFee = $calculatesTransactionTransferFee;
        $this->createsDocument = $createsDocument;
        $this->createsFile = $createsFile;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {
        $group = $this->fetchesGroup->execute(['id' => $request->route('id')]);

        $transactions = $group->transactions()->get();

        $rate = $request->input('rate');

        $supplier = $this->fetchesCompany->execute(['id' => $request->input('supplier_id')]);

//        $group->transactions()->update(['issuer' => $supplier->id, 'currency_rate' => $rate]);
//        $group->transactions()->update(['amount' => DB::raw('(original_amount * (1 / currency_rate)) + service_charge + tax')]);


        foreach($transactions as $transaction) {

            $constant = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $supplier->id)->first();
            $serviceCharge = $this->calculatesTransactionServiceCharge->execute($transaction->original_amount, $rate, $constant);

            $object = new TransactionObject(
                $transaction->bill_no,
                TransactionType::BILL,
                $supplier->id,
                1,
                $supplier->banks()->where('default', true)->first()->id,
                PaymentMethodType::CASH,
                $transaction->original_amount * (1 / $rate),
                $transaction->original_amount,
                1,
                $transaction->original_currency_id,
                $rate,
                0,
                $serviceCharge,
                null,
                ApprovalStatus::PENDING_VERIFICATION
            );

            $billTransaction = $this->updatesTransaction->execute($transaction, $object);

            $supplierRefundTransactions = $transaction->owner->transactions()->supplierRefunds()->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->get();

            foreach ($supplierRefundTransactions as  $supplierRefundTransaction) {
                $claimBefore = $supplierRefundTransaction->transactions()->where('type', TransactionType::BILL_REFUND)->where('status', ApprovalStatus::APPROVED)->exists();

                if (!$claimBefore) {
                    $supplierRefundTransaction->currency_rate = $rate;
                    $supplierRefundTransaction->amount =  $supplierRefundTransaction->original_amount / $rate;
                    $supplierRefundTransaction->save();
                }
            }

            $transferTransaction = $transaction->transactions()->where('type', TransactionType::TRANSFER_FEE)->first();

            $transferFee = $this->calculatesTransactionTransferFee->execute($billTransaction->original_amount, $constant);

            $object = new TransactionObject(
                $transferTransaction->bill_no,
                TransactionType::TRANSFER_FEE,
                $supplier->id,
                1,
                $supplier->banks()->where('default', true)->first()->id,
                PaymentMethodType::CASH,
                $transaction->original_amount,
                $transaction->original_amount,
                $transaction->original_currency_id,
                $transaction->original_currency_id,
                1,
                0,
                $transferFee,
                null,
                ApprovalStatus::PENDING_VERIFICATION
            );

            $this->updatesTransaction->execute($transferTransaction, $object);
        }

        // group transfer fee from supplier currency order dashboard manual input
        if ($request->input('group_transfer_fee')) {
            $fee = $request->input('group_transfer_fee');

            $group_transfer_fee = $group->morphTransactions()->where('type', TransactionType::TRANSFER_FEE)->first();

            if ($group_transfer_fee) {
                $group_transfer_fee->amount = $fee;
                $group_transfer_fee->original_amount = $fee;
                $group_transfer_fee->save();
            } else {
                $transferFeeNumber = $this->generatesTransactionBillNumber->execute('TRFR-');
                $object = new TransactionObject($transferFeeNumber, TransactionType::TRANSFER_FEE, 1, $supplier->id,
                    $supplier->banks()->where('default', true)->first()->id, PaymentMethodType::CASH,
                    $fee, $fee, $group->original_currency_id, $group->original_currency_id,
                    1, 0, 0, null, ApprovalStatus::APPROVED);

                $model = new Transaction();
                $model->bill_no = $object->getBillNo();
                $model->type = $object->getTransactionType();
                $model->issuer = $object->getIssuer();
                $model->receiver = $object->getReceiver();
                $model->recipient_bank_account_id = $object->getRecipientBankAccountId();
                $model->payment_method = $object->getPaymentMethod();
                $model->amount = $object->getAmount();
                $model->original_amount = $object->getOriginalAmount();
                $model->currency_id = $object->getCurrencyId();
                $model->original_currency_id = $object->getOriginalCurrencyId();
                $model->currency_rate = $object->getCurrencyRate();
                $model->tax = $object->getTax();
                $model->service_charge = $object->getServiceCharge();
                $model->expires_on = $object->getExpiresOn();
                $model->status = $object->getStatus();
                $model->payment_reference = $object->getPaymentReference();

                $group->morphTransactions()->save($model);
            }
        }

        $group_transfer_fee = $group->morphTransactions()->where('type', TransactionType::TRANSFER_FEE)->first();

        $group_transfer_fee_original_amount = 0;

        if ($group_transfer_fee) {
            $group_transfer_fee_original_amount = $group_transfer_fee->original_amount;
        }

        $transferFeeTransactions = $group->transactions()->with([
            'transactions' => function ($transaction) {
                return $transaction->where('type', TransactionType::TRANSFER_FEE);
            }])->get()->pluck('transactions')->flatten();

        $group->issuer = $supplier->id;
        $group->original_amount = $group->transactions()->sum('original_amount') + ((float)$transferFeeTransactions->sum('service_charge') + (float)$group_transfer_fee_original_amount);
        $group->amount = $group->transactions()->sum('amount') + (((float)$transferFeeTransactions->sum('service_charge') + (float)$group_transfer_fee_original_amount) / $rate) + $group->transactions()->sum('service_charge');
        $group->currency_rate = $rate;
        $group->tax = $group->transactions()->sum('tax');
        $group->service_charge = $group->transactions()->sum('service_charge');

        $group->save();

        $group->documents()->delete();

        $pdf = LaravelMpdf::loadView('pages.pdfs.currency_vendor_order', ['transactions' => $group->transactions, 'transferFeeTransactions' => $transferFeeTransactions, 'supplier' => $supplier, 'groupTransferFeeOriginalAmount' => $group_transfer_fee_original_amount]);

        $object = new DocumentObject(
            DocumentType::CURRENCY_VENDOR_ORDER,
            [chunk_split('data:application/pdf;base64,'.base64_encode($pdf->output()))],
            '',
            ApprovalStatus::COMPLETED,
            'currency_vendor_order'
        );

        /** @var Document $document */
        $document = $this->createsDocument->execute($group, $object);
        $this->createsFile->execute($document, $object);

        return $this->resourceResponse(new GroupResource($group));
    }

}
