<?php

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

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

class RedeemsVoucherifyVoucher
{

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


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

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

            $redeemVoucherObject['order']['metadata']['transaction_id'] = $redeemVoucherifyVoucherObject->getTransactionId();

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

            $result = $this->voucherifyClient->redemptions->redeem($redeemVoucherifyVoucherObject->getPromoCode(), $redeemVoucherObject);

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