<?php

namespace WHMCS\Module\Addon\ProxyCheap;

class API
{
    public const API_URL = 'https://api.proxy-cheap.com/';
    public $apiclient;
    private $apikey;
    private $apisecret;
    private $headers;
    private $URLParams = 'origin=whmcs';

    public function setKey(string $key)
    {
        $this->apikey = $key;
        return $this;
    }
    public function setSecret(string $secret)
    {
        $this->apisecret = $secret;
        return $this;
    }

    public function setHeaders()
    {
        $this->headers = [
            "Accept" => "application/json",
            "Content-Type" => "application/json",

        ];

        if ($this->apikey) {
            $this->headers["X-Api-Key"] = $this->apikey;
        }

        if ($this->apisecret) {
            $this->headers["X-Api-Secret"] = $this->apisecret;
        }
        return $this;
    }
    public function __construct()
    {
        $options = ["base_uri" => self::API_URL];

        $this->apiclient = new \GuzzleHttp\Client($options);
    }

    public function executeGET(string $endpoint, array $payload = [])
    {
        return $this->execute('get', $endpoint, $payload);
    }
    public function executePOST(string $endpoint, array $payload = [])
    {

        return $this->execute('post', $endpoint, $payload);
    }
    public function execute(string $method, string $endpoint, array $payload = [])
    {
        $separator = strpos($endpoint, '?') !== false ? '&' : '?';

        try {
            return json_decode($this->apiclient->$method(
                $endpoint . $separator . $this->URLParams,
                [
                    \GuzzleHttp\RequestOptions::JSON => $payload,
                    \GuzzleHttp\RequestOptions::HEADERS => $this->headers
                ]
            )->getBody()->getContents());
        } catch (\Exception $e) {
            logModuleCall('ProxyCheap', $method . ' ' . $endpoint, $e->getMessage(), $e->getMessage());
            logActivity('Proxy Module Exception: ' . $e->getMessage());
            return;
        }
    }
}
