<?php
// api.php - API для работы с данными турнира
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

// Пути к файлам данных
$playersFile = 'data/players.json';
$tournamentsFile = 'data/tournaments.json';
$configFile = 'data/config.json';

// Создаем папку data если её нет
if (!file_exists('data')) {
    mkdir('data', 0777, true);
}

// Инициализация файлов если их нет
if (!file_exists($playersFile)) {
    $defaultPlayers = [
        ["name" => "ВИКИНГ", "score" => 9850, "photo" => ""],
        ["name" => "БЕРСЕРК", "score" => 9200, "photo" => ""],
        ["name" => "ЯРОСТЬ", "score" => 8750, "photo" => ""],
        ["name" => "ДРАКАР", "score" => 8100, "photo" => ""],
        ["name" => "ОДИН", "score" => 7500, "photo" => ""]
    ];
    file_put_contents($playersFile, json_encode($defaultPlayers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

if (!file_exists($tournamentsFile)) {
    $defaultTournaments = [];
    file_put_contents($tournamentsFile, json_encode($defaultTournaments, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

if (!file_exists($configFile)) {
    // ВАЖНО: ИЗМЕНИТЕ ПАРОЛЬ!
    $defaultConfig = [
        "adminPassword" => password_hash("topor2025", PASSWORD_DEFAULT)
    ];
    file_put_contents($configFile, json_encode($defaultConfig, JSON_PRETTY_PRINT));
}

// Обработка запросов
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'login':
        if ($method === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $password = $data['password'] ?? '';
            $config = json_decode(file_get_contents($configFile), true);
            
            if (password_verify($password, $config['adminPassword'])) {
                session_start();
                $_SESSION['admin'] = true;
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Неверный пароль']);
            }
        }
        break;
        
    case 'checkAuth':
        session_start();
        echo json_encode(['authenticated' => isset($_SESSION['admin']) && $_SESSION['admin']]);
        break;
        
    case 'logout':
        session_start();
        session_destroy();
        echo json_encode(['success' => true]);
        break;
        
    case 'getPlayers':
        $players = json_decode(file_get_contents($playersFile), true);
        echo json_encode($players);
        break;
        
    case 'savePlayers':
        if ($method === 'POST') {
            session_start();
            if (!isset($_SESSION['admin']) || !$_SESSION['admin']) {
                http_response_code(401);
                echo json_encode(['error' => 'Не авторизован']);
                exit;
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            file_put_contents($playersFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            echo json_encode(['success' => true]);
        }
        break;
        
    case 'getTournaments':
        $tournaments = json_decode(file_get_contents($tournamentsFile), true);
        echo json_encode($tournaments);
        break;
        
    case 'saveTournament':
        if ($method === 'POST') {
            session_start();
            if (!isset($_SESSION['admin']) || !$_SESSION['admin']) {
                http_response_code(401);
                echo json_encode(['error' => 'Не авторизован']);
                exit;
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            $tournaments = json_decode(file_get_contents($tournamentsFile), true);
            $tournaments[] = $data;
            file_put_contents($tournamentsFile, json_encode($tournaments, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            echo json_encode(['success' => true]);
        }
        break;
        
    case 'changePassword':
        if ($method === 'POST') {
            session_start();
            if (!isset($_SESSION['admin']) || !$_SESSION['admin']) {
                http_response_code(401);
                echo json_encode(['error' => 'Не авторизован']);
                exit;
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            $newPassword = $data['newPassword'] ?? '';
            
            if (strlen($newPassword) < 6) {
                echo json_encode(['success' => false, 'error' => 'Пароль должен быть не менее 6 символов']);
                exit;
            }
            
            $config = json_decode(file_get_contents($configFile), true);
            $config['adminPassword'] = password_hash($newPassword, PASSWORD_DEFAULT);
            file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
            echo json_encode(['success' => true]);
        }
        break;
        
    default:
        echo json_encode(['error' => 'Неизвестное действие']);
}
?>