<?php
// ==========================================================
// MODO DE DEPURAÇÃO E CONFIGURAÇÃO
// ==========================================================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// 1. Carrega Conexão com proteção
$conexaoPath = 'includes/conexao.php';
if (file_exists($conexaoPath)) {
    require_once $conexaoPath;
} else {
    die("<h3 style='color:white; background:red; padding:10px'>Erro: 'includes/conexao.php' não encontrado.</h3>");
}

// 2. Configurações SEO
$serverName = "Pokemon Relics";
$page_title = "Guildas - $serverName";
$metaDesc = "Ranking de Guildas e Clãs do $serverName. Junte-se às batalhas!";

// ==========================================================
// LÓGICA PHP (Backend)
// ==========================================================
$viewId = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$myCharacters = [];
$isManager = false;
$managerId = 0;
$guildData = null;
$guildMembers = [];
$guildInvites = [];
$guildsList = [];
$errorMsg = "";

try {
    // A. Busca personagens da conta logada
    if (isset($_SESSION['account_id'])) {
        $stmt = $pdo->prepare("SELECT id, name, level FROM players WHERE account_id = ? ORDER BY level DESC");
        $stmt->execute([$_SESSION['account_id']]);
        $myCharacters = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // B. Perfil da Guilda (Visualização Específica)
    if ($viewId > 0) {
        $stmt = $pdo->prepare("SELECT g.*, p.name as leader_name FROM guilds g LEFT JOIN players p ON g.ownerid = p.id WHERE g.id = ?");
        $stmt->execute([$viewId]);
        $guildData = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($guildData) {
            // Busca Membros
            $mSql = "SELECT p.name, p.level, p.vocation, p.looktype, p.lookhead, p.lookbody, p.looklegs, p.lookfeet, 
                            gr.name as rank_name, gr.level as rank_level, gm.player_id,
                            (SELECT COUNT(*) FROM players_online WHERE player_id = p.id) as online
                     FROM guild_membership gm 
                     JOIN players p ON gm.player_id = p.id 
                     JOIN guild_ranks gr ON gm.rank_id = gr.id 
                     WHERE gm.guild_id = ? 
                     ORDER BY gr.level DESC, p.level DESC";
            $mStmt = $pdo->prepare($mSql);
            $mStmt->execute([$viewId]);
            $guildMembers = $mStmt->fetchAll(PDO::FETCH_ASSOC);

            // Verifica Permissão (Se sou Líder ou Vice)
            if (isset($_SESSION['account_id']) && !empty($myCharacters)) {
                $myIds = array_column($myCharacters, 'id');
                foreach ($guildMembers as $mem) {
                    if (in_array($mem['player_id'], $myIds) && $mem['rank_level'] >= 2) {
                        $isManager = true;
                        $managerId = $mem['player_id'];
                        break;
                    }
                }
            }

            // Busca Convites (Apenas para Staff da Guilda)
            if ($isManager) {
                $invSql = "SELECT p.name, p.level, gi.player_id FROM guild_invites gi JOIN players p ON gi.player_id = p.id WHERE gi.guild_id = ?";
                $invStmt = $pdo->prepare($invSql);
                $invStmt->execute([$viewId]);
                $guildInvites = $invStmt->fetchAll(PDO::FETCH_ASSOC);
            }
        }
    } 
    // C. Lista de Guildas (Index)
    else {
        $sqlList = "SELECT g.*, p.name as leader_name, 
                    (SELECT COUNT(*) FROM guild_membership WHERE guild_id = g.id) as total_members 
                    FROM guilds g 
                    LEFT JOIN players p ON g.ownerid = p.id 
                    ORDER BY total_members DESC LIMIT 20";
        $guildsList = $pdo->query($sqlList)->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (PDOException $e) {
    $errorMsg = "Erro no Banco de Dados: " . $e->getMessage();
}

// Carrega o Header do Site
if (file_exists('includes/header.php')) include 'includes/header.php';
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<meta name="description" content="<?php echo $metaDesc; ?>">
<meta property="og:title" content="<?php echo $page_title; ?>">
<meta property="og:description" content="<?php echo $metaDesc; ?>">

<style>
    :root {
        --bg-dark: #0b1120;       /* Fundo Principal Muito Escuro */
        --bg-card: #162032;       /* Fundo dos Cards */
        --primary: #3b82f6;       /* Azul Principal */
        --accent: #facc15;        /* Amarelo/Ouro */
        --text-bright: #ffffff;   /* Branco Puro */
        --text-soft: #e2e8f0;     /* Branco Suave (Substitui Cinza) */
        --border-light: rgba(255, 255, 255, 0.15); /* Bordas Claras */
    }

    body {
        background-color: var(--bg-dark);
        color: var(--text-bright);
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        overflow-x: hidden;
    }

    /* ELIMINAÇÃO TOTAL DO CINZA */
    .text-muted { color: var(--text-soft) !important; opacity: 0.9; }
    .text-white-50 { color: var(--text-soft) !important; opacity: 1; }
    h1, h2, h3, h4, h5, h6 { color: #ffffff !important; text-shadow: 0 2px 4px rgba(0,0,0,0.5); }
    small { color: #bae6fd !important; font-weight: 600; } /* Azul claro em vez de cinza pequeno */

    /* HERO SECTION */
    .guild-hero {
        background: linear-gradient(180deg, rgba(11,17,32,0.85) 0%, #0b1120 100%), url('images/hero-guilds.jpg') center/cover;
        padding: 80px 0 50px 0;
        text-align: center;
        border-bottom: 1px solid var(--border-light);
        margin-top: -20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }
    .hero-title {
        font-family: 'Rajdhani', sans-serif;
        font-size: 4rem;
        font-weight: 800;
        letter-spacing: 2px;
        color: white;
        text-transform: uppercase;
        text-shadow: 0 0 20px rgba(59, 130, 246, 0.8);
    }
    .hero-subtitle {
        font-size: 1.2rem;
        color: var(--text-soft);
        font-weight: 500;
    }

    /* CARDS */
    .guild-card {
        background: var(--bg-card);
        border: 1px solid var(--border-light);
        border-radius: 16px;
        transition: all 0.3s ease;
        height: 100%;
        cursor: pointer;
        box-shadow: 0 4px 6px rgba(0,0,0,0.3);
    }
    .guild-card:hover {
        transform: translateY(-8px);
        border-color: var(--primary);
        box-shadow: 0 0 25px rgba(59, 130, 246, 0.4);
        background: #1e293b;
    }
    .card-logo-area {
        height: 110px;
        background: linear-gradient(135deg, #1e293b, #0f172a);
        display: flex;
        align-items: center;
        justify-content: center;
        border-bottom: 1px solid var(--border-light);
    }
    .card-logo-img {
        width: 75px; height: 75px;
        border-radius: 12px;
        border: 2px solid white;
        object-fit: cover;
        background: #000;
        box-shadow: 0 0 15px rgba(255,255,255,0.2);
    }

    /* PERFIL HEADER */
    .profile-header {
        background: linear-gradient(to right, #1e293b, #111827);
        border: 1px solid var(--border-light);
        border-radius: 20px;
        padding: 30px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.4);
    }
    .profile-logo {
        width: 140px; height: 140px;
        border-radius: 50%;
        border: 4px solid white;
        box-shadow: 0 0 25px rgba(59, 130, 246, 0.6);
        object-fit: cover;
    }

    /* TABELAS E LISTAS */
    .table-custom { color: white; width: 100%; }
    .table-custom thead th {
        background-color: rgba(255,255,255,0.1);
        color: #fff;
        font-weight: 800;
        text-transform: uppercase;
        border: none;
        padding: 15px;
    }
    .table-custom tbody td {
        background-color: rgba(0,0,0,0.2);
        border-bottom: 1px solid rgba(255,255,255,0.05);
        padding: 12px 15px;
        color: white;
        font-weight: 500;
    }
    .table-custom tbody tr:hover td {
        background-color: rgba(255,255,255,0.05);
    }

    /* INPUTS E FORMS (SEMPRE CLAROS) */
    .form-control, .form-select {
        background-color: rgba(255,255,255,0.1) !important;
        border: 1px solid rgba(255,255,255,0.3) !important;
        color: white !important;
        font-weight: 600;
    }
    .form-control:focus, .form-select:focus {
        background-color: rgba(255,255,255,0.15) !important;
        border-color: var(--primary) !important;
        box-shadow: 0 0 15px rgba(59, 130, 246, 0.4);
    }
    .form-control::placeholder {
        color: rgba(255,255,255,0.7) !important;
    }
    label {
        color: white !important;
        font-weight: 700;
        margin-bottom: 5px;
        text-transform: uppercase;
        font-size: 0.85rem;
    }

    /* BOTÕES E TABS */
    .nav-pills .nav-link {
        background: rgba(255,255,255,0.1);
        color: white;
        font-weight: 700;
        margin-right: 10px;
        border: 1px solid rgba(255,255,255,0.1);
    }
    .nav-pills .nav-link.active {
        background: var(--primary);
        border-color: var(--primary);
        box-shadow: 0 0 15px var(--primary-glow);
    }
    .btn-glass {
        background: rgba(255,255,255,0.1);
        border: 1px solid rgba(255,255,255,0.3);
        color: white;
        font-weight: bold;
    }
    .btn-glass:hover {
        background: white;
        color: black;
    }

    /* MODAL */
    .modal-content {
        background-color: #1e293b;
        border: 1px solid rgba(255,255,255,0.2);
        box-shadow: 0 0 50px rgba(0,0,0,0.8);
    }
    .modal-header { border-bottom: 1px solid rgba(255,255,255,0.1); }
    .btn-close { filter: invert(1); } /* X branco */

    @media(max-width: 768px) {
        .hero-title { font-size: 2.8rem; }
        .profile-header { text-align: center; }
        .d-flex-md { display: block !important; }
        .profile-logo { margin: 0 auto 20px auto; display: block; }
    }
</style>

<div class="guild-hero">
    <div class="container" data-aos="fade-down">
        <h1 class="hero-title">CENTRAL DE GUILDAS</h1>
        <p class="hero-subtitle">Junte-se às maiores lendas de <?php echo $serverName; ?></p>
        
        <?php if($viewId == 0): // Botão criar apenas na index ?>
            <div class="mt-4">
                <?php if(isset($_SESSION['account_id'])): ?>
                    <button class="btn btn-primary fw-bold px-5 py-3 rounded-pill shadow-lg text-uppercase" data-bs-toggle="modal" data-bs-target="#createGuildModal">
                        <i class="fas fa-plus-circle me-2"></i> Fundar Nova Guilda
                    </button>
                <?php else: ?>
                    <a href="login.php" class="btn btn-glass px-4 rounded-pill">Faça Login para Criar</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="container my-5">

    <?php if ($errorMsg): ?>
        <div class="alert alert-danger bg-danger text-white border-0 shadow fw-bold">
            <i class="fas fa-exclamation-triangle me-2"></i> <?php echo $errorMsg; ?>
        </div>
    <?php endif; ?>

    <?php if ($viewId > 0 && $guildData): 
        $logoUrl = "images/guilds/" . (!empty($guildData['logo_gfx']) ? $guildData['logo_gfx'] : 'default.png');
    ?>
    
    <div class="profile-header mb-4" data-aos="fade-up">
        <div class="d-flex align-items-center d-flex-md">
            <div class="me-md-5">
                <img src="<?php echo $logoUrl; ?>" class="profile-logo" alt="Logo">
            </div>
            <div class="flex-grow-1">
                <h2 class="fw-bold mb-2 text-white" style="font-family: 'Rajdhani', sans-serif; font-size: 3rem; text-transform:uppercase;">
                    <?php echo htmlspecialchars($guildData['name']); ?>
                </h2>
                <div class="mb-3 fs-5">
                    <span class="text-warning fw-bold"><i class="fas fa-crown me-1"></i> Líder:</span> 
                    <span class="text-white"><?php echo htmlspecialchars($guildData['leader_name']); ?></span>
                    <span class="mx-3 text-secondary">|</span>
                    <span class="text-info fw-bold"><i class="fas fa-users me-1"></i> <?php echo count($guildMembers); ?> Membros</span>
                </div>
                <div class="p-3 rounded border border-white border-opacity-10" style="background: rgba(255,255,255,0.05);">
                    <i class="fas fa-quote-left text-white-50 me-2"></i>
                    <span class="text-white fst-italic fw-bold">
                        "<?php echo !empty($guildData['motd']) ? htmlspecialchars($guildData['motd']) : 'Bem vindos à nossa guilda!'; ?>"
                    </span>
                </div>
            </div>
            <div class="ms-md-4 mt-4 mt-md-0">
                <a href="guilds.php" class="btn btn-glass rounded-pill px-4"><i class="fas fa-arrow-left me-2"></i> Voltar</a>
            </div>
        </div>
    </div>

    <ul class="nav nav-pills mb-4" id="guildTabs" role="tablist" data-aos="fade-up" data-aos-delay="100">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tab-members">
                <i class="fas fa-users me-2"></i> LISTA DE MEMBROS
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-info">
                <i class="fas fa-info-circle me-2"></i> INFORMAÇÕES
            </button>
        </li>
        <?php if ($isManager): ?>
        <li class="nav-item ms-auto">
            <button class="nav-link bg-warning text-dark border-warning" data-bs-toggle="pill" data-bs-target="#tab-manage">
                <i class="fas fa-cog me-2"></i> PAINEL DO LÍDER
                <?php if(count($guildInvites)>0) echo '<span class="badge bg-danger ms-1">'.count($guildInvites).'</span>'; ?>
            </button>
        </li>
        <?php endif; ?>
    </ul>

    <div class="tab-content" data-aos="fade-up" data-aos-delay="200">
        
        <div class="tab-pane fade show active" id="tab-members">
            <div class="card bg-transparent border-0">
                <div class="table-responsive rounded-3 border border-white border-opacity-10">
                    <table class="table-custom">
                        <thead>
                            <tr>
                                <th class="ps-4">Treinador</th>
                                <th class="text-center">Level</th>
                                <th class="text-center">Vocação</th>
                                <th class="text-center">Cargo</th>
                                <th class="text-center">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($guildMembers as $m): 
                                $status = $m['online'] ? '<span class="badge bg-success shadow-sm">ONLINE</span>' : '<span class="badge bg-secondary opacity-50">OFFLINE</span>';
                                
                                $rankStyle = 'badge bg-secondary bg-opacity-25 border border-white border-opacity-10';
                                if($m['rank_level'] == 3) $rankStyle = 'badge bg-warning text-dark border-warning shadow-sm'; // Lider
                                if($m['rank_level'] == 2) $rankStyle = 'badge bg-info text-dark border-info shadow-sm';    // Vice
                                
                                $outfit = "https://outfit-images.ots.me/1285_walk_animation/animoutfit.php?id={$m['looktype']}&head={$m['lookhead']}&body={$m['lookbody']}&legs={$m['looklegs']}&feet={$m['lookfeet']}";
                            ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div style="width:40px; height:40px; margin-right:15px; overflow:hidden; display:flex; align-items:center; justify-content:center;">
                                            <img src="<?php echo $outfit; ?>" style="transform: scale(1.2);">
                                        </div>
                                        <a href="character.php?name=<?php echo urlencode($m['name']); ?>" class="text-white text-decoration-none fw-bold fs-5 hover-link">
                                            <?php echo htmlspecialchars($m['name']); ?>
                                        </a>
                                    </div>
                                </td>
                                <td class="text-center fw-bold text-white"><?php echo $m['level']; ?></td>
                                <td class="text-center small text-info"><?php echo $m['vocation']; ?></td>
                                <td class="text-center"><span class="<?php echo $rankStyle; ?> px-3 py-2"><?php echo $m['rank_name']; ?></span></td>
                                <td class="text-center"><?php echo $status; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="tab-info">
            <div class="row g-4">
                <div class="col-md-6">
                    <div class="card p-4 h-100" style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.1);">
                        <h4 class="text-warning fw-bold mb-3"><i class="fas fa-scroll me-2"></i> Descrição da Guilda</h4>
                        <div class="text-white lh-lg">
                            <?php echo !empty($guildData['description']) ? nl2br(htmlspecialchars($guildData['description'])) : 'Nenhuma descrição informada.'; ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card p-4 h-100" style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.1);">
                        <h4 class="text-danger fw-bold mb-3"><i class="fas fa-gavel me-2"></i> Regras Internas</h4>
                        <div class="text-white lh-lg">
                            <?php echo !empty($guildData['rules']) ? nl2br(htmlspecialchars($guildData['rules'])) : 'Sem regras definidas.'; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($isManager): ?>
        <div class="tab-pane fade" id="tab-manage">
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="p-3 text-center rounded border border-primary bg-primary bg-opacity-10" style="cursor:pointer" onclick="new bootstrap.Modal('#inviteModal').show()">
                        <i class="fas fa-user-plus fa-2x text-primary mb-2"></i>
                        <h6 class="fw-bold text-white mb-0">CONVIDAR JOGADOR</h6>
                    </div>
                </div>
                <?php if($guildData['ownerid'] == $managerId): ?>
                <div class="col-md-4">
                    <div class="p-3 text-center rounded border border-warning bg-warning bg-opacity-10" style="cursor:pointer" onclick="new bootstrap.Modal('#editModal').show()">
                        <i class="fas fa-edit fa-2x text-warning mb-2"></i>
                        <h6 class="fw-bold text-white mb-0">EDITAR GUILDA</h6>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="p-3 text-center rounded border border-danger bg-danger bg-opacity-10" style="cursor:pointer" onclick="deleteGuild(<?php echo $viewId; ?>)">
                        <i class="fas fa-trash-alt fa-2x text-danger mb-2"></i>
                        <h6 class="fw-bold text-white mb-0">DESFAZER GUILDA</h6>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card" style="background: #1e293b; border: 1px solid rgba(255,255,255,0.1);">
                        <div class="card-header bg-transparent border-bottom border-white border-opacity-10 fw-bold text-white">CONVITES PENDENTES</div>
                        <ul class="list-group list-group-flush">
                            <?php if(empty($guildInvites)): ?>
                                <li class="list-group-item bg-transparent text-white text-center py-3">Nenhum convite pendente.</li>
                            <?php else: foreach($guildInvites as $inv): ?>
                                <li class="list-group-item bg-transparent text-white d-flex justify-content-between align-items-center">
                                    <span><?php echo $inv['name']; ?> <small class="text-info">(Lvl <?php echo $inv['level']; ?>)</small></span>
                                    <div>
                                        <button class="btn btn-sm btn-success fw-bold me-1" onclick="act('accept_invite', <?php echo $inv['player_id']; ?>)">ACEITAR</button>
                                        <button class="btn btn-sm btn-danger fw-bold" onclick="act('reject_invite', <?php echo $inv['player_id']; ?>)">RECUSAR</button>
                                    </div>
                                </li>
                            <?php endforeach; endif; ?>
                        </ul>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card" style="background: #1e293b; border: 1px solid rgba(255,255,255,0.1);">
                        <div class="card-header bg-transparent border-bottom border-white border-opacity-10 fw-bold text-white">GERENCIAR MEMBROS</div>
                        <div class="card-body p-0" style="max-height: 300px; overflow-y:auto;">
                            <ul class="list-group list-group-flush">
                                <?php foreach($guildMembers as $m): 
                                    if($m['player_id'] == $managerId) continue;
                                    $canKick = ($guildData['ownerid'] == $managerId) || ($m['rank_level'] < 2);
                                    if(!$canKick) continue;
                                ?>
                                <li class="list-group-item bg-transparent text-white d-flex justify-content-between align-items-center">
                                    <span><?php echo $m['name']; ?></span>
                                    <button class="btn btn-sm btn-outline-danger fw-bold" onclick="act('remove_member', <?php echo $m['player_id']; ?>)">EXPULSAR</button>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <?php else: ?>
        
        <div class="row g-4" data-aos="fade-up">
            <?php if(empty($guildsList)): ?>
                <div class="col-12 text-center py-5">
                    <div class="p-5 rounded border border-white border-opacity-10" style="background: rgba(255,255,255,0.02)">
                        <i class="fas fa-shield-alt fa-4x text-white opacity-50 mb-3"></i>
                        <h3 class="text-white fw-bold">Nenhuma guilda formada.</h3>
                        <p class="text-white fs-5">Seja o primeiro a criar um legado!</p>
                    </div>
                </div>
            <?php else: foreach($guildsList as $g): 
                 $logoUrl = "images/guilds/" . (!empty($g['logo_gfx']) ? $g['logo_gfx'] : 'default.png');
            ?>
            <div class="col-md-6 col-lg-4">
                <div class="guild-card" onclick="window.location='guilds.php?view=<?php echo $g['id']; ?>'">
                    <div class="card-logo-area">
                        <img src="<?php echo $logoUrl; ?>" class="card-logo-img">
                    </div>
                    <div class="p-4 text-center">
                        <h4 class="fw-bold text-white mb-1 text-truncate text-uppercase"><?php echo htmlspecialchars($g['name']); ?></h4>
                        <p class="text-info small mb-3 fw-bold">Líder: <?php echo htmlspecialchars($g['leader_name']); ?></p>
                        <div class="d-flex justify-content-between border-top border-white border-opacity-10 pt-3 mt-3">
                            <span class="text-white fw-bold small"><i class="fas fa-users me-1 text-warning"></i> <?php echo $g['total_members']; ?> Membros</span>
                            <span class="text-white fw-bold small">VER PERFIL <i class="fas fa-arrow-right ms-1"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; endif; ?>
        </div>

    <?php endif; ?>

</div>

<div class="modal fade" id="createGuildModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content text-white">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">CRIAR NOVA GUILDA</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="createForm" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="create_guild">
                    <div class="mb-3">
                        <label>Nome da Guilda</label>
                        <input type="text" name="guild_name" class="form-control" required minlength="3" placeholder="Ex: Team Rocket">
                    </div>
                    <div class="mb-3">
                        <label>Líder (Seu Personagem)</label>
                        <select name="leader_id" class="form-select" required>
                            <?php foreach($myCharacters as $char): ?>
                                <option value="<?php echo $char['id']; ?>"><?php echo htmlspecialchars($char['name']); ?> (Lvl <?php echo $char['level']; ?>)</option>
                            <?php endforeach; ?>
                        </select>
                        <div class="small mt-1 text-info"><i class="fas fa-info-circle"></i> Req: Level 50+ e 50k Gold.</div>
                    </div>
                    <div class="mb-3">
                        <label>Logo (Opcional)</label>
                        <input type="file" name="guild_logo" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Mensagem do Dia</label>
                        <input type="text" name="motd" class="form-control" placeholder="Sejam bem vindos...">
                    </div>
                    <button type="submit" class="btn btn-success w-100 fw-bold py-3 mt-2 shadow">CONFIRMAR E PAGAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php if($isManager): ?>
<div class="modal fade" id="inviteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content text-white">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">CONVIDAR JOGADOR</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="inviteForm">
                    <input type="hidden" name="action" value="invite_player">
                    <input type="hidden" name="guild_id" value="<?php echo $viewId; ?>">
                    <input type="hidden" name="manager_id" value="<?php echo $managerId; ?>">
                    <label>Nome do Personagem</label>
                    <input type="text" name="player_name" class="form-control mb-3" required placeholder="Digite o nome exato...">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2">ENVIAR CONVITE</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content text-white">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">EDITAR INFORMAÇÕES</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="editForm" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="edit_info">
                    <input type="hidden" name="guild_id" value="<?php echo $viewId; ?>">
                    <input type="hidden" name="manager_id" value="<?php echo $managerId; ?>">
                    
                    <div class="mb-3">
                        <label>Mensagem do Dia (MOTD)</label>
                        <input type="text" name="motd" class="form-control" value="<?php echo htmlspecialchars($guildData['motd']); ?>">
                    </div>
                    <div class="mb-3">
                        <label>Descrição</label>
                        <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($guildData['description']); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label>Regras</label>
                        <textarea name="rules" class="form-control" rows="3"><?php echo htmlspecialchars($guildData['rules']); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label>Nova Logo (Opcional)</label>
                        <input type="file" name="new_logo" class="form-control">
                    </div>
                    <button type="submit" class="btn btn-warning w-100 fw-bold text-dark py-2">SALVAR ALTERAÇÕES</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
    AOS.init({ once: true });

    function send(fd) {
        fetch('guild_actions.php', { method: 'POST', body: fd })
        .then(r => r.text())
        .then(t => {
            try {
                let d = JSON.parse(t);
                alert(d.message);
                if(d.status === 'success') {
                    if(d.redirect) window.location.href = d.redirect;
                    else window.location.reload();
                }
            } catch(e) {
                console.error("Erro Parse:", t);
                alert('Erro de sistema. Verifique o console.');
            }
        })
        .catch(() => alert('Erro de conexão.'));
    }

    // Auto Bind Forms
    ['createForm', 'inviteForm', 'editForm'].forEach(fid => {
        let f = document.getElementById(fid);
        if(f) f.onsubmit = e => { e.preventDefault(); send(new FormData(f)); }
    });

    // Ações de Botões
    function act(action, tid) {
        if(!confirm('Tem certeza?')) return;
        let fd = new FormData();
        fd.append('action', action);
        fd.append('guild_id', <?php echo $viewId; ?>);
        fd.append('manager_id', <?php echo $managerId; ?>);
        if(tid) fd.append('target_id', tid);
        send(fd);
    }

    function deleteGuild(id) {
        if(!confirm('ATENÇÃO: DELETAR A GUILDA É IRREVERSÍVEL. CONTINUAR?')) return;
        let fd = new FormData();
        fd.append('action', 'delete_guild');
        fd.append('guild_id', id);
        fd.append('manager_id', <?php echo $managerId; ?>);
        send(fd);
    }
</script>

<?php 
if (file_exists('includes/footer.php')) include 'includes/footer.php'; 
else echo '</body></html>';
?>