<?php
// Detect the current page for auto-active state
$current_page = basename($_SERVER['PHP_SELF']);
if ($current_page == '' || $current_page == '/') {
    $current_page = 'index.php';
}

// Safely start session
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

// ---------------------------------------------------------
// PULL IN DB CONNECTION (Checks both current and 1 level up)
// ---------------------------------------------------------
$is_root_dir = false; // Flag to determine if we are in the main folder
if (file_exists('../config.php')) {
    require_once '../config.php';
} elseif (file_exists('./config.php')) {
    require_once './config.php';
    $is_root_dir = true; // We are in the main root folder
}

// Check common session variable names to see if the user is logged in
$user_id = $_SESSION['user_id'] ?? $_SESSION['id'] ?? null;
$is_logged_in = ($user_id !== null);

// ==============================================================================
// FETCH LOGGED IN USER DATA & CALCULATE VIP
// ==============================================================================
$member_name = "MemberNNGXONRC"; // Fallbacks
$balance = 0.00;
$total_deposits = 0.00;

if ($is_logged_in) {
    global $pdo, $conn;
    try {
        if (isset($pdo)) {
            $stmt = $pdo->prepare("SELECT member_name, balance, total_deposits FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($user) {
                $member_name = $user['member_name'] ?? $member_name;
                $balance = (float)($user['balance'] ?? 0);
                $total_deposits = (float)($user['total_deposits'] ?? 0);
            }
        } elseif (isset($conn)) {
            $stmt = $conn->prepare("SELECT member_name, balance, total_deposits FROM users WHERE id = ?");
            $stmt->bind_param("s", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($user = $result->fetch_assoc()) {
                $member_name = $user['member_name'] ?? $member_name;
                $balance = (float)($user['balance'] ?? 0);
                $total_deposits = (float)($user['total_deposits'] ?? 0);
            }
        }
    } catch (Exception $e) { }

    // VIP Formula
    $vip_level = 0;
    $next_vip_level = 1;
    $progress_percent = 0;
    $current_target = 0;
    $next_target = 1000;
    $remaining_amount = 1000;

    if ($total_deposits >= 1000) {
        $vip_level = floor(log($total_deposits / 1000, 2)) + 1;
        if ($vip_level >= 8) {
            $vip_level = 8;
            $next_vip_level = 8;
            $progress_percent = 100;
            $remaining_amount = 0;
            $next_target = 128000;
        } else {
            $next_vip_level = $vip_level + 1;
            $current_target = 1000 * pow(2, $vip_level - 1);
            $next_target = 1000 * pow(2, $vip_level);
            $progress = $total_deposits - $current_target;
            $target_diff = $next_target - $current_target;
            $progress_percent = ($progress / $target_diff) * 100;
            $remaining_amount = $next_target - $total_deposits;
        }
    } else {
        $progress_percent = ($total_deposits / 1000) * 100;
        $remaining_amount = 1000 - $total_deposits;
        $next_target = 1000;
    }
    $progress_percent = max(0, min(100, $progress_percent));
}
?>
<meta name="google" content="notranslate">
<meta name="robots" content="notranslate">
<meta http-equiv="Content-Language" content="en">

<script>
    document.documentElement.setAttribute("translate", "no");
    document.documentElement.classList.add("notranslate");
    document.documentElement.setAttribute("lang", "en");

    const translateObserver = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            mutation.addedNodes.forEach((node) => {
                if (node.tagName === 'SCRIPT' && node.src && node.src.includes('translate.google.com')) { node.remove(); }
                if (node.className && typeof node.className === 'string' && node.className.includes('goog-te-')) { node.remove(); }
            });
        });
    });
    translateObserver.observe(document.documentElement, { childList: true, subtree: true });
</script>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
<link rel="icon" type="image/png" href="./img/ico.png">
<link rel="apple-touch-icon" href="./img/ico.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    /* ========================================================
       GLOBAL COLOR OVERRIDES
       ======================================================== */
    :root {
        --bg-dark: #120904;         /* Deep rich brown background */
        --bg-header: #1c100a;       /* Header and UI background */
        --bg-card: #22150f;         /* Deep brown card background */
        --primary-orange: #f26d0f;  /* Solid sharp orange */
        --text-main: #ffffff;
        --text-muted: #92837b;
        --border-color: #33241d;
        --success-green: #32c149;
    }

    /* ========================================================
       TRANSLATION CSS CLOAKING DEVICE
       ======================================================== */
    .goog-te-banner-frame.skiptranslate, 
    .goog-te-banner-frame, 
    #goog-gt-tt, 
    .goog-te-balloon-frame { 
        display: none !important; 
        visibility: hidden !important; 
        opacity: 0 !important;
    }
    body { top: 0px !important; }
    .goog-text-highlight { background-color: transparent !important; box-shadow: none !important; }

    /* ========================================================
       ANTI-BEHAVIOR GLOBAL LOCKS
       ======================================================== */
    *, *::before, *::after { box-sizing: border-box !important; }
    
    * {
        -webkit-tap-highlight-color: transparent !important;
        -webkit-tap-highlight-color: rgba(0,0,0,0) !important;
        -webkit-touch-callout: none !important; 
        -webkit-user-select: none !important;   
        -moz-user-select: none !important;      
        -ms-user-select: none !important;       
        user-select: none !important;           
    }

    input, textarea {
        -webkit-user-select: auto !important;
        -moz-user-select: auto !important;
        -ms-user-select: auto !important;
        user-select: auto !important;
    }

    a, button, img, .lang-selector, .auth-header-left {
        touch-action: manipulation !important;
        outline: none !important; 
    }

    /* ========================================================
       GLOBAL APP WRAPPER & FLASHBACK FIX
       ======================================================== */
    /* Mobile First: Keep HTML dark to prevent white flash on load */
    html {
        background-color: var(--bg-dark) !important; 
        scroll-behavior: smooth; 
        scrollbar-width: none; 
        overflow-y: auto !important; /* STRICTLY ALLOW HTML SCROLL */
        height: 100%;
    }

    /* Desktop/PC: Change outside background to mid-light grey */
    @media screen and (min-width: 415px) {
        html {
            background-color: #d1d5db !important; /* Changed to mid-light grey */
        }
    }

    ::-webkit-scrollbar { display: none; width: 0px; background: transparent; }

    body {
        width: 100% !important;
        max-width: 414px !important; 
        margin: 0 auto !important;
        background-color: var(--bg-dark) !important; 
        color: var(--text-main) !important;
        background-image: none !important;
        position: relative !important;
        min-height: 100vh !important;
        overflow-x: hidden !important;
        overflow-y: auto !important; /* EXPLICITLY ALLOW Y SCROLLING */
        -ms-overflow-style: none; 
        -webkit-overflow-scrolling: touch !important; 
        box-shadow: 0 0 20px rgba(0,0,0,0.2); 
    }

    .footer-container {
        max-width: 414px !important; 
        left: 50% !important;
        transform: translateX(-50%) !important;
    }

    /* TEXT VISIBILITY OVERRIDES */
    h1, h2, h3, h4, h5, h6, .page-title, .header-title, .tab-button, .nav-tab, button {
        color: var(--text-main) !important;
    }
    .card-content span, .card-content p, .stats-text {
        color: var(--text-muted) !important;
    }

    /* ========================================================
       HEADER SPECIFIC STYLES
       ======================================================== */
    .main-header {
        <?php if(isset($is_auth_page) && $is_auth_page): ?>
            background-color: var(--bg-dark);
            padding: 15px 15px 10px 15px;
        <?php else: ?>
            background-color: var(--bg-header);
            padding: 10px 15px 15px 15px;
            border-bottom: 1px solid var(--border-color);
        <?php endif; ?>
        position: sticky; 
        top: 0; 
        z-index: 999; 
        width: 100%;
    }

    .header-content { display: flex; justify-content: space-between; align-items: center; position: relative; }

    .header-logo { height: 40px; width: auto; filter: drop-shadow(0 2px 4px rgba(0,0,0,0.5)); }
    
    .auth-buttons { display: flex; gap: 10px; align-items: center; }
    .auth-buttons a {
        padding: 6px 18px; border-radius: 25px; font-size: 13px; font-weight: bold;
        cursor: pointer; font-family: inherit; transition: all 0.2s ease; text-decoration: none; 
        display: inline-block; text-align: center;
    }
    .btn-register { background-color: var(--primary-orange) !important; color: var(--text-main) !important; border: none; box-shadow: none !important; }
    .btn-register:active { transform: scale(0.95); }
    
    .btn-login { background-color: transparent; color: var(--primary-orange) !important; border: 1px solid var(--primary-orange); }
    .btn-login:active { transform: scale(0.95); background: rgba(242, 109, 15, 0.1); }

    /* VIP PROFILE HEADER */
    .top-flap-wrapper {
        position: absolute; top: -16px; left: 50%; transform: translateX(-50%);
        width: 190px; height: 48px; z-index: 10; display: flex; justify-content: center;
        align-items: flex-end; padding-bottom: 5px; 
    }
    .flap-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; }
    .flap-img { height: 32px; width: auto; z-index: 2; position: relative; filter: drop-shadow(0 2px 3px rgba(0,0,0,0.8)); }

    .profile-top-row { display: flex; justify-content: space-between; align-items: center; width: 100%; margin-top: 38px; }
    .profile-left { display: flex; align-items: center; gap: 10px; }
    .profile-avatar { width: 48px; height: 48px; border-radius: 50%; border: 2px solid #eab03c; object-fit: cover; }
    .profile-info { display: flex; flex-direction: column; justify-content: center; }
    .profile-name { color: var(--text-main); font-size: 14px; font-weight: 700; margin-bottom: 2px; }
    .profile-balance-wrapper { display: flex; align-items: center; gap: 6px; }
    .profile-balance { color: #eab03c; font-size: 17px; font-weight: 900; }
    .toggle-balance { color: var(--text-muted); font-size: 13px; cursor: pointer; }

    .profile-right { display: flex; align-items: center; gap: 10px; }
    .action-sq-btn {
        background-color: var(--border-color); border-radius: 14px; width: 40px; height: 40px;
        display: flex; align-items: center; justify-content: center; color: var(--text-main);
        font-size: 18px; text-decoration: none; cursor: pointer; position: relative;
    }
    .action-sq-btn:active { background-color: #4a342a; }

    .vip-progress-container {
        display: flex; flex-direction: column; border: 1px solid var(--border-color);
        border-radius: 20px; padding: 8px 15px; margin-top: 15px;
    }
    .vip-progress-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
    .vip-badge { color: var(--text-main); font-size: 13px; font-weight: bold; white-space: nowrap; }
    .vip-track { flex: 1; height: 8px; background-color: var(--bg-dark); border-radius: 10px; margin: 0 15px; overflow: hidden; }
    .vip-fill { height: 100%; background: linear-gradient(to right, #e77320, #f8c946); border-radius: 10px; transition: width 0.5s ease-out; }
    .vip-target-text { color: #eab03c; font-size: 12px; font-weight: bold; white-space: nowrap; }
    .vip-amounts-text { color: var(--text-muted); font-size: 10px; text-align: right; margin-right: 5px; margin-top: 2px; }

    .notif-dropdown {
        position: absolute; top: 85px; right: 15px; width: 240px; background: rgba(28, 16, 10, 0.95);
        backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border: 1px solid var(--border-color);
        border-radius: 12px; box-shadow: 0 10px 20px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;
    }
    .notif-dropdown.show { display: flex; }
    .notif-item { padding: 12px 15px; color: #e2d1c3; font-size: 13px; border-bottom: 1px solid var(--border-color); }
    .notif-item:last-child { border-bottom: none; }
    .notif-header { background: var(--bg-dark); color: #fff; padding: 10px 15px; font-size: 14px; font-weight: bold; }

    .auth-header-left { color: #fff; font-size: 20px; cursor: pointer; text-decoration: none; padding: 5px; }
    .auth-header-right { display: flex; align-items: center; gap: 15px; color: #d1c4b2; font-size: 18px; }
    .lang-selector { display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: bold; color: #fff; cursor: pointer; }
    .lang-selector img { width: 18px; height: 18px; border-radius: 50%; object-fit: cover; }

    /* ========================================================
       FLOATING WHATSAPP BUTTON
       ======================================================== */
    .floating-whatsapp {
        position: fixed;
        bottom: 110px; 
        right: 20px;
        width: 55px;
        height: 55px;
        background-color: #25D366;
        color: white !important;
        border-radius: 50%;
        border: 2px solid #ffffff; 
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32px;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.4);
        z-index: 9999;
        text-decoration: none;
        transition: transform 0.2s ease;
        animation: pulse-wa 2s infinite;
    }

    .floating-whatsapp:active {
        transform: scale(0.9);
    }

    @keyframes pulse-wa {
        0% { box-shadow: 0 0 0 0 rgba(37, 211, 102, 0.7); }
        70% { box-shadow: 0 0 0 15px rgba(37, 211, 102, 0); }
        100% { box-shadow: 0 0 0 0 rgba(37, 211, 102, 0); }
    }
</style>

<div class="main-header">
    <div class="header-content">
        <?php if(isset($is_auth_page) && $is_auth_page): ?>
            <a href="javascript:history.back()" class="auth-header-left"><i class="fa-solid fa-chevron-left"></i></a>
            <div class="auth-header-right">
                <i class="fa-solid fa-headset" style="color: var(--primary-orange);"></i>
                <div class="lang-selector"><img src="https://flagcdn.com/w40/pk.png" alt="PK"> UR</div>
            </div>
        <?php else: ?>
            <?php if(!$is_logged_in): ?>
                <img src="./img/logo.png" alt="PAKclub Logo" class="header-logo">
                <div class="auth-buttons">
                    <a href="signup.php" class="btn-register">رجسٹر کریں</a>
                    <a href="login.php" class="btn-login">لاگ ان</a>
                </div>
            <?php else: ?>
                <div class="top-flap-wrapper">
                    <svg class="flap-svg" viewBox="0 0 190 48" preserveAspectRatio="none">
                        <defs>
                            <linearGradient id="flapBgGrad" x1="0%" y1="0%" x2="0%" y2="100%">
                                <stop offset="0%" stop-color="#2a170d" />
                                <stop offset="100%" stop-color="#120904" />
                            </linearGradient>
                            <linearGradient id="flapGoldGrad" x1="0%" y1="0%" x2="100%" y2="0%">
                                <stop offset="0%" stop-color="#110905" stop-opacity="0" />
                                <stop offset="15%" stop-color="#110905" stop-opacity="0" />
                                <stop offset="30%" stop-color="#8a5a19" />
                                <stop offset="50%" stop-color="#ffde73" />
                                <stop offset="70%" stop-color="#8a5a19" />
                                <stop offset="85%" stop-color="#110905" stop-opacity="0" />
                                <stop offset="100%" stop-color="#110905" stop-opacity="0" />
                            </linearGradient>
                            <filter id="flapShadow" x="-10%" y="-10%" width="120%" height="150%">
                                <feDropShadow dx="0" dy="3" stdDeviation="3" flood-color="#000000" flood-opacity="0.85"/>
                            </filter>
                        </defs>
                        <path d="M 0,0 C 10,0 15,4 20,12 L 25,32 C 30,42 35,45 45,45 L 145,45 C 155,45 160,42 165,32 L 170,12 C 175,4 180,0 190,0 Z" fill="url(#flapBgGrad)" filter="url(#flapShadow)"/>
                        <path d="M 0,0 C 10,0 15,4 20,12 L 25,32 C 30,42 35,45 45,45 L 145,45 C 155,45 160,42 165,32 L 170,12 C 175,4 180,0 190,0" fill="none" stroke="#050201" stroke-width="2.5"/>
                        <path d="M 0,0 C 10,0 15,4 20,12 L 25,32 C 30,42 35,45 45,45 L 145,45 C 155,45 160,42 165,32 L 170,12 C 175,4 180,0 190,0" fill="none" stroke="url(#flapGoldGrad)" stroke-width="1.2"/>
                    </svg>
                    <img src="./img/logo.png" alt="PAKclub Logo" class="flap-img">
                </div>
                
                <div style="width: 100%;">
                    <div class="profile-top-row">
                        <div class="profile-left">
                            <img src="https://pakclub.club/images/1-BpxbCNk8.webp" class="profile-avatar" alt="User">
                            <div class="profile-info">
                                <div class="profile-name"><?php echo htmlspecialchars($member_name); ?></div>
                                <div class="profile-balance-wrapper">
                                    <span class="profile-balance" id="headerBalanceText" data-balance="Rs<?php echo number_format($balance, 2); ?>">Rs<?php echo number_format($balance, 2); ?></span>
                                    <i class="fa-solid fa-eye-slash toggle-balance" id="toggleBalanceBtn"></i>
                                </div>
                            </div>
                        </div>
                        <div class="profile-right">
                            <div class="action-sq-btn" id="notifBellBtn"><i class="fa-regular fa-bell"></i></div>
                            <a href="support.php" class="action-sq-btn"><i class="fa-regular fa-comment-dots"></i></a>
                        </div>
                    </div>

                    <div class="vip-progress-container">
                        <div class="vip-progress-top">
                            <span class="vip-badge">VIP <?php echo $vip_level; ?></span>
                            <div class="vip-track">
                                <div class="vip-fill" style="width: <?php echo number_format($progress_percent, 2); ?>%;"></div>
                            </div>
                            <?php if ($vip_level >= 8): ?>
                                <span class="vip-target-text">MAX VIP</span>
                            <?php else: ?>
                                <span class="vip-target-text">To VIP <?php echo $next_vip_level; ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if ($vip_level >= 8): ?>
                            <div class="vip-amounts-text">Total Deposits: <?php echo number_format($total_deposits); ?> (Max Level Reached)</div>
                        <?php else: ?>
                            <div class="vip-amounts-text">
                                <?php echo number_format($total_deposits); ?> / <?php echo number_format($next_target); ?> 
                                (<?php echo number_format($remaining_amount); ?> remaining)
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="notif-dropdown" id="notifDropdown">
                    <div class="notif-header">Notifications</div>
                    <?php
                    try {
                        if (isset($pdo)) {
                            $n_stmt = $pdo->query("SELECT * FROM notifications ORDER BY id DESC LIMIT 5");
                            $notifs = $n_stmt->fetchAll(PDO::FETCH_ASSOC);
                            if (empty($notifs)) {
                                echo '<div class="notif-item">No new notifications.</div>';
                            } else {
                                foreach ($notifs as $n) {
                                    echo '<div class="notif-item" style="display:flex;flex-direction:column;gap:3px;">';
                                    echo '<strong>' . htmlspecialchars($n['title']) . '</strong>';
                                    echo '<span>' . htmlspecialchars($n['message']) . '</span>';
                                    echo '<small style="font-size:10px;color:#a0938a;">' . htmlspecialchars($n['created_at']) . '</small>';
                                    echo '</div>';
                                }
                            }
                        }
                    } catch (Exception $e) {}
                    ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php 
// Show WhatsApp only if the file is index.php AND it's in the root directory
if ($current_page === 'index.php' && $is_root_dir): 
?>
<a href="https://whatsapp.com/channel/0029Vb7Phpp1NCrddQ1bQK0a" target="_blank" class="floating-whatsapp">
    <i class="fa-brands fa-whatsapp"></i>
</a>
<?php endif; ?>

<?php if($is_logged_in && !(isset($is_auth_page) && $is_auth_page)): ?>
<script>
    const balanceText = document.getElementById('headerBalanceText');
    const toggleBtn = document.getElementById('toggleBalanceBtn');
    
    if(toggleBtn && balanceText) {
        toggleBtn.addEventListener('click', () => {
            if (toggleBtn.classList.contains('fa-eye-slash')) {
                toggleBtn.classList.remove('fa-eye-slash');
                toggleBtn.classList.add('fa-eye');
                balanceText.innerText = '*****';
            } else {
                toggleBtn.classList.remove('fa-eye');
                toggleBtn.classList.add('fa-eye-slash');
                balanceText.innerText = balanceText.getAttribute('data-balance');
            }
        });
    }

    const notifBellBtn = document.getElementById('notifBellBtn');
    const notifDropdown = document.getElementById('notifDropdown');
    
    if(notifBellBtn && notifDropdown) {
        notifBellBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            notifDropdown.classList.toggle('show');
        });

        document.addEventListener('click', (e) => {
            if (!notifDropdown.contains(e.target) && !notifBellBtn.contains(e.target)) {
                notifDropdown.classList.remove('show');
            }
        });
    }
</script>
<?php endif; ?>