<?php

namespace App\Classes\Modules\Vouchers\ControllersLogic;


use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Vouchers\Services\Voucherify\ValidatesVoucherifyVoucher;
use App\Classes\Modules\Vouchers\DataTransferObjects\ValidateVoucherifyVoucherObject;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Classes\Modules\Vouchers\Services\Voucherify\FetchesVoucherifyVoucher;
use App\Classes\Modules\Bookings\DataTransferObjects\CalculationObject;
use App\Classes\Modules\Companies\Services\FetchesCompanyServiceSettings;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Models\Booking;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Carbon;

class ValidateVoucherLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Validate Voucher',
            'message' => 'You have successfully validated a voucher'
        ];
    }

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

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

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

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

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

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {
        $employeeWhoOwnsTheVoucher = null;
        $booking = Booking::find($request->input('itemId'));

        //Need to get amount in MYR, not currency to be exchanged - starts
        $conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $booking->convertible_currency_id, $booking->service_id,  $booking->fix_currency_id === 1 ? 0:1); //default $paymentMethod = PaymentMethodType::CASH

        if($conversionObject->getAmount() <= 0) throw new MalformedRequestException('Your transfer must be greater than zero.');

        $configurations = $this->fetchesCompanyServiceSettings->execute($booking->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);
        //Need to get amount in MYR, not currency to be exchanged - ends

        $employees = $booking->company->employees()->get();

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

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


        $isNewOrder = false;
        $voucherifyVoucherFetched = $this->fetchesVoucherifyVoucher->execute($employeeWhoOwnsTheVoucher, $request->input('voucherCode'));
        if($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: " . $request->input('voucherCode'));
                Log::info("booking created_at: " . json_encode($booking->created_at) . ", booking id: " . json_encode($booking->id));
                Log::info("The voucherify voucher was created later than the booking.");
            } else {
                $isNewOrder = true;
            }
        }

        $validateVoucherifyVoucherObject = new ValidateVoucherifyVoucherObject($booking->company_id, $request->input('voucherCode'), $calculationObject->getTotal(), $calculationObject->getServiceCharge(), $employeeWhoOwnsTheVoucher, $isNewOrder);
        $result = $this->validatesVoucherifyVoucher->execute($validateVoucherifyVoucherObject);
        Log::info("ValidateVoucherLogic validatesVoucherifyVoucher: " .json_encode($result));

        return $this->response(['data' => $result]);
    }

    private function floatvalue($val){
        $val = str_replace(",",".",$val);
        $val = preg_replace('/\.(?=.*\.)/', '', $val);
        return floatval($val);
    }
}
