<?php

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

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Support\Facades\Log;

class FetchesVoucherifyCampaign
{

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


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

     /**
     * @param string $campaignId
     * @return null|object
     * @throws \Voucherify\ClientException
     */
    public function execute(string $campaignId)
    {
        //REST API - Direct Query
        try{
            $response = Http::withHeaders([
                'X-App-Id' => config('voucherify.application_id'),
                'X-App-Token' => config('voucherify.client_secret_key'),
            ])
            ->get(config('voucherify.url').'/v1/campaigns/'.$campaignId);

            if($response->successful()){
                $data = $response->json();
                return (object) $data;
            }else{
                Log::error($response);
                return null;
            }
        }catch(\Exception $exception){
            throw new MalformedRequestException('Unable to get correct response from Voucherify: ' . $exception->getMessage());
        }

        //PHP SDK
        // try {
        //     $result = $this->voucherifyClient->campaigns->get($name); //this is undefined in voucherify php sdk
        //     return $result;
        // } catch (\Voucherify\ClientException $e) {
        //     Log::error('FetchesVoucherifyCampaign '.$e);
        //     return null;
        // }
    }
}
