<?php
session_start();
require_once 'inc/functions.php';
check404();
securityCheck();
if (!isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// Обработка сохранения
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['abilities'])) {
    $selected = array_filter(array_map('intval', $_POST['abilities']));
    if (count($selected) > 3) {
        $error = 'Можно выбрать не более 3 умений';
    } else {
        // Удаляем старый выбор
        $pdo->prepare("DELETE FROM arena_selected_abilities WHERE user_id = ?")->execute([$user['id']]);
        // Вставляем новые
        $slot = 1;
        foreach ($selected as $abilityId) {
            $stmt = $pdo->prepare("INSERT INTO arena_selected_abilities (user_id, ability_id, slot) VALUES (?, ?, ?)");
            $stmt->execute([$user['id'], $abilityId, $slot++]);
        }
        $success = 'Умения сохранены';
    }
}

// Получаем все умения игрока
$stmt = $pdo->prepare("
    SELECT ua.*, a.name, a.description, a.icon, at.tier_name, at.icon_star
    FROM user_abilities ua
    JOIN abilities a ON ua.ability_id = a.id
    JOIN ability_tiers at ON ua.ability_id = at.ability_id AND ua.tier_level = at.tier_level
    WHERE ua.user_id = ?
    ORDER BY a.name
");
$stmt->execute([$user['id']]);
$userAbilities = $stmt->fetchAll();

// Получаем уже выбранные
$stmt = $pdo->prepare("SELECT ability_id FROM arena_selected_abilities WHERE user_id = ?");
$stmt->execute([$user['id']]);
$selectedIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

require_once 'inc/header.php';
?>

<span class="ttl"><b>Выбор умений на бой (максимум 3)</b></span>
<div class="hr"></div>

<?php if (isset($success)): ?>
    <div class="info"><?= $success ?></div>
<?php endif; ?>
<?php if (isset($error)): ?>
    <div class="error"><?= $error ?></div>
<?php endif; ?>

<form method="post">
    <table width="100%">
        <?php foreach ($userAbilities as $ab): ?>
            <tr>
                <td width="20">
                    <input type="checkbox" name="abilities[]" value="<?= $ab['ability_id'] ?>" 
                        <?= in_array($ab['ability_id'], $selectedIds) ? 'checked' : '' ?>>
                </td>
                <td width="20"><img src="/images/icons/<?= $ab['icon_star'] ?>" width="16" height="16" alt=""></td>
                <td><b><?= htmlspecialchars($ab['name']) ?></b> (<?= $ab['tier_name'] ?>)</td>
                <td><?= htmlspecialchars($ab['description']) ?></td>
            </tr>
        <?php endforeach; ?>
    </table>
    <div class="hr"></div>
    <input type="submit" value="Сохранить" class="btn">
    <a href="arena.php" class="btn">Назад</a>
</form>

<?php require_once 'inc/foot.php'; ?>