<?php
declare(strict_types=1);

const URL_API = 'https://api.icefact.ro:10999/v1/demo';
const CERTIFICAT = '10999-demo.crt';
const CHEIE = '10999-demo.key';

class ApiEroare extends RuntimeException
{
    public function __construct(
        public readonly int $status,
        public readonly ?string $cod,
        public readonly mixed $details,
    ) {
        $text = is_string($details) ? $details : json_encode($details, JSON_UNESCAPED_UNICODE);
        parent::__construct(trim("$status $cod $text"));
    }
}

function api_cerere(string $metoda, string $ruta, array $parametri = [], ?array $body = null): mixed
{
    $url = URL_API . '/' . $ruta . ($parametri ? '?' . http_build_query($parametri) : '');
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $metoda,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSLCERT => CERTIFICAT,
        CURLOPT_SSLKEY => CHEIE,
        CURLOPT_TIMEOUT => 120,
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    }

    $continut = curl_exec($ch);
    if ($continut === false) {
        throw new RuntimeException(curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $tip = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $ok = $status >= 200 && $status < 300;

    if (!str_starts_with($tip, 'application/json')) {
        if ($ok) {
            return $continut;
        }
        // pagină HTML: certificat lipsă sau refuzat, rută sau metodă necunoscută
        throw new ApiEroare($status, null, "HTTP $status");
    }
    $raspuns = json_decode($continut, true, 512, JSON_THROW_ON_ERROR);
    if (!$ok) {
        // erorile de parametru ale rutelor search și list nu au details
        throw new ApiEroare($status, $raspuns['cod'] ?? null, $raspuns['details'] ?? $raspuns);
    }
    return $raspuns;
}

function api_get(string $ruta, array $parametri = []): mixed
{
    return api_cerere('GET', $ruta, $parametri);
}

function api_post(string $ruta, array $body): mixed
{
    return api_cerere('POST', $ruta, [], $body);
}
