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

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

// Get all roles
$rolesQuery = "SELECT r.ID, r.RoleName, r.RoleCode, r.Status,
               COUNT(DISTINCT rp.PermissionID) as permission_count,
               COUNT(DISTINCT u.ID) as user_count
               FROM tblroles r
               LEFT JOIN tblrolepermissions rp ON r.ID = rp.RoleID
               LEFT JOIN tblusers u ON r.ID = u.RoleID
               WHERE r.Status = 'Active'
               GROUP BY r.ID
               ORDER BY r.RoleName";

$rolesResult = mysqli_query($con, $rolesQuery);

$roles = [];
if ($rolesResult) {
    while ($role = mysqli_fetch_assoc($rolesResult)) {
        $roles[] = $role;
    }
}

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