<?php
/**
 * Get unread notification count for a user
 */
function getUnreadNotificationCount($db, $user_type, $user_id) {
    try {
        $stmt = $db->prepare("
            SELECT COUNT(*) as count 
            FROM notifications 
            WHERE user_type = ? AND user_id = ? AND is_read = FALSE
        ");
        $stmt->execute([$user_type, $user_id]);
        $result = $stmt->fetch();
        return (int)$result['count'];
    } catch (PDOException $e) {
        return 0;
    }
}

/**
 * Get recent notifications for a user
 */
function getRecentNotifications($db, $user_type, $user_id, $limit = 5) {
    try {
        $stmt = $db->prepare("
            SELECT * FROM notifications 
            WHERE user_type = ? AND user_id = ?
            ORDER BY created_at DESC 
            LIMIT ?
        ");
        $stmt->execute([$user_type, $user_id, $limit]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Render notification dropdown for navbar
 */
function renderNotificationDropdown($db, $user_type, $user_id) {
    $unread_count = getUnreadNotificationCount($db, $user_type, $user_id);
    $recent_notifications = getRecentNotifications($db, $user_type, $user_id, 5);
    
    ob_start();
    ?>
    <div class="dropdown">
        <a class="nav-link dropdown-toggle position-relative" href="#" id="notificationDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="fas fa-bell"></i>
            <?php if ($unread_count > 0): ?>
                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.6rem;">
                    <?php echo $unread_count > 9 ? '9+' : $unread_count; ?>
                </span>
            <?php endif; ?>
        </a>
        
        <div class="dropdown-menu dropdown-menu-end notification-dropdown" aria-labelledby="notificationDropdown" style="width: 350px; max-height: 400px; overflow-y: auto;">
            <div class="dropdown-header d-flex justify-content-between align-items-center">
                <strong>Notifications</strong>
                <?php if ($unread_count > 0): ?>
                    <span class="badge bg-primary"><?php echo $unread_count; ?> unread</span>
                <?php endif; ?>
            </div>
            
            <?php if (empty($recent_notifications)): ?>
                <div class="dropdown-item-text text-center py-3 text-muted">
                    <i class="fas fa-bell-slash fa-2x mb-2 d-block"></i>
                    No notifications yet
                </div>
            <?php else: ?>
                <?php foreach ($recent_notifications as $notification): ?>
                    <a href="notifications.php" class="dropdown-item <?php echo !$notification['is_read'] ? 'notification-unread' : ''; ?>">
                        <div class="d-flex">
                            <div class="me-2">
                                <i class="fas fa-<?php echo getNotificationIcon($notification['type']); ?> text-<?php echo $notification['type'] === 'success' ? 'success' : ($notification['type'] === 'warning' ? 'warning' : 'primary'); ?>"></i>
                            </div>
                            <div class="flex-grow-1">
                                <div class="fw-bold small"><?php echo htmlspecialchars(substr($notification['title'], 0, 40)) . (strlen($notification['title']) > 40 ? '...' : ''); ?></div>
                                <div class="text-muted small"><?php echo htmlspecialchars(substr($notification['message'], 0, 60)) . (strlen($notification['message']) > 60 ? '...' : ''); ?></div>
                                <div class="text-muted" style="font-size: 0.7rem;"><?php echo timeAgo($notification['created_at']); ?></div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php endif; ?>
            
            <div class="dropdown-divider"></div>
            <a href="notifications.php" class="dropdown-item text-center">
                <i class="fas fa-bell me-1"></i>View All Notifications
            </a>
        </div>
    </div>
    
    <style>
        .notification-dropdown {
            border: none;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        }
        .notification-unread {
            background-color: #f8f9fa;
            border-left: 3px solid #0d6efd;
        }
        .notification-dropdown .dropdown-item {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #f8f9fa;
        }
        .notification-dropdown .dropdown-item:hover {
            background-color: #f1f3f4;
        }
    </style>
    <?php
    return ob_get_clean();
}

function getNotificationIcon($type) {
    switch ($type) {
        case 'success': return 'check-circle';
        case 'warning': return 'exclamation-triangle';
        case 'error': return 'times-circle';
        default: return 'info-circle';
    }
}

function timeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return 'Just now';
    } elseif ($diff < 3600) {
        $minutes = floor($diff / 60);
        return $minutes . ' min ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . ' hr ago';
    } else {
        return date('M j', $time);
    }
}
?>