<?php
$sessionId = $_SESSION["user_id"];
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE user_id = $sessionId"));

// Get unread support messages count
$unread_query = "SELECT COUNT(DISTINCT m.id) as total 
                 FROM support_messages m 
                 JOIN support_tickets t ON m.ticket_id = t.id 
                 WHERE t.user_id = '$sessionId' 
                 AND m.sender_type = 'admin' 
                 AND m.is_read = 0";
$unread_result = mysqli_query($conn, $unread_query);
$unread_data = mysqli_fetch_assoc($unread_result);
$unread_count = $unread_data['total'] ?? 0;

// Get recent unread messages for dropdown
$recent_messages_query = "SELECT m.*, t.ticket_id, t.subject 
                          FROM support_messages m 
                          JOIN support_tickets t ON m.ticket_id = t.id 
                          WHERE t.user_id = '$sessionId' 
                          AND m.sender_type = 'admin' 
                          AND m.is_read = 0 
                          ORDER BY m.created_at DESC 
                          LIMIT 5";
$recent_messages = mysqli_query($conn, $recent_messages_query);
?>

<style>
.logo img {
    max-height: 43px;
}

/* Support Notification Styles */
.support-icon {
    position: relative;
    padding: 8px 12px;
    font-size: 1.2rem;
    color: #6c757d;
    transition: color 0.3s;
    display: flex;
    align-items: center;
}

.support-icon:hover {
    color: #4154f1;
}

.support-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 20px;
    padding: 3px 8px;
    font-size: 0.65rem;
    font-weight: 600;
    min-width: 20px;
    text-align: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    animation: pulse 2s infinite;
}

.support-dropdown {
    width: 320px;
    max-height: 400px;
    overflow-y: auto;
    padding: 0;
    border: none;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.support-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 15px 20px;
    border-radius: 15px 15px 0 0;
    font-weight: 600;
}

.support-header a {
    color: white;
    text-decoration: none;
    font-size: 0.85rem;
    opacity: 0.9;
}

.support-header a:hover {
    opacity: 1;
    text-decoration: underline;
}

.support-item {
    padding: 12px 15px;
    border-bottom: 1px solid #e9ecef;
    transition: background-color 0.2s;
}

.support-item:hover {
    background-color: #f8f9fa;
}

.support-item a {
    text-decoration: none;
    color: inherit;
    display: flex;
    gap: 12px;
}

.support-item-icon {
    width: 35px;
    height: 35px;
    border-radius: 10px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
}

.support-item-content {
    flex: 1;
}

.support-item-title {
    font-weight: 600;
    font-size: 0.9rem;
    margin-bottom: 3px;
    color: #333;
}

.support-item-preview {
    font-size: 0.8rem;
    color: #6c757d;
    margin-bottom: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
}

.support-item-time {
    font-size: 0.7rem;
    color: #adb5bd;
}

.support-footer {
    padding: 12px;
    text-align: center;
    background: #f8f9fa;
    border-radius: 0 0 15px 15px;
}

.support-footer a {
    color: #667eea;
    text-decoration: none;
    font-size: 0.9rem;
    font-weight: 500;
}

.support-footer a:hover {
    text-decoration: underline;
}

.empty-state {
    padding: 30px;
    text-align: center;
    color: #6c757d;
}

.empty-state i {
    font-size: 2.5rem;
    margin-bottom: 10px;
    opacity: 0.5;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

/* Notification sound indicator */
.sound-toggle {
    cursor: pointer;
    margin-right: 5px;
    font-size: 0.9rem;
    color: #6c757d;
}

.sound-toggle:hover {
    color: #4154f1;
}
</style>

<header id="header" class="header fixed-top d-flex align-items-center">
    <div class="d-flex align-items-center justify-content-between">
        <a href="dashboard.php" class="logo d-flex align-items-center">
            <img src="../img/logo/logo_panel.png" style="width: auto; height: 100%;" alt="">
        </a>
        <i class="bi bi-list toggle-sidebar-btn"></i>
    </div><!-- End Logo -->

    <div class="search-bar">
        <form class="search-form d-flex align-items-center" method="POST" action="#">
            <input type="text" name="query" placeholder="Search" title="Enter search keyword">
            <button type="submit" title="Search"><i class="bi bi-search"></i></button>
        </form>
    </div><!-- End Search Bar -->

    <nav class="header-nav ms-auto">
        <ul class="d-flex align-items-center">
            
            <!-- SUPPORT ICON WITH NOTIFICATION - ADDED HERE -->
            <li class="nav-item dropdown">
                <a class="nav-link support-icon" href="#" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-headset"></i>
                    <?php if ($unread_count > 0): ?>
                        <span class="support-badge" id="supportBadge"><?php echo $unread_count; ?></span>
                    <?php else: ?>
                        <span class="support-badge" id="supportBadge" style="display: none;">0</span>
                    <?php endif; ?>
                </a>
                
                <ul class="dropdown-menu dropdown-menu-end support-dropdown">
                    <li>
                        <div class="support-header d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-headset me-2"></i>Support Messages</span>
                            <?php if ($unread_count > 0): ?>
                                <a href="help.php">View All</a>
                            <?php endif; ?>
                        </div>
                    </li>
                    
                    <?php if (mysqli_num_rows($recent_messages) > 0): ?>
                        <?php while ($message = mysqli_fetch_assoc($recent_messages)): ?>
                            <li class="support-item">
                                <a href="help.php?ticket=<?php echo $message['ticket_id']; ?>" onclick="markTicketRead(<?php echo $message['ticket_id']; ?>)">
                                    <div class="support-item-icon">
                                        <i class="bi bi-chat-dots"></i>
                                    </div>
                                    <div class="support-item-content">
                                        <div class="support-item-title">
                                            Ticket #<?php echo $message['ticket_id']; ?>
                                        </div>
                                        <div class="support-item-preview">
                                            <?php echo htmlspecialchars(substr($message['message'], 0, 50)) . (strlen($message['message']) > 50 ? '...' : ''); ?>
                                        </div>
                                        <div class="support-item-time">
                                            <i class="bi bi-clock me-1"></i><?php echo date('h:i A', strtotime($message['created_at'])); ?>
                                        </div>
                                    </div>
                                </a>
                            </li>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <li class="empty-state">
                            <i class="bi bi-check-circle"></i>
                            <p class="mb-0">No new messages</p>
                            <small>All caught up!</small>
                        </li>
                    <?php endif; ?>
                    
                    <li class="support-footer">
                        <a href="help.php">
                            <i class="bi bi-headset me-1"></i>
                            Go to Support Center
                        </a>
                    </li>
                </ul>
            </li>

            <li class="nav-item d-block d-lg-none">
                <a class="nav-link nav-icon search-bar-toggle" href="#">
                    <i class="bi bi-search"></i>
                </a>
            </li><!-- End Search Icon-->

            <?php
            $details = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$my_id'"));
            ?>
            
            <li class="nav-item dropdown pe-3">
                <a class="nav-link nav-profile d-flex align-items-center pe-0" href="#" data-bs-toggle="dropdown">
                    <img src="profile-img/<?php echo $details['image']; ?>" alt="Profile" class="rounded-circle">
                    <span class="d-none d-md-block dropdown-toggle ps-2"><?php echo $details['name'] ?></span>
                </a><!-- End Profile Image Icon -->

                <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile">
                    <li class="dropdown-header">
                        <h6><?php echo $details['name'] ?></h6>
                        <span><?php echo $my_id ?></span>
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>

                    <li>
                        <a class="dropdown-item d-flex align-items-center" href="profile.php">
                            <i class="bi bi-person"></i>
                            <span>My Profile</span>
                        </a>
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>

                    <!-- SUPPORT LINK IN PROFILE DROPDOWN - ADDED HERE -->
                    <li>
                        <a class="dropdown-item d-flex align-items-center" href="help.php">
                            <i class="bi bi-headset"></i>
                            <span>Help & Support</span>
                            <?php if ($unread_count > 0): ?>
                                <span class="badge bg-primary rounded-pill ms-auto" id="profileSupportBadge"><?php echo $unread_count; ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>

                    <li>
                        <a class="dropdown-item d-flex align-items-center" href="logout.php">
                            <i class="bi bi-box-arrow-right"></i>
                            <span>Sign Out</span>
                        </a>
                    </li>
                </ul><!-- End Profile Dropdown Items -->
            </li><!-- End Profile Nav -->

        </ul>
    </nav><!-- End Icons Navigation -->
</header>

<!-- JavaScript for real-time updates -->
<script>
// Configuration
let soundEnabled = true;
let lastUnreadCount = <?php echo $unread_count; ?>;

// Toggle sound
function toggleSound() {
    soundEnabled = !soundEnabled;
    localStorage.setItem('supportSound', soundEnabled);
    const icon = document.getElementById('soundToggleIcon');
    if (icon) {
        icon.className = soundEnabled ? 'bi bi-volume-up' : 'bi bi-volume-mute';
    }
}

// Load sound preference
document.addEventListener('DOMContentLoaded', function() {
    const saved = localStorage.getItem('supportSound');
    if (saved !== null) {
        soundEnabled = saved === 'true';
    }
});

// Update support notifications in real-time
function updateSupportNotifications() {
    const userId = <?php echo $sessionId; ?>;
    
    fetch(`ajax/user_support_notifications.php?user_id=${userId}&t=<?php echo time(); ?>`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const badge = document.getElementById('supportBadge');
                const profileBadge = document.getElementById('profileSupportBadge');
                
                // Update header badge
                if (badge) {
                    if (data.unread_count > 0) {
                        badge.textContent = data.unread_count;
                        badge.style.display = 'inline';
                    } else {
                        badge.style.display = 'none';
                    }
                }
                
                // Update profile dropdown badge
                if (profileBadge) {
                    if (data.unread_count > 0) {
                        profileBadge.textContent = data.unread_count;
                        profileBadge.style.display = 'inline';
                    } else {
                        profileBadge.style.display = 'none';
                    }
                }
                
                // Play sound if new message arrived and page is not focused
                if (data.unread_count > lastUnreadCount && !document.hasFocus() && soundEnabled) {
                    playNotificationSound();
                    
                    // Show browser notification if permitted
                    if (Notification.permission === 'granted') {
                        new Notification('New Support Message', {
                            body: 'You have a new message from support team',
                            icon: '../img/logo/logo_panel.png'
                        });
                    } else if (Notification.permission !== 'denied') {
                        Notification.requestPermission();
                    }
                }
                
                lastUnreadCount = data.unread_count;
            }
        })
        .catch(error => console.error('Error updating notifications:', error));
}

// Play notification sound
function playNotificationSound() {
    const audio = new Audio('assets/sounds/notification.mp3');
    audio.volume = 0.5;
    audio.play().catch(e => console.log('Audio play failed:', e));
}

// Mark ticket as read when clicked
function markTicketRead(ticketId) {
    const userId = <?php echo $sessionId; ?>;
    
    fetch('ajax/mark_messages_read.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `ticket_id=${ticketId}&user_id=${userId}`
    }).catch(e => console.log('Error marking read:', e));
}

// Update every 10 seconds
setInterval(updateSupportNotifications, 10000);

// Update when page becomes visible
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        updateSupportNotifications();
    }
});

// Request notification permission
if (Notification.permission === 'default') {
    Notification.requestPermission();
}

// Mark messages as read when viewing help page with ticket
if (window.location.pathname.includes('help.php') && window.location.search.includes('ticket=')) {
    const urlParams = new URLSearchParams(window.location.search);
    const ticketId = urlParams.get('ticket');
    if (ticketId) {
        setTimeout(() => {
            markTicketRead(ticketId);
            updateSupportNotifications();
        }, 2000);
    }
}
</script>