<?php
// mark_as_read.php
// Handles the database update to change notification status from 0 (unread) to 1 (read).

// Ensure session is started and user is authenticated
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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'];
$notification_id = $_GET['notification_id'] ?? null; // Can be null if marking ALL

try {
    // The $pdo object is now available from the included database.php file.
    
    if ($notification_id) {
        // --- 1. Mark a single specific notification as read ---
        // Prevents users from marking another user's notification as read
        $sql = "UPDATE notifications SET is_read = 1 WHERE id = :id AND user_id = :user_id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':id' => $notification_id, ':user_id' => $student_id]);
        
        // Add a success message to the session here
        $_SESSION['flash_message'] = "Notification ID #{$notification_id} marked as read.";

    } else {
        // --- 2. Mark ALL unread notifications for the user as read ---
        $sql = "UPDATE notifications SET is_read = 1 WHERE user_id = :user_id AND is_read = 0";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':user_id' => $student_id]);

        // Add a success message to the session here
        $_SESSION['flash_message'] = "All unread notifications marked as read.";
    }

} catch (PDOException $e) {
    // Catch PDO-specific exceptions for better error handling
    // Log the error and store an error message
    error_log("Database Error: " . $e->getMessage());
    $_SESSION['flash_error'] = "Error marking notifications as read. Please try again.";
}

// Redirect back to the notifications page to see the updated lists
header("Location: index.php?page=notifications");
exit();
?>