<?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;
}

$abilityId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$ability = getAbility($abilityId);
if (!$ability) {
    header('Location: ability_shop.php');
    exit;
}

$tiers = getAbilityTiers($abilityId);
$userAbility = getUserAbility($user['id'], $abilityId);
$currentTier = $userAbility ? $userAbility['tier_level'] : 0;

// Обработка покупки
$purchaseMessage = '';
if (isset($_GET['buy'])) {
    $buyTier = (int)$_GET['buy'];
    if ($buyTier == $currentTier + 1 && $buyTier <= 6) {
        $result = purchaseAbility($user['id'], $abilityId, $buyTier);
        if ($result['success']) {
            $purchaseMessage = '<div class="info">' . $result['message'] . '</div>';
            // Обновляем данные
            $user = getUserById($_SESSION['user_id']);
            $userAbility = getUserAbility($user['id'], $abilityId);
            $currentTier = $userAbility ? $userAbility['tier_level'] : 0;
        } else {
            $purchaseMessage = '<div class="error">' . $result['message'] . '</div>';
        }
    } else {
        $purchaseMessage = '<div class="error">Невозможно купить этот уровень (требуется сначала купить предыдущий).</div>';
    }
}

require_once 'inc/header.php';
?>

<span class="ttl"><b><?= htmlspecialchars($ability['name']) ?></b></span>
<div class="clb"></div>
<div class="hr"></div>

<p>
    <img width="40" height="40" src="/images/ability/<?= $ability['icon'] ?>" alt="" style="float:left;margin-right:6px;">
    <img width="12" height="12" src="/images/icons/star_default.png" alt=""> 
    <span><b><?= htmlspecialchars($ability['name']) ?></b> <?= $ability['description'] ?></span>
</p>
<div style="clear:both;"></div>

<?= $purchaseMessage ?>

<div class="hr"></div>

<?php foreach ($tiers as $tier): 
    $isOwned = ($currentTier >= $tier['tier_level']);
    $canBuy = ($currentTier == $tier['tier_level'] - 1);
    $starIcon = $tier['icon_star'];
?>
    <div>
        <div class="hr"></div>
        <img width="12" height="12" src="/images/icons/<?= $starIcon ?>" alt=""/> 
        <span><?= htmlspecialchars($ability['name']) ?></span>, <span><?= $tier['tier_name'] ?></span><br/>
        <span>
            <span class=""><img width="12" height="12" src="/images/icons/<?= $starIcon ?>" alt=""/> 
            <?php
            switch ($ability['effect_type']) {
                case 'attack_multiplier': echo 'сила атаки'; break;
                case 'defense_percent':   echo 'процент защиты'; break;
                case 'evasion':            echo 'уклонение'; break;
                case 'crit_chance':        echo 'крит. шанс'; break;
                default: echo 'эффект';
            }
            ?>: 
            <span class="info"><?= $tier['effect_value'] ?>%</span>
            </span>
        </span><br/>

        <?php if ($isOwned): ?>
            <span class="info">✓ Уже куплено</span>
        <?php elseif ($canBuy): ?>
            [<a href="?id=<?= $abilityId ?>&buy=<?= $tier['tier_level'] ?>">купить</a>] 
            цена: <span><img src="images/icons/money_gold.png" width="12" height="12" alt="з"/><?= $tier['price_gold'] ?></span>
        <?php else: ?>
            <span class="minor">[купить] цена: <img src="images/icons/money_gold.png" width="12" height="12" alt="з"/><?= $tier['price_gold'] ?></span>
            <span class="minor">(доступно после покупки предыдущего уровня)</span>
        <?php endif; ?>
        <br/>
    </div>
<?php endforeach; ?>

<div class="hr"></div>
<a href="ability_shop.php" class="btn full">← Вернуться в магазин</a>

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