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

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

$sql = "SELECT
    SUM(CASE WHEN dias_vencidos <= 0 THEN saldo ELSE 0 END) AS al_dia,
    SUM(CASE WHEN dias_vencidos BETWEEN 1 AND 30 THEN saldo ELSE 0 END) AS r1_30,
    SUM(CASE WHEN dias_vencidos BETWEEN 31 AND 60 THEN saldo ELSE 0 END) AS r31_60,
    SUM(CASE WHEN dias_vencidos BETWEEN 61 AND 90 THEN saldo ELSE 0 END) AS r61_90,
    SUM(CASE WHEN dias_vencidos > 90 THEN saldo ELSE 0 END) AS r90_mas
    FROM cartera";
$r = $conn->query($sql)->fetch_assoc();

echo json_encode([
    'labels' => ['Al día', '1-30 días', '31-60 días', '61-90 días', 'Más de 90 días'],
    'data' => [
        round((float) $r['al_dia'], 2),
        round((float) $r['r1_30'], 2),
        round((float) $r['r31_60'], 2),
        round((float) $r['r61_90'], 2),
        round((float) $r['r90_mas'], 2),
    ],
], JSON_UNESCAPED_UNICODE);
