<?php
class LeaseService {
    /**
     * Récupère tous les leases IPv4 via l'API Kea Control Agent.
     * Fonctionne en mode AlmaLinux ET FreeBSD (appel direct à kea-ctrl-agent).
     * Retourne ['success' => bool, 'leases' => array, 'message' => string].
     */
    public static function getLeases(): array {
        $url = rtrim(Settings::get('kea_api_url', 'http://localhost:8000'), '/') . '/';
        if ($url === '/') {
            return ['success' => false, 'leases' => [], 'message' => 'URL Kea Control Agent non configurée.'];
        }

        // Certaines versions de Kea exigent la liste des subnets dans les arguments.
        // On passe tous les kea_subnet_id gérés par l'application.
        $subnetIds = array_map('intval', Database::get()->query(
            'SELECT kea_subnet_id FROM app_subnets ORDER BY kea_subnet_id'
        )->fetchAll(PDO::FETCH_COLUMN));

        $payload = json_encode([
            'command'   => 'lease4-get-all',
            'service'   => ['dhcp4'],
            'arguments' => ['subnets' => $subnetIds],
        ]);
        $headers = ['Content-Type: application/json'];

        $apiUser = Settings::get('kea_api_user', '');
        if ($apiUser !== '') {
            $token     = base64_encode($apiUser . ':' . Settings::get('kea_api_password', ''));
            $headers[] = 'Authorization: Basic ' . $token;
        }

        $result = self::httpPost($url, $payload, $headers);
        if ($result === false) {
            return ['success' => false, 'leases' => [], 'message' => 'Impossible de joindre l\'API Kea : ' . $url];
        }

        $data = json_decode($result, true);
        if (!is_array($data) || !isset($data[0])) {
            return ['success' => false, 'leases' => [], 'message' => 'Réponse invalide de l\'API Kea.'];
        }

        $res = $data[0];
        // result 0 = succès, result 3 = vide (aucun lease trouvé)
        if (!in_array($res['result'] ?? -1, [0, 3], true)) {
            return ['success' => false, 'leases' => [], 'message' => $res['text'] ?? 'Erreur inconnue Kea API'];
        }

        $leases = $res['arguments']['leases'] ?? [];
        return ['success' => true, 'leases' => $leases, 'message' => count($leases) . ' lease(s) trouvé(s)'];
    }

    private static function httpPost(string $url, string $body, array $headers = []): string|false {
        if (!function_exists('curl_init')) {
            $opts = [
                'http' => [
                    'method'         => 'POST',
                    'header'         => implode("\r\n", $headers),
                    'content'        => $body,
                    'timeout'        => 10,
                    'ignore_errors'  => true,
                ],
            ];
            return @file_get_contents($url, false, stream_context_create($opts));
        }

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $body,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_CONNECTTIMEOUT => 5,
        ]);
        $response = curl_exec($ch);
        $err      = curl_errno($ch);
        // curl_close() supprimé : no-op depuis PHP 8.0 (CurlHandle libéré par le GC), déprécié en 8.5
        return $err === 0 ? $response : false;
    }
}
