document.addEventListener("DOMContentLoaded", function() {
    cargarConciertos();
});

function cargarConciertos() {
    fetch("../php/conciertos.php")
        .then(response => response.json())
        .then(data => {
            let select = document.getElementById("concierto");
            select.innerHTML = '<option value="">Selecciona un concierto</option>';
            
            data.forEach(concierto => {
                let option = document.createElement("option");
                option.value = concierto.id;
                option.textContent = concierto.nombre;
                select.appendChild(option);
            });

            select.addEventListener("change", function() {
                cargarAsientos(select.value);
            });
        })
        .catch(error => console.error("Error cargando conciertos:", error));
}

function cargarAsientos(conciertoId) {
    fetch(`../php/asientos.php?concierto_id=${conciertoId}`)
        .then(response => response.json())
        .then(data => {
            if (!Array.isArray(data)) {
                console.error("Error: La respuesta del servidor no es un array.", data);
                return;
            }

            let containerVIP = document.getElementById("asientosVIP");
            let containerGeneral = document.getElementById("asientosGeneral");

            containerVIP.innerHTML = "";
            containerGeneral.innerHTML = "";

            if (data.length === 0) {
                containerVIP.innerHTML = "<p>No hay asientos VIP disponibles.</p>";
                containerGeneral.innerHTML = "<p>No hay asientos Generales disponibles.</p>";
                return;
            }

            data.forEach(asiento => {
                let div = document.createElement("div");
                div.classList.add("asiento", asiento.estado);
                div.textContent = `Asiento ${asiento.numero}`;

                if (asiento.estado === "disponible") {
                    div.addEventListener("click", () => seleccionarAsiento(div, asiento.id));
                }

                if (asiento.zona === "VIP") {
                    containerVIP.appendChild(div);
                } else {
                    containerGeneral.appendChild(div);
                }
            });
        })
        .catch(error => console.error("Error cargando asientos:", error));
}

let asientosSeleccionados = [];

function seleccionarAsiento(element, asientoId) {
    if (asientosSeleccionados.includes(asientoId)) {
        asientosSeleccionados = asientosSeleccionados.filter(id => id !== asientoId);
        element.classList.remove("seleccionado");
    } else {
        asientosSeleccionados.push(asientoId);
        element.classList.add("seleccionado");
    }
}

document.getElementById("confirmarCompra").addEventListener("click", function() {
    if (asientosSeleccionados.length === 0) {
        alert("Selecciona al menos un asiento.");
        return;
    }

    const conciertoId = document.getElementById("concierto").value;

    fetch("../php/comprar_asiento.php", {
        method: "POST",
        body: JSON.stringify({ concierto_id: conciertoId, asientos: asientosSeleccionados }),
        headers: { "Content-Type": "application/json" }
    })
    .then(response => response.json())
    .then(data => {
        if (!data.error) {
            window.location.href = `../php/comprobante.php?transaction_id=${data.transaction_id}`;
        }
    })
    .catch(error => console.error("Error al comprar boletos:", error));
});