<?php

class EcomZoneAPI
{
    private $apiKey;
    private $apiUrl;
    private $lastRequestTime;
    private $requestCount = 0;
    private const RATE_LIMIT = 120; // requests per minute
    private const RATE_WINDOW = 60; // seconds

    public function __construct()
    {
        $this->apiKey = Configuration::get('ECOMZONE_API_KEY');
        $this->apiUrl = Configuration::get('ECOMZONE_API_URL');
        $this->lastRequestTime = time();
    }

    private function checkRateLimit()
    {
        $currentTime = time();
        if ($currentTime - $this->lastRequestTime >= self::RATE_WINDOW) {
            $this->requestCount = 0;
            $this->lastRequestTime = $currentTime;
        }

        if ($this->requestCount >= self::RATE_LIMIT) {
            throw new Exception('Rate limit exceeded. Please wait before making more requests.');
        }

        $this->requestCount++;
    }

    public function getCatalog($perPage = 1000)
    {
        $this->checkRateLimit();
        $url = $this->apiUrl . '/catalog';
        return $this->makeRequest('GET', $url, ['per_page' => $perPage]);
    }

    public function getProduct($sku)
    {
        $this->checkRateLimit();
        $url = $this->apiUrl . '/product/' . urlencode($sku);
        return $this->makeRequest('GET', $url);
    }

    public function createOrder($orderData)
    {
        $this->checkRateLimit();
        $url = $this->apiUrl . '/ordering';
        return $this->makeRequest('POST', $url, $orderData);
    }

    private function makeRequest($method, $url, $params = [])
    {
        try {
            $curl = curl_init();
            
            $options = [
                CURLOPT_URL => $url . ($method === 'GET' && !empty($params) ? '?' . http_build_query($params) : ''),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $this->apiKey,
                    'Accept: application/json',
                    'Content-Type: application/json'
                ],
            ];

            if ($method === 'POST') {
                $options[CURLOPT_POSTFIELDS] = json_encode($params);
            }

            curl_setopt_array($curl, $options);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            curl_close($curl);

            if ($err) {
                throw new Exception("cURL Error: " . $err);
            }

            if ($httpCode >= 400) {
                throw new Exception("HTTP Error: " . $httpCode . " Response: " . $response);
            }

            return json_decode($response, true);
        } catch (Exception $e) {
            PrestaShopLogger::addLog(
                'EcomZone API Error: ' . $e->getMessage(),
                3,
                null,
                'EcomZone'
            );
            throw $e;
        }
    }
} 