<?php

date_default_timezone_set('Asia/Kolkata');

// 1. Fetch total count for the badge
$count_res = $conn->query("SELECT COUNT(*) as total FROM pending_approvals WHERE status = 'Awaiting'");
$total_pending = $count_res->fetch_assoc()['total'];

// 2. Fetch recent 5 for the dropdown list
$notif_res = $conn->query("SELECT pa.*, u.name 
                           FROM pending_approvals pa 
                           JOIN users u ON pa.user_id = u.id 
                           WHERE pa.status = 'Awaiting' 
                           ORDER BY pa.uploaded_at DESC LIMIT 5");

// 3. SAFE FUNCTION DECLARATION
if (!function_exists('time_ago')) {
    function time_ago($timestamp) {
        $time_ago = strtotime($timestamp);
        $current_time = time();
        $time_difference = $current_time - $time_ago;
        
        if ($time_difference <= 60) return "Just now";
        $minutes = round($time_difference / 60);
        if ($minutes <= 60) return $minutes . " mins ago";
        $hours = round($time_difference / 3600);
        if ($hours <= 24) return $hours . " hrs ago";
        return date('d M', $time_ago);
    }
}
?>

<style>
        :root {
        --sidebar-bg: #3b4368;
        --sidebar-hover: #4a537d;
        --topbar-bg: #ffffff;
        --text-color: #ffffff;
        --border-color: rgba(255, 255, 255, 0.1);
        --accent-color: #3498db;
    }

    .header-top {
        position: fixed; top: 0; left: 280px; right: 0; height: 70px;
        background: var(--topbar-bg); display: flex; justify-content: flex-end;
        align-items: center; padding: 0 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); z-index: 100;
    }

    .top-actions { 
        display: flex; 
        align-items: center; 
        gap: 25px; 
        position: relative; /* CRITICAL for dropdown positioning */
    }
    .icon-btn { background: none; border: none; cursor: pointer; position: relative; font-size: 20px; color: #666; margin-right: 20px; }

    .badge {
        position: absolute; top: -5px; right: -5px; background: #e74c3c;
        color: white; font-size: 10px; padding: 2px 5px; border-radius: 10px;
    }

    /* --- NOTIFICATION DROPDOWN --- */
    .notif-dropdown {
        position: absolute; 
        top: 60px; /* Adjusted to sit below the bell */
        right: 0; 
        width: 320px;
        background: white; 
        border-radius: 12px; 
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        display: none; /* Controlled by JS */
        flex-direction: column; 
        overflow: hidden; 
        border: 1px solid #eee;
        z-index: 9999; /* Ensure it stays on top of all content */
    }

    #notifMenu {
    display: none; position: absolute; top: 49px; right: 10px; width: 320px; background: white; 
    border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); border: 1px solid #eee; z-index: 9999; flex-direction: column; overflow: hidden;
}

    /* This class forces the display when clicked */
#notifMenu.active-notif {
    display: flex !important;
    z-index: 99999 !important;
}
    
    .notif-dropdown.show {
        display: flex !important;
        z-index: 99999 !important;
    }

    .notif-item { 
        padding: 12px 15px; 
        border-bottom: 1px solid #f1f1f1; 
        text-decoration: none; 
        display: block;
    }
    .notif-header { padding: 15px; border-bottom: 1px solid #eee; font-weight: bold; font-size: 14px; background: #f8f9fa; }
    
    .notif-item:hover { background: #f9f9fb; }
    .notif-user { font-size: 13px; font-weight: 600; color: #333; }
    .notif-meta { font-size: 11px; color: #888; margin-top: 3px; display: flex; justify-content: space-between; }
    .notif-type { color: var(--accent-color); font-weight: bold; }
    .show-all { 
        padding: 12px; text-align: center; font-size: 13px; font-weight: bold;
        color: var(--accent-color); text-decoration: none; border-top: 1px solid #eee;
    }

    .user-profile img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 2px solid #eee; }
    .user-name { font-weight: 600; font-size: 14px; color: #333; }

        /* Chevron arrow */
        .chevron { width: 8px; height: 8px; border-top: 2px solid #fff; border-right: 2px solid #fff; transform: rotate(45deg); opacity: 0.6; }

        /* Content Area Spacer */
        .main-content { margin-left: 280px; margin-top: 70px; padding: 30px; width: 100%; z-index: 1;}

    .user-profile { 
        display: flex; 
        align-items: center; 
        gap: 12px; 
        cursor: pointer; 
        position: relative; /* CRITICAL for dropdown positioning */
    }

    /* --- PROFILE DROPDOWN STYLES --- */
    .profile-dropdown {
        position: absolute;
        top: 55px;
        right: 0;
        width: 180px;
        background: #ffffff;
        border-radius: 10px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        border: 1px solid #eee;
        display: none; /* Controlled by JS */
        flex-direction: column;
        overflow: hidden;
        z-index: 10000;
    }

    .profile-dropdown.show {
        display: flex !important;
    }

    .profile-link {
        padding: 12px 20px;
        display: flex;
        align-items: center;
        gap: 10px;
        text-decoration: none;
        color: #333;
        font-size: 14px;
        transition: 0.2s;
    }

    .profile-link:hover {
        background: #f8f9fa;
        color: var(--accent);
    }

    .profile-link.logout {
        color: #e74c3c;
        border-top: 1px solid #f1f1f1;
    }

    .profile-link.logout:hover {
        background: #fff5f5;
    }

    .menu-icon { font-size: 16px; width: 20px; text-align: center; }

</style>
<header class="header-top">
<div class="top-actions" style="position: relative;">
    <button class="icon-btn" id="notifBell">
        🔔 <span class="badge" style="position:absolute; top:-5px; right:-5px; background:#e74c3c; color:white; font-size:10px; padding:2px 5px; border-radius:10px;">
            <?php echo $total_pending; ?>
        </span>
    </button>

    <div id="notifMenu" style="">
        <div style="padding:15px; border-bottom:1px solid #eee; font-weight:bold; background:#f8f9fa; color:#333;">
            Pending Approvals (<?php echo $total_pending; ?>)
        </div>
        
        <div style="max-height: 400px; overflow-y: auto;">
            <?php if($notif_res && $notif_res->num_rows > 0): ?>
                <?php while($n = $notif_res->fetch_assoc()): ?>
                    <a href="pending-approvals.php" style="padding:12px 15px; border-bottom:1px solid #f1f1f1; text-decoration:none; display:block; transition: 0.2s;">
                        <span style="font-weight:600; font-size:13px; color:#333;"><?php echo htmlspecialchars($n['name']); ?></span>
                        <div style="display:flex; justify-content:space-between; font-size:11px; color:#888; margin-top:3px;">
                            <span><b style="color:#3498db;"><?php echo strtoupper($n['upload_type']); ?></b></span>
                            <span><?php echo time_ago($n['uploaded_at']); ?></span>
                        </div>
                    </a>
                <?php endwhile; ?>
            <?php else: ?>
                <div style="padding:30px; text-align:center; color:#999; font-size:13px;">No new requests.</div>
            <?php endif; ?>
        </div>

        <a href="pending-approvals.php" style="padding:12px; text-align:center; font-weight:bold; color:#3498db; text-decoration:none; border-top:1px solid #eee; display:block; background:#fff;">
            View All Approvals
        </a>
    </div>
</div>

            <div class="user-profile" id="profileTrigger">
                <span class="user-name"><?php echo $_SESSION['team_user'] ?? 'Admin'; ?></span>
                <img src="https://ui-avatars.com/api/?name=<?php echo $_SESSION['team_user'] ?? 'Admin'; ?>&background=3b4368&color=fff" alt="Profile">
                
                <div class="profile-dropdown" id="profileMenu">
                    <a href="profile.php" class="profile-link">
                        <span class="menu-icon">👤</span> My Profile
                    </a>
                    <a href="settings.php" class="profile-link">
                        <span class="menu-icon">⚙️</span> Settings
                    </a>
                    <a href="logout.php" class="profile-link logout">
                        <span class="menu-icon">🚪</span> Logout
                    </a>
            </div>
</header>

<script>
// This script is now directly below the elements it controls
// Replace the existing script with this more robust version
(function() {
    function initNotification() {
        const bell = document.getElementById('notifBell');
        const menu = document.getElementById('notifMenu');

        if (!bell || !menu) {
            console.warn("Notification Script: Elements not found on this page.", { bell, menu });
            return;
        }

        // Use addEventListener to avoid overwriting other scripts
        bell.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            menu.classList.toggle('active-notif');
            console.log("Notification Toggle: ", menu.classList.contains('active-notif'));
        });

        document.addEventListener('click', function(e) {
            if (!menu.contains(e.target) && !bell.contains(e.target)) {
                menu.classList.remove('active-notif');
            }
        });
        
        console.log("Notification Script: Successfully initialized.");
    }

    // Run immediately if DOM is ready, otherwise wait for DOMContentLoaded
    if (document.readyState === "complete" || document.readyState === "interactive") {
        initNotification();
    } else {
        document.addEventListener('DOMContentLoaded', initNotification);
    }
})();

document.addEventListener('DOMContentLoaded', function() {
    const profileTrigger = document.getElementById('profileTrigger');
    const profileMenu = document.getElementById('profileMenu');

    if (profileTrigger && profileMenu) {
        profileTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            profileMenu.classList.toggle('show');
            
            // Close notification menu if it's open
            const notifMenu = document.getElementById('notifMenu');
            if(notifMenu) notifMenu.classList.remove('active-notif');
        });

        // Close dropdown when clicking outside
        window.addEventListener('click', function(e) {
            if (!profileTrigger.contains(e.target)) {
                profileMenu.classList.remove('show');
            }
        });
    }
});
</script>