<?php

namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\CalculatesBillGroupPaymentAmount;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\FetchesBillGroup;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Http\Resources\BillGroupResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateBillGroupPaymentTransactionLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Create Bill Group Payment Transaction',
            'message' => 'You have successfully created payment for this Bill Group'
        ];
    }

    /** @var FetchesBillGroup */
    private $fetchesBillGroup;

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

    /** @var CreatesTransaction */
    private $createsTransaction;

    /** @var CalculatesBillGroupPaymentAmount */
    private $calculatesBillGroupPaymentAmount;

    /**
     * CreateBillGroupPaymentTransactionLogic constructor.
     * @param FetchesBillGroup $fetchesBillGroup
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
     * @param CreatesTransaction $createsTransaction
     * @param CalculatesBillGroupPaymentAmount $calculatesBillGroupPaymentAmount
     */
    public function __construct(FetchesBillGroup $fetchesBillGroup, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBillGroupPaymentAmount $calculatesBillGroupPaymentAmount)
    {
        $this->fetchesBillGroup = $fetchesBillGroup;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
        $this->createsTransaction = $createsTransaction;
        $this->calculatesBillGroupPaymentAmount = $calculatesBillGroupPaymentAmount;
    }

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

        $billGroupPayment = $this->calculatesBillGroupPaymentAmount->execute($billGroup);
        $outstanding_amount = $billGroupPayment['outstanding_amount'];

        if ($billGroupPayment['outstanding_amount'] <= 0) {
            if ($billGroup->transactions()->whereIn('status', [ApprovalStatus::PENDING_SUBMISSION, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->count() !== 0) {
                throw new MalformedRequestException('Invalid bill group, payment transaction already exist.');
            }
        }

        $payAmount = floatval(str_replace(',', '', $request->input('payAmount')));
        if($payAmount > round($outstanding_amount, 2)) throw new MalformedRequestException('Your payment must not be greater than '. $outstanding_amount .'.');

        if ($billGroupPayment['outstanding_amount'] == 0 && $payAmount == 0) {
            $billGroup->status = ApprovalStatus::APPROVED;
            $billGroup->save();
        } else {
            $billNumber = $this->generatesTransactionBillNumber->execute('SPLR-PYMT-');
            $transaction_object = new TransactionObject($billNumber, TransactionType::SUPPLIER_PAYMENT, $billGroup->issuer, 
               $billGroup->receiver, $billGroup->issuerCompany->banks()->where('default', true)->first()->id, PaymentMethodType::CASH, 
               $payAmount, $payAmount, 1, 1, 1, 
                0, 0, null, ApprovalStatus::PENDING_SUBMISSION, [], '');
            $this->createsTransaction->execute($billGroup, $transaction_object);
        }

        return $this->resourceResponse(new BillGroupResource($billGroup));
    }

}