<?php
/* -----------------------------------------------------------
   SESSÃO SEGURA — Otimizada e Blindada
----------------------------------------------------------- */
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_strict_mode', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_samesite', 'Strict');
    
    if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || 
       (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')) {
        ini_set('session.cookie_secure', 1);
    }
    session_start();
}

/* -----------------------------------------------------------
   HEADERS DE SEGURANÇA
----------------------------------------------------------- */
header_remove("X-Powered-By");
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");
header("Content-Security-Policy: upgrade-insecure-requests;");

error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

/* -----------------------------------------------------------
   SQLITE & CONFIGS
----------------------------------------------------------- */
$baseDir = __DIR__;
if (file_exists($baseDir . '/functions.php')) {
    include_once($baseDir . '/functions.php');
}

function openSQLiteFast($path) {
    if (!file_exists($path)) {
        $dir = dirname($path);
        if (!is_dir($dir)) { @mkdir($dir, 0755, true); }
    }
    try {
        $db = new SQLite3($path);
        $db->busyTimeout(5000); 
        $db->exec("PRAGMA journal_mode = WAL;");
        $db->exec("PRAGMA synchronous = NORMAL;");
        return $db;
    } catch (Exception $e) { return null; }
}

$adb  = openSQLiteFast($baseDir . '/api/.adb.db');
$adb4 = openSQLiteFast($baseDir . '/api/.db_bg.db');

/* -----------------------------------------------------------
   AUTENTICAÇÃO
----------------------------------------------------------- */
if (!isset($_SESSION['name'])) { header("Location: index.php"); exit; }

if (!isset($_SESSION['loggedin_admin_username']) && isset($adb)) {
    if (method_exists($adb, 'querySingle')) {
         $res = $adb->querySingle("SELECT username FROM users WHERE id = 1");
         if ($res) $_SESSION['loggedin_admin_username'] = $res;
    }
}

if ($_SESSION['name'] !== ($_SESSION['loggedin_admin_username'] ?? $_SESSION['name'])) {
    session_destroy(); header("Location: index.php"); exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>IBO XC</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #4f46e5;
            --primary-hover: #4338ca;
            --bg-body: #f3f4f6;
            --sidebar-bg: #ffffff;
            --text-dark: #111827;
            --text-muted: #6b7280;
            --border-color: #e5e7eb;
            --shadow-soft: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            --transition: all 0.2s ease-in-out;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-dark);
            margin: 0; padding: 0;
            overflow-x: hidden;
        }

        #wrapper { display: flex; width: 100%; transition: var(--transition); }
        #wrapper.toggled #sidebar-wrapper { margin-left: -260px; }

        /* Sidebar Ajustada */
        #sidebar-wrapper {
            background: var(--sidebar-bg);
            height: 100vh;
            width: 260px; min-width: 260px;
            border-right: 1px solid var(--border-color);
            transition: var(--transition);
            display: flex;
            flex-direction: column;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .sidebar-heading {
            padding: 1.5rem;
            color: var(--primary);
            font-weight: 800; font-size: 1.4rem;
            border-bottom: 1px solid var(--border-color);
        }

        /* Área de links com scroll interno para não quebrar o botão sair */
        .list-group {
            flex-grow: 1;
            overflow-y: auto;
            overflow-x: hidden;
        }

        .menu-label {
            padding: 1.5rem 1.5rem 0.5rem;
            font-size: 0.75rem; font-weight: 700;
            color: #9ca3af;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .list-group-item {
            background: transparent !important;
            color: var(--text-muted);
            border: none !important;
            padding: 0.75rem 1.5rem !important;
            font-weight: 500; font-size: 0.95rem;
            display: flex; align-items: center;
            transition: var(--transition);
            margin: 2px 12px;
            border-radius: 8px;
            text-decoration: none;
        }

        .list-group-item i { width: 24px; margin-right: 12px; color: #9ca3af; }

        .list-group-item:hover {
            background-color: #eef2ff !important;
            color: var(--primary);
        }

        /* Botão Sair - Fixado e Organizado */
        .logout-item { 
            color: #ef4444 !important; 
            margin-top: auto !important; 
            margin-bottom: 20px !important;
            border-top: 1px solid var(--border-color) !important;
            border-radius: 0 !important;
            padding-top: 1.5rem !important;
        }
        .logout-item:hover { background-color: #fef2f2 !important; color: #b91c1c !important; }

        .navbar {
            background: #ffffff;
            border-bottom: 1px solid var(--border-color);
            padding: 0.8rem 2rem;
            box-shadow: var(--shadow-soft);
        }

        #menu-toggle {
            background: #fff; border: 1px solid var(--border-color);
            color: var(--text-muted); border-radius: 8px; padding: 6px 10px;
        }

        #preloader {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            z-index: 9999; background: #fff;
            display: flex; justify-content: center; align-items: center;
        }
        .pulse {
            width: 50px; height: 50px; background: var(--primary);
            border-radius: 50%; animation: pulse-animation 1.5s infinite;
        }
        @keyframes pulse-animation {
            0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.7); }
            70% { transform: scale(1); box-shadow: 0 0 0 20px rgba(79, 70, 229, 0); }
            100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(79, 70, 229, 0); }
        }

        @media (max-width: 768px) {
            #sidebar-wrapper { position: fixed; margin-left: -260px; }
            #wrapper.toggled #sidebar-wrapper { margin-left: 0; }
        }
    </style>
</head>
<body>

<div id="preloader"><div class="pulse"></div></div>

<div class="d-flex" id="wrapper" style="opacity:0;">
    <div id="sidebar-wrapper">
        <div class="sidebar-heading">
            <i class="fas fa-cubes"></i> <span>IBO XC</span>
        </div>
        
        <div class="list-group list-group-flush">
            <small class="menu-label">Principal</small>
            <a href="dashboard.php" class="list-group-item"><i class="fas fa-home"></i> Dashboard</a>
            <a href="dns.php" class="list-group-item"><i class="fas fa-server"></i> Servidores DNS</a>
            <a href="migrar.php" class="list-group-item"><i class="fas fa-exchange-alt"></i> Migração</a>

            <small class="menu-label">Aplicativo</small>
            <a href="themes.php" class="list-group-item"><i class="fas fa-paint-brush"></i> Temas</a>
            <a href="settings.php" class="list-group-item"><i class="fas fa-comment-alt"></i> Mensagens</a>
            <a href="seletor.php" class="list-group-item"><i class="fas fa-cog"></i> Configs Ads</a>

            <small class="menu-label">Extras</small>
            <a href="chatbot.php" class="list-group-item"><i class="fas fa-robot"></i> Chatbot</a>
            <a href="qrcode.php" class="list-group-item"><i class="fas fa-qrcode"></i> Pix Copia e Cola</a>
            <a href="edit_texto.php" class="list-group-item"><i class="fas fa-bell"></i> Alertas</a>

            <a href="user.php" class="list-group-item mt-4 border-top pt-3" style="border-radius: 0;">
                <i class="fas fa-user-circle"></i> Meu Perfil
            </a>
        </div>
    </div>

   <div id="page-content-wrapper" class="w-100">
    <nav class="navbar navbar-expand-lg">
        <button id="menu-toggle"><i class="fas fa-bars"></i></button>

        <div class="ms-auto d-flex align-items-center gap-3">
            <div class="d-none d-sm-block text-end">
                <span class="d-block text-dark fw-bold" style="font-size: 0.9rem;">
                    <?= htmlspecialchars($_SESSION['name']); ?>
                </span>
                <span class="d-block text-muted" style="font-size: 0.75rem;">Administrador</span>
            </div>

            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 35px; height: 35px; font-weight: bold;">
                <?= strtoupper(substr($_SESSION['name'], 0, 1)); ?>
            </div>

            <a href="logout.php" class="btn btn-outline-danger btn-sm ms-2" style="border-radius: 8px; font-weight: 600;">
                <i class="fas fa-sign-out-alt"></i> Sair
            </a>
        </div>
    </nav>
        
        <div class="container-fluid py-4">
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script>
// NOVO: SCRIPT PARA CONTROLE DO PRELOADER E TOGGLE DO MENU
$(window).on('load', function() {
    // 1. Esconde o preloader APÓS todo o conteúdo estar carregado (incluindo imagens/CSS)
    $('#preloader').fadeOut('slow', function() {
        // 2. Torna o conteúdo principal visível com a animação fadeIn original
        $('#wrapper').animate({ opacity: 1 }, 400); 
    });
});
</script>
</body>
</html>