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

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

$desde = $_GET['desde'] ?? date('Y-m-01');
$hasta = $_GET['hasta'] ?? date('Y-m-d');

$stmt = $conn->prepare(
    "SELECT COALESCE(p.categoria, 'Sin categoría') AS categoria, SUM(vd.valor_neto + vd.valor_iva) AS total
     FROM ventas_detalle vd
     LEFT JOIN productos p ON p.codigo = vd.codigo_producto
     WHERE vd.fecha BETWEEN ? AND ?
     GROUP BY categoria
     ORDER BY total DESC
     LIMIT 12"
);
$stmt->bind_param('ss', $desde, $hasta);
$stmt->execute();
$res = $stmt->get_result();

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

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