<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Bookings\Standards\Rules\CanCreateBooking;
use App\Classes\Modules\Bookings\Services\CreatesBooking;
use App\Classes\Modules\Bookings\Services\GeneratesBookingMarking;
use App\Classes\Modules\Bookings\DataTransferObjects\BookingObject;
use App\Classes\Modules\PerfexCRM\Processors\BookingToPerfexCRMProcessor;
use App\Classes\Modules\Milestones\Processors\CheckMilestonesForRewardProcessor;
use App\Classes\Modules\Vouchers\DataTransferObjects\CreateVoucherifyOrderObject;
use App\Classes\Modules\Vouchers\Services\Voucherify\CreatesVoucherifyOrder;
use App\Classes\Modules\Vouchers\Services\CreatesVoucherEntityMapping;
use App\Classes\Modules\Vouchers\DataTransferObjects\VoucherEntityObject;
use App\Classes\Modules\Affiliate\Services\TracksAffiliateOrder;
use App\Classes\ValueObjects\Constants\BookingAttributeNames;
use App\Classes\ValueObjects\Constants\VoucherifyEntityType;
use App\Http\Resources\BookingResource;
use App\Models\User;
use App\Models\Booking;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateBookingLogic extends AbstractControllerLogic
{

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

    /** @var CanCreateBooking */
    private $canCreateBooking;

    /** @var CreatesBooking */
    private $createsBooking;

    /** @var GeneratesBookingMarking */
    private $generatesBookingMarking;

    /** @var FetchesCompany */
    private $fetchesCompany;

    /** @var BookingToPerfexCRMProcessor */
    private $bookingToPerfexCRMProcessor;

    /** @var CheckMilestonesForRewardProcessor */
    private $checkMilestonesForRewardProcessor;

    /** @var CreatesVoucherifyOrder */
    private $createsVoucherifyOrder;

    /** @var CreatesVoucherEntityMapping */
    private $createsVoucherEntityMapping;

    /** @var TracksAffiliateOrder */
    private $tracksAffiliateOrder;

    /**
     * CreateBookingLogic constructor.
     * @param CanCreateBooking $canCreateBooking
     * @param CreatesBooking $createsBooking
     * @param GeneratesBookingMarking $generatesBookingMarking
     * @param FetchesCompany $fetchesCompany
     * @param BookingToPerfexCRMProcessor $bookingToPerfexCRMProcessor
     * @param CheckMilestoneForRewardProcessor $checkMilestonesForRewardProcessor
     * @param CreatesVoucherifyOrder $createsVoucherifyOrder
     * @param CreatesVoucherEntityMapping $createsVoucherEntityMapping
     * @param TracksAffiliateOrder $tracksAffiliateOrder
     */
    public function __construct(CanCreateBooking $canCreateBooking, CreatesBooking $createsBooking, GeneratesBookingMarking $generatesBookingMarking, FetchesCompany $fetchesCompany, BookingToPerfexCRMProcessor $bookingToPerfexCRMProcessor, CheckMilestonesForRewardProcessor $checkMilestonesForRewardProcessor, CreatesVoucherifyOrder $createsVoucherifyOrder, CreatesVoucherEntityMapping $createsVoucherEntityMapping, TracksAffiliateOrder $tracksAffiliateOrder)
    {
        $this->canCreateBooking = $canCreateBooking;
        $this->createsBooking = $createsBooking;
        $this->generatesBookingMarking = $generatesBookingMarking;
        $this->fetchesCompany = $fetchesCompany;
        $this->bookingToPerfexCRMProcessor = $bookingToPerfexCRMProcessor;
        $this->checkMilestonesForRewardProcessor = $checkMilestonesForRewardProcessor;
        $this->createsVoucherifyOrder = $createsVoucherifyOrder;
        $this->createsVoucherEntityMapping = $createsVoucherEntityMapping;
        $this->tracksAffiliateOrder = $tracksAffiliateOrder;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request) : JsonResponse
    {
        if (in_array($request->input('service_id'), [4, 10])) {
            if (!$request['order_reference_no']) {
                throw new MalformedRequestException('At least 1 order reference required.');
            }

            if ($request['order_reference_no']) {
                foreach ($request['order_reference_no'] as $index => $reference) {
                    if (!$reference) {
                        $index += 1;
                        throw new MalformedRequestException("Order reference {$index} cannot be empty");
                    }
                }
            }
        }

        $company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);

        $object = new BookingObject($request->input('service_id'), $request->input('transferable_bank_id'), $this->generatesBookingMarking->execute(), number_format( floatval(str_replace(',', '', $request->input('fix_amount'))), 5, '.', ''), $request->input('type') === 1 ? $request->input('convertible_currency_id') : 1, $request->input('convertible_currency_id'), 1);

        $this->canCreateBooking->passes($object);

        /** @var Booking $booking */
        $booking = $this->createsBooking->execute($company, $object);

        if(config('perfexcrm.is_enabled') == 'true'){
            $this->bookingToPerfexCRMProcessor->execute($booking);
        }

        if (in_array($request->input('service_id'), [4, 10])) {
            foreach ($request['order_reference_no'] as $order_reference) {
                $booking->modelAttributes()->create([
                    'name' => BookingAttributeNames::ORDER_REFERENCE_NO,
                    'value' => $order_reference
                ]);
            }
        }

        $voucherify_customer_id = "";
        $voucherify_order_id = "";

        $user = $company->employees()->first();
        $createVoucherifyOrderObject = new CreateVoucherifyOrderObject($user, $company->id, $booking->id, 0, 0, false, false);
        $createVoucherufyOrderResult = $this->createsVoucherifyOrder->execute($createVoucherifyOrderObject);

        if($createVoucherufyOrderResult && isset($createVoucherufyOrderResult->id)){
            $voucherify_order_id = $createVoucherufyOrderResult->id;
            if(isset($createVoucherufyOrderResult->customer)){
                $voucherify_customer_id = $createVoucherufyOrderResult->customer->id;
            }
        }

        $this->recordVoucherifyOrderInfo($voucherify_order_id, $booking);
        $this->recordVoucherifyCustomerInfo($voucherify_customer_id, $user);

        // Track affiliate order if user has an affiliate code
        $this->tracksAffiliateOrder->execute($booking);

        //cief todo: case study 5 voucherify
        // $user = $company->employees()->first();
        // $this->checkMilestonesForRewardProcessor->execute($user, [Milestones::MILESTONE_5]);

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

    }

    private function recordVoucherifyOrderInfo(string $voucherify_order_id, Booking $booking){
        if($voucherify_order_id){
            $voucherify_entity = $booking->voucherifyEntities()->first();
            if(!$voucherify_entity){
                $voucherEntityObject = new VoucherEntityObject($voucherify_order_id, VoucherifyEntityType::ORDER);
                $this->createsVoucherEntityMapping->execute($booking, $voucherEntityObject);
            }
        }
    }

    private function recordVoucherifyCustomerInfo(string $voucherify_customer_id, User $user){
        if($voucherify_customer_id){
            $voucherify_entity = $user->voucherifyEntities()->first();
            if(!$voucherify_entity){
                $voucherEntityObject = new VoucherEntityObject($voucherify_customer_id, VoucherifyEntityType::CUSTOMER);
                $this->createsVoucherEntityMapping->execute($user, $voucherEntityObject);
            }
        }
    }
}
