<?php
session_start();

// Configuration for session timeout (in seconds)
define('SESSION_TIMEOUT', 1800); // 30 minutes

// Check if the user is logged in
if (!isset($_SESSION['userId'])) {
    redirectToLogin("You must be logged in to access this page.");
}

// Session Timeout Check
if (isset($_SESSION['lastActivity']) && (time() - $_SESSION['lastActivity']) > SESSION_TIMEOUT) {
    // Session expired
    session_unset();
    session_destroy();
    redirectToLogin("Session expired. Please log in again.");
} else {
    $_SESSION['lastActivity'] = time(); // Update activity timestamp
}

// Function to check user roles
function checkUserRole($allowedRoles = []) {
    if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], $allowedRoles)) {
        $_SESSION['errorMessage'] = "Access denied: You do not have the required permissions.";
        header("Location: dashboard.php");  // Redirect to dashboard or another page
        exit();
    }
}

// Function to redirect to login with optional message
function redirectToLogin($message = '') {
    if (!empty($message)) {
        $_SESSION['errorMessage'] = $message;
    }
    header("Location: login.php");
    exit();
}
?>
