<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
include_once __DIR__ . "/config.php";

try {
    $roles = [];
    
    // 1. Get all roles
    $sql = "SELECT id, name, description, access_type, created_at 
            FROM roles 
            ORDER BY id DESC";
    $result = $conn->query($sql);

    while ($role = $result->fetch_assoc()) {
        $role_id = $role['id'];
        $permissions = [];

        // 2. If role is custom → fetch actual assigned permissions
        if ($role['access_type'] === 'custom') {
            $perm_sql = "SELECT p.id, p.name, p.module, p.description 
                         FROM permissions p
                         JOIN role_permissions rp ON p.id = rp.permission_id
                         WHERE rp.role_id = ?
                         ORDER BY p.module, p.name";
            $perm_stmt = $conn->prepare($perm_sql);
            $perm_stmt->bind_param("i", $role_id);
            $perm_stmt->execute();
            $perm_result = $perm_stmt->get_result();

            while ($perm = $perm_result->fetch_assoc()) {
                $permissions[] = $perm;
            }
            $perm_stmt->close();
        }
        // For "full" and "read-only", we just send a label (or you can list them too if you want)
        elseif ($role['access_type'] === 'full') {
            $permissions = "All permissions granted (full access)";
        }
        elseif ($role['access_type'] === 'read-only') {
            $permissions = "Only view permissions (read-only)";
        }

        // Attach permissions to role
        $role['permissions'] = $permissions;

        $roles[] = $role;
    }

    echo json_encode([
        "success" => true,
        "count"   => count($roles),
        "data"    => $roles
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Server error",
        "error"   => $e->getMessage()
    ]);
}
?>