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

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

$carteraTotal = $conn->query('SELECT COALESCE(SUM(saldo),0) AS n FROM cartera')->fetch_assoc()['n'];
$carteraVencida = $conn->query('SELECT COALESCE(SUM(saldo),0) AS n FROM cartera WHERE dias_vencidos > 0')->fetch_assoc()['n'];
$facturasPendientes = $conn->query('SELECT COUNT(*) AS n FROM cartera WHERE saldo > 0')->fetch_assoc()['n'];

$ventasMes = $conn->query(
    "SELECT COALESCE(SUM(valor_neto + valor_iva),0) AS n FROM ventas_detalle
     WHERE YEAR(fecha) = YEAR(CURDATE()) AND MONTH(fecha) = MONTH(CURDATE())"
)->fetch_assoc()['n'];

$recaudoMes = $conn->query(
    "SELECT COALESCE(SUM(valor_recaudo),0) AS n FROM recaudos
     WHERE YEAR(fecha_recaudo) = YEAR(CURDATE()) AND MONTH(fecha_recaudo) = MONTH(CURDATE())"
)->fetch_assoc()['n'];

$totalClientes = $conn->query('SELECT COUNT(*) AS n FROM clientes')->fetch_assoc()['n'];
$totalProductos = $conn->query('SELECT COUNT(*) AS n FROM productos')->fetch_assoc()['n'];

echo json_encode([
    'cartera_total' => (float) $carteraTotal,
    'cartera_vencida' => (float) $carteraVencida,
    'facturas_pendientes' => (int) $facturasPendientes,
    'ventas_mes' => (float) $ventasMes,
    'recaudo_mes' => (float) $recaudoMes,
    'total_clientes' => (int) $totalClientes,
    'total_productos' => (int) $totalProductos,
], JSON_UNESCAPED_UNICODE);
