<?php

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

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

class CreatesVoucherifyCustomer
{

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


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

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

            $customerObj = [
                "source_id" => $object->getUser()->id,
                "name" => $object->getUser()->name,
                "email" => $object->getUser()->email,
                "address" => [
                    "city" => '',
                    "country" => '',
                    "line_1" => '',
                    "line_2" => '',
                    "postal_code" => '',
                    "state" => '',
                ],
            ];

            if ($object->getIsNew()) {
                $customerObj['metadata']["new_customer"] = date('Y-m-d H:i:s');
            }
            if ($object->getCompanyId()) {
                $customerObj['metadata']["exchange_company_id"] = $object->getCompanyId();
                $customerObj['metadata']["exchange_user_id"] = $object->getUser()->id;
            }
            if ($object->getAcquisitionChannel()) {
                $customerObj['metadata']["acquisition"] = $object->getAcquisitionChannel();
            }

            $result = $this->voucherifyClient->customers->create($customerObj);
            return $result;
        } catch (\Voucherify\ClientException $e) {
            // throw $e;
            Log::error('CreatesVoucherifyCustomer '.$e);
            return null;
        }
    }
}
