<?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 Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Booking;

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

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

    /**
     * ValidateVoucherLogic constructor.
     * @param ValidatesVoucherifyVoucher $validatesVoucherifyVoucher
     */
    public function __construct(ValidatesVoucherifyVoucher $validatesVoucherifyVoucher)
    {
        $this->validatesVoucherifyVoucher = $validatesVoucherifyVoucher;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {
        $booking = Booking::find($request->input('itemId'));
        $employee = $booking->company->employees()->first();
        $amount = $this->floatvalue($request->input('amount'));

        $validateVoucherifyVoucherObject = new ValidateVoucherifyVoucherObject($booking->company_id, $request->input('voucherCode'), $amount, $employee);
        $result = $this->validatesVoucherifyVoucher->execute($validateVoucherifyVoucherObject);
        return $this->response(['data' => $result]);
    }

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