<?php
require_once("public/connection.php");
require_once("public/functions.php");

// Ensure a role is set
if (!isset($_SESSION['role'])) {
    header("Location: ../index.php");
    exit();
}

$role_id = $_SESSION['role'];
$current_page = basename($_SERVER['REQUEST_URI']);

// Pages that don’t require permission checks
$exclude_pages = ['admin', 'dashboard', 'index', 'logout'];

// Skip permission check for excluded pages
if (!in_array($current_page, $exclude_pages)) {

    // Get role name
    $stmt_role = $connection->prepare("SELECT role_name FROM role WHERE id = ?");
    $stmt_role->bind_param("i", $role_id);
    $stmt_role->execute();
    $stmt_role->bind_result($role_name);
    $stmt_role->fetch();
    $stmt_role->close();

    // Skip permission check for Super Admin roles
    $skip_roles = ['super admin', 'admin']; // Add/remove as needed
    if (!in_array(strtolower($role_name), $skip_roles)) {
        $stmt = $connection->prepare("
            SELECT 1 FROM role_permissions 
            JOIN permissions ON role_permissions.permission_id = permissions.id 
            WHERE role_permissions.role_id = ? AND permissions.permission_name = ?
        ");
        $stmt->bind_param("is", $role_id, $current_page);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $_SESSION['msg'] = "Access denied to {$current_page} page.";
            $_SESSION['type'] = "error";
            header("Location: dashboard");
            exit();
        }

        $stmt->close();
    }
}
?>

