<?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-kids.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 enfants introuvable'
    ]);
}

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

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

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

respond_json(200, [
    'ok' => true,
    'mode' => 'kids',
    'themes' => array_values($themes),
    'difficulties' => ['facile', 'moyen', 'difficile'],
    'difficultyLabels' => [
        'facile' => 'Facile — 6/7 ans',
        'moyen' => 'Moyen — 8/10 ans',
        'difficile' => 'Difficile — 11 ans et +'
    ],
    'maxWords' => 80
]);