<?php

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


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

class ListsVoucherifyVouchers
{

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


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

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

        //PHP SDK
//         try {
//             $listVouchers = $this->voucherifyClient->vouchers->getList([
//                 "campaign" => $campaignName,
//             ]);
//             if (isset($listVouchers->vouchers) && isset($listVouchers->total) && $listVouchers->total > 0) {
//                 $campaignId = $listVouchers->vouchers[0]->campaign_id;
//             }
//         } catch (\Voucherify\ClientException $e) {
//             Log::error('ListsVoucherifyVouchers '.$e);
//             return null;
//         }

        //REST API - Direct Query
        try{
            $dateRange = $this->getDateRangeForMonth(Carbon::now()->year, Carbon::now()->month);
            $queryString = http_build_query([
                'limit' => 50,
                'campaign_id' => $campaignId,
                '[created_at][after]' => $dateRange['start'],
                '[created_at][before]' => $dateRange['end'],
            ]);
            //$queryString = 'limit=50&campaign_id=' . $campaignId  . '&[created_at][after]='. $dateRange['start'] . '&[created_at][before]='. $dateRange['end'];
            $response = Http::withHeaders([
                'X-App-Id' => config('voucherify.application_id'),
                'X-App-Token' => config('voucherify.client_secret_key'),
            ])
            ->get(config('voucherify.url').'/v1/vouchers?'.$queryString);

            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());
        }
    }

    private function getDateRangeForMonth($year, $month) {
        $startDate = Carbon::createFromFormat('Y-m-d H:i:s', "{$year}-{$month}-01 00:00:00", 'Asia/Kuala_Lumpur')->startOfDay()->setTimezone('UTC');
        $endDate = Carbon::createFromFormat('Y-m-d H:i:s', "{$year}-{$month}-01 00:00:00", 'Asia/Kuala_Lumpur')->endOfMonth()->setTimezone('UTC');

        return [
            'start' => $startDate->toISOString(),
            'end' => $endDate->toISOString(), //'2024-07-11T15:59:59.999999Z'
        ];
    }
}
