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

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

    if (!empty($_GET['fecha_desde'])) { $where[] = "DATE(v.fecha_y_hora) >= ?"; $params[] = $_GET['fecha_desde']; }
    if (!empty($_GET['fecha_hasta'])) { $where[] = "DATE(v.fecha_y_hora) <= ?"; $params[] = $_GET['fecha_hasta']; }
    if (!empty($_GET['tipo_pago'])) { 
        $tp = (int)$_GET['tipo_pago'];
        $where[] = "v.id_tipopago = ?"; $params[] = $tp;
    }
    $wc = count($where) ? 'AND ' . implode(' AND ', $where) : '';

    // Daily aggregation
    $sql = "SELECT DATE(v.fecha_y_hora) as fecha, COUNT(*) as transacciones, 
                   COALESCE(SUM(v.total),0) as total, 
                   COALESCE(SUM(v.monto_efectivo),0) as efectivo, 
                   COALESCE(SUM(v.monto_tarjeta),0) as tarjeta,
                   COALESCE(SUM(v.descuento),0) as descuentos
            FROM ventas v WHERE 1=1 $wc $where_suc
            GROUP BY DATE(v.fecha_y_hora) ORDER BY fecha DESC";
    $st = $pdo->prepare($sql); $st->execute($params);
    $diario = $st->fetchAll(PDO::FETCH_ASSOC);

    // By branch
    $sql2 = "SELECT s.nombre as sucursal, COUNT(*) as transacciones, COALESCE(SUM(v.total),0) as total
             FROM ventas v JOIN sucursales s ON s.id=v.sucursal_id WHERE 1=1 $wc $where_suc
             GROUP BY v.sucursal_id ORDER BY total DESC";
    $st2 = $pdo->prepare($sql2); $st2->execute($params);
    $porSucursal = $st2->fetchAll(PDO::FETCH_ASSOC);

    // By payment type
    $sql3 = "SELECT tp.id, tp.nombre as nombre, COUNT(*) as transacciones, COALESCE(SUM(v.total),0) as total
             FROM ventas v JOIN tipopago tp ON tp.id=v.id_tipopago WHERE 1=1 $wc $where_suc
             GROUP BY v.id_tipopago ORDER BY total DESC";
    $st3 = $pdo->prepare($sql3); $st3->execute($params);
    $porPago = $st3->fetchAll(PDO::FETCH_ASSOC);

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

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