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

$clanId = isset($_GET['clan_id']) ? (int)$_GET['clan_id'] : 0;
if (!$clanId) {
    header('Location: admin_clans.php');
    exit;
}

$clan = getClanById($clanId);
if (!$clan) {
    $_SESSION['admin_message'] = '❌ Клан не найден.';
    header('Location: admin_clans.php');
    exit;
}

// Получить участников
$members = $pdo->prepare("
    SELECT u.*, cm.rank, cm.joined_at 
    FROM clan_members cm 
    JOIN users u ON cm.user_id = u.id 
    WHERE cm.clan_id = ?
    ORDER BY FIELD(cm.rank, 'leader', 'deputy', 'advisor', 'veteran', 'recruit'), u.username
")->execute([$clanId])->fetchAll();

// Обработка действий
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['kick'])) {
            $userId = (int)$_POST['user_id'];
            // Нельзя кикнуть лидера
            $rank = getUserRankInClan($userId);
            if ($rank == 'leader') {
                throw new Exception('Нельзя исключить лидера');
            }
            $pdo->prepare("DELETE FROM clan_members WHERE user_id = ? AND clan_id = ?")->execute([$userId, $clanId]);
            $_SESSION['admin_message'] = '✅ Игрок исключён из клана.';
            header("Location: admin_clan_members.php?clan_id=$clanId");
            exit;
        }
        if (isset($_POST['change_rank'])) {
            $userId = (int)$_POST['user_id'];
            $newRank = $_POST['new_rank'];
            $allowed = ['deputy', 'advisor', 'veteran', 'recruit'];
            if (!in_array($newRank, $allowed)) {
                throw new Exception('Недопустимый ранг');
            }
            $pdo->prepare("UPDATE clan_members SET rank = ? WHERE user_id = ? AND clan_id = ?")->execute([$newRank, $userId, $clanId]);
            $_SESSION['admin_message'] = '✅ Ранг изменён.';
            header("Location: admin_clan_members.php?clan_id=$clanId");
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['admin_message'] = '❌ Ошибка: ' . $e->getMessage();
        header("Location: admin_clan_members.php?clan_id=$clanId");
        exit;
    }
}

require_once '../inc/header.php';
if (isset($_SESSION['admin_message'])) {
    echo '<div style="border:1px solid green; background:#e0ffe0; padding:10px; margin-bottom:10px;">' . htmlspecialchars($_SESSION['admin_message']) . '</div>';
    unset($_SESSION['admin_message']);
}
?>

<span class="ttl"><b>👥 Участники клана: <?= htmlspecialchars($clan['name']) ?></b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="menu">
    <a class="btn full" href="admin_clans.php">← Назад к списку кланов</a>
</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>
    </tr>
    <?php foreach ($members as $member): ?>
    <tr>
        <td><?= $member['id'] ?></td>
        <td><?= htmlspecialchars($member['username']) ?></td>
        <td><?= $member['level'] ?></td>
        <td>
            <?php if ($member['rank'] == 'leader'): ?>
                <b>Лидер</b>
            <?php else: ?>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="user_id" value="<?= $member['id'] ?>">
                    <select name="new_rank">
                        <option value="deputy" <?= $member['rank'] == 'deputy' ? 'selected' : '' ?>>Заместитель</option>
                        <option value="advisor" <?= $member['rank'] == 'advisor' ? 'selected' : '' ?>>Советник</option>
                        <option value="veteran" <?= $member['rank'] == 'veteran' ? 'selected' : '' ?>>Ветеран</option>
                        <option value="recruit" <?= $member['rank'] == 'recruit' ? 'selected' : '' ?>>Соучастник</option>
                    </select>
                    <button type="submit" name="change_rank" class="btn-mini">💾</button>
                </form>
            <?php endif; ?>
        </td>
        <td><?= date('d.m.Y', strtotime($member['joined_at'])) ?></td>
        <td>
            <?php if ($member['rank'] != 'leader'): ?>
                <form method="post" style="display:inline;" onsubmit="return confirm('Исключить игрока из клана?');">
                    <input type="hidden" name="user_id" value="<?= $member['id'] ?>">
                    <button type="submit" name="kick" class="btn-mini">❌ Исключить</button>
                </form>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

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