<?php

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

use App\Models\User;
use Illuminate\Support\Facades\Log;

class FetchesVoucherifyVoucher
{

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


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

     /**
     * @param User $user
     * @param string $voucherifyVoucherCode
     * @return null|object
     * @throws \Voucherify\ClientException
     */
    public function execute(User $user, string $voucherifyVoucherCode)
    {
        try {
            $result = $this->voucherifyClient->vouchers->get($voucherifyVoucherCode);

            if (isset($result->metadata) && isset($result->metadata->email)) {
                if($user->email != $result->metadata->email){
                    $result->reason = 'Invalid Code';
                }
            }

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