<?php
// includes/header.php

// 1. Iniciar Sessão
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 2. Configurações Visuais
$config = [
    'server_name'      => 'Pokemon Relics', 
    'meta_description' => 'O melhor servidor de Poketibia MMORPG.',
    'color_hero_start' => '#0f172a', 
    'color_hero_end'   => '#3b82f6'
];

// 3. Carregar configs do Banco
if (isset($pdo)) {
    try {
        $stmtConfig = $pdo->query("SELECT server_name, meta_description FROM site_config LIMIT 1");
        $dbConfig = $stmtConfig->fetch(PDO::FETCH_ASSOC);
        if ($dbConfig) {
            $config = array_merge($config, $dbConfig);
        }
    } catch (Exception $e) { }
}

$pageTitle = isset($page_title) ? $page_title . ' | ' . $config['server_name'] : $config['server_name'];
$current_page = basename($_SERVER['PHP_SELF'], '.php');

// 4. Dados do Usuário & Servidor
$isAdmin = false;
$logged = false;
$user_name = "Visitante";
$user_coins = 0;
$players_online = 0;
$server_record = 0;

if (isset($pdo)) {
    // A) Contagem de Players
    try {
        $queryOnline = $pdo->query("SELECT COUNT(*) FROM players WHERE online > 0");
        $players_online = $queryOnline->fetchColumn();
    } catch (Exception $e) {
        $players_online = 0;
    }

    // B) Recorde
    try {
        $queryRecord = $pdo->query("SELECT MAX(`record`) FROM server_record");
        $server_record = $queryRecord->fetchColumn();
        if(!$server_record) $server_record = 0;
    } catch (Exception $e) {}

    // C) Usuário
    if (isset($_SESSION['account_id'])) {
        try {
            $stmt = $pdo->prepare("SELECT name, page_access, post_points FROM accounts WHERE id = ?");
            $stmt->execute([$_SESSION['account_id']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                $logged = true;
                $user_name = $user['name']; 
                $user_coins = $user['post_points'];
                if (isset($user['page_access']) && $user['page_access'] >= 3) { 
                    $isAdmin = true;
                }
            } else { session_destroy(); }
        } catch (Exception $e) {}
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="<?php echo htmlspecialchars($config['meta_description']); ?>">
    
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    
    <link rel="icon" href="images/iconrelics.png" type="image/png">
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@500;600;700;800&family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary: #3b82f6;        
            --primary-dark: #1d4ed8; 
            --accent: #f59e0b;        
            --bg-dark: #0f172a;        
            --text-main: #f8fafc;
            --glass-nav: rgba(15, 23, 42, 0.95);
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-main);
            padding-top: 140px; /* Espaço para o header */
            overflow-x: hidden;
        }

        /* --- HEADER FLUTUANTE --- */
        .header-floating {
            position: fixed;
            top: 0; left: 0; right: 0;
            z-index: 1040;
            transition: all 0.3s ease;
        }

        .navbar-custom {
            background: var(--glass-nav);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(255,255,255,0.05);
            box-shadow: 0 4px 30px rgba(0,0,0,0.5);
            padding: 0; 
            height: 80px;
        }

        /* --- LOGO CENTRAL & ARCO --- */
        .brand-container {
            position: absolute;
            left: 50%;
            top: 0;
            transform: translateX(-50%);
            background: var(--bg-dark);
            
            /* Padding ajustado para dar respiro */
            padding: 0 50px 15px 50px; 
            
            border-bottom-left-radius: 50px; 
            border-bottom-right-radius: 50px;
            
            box-shadow: 0 15px 35px rgba(0,0,0,0.6);
            z-index: 1060;
            border: 1px solid rgba(255,255,255,0.05);
            border-top: none;
            transition: all 0.3s ease;
        }
        
        .brand-logo {
            height: 120px;
            width: auto;
            filter: drop-shadow(0 0 15px rgba(59, 130, 246, 0.4));
            transition: transform 0.3s;
            display: block;
            margin-top: 5px;
        }

        .brand-container:hover .brand-logo {
            transform: scale(1.05) rotate(-2deg);
            filter: drop-shadow(0 0 25px rgba(59, 130, 246, 0.8));
        }

        /* --- LINKS DO MENU --- */
        .nav-link-custom {
            font-family: 'Rajdhani', sans-serif;
            font-weight: 700;
            font-size: 1rem; 
            text-transform: uppercase;
            color: #94a3b8 !important;
            padding: 28px 12px !important;
            letter-spacing: 0.5px;
            transition: all 0.3s;
            position: relative;
            white-space: nowrap; /* Evita quebra de linha */
        }

        .nav-link-custom:hover, .nav-link-custom.active {
            color: #fff !important;
            text-shadow: 0 0 10px rgba(255,255,255,0.5);
        }
        
        .nav-link-custom.active::after {
            content: ''; position: absolute; bottom: 0; left: 50%; transform: translateX(-50%);
            width: 40px; height: 3px; background: var(--primary);
            box-shadow: 0 -5px 10px var(--primary);
        }

        /* --- ESPAÇAMENTO INTELIGENTE (CORREÇÃO DO "DOAR") --- */
        @media (min-width: 992px) {
            /* Aumentei a margem para 160px para afastar mais da logo */
            .navbar-nav-left { margin-right: 160px; } 
            .navbar-nav-right { margin-left: 160px; } 
        }

        /* Ajuste para Laptops médios (evita sobreposição) */
        @media (min-width: 992px) and (max-width: 1280px) {
            .navbar-nav-left { margin-right: 130px; }
            .navbar-nav-right { margin-left: 130px; }
            .nav-link-custom { font-size: 0.9rem; padding: 28px 8px !important; }
            .brand-logo { height: 100px; } /* Logo um pouco menor em telas médias */
            .brand-container { padding: 0 35px 10px 35px; }
        }

        .nav-link-donate { color: var(--accent) !important; }
        .nav-link-donate:hover { color: #fbbf24 !important; text-shadow: 0 0 15px rgba(245, 158, 11, 0.8); }

        /* Botão Jogar */
        .btn-play {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white; font-family: 'Rajdhani', sans-serif; font-weight: 800;
            border: none; border-radius: 50px; padding: 10px 30px;
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
            transition: all 0.3s; letter-spacing: 1px; text-transform: uppercase;
            margin-left: 15px;
            text-decoration: none;
            white-space: nowrap;
        }
        .btn-play:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(59, 130, 246, 0.6);
            color: white;
        }

        /* Status & User Pill */
        .status-pill {
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: #34d399; font-weight: 700; font-size: 0.9rem;
            padding: 8px 18px; border-radius: 30px;
            display: flex; align-items: center; gap: 8px;
            white-space: nowrap;
        }
        .dot-online { width: 8px; height: 8px; background: #34d399; border-radius: 50%; box-shadow: 0 0 8px #34d399; animation: pulse 2s infinite; }
        
        .user-dropdown-btn {
            background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
            color: white; padding: 6px 15px; border-radius: 30px;
            display: flex; align-items: center; gap: 10px; cursor: pointer; transition: 0.3s;
        }
        .user-dropdown-btn:hover { background: rgba(255,255,255,0.1); border-color: var(--primary); }
        .user-avatar { width: 32px; height: 32px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0; }

        /* Dropdown Desktop */
        .dropdown-menu-dark-custom {
            background: #1e293b; border: 1px solid rgba(255,255,255,0.1);
            box-shadow: 0 10px 40px rgba(0,0,0,0.5); margin-top: 15px;
        }
        .dropdown-menu-dark-custom .dropdown-item { color: #cbd5e1; padding: 8px 20px; }
        .dropdown-menu-dark-custom .dropdown-item:hover { background: rgba(59, 130, 246, 0.1); color: white; border-left: 3px solid var(--primary); }

        /* --- OFF-CANVAS (MENU MOBILE & TABLET) --- */
        .offcanvas-custom {
            background-color: var(--bg-dark) !important;
            background-image: linear-gradient(to bottom, rgba(15, 23, 42, 0.98), #0b1120);
            color: white;
            border-left: 1px solid rgba(255,255,255,0.15);
            z-index: 10000 !important; /* CORREÇÃO: Z-Index maior que o header */
            width: 85% !important;
            max-width: 320px;
            box-shadow: -10px 0 30px rgba(0,0,0,0.8);
        }
        
        .offcanvas-backdrop.show {
            opacity: 0.7;
            background-color: #000;
            z-index: 9990; /* Abaixo do menu */
        }

        .offcanvas-header { 
            border-bottom: 1px solid rgba(255,255,255,0.1); 
            padding: 20px;
            background: rgba(0,0,0,0.2);
        }
        .btn-close-white { filter: invert(1); opacity: 1; }
        
        /* Links Mobile */
        .mobile-nav-link {
            color: #cbd5e1; 
            font-family: 'Rajdhani', sans-serif;
            font-weight: 700;
            font-size: 1.1rem; 
            padding: 14px 20px;
            border-bottom: 1px solid rgba(255,255,255,0.03);
            text-transform: uppercase;
            display: flex;
            align-items: center;
            text-decoration: none;
            transition: 0.3s;
        }
        
        .mobile-nav-link i {
            width: 30px;
            text-align: center;
            transition: 0.3s;
            font-size: 1rem;
            opacity: 0.7;
        }

        .mobile-nav-link:hover, .mobile-nav-link.active {
            color: #fff;
            background: rgba(59, 130, 246, 0.1); 
            border-left: 4px solid var(--primary);
            padding-left: 16px; /* Compensa a borda */
        }
        
        .mobile-nav-link:hover i {
            color: var(--primary);
            opacity: 1;
            transform: scale(1.1);
        }

        .mobile-nav-link.donate { color: var(--accent); background: rgba(245, 158, 11, 0.05); }
        .mobile-nav-link.donate i { color: var(--accent); opacity: 1; }
        
        /* Botão Sair Mobile */
        .logout-link {
            color: #fff !important; 
            background: #dc2626; 
            border: 1px solid #b91c1c;
            border-radius: 12px;
            text-align: center;
            margin-top: 25px;
            padding: 12px;
            font-weight: 800; 
            font-size: 1rem;
            text-transform: uppercase;
            box-shadow: 0 4px 10px rgba(220, 38, 38, 0.3);
            text-decoration: none;
            display: block;
            transition: transform 0.2s;
        }
        .logout-link:hover {
            background: #ef4444;
            transform: scale(1.02);
        }

        /* --- AJUSTES MOBILE / TABLET --- */
        @media (max-width: 991px) {
            body { padding-top: 90px; }
            .navbar-custom { height: 70px; padding: 0 10px; }
            
            /* Logo Mobile - Simplificado */
            .brand-container { 
                position: static; 
                transform: none; 
                background: transparent; 
                padding: 0; 
                border: none; 
                box-shadow: none; 
                display: flex; 
                align-items: center;
                margin-left: 5px;
                height: 100%;
            }
            .brand-logo { height: 60px; margin-top: 0; filter: drop-shadow(0 0 5px rgba(59, 130, 246, 0.5)); }
            
            .navbar-collapse { display: none !important; } 
            
            .navbar-toggler {
                border: 1px solid rgba(255,255,255,0.1);
                background: rgba(255,255,255,0.05);
                padding: 6px 10px;
                border-radius: 8px;
            }
            .navbar-toggler:focus { box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5); }
        }

        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(52, 211, 153, 0); } 100% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0); } }
    </style>
</head>
<body>

<header class="header-floating w-100">
    <nav class="navbar navbar-expand-lg navbar-custom">
        <div class="container-fluid px-2 px-lg-4 position-relative d-flex justify-content-between align-items-center">
            
            <a class="brand-container" href="index.php">
                <img src="images/logorelics.png" alt="Pokemon Relics" class="brand-logo">
            </a>

            <div class="d-lg-none ms-auto me-2">
                 <div class="status-pill px-2 py-1" style="font-size: 0.75rem; border-radius: 6px;">
                    <div class="dot-online" style="width: 6px; height: 6px;"></div>
                    <span><?php echo $players_online; ?></span>
                </div>
            </div>

            <button class="navbar-toggler text-white" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
                <i class="fas fa-bars"></i>
            </button>

            <div class="collapse navbar-collapse justify-content-between d-none d-lg-flex" id="mainNav">
                
                <ul class="navbar-nav navbar-nav-left ms-auto">
                    <li class="nav-item"><a class="nav-link nav-link-custom <?php echo ($current_page == 'index') ? 'active' : ''; ?>" href="index">Início</a></li>
                    
                    <li class="nav-item">
                        <a class="nav-link nav-link-custom <?php echo ($current_page == 'loteria' || $current_page == 'gacha') ? 'active' : ''; ?>" href="gacha">
                            Loteria
                        </a>
                    </li>
                    
                    <li class="nav-item dropdown">
                        <a class="nav-link nav-link-custom dropdown-toggle" href="#" data-bs-toggle="dropdown">Comunidade</a>
                        <ul class="dropdown-menu dropdown-menu-dark-custom fade-down">
                            <li><a class="dropdown-item" href="guilds"><i class="fas fa-shield-alt w-20"></i> Guildas</a></li>
                            <li><a class="dropdown-item" href="ranking"><i class="fas fa-trophy w-20"></i> Ranking</a></li>
                            <li><a class="dropdown-item" href="houses"><i class="fas fa-home w-20"></i> Casas</a></li>
                            <li><hr class="dropdown-divider bg-secondary opacity-25"></li>
                            <li><a class="dropdown-item" href="suporte"><i class="fas fa-headset w-20"></i> Suporte</a></li>
                        </ul>
                    </li>
                    <li class="nav-item"><a class="nav-link nav-link-custom <?php echo ($current_page == 'regras') ? 'active' : ''; ?>" href="regras">Regras</a></li>
                </ul>

                <ul class="navbar-nav navbar-nav-right me-auto align-items-center">
                    <li class="nav-item">
                        <a class="nav-link nav-link-custom nav-link-donate" href="donate">
                            <i class="fas fa-gem me-1"></i> DOAR
                        </a>
                    </li>
                    <li class="nav-item me-3"><a class="nav-link nav-link-custom" href="downloads">BAIXAR</a></li>
                    
                    <li class="nav-item me-3">
                        <div class="status-pill" title="Recorde: <?php echo $server_record; ?>">
                            <div class="dot-online"></div>
                            <span><?php echo $players_online; ?> ON</span>
                        </div>
                    </li>

                    <?php if (!$logged): ?>
                        <li class="nav-item"><a href="login" class="text-white text-decoration-none fw-bold small me-2 hover-opacity">LOGIN</a></li>
                        <li class="nav-item"><a href="register" class="btn-play">JOGAR</a></li>
                    <?php else: ?>
                        <li class="nav-item dropdown">
                            <div class="user-dropdown-btn" data-bs-toggle="dropdown">
                                <div class="text-end lh-1">
                                    <span class="d-block fw-bold text-white" style="font-size:0.85rem"><?php echo htmlspecialchars($user_name); ?></span>
                                    <small class="text-warning fw-bold" style="font-size:0.7rem"><i class="fas fa-coins"></i> <?php echo number_format($user_coins,0,',','.'); ?></small>
                                </div>
                                <div class="user-avatar"><?php echo strtoupper(substr($user_name, 0, 1)); ?></div>
                            </div>
                            <ul class="dropdown-menu dropdown-menu-dark-custom dropdown-menu-end">
                                <li><a class="dropdown-item" href="shop"><i class="fas fa-shopping-cart w-20"></i> Shop Online</a></li>
                                <li><a class="dropdown-item" href="account"><i class="fas fa-user-circle w-20"></i> Minha Conta</a></li>
                                <?php if($isAdmin): ?>
                                    <li><a class="dropdown-item text-danger fw-bold" href="admin/index"><i class="fas fa-cogs w-20"></i> Painel Admin</a></li>
                                <?php endif; ?>
                                <li><hr class="dropdown-divider bg-secondary opacity-25"></li>
                                <li><a class="dropdown-item text-white" href="logout"><i class="fas fa-sign-out-alt w-20"></i> Sair</a></li>
                            </ul>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </nav>

    <div class="offcanvas offcanvas-end offcanvas-custom" tabindex="-1" id="offcanvasNavbar">
        <div class="offcanvas-header d-flex justify-content-between align-items-center">
            <h5 class="offcanvas-title font-monospace text-primary fw-bold mb-0" style="letter-spacing: 2px;">MENU RELICS</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
        </div>
        <div class="offcanvas-body">
            
            <?php if ($logged): ?>
                <div class="bg-dark bg-opacity-50 p-3 rounded mb-4 border border-secondary d-flex align-items-center shadow-sm">
                    <div class="user-avatar me-3" style="width: 45px; height: 45px; font-size: 1.2rem;"><?php echo strtoupper(substr($user_name, 0, 1)); ?></div>
                    <div>
                        <div class="fw-bold text-white fs-5 lh-1 mb-1"><?php echo htmlspecialchars($user_name); ?></div>
                        <div class="text-warning small fw-bold"><i class="fas fa-coins"></i> <?php echo number_format($user_coins, 0, ',', '.'); ?> Pts</div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="d-flex flex-column gap-1">
                <a href="index" class="mobile-nav-link"><i class="fas fa-home"></i> Início</a>
                <a href="gacha" class="mobile-nav-link"><i class="fas fa-dice text-primary"></i> Loteria</a>
                <a href="shop" class="mobile-nav-link"><i class="fas fa-shopping-cart text-info"></i> Shop</a>
                <a href="downloads" class="mobile-nav-link"><i class="fas fa-download"></i> Baixar</a>
                <a href="donate" class="mobile-nav-link donate"><i class="fas fa-gem"></i> Doar / VIP</a>
            </div>
            
            <div class="border-top border-secondary my-3 pt-3">
                <span class="text-white-50 small text-uppercase fw-bold mb-2 d-block ms-2">Comunidade</span>
                <div class="d-flex flex-column gap-1">
                    <a href="ranking" class="mobile-nav-link"><i class="fas fa-trophy text-warning"></i> Ranking</a>
                    <a href="guilds" class="mobile-nav-link"><i class="fas fa-shield-alt"></i> Guildas</a>
                    <a href="wiki" class="mobile-nav-link"><i class="fas fa-book"></i> Wiki</a>
                    <a href="regras" class="mobile-nav-link"><i class="fas fa-scroll"></i> Regras</a>
                    <a href="suporte" class="mobile-nav-link"><i class="fas fa-headset"></i> Suporte</a>
                </div>
            </div>

            <div class="mt-4 pb-3">
                <?php if (!$logged): ?>
                    <a href="login" class="btn btn-outline-light w-100 mb-2 py-3 fw-bold rounded-pill">ENTRAR</a>
                    <a href="register" class="btn btn-play w-100 m-0 py-3 rounded-pill text-center d-block">CRIAR CONTA</a>
                <?php else: ?>
                    <a href="account" class="btn btn-primary w-100 mb-2 fw-bold py-2 rounded-pill">Minha Conta</a>
                    <?php if($isAdmin): ?>
                        <a href="admin/index" class="btn btn-warning text-dark w-100 mb-2 fw-bold py-2 rounded-pill">Painel Admin</a>
                    <?php endif; ?>
                    
                    <a href="logout" class="logout-link">
                        <i class="fas fa-sign-out-alt me-2"></i> SAIR DA CONTA
                    </a>
                <?php endif; ?>
            </div>

        </div>
    </div>

</header>

<div id="gachaGlobalToast" class="gacha-toast position-fixed" style="top: 120px; right: -400px; width: 320px; z-index: 9999; transition: right 0.5s;">
    <div class="card bg-dark text-white border-primary border-start border-4 shadow-lg">
        <div class="card-body p-3 d-flex align-items-center">
            <div class="me-3 bg-primary bg-opacity-25 p-2 rounded-circle text-primary"><i class="fas fa-gift fa-lg"></i></div>
            <div>
                <h6 class="fw-bold mb-1 text-primary small">LOTERIA WINNER!</h6>
                <p class="mb-0 small line-height-sm">
                    <strong id="gachaWinner" class="text-white">Player</strong> ganhou:<br>
                    <span id="gachaItem" class="text-warning fw-bold">Item Name</span> 
                    <span id="gachaRarity" class="badge bg-secondary" style="font-size:0.6rem">Raro</span>
                </p>
            </div>
        </div>
    </div>
</div>

<script>
    // Tooltips
    document.addEventListener("DOMContentLoaded", function(){
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl); });
    });

    // Notificação Global Gacha
    let lastNotifyId = 0; 
    setInterval(() => {
        const apiPath = window.location.pathname.includes('/admin/') ? '../api/get_notifications.php' : 'api/get_notifications.php';
        fetch(apiPath).then(res => res.json()).then(res => {
            if(res.has_notify && res.data.id != lastNotifyId) {
                lastNotifyId = res.data.id; 
                showGlobalGachaToast(res.data.player_name, res.data.item_name, res.data.rarity);
            }
        }).catch(e => {}); 
    }, 10000); 

    function showGlobalGachaToast(player, item, rarity) {
        const toast = document.getElementById('gachaGlobalToast');
        document.getElementById('gachaWinner').innerText = player;
        document.getElementById('gachaItem').innerText = item;
        
        const rarityEl = document.getElementById('gachaRarity');
        rarityEl.innerText = rarity;
        rarityEl.className = 'badge ms-1'; 
        
        if(rarity === 'Incomum') rarityEl.classList.add('bg-success');
        else if(rarity === 'Rara') rarityEl.classList.add('bg-primary');
        else if(rarity === 'Epica') rarityEl.style.backgroundColor = '#a855f7';
        else if(rarity === 'Lendaria') { rarityEl.style.backgroundColor = '#eab308'; rarityEl.style.color = 'black'; }
        else if(rarity === 'Mitica') rarityEl.style.backgroundColor = '#ef4444';
        else rarityEl.classList.add('bg-secondary');

        toast.style.right = '20px';
        setTimeout(() => { toast.style.right = '-400px'; }, 6000);
    }
</script>
</body>
</html>