<?php
// includes/header.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/auto_backup_runner.php';

$is_admin_header = (isset($_SESSION['role']) && $_SESSION['role'] === 'admin');

// متغیرهای سایدبار
$sidebar_wallet = 0;
$sidebar_credit_debt = 0;

$showSidebarTimer = false;
$sidebarTimerTarget = '';

$showFestivalTimer = false;
$festivalTimerTarget = '';
$festivalPlanName = '';

if (isset($pdo)) {
    // ۱. دریافت اطلاعات مالی کاربر
    if (isset($_SESSION['user_id']) && !$is_admin_header) {
        try {
            $stmt_fin = $pdo->prepare("SELECT wallet_balance, credit_debt FROM users WHERE id = ?");
            $stmt_fin->execute([$_SESSION['user_id']]);
            $user_fin = $stmt_fin->fetch();
            if ($user_fin) {
                $sidebar_wallet = (int)($user_fin['wallet_balance'] ?? 0);
                $sidebar_credit_debt = (int)($user_fin['credit_debt'] ?? 0);
            }
        } catch (Exception $e) {}
    }

    // هماهنگ‌سازی زمان سرور با دیتابیس برای جلوگیری از خطای Timezone
    $dbTimeStr = null;
    try { $dbTimeStr = $pdo->query("SELECT NOW()")->fetchColumn(); } catch(Exception $e) {}
    $dbTimestamp = $dbTimeStr ? strtotime($dbTimeStr) : time();

    // ۲. بررسی تایمر بونوس مالی (شارژ کیف پول)
    try {
        $stmtGS = $pdo->query("SELECT setting_key, setting_value FROM global_settings WHERE setting_key IN ('bonus_system_status', 'bonus_timer_active', 'bonus_timer_date')");
        $gSettings = [];
        while ($row = $stmtGS->fetch(PDO::FETCH_ASSOC)) {
            $gSettings[$row['setting_key']] = $row['setting_value'];
        }
        
        if (($gSettings['bonus_system_status'] ?? '0') === '1' && ($gSettings['bonus_timer_active'] ?? '0') === '1' && !empty($gSettings['bonus_timer_date'])) {
            if (strtotime($gSettings['bonus_timer_date']) > $dbTimestamp) {
                $showSidebarTimer = true;
                $sidebarTimerTarget = date('Y-m-d\TH:i:s', strtotime($gSettings['bonus_timer_date']));
            }
        }
    } catch (Exception $e) {}

    // ۳. بررسی تایمر جشنواره محصولات (فروشگاه)
    try {
        $colExists = $pdo->query("SHOW COLUMNS FROM plans LIKE 'has_timer'")->rowCount() > 0;
        if($colExists) {
            $stmtFest = $pdo->query("SELECT plan_name, timer_end FROM plans WHERE has_timer = 1 AND timer_end IS NOT NULL ORDER BY timer_end ASC");
            $activeFests = $stmtFest->fetchAll(PDO::FETCH_ASSOC);
            foreach($activeFests as $fest) {
                if (strtotime($fest['timer_end']) > $dbTimestamp) {
                    $showFestivalTimer = true;
                    $festivalTimerTarget = date('Y-m-d\TH:i:s', strtotime($fest['timer_end']));
                    $festivalPlanName = $fest['plan_name'];
                    break; // فقط نزدیک‌ترین جشنواره را در سایدبار نشان می‌دهد
                }
            }
        }
    } catch (Exception $e) {}

    // ۴. اعمال محدودیت نمایش برای نمایندگان دارای قیمت اختصاصی (VIP)
    if (!$is_admin_header && isset($_SESSION['user_id'])) {
        try {
            $stmtCheckVIP = $pdo->prepare("SELECT allow_bonus, allow_festival FROM user_prices WHERE user_id = ?");
            $stmtCheckVIP->execute([$_SESSION['user_id']]);
            $vipPerms = $stmtCheckVIP->fetchAll(PDO::FETCH_ASSOC);
            
            if (count($vipPerms) > 0) {
                $vipAllowBonus = false;
                $vipAllowFestival = false;
                foreach ($vipPerms as $perm) {
                    if ($perm['allow_bonus'] == 1) $vipAllowBonus = true;
                    if ($perm['allow_festival'] == 1) $vipAllowFestival = true;
                }
                if (!$vipAllowBonus) $showSidebarTimer = false;
                if (!$vipAllowFestival) $showFestivalTimer = false;
            }
        } catch (Exception $e) {}
    }
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title>پنل مدیریت VPNet</title>
    
    <link rel="manifest" href="/vpnet-panel/manifest.json">
    <meta name="theme-color" content="#3b82f6">
    <link rel="apple-touch-icon" href="/vpnet-panel/assets/images/icon-192.png">

    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/vpnet-panel/sw.js', { scope: '/vpnet-panel/' })
                    .catch(err => console.log('ServiceWorker Error!', err));
            });
        }
    </script>

    <script>
        // بررسی تم دارک و وضعیت جمع بودن سایدبار
        if (localStorage.getItem('color-theme') === 'dark' || (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
        
        if (localStorage.getItem('sidebar_collapsed') === 'true') {
            document.documentElement.classList.add('sidebar-collapsed');
        }
    </script>
    
    <script src="/vpnet-panel/assets/js/tailwindcss.js"></script>
    <script>tailwind.config = { darkMode: 'class' }</script>
    
    <link rel="stylesheet" href="/vpnet-panel/assets/css/datatables.min.css">
    <link rel="stylesheet" href="/vpnet-panel/assets/css/Vazirmatn-font-face.css">
    
    <style> 
        body { font-family: 'Vazirmatn', sans-serif; background-color: #f8fafc; transition: background-color 0.3s, color 0.3s; } 
        .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
        .nav-item.active { background-color: #eff6ff; color: #1d4ed8; border-right: 4px solid #2563eb; font-weight: 900; }
        .nav-item.active svg { color: #2563eb; }

        html.dark body { background-color: #0f172a !important; color: #f8fafc !important; }
        html.dark .bg-white { background-color: #1e293b !important; border-color: #334155 !important; }
        html.dark .bg-gray-50 { background-color: #0f172a !important; border-color: #334155 !important; }
        html.dark .bg-gray-100, html.dark .bg-gray-200 { background-color: #334155 !important; border-color: #475569 !important; }
        html.dark .border-gray-100, html.dark .border-gray-200 { border-color: #334155 !important; }
        html.dark .text-gray-800, html.dark .text-gray-700 { color: #f8fafc !important; }
        html.dark .text-gray-600 { color: #cbd5e1 !important; }
        html.dark .text-gray-500, html.dark .text-gray-400 { color: #94a3b8 !important; }
        
        html.dark aside#sidebar, html.dark header { background-color: #1e293b !important; border-color: #334155 !important; }
        html.dark aside#sidebar .border-b { border-color: #334155 !important; }
        html.dark aside#sidebar .bg-gradient-to-b { background: #1e293b !important; }
        html.dark aside#sidebar .nav-item:hover:not(.active) { background-color: #0f172a !important; color: #60a5fa !important; }
        html.dark aside#sidebar .nav-item.active { background-color: #1e3a8a !important; color: #bfdbfe !important; border-color: #3b82f6 !important; }
        html.dark aside#sidebar .nav-item.active svg { color: #bfdbfe !important; }
        html.dark #mobileMenu { background-color: #1e293b !important; border-color: #334155 !important; }
        html.dark #mobileMenu a:hover { background-color: #0f172a !important; color: #60a5fa !important; }
        
        html.dark input:not([type="color"]), html.dark select, html.dark textarea { background-color: #0f172a !important; color: #f8fafc !important; border-color: #334155 !important; }
        html.dark input:focus, html.dark select:focus { border-color: #3b82f6 !important; }
        html.dark table.dataTable tbody tr { background-color: #1e293b !important; color: #cbd5e1 !important; }
        html.dark table.dataTable tbody tr:hover, html.dark tr:hover { background-color: #334155 !important; }
        html.dark .dataTables_wrapper .dataTables_paginate .paginate_button { background-color: #334155 !important; color: #cbd5e1 !important; border-color: #475569 !important; }
        html.dark .dataTables_wrapper .dataTables_paginate .paginate_button.current { background-color: #3b82f6 !important; color: white !important; border-color: #3b82f6 !important; }
        html.dark .dataTables_wrapper .dataTables_info, html.dark .dataTables_wrapper label { color: #94a3b8 !important; }

        html.dark #notiDropdown { background-color: #1e293b !important; border-color: #334155 !important; }
        html.dark #notiDropdown > div:first-child { background-color: #0f172a !important; border-color: #334155 !important; }
        html.dark #notiList a:hover { background-color: #334155 !important; border-color: #475569 !important; }

        /* استایل‌های مربوط به جمع شدن سایدبار */
        .logo-mini { display: none; }
        @media (min-width: 768px) {
            html.sidebar-collapsed aside#sidebar { width: 5.5rem; }
            html.sidebar-collapsed .main-content-wrapper { padding-right: 5.5rem; }
            html.sidebar-collapsed .sidebar-text,
            html.sidebar-collapsed .sidebar-banner { display: none !important; }
            html.sidebar-collapsed .nav-item { justify-content: center; padding-left: 0; padding-right: 0; position: relative; }
            html.sidebar-collapsed .nav-item svg { margin: 0; width: 1.5rem; height: 1.5rem; }
            html.sidebar-collapsed .logo-full { display: none; }
            html.sidebar-collapsed .logo-mini { display: block !important; }
            
            html.sidebar-collapsed .nav-item:hover::after {
                content: attr(data-tooltip);
                position: absolute;
                right: 100%;
                margin-right: 0.75rem;
                background-color: #1e293b;
                color: #fff;
                padding: 0.35rem 0.75rem;
                border-radius: 0.5rem;
                font-size: 0.75rem;
                font-weight: bold;
                white-space: nowrap;
                z-index: 50;
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            }
        }
    </style>
    
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const formatNum = (num) => num < 10 ? "0" + num : num;
        const timers = document.querySelectorAll('.sidebar-timer-el, .store-plan-timer');
        
        if (timers.length > 0) {
            timers.forEach(function(el) {
                const targetStr = el.getAttribute('data-target');
                if (!targetStr) return; 

                const targetDate = new Date(targetStr).getTime();
                
                const timerInterval = setInterval(function() {
                    const now = new Date().getTime();
                    const distance = targetDate - now;
                    
                    if (distance < 0) {
                        clearInterval(timerInterval);
                        el.innerHTML = "پایان زمان";
                        if(el.classList.contains('store-plan-timer') && !el.dataset.reloaded) {
                            el.dataset.reloaded = "1";
                            setTimeout(() => location.reload(), 2000);
                        }
                        return;
                    }
                    
                    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
                    
                    let timeStr = "";
                    if (days > 0) timeStr += days + " روز و ";
                    timeStr += formatNum(hours) + ":" + formatNum(minutes) + ":" + formatNum(seconds);
                    
                    el.innerHTML = timeStr;
                }, 1000);
            });
        }
    });

    function toggleDesktopSidebar() {
        document.documentElement.classList.toggle('sidebar-collapsed');
        localStorage.setItem('sidebar_collapsed', document.documentElement.classList.contains('sidebar-collapsed'));
    }
    </script>

    <script>
        let deferredPrompt = null;
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            deferredPrompt = e;
            const installBtns = document.querySelectorAll('.install-pwa-btn');
            installBtns.forEach(btn => btn.classList.remove('hidden'));
        });

        window.addEventListener('appinstalled', () => {
            deferredPrompt = null;
            document.querySelectorAll('.install-pwa-btn').forEach(btn => btn.classList.add('hidden'));
        });

        document.addEventListener('DOMContentLoaded', () => {
            const installBtns = document.querySelectorAll('.install-pwa-btn');
            installBtns.forEach(btn => {
                if (deferredPrompt) btn.classList.remove('hidden');
                btn.addEventListener('click', async () => {
                    if (deferredPrompt) {
                        deferredPrompt.prompt();
                        const { outcome } = await deferredPrompt.userChoice;
                        deferredPrompt = null;
                        installBtns.forEach(b => b.classList.add('hidden'));
                    }
                });
            });
        });
    </script>
</head>
<body class="text-gray-800 flex h-screen overflow-hidden transition-colors duration-300">

    <div id="page-loading-overlay" class="fixed inset-0 z-[99999] bg-white/80 dark:bg-[#0f172a]/80 backdrop-blur-sm flex flex-col items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300">
        <div class="relative w-16 h-16">
            <div class="absolute inset-0 border-4 border-blue-100 dark:border-slate-700 rounded-full"></div>
            <div class="absolute inset-0 border-4 border-blue-600 dark:border-blue-500 rounded-full border-t-transparent animate-spin"></div>
        </div>
        <span class="mt-4 text-sm font-black text-blue-600 dark:text-blue-400 animate-pulse drop-shadow-sm">در حال دریافت اطلاعات...</span>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const overlay = document.getElementById('page-loading-overlay');
            const showLoader = () => { overlay.classList.remove('opacity-0', 'pointer-events-none'); overlay.classList.add('opacity-100'); };
            const hideLoader = () => { overlay.classList.remove('opacity-100'); overlay.classList.add('opacity-0', 'pointer-events-none'); };

            document.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', function(e) {
                    const href = this.getAttribute('href');
                    const target = this.getAttribute('target');
                    if (href && !href.startsWith('#') && !href.startsWith('javascript:') && target !== '_blank' && !this.hasAttribute('download') && !this.hasAttribute('onclick')) {
                        showLoader();
                    }
                });
            });

            document.querySelectorAll('form').forEach(form => {
                form.addEventListener('submit', function() { showLoader(); });
            });

            window.addEventListener('pageshow', (e) => { hideLoader(); });
        });
    </script>

    <?php require_once 'sidebar.php'; ?>

    <div class="flex-1 flex flex-col h-screen overflow-hidden md:pr-64 transition-all duration-300 relative main-content-wrapper">
        <header class="h-20 bg-white/90 backdrop-blur shadow-[0_4px_30px_rgba(0,0,0,0.03)] border-b border-gray-100 flex items-center justify-between px-4 sm:px-6 z-30 relative transition-colors duration-300 dark:bg-slate-800/90 dark:border-slate-700">
            <div class="flex items-center gap-3">
                <button onclick="toggleSidebar()" class="md:hidden text-gray-500 hover:text-blue-600 hover:bg-blue-50 focus:outline-none p-2 rounded-xl transition dark:hover:bg-slate-700">
                    <svg class="w-6 h-6 sm:w-7 sm:h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                </button>
                <button onclick="toggleDesktopSidebar()" class="hidden md:block text-gray-500 hover:text-blue-600 hover:bg-blue-50 focus:outline-none p-2 rounded-xl transition dark:hover:bg-slate-700">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                </button>
            </div>
            
            <div class="flex items-center gap-2 md:gap-4">
                
                <button class="install-pwa-btn hidden relative p-2.5 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 rounded-full transition focus:outline-none shadow-sm dark:bg-emerald-900/30 dark:border-emerald-800 dark:text-emerald-400" title="نصب اپلیکیشن">
                    <svg class="w-5 h-5 sm:w-6 sm:h-6 animate-bounce" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                </button>

                <button id="theme-toggle" class="relative p-2.5 text-gray-500 bg-gray-50 hover:bg-gray-100 border border-gray-100 rounded-full transition focus:outline-none shadow-sm dark:bg-slate-800 dark:border-slate-700 dark:hover:bg-slate-700 dark:text-yellow-400">
                    <svg id="theme-toggle-light-icon" class="hidden w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="5"></circle>
                        <line x1="12" y1="1" x2="12" y2="3"></line>
                        <line x1="12" y1="21" x2="12" y2="23"></line>
                        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
                        <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
                        <line x1="1" y1="12" x2="3" y2="12"></line>
                        <line x1="21" y1="12" x2="23" y2="12"></line>
                        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
                        <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
                    </svg>
                    <svg id="theme-toggle-dark-icon" class="hidden w-5 h-5 sm:w-6 sm:h-6" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"></path>
                    </svg>
                </button>
                
                <?php if(isset($_SESSION['user_id'])): ?>
                <div class="relative">
                    <button id="notiBtn" class="relative p-2.5 text-gray-500 bg-gray-50 hover:bg-gray-100 border border-gray-100 rounded-full transition focus:outline-none shadow-sm dark:bg-slate-800 dark:border-slate-700 dark:hover:bg-slate-700 dark:text-gray-300">
                        <svg class="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"></path></svg>
                        <span id="notiBadge" class="absolute top-0 right-0 flex h-3 w-3 hidden">
                          <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                          <span class="relative inline-flex rounded-full h-3 w-3 bg-red-500 border-2 border-white dark:border-slate-800"></span>
                        </span>
                    </button>
                    <div id="notiDropdown" class="hidden absolute left-0 mt-3 w-80 sm:w-96 bg-white rounded-3xl shadow-2xl border border-gray-100 z-50 overflow-hidden transform origin-top-left transition-all">
                        <div class="bg-gray-50 px-5 py-4 border-b border-gray-100 flex justify-between items-center dark:bg-slate-900 dark:border-slate-700">
                            <h3 class="text-sm font-black text-gray-800 dark:text-gray-200">اعلانات سیستم</h3>
                            <span id="notiCountText" class="text-xs bg-blue-600 text-white px-2 py-0.5 rounded-md font-bold shadow-sm">0</span>
                        </div>
                        <div id="notiList" class="max-h-[350px] overflow-y-auto p-2 flex flex-col gap-1 custom-scrollbar dark:bg-slate-800">
                            <div class="p-6 text-center text-xs text-gray-400 font-bold">در حال بررسی...</div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="flex items-center gap-3 border-r border-gray-200 dark:border-slate-600 pr-3 md:pr-5">
                    <a href="/vpnet-panel/modules/profile.php" class="hidden sm:flex items-center gap-2 text-sm font-bold bg-white border border-gray-200 text-gray-700 px-4 py-2 rounded-xl hover:bg-gray-50 hover:border-gray-300 transition shadow-sm dark:bg-slate-800 dark:border-slate-700 dark:text-gray-200 dark:hover:bg-slate-700">
                        <div class="w-6 h-6 bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400 rounded-full flex items-center justify-center text-xs">👤</div>
                        <?php echo htmlspecialchars(!empty($_SESSION['fullname']) ? $_SESSION['fullname'] : ($_SESSION['username'] ?? 'ناشناس')); ?>
                    </a>
                    <a href="/vpnet-panel/logout.php" class="bg-red-50 text-red-600 hover:bg-red-500 hover:text-white border border-red-100 text-xs sm:text-sm font-bold px-3 py-2 sm:px-4 sm:py-2.5 rounded-xl transition shadow-sm flex items-center gap-2 dark:bg-[#4c0519] dark:border-[#881337] dark:text-red-400 dark:hover:bg-[#881337] dark:hover:text-white">
                        <span class="hidden sm:inline">خروج</span>
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path></svg>
                    </a>
                </div>
            </div>
        </header>

        <main class="flex-1 overflow-x-hidden overflow-y-auto p-4 sm:p-6 lg:p-8 relative">
            <div class="max-w-7xl mx-auto">