<?php
header("Content-Type: application/json");
require_once "conexion-bd.php";

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    echo json_encode(["error" => "Método no permitido."]);
    exit();
}

$fecha_inicio = isset($_GET['fecha_inicio']) ? $_GET['fecha_inicio'].' 00:00:00' : '';
$fecha_fin = isset($_GET['fecha_fin']) ? $_GET['fecha_fin'].' 23:59:59' : '';

if (empty($fecha_inicio) || empty($fecha_fin)) {
    echo json_encode(["error" => "Debes proporcionar un rango de fechas."]);
    exit();
}

$sql = "SELECT ventas.id, ventas.fecha_venta, conciertos.artista, lugares.nombre AS lugar, 
               asientos.numero_asiento, ventas_asientos.precio 
        FROM ventas
        JOIN conciertos ON ventas.evento_id = conciertos.id
        JOIN lugares ON conciertos.lugar_id = lugares.id
        JOIN ventas_asientos ON ventas.id = ventas_asientos.venta_id
        JOIN asientos ON ventas_asientos.asiento_id = asientos.id
        WHERE ventas.fecha_venta BETWEEN ? AND ? 
        ORDER BY ventas.fecha_venta DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $fecha_inicio, $fecha_fin);
$stmt->execute();
$result = $stmt->get_result();

$ventas = [];
while ($row = $result->fetch_assoc()) {
    $ventas[] = [
        'fecha_venta' => $row['fecha_venta'],
        'artista' => $row['artista'],
        'lugar' => $row['lugar'],
        'numero_asiento' => $row['numero_asiento'],
        'precio' => $row['precio']
    ];
}

echo json_encode(["ventas" => $ventas], JSON_UNESCAPED_UNICODE);

$stmt->close();
$conn->close();
?>