<?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\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use ErrorException;
use Illuminate\Support\Facades\DB;
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;

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

    /**
     * @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);

            $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->issuer = $supplier->id;
        $group->amount = $group->transactions()->sum('amount');
        $group->currency_rate = $rate;
        $group->tax = $group->transactions()->sum('tax');
        $group->service_charge = $group->transactions()->sum('service_charge');

        $group->save();

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

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

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

        $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));
    }

}
