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

$userId = $_SESSION['user_id'];
$user = getUserById($userId);

$stmt = $pdo->prepare("SELECT district_id FROM district_players WHERE user_id = ?");
$stmt->execute([$userId]);
$districtId = $stmt->fetchColumn();

if (!$districtId) {
    header('Location: district_select.php');
    exit;
}

$district = getDistrictById($districtId);
if (!$district) {
    exitDistrict($userId);
    header('Location: district_select.php');
    exit;
}

ensureBotsInDistrict($districtId, $userId);
regenerateInBattle($userId);

// Активация конкретного умения
if (isset($_GET['activate_ability']) && is_numeric($_GET['activate_ability'])) {
    $abilityId = (int)$_GET['activate_ability'];
    $result = activateAbility($userId, $abilityId);
    if ($result['success']) {
        $_SESSION['district_message'] = $result['message'];
    } else {
        $_SESSION['district_error'] = $result['message'];
    }
    header('Location: district.php');
    exit;
}

// Атака башни
if (isset($_GET['attack_tower'])) {
    $towerResult = attackTower($userId, $districtId);
    $_SESSION['battle_message'] = $towerResult['message'];
    $_SESSION['battle_data'] = $towerResult;
    header('Location: district.php');
    exit;
}

$opponents = getOpponentsInDistrict($userId, $districtId);
$opponentsCount = count($opponents);

if (isset($_GET['attack_random']) && !empty($opponents)) {
    $randomKeys = array_keys($opponents);
    $randomOpponent = $opponents[$randomKeys[array_rand($randomKeys)]];
    $_SESSION['last_opponent_id'] = $randomOpponent['id'];
    header('Location: district.php?fight=1&opponent_id=' . $randomOpponent['id']);
    exit;
}

$lastOpponentId = $_SESSION['last_opponent_id'] ?? null;
$lastOpponent = null;
if ($lastOpponentId) {
    foreach ($opponents as $op) {
        if ($op['id'] == $lastOpponentId && $op['current_hp'] > 0) {
            $lastOpponent = $op;
            break;
        }
    }
}
if (isset($_GET['attack_last']) && $lastOpponent) {
    header('Location: district.php?fight=1&opponent_id=' . $lastOpponent['id']);
    exit;
}

// Атаки ботов
$botAttacks = [];
$stmt = $pdo->prepare("SELECT user_id FROM district_players WHERE district_id = ? AND is_bot = 1 AND current_hp > 0");
$stmt->execute([$districtId]);
$bots = $stmt->fetchAll();

foreach ($bots as $bot) {
    $botId = $bot['user_id'];
    $stmt = $pdo->prepare("SELECT last_attack_time FROM district_players WHERE user_id = ?");
    $stmt->execute([$botId]);
    $lastAttack = $stmt->fetchColumn();
    $canAttack = true;
    if ($lastAttack) {
        $diff = time() - strtotime($lastAttack);
        $canAttack = $diff >= 5;
    }
    if ($canAttack) {
        $result = botAttackPlayer($botId, $userId);
        if ($result) {
            $botAttacks[] = $result;
        }
    }
}

// Атака игрока
$fightResult = null;
if (isset($_GET['fight']) && isset($_GET['opponent_id'])) {
    $opponentId = (int)$_GET['opponent_id'];
    $fightResult = attackOpponent($userId, $opponentId);
    $user = getUserById($userId);
    $user['exp_percent'] = getExpPercent($user['exp']);
    regenerateInBattle($userId);
}

$stmt = $pdo->prepare("SELECT current_hp, current_stamina FROM district_players WHERE user_id = ?");
$stmt->execute([$userId]);
$myState = $stmt->fetch();

$districtLogs = getDistrictBattleLogs($districtId, 20);

require_once 'inc/header.php';
?>

<span class="ttl">
    <img src="<?= htmlspecialchars($district['icon']) ?>" alt="" border="0"> 
    <b><?= htmlspecialchars($district['name']) ?></b>
</span>
<div class="clb"></div>
<div class="hr"></div>

<div style="margin-bottom:8px;">
    <span class="small">Уровни: <?= $district['level_min'] ?>-<?= $district['level_max'] ?></span><br>
    Владелец: 
    <b class="<?= $district['current_owner'] == 'Коза Ностра' ? 'info' : ($district['current_owner'] == 'Якудза' ? 'minor' : '') ?>">
        <?= $district['current_owner'] ?: 'нейтральная' ?>
    </b>
</div>
<div class="hr"></div>

<div style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap;">
    <?php $tower_hp = max(0, $district['capture_threshold'] - $district['progress']); ?>
    <a href="?attack_tower=1" class="btn">
        <img src="images/icons/attack.png" class="internalIcon" alt=""> Бить башню (<span><?= $tower_hp ?></span> хп)
    </a>

    <?php if ($opponentsCount > 0): ?>
        <a href="?attack_random=1" class="btn">
            <img src="images/icons/attack.png" class="internalIcon" alt=""> Бить врагов
        </a>
    <?php endif; ?>

    <?php if ($lastOpponent): 
        $avatar = $lastOpponent['is_bot'] ? 'images/avatars/bot.png' : getAvatarUrl($lastOpponent['gender']);
    ?>
        <a href="?attack_last=1" class="btn">
            <img src="images/icons/attack.png" class="internalIcon" alt=""> Добивать 
            <img src="<?= $avatar ?>" width="12" height="12"> <?= htmlspecialchars($lastOpponent['username']) ?> 
            (<img src="images/icons/life.png" width="12" height="12"> <?= $lastOpponent['current_hp'] ?>)
        </a>
    <?php endif; ?>

    <?php
    $abilities = getUserAbilities($userId);
    foreach ($abilities as $ab):
        $canUse = canUseAbility($userId, $ab['ability_id']);
        $activeUntil = $ab['active_until'] ? strtotime($ab['active_until']) : 0;
        $cooldownUntil = $ab['cooldown_until'] ? strtotime($ab['cooldown_until']) : 0;
        $now = time();
        $state = '';
        if ($activeUntil > $now) $state = '⚡ Действует';
        elseif ($cooldownUntil > $now) $state = '🕒 Перезарядка';
        else $state = 'Готово';
    ?>
        <a href="?activate_ability=<?= $ab['ability_id'] ?>" class="btn <?= $canUse ? '' : 'disabled' ?>" style="margin-left:5px;">
            <img src="images/icons/star_gray.png" class="internalIcon" alt=""> <?= htmlspecialchars($ab['name']) ?> (<?= $state ?>)
        </a>
    <?php endforeach; ?>
</div>
<div class="hr"></div>

<?php if ($fightResult && isset($fightResult['success']) && $fightResult['success']): ?>
    <div style="margin-bottom:15px;">
        <div>
            <img src="/images/icons/attack.png" width="12" height="12" alt=""> 
            <span><?= $fightResult['damage_dealt'] ?></span>
            <img src="/images/icons/life.png" width="12" height="12" alt="">
            <span style="color:#6FCD72;">+<?= $fightResult['defender_new_hp'] ?></span>
        </div>
        <div class="hr"></div>
        <div>
            Ты ударил 
            <?php if ($fightResult['is_bot_defender']): ?>
                <img src="/images/icons/red_warrior.png" width="12" height="12" alt=""> 
                <span><?= htmlspecialchars($fightResult['defender_name']) ?></span>
            <?php else: ?>
                <img src="<?= getAvatarUrl($fightResult['defender_gender'] ?? 'Мужской') ?>" width="12" height="12" alt=""> 
                <a href="user.php?id=<?= $fightResult['defender_id'] ?>"><?= htmlspecialchars($fightResult['defender_name']) ?></a>
            <?php endif; ?>
            на <?= $fightResult['damage_dealt'] ?>
            <?php if ($fightResult['is_crit']): ?><span class="crit">(крит)</span><?php endif; ?>
        </div>
        <?php if ($fightResult['district_captured']): ?>
            <div style="color:green; margin-top:5px;">🎉 Вы захватили район и получили 50 баксов!</div>
        <?php endif; ?>
    </div>
    <div class="hr"></div>
<?php elseif ($fightResult && isset($fightResult['miss'])): ?>
    <div class="battle-result" style="margin-bottom:15px;">
        <b class="minor">ПРОМАХ!</b>
        <div class="small">Атакуйте не чаще 1 раза в 5 секунд.</div>
    </div>
    <div class="hr"></div>
<?php elseif ($fightResult && !$fightResult['success']): ?>
    <div class="battle-result" style="margin-bottom:15px;">
        <b class="minor">Ошибка</b>
        <div class="small"><?= htmlspecialchars($fightResult['message']) ?></div>
    </div>
    <div class="hr"></div>
<?php endif; ?>

<?php if (!empty($botAttacks)): ?>
    <div style="background:#fff3cd; border-left:4px solid #ffc107; padding:8px; margin-bottom:10px;">
        <b>⚔️ Атаки противников</b>
        <?php foreach ($botAttacks as $ba): ?>
            <div class="small" style="margin-top:5px;">
                <img src="/images/icons/red_warrior.png" width="12" height="12" alt=""> 
                <b><?= htmlspecialchars($ba['bot_name']) ?></b> атакует вас!<br>
                Урон: <?= $ba['damage'] ?> (заблокировано: <?= $ba['damage_blocked'] ?>)<br>
                <?php if ($ba['is_crit']): ?><span class="crit">Критический удар!</span><br><?php endif; ?>
                Вы получили <?= $ba['player_exp'] ?> опыта и <?= $ba['player_participation'] ?> участия.<br>
                Ваше здоровье: <?= $ba['player_new_hp'] ?>/<?= $user['health'] ?><br>
                <?php if ($ba['player_killed']): ?>
                    <span style="color:red;">Вы были убиты и покинули район!</span>
                    <?php echo '<meta http-equiv="refresh" content="2;url=district_select.php">'; ?>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <div class="hr"></div>
<?php endif; ?>

<div class="hr"></div>
<span class="ttl"><b>Лог боя</b></span>
<div class="hr"></div>
<div style="max-height:300px; overflow-y:auto; background:#f9f9f9; padding:5px; border:1px solid #0e0429;">
<?php if (empty($districtLogs)): ?>
    <div class="small cntr">Пока нет записей</div>
<?php else: ?>
    <?php foreach ($districtLogs as $log): ?>
        <div class="small" style="border-bottom:1px dotted #ccc; padding:2px 0;">
            [<?= date('H:i:s', strtotime($log['created_at'])) ?>] 
            <?= htmlspecialchars($log['message']) ?>
        </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>
<div class="hr"></div>

<div class="cntr">
    <?php if ($opponentsCount == 0): ?>
        В районе нет врагов. Подождите, они появятся...
    <?php else: ?>
        Противников в районе: <b><?= $opponentsCount ?></b>
    <?php endif; ?>
</div>

<div class="hr"></div>
<a href="district_select.php" class="btn full">Сменить район</a>
<a href="exit_district.php" class="btn full">Покинуть район</a>

<script>
setTimeout(function() { location.reload(); }, 5000);
</script>

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