<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\Exceptions\CriteriaNotFulfilledException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Bookings\Services\FetchesBooking;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Transactions\DataTransferObjects\CreatePurchaseOrderDTO;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Processors\CreatePurchaseOrderTransactionProcessor;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\DeletesTransactionDetails;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\Services\UpdatesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\Modules\Rules\Services\RuleEvaluator;
use App\Classes\Modules\Rules\Standards\Rules\CanPassEditingPORule;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Http\Resources\TransactionResource;
use App\Models\Booking;
use App\Models\Transaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CreatePurchaseOrderTransactionLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Update Purchase Order',
            'message' => 'You have successfully updated your booking\'s purchase order'
        ];
    }

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

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

    /** @var CreatePurchaseOrderTransactionProcessor */
    private $createPurchaseOrderTransactionProcessor;

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

    /** @var CanPassEditingPORule */
    private $canPassEditingPORule;

    /**
     * CreatePurchaseOrderTransactionLogic constructor.
     * @param FetchesBooking $fetchesBooking
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
     * @param CreatePurchaseOrderTransactionProcessor $createPurchaseOrderTransactionProcessor
     * @param RuleEvaluator $ruleEvaluator
     * @param CanPassEditingPORule $canPassEditingPORule
     */
    public function __construct(FetchesBooking $fetchesBooking, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatePurchaseOrderTransactionProcessor $createPurchaseOrderTransactionProcessor, RuleEvaluator $ruleEvaluator, CanPassEditingPORule $canPassEditingPORule)
    {
        $this->fetchesBooking = $fetchesBooking;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
        $this->createPurchaseOrderTransactionProcessor = $createPurchaseOrderTransactionProcessor;
        $this->ruleEvaluator = $ruleEvaluator;
        $this->canPassEditingPORule = $canPassEditingPORule;
    }

    /**
     * @param Request $request
     * @param string $id
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\CriteriaNotFulfilledException
     */
    public function logic(Request $request, $id = '') : JsonResponse
    {
        //This checking is excluded for (1) Admin, (2) Update of booking amount post payment as user
        if(!in_array(Auth::user()->type, RoleTypes::ADMIN_ROLES) && !$request->has('is_privilleged_update')){
            $dto = new CreatePurchaseOrderDTO($request->all());
            $result = $this->ruleEvaluator->evaluate([
                $this->canPassEditingPORule
            ], $dto);

            if ($result->failed()) {
                throw new CriteriaNotFulfilledException("- " . implode("<br>- ", $result->messages()));
            }
        }

        /** @var Booking $booking */
        $booking = $this->fetchesBooking->execute(['id' => $request->route('id') ?? $id]);

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

        $total = collect($request->input('products'))->sum(function($product){
            return $product['quantity'] * floatval(str_replace(',', '', $product['unit_price']));
        });

        $object = new TransactionObject($billNumber, TransactionType::PURCHASE_ORDER, $booking->company->id, 1,
            1, PaymentMethodType::CASH,
            $total, $total, $booking->fix_currency_id, $booking->fix_currency_id,
            1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, $request->input('products'));


        $transaction = $this->createPurchaseOrderTransactionProcessor->execute($booking, $object);

        return $this->resourceResponse(new TransactionResource($transaction));

    }
}
