<?php
// notifications.php
// Displays all notifications for the logged-in student, separating Unread and Read lists.

// Ensure the user is logged in and is a student
if (!isset($_SESSION['loggedin']) || $_SESSION['user_role'] !== 'student') {
    header("Location: index.php?page=login");
    exit();
}

// *** CRITICAL: Include the database configuration file ***
require_once 'config/database.php';

$student_id = $_SESSION['user_id'];
$unread_notifications = [];
$read_notifications = [];
$message = '';

// Check for and display flash messages from mark_as_read.php
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}
if (isset($_SESSION['flash_error'])) {
    $message = "<span class='font-bold text-red-700'>Error:</span> " . $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

// --- FUNCTION DEFINITIONS (Moved to Top for Execution) ---

// Helper function to calculate time difference in human-readable format (e.g., "3 days")
if (!function_exists('human_time_diff')) {
    function human_time_diff($from, $to = '') {
        if (empty($to)) $to = time();
        $diff = abs($to - $from);
        
        $intervals = [
            'year'    => 31570560, 'month' => 2630880, 'week' => 604800,
            'day'     => 86400,    'hour'  => 3600,     'minute' => 60,
            'second'  => 1
        ];

        foreach ($intervals as $label => $seconds) {
            $value = floor($diff / $seconds);
            if ($value >= 1) {
                return $value . ' ' . $label . ($value > 1 ? 's' : '');
            }
        }
        return 'just now';
    }
}

// Helper function to determine card color based on notification type
function get_notification_style($type, $is_read) {
    $base_color = 'bg-gray-50';
    $border_color = 'border-gray-200';
    
    if (!$is_read) {
        // UNREAD Styling - Use white background and strong border
        $base_color = 'bg-white'; 
        switch ($type) {
            case 'payment':
                $border_color = 'border-yellow-500'; 
                break;
            case 'access':
                $border_color = 'border-green-500'; 
                break;
            case 'schedule':
                $border_color = 'border-blue-500'; 
                break;
            case 'enrollment':
                $border_color = 'border-purple-500'; 
                break;
            default:
                $border_color = 'border-gray-500';
        }
    } else {
        // READ Styling - Use light gray background and border
        $base_color = 'bg-gray-50';
        $border_color = 'border-gray-300';
    }
    
    return "{$base_color} {$border_color} shadow";
}

// --- DATABASE LOGIC ---
try {
    // 1. Fetch ALL UNREAD notifications (Status: is_read = 0)
    $sql_unread = "
        SELECT 
            id, type, title, message, is_read, created_at 
        FROM 
            notifications 
        WHERE 
            user_id = :user_id AND is_read = 0
        ORDER BY 
            created_at DESC";
    
    // Execute the unread fetch query
    $stmt_unread = $pdo->prepare($sql_unread);
    $stmt_unread->execute([':user_id' => $student_id]);
    $unread_notifications = $stmt_unread->fetchAll(PDO::FETCH_ASSOC);

    // 2. Fetch LIMITED READ notifications (Status: is_read = 1, Limited to 20)
    $sql_read = "
        SELECT 
            id, type, title, message, is_read, created_at 
        FROM 
            notifications 
        WHERE 
            user_id = :user_id AND is_read = 1
        ORDER BY 
            created_at DESC 
        LIMIT 20";

    // Execute the read fetch query
    $stmt_read = $pdo->prepare($sql_read);
    $stmt_read->execute([':user_id' => $student_id]);
    $read_notifications = $stmt_read->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $message = "Error retrieving notifications: " . $e->getMessage();
}
?>

<div class="w-full max-w-4xl mx-auto">
    <h1 class="text-3xl font-extrabold text-gray-800 mb-6 border-b-2 border-blue-500 pb-2">
        <i class="fas fa-bell mr-2 text-blue-500"></i> My Notifications
    </h1>

    <?php if ($message): ?>
        <div class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded relative mb-4" role="alert">
            <strong class="font-bold">Info:</strong>
            <span class="block sm:inline"><?php echo htmlspecialchars($message); ?></span>
        </div>
    <?php endif; ?>

    <div class="flex justify-between items-center mb-4 mt-8">
        <h2 class="text-2xl font-bold text-red-600">
            New Notifications (<?php echo count($unread_notifications); ?>)
        </h2>
        <?php if (!empty($unread_notifications)): ?>
            <a href="index.php?page=mark_as_read" class="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium py-1.5 px-3 rounded-md transition duration-300">
                Mark All as Read <i class="fas fa-check-double ml-1"></i>
            </a>
        <?php endif; ?>
    </div>
    
    <div class="space-y-4">
        <?php if (empty($unread_notifications)): ?>
            <div class="text-center py-6 bg-white rounded-lg shadow-md border-2 border-green-500">
                <i class="fas fa-check-circle text-3xl text-green-500 mb-2"></i>
                <p class="text-gray-600 text-lg font-semibold">You're all caught up! No new notifications.</p>
            </div>
        <?php else: ?>
            <?php foreach ($unread_notifications as $notification): ?>
                <?php 
                $card_style = get_notification_style($notification['type'], 0); // is_read is 0
                $read_text = 'text-blue-700 font-semibold';
                ?>
                <div class="p-4 rounded-xl border-l-4 transition duration-300 ease-in-out hover:shadow-xl <?php echo $card_style; ?>">
                    <div class="flex justify-between items-start">
                        <div>
                            <span class="text-xs uppercase font-medium px-2 py-0.5 rounded-full mr-2 bg-red-500 text-white">
                                NEW
                            </span>
                            <h3 class="inline text-lg <?php echo $read_text; ?>">
                                <?php echo htmlspecialchars($notification['title']); ?>
                            </h3>
                        </div>
                        
                        <div class="flex items-center space-x-3">
                            <a href="index.php?page=mark_as_read&notification_id=<?php echo $notification['id']; ?>" class="text-xs text-gray-500 hover:text-blue-600 transition duration-150" title="Mark this as read">
                                Mark Read
                            </a>
                            <span class="text-xs text-gray-400 mt-1 whitespace-nowrap" title="<?php echo htmlspecialchars($notification['created_at']); ?>">
                                <?php 
                                $time_ago = strtotime($notification['created_at']);
                                echo human_time_diff($time_ago, time()) . ' ago';
                                ?>
                            </span>
                        </div>
                    </div>
                    <p class="mt-2 text-sm text-gray-700">
                        <?php echo nl2br(htmlspecialchars($notification['message'])); ?>
                    </p>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <h2 class="text-2xl font-bold text-gray-600 mb-4 mt-12 border-t pt-4">
        Recent History (Last 20 Read)
    </h2>
    <div class="space-y-3">
        <?php if (empty($read_notifications)): ?>
            <div class="text-center py-6 bg-white rounded-lg shadow-md border-2 border-gray-300">
                <p class="text-gray-600 text-lg font-semibold">No recent read history available.</p>
            </div>
        <?php else: ?>
            <?php foreach ($read_notifications as $notification): ?>
                <?php 
                $card_style = get_notification_style($notification['type'], 1); // is_read is 1
                $read_text = 'text-gray-600';
                ?>
                <div class="p-4 rounded-xl border-l-4 opacity-80 <?php echo $card_style; ?>">
                    <div class="flex justify-between items-start">
                        <div>
                            <h3 class="inline text-lg font-medium <?php echo $read_text; ?>">
                                <?php echo htmlspecialchars($notification['title']); ?>
                            </h3>
                        </div>
                        
                        <span class="text-xs text-gray-400 mt-1 whitespace-nowrap" title="<?php echo htmlspecialchars($notification['created_at']); ?>">
                            <?php 
                            $time_ago = strtotime($notification['created_at']);
                            echo human_time_diff($time_ago, time()) . ' ago';
                            ?>
                        </span>
                    </div>

                    <p class="mt-2 text-sm text-gray-500">
                        <?php echo nl2br(htmlspecialchars($notification['message'])); ?>
                    </p>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>