<?php

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

use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Vouchers\DataTransferObjects\CreateVoucherifyOrderObject;

class CreatesVoucherifyOrder
{

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


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


    /**
     * @param CreateVoucherifyOrderObject $obj
     * @return null|object
     * @throws \Voucherify\ClientException
     */
    public function execute(CreateVoucherifyOrderObject $obj)
    {
        try {
            $orderObj = [
                "source_id" => $obj->getTransactionId(),
                "customer" => [
                    "source_id" => $obj->getEmployee()->id,
                    "name" => $obj->getEmployee()->name,
                    "email" => $obj->getEmployee()->email,
                    "metadata" => [
                        "exchange_company_id" => $obj->getCompanyId(),
                        "exchange_user_id" => $obj->getEmployee()->id
                    ]
                ],
                "amount" => $obj->getAmount() * 100, //converting it to cents
            ];

            if ($obj->getIsNoVoucher()) {
                $orderObj['metadata']["no_voucher"] = true;
            }

            if ($obj->getIsTopUpWallet()) {
                $orderObj['metadata']["is_wallet_top_up"] = true;
            }

            $result = $this->voucherifyClient->orders->create($orderObj);
            return $result;
        } catch (\Voucherify\ClientException $e) {
            Log::error($e);
            return null;
        }
    }
}
