<?php

declare(strict_types=1);

namespace QrStudio\Sdk;

/**
 * QrStudio Official Lightweight PHP SDK (v5.9.0) — Zero external dependencies (cURL only).
 */
class QrStudioClient
{
    private string $baseUrl;
    private string $apiKey;
    private int $timeout;

    public function __construct(string $baseUrl, string $apiKey, int $timeout = 20)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiKey = $apiKey;
        $this->timeout = max(3, $timeout);
    }

    public function health(): array
    {
        return $this->request('GET', '/api/v5/health');
    }

    public function listCampaigns(): array
    {
        return $this->request('GET', '/api/v5/campaigns');
    }

    public function listOrders(): array
    {
        return $this->request('GET', '/api/v5/orders');
    }

    public function listCustomers(): array
    {
        return $this->request('GET', '/api/v5/customers');
    }

    public function upsertCustomer(array $payload): array
    {
        return $this->request('POST', '/api/v5/customers', $payload);
    }

    public function listLoyaltyAccounts(): array
    {
        return $this->request('GET', '/api/v5/loyalty');
    }

    public function sandboxCreate(string $resourceType, array $data): array
    {
        return $this->request('POST', '/api/v5/sandbox', [
            'resource_type' => $resourceType,
            'data' => $data,
        ]);
    }

    public function request(string $method, string $path, ?array $body = null): array
    {
        $ch = curl_init($this->baseUrl . $path);
        $headers = [
            'Accept: application/json',
            'X-API-KEY: ' . $this->apiKey,
        ];
        $opts = [
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
        ];
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        $opts[CURLOPT_HTTPHEADER] = $headers;
        curl_setopt_array($ch, $opts);
        $raw = curl_exec($ch);
        $err = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($err !== '') {
            return ['success' => false, 'http_code' => 0, 'error' => $err];
        }
        $decoded = is_string($raw) ? json_decode($raw, true) : null;
        return is_array($decoded) ? array_merge(['http_code' => $code], $decoded) : ['success' => false, 'http_code' => $code, 'raw' => $raw];
    }
}
