document.addEventListener("DOMContentLoaded", function () {
    const params = new URLSearchParams(window.location.search);
    const idEvento = params.get("id");

    if (!idEvento) {
        document.getElementById("eventoInfo").innerHTML = "<p>Error: No se especificó un evento.</p>";
        return;
    }

    fetch("controladores/detalles-evento.php?id=" + idEvento)
    .then(response => response.json())
    .then(data => {
        console.log("Respuesta del servidor:", data);

        if (!data || data.error) {
            document.getElementById("eventoInfo").innerHTML = "<p>" + (data.error || "Error desconocido.") + "</p>";
            return;
        }

        document.getElementById("titulo").textContent = "Comprar Boletos para " + data.artista;
        document.getElementById("fecha").textContent = "Fecha: " + data.fecha;
        document.getElementById("lugar").textContent = "Lugar: " + data.lugar;
        document.getElementById("evento_id").value = idEvento;
        document.getElementById("precioBoleto").textContent = "$" + data.precio;

        let inputCantidad = document.getElementById("cantidad");
        if (inputCantidad) {
            inputCantidad.setAttribute("max", data.cupos_disponibles);
        } else {
            console.warn("Advertencia: El campo 'cantidad' no se encontró en el HTML.");
        }
    })
    .catch(error => {
        console.error("Error al obtener datos del evento:", error);
        document.getElementById("eventoInfo").innerHTML = "<p>Error al cargar los detalles del evento.</p>";
    });
});

// Lógica de selección de asientos
document.addEventListener("DOMContentLoaded", function () {
    const params = new URLSearchParams(window.location.search);
    const eventoId = params.get("id");

    fetch(`controladores/obtener-asientos.php?id=${eventoId}`)
        .then(response => response.json())
        .then(asientos => {
            const contenedor = document.getElementById("mapa-asientos");
            contenedor.innerHTML = ""; 

            asientos.forEach(asiento => {
                let btn = document.createElement("button");
                btn.textContent = asiento.numero_asiento;
                btn.classList.add('seat', asiento.estado === "disponible" ? "disponible" : "vendido");

                if (asiento.estado === "vendido") {
                    btn.disabled = true;
                } else {
                    btn.addEventListener("click", function (event) {
                        event.preventDefault(); 

                        let cantidadBoletos = parseInt(document.getElementById("cantidad").value) || 0;
                        let seleccionados = document.querySelectorAll(".seleccionado").length;

                        if (this.classList.contains("seleccionado")) {
                            this.classList.remove("seleccionado");
                        } else if (seleccionados < cantidadBoletos) {
                            this.classList.add("seleccionado");
                        } else {
                            alert("Has seleccionado el número máximo de boletos.");
                        }
                    });
                }

                contenedor.appendChild(btn);
            });
        })
        .catch(error => console.error("Error al cargar los asientos:", error));
});

// Confirmación de la compra
document.getElementById("comprarBoletos").addEventListener("click", function (event) {
    event.preventDefault(); 

    let asientosSeleccionados = [];
    document.querySelectorAll(".seleccionado").forEach(btn => {
        asientosSeleccionados.push(btn.textContent);
    });

    console.log("Asientos seleccionados antes de enviar:", asientosSeleccionados);

    if (asientosSeleccionados.length === 0) {
        alert("Debes seleccionar al menos un asiento antes de confirmar la compra.");
        return;
    }

    let cantidadBoletos = parseInt(document.getElementById("cantidad").value) || 0;
    if (asientosSeleccionados.length !== cantidadBoletos) {
        alert("Debes seleccionar exactamente " + cantidadBoletos + " asientos.");
        return;
    }

    let confirmacion = confirm("¿Estás seguro de realizar la compra?");
    if (!confirmacion) {
        return;
    }

    let formData = new FormData(document.getElementById("formCompra"));
    formData.append("asientos", JSON.stringify(asientosSeleccionados));

    console.log("Datos enviados:", Object.fromEntries(formData));

    fetch("controladores/procesar-compra.php", {
        method: "POST",
        body: formData,
        credentials: 'include'
    })
    .then(response => response.json())  
    .then(data => {
        console.log("Respuesta del servidor:", data);

        if (data.mensaje.includes("exitosamente")) {
            alert("Compra realizada exitosamente.");
            window.location.href = "comprobante.html?id=" + data.id_compra;
        } else {
            alert("Error en la compra: " + data.mensaje);
        }
    })
    .catch(error => console.error("Error al procesar la compra:", error));
});