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

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

$ventas = [];
$res = $conn->query(
    "SELECT DATE_FORMAT(fecha, '%Y-%m') AS periodo, SUM(valor_neto + valor_iva) AS total
     FROM ventas_detalle
     WHERE fecha >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
     GROUP BY periodo ORDER BY periodo"
);
while ($row = $res->fetch_assoc()) {
    $ventas[$row['periodo']] = (float) $row['total'];
}

$recaudos = [];
$res = $conn->query(
    "SELECT DATE_FORMAT(fecha_recaudo, '%Y-%m') AS periodo, SUM(valor_recaudo) AS total
     FROM recaudos
     WHERE fecha_recaudo >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
     GROUP BY periodo ORDER BY periodo"
);
while ($row = $res->fetch_assoc()) {
    $recaudos[$row['periodo']] = (float) $row['total'];
}

$periodos = array_unique(array_merge(array_keys($ventas), array_keys($recaudos)));
sort($periodos);

$dataVentas = [];
$dataRecaudos = [];
foreach ($periodos as $p) {
    $dataVentas[] = round($ventas[$p] ?? 0, 2);
    $dataRecaudos[] = round($recaudos[$p] ?? 0, 2);
}

echo json_encode([
    'labels' => $periodos,
    'ventas' => $dataVentas,
    'recaudos' => $dataRecaudos,
], JSON_UNESCAPED_UNICODE);
