<?php
/**
 * Lightweight API Endpoint for Game Settings
 * 
 * Pobiera snapshot ustawień dla gry (bez wymogu admin role)
 * Endpoint: /api/discipline-settings.php?discipline=ping-pong&snapshot=true
 * 
 * To pozwala grze kliencka pobierać settings na start meczu
 * bez dostępu do panelu administracyjnego
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'error' => 'Only GET method is supported'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== BAZA DANYCH =====
require_once __DIR__ . '/../../administration/includes/config.php';
require_once __DIR__ . '/DisciplineSettingsModel.php';

// ===== PARAMETRY =====
$discipline = $_GET['discipline'] ?? 'ping-pong';
$version = isset($_GET['version']) ? (int)$_GET['version'] : null;

// ===== WALIDACJA =====
$allowed = ['ping-pong', 'rock-paper-scissors', 'table-football'];
if (!in_array($discipline, $allowed, true)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Invalid discipline',
        'allowed' => $allowed
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== POBRANIE USTAWIEŃ =====
try {
    $model = new DisciplineSettingsModel($pdo);

    // Pobierz ustawienia z określonej wersji lub najnowsze
    if ($version !== null) {
        $settings = $model->getSettingsByVersion($discipline, $version);
        if (!$settings) {
            throw new RuntimeException("Settings version $version not found");
        }
    } else {
        $settings = $model->getSettings($discipline);
        if (!$settings) {
            // Jeśli nie ma w bazie, inicjalizuj defaults
            $defaults = DisciplineSettingsModel::getDefaults($discipline);
            // Możemy tu czasem automatycznie je inicjalizować (jako admin ID 0)
            // Ale lepiej je zwrócić bezpośrednio z defaults
            $settings = array_merge($defaults, [
                'discipline' => $discipline,
                'settingsVersion' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => null
            ]);
        }
    }

    // Formatuj snapshot
    $snapshot = [
        'discipline' => $settings['discipline'],
        'settingsVersion' => (int)$settings['settingsVersion'],
        'rules' => [
            'pointsToWin' => (int)$settings['pointsToWin'],
            'setsToWin' => (int)$settings['setsToWin'],
            'serveRotation' => (int)$settings['serveRotation'],
            'specialRules' => $settings['specialRules']
        ],
        'customization' => $settings['customization'] ?? [],
        'snapshotTimestamp' => date('Y-m-d H:i:s')
    ];

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'snapshot' => $snapshot
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>
