<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Jobs\Commands\V2\CreateInvoiceTransactionV2CommandJob;
use App\Classes\Modules\Bookings\DataTransferObjects\BookingObject;
use App\Classes\Modules\Bookings\DataTransferObjects\UpdateBookingInvoiceStatusObject;
use App\Classes\Modules\Bookings\Services\CalculatesBookingOutstanding;
use App\Classes\Modules\Bookings\Services\FetchesBooking;
use App\Classes\Modules\Bookings\Services\UpdatesBookingInvoiceStatus;
use App\Classes\Modules\Bookings\Services\UpdatesBookingFixedAmount;
use App\Classes\Modules\Bookings\Standards\Rules\CanUpdateBooking;
use App\Classes\Modules\Rules\Services\RuleEvaluator;
use App\Classes\Modules\Rules\Standards\Rules\CanPassTransferPeriodLockRule;
use App\Classes\Modules\Rules\DataTransferObjects\CheckTransferPeriodLockRuleVariant2DTO;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionV2Processor;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Http\Resources\BookingResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Classes\Exceptions\CriteriaNotFulfilledException;
use Illuminate\Support\Facades\Log;

class UpdateBookingAmountLogic extends AbstractControllerLogic
{


    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Updated Booking',
            'message' => 'You have successfully updated the Booking'
        ];
    }

    /** @var CanUpdateBooking */
    private $canUpdateBooking;

    /** @var UpdatesBookingFixedAmount */
    private $updatesBookingFixedAmount;

    /** @var FetchesBooking */
    private $fetchesBooking;

    /** @var CalculatesBookingOutstanding */
    private $calculatesBookingOutstanding;

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

    /** @var UpdatesBookingInvoiceStatus */
    private $updatesBookingInvoiceStatus;

    /** @var CreateInvoiceTransactionV2Processor */
    private $createInvoiceTransactionProcessor;

    /** @var RuleEvaluator */
    private $ruleEvaluator;

    /** @var CanPassTransferPeriodLockRule */
    private $canPassTransferPeriodLockRule;

    /**
     * UpdateBookingAmountLogic constructor.
     * @param CanUpdateBooking $canUpdateBooking
     * @param UpdatesBookingFixedAmount $updatesBookingFixedAmount
     * @param FetchesBooking $fetchesBooking
     * @param CalculatesBookingOutstanding $calculatesBookingOutstanding
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     * @param UpdatesBookingInvoiceStatus $updatesBookingInvoiceStatus
     * @param CreateInvoiceTransactionV2Processor $createInvoiceTransactionProcessor
     * @param RuleEvaluator $ruleEvaluator
     * @param CanPassTransferPeriodLockRule $canPassTransferPeriodLockRule
     */
    public function __construct(CanUpdateBooking $canUpdateBooking, UpdatesBookingFixedAmount $updatesBookingFixedAmount, FetchesBooking $fetchesBooking, CalculatesBookingOutstanding $calculatesBookingOutstanding, UpdatesTransactionStatus $updatesTransactionStatus, UpdatesBookingInvoiceStatus $updatesBookingInvoiceStatus, CreateInvoiceTransactionV2Processor $createInvoiceTransactionProcessor, RuleEvaluator $ruleEvaluator, CanPassTransferPeriodLockRule $canPassTransferPeriodLockRule)
    {
        $this->canUpdateBooking = $canUpdateBooking;
        $this->updatesBookingFixedAmount = $updatesBookingFixedAmount;
        $this->fetchesBooking = $fetchesBooking;
        $this->calculatesBookingOutstanding = $calculatesBookingOutstanding;
        $this->updatesTransactionStatus = $updatesTransactionStatus;
        $this->updatesBookingInvoiceStatus = $updatesBookingInvoiceStatus;
        $this->createInvoiceTransactionProcessor = $createInvoiceTransactionProcessor;
        $this->ruleEvaluator = $ruleEvaluator;
        $this->canPassTransferPeriodLockRule = $canPassTransferPeriodLockRule;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     * @throws CriteriaNotFulfilledException
     */
    public function logic(Request $request) : JsonResponse
    {
        //cief todo: 110 - Prototype Period Lock - Starts
        // $reqData['id'] = $request->route('id');
        // $dto = new CheckTransferPeriodLockRuleVariant2DTO($reqData);

        // $result = $this->ruleEvaluator->evaluate([
        //     $this->canPassTransferPeriodLockRule,
        // ], $dto);

        // if ($result->failed()) {
        //     throw new CriteriaNotFulfilledException("- " . implode("<br>- ", $result->messages()));
        // }
        //cief todo: 110 - Prototype Period Lock - Ends

        $booking = $this->fetchesBooking->execute(['id' => $request->route('id')]);

        $input_amount = number_format( floatval(str_replace(',', '', $request->input('fix_amount', $booking->fix_amount))), 5, '.', '');

        $minimum_amount = $booking->fix_amount - $this->calculatesBookingOutstanding->execute($booking);

        if (((float)$input_amount + 0.01) < (float)$minimum_amount) {
            $input_amount = 0;
            // throw new MalformedRequestException('Booking Amount cannot be less than '. $minimum_amount .'.');
            Log::warning('Booking ID: '. $booking->id .'. Booking Marking: '. $booking->marking .'. Booking Amount cannot be less than '. $minimum_amount .'.');
        }

        $poTransaction = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first();
        $booking->transactions()->where('type', TransactionType::PROFORMA)->delete();

        if($poTransaction) {
            $this->updatesTransactionStatus->execute($poTransaction, ApprovalStatus::PENDING_SUBMISSION);
        }

        $booking = $this->updatesBookingFixedAmount->execute($booking, $input_amount);

        if($booking->invoice_status === ApprovalStatus::APPROVED){
            $updateBookingInvoiceStatusObject = new UpdateBookingInvoiceStatusObject($booking->id, ApprovalStatus::PENDING_VERIFICATION);
            $this->updatesBookingInvoiceStatus->execute($booking, $updateBookingInvoiceStatusObject);
        }
        else{
            // $this->createInvoiceTransactionProcessor->execute($booking);
            $this->createInvoiceTransactionProcessor->execute($booking, "", null, [
                    'generateEInvoice' => false,
                    'generateEInvoiceWithNormalInvoiceTemplate' => false,
                    'generateEInvoiceRefund' => false,
                    'bookingOriginalStatus' => $booking->status
                ]
            );
        }

        return $this->resourceResponse(new BookingResource($booking));
    }

}
