<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/helpers.php';

$pdo = getConnection();

$sucursal_id = intval($_GET['sucursal_id'] ?? 0);
$where_suc = $sucursal_id ? "AND c.sucursal_id=$sucursal_id" : '';

try {
    $where = []; $params = [];

    if (!empty($_GET['fecha_desde'])) { $where[] = "DATE(c.fecha_compra) >= ?"; $params[] = $_GET['fecha_desde']; }
    if (!empty($_GET['fecha_hasta'])) { $where[] = "DATE(c.fecha_compra) <= ?"; $params[] = $_GET['fecha_hasta']; }
    if (!empty($_GET['proveedor_id'])) { $where[] = "c.id_lugarCompra = ?"; $params[] = (int)$_GET['proveedor_id']; }
    $wc = count($where) ? 'AND ' . implode(' AND ', $where) : '';

    // Monthly aggregation
    $sql = "SELECT DATE_FORMAT(c.fecha_compra,'%Y-%m') as mes, COUNT(*) as transacciones, COALESCE(SUM(c.total),0) as total
            FROM compras c WHERE 1=1 $wc $where_suc GROUP BY DATE_FORMAT(c.fecha_compra,'%Y-%m') ORDER BY mes DESC";
    $st = $pdo->prepare($sql); $st->execute($params);
    $mensual = $st->fetchAll(PDO::FETCH_ASSOC);

    // By supplier
    $sql2 = "SELECT l.nombre as proveedor, COUNT(*) as transacciones, COALESCE(SUM(c.total),0) as total
             FROM compras c JOIN lugarcompra l ON l.id=c.id_lugarCompra WHERE 1=1 $wc $where_suc
             GROUP BY c.id_lugarCompra ORDER BY total DESC";
    $st2 = $pdo->prepare($sql2); $st2->execute($params);
    $porProveedor = $st2->fetchAll(PDO::FETCH_ASSOC);

    // By payment type
    $sql3 = "SELECT c.tipo_pago, COUNT(*) as transacciones, COALESCE(SUM(c.total),0) as total
             FROM compras c WHERE 1=1 $wc $where_suc GROUP BY c.tipo_pago ORDER BY total DESC";
    $st3 = $pdo->prepare($sql3); $st3->execute($params);
    $porPago = $st3->fetchAll(PDO::FETCH_ASSOC);

    // Totals
    $sql4 = "SELECT COALESCE(SUM(c.total),0) as gran_total, COUNT(*) as gran_transacciones FROM compras c WHERE 1=1 $wc $where_suc";
    $st4 = $pdo->prepare($sql4); $st4->execute($params);
    $totales = $st4->fetch(PDO::FETCH_ASSOC);

    json_success([
        'mensual' => $mensual,
        'por_proveedor' => $porProveedor,
        'por_pago' => $porPago,
        'totales' => ['total' => (float)$totales['gran_total'], 'transacciones' => (int)$totales['gran_transacciones']]
    ]);
} catch (Exception $e) {
    json_error("Error: " . $e->getMessage());
}
