<?php

namespace App\Classes\Modules\Vouchers\Services\Voucherify;

use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Vouchers\DataTransferObjects\ValidateVoucherifyVoucherObject;
use App\Classes\General\Helper;

class ValidatesVoucherifyVoucher
{

    /** @var VoucherifyClient */
    private $voucherifyClient;


    /**
     * ValidatesVoucherifyVoucher constructor.
     *
     */
    public function __construct()
    {
        $this->voucherifyClient = createVoucherifyClient();
    }

     /**
     * @param ValidateVoucherifyVoucherObject $validateVoucherifyVoucherObject
     * @return null|object
     * @throws \Voucherify\ClientException
     */
    public function execute(ValidateVoucherifyVoucherObject $validateVoucherifyVoucherObject)
    {

        try {
            $validateVoucherObj = [
                "customer" => [
                    "source_id" => $validateVoucherifyVoucherObject->getUser()->id,
                    "name" => $validateVoucherifyVoucherObject->getUser()->name,
                    "email" => $validateVoucherifyVoucherObject->getUser()->email,
                    "metadata" => [
                        "exchange_company_id" => $validateVoucherifyVoucherObject->getCompanyId(),
                        "exchange_user_id" => $validateVoucherifyVoucherObject->getUser()->id
                    ]
                ]
            ];

            $validateVoucherObj['order']['amount'] = $validateVoucherifyVoucherObject->getAmount() * 100; // converting to cents

            if ($validateVoucherifyVoucherObject->getServiceCharge()) {
                $serviceCharge = round($validateVoucherifyVoucherObject->getServiceCharge(), 2);
                $validateVoucherObj['order']['metadata']['service_charge'] = $serviceCharge;
            }
            if ($validateVoucherifyVoucherObject->getIsNewOrder()) {
                $validateVoucherObj['order']['metadata']['is_new_order'] = $validateVoucherifyVoucherObject->getIsNewOrder();
            }

            $result = $this->voucherifyClient->validations->validateVoucher($validateVoucherifyVoucherObject->getVoucherCode(), $validateVoucherObj);

            if (isset($result->metadata) && isset($result->metadata->email)) { // used in CheckMilestonesForRewardProcessor
                if($validateVoucherifyVoucherObject->getUser()->email != $result->metadata->email){
                    $result->reason = 'Invalid Code';
                }
            }

            if (isset($result->reason)) {
                Helper::debugLogger('ValidatesVoucherifyVoucher error: '. $result->reason);
                $result->reason = 'Invalid Code';
            }

            return $result;
        } catch (\Voucherify\ClientException $e) {
            // throw $e;
            Log::error('ValidatesVoucherifyVoucher '.$e);
            return null;
        }
    }
}
