<?php
declare(strict_types=1);

session_start();
require_once __DIR__ . '/session-guard.php';
header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Europe/Paris');

require_active_client_session(false);

function respond_json(int $statusCode, array $payload): void
{
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$configFile = dirname(__DIR__) . '/privatedata/client-config.php';
$themesFile = dirname(__DIR__) . '/privatedata/themes-premium.json';

if (!is_file($configFile)) {
    respond_json(500, [
        'ok' => false,
        'message' => 'Configuration privÃ©e introuvable'
    ]);
}

$config = require $configFile;

if (!is_array($config) || empty($config['access_end'])) {
    respond_json(500, [
        'ok' => false,
        'message' => 'Configuration privÃ©e invalide'
    ]);
}

if (date('Y-m-d') > (string) $config['access_end']) {
    respond_json(403, [
        'ok' => false,
        'message' => 'AccÃ¨s premium expirÃ©'
    ]);
}

if (!is_file($themesFile)) {
    respond_json(500, [
        'ok' => false,
        'message' => 'Base de mots introuvable'
    ]);
}

$allData = json_decode((string) file_get_contents($themesFile), true);

if (!is_array($allData)) {
    respond_json(500, [
        'ok' => false,
        'message' => 'Base de mots invalide'
    ]);
}

$themes = array_values(array_filter(array_map('strval', array_keys($allData))));
natcasesort($themes);

respond_json(200, [
    'ok' => true,
    'themes' => array_values($themes),
    'difficulties' => ['facile', 'moyen', 'difficile'],
    'maxWords' => max(10, (int) ($config['max_words'] ?? 80))
]);
