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

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid role ID']);
    exit();
}

$roleId = (int)$_GET['id'];

// Get role details
$roleQuery = "SELECT * FROM tblroles WHERE ID = $roleId";
$roleResult = mysqli_query($con, $roleQuery);

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

$role = mysqli_fetch_assoc($roleResult);

// Get assigned permissions for this role
$permissionsQuery = "SELECT PermissionID FROM tblrolepermissions WHERE RoleID = $roleId";
$permissionsResult = mysqli_query($con, $permissionsQuery);

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

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