<?php
session_start();
define('SUPPRESS_ERRORS', true);
include_once('../includes/config.php');

header('Content-Type: application/json');

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$userId = $_SESSION['uid'];

// Get user's role
$userQuery = "SELECT RoleID FROM tblusers WHERE ID = $userId";
$userResult = mysqli_query($con, $userQuery);

if (!$userResult || mysqli_num_rows($userResult) == 0) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit();
}

$user = mysqli_fetch_assoc($userResult);
$roleId = $user['RoleID'];

if (!$roleId) {
    // No role assigned, check if admin
    echo json_encode([
        'success' => true,
        'permissions' => [],
        'hasRole' => false
    ]);
    exit();
}

// Get user's permissions through their role
$permissionsQuery = "SELECT p.PermissionCode, p.PermissionName
                     FROM tblpermissions p
                     INNER JOIN tblrolepermissions rp ON p.ID = rp.PermissionID
                     WHERE rp.RoleID = $roleId";

$permissionsResult = mysqli_query($con, $permissionsQuery);

$permissions = [];
if ($permissionsResult) {
    while ($row = mysqli_fetch_assoc($permissionsResult)) {
        $permissions[] = $row['PermissionCode'];
    }
}

echo json_encode([
    'success' => true,
    'permissions' => $permissions,
    'hasRole' => true,
    'roleId' => $roleId
]);
?>
