<?php
// Inclure la protection d'authentification
require_once __DIR__ . '/auth-check.php';

// Gestion de la déconnexion
if (isset($_GET['logout']) && $_GET['logout'] == '1') {
    // Démarrer la session si ce n'est pas déjà fait
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Détruire toutes les données de session
    $_SESSION = array();
    
    // Si on veut détruire la session, on efface aussi le cookie de session
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    // Finalement, détruire la session
    session_destroy();
    
    // Log de sécurité
    error_log("Admin logout at " . date('Y-m-d H:i:s') . " from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
    
    // Redirection vers la page de confirmation de déconnexion
    header("Location: ../logout-success.php");
    exit();
}

// Démarrer la session pour les autres pages
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
?>
<!DOCTYPE html>
<html lang="fr" class="layout-menu-fixed layout-compact" data-assets-path="pages/assets/">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <meta name="robots" content="noindex, nofollow" />

    <title><?php echo $page_title ?? 'Panel Admin'; ?> - SERVICES-AE</title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="../images/fevicon/fevicon.png" />

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />

    <link rel="stylesheet" href="pages/assets/vendor/fonts/iconify-icons.css" />

    <!-- Core CSS -->
    <link rel="stylesheet" href="pages/assets/vendor/libs/node-waves/node-waves.css" />
    <link rel="stylesheet" href="pages/assets/vendor/css/core.css" />
    <link rel="stylesheet" href="pages/assets/css/demo.css" />

    <!-- Vendors CSS -->
    <link rel="stylesheet" href="pages/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />
    
    <!-- Custom Admin CSS -->
    <link rel="stylesheet" href="assets/css/admin-custom.css" />
    
    <?php if (isset($include_charts) && $include_charts): ?>
    <!-- Charts CSS -->
    <link rel="stylesheet" href="pages/assets/vendor/libs/apex-charts/apex-charts.css" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <?php endif; ?>

    <!-- Custom CSS -->
    <style>
        .services-brand {
            color: #696cff;
            font-weight: bold;
        }
        
        .stats-card-custom {
            background: transparent;
            border: 2px solid #696cff;
            border-radius: 12px;
            color: #696cff;
            transition: transform 0.2s, border-color 0.2s;
        }
        
        .stats-card-custom:hover {
            transform: translateY(-2px);
            border-color: #5a5fe7;
        }
        
        .menu-item.active > .menu-link {
            background: transparent !important;
            border-left: 4px solid #696cff !important;
            color: #696cff !important;
            font-weight: 600;
        }
        
        .navbar-brand-custom {
            color: #696cff;
            font-weight: bold;
        }
        
        /* Sidebar avec bordure colorée */
        .layout-menu {
            border-right: 3px solid #696cff !important;
            background: #ffffff !important;
        }
        
        /* Menu items avec bordures */
        .menu-item > .menu-link:hover:not(.active) {
            background: rgba(105, 108, 255, 0.08) !important;
            border-left: 2px solid #696cff;
        }
        
        .navbar-nav .form-control {
            min-width: 200px;
        }
        
        .navbar-nav .nav-item .ri {
            color: #8692a6;
        }
    </style>

    <!-- Helpers -->
    <script src="pages/assets/vendor/js/helpers.js"></script>
    <script src="pages/assets/js/config.js"></script>
</head>

<body>
    <!-- Layout wrapper -->
    <div class="layout-wrapper layout-content-navbar">
        <div class="layout-container">
            
            <!-- Menu Sidebar -->
            <aside id="layout-menu" class="layout-menu menu-vertical menu bg-menu-theme">
                
                <!-- Brand -->
                <div class="app-brand demo">
                    <a href="index.php" class="app-brand-link">
                        <span class="app-brand-logo demo me-1">
                            <img src="../images/fevicon/fevicon.png" alt="SERVICES-AE Logo" width="30" height="30" style="border-radius: 4px;">
                        </span>
                        <span class="app-brand-text demo menu-text fw-semibold ms-2 services-brand">SERVICES-AE</span>
                    </a>

                    <a href="javascript:void(0);" class="layout-menu-toggle menu-link text-large ms-auto">
                        <i class="menu-toggle-icon d-xl-inline-block align-middle"></i>
                    </a>
                </div>

                <div class="menu-inner-shadow"></div>

                <!-- Menu Items -->
                <ul class="menu-inner py-1">

                    <!-- Téléchargement -->
                    <li class="menu-item <?php echo in_array($current_page ?? '', ['admin-telechargements','admin-liste-telechargements']) ? 'active open' : ''; ?>">
                        <a href="javascript:void(0);" class="menu-link menu-toggle">
                            <i class="menu-icon icon-base ri-file-download-line"></i>
                            <div>Téléchargement</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item <?php echo ($current_page ?? '') === 'admin-telechargements' ? 'active' : ''; ?>">
                                <a href="admin-telechargements.php" class="menu-link">
                                    <div>Ajouter un fichier</div>
                                </a>
                            </li>
                            <li class="menu-item <?php echo ($current_page ?? '') === 'admin-liste-telechargements' ? 'active' : ''; ?>">
                                <a href="admin-liste-telechargements.php" class="menu-link">
                                    <div>Liste des fichiers</div>
                                </a>
                            </li>
                        </ul>
                    </li>
                    <li class="menu-item <?php echo ($current_page ?? '') === 'support' ? 'active open' : ''; ?>">
                        <a href="javascript:void(0);" class="menu-link menu-toggle">
                            <i class="menu-icon icon-base ri-customer-service-2-line"></i>
                            <div>Support</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item <?php echo ($current_page ?? '') === 'support-chat' ? 'active' : ''; ?>">
                                <a href="chat.php" class="menu-link">
                                    <div>Conversations live</div>
                                </a>
                            </li>
                            <li class="menu-item <?php echo ($current_page ?? '') === 'support-missed' ? 'active' : ''; ?>">
                                <a href="support-chat-admin.php?missed=1" class="menu-link">
                                    <div>Conversations manquées</div>
                                </a>
                            </li>
                            <li class="menu-item <?php echo ($current_page ?? '') === 'support-chat-closed' ? 'active' : ''; ?>">
                                <a href="support-chat-closed.php" class="menu-link">
                                    <div>Conversations clôturées</div>
                                </a>
                            </li>
                        </ul>
                    </li>
                    
                    <!-- Dashboard -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'dashboard' ? 'active' : ''; ?>">
                        <a href="index.php" class="menu-link">
                            <i class="menu-icon icon-base ri-dashboard-3-line"></i>
                            <div>Tableau de Bord</div>
                        </a>
                    </li>

                    <!-- Analytics -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'analytics' ? 'active' : ''; ?>">
                        <a href="dashboard-stats.php" class="menu-link">
                            <i class="menu-icon icon-base ri-line-chart-line"></i>
                            <div>Analytics</div>
                            <div class="badge text-bg-danger rounded-pill ms-auto">Live</div>
                        </a>
                    </li>

                    <!-- Mon Profil -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'profile' ? 'active' : ''; ?>">
                        <a href="admin-profile.php" class="menu-link">
                            <i class="menu-icon icon-base ri-user-3-line"></i>
                            <div>Mon Profil</div>
                        </a>
                    </li>

                    <!-- Gestion Utilisateurs -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'users' ? 'active' : ''; ?>">
                        <a href="admin-users.php" class="menu-link">
                            <i class="menu-icon icon-base ri-group-line"></i>
                            <div>Utilisateurs</div>
                        </a>
                    </li>

                    <!-- Gestion SEO -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'seo' ? 'active' : ''; ?>">
                        <a href="seo-management.php" class="menu-link">
                            <i class="menu-icon icon-base ri-search-eye-line"></i>
                            <div>SEO</div>
                        </a>
                    </li>

                    <!-- Pages Légales -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'legal' ? 'active' : ''; ?>">
                        <a href="legal-pages.php" class="menu-link">
                            <i class="menu-icon icon-base ri-file-text-line"></i>
                            <div>Pages Légales</div>
                        </a>
                    </li>

                    <!-- Témoignages -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'testimonials' ? 'active open' : ''; ?>">
                        <a href="javascript:void(0);" class="menu-link menu-toggle">
                            <i class="menu-icon icon-base ri-chat-quote-line"></i>
                            <div>Témoignages</div>
                            <?php if (isset($pending_testimonials) && $pending_testimonials > 0): ?>
                            <div class="badge text-bg-warning rounded-pill ms-auto"><?php echo $pending_testimonials; ?></div>
                            <?php endif; ?>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item <?php echo ($current_page ?? '') === 'testimonials' && ($current_action ?? '') === 'manage' ? 'active' : ''; ?>">
                                <a href="admin-testimonials.php" class="menu-link">
                                    <div>Gestion Témoignages</div>
                                </a>
                            </li>
                            <li class="menu-item <?php echo ($current_page ?? '') === 'testimonials' && ($current_action ?? '') === 'add' ? 'active' : ''; ?>">
                                <a href="../add-testimonial.php" class="menu-link">
                                    <div>Ajouter un Avis</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="../testimonials.php" class="menu-link" target="_blank">
                                    <div>Vue Publique</div>
                                </a>
                            </li>
                        </ul>
                    </li>

                    <!-- Sécurité -->
                    <li class="menu-item <?php echo ($current_page ?? '') === 'captcha-admin' ? 'active' : ''; ?>">
                        <a href="captcha-admin.php" class="menu-link">
                            <i class="menu-icon fa fa-shield-alt"></i>
                            <div>Gestion Captcha</div>
                        </a>
                    </li>

                    <!-- Outils -->
                    <li class="menu-header mt-7"><span class="menu-header-text">Outils</span></li>
                    <li class="menu-item">
                        <a href="smtp-config.php" class="menu-link">
                            <i class="menu-icon icon-base ri-mail-settings-line"></i>
                            <div>Config SMTP</div>
                        </a>
                    </li>



                    <!-- Documentation -->
                    <li class="menu-item">
                        <a href="../ANALYTICS-DOCUMENTATION.md" class="menu-link" target="_blank">
                            <i class="menu-icon icon-base ri-book-open-line"></i>
                            <div>Documentation</div>
                        </a>
                    </li>
                </ul>
            </aside>
            <!-- / Menu -->

            <!-- Layout container -->
            <div class="layout-page">
                
                <!-- Navbar -->
                <nav class="layout-navbar container-xxl navbar-detached navbar navbar-expand-xl align-items-center bg-navbar-theme" id="layout-navbar">
                    
                    <!-- Menu Toggle -->
                    <div class="layout-menu-toggle navbar-nav align-items-xl-center me-4 me-xl-0 d-xl-none">
                        <a class="nav-item nav-link px-0 me-xl-6" href="javascript:void(0)">
                            <i class="icon-base ri ri-menu-line icon-md"></i>
                        </a>
                    </div>

                    <div class="navbar-nav-right d-flex align-items-center justify-content-end" id="navbar-collapse">
                        
                        <!-- Search -->
                        <div class="navbar-nav align-items-center">
                            <div class="nav-item d-flex align-items-center">
                                <i class="icon-base ri ri-search-line icon-lg lh-0"></i>
                                <input type="text" class="form-control border-0 shadow-none" placeholder="Rechercher..." aria-label="Search..." />
                            </div>
                        </div>
                        <!-- /Search -->

                        <ul class="navbar-nav flex-row align-items-center ms-md-auto">
                            
                            <!-- Notifications -->
                            <?php if (isset($pending_testimonials) && $pending_testimonials > 0): ?>
                            <li class="nav-item dropdown-notifications navbar-dropdown dropdown me-4">
                                <a class="nav-link dropdown-toggle hide-arrow" href="admin-testimonials.php" title="<?php echo $pending_testimonials; ?> témoignages en attente">
                                    <i class="icon-base ri ri-notification-line icon-lg"></i>
                                    <span class="badge rounded-pill bg-danger badge-dot badge-notifications"><?php echo $pending_testimonials; ?></span>
                                </a>
                            </li>
                            <?php endif; ?>

                            <!-- User Profile -->
                            <li class="nav-item navbar-dropdown dropdown-user dropdown">
                                <a class="nav-link dropdown-toggle hide-arrow p-0" href="javascript:void(0);" data-bs-toggle="dropdown">
                                    <div class="avatar avatar-online">
                                        <?php 
                                        // Récupérer les informations utilisateur depuis la session ou la base de données
                                        $avatar_file = null;
                                        $current_username = $_SESSION['admin_username'] ?? 'Administrateur';
                                        $current_email = $_SESSION['admin_email'] ?? '';
                                        
                                        if (isset($_SESSION['admin_avatar'])) {
                                            $avatar_file = $_SESSION['admin_avatar'];
                                        } elseif (isset($_SESSION['admin_user_id'])) {
                                            // Récupérer depuis la BDD si pas en session
                                            try {
                                                require_once __DIR__ . '/AdminUser.php';
                                                $adminUserTemp = new AdminUser($pdo ?? null);
                                                $userTemp = $adminUserTemp->getById($_SESSION['admin_user_id']);
                                                if ($userTemp) {
                                                    if ($userTemp['avatar']) {
                                                        $avatar_file = $userTemp['avatar'];
                                                        $_SESSION['admin_avatar'] = $avatar_file;
                                                    }
                                                    // Mettre à jour les informations en session
                                                    $current_username = $userTemp['username'];
                                                    $current_email = $userTemp['email'];
                                                    $_SESSION['admin_username'] = $current_username;
                                                    $_SESSION['admin_email'] = $current_email;
                                                }
                                            } catch (Exception $e) {
                                                // Ignorer l'erreur et utiliser les valeurs par défaut
                                            }
                                        }
                                        ?>
                                        <?php if ($avatar_file && file_exists(__DIR__ . '/uploads/avatars/' . $avatar_file)): ?>
                                            <img src="uploads/avatars/<?php echo htmlspecialchars($avatar_file); ?>" 
                                                 alt="Avatar Admin" 
                                                 class="rounded-circle" 
                                                 style="width: 40px; height: 40px; object-fit: cover;">
                                        <?php else: ?>
                                            <div class="avatar-initial bg-primary rounded-circle">
                                                <i class="ri ri-admin-line"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li>
                                        <a class="dropdown-item" href="admin-profile.php">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0 me-3">
                                                    <div class="avatar avatar-online">
                                                        <?php if ($avatar_file && file_exists(__DIR__ . '/uploads/avatars/' . $avatar_file)): ?>
                                                            <img src="uploads/avatars/<?php echo htmlspecialchars($avatar_file); ?>" 
                                                                 alt="Avatar Admin" 
                                                                 class="rounded-circle" 
                                                                 style="width: 40px; height: 40px; object-fit: cover;">
                                                        <?php else: ?>
                                                            <div class="avatar-initial bg-primary rounded-circle">
                                                                <i class="ri ri-admin-line"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($current_username); ?></h6>
                                                    <small class="text-muted"><?php echo htmlspecialchars($current_email ?: 'SERVICES-AE'); ?></small>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <li><div class="dropdown-divider my-1"></div></li>
                                    <li>
                                        <a class="dropdown-item" href="admin-profile.php">
                                            <i class="ri ri-user-3-line me-3"></i>
                                            <span class="align-middle">Mon Profil</span>
                                        </a>
                                    </li>
                                    <li><div class="dropdown-divider my-1"></div></li>
                                    <li>
                                        <a class="dropdown-item" href="../index.php" target="_blank">
                                            <i class="ri ri-home-line me-3"></i>
                                            <span class="align-middle">Voir le Site</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="dashboard-stats.php">
                                            <i class="ri ri-line-chart-line me-3"></i>
                                            <span class="align-middle">Analytics</span>
                                        </a>
                                    </li>
                                    <li><div class="dropdown-divider my-1"></div></li>
                                    <li>
                                        <a class="dropdown-item" href="?logout=1">
                                            <i class="ri ri-logout-box-r-line me-3"></i>
                                            <span class="align-middle">Déconnexion</span>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </div>
                </nav>
                <!-- / Navbar -->

                <!-- Content wrapper -->
                <div class="content-wrapper">
                    <!-- Content -->
                    <div class="container-xxl flex-grow-1 container-p-y">
                        
                        <!-- Page Content -->
                        <?php if (isset($page_content)): ?>
                            <?php echo $page_content; ?>
                        <?php else: ?>
                            <!-- Default content will be inserted here -->
                        <?php endif; ?>
                        
                    </div>
                    <!-- / Content -->

                    <!-- Footer -->
                    <footer class="content-footer footer bg-footer-theme">
                        <div class="container-xxl">
                            <div class="footer-container d-flex align-items-center justify-content-between py-4 flex-md-row flex-column">
                                <div class="text-body">
                                    © <?php echo date('Y'); ?> <strong>SERVICES-AE</strong> - Panel d'Administration
                                </div>
                                <div class="d-none d-lg-inline-block">
                                    <!-- Suppression du lien Site Web dans le footer -->
                                    <a href="../ANALYTICS-DOCUMENTATION.md" class="footer-link" target="_blank">Documentation</a>
                                </div>
                            </div>
                        </div>
                    </footer>
                    <!-- / Footer -->

                    <div class="content-backdrop fade"></div>
                </div>
                <!-- Content wrapper -->
            </div>
            <!-- / Layout page -->
        </div>

        <!-- Overlay -->
        <div class="layout-overlay layout-menu-toggle"></div>
    </div>
    <!-- / Layout wrapper -->

    <!-- Core JS -->
    <script src="pages/assets/vendor/libs/jquery/jquery.js"></script>
    <script src="pages/assets/vendor/libs/popper/popper.js"></script>
    <script src="pages/assets/vendor/js/bootstrap.js"></script>
    <script src="pages/assets/vendor/libs/node-waves/node-waves.js"></script>
    <script src="pages/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>

    <script src="pages/assets/vendor/js/menu.js"></script>

    <!-- Main JS -->
    <script src="pages/assets/js/main.js"></script>

    <?php if (isset($include_charts) && $include_charts): ?>
    <!-- Charts JS -->
    <script src="pages/assets/vendor/libs/apex-charts/apexcharts.js"></script>
    <?php endif; ?>

    <!-- Page Specific JS -->
    <?php if (isset($page_js)): ?>
        <script><?php echo $page_js; ?></script>
    <?php endif; ?>

    <?php if (isset($page_js_files) && is_array($page_js_files)): ?>
        <?php foreach ($page_js_files as $js_file): ?>
            <script src="<?php echo $js_file; ?>"></script>
        <?php endforeach; ?>
    <?php endif; ?>

    <script>
        // Ajout d'animations et interactions personnalisées
        document.addEventListener('DOMContentLoaded', function() {
            // Animation des cartes statistiques
            const statsCards = document.querySelectorAll('.stats-card-custom');
            statsCards.forEach(card => {
                card.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-5px) scale(1.02)';
                });
                card.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0) scale(1)';
                });
            });

            // Mise à jour automatique de l'heure dans le footer
            function updateTime() {
                const now = new Date();
                const timeStr = now.toLocaleTimeString('fr-FR');
                const timeElement = document.getElementById('current-time');
                if (timeElement) {
                    timeElement.textContent = timeStr;
                }
            }
            setInterval(updateTime, 1000);
        });
    </script>
</body>
</html>