const preciosPorArtista = {
    'The Driver Era': {
        1: 4500, 
        4: 2600, 
        8: 1300  
    },
    'The 1975': {
        1: 5000, 
        4: 3100, 
        8: 1600  
    },
    'Taylor Swift': {
        1: 7800, 
        4: 3800, 
        8: 2100  
    }
};


let artista, dias;

const filas = 10;
const columnas = 12;
let diaSeleccionado;
const asientosVendidos = {};
let asientosSeleccionados = {}; 

function inicializarPagina(nombreArtista, diasArtista) {
    artista = nombreArtista;
    dias = diasArtista;
    diaSeleccionado = dias[0]; 

    dias.forEach(dia => asientosVendidos[dia] = new Set());

    verificarEInsertarAsientos();

    renderizarDias();
}

function obtenerPrecio(fila) {
    if (!artista || !preciosPorArtista[artista]) {
        console.error("Artista no definido o no tiene precios asignados.");
        return 0;
    }

    if (fila >= 1 && fila <= 3) {
        return preciosPorArtista[artista][1];
    } else if (fila >= 4 && fila <= 7) {
        return preciosPorArtista[artista][4];
    } else if (fila >= 8 && fila <= 10) {
        return preciosPorArtista[artista][8];
    } else {// En caso de fila no vĂ¡lida
    }
}

function verificarEInsertarAsientos() {
    const url = 'control/verificar_e_insertar_asientos.php';
    const data = {
        artista: artista,
        dias: dias,
        filas: filas,
        columnas: columnas
    };

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.error) {
            console.error("Error al verificar/insertar asientos:", result.error);
        } else {
            console.log(result.message);
            cargarAsientos();
        }
    })
    .catch(error => console.error('Error al verificar/insertar asientos:', error));
}

function renderizarDias() {
    const contenedorDias = document.querySelector('.dias');
    contenedorDias.innerHTML = '';
    dias.forEach(dia => {
        const boton = document.createElement('button');
        boton.className = 'btn btn-primary';
        boton.textContent = dia;
        boton.onclick = () => seleccionarDia(dia);
        contenedorDias.appendChild(boton);
    });
}

function seleccionarDia(dia) {
    diaSeleccionado = dia;
    asientosSeleccionados = {}; 
    document.querySelectorAll('.dias button').forEach(btn => btn.classList.remove('selected'));
    event.target.classList.add('selected');
    document.getElementById("asientos").style.display = "grid";
    cargarAsientos();
}

function cargarAsientos() {
    const url = `control/consultar_asientos.php?artista=${encodeURIComponent(artista)}&dia=${diaSeleccionado}`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error("Error al cargar los asientos:", data.error);
                return;
            }

            asientosVendidos[diaSeleccionado].clear();

            data.asientos.forEach(asiento => {
                if (asiento.estado === 'vendido') {
                    asientosVendidos[diaSeleccionado].add(asiento.asiento);
                }
            });

            renderizarAsientos();
        })
        .catch(error => console.error('Error al cargar los asientos:', error));
}

function actualizarPanelBoletos() {
    const panel = document.getElementById("panel-boletos");
    const lista = document.getElementById("lista-boletos");
    const totalPrecio = document.getElementById("total-precio");

    lista.innerHTML = ""; 
    const asientos = Object.keys(asientosSeleccionados);
    let total = 0;

    if (asientos.length === 0) {
        panel.classList.add("oculto"); 
        return;
    } else {
        panel.classList.remove("oculto"); 
    }

    asientos.forEach(asiento => {
        const precio = asientosSeleccionados[asiento];
        total += precio;

        const boletoItem = document.createElement("div");
        boletoItem.className = "boleto-item";
        boletoItem.innerHTML = `
            <span>${asiento}</span>
            <span>$${precio} MXN</span>
        `;

        lista.appendChild(boletoItem);
    });

    totalPrecio.textContent = `$${total} MXN`;
}

function toggleAsiento(asiento, precio) {
    if (asientosVendidos[diaSeleccionado].has(asiento)) return;

    if (asientosSeleccionados[asiento]) {
        delete asientosSeleccionados[asiento]; 
    } else {
        asientosSeleccionados[asiento] = precio; 
    }

    actualizarPanelBoletos();
    renderizarAsientos();
}




function renderizarAsientos() {
    const contenedor = document.getElementById('asientos');
    contenedor.innerHTML = '';
    for (let i = 0; i < filas * columnas; i++) {
        const fila = Math.floor(i / columnas) + 1;
        const columna = String.fromCharCode(65 + (i % columnas)); 
        const asiento = `${fila}${columna}`;
        const precio = obtenerPrecio(fila);

        const boton = document.createElement('button');
        boton.className = 'asiento';
        
        if (asientosVendidos[diaSeleccionado].has(asiento)) {
            boton.classList.add('vendido');
        } else if (asientosSeleccionados[asiento]) {
            boton.style.backgroundColor = 'orange';
        }
        boton.textContent = `${asiento}`;
        boton.onclick = () => toggleAsiento(asiento, precio);
        contenedor.appendChild(boton);
    }
}

document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("asientos").style.display = "none";

    const btnVender = document.getElementById("btnVender");
    if (btnVender) {
        btnVender.addEventListener("click", venderAsientos);
    }
});

function venderAsientos() {
    const asientos = Object.keys(asientosSeleccionados);
    if (asientos.length === 0) {
        alert("Selecciona al menos un asiento para vender.");
        return;
    }

    let precioTotal = 0;
    const asientosSeleccionadosArray = [];

    asientos.forEach(asiento => {
        const precio = asientosSeleccionados[asiento];
        if (typeof precio === 'number') { 
            precioTotal += precio;
            asientosSeleccionadosArray.push(`${asiento} - $${precio}`);
        }
    });

    const fechaHora = new Date().toLocaleString();

    document.getElementById('modalArtista').textContent = artista;
    document.getElementById('modalDia').textContent = diaSeleccionado;
    document.getElementById('modalAsientos').textContent = asientosSeleccionadosArray.join(', ');
    document.getElementById('modalPrecioTotal').textContent = `$${precioTotal}`;
    document.getElementById('modalFechaHora').textContent = fechaHora;

    document.getElementById('modalOverlay').classList.add('modal-visible');
    document.getElementById('comprobanteModal').style.display = 'block';
}


function confirmarVenta() {
    const url = 'control/vender_asientos.php';
    const data = {
        artista: artista,
        dia: diaSeleccionado,
        asientos: Object.keys(asientosSeleccionados) 
    };

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.error) {
            console.error("Error al vender los asientos:", result.error);
            alert("Error al vender los asientos: " + result.error);
        } else {
            console.log("Venta realizada:", result.message);
            alert(result.message);

            Object.keys(asientosSeleccionados).forEach(asiento => {
                asientosVendidos[diaSeleccionado].add(asiento);
            });
            asientosSeleccionados = {}; 
            renderizarAsientos();
        }
    })
    .catch(error => console.error('Error al vender los asientos:', error));

    document.getElementById('modalOverlay').classList.remove('modal-visible');
    document.getElementById('comprobanteModal').style.display = 'none';
}


function rechazarVenta() {
    asientosSeleccionados = {};
    renderizarAsientos();

    document.getElementById('modalOverlay').classList.remove('modal-visible');
    document.getElementById('comprobanteModal').style.display = 'none';
}


const modal = document.getElementById('comprobanteModal');
const span = document.getElementsByClassName('close')[0];

span.onclick = () => modal.style.display = 'none';
window.onclick = (event) => {
    if (event.target === modal) {
        modal.style.display = 'none';
    }
};

document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("asientos").style.display = "none"; // Ocultar los asientos al cargar
});