<?php

namespace App\Classes\Modules\Bookings\Services;


use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Modules\Bookings\DataTransferObjects\CalculationObject;
use App\Classes\Modules\Companies\Services\FetchesCompanyServiceSettings;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Classes\Modules\Vouchers\DataTransferObjects\ValidatedVoucherObject;
use App\Classes\Modules\Vouchers\DataTransferObjects\ValidateVoucherifyVoucherObject;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Classes\Modules\Vouchers\Services\Voucherify\ValidatesVoucherifyVoucher;
use App\Classes\Modules\Vouchers\Services\Voucherify\FetchesVoucherifyRedemption;
use App\Classes\Modules\Vouchers\Services\Voucherify\FetchesVoucherifyVoucher;
use App\Models\Booking;
use App\Models\Company;
use App\Models\Currency;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class FetchesBookingQuotation
{

    /** @var FetchesCompanyServiceSettings */
    private $fetchesCompanyServiceSettings;

    /** @var FetchesCurrency */
    private $fetchesCurrency;

    /** @var ValidatesVoucherifyVoucher */
    private $validatesVoucherifyVoucher;

    /** @var FetchesVoucherifyRedemption */
    private $fetchesVoucherifyRedemption;

    /** @var FetchesVoucherifyVoucher */
    private $fetchesVoucherifyVoucher;

    /**
     * FetchesBookingQuotation constructor.
     * @param FetchesCompanyServiceSettings $fetchesCompanyServiceSettings
     * @param FetchesCurrency $fetchesCurrency
     * @param ValidatesVoucherifyVoucher $validatesVoucherifyVoucher
     * @param FetchesVoucherifyRedemption $fetchesVoucherifyRedemption
     * @param FetchesVoucherifyVoucher $fetchesVoucherifyVoucher
     */
    public function __construct(FetchesCompanyServiceSettings $fetchesCompanyServiceSettings, FetchesCurrency $fetchesCurrency, ValidatesVoucherifyVoucher $validatesVoucherifyVoucher, FetchesVoucherifyRedemption $fetchesVoucherifyRedemption, FetchesVoucherifyVoucher $fetchesVoucherifyVoucher)
    {
        $this->fetchesCompanyServiceSettings = $fetchesCompanyServiceSettings;
        $this->fetchesCurrency = $fetchesCurrency;
        $this->validatesVoucherifyVoucher = $validatesVoucherifyVoucher;
        $this->fetchesVoucherifyRedemption = $fetchesVoucherifyRedemption;
        $this->fetchesVoucherifyVoucher = $fetchesVoucherifyVoucher;
    }


    /**
     * @param Company $company
     * @param CurrencyConversionObject $conversionObject
     * @param null|string $voucherCode
     * @param null|string $redemptionId
     * @return CalculationObject
     * @throws MalformedRequestException
     */
    public function execute(Company $company, CurrencyConversionObject $conversionObject, ?string $voucherCode = null, ?string $redemptionId = null, ?Booking $booking = null){
        if($conversionObject->getAmount() <= 0) throw new MalformedRequestException('Your transfer must be greater than zero.');

        $configurations = $this->fetchesCompanyServiceSettings->execute($company, $conversionObject);

        /** @var Currency $currency */
        $currency = $this->fetchesCurrency->execute(['id' => $conversionObject->getCurrencyId()]);
        if($conversionObject->getAmount() > $configurations->getMaxLimit()) throw new MalformedRequestException('Your transfer can\'t be greater than '.number_format( floatval(str_replace(',', '', $configurations->getMaxLimit())), 2, '.', ',').' '.$currency->short_code);

        $calculationObject = new CalculationObject($conversionObject, $configurations, null);

        //Voucherify
        $voucher = null;
        if($voucherCode){
            $employeeWhoOwnsTheVoucher = null;

            $employees = $company->first()->employees;
            if(count($employees) > 1){
                foreach($employees as $singleEmployee){
                    $userRewards = $singleEmployee->rewards;
                    foreach($userRewards as $userReward){
                        if ($userReward->voucher && $userReward->voucher->code === $voucherCode) {
                            Log::info('1. Company with multiple employees: ' . json_encode($singleEmployee) . ", voucher: " . $voucherCode);
                            $employeeWhoOwnsTheVoucher = $singleEmployee;
                        }
                    }
                }
            }

            if(!$employeeWhoOwnsTheVoucher){
                $employeeWhoOwnsTheVoucher = $company->employees()->first();
            }

            $isNewOrder = false;
            $voucherifyVoucherFetched = $this->fetchesVoucherifyVoucher->execute($employeeWhoOwnsTheVoucher, $voucherCode);
            if($booking && $voucherifyVoucherFetched && isset($voucherifyVoucherFetched->created_at)) {
                $voucherifyDate = Carbon::parse($voucherifyVoucherFetched->created_at);
                $bookingDate = Carbon::parse($booking->created_at);

                if ($voucherifyDate->gt($bookingDate)) { // 'gt' means 'greater than'
                    Log::info("voucherifyVoucherFetched created_at: " . json_encode($voucherifyVoucherFetched->created_at). ", voucher code: " . $voucherCode);
                    Log::info("booking created_at: " . json_encode($booking->created_at) . ", booking id: " . json_encode($booking->id));
                } else {
                    $isNewOrder = true;
                }
            }

            $validateVoucherifyVoucherObject = new ValidateVoucherifyVoucherObject($company->id, $voucherCode, $calculationObject->getSubTotal(), $calculationObject->getServiceCharge(), $employeeWhoOwnsTheVoucher, $isNewOrder);
            $result = $this->validatesVoucherifyVoucher->execute($validateVoucherifyVoucherObject);
            $voucher = [
                "code" => $result->code,
                "discount" => property_exists($result, 'discount') ? $result->discount : null,
                "metadata" => property_exists($result, 'metadata') ? $result->metadata : null,
                "order" => property_exists($result, 'order') ? $result->order : null,
            ];
        }
        else if($redemptionId){
            $result = $this->fetchesVoucherifyRedemption->execute($redemptionId);
            $voucher = [
                "code" => $result->voucher->code ?? null,
                "discount" => null,
                "metadata" => null,
                "order" => $result->order ?? null,
            ];
        }

        if($voucher){
            $totalDiscountAmount = 0;
            $totalAmount = 0;

            if(isset($voucher['order']->total_discount_amount)){
                $totalDiscountAmount = $voucher['order']->total_discount_amount;
            }
            if(isset($voucher['order']->total_amount)){
                $totalAmount = $voucher['order']->total_amount;
            }

            $validatedVoucherObject = new ValidatedVoucherObject(
                isset($voucher['metadata']->name) ? $voucher['metadata']->name : "",
                $voucher['code'],
                $voucher['discount']->type ?? 'AMOUNT',
                $totalDiscountAmount,
                $totalAmount);
            $calculationObject = new CalculationObject($conversionObject, $configurations, $validatedVoucherObject);
        }

        return $calculationObject;
    }

}
