<?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 (isset($_GET['join_queue'])) {
    joinArenaQueue($user['id']);
    header('Location: arena.php');
    exit;
}
if (isset($_GET['leave_queue'])) {
    leaveArenaQueue($user['id']);
    header('Location: arena.php');
    exit;
}
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $target = $_GET['target'] ?? null;
    $result = processArenaAction($user['id'], $action, $target);
    if (isset($result['error'])) {
        $_SESSION['arena_error'] = $result['error'];
    }
    header('Location: arena.php');
    exit;
}

if (isset($_GET['activate_ability'])) {
    $result = activateAbility($user['id']);
    if ($result['success']) {
        $_SESSION['arena_message'] = $result['message'];
    } else {
        $_SESSION['arena_error'] = $result['message'];
    }
    header('Location: arena.php');
    exit;
}
// ========================================

updateLastActivity($_SESSION['user_id']);
$user = getUserById($_SESSION['user_id']);
$user['exp_percent'] = getExpPercent($user['exp']);

$error = $_SESSION['arena_error'] ?? null;
$message = $_SESSION['arena_message'] ?? null;
unset($_SESSION['arena_error'], $_SESSION['arena_message']);

$queueCount = getArenaQueueCount();

$stmt = $pdo->prepare("SELECT 1 FROM arena_queue WHERE user_id = ?");
$stmt->execute([$user['id']]);
$inQueue = (bool)$stmt->fetch();

$currentBattle = getCurrentArenaBattle($user['id']);

if ($currentBattle && $currentBattle['status'] == 'preparing') {
    $created = strtotime($currentBattle['timeout_at']) - 5 * 60;
    if (time() - $created >= 10) {
        startArenaBattle($currentBattle['id']);
        $currentBattle = getCurrentArenaBattle($user['id']);
    }
}

if (!$currentBattle && $queueCount > 0) {
    $timeout = isArenaQueueTimeout();
    if ($queueCount >= 8 || ($timeout && $queueCount >= 1)) {
        $battleCreated = tryFormTeams();
        if ($battleCreated) {
            header('Location: arena.php');
            exit;
        } else {
            $_SESSION['arena_error'] = 'Не удалось создать бой (смотрите логи сервера)';
        }
    }
}

if ($currentBattle && $currentBattle['status'] == 'active') {
    regenerateAllParticipants($currentBattle['id']);
    processBotTurns($currentBattle['id']);

    $participants = getBattleParticipants($currentBattle['id']);
    $team0Alive = 0; $team1Alive = 0;
    foreach ($participants as $p) {
        if ($p['current_health'] > 0) {
            if ($p['team'] == 0) $team0Alive++; else $team1Alive++;
        }
    }

    if (strtotime($currentBattle['timeout_at']) < time()) {
        finishBattleByTimeout($currentBattle['id']);
        header('Location: arena.php');
        exit;
    }

    if ($team0Alive == 0) { finishBattle($currentBattle['id'], 1); header('Location: arena.php'); exit; }
    if ($team1Alive == 0) { finishBattle($currentBattle['id'], 0); header('Location: arena.php'); exit; }
}

$todayBattles = getTodayArenaBattlesCount($user['id']);
$arenaPoints = $user['arena_points'] ?? 0;
$ratingData = getArenaRating($user['id']);

require_once 'inc/header.php';
?>

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

<?php if ($currentBattle): ?>
    <?php
    $battleId = $currentBattle['id'];
    $participants = getBattleParticipants($battleId);
    $myTeam = $currentBattle['team'];

    $attacker = null;
    foreach ($participants as $p) {
        if ($p['user_id'] == $user['id']) {
            $attacker = $p;
            break;
        }
    }
    $playerAlive = ($attacker && $attacker['current_health'] > 0);

    $teamPlayers = []; $enemyPlayers = [];
    foreach ($participants as $p) {
        if ($p['team'] == $myTeam) $teamPlayers[] = $p;
        else $enemyPlayers[] = $p;
    }

    $teamAlive = 0;
    foreach ($teamPlayers as $p) if ($p['current_health'] > 0) $teamAlive++;
    $enemyAlive = 0;
    foreach ($enemyPlayers as $p) if ($p['current_health'] > 0) $enemyAlive++;

    $timeout = strtotime($currentBattle['timeout_at']) - time();
    if ($timeout < 0) $timeout = 0;
    $minutes = floor($timeout / 60);
    $seconds = $timeout % 60;
    $timeString = sprintf("%02d:%02d", $minutes, $seconds);

    $stmt = $pdo->prepare("SELECT * FROM arena_battle_log WHERE battle_id = ? ORDER BY created_at DESC LIMIT 20");
    $stmt->execute([$battleId]);
    $logs = $stmt->fetchAll();
    ?>

    <span class="ttl"><b>Уличная перестрелка</b></span>
    <div class="hr"></div>

    <div>
        <img src="/images/icons/gladiator_blue.png" width="12" height="12" alt=""/> Наши: <span><?= $teamAlive ?></span>
        <img src="/images/icons/gladiator_orange.png" width="12" height="12" alt=""/> Враги: <span><?= $enemyAlive ?></span>
        <img src="/images/icons/clock.png" width="12" height="12" alt=""/> <span><?= $timeString ?></span>
    </div>
    <div class="hr"></div>

    <?php if ($currentBattle['status'] == 'finished'): ?>
        <span class="notify">Бой завершён! Победила команда <?= ($currentBattle['winner'] == $myTeam) ? 'синих' : 'оранжевых' ?>.</span><br/>
        <img class="internalIcon" src="/images/icons/dot.png"/> <a href="arena.php">Вернуться к очереди</a>
    <?php elseif ($currentBattle['status'] == 'preparing'): ?>
        <span class="notify">Бой начнётся через несколько секунд...</span><br/>
        <img class="internalIcon" src="/images/icons/dot.png"/> <a href="arena.php">Обновить</a>
        <script>setTimeout(function() { location.reload(); }, 5000);</script>
    <?php else: ?>
        <?php if (!$playerAlive): ?>
            <span class="notify">Вы мертвы и наблюдаете за боем.</span><br/>
            <script>setTimeout(function() { location.reload(); }, 5000);</script>
        <?php else: ?>
            <?php
            $activeAbility = getActiveAbility($user['id']);
            if ($activeAbility && canUseAbility($user['id'], $activeAbility['ability_id'])):
            ?>
                <a class="flhdr" href="?activate_ability=1">
                    <img src="/images/icons/<?= $activeAbility['icon_star'] ?>" class="internalIcon" alt=""/>
                    Активировать <?= htmlspecialchars($activeAbility['name']) ?>
                </a><br>
            <?php endif; ?>

            <a class="flhdr" href="?action=attack_random">
                <img src="/images/icons/attack.png" class="internalIcon" alt=""/> Бить врагов
            </a>

            <?php
            $firstEnemy = null;
            foreach ($enemyPlayers as $ep) if ($ep['current_health'] > 0) { $firstEnemy = $ep; break; }
            if ($firstEnemy):
                $name = $firstEnemy['is_bot'] ? ($firstEnemy['bot_data']['username'] ?? 'Бот') : htmlspecialchars($firstEnemy['username']);
            ?>
                <br><a class="flhdr" href="?action=attack_target&target=<?= $firstEnemy['id'] ?>">
                    <img src="/images/icons/attack.png" class="internalIcon" alt=""/>
                    Добивать <?= $name ?> (❤️<?= $firstEnemy['current_health'] ?>)
                </a>
            <?php endif; ?>

            <br><a class="flhdr" href="?action=use_medkit">
                <img src="/images/icons/medkit.png" class="internalIcon" alt=""/> Аптечка (<?= $user['medkits'] ?>)
            </a>

            <?php
            $stmt = $pdo->prepare("
                SELECT asa.*, a.name, at.icon_star
                FROM arena_selected_abilities asa
                JOIN abilities a ON asa.ability_id = a.id
                LEFT JOIN ability_tiers at ON a.id = at.ability_id AND at.tier_level = (SELECT tier_level FROM user_abilities WHERE user_id = asa.user_id AND ability_id = asa.ability_id)
                WHERE asa.user_id = ?
                ORDER BY asa.slot
            ");
            $stmt->execute([$user['id']]);
            $abilities = $stmt->fetchAll();

            $usedAbilities = !empty($attacker['used_abilities']) ? json_decode($attacker['used_abilities'], true) : [];
            if (!is_array($usedAbilities)) $usedAbilities = [];

            foreach ($abilities as $ab):
                $disabled = in_array($ab['ability_id'], $usedAbilities) ? 'disabled' : '';
                $starIcon = $ab['icon_star'] ?? 'star_brown.png';
            ?>
                <br><a class="flhdr <?= $disabled ?>" href="?action=use_ability&target=<?= $ab['ability_id'] ?>" onclick="return !<?= $disabled ? 'false' : 'true' ?>;">
                    <img class="internalIcon" src="/images/icons/<?= $starIcon ?>" alt=""/> <?= htmlspecialchars($ab['name']) ?>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>

        <div class="hr"></div>
        <?php foreach ($logs as $log): ?>
            <div><?= htmlspecialchars($log['message']) ?></div>
        <?php endforeach; ?>
    <?php endif; ?>

<?php else: ?>
    <span class="ttl"><b>Уличные перестрелки</b></span>
    <div class="hr"></div>
    <div class="cntr"><img src="/images/icons/ring.png"/></div>
    <div class="hr"></div>
    <img class="internalIcon" src="/images/icons/dot.png"/> <a href="arena.php">Обновить</a><br/>
    <div class="hr"></div>

    <div>
        Очередь:
        <img src="/images/icons/gladiator_blue.png" width="12" height="12" alt=""/>
        <img src="/images/icons/gladiator_orange.png" width="12" height="12" alt=""/>
        <span><?= $queueCount ?></span> <span class="minor">(нужно 8 или 15 сек ожидания)</span>
    </div>

    <div>
        <?php if ($inQueue): ?>
            <img src="/images/icons/dot.png" width="12" height="12" alt=""/> <a href="?leave_queue">Покинуть очередь</a><br/>
        <?php else: ?>
            <img src="/images/icons/dot.png" width="12" height="12" alt=""/> <a href="?join_queue">Встать в очередь</a><br/>
        <?php endif; ?>
    </div>

    <div class="hr"></div>
    <div>
        <img src="/images/icons/dot.png" width="12" height="12" alt=""/> мои игры на перестрелок: <span><?= $todayBattles ?></span>/<span>5</span><br/>
        <img src="/images/icons/dot.png" width="12" height="12" alt=""/> мои очки перестрелки: <img src="/images/icons/arenapoint.png" width="12" height="12" alt=""/><span><?= $arenaPoints ?></span><br/>
        <img src="/images/icons/dot.png" width="12" height="12" alt=""/> мой рейтинг: <span><?= $ratingData['rating'] ?></span><br/>
        <?php if (!empty($ratingData['multiplier_until']) && strtotime($ratingData['multiplier_until']) > time()): ?>
            <span class="notify">Удвоение очков до <?= date('d.m.Y H:i', strtotime($ratingData['multiplier_until'])) ?></span><br/>
        <?php endif; ?>
    </div>

    <div class="hr"></div>
    <span class="notify small">Командные бои 4х4. Проведи 5 боёв и получи очки перестрелок для покупки снаряжения!</span>

    <div class="hr"></div>
    <img src="/images/icons/dot.png" width="12" height="12" alt=""/> <a href="arena_abilities.php">Выбрать умения на бой</a>

    <?php if ($inQueue): ?>
    <script>setTimeout(function() { location.reload(); }, 5000);</script>
    <?php endif; ?>
<?php endif; ?>

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