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

$clans = $pdo->query("SELECT c.*, u.username as leader_name FROM clans c LEFT JOIN users u ON c.leader_id = u.id ORDER BY c.id DESC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['delete_clan'])) {
            $clanId = (int)$_POST['clan_id'];
            $pdo->prepare("DELETE FROM clans WHERE id = ?")->execute([$clanId]);
            $_SESSION['admin_message'] = '✅ Клан удалён.';
            header('Location: admin_clans.php');
            exit;
        }
        if (isset($_POST['edit_clan'])) {
            $clanId = (int)$_POST['clan_id'];
            $name = trim($_POST['name']);
            $description = trim($_POST['description']);
            $announcement = trim($_POST['announcement']);
            $gold = (int)$_POST['gold'];
            $bucks = (int)$_POST['bucks'];
            $pdo->prepare("UPDATE clans SET name=?, description=?, announcement=?, gold=?, bucks=? WHERE id=?")
                ->execute([$name, $description, $announcement, $gold, $bucks, $clanId]);
            $_SESSION['admin_message'] = '✅ Клан обновлён.';
            header('Location: admin_clans.php');
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['admin_message'] = '❌ Ошибка: ' . $e->getMessage();
        header('Location: admin_clans.php');
        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>🏰 Управление кланами</b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="menu">
    <a class="btn full" href="index.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>
        <th>💵 Баксы</th>
        <th>Действия</th>
    </tr>
    <?php foreach ($clans as $clan): ?>
    <tr>
        <form method="post">
            <input type="hidden" name="clan_id" value="<?= $clan['id'] ?>">
            <td><?= $clan['id'] ?></td>
            <td><input type="text" name="name" value="<?= htmlspecialchars($clan['name']) ?>" style="width:150px;"></td>
            <td><?= htmlspecialchars($clan['leader_name'] ?? '—') ?></td>
            <td><?= $clan['level'] ?></td>
            <td><?= number_format($clan['exp']) ?></td>
            <td><input type="number" name="gold" value="<?= $clan['gold'] ?>" style="width:80px;"></td>
            <td><input type="number" name="bucks" value="<?= $clan['bucks'] ?>" style="width:80px;"></td>
            <td>
                <button type="submit" name="edit_clan" class="btn-mini" title="Сохранить">💾</button>
                <button type="submit" name="delete_clan" class="btn-mini" title="Удалить" onclick="return confirm('Удалить клан?');">❌</button>
                <a href="admin_clan_members.php?clan_id=<?= $clan['id'] ?>" class="btn-mini">👥 Участники</a>
            </td>
        </form>
    </tr>
    <tr>
        <td colspan="8">
            <strong>Описание:</strong> <input type="text" form="form_<?= $clan['id'] ?>" name="description" value="<?= htmlspecialchars($clan['description'] ?? '') ?>" style="width:60%;">
            <strong>Объявление:</strong> <input type="text" form="form_<?= $clan['id'] ?>" name="announcement" value="<?= htmlspecialchars($clan['announcement'] ?? '') ?>" style="width:60%;">
        </td>
    </tr>
    <?php endforeach; ?>
</table>

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