<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;


use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\TransactionResource;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Bookings\Services\FetchesBookingQuotation;
use App\Classes\Modules\Bookings\Standards\Rules\CanCreateBookingRefund;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Transactions\ControllersLogic\UpdateRefundTransactionStatusLogic;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionRefundCalculationObject;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;

class CreateBookingRefundLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Create Refund Booking',
            'message' => 'You have successfully created a refund booking'
        ];
    }

    /** @var FetchesBookingQuotation */
    private $fetchBookingQuotation;

    /** @var FetchesTransaction */
    private $fetchesTransaction;

    /** @var UpdatesTransactionStatus */
    private $updatesTransactionStatus;

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

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

    /** @var UpdateRefundTransactionStatusLogic */
    private $updateRefundTransactionStatusLogic;

    /** @var CreateRemarkProcessor */
    private $createRemarkProcessor;

    /** @var CanCreateBookingRefund */
    private $canCreateBookingRefund;

    /**
     * CreateBookingPaymentLogic constructor.
     * @param FetchesBookingQuotation $fetchBookingQuotation
     * @param FetchesTransaction $fetchesTransaction
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
     * @param CreatesTransaction $createsTransaction
     * @param UpdateRefundTransactionStatusLogic $updateRefundTransactionStatusLogic
     * @param CreateRemarkProcessor $createRemarkProcessor
     * @param CanCreateBookingRefund $canCreateBookingRefund
     */
    public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, UpdateRefundTransactionStatusLogic $updateRefundTransactionStatusLogic, CreateRemarkProcessor $createRemarkProcessor, CanCreateBookingRefund $canCreateBookingRefund)
    {
        $this->fetchBookingQuotation = $fetchBookingQuotation;
        $this->fetchesTransaction = $fetchesTransaction;
        $this->updatesTransactionStatus = $updatesTransactionStatus;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
        $this->createsTransaction = $createsTransaction;
        $this->updateRefundTransactionStatusLogic = $updateRefundTransactionStatusLogic;
        $this->createRemarkProcessor = $createRemarkProcessor;
        $this->canCreateBookingRefund = $canCreateBookingRefund;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {

        $transaction = $this->fetchesTransaction->execute(['id' => $request->route('payment_id')]);

        $booking = $transaction->owner;

        $invoice = $booking->transactions()->where('type', TransactionType::INVOICE)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->first();

        // $this->canCreateBookingRefund->passes();

        $billNumber = $this->generatesTransactionBillNumber->execute('RFD-');

        $refund = $transaction->transactions()->refunds()->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->sum('original_amount');
        $isFullyRefund = round($refund + $request->input('amount'), 2) == round((float) $transaction->original_amount, 2);
        if ($isFullyRefund) {
            $request->merge(['amount' => $transaction->original_amount]);
        }

        $refundInPending = $transaction->transactions()->refunds()->where('status', ApprovalStatus::PENDING_VERIFICATION)->sum('original_amount');

        if($refund + $request->input('amount') > $transaction->original_amount) throw new MalformedRequestException('Your refund must not be greater than '. $transaction->original_amount .'.');

        // $transactionRefundCalculationObject = new TransactionRefundCalculationObject($booking, $transaction, $request->input('amount'));
        // $transactionRefundCalculationObject->init();

        // full refund
        if ((float)$request->input('amount') === (float)$transaction->original_amount) {
            $refundAmount = $transaction->original_amount / $transaction->currency_rate;
            $service_charges_to_refund = $transaction->service_charge;
        } else {
            // partial refund
            $refundAmount = bcdiv($request->input('amount'), $transaction->currency_rate, 7);

            $bookingAmountBeforeCurrentRefund = $booking->fix_amount - $refundInPending;

            $bookingAmountAfterRefunded = $booking->fix_amount - $refundInPending - $request->input('amount');

            $voucherCode = null;
            $redemptionId = null;

            if ($transaction->voucherRedemption) {
                $redemptionId = $transaction->voucherRedemption->redemption_id;
            }

            $conversionObjectBeforeCurrentRefund = new CurrencyConversionObject($bookingAmountBeforeCurrentRefund, $booking->convertible_currency_id, $booking->service_id,  $booking->fix_currency_id === 1 ? 0:1, $transaction->payment_method);

            $conversionObjectAfterRefund = new CurrencyConversionObject($isFullyRefund ? $request->input('amount') : $bookingAmountAfterRefunded, $booking->convertible_currency_id, $booking->service_id,  $booking->fix_currency_id === 1 ? 0:1, $transaction->payment_method);

            $quotationBeforeCurrentRefund = $this->fetchBookingQuotation->execute($booking->company, $conversionObjectBeforeCurrentRefund, $voucherCode, $redemptionId, $booking);

            $quotationAfterRefund = $this->fetchBookingQuotation->execute($booking->company, $conversionObjectAfterRefund, $voucherCode, $redemptionId, $booking);

            $service_charges_to_refund = $isFullyRefund ? $quotationBeforeCurrentRefund->getServiceCharge() : $quotationBeforeCurrentRefund->getServiceCharge() - $quotationAfterRefund->getServiceCharge();
        }


        $refundTotal = $refundAmount;

        // refund service charges if booking is not E2E - starts
        // if ($booking->service_id !== 5) {
        //     $refundTotal = $refundTotal + $service_charges_to_refund + $transaction->tax;
        // } else {
        //     $service_charges_to_refund = 0;
        // }
        // refund service charges if booking is not E2E - ends

        //Reinstate refund service charges to all services, no checking if it is E2E or otherwise
        $refundTotal = $refundTotal + $service_charges_to_refund + $transaction->tax;

        $object = new TransactionObject($billNumber, TransactionType::REFUND, 1, $booking->company->id,
            1, PaymentMethodType::CASH,
            $refundTotal, $request->input('amount'), 1,
            $transaction->original_currency_id, $transaction->currency_rate,
            0, $service_charges_to_refund, null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no);

        $refund_transaction = $this->createsTransaction->execute($transaction, $object);

        $bookingInWhiteForm = $transaction->transactions()->bills()->first(); // if no white form created yet can approve right away

        // create supplier refund
        if ($bookingInWhiteForm) {
            $billNumber = $this->generatesTransactionBillNumber->execute('SRFD-');
            $supplierRefundTotal = bcdiv($request->input('amount'), $bookingInWhiteForm->currency_rate, 7);

            $object = new TransactionObject($billNumber, TransactionType::SUPPLIER_REFUND, 1, $bookingInWhiteForm->issuer,
                1, PaymentMethodType::CASH,
                $supplierRefundTotal, $request->input('amount'), 1,
                $transaction->original_currency_id, $bookingInWhiteForm->currency_rate,
                0, 0, null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no);

            $transaction = $this->createsTransaction->execute($transaction, $object);
        } else {
            $request->route()->setParameter('id', $refund_transaction->id);
            $request->route()->setParameter('status', ApprovalStatus::APPROVED);
            $this->updateRefundTransactionStatusLogic->execute($request);

        }

        if($request->input('refundRemark')){
            $remarkObject = new RemarkObject($request->input('refundRemark'), Auth()->user()->id);
            $this->createRemarkProcessor->execute($this->fetchesTransaction->execute(['id' => $refund_transaction->id]), $remarkObject);
        }

        return $this->resourceResponse(new TransactionResource($refund_transaction));
    }


}
