<?php

class SicService
{
    private string $baseUrl;
    private string $key;
    private int $entity;

    public function __construct()
    {
        $config = require __DIR__ . '/../config/sic.php';

        $this->baseUrl = $config['base_url'];
        $this->key = $config['key'];
        $this->entity = $config['entity'];
    }

    public function getRecords(string $module): array
    {
        $url = "{$this->baseUrl}/recs.php?t={$module}&e={$this->entity}&k={$this->key}";
        return $this->request($url);
    }

    public function getImages(string $module): array
    {
        $url = "{$this->baseUrl}/imgs.php?t={$module}&e={$this->entity}&k={$this->key}";
        return $this->request($url);
    }

    private function request(string $url): array
    {
        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => 'CinemaMexico-IMCINE/1.0'
        ]);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        if ($error) {
            throw new Exception('Error CURL: ' . $error);
        }

        if ($httpCode !== 200) {
            throw new Exception('Error HTTP desde SIC: ' . $httpCode);
        }

        $data = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('JSON inválido desde SIC: ' . json_last_error_msg());
        }

        if (!is_array($data)) {
            throw new Exception('La respuesta del SIC no es un arreglo válido.');
        }

        return $data;
    }
}