<?php
/**
 * Access Control Helper
 * Checks user role and redirects accordingly
 */

session_start();

// Function to check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Function to check if user is admin
function isAdmin() {
    return isset($_SESSION['is_admin']) && $_SESSION['is_admin'];
}

// Function to get redirect URL based on role
function getRedirectUrl() {
    if (!isLoggedIn()) {
        return 'login.php';
    }
    
    if (isAdmin()) {
        return 'dashboard.html';
    } else {
        return 'dashboard-mobile.html';
    }
}

// Function to enforce access control
function enforceAccess($requiredRole = null) {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit();
    }
    
    if ($requiredRole === 'admin' && !isAdmin()) {
        // User trying to access admin page, redirect to mobile dashboard
        header('Location: dashboard-mobile.html');
        exit();
    }
}

// Return user info as JSON
function getUserInfo() {
    if (!isLoggedIn()) {
        return null;
    }
    
    return [
        'id' => $_SESSION['user_id'] ?? null,
        'username' => $_SESSION['username'] ?? null,
        'fullName' => $_SESSION['user_name'] ?? null,
        'role' => $_SESSION['user_role'] ?? 'user',
        'isAdmin' => $_SESSION['is_admin'] ?? false
    ];
}
?>
