<?php
session_start();
require_once '../inc/admin_auth.php';
requireAdmin();
require_once '../inc/functions.php';

$userId = $_GET['id'] ?? null;

if ($userId) {
    $profile = getUserById($userId);
    if (!$profile) {
        $_SESSION['admin_message'] = '❌ Пользователь не найден.';
        header('Location: users.php');
        exit;
    }
    $banHistory = getUserBanHistory($userId);

    // Обработка POST-запросов
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'ban':
                    $reason = $_POST['reason'] ?? '';
                    $until = !empty($_POST['banned_until']) ? $_POST['banned_until'] : null;
                    $pdo->prepare("UPDATE users SET is_banned=1, ban_reason=?, banned_at=NOW(), banned_until=? WHERE id=?")
                        ->execute([$reason, $until, $userId]);
                    addBanHistory($userId, $_SESSION['user_id'], 'ban', $reason, $until, null);
                    $_SESSION['admin_message'] = '✅ Пользователь забанен.';
                    break;
                case 'unban':
                    $pdo->prepare("UPDATE users SET is_banned=0, ban_reason=NULL, banned_at=NULL, banned_until=NULL WHERE id=?")
                        ->execute([$userId]);
                    addBanHistory($userId, $_SESSION['user_id'], 'unban', 'Снятие бана');
                    $_SESSION['admin_message'] = '✅ Бан снят.';
                    break;
                case 'mute':
                    $reason = $_POST['reason'] ?? '';
                    $until = !empty($_POST['muted_until']) ? $_POST['muted_until'] : null;
                    $pdo->prepare("UPDATE users SET is_muted=1, muted_until=? WHERE id=?")
                        ->execute([$until, $userId]);
                    addBanHistory($userId, $_SESSION['user_id'], 'mute', $reason, null, $until);
                    $_SESSION['admin_message'] = '✅ Мут установлен.';
                    break;
                case 'unmute':
                    $pdo->prepare("UPDATE users SET is_muted=0, muted_until=NULL WHERE id=?")
                        ->execute([$userId]);
                    addBanHistory($userId, $_SESSION['user_id'], 'unmute', 'Снятие мута');
                    $_SESSION['admin_message'] = '✅ Мут снят.';
                    break;
                case 'edit_stats':
                    // Обновляем базовые характеристики
                    $baseData = [
                        'base_attack'   => $_POST['base_attack'],
                        'base_health'   => $_POST['base_health'],
                        'base_defense'  => $_POST['base_defense'],
                        'base_stamina'  => $_POST['base_stamina'],
                        'base_accuracy' => $_POST['base_accuracy'],
                        'base_recovery' => $_POST['base_recovery'],
                        'mastery'       => $_POST['mastery']
                    ];
                    updateUserFull($userId, $baseData);
                    recalcUserStats($userId);
                    $_SESSION['admin_message'] = '✅ Базовые характеристики обновлены.';
                    break;
                case 'edit_full':
                    // Обновляем основные поля (включая базовые и другие)
                    $allowed = ['username','role','side','gender','clan_id','gold','bucks','medkits','energy','max_energy','bag_max','exp','level','mastery','base_attack','base_health','base_defense','base_stamina','base_accuracy','base_recovery','talent_points_total','talent_points_spent','achievement_points','bonus_attack','bonus_health','bonus_defense','bonus_stamina','bonus_recovery'];
                    $data = [];
                    foreach ($allowed as $field) {
                        if (isset($_POST[$field])) {
                            $data[$field] = $_POST[$field];
                        }
                    }
                    if (isset($data['exp'])) {
                        $data['level'] = getLevelByExp($data['exp']);
                    }
                    updateUserFull($userId, $data);
                    recalcUserStats($userId);
                    $_SESSION['admin_message'] = '✅ Основные данные обновлены.';
                    break;
            }
            header("Location: users.php?id=$userId");
            exit;
        }
    }

    require_once '../inc/header.php';
    ?>
    <style>
        .tab-container { margin-top: 20px; }
        .tabs { display: flex; border-bottom: 2px solid #ccc; margin-bottom: 15px; }
        .tab { padding: 8px 16px; cursor: pointer; border: 1px solid #ccc; border-bottom: none; background: #f0f0f0; margin-right: 5px; border-radius: 4px 4px 0 0; }
        .tab.active { background: white; border-bottom: 2px solid white; margin-bottom: -2px; font-weight: bold; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .stat-input { width: 120px; padding: 4px; margin: 2px; }
        .btn { display:inline-block; padding:6px 12px; background:#3498db; color:white; text-decoration:none; border-radius:4px; border:none; cursor:pointer; }
        .btn.danger { background:#e74c3c; }
        .btn.warning { background:#f39c12; }
        .btn:hover { opacity:0.9; }
    </style>

    <span class="ttl"><b>📋 Редактирование: <?= htmlspecialchars($profile['username']) ?></b></span>
    <div class="clb"></div>
    <div class="hr"></div>

    <?php if (isset($_SESSION['admin_message'])): ?>
        <div style="border:1px solid green; background:#e0ffe0; padding:10px; margin-bottom:10px;">
            <?= $_SESSION['admin_message']; unset($_SESSION['admin_message']); ?>
        </div>
    <?php endif; ?>

    <div class="menu">
        <a class="btn full" href="users.php">
            <span class="nwr"><img src="/images/icons/arrow.png" width="12" height="12"/> ← Вернуться к списку</span>
        </a>
    </div>

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

    <div class="tab-container">
        <div class="tabs">
            <div class="tab active" data-tab="main">Основное</div>
            <div class="tab" data-tab="stats">Характеристики</div>
            <div class="tab" data-tab="ban">Блокировка</div>
            <div class="tab" data-tab="history">История</div>
            <div class="tab" data-tab="extra">Дополнительно</div>
        </div>

        <!-- Вкладка Основное -->
        <div class="tab-content active" id="tab-main">
            <form method="post">
                <input type="hidden" name="action" value="edit_full">
                <input type="hidden" name="user_id" value="<?= $userId ?>">
                <table class="tables" style="width:100%;">
                    <tr><th style="width:200px;">Поле</th><th>Значение</th></tr>
                    <tr><td>ID:</td><td><?= $profile['id'] ?></td></tr>
                    <tr><td>Имя пользователя:</td><td><input type="text" name="username" value="<?= htmlspecialchars($profile['username']) ?>" class="stat-input"></td></tr>
                    <tr><td>Роль:</td><td>
                        <select name="role" class="stat-input">
                            <option value="player" <?= $profile['role']=='player'?'selected':'' ?>>Игрок</option>
                            <option value="moderator" <?= $profile['role']=='moderator'?'selected':'' ?>>Модератор</option>
                            <option value="support" <?= $profile['role']=='support'?'selected':'' ?>>Поддержка</option>
                            <option value="admin" <?= $profile['role']=='admin'?'selected':'' ?>>Администратор</option>
                        </select>
                    </td></tr>
                    <tr><td>Сторона:</td><td>
                        <select name="side" class="stat-input">
                            <option value="Коза Ностра" <?= $profile['side']=='Коза Ностра'?'selected':'' ?>>Коза Ностра</option>
                            <option value="Якудза" <?= $profile['side']=='Якудза'?'selected':'' ?>>Якудза</option>
                        </select>
                    </td></tr>
                    <tr><td>Пол:</td><td>
                        <select name="gender" class="stat-input">
                            <option value="Мужской" <?= $profile['gender']=='Мужской'?'selected':'' ?>>Мужской</option>
                            <option value="Женский" <?= $profile['gender']=='Женский'?'selected':'' ?>>Женский</option>
                        </select>
                    </td></tr>
                    <tr><td>ID клана:</td><td><input type="number" name="clan_id" value="<?= $profile['clan_id'] ?>" class="stat-input" placeholder="0 = нет"></td></tr>
                    <tr><td>💰 Золото:</td><td><input type="number" name="gold" value="<?= $profile['gold'] ?>" class="stat-input"></td></tr>
                    <tr><td>💵 Баксы:</td><td><input type="number" name="bucks" value="<?= $profile['bucks'] ?>" class="stat-input"></td></tr>
                    <tr><td>🔮 Опыт:</td><td><input type="number" name="exp" value="<?= $profile['exp'] ?>" class="stat-input"></td></tr>
                    <tr><td>🎚️ Уровень (авто):</td><td><span id="level-display"><?= $profile['level'] ?></span> (изменится при сохранении опыта)</td></tr>
                </table>
                <div class="menu" style="margin-top:10px;">
                    <button type="submit" class="btn full">Сохранить изменения</button>
                </div>
            </form>
        </div>

        <!-- Вкладка Характеристики -->
        <div class="tab-content" id="tab-stats">
            <form method="post">
                <input type="hidden" name="action" value="edit_stats">
                <input type="hidden" name="user_id" value="<?= $userId ?>">
                <table class="tables" style="width:100%;">
                    <tr><th style="width:200px;">Параметр (базовый)</th><th>Значение</th><th>Итоговый (после пересчёта)</th></tr>
                    <tr><td>⚔️ Атака (база):</td><td><input type="number" name="base_attack" value="<?= $profile['base_attack'] ?>" class="stat-input"></td><td><?= $profile['attack'] ?></td></tr>
                    <tr><td>❤️ Здоровье (база):</td><td><input type="number" name="base_health" value="<?= $profile['base_health'] ?>" class="stat-input"></td><td><?= $profile['health'] ?></td></tr>
                    <tr><td>🛡️ Защита (база):</td><td><input type="number" name="base_defense" value="<?= $profile['base_defense'] ?>" class="stat-input"></td><td><?= $profile['defense'] ?></td></tr>
                    <tr><td>⚡ Выносливость (база):</td><td><input type="number" name="base_stamina" value="<?= $profile['base_stamina'] ?>" class="stat-input"></td><td><?= $profile['stamina'] ?></td></tr>
                    <tr><td>🎯 Точность (база):</td><td><input type="number" step="0.1" name="base_accuracy" value="<?= $profile['base_accuracy'] ?>" class="stat-input"></td><td><?= $profile['accuracy'] ?></td></tr>
                    <tr><td>🔄 Восстановление (база):</td><td><input type="number" name="base_recovery" value="<?= $profile['base_recovery'] ?>" class="stat-input"></td><td><?= $profile['recovery'] ?></td></tr>
                    <tr><td>🔮 Мастерство (%):</td><td><input type="number" step="0.1" name="mastery" value="<?= $profile['mastery'] ?>" class="stat-input"></td><td>—</td></tr>
                    <tr><td>📊 Сумма статов (итог):</td><td colspan="2"><strong><?= $profile['total_stats'] ?></strong></td></tr>
                </table>
                <div class="menu" style="margin-top:10px;">
                    <button type="submit" class="btn full">Сохранить базовые характеристики</button>
                </div>
            </form>
        </div>

        <!-- Вкладка Блокировка -->
        <div class="tab-content" id="tab-ban">
            <div style="display:flex; gap:20px; flex-wrap:wrap;">
                <div style="flex:1; min-width:250px;">
                    <h3><img src="/images/icons/ban.png" width="12" height="12"> Бан</h3>
                    <?php if ($profile['is_banned']): ?>
                        <p style="color:red;">⚠ Забанен до: <?= $profile['banned_until'] ?: 'навсегда' ?></p>
                        <p><strong>Причина:</strong> <?= htmlspecialchars($profile['ban_reason'] ?: 'не указана') ?></p>
                        <form method="post">
                            <input type="hidden" name="action" value="unban">
                            <button type="submit" class="btn">Разбанить</button>
                        </form>
                    <?php else: ?>
                        <form method="post">
                            <input type="hidden" name="action" value="ban">
                            <table>
                                <tr><td>Причина:</td><td><input type="text" name="reason" required></td></tr>
                                <tr><td>До (YYYY-MM-DD HH:MM):</td><td><input type="text" name="banned_until" placeholder="пусто = навсегда"></td></tr>
                            </table>
                            <button type="submit" class="btn danger">Забанить</button>
                        </form>
                    <?php endif; ?>
                </div>
                <div style="flex:1; min-width:250px;">
                    <h3><img src="/images/icons/mute.png" width="12" height="12"> Мут</h3>
                    <?php if ($profile['is_muted']): ?>
                        <p style="color:orange;">🔇 Замучен до: <?= $profile['muted_until'] ?: 'навсегда' ?></p>
                        <form method="post">
                            <input type="hidden" name="action" value="unmute">
                            <button type="submit" class="btn">Снять мут</button>
                        </form>
                    <?php else: ?>
                        <form method="post">
                            <input type="hidden" name="action" value="mute">
                            <table>
                                <tr><td>Причина:</td><td><input type="text" name="reason"></td></tr>
                                <tr><td>До (YYYY-MM-DD HH:MM):</td><td><input type="text" name="muted_until" placeholder="пусто = навсегда"></td></tr>
                            </table>
                            <button type="submit" class="btn warning">Замутить</button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Вкладка История -->
        <div class="tab-content" id="tab-history">
            <?php if (empty($banHistory)): ?>
                <p class="minor">История пуста.</p>
            <?php else: ?>
                <table class="tables" style="width:100%;">
                    <tr><th>Дата</th><th>Админ</th><th>Действие</th><th>Причина</th><th>Срок</th></tr>
                    <?php foreach ($banHistory as $log): ?>
                    <tr>
                        <td><?= date('d.m.Y H:i', strtotime($log['created_at'])) ?></td>
                        <td><?= htmlspecialchars($log['admin_name']) ?></td>
                        <td><?php 
                            switch ($log['action']) {
                                case 'ban': echo '🔨 Бан'; break;
                                case 'unban': echo '✅ Разбан'; break;
                                case 'mute': echo '🔇 Мут'; break;
                                case 'unmute': echo '🔊 Снятие мута'; break;
                            }
                        ?></td>
                        <td><?= htmlspecialchars($log['reason']) ?></td>
                        <td><?= $log['banned_until'] ?? $log['muted_until'] ?? '—' ?></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            <?php endif; ?>
        </div>

        <!-- Вкладка Дополнительно -->
        <div class="tab-content" id="tab-extra">
            <form method="post">
                <input type="hidden" name="action" value="edit_full">
                <input type="hidden" name="user_id" value="<?= $userId ?>">
                <table class="tables" style="width:100%;">
                    <tr><th style="width:200px;">Поле</th><th>Значение</th></tr>
                    <tr><td>❤️‍🔥 Аптечки:</td><td><input type="number" name="medkits" value="<?= $profile['medkits'] ?>" class="stat-input"></td></tr>
                    <tr><td>⚡ Энергия:</td><td><input type="number" name="energy" value="<?= $profile['energy'] ?>" class="stat-input"></td></tr>
                    <tr><td>🔋 Макс. энергия:</td><td><input type="number" name="max_energy" value="<?= $profile['max_energy'] ?>" class="stat-input"></td></tr>
                    <tr><td>🎒 Размер сумки:</td><td><input type="number" name="bag_max" value="<?= $profile['bag_max'] ?>" class="stat-input"></td></tr>
                    <tr><td>✨ Очки талантов (всего):</td><td><input type="number" name="talent_points_total" value="<?= $profile['talent_points_total'] ?>" class="stat-input"></td></tr>
                    <tr><td>✨ Очки талантов (потрачено):</td><td><input type="number" name="talent_points_spent" value="<?= $profile['talent_points_spent'] ?>" class="stat-input"></td></tr>
                    <tr><td>🏆 Очки достижений:</td><td><input type="number" name="achievement_points" value="<?= $profile['achievement_points'] ?>" class="stat-input"></td></tr>
                    <tr><td>➕ Бонус атаки:</td><td><input type="number" name="bonus_attack" value="<?= $profile['bonus_attack'] ?>" class="stat-input"></td></tr>
                    <tr><td>➕ Бонус здоровья:</td><td><input type="number" name="bonus_health" value="<?= $profile['bonus_health'] ?>" class="stat-input"></td></tr>
                    <tr><td>➕ Бонус защиты:</td><td><input type="number" name="bonus_defense" value="<?= $profile['bonus_defense'] ?>" class="stat-input"></td></tr>
                    <tr><td>➕ Бонус выносливости:</td><td><input type="number" name="bonus_stamina" value="<?= $profile['bonus_stamina'] ?>" class="stat-input"></td></tr>
                    <tr><td>➕ Бонус восстановления:</td><td><input type="number" name="bonus_recovery" value="<?= $profile['bonus_recovery'] ?>" class="stat-input"></td></tr>
                </table>
                <div class="menu" style="margin-top:10px;">
                    <button type="submit" class="btn full">Сохранить изменения</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Переключение вкладок
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const tabId = this.dataset.tab;
                document.getElementById('tab-' + tabId).classList.add('active');
            });
        });
    </script>

    <?php require_once '../inc/foot.php'; exit;
}

// ---------- СПИСОК ПОЛЬЗОВАТЕЛЕЙ ----------
$search = $_GET['search'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

if ($search) {
    $stmt = $pdo->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM users 
                           WHERE username LIKE ? OR id = ? 
                           ORDER BY id DESC LIMIT ? OFFSET ?");
    $stmt->bindValue(1, "%$search%", PDO::PARAM_STR);
    $stmt->bindValue(2, is_numeric($search) ? $search : 0, PDO::PARAM_INT);
    $stmt->bindValue(3, $limit, PDO::PARAM_INT);
    $stmt->bindValue(4, $offset, PDO::PARAM_INT);
    $stmt->execute();
} else {
    $stmt = $pdo->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM users ORDER BY id DESC LIMIT ? OFFSET ?");
    $stmt->bindValue(1, $limit, PDO::PARAM_INT);
    $stmt->bindValue(2, $offset, PDO::PARAM_INT);
    $stmt->execute();
}
$users = $stmt->fetchAll();
$total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

require_once '../inc/header.php';
?>

<span class="ttl"><b>👥 Управление игроками</b></span>
<div class="clb"></div>
<div class="hr"></div>

<?php if (isset($_SESSION['admin_message'])): ?>
    <div style="border:1px solid green; background:#e0ffe0; padding:10px; margin-bottom:10px;">
        <?= $_SESSION['admin_message']; unset($_SESSION['admin_message']); ?>
    </div>
<?php endif; ?>

<div class="menu">
    <form method="get" style="display:flex; gap:10px; align-items:center;">
        <span class="nwr"><img src="/images/icons/search.png" width="12" height="12"> Поиск:</span>
        <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="ID или имя" style="flex:1;">
        <button type="submit" class="btn">Найти</button>
    </form>
</div>

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

<table class="tables" border="1" cellpadding="5" style="width:100%;">
    <tr>
        <th>ID</th>
        <th>Имя</th>
        <th>Ур.</th>
        <th>Роль</th>
        <th>Сторона</th>
        <th>💰 Золото</th>
        <th>🔨 Бан?</th>
        <th>🔇 Мут?</th>
        <th>⚙️</th>
    </tr>
    <?php foreach ($users as $u): ?>
    <tr>
        <td><?= $u['id'] ?></td>
        <td><a href="?id=<?= $u['id'] ?>" style="font-weight:bold;"><?= htmlspecialchars($u['username']) ?></a></td>
        <td><?= $u['level'] ?></td>
        <td><?= $u['role'] ?></td>
        <td><?= $u['side'] ?></td>
        <td><?= number_format($u['gold'], 0, '', ' ') ?></td>
        <td><?= $u['is_banned'] ? 'Да' : 'Нет' ?></td>
        <td><?= $u['is_muted'] ? 'Да' : 'Нет' ?></td>
        <td><a href="?id=<?= $u['id'] ?>"><img src="/images/icons/edit.png" width="12" height="12"> ред.</a></td>
    </tr>
    <?php endforeach; ?>
</table>

<?php if ($total > $limit): ?>
<div style="margin-top:15px;">
    Страницы: 
    <?php for ($i = 1; $i <= ceil($total / $limit); $i++): ?>
        <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>" <?= ($i == $page) ? 'style="font-weight:bold;"' : '' ?>>
            [<?= $i ?>]
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

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