<?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 g.sucursal_id=$sucursal_id" : '';

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

    if (!empty($_GET['fecha_desde'])) { $where[] = "g.fecha_gasto >= ?"; $params[] = $_GET['fecha_desde']; }
    if (!empty($_GET['fecha_hasta'])) { $where[] = "g.fecha_gasto <= ?"; $params[] = $_GET['fecha_hasta']; }
    if (!empty($_GET['categoria_id'])) { $where[] = "g.categoria_id = ?"; $params[] = (int)$_GET['categoria_id']; }
    $wc = count($where) ? 'AND ' . implode(' AND ', $where) : '';

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

    // By category
    $sql2 = "SELECT c.nombre as categoria, COALESCE(SUM(g.monto),0) as total, COUNT(*) as transacciones
             FROM gastos_operativos g LEFT JOIN categorias_gastos c ON c.id=g.categoria_id WHERE 1=1 $wc $where_suc
             GROUP BY g.categoria_id ORDER BY total DESC";
    $st2 = $pdo->prepare($sql2); $st2->execute($params);
    $porCategoria = $st2->fetchAll(PDO::FETCH_ASSOC);

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

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

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