<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/db.php';

header('Content-Type: application/json; charset=utf-8');
$conn = db();

$sql = "SELECT c.nombre, SUM(car.saldo) AS saldo
        FROM cartera car
        JOIN clientes c ON c.codigo_cliente = car.codigo_cliente
        GROUP BY car.codigo_cliente, c.nombre
        ORDER BY saldo DESC
        LIMIT 10";
$res = $conn->query($sql);

$labels = [];
$data = [];
while ($row = $res->fetch_assoc()) {
    $labels[] = $row['nombre'];
    $data[] = round((float) $row['saldo'], 2);
}

echo json_encode(['labels' => $labels, 'data' => $data], JSON_UNESCAPED_UNICODE);
