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

include_once __DIR__ . "/config.php";

try {
    $admins = [];

    $sql = "
        SELECT 
            a.client_index AS id,
            a.username,
            a.email,
            a.empId,
            a.status,
            a.userRole AS role_name,
            a.userAccessLevel AS access_type,
            a.role_id,
            r.description AS role_description
        FROM adminlogins a
        LEFT JOIN roles r ON a.role_id = r.id
        ORDER BY a.client_index DESC
    ";

    $result = $conn->query($sql);

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

        // Only fetch permissions if role is custom
        if ($access_type === 'custom' && $role_id) {
            $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
            ";
            $stmt = $conn->prepare($perm_sql);
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $perm_result = $stmt->get_result();

            while ($p = $perm_result->fetch_assoc()) {
                $permissions[] = $p;
            }
            $stmt->close();
        }
        // For full & read-only → just show a readable label
        elseif ($access_type === 'full') {
            $permissions = "Full Access - All Permissions";
        }
        elseif ($access_type === 'read-only') {
            $permissions = "Read-Only - Only View Permissions";
        }
        // Fallback
        else {
            $permissions = "No permissions assigned";
        }

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

        // Clean up: remove internal fields you don't need in frontend
        unset($admin['role_id']);

        $admins[] = $admin;
    }

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

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