// ===================================================== // VARIABLES // ===================================================== let intervaloBuscadorSalas = null; let cargandoSalas = false; // ===================================================== // INICIAR ACTUALIZACIÓN AUTOMÁTICA // ===================================================== function iniciarActualizacionSalas() { // Evitar crear varios intervalos if (intervaloBuscadorSalas) { clearInterval(intervaloBuscadorSalas); } // Primera carga cargarSalas(); // Actualizar cada 5 segundos intervaloBuscadorSalas = setInterval(function () { // Si el usuario está dentro de una sala, // no necesitamos actualizar el buscador. if (!usuarioYaEstaEnEquipo) { cargarSalas(); } }, 5000); } // ===================================================== // CARGAR LISTA DE SALAS // ===================================================== function cargarSalas() { // Evitar peticiones simultáneas if (cargandoSalas) { return; } cargandoSalas = true; $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "listar", }, success: function (partidas) { const contenedor = $("#contenedorSalas"); // ================================================= // NO HAY SALAS // ================================================= if ( !Array.isArray(partidas) || partidas.length === 0 ) { // Ocultamos/eliminamos únicamente las salas $(".sala-item").remove(); if ($("#mensajeSinSalas").length === 0) { contenedor.append(`

No hay salas disponibles actualmente.

`); } return; } // ================================================= // HAY SALAS // ================================================= // Eliminar mensaje de "no hay salas" $("#mensajeSinSalas").remove(); // ================================================= // OBTENER IDS DE LAS SALAS ACTUALES // ================================================= const idsPartidas = partidas.map(function (partida) { return String(partida.idPartida); }); // ================================================= // ELIMINAR SALAS QUE YA NO EXISTEN // ================================================= $(".sala-item").each(function () { const idPartida = String( $(this).data("id-partida") ); if (!idsPartidas.includes(idPartida)) { $(this).remove(); } }); // ================================================= // ACTUALIZAR / CREAR CADA SALA // ================================================= partidas.forEach(function (partida) { cargarSalaBuscador(partida); }); }, error: function (xhr, status, error) { console.error( "Error al obtener las partidas:", error ); }, complete: function () { cargandoSalas = false; }, }); } // ===================================================== // CARGAR INFORMACIÓN DE UNA SALA // ===================================================== function cargarSalaBuscador(partida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "getEquipos", idPartida: partida.idPartida, }, success: function (equipos) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "getJugadores", idPartida: partida.idPartida, }, success: function (jugadores) { actualizarSalaBuscador( partida, equipos, jugadores ); }, error: function (xhr, status, error) { console.error( "Error al obtener jugadores:", error ); }, }); }, error: function (xhr, status, error) { console.error( "Error al obtener equipos:", error ); }, }); } // ===================================================== // ACTUALIZAR UNA SALA // ===================================================== function actualizarSalaBuscador( partida, equipos, jugadores ) { const selectorSala = `.sala-item[data-id-partida="${partida.idPartida}"]`; const salaExistente = $(selectorSala); // =================================================== // SI LA SALA NO EXISTE → CREARLA // =================================================== if (salaExistente.length === 0) { crearSalaBuscador( partida, equipos, jugadores ); return; } // =================================================== // LA SALA YA EXISTE // =================================================== // // NO TOCAMOS LA TARJETA COMPLETA. // // Solo actualizamos .equipos // const equiposHTML = generarEquiposHTML( partida, equipos, jugadores ); salaExistente .find(".equipos") .html(equiposHTML); } // ===================================================== // CREAR UNA SALA NUEVA // ===================================================== function crearSalaBuscador( partida, equipos, jugadores ) { const equiposHTML = generarEquiposHTML( partida, equipos, jugadores ); const salaHTML = `
${escapeHTML( partida.nombrePartida )}
${equiposHTML}
`; $("#contenedorSalas").append( salaHTML ); } // ===================================================== // GENERAR HTML DE EQUIPOS Y JUGADORES // ===================================================== function generarEquiposHTML( partida, equipos, jugadores ) { let equiposHTML = ""; equipos.forEach(function (equipo) { // ----------------------------------------------- // JUGADORES DE ESTE EQUIPO // ----------------------------------------------- const jugadoresEquipo = jugadores.filter( function (jugador) { return ( jugador.idEquipo == equipo.idEquipo ); } ); let jugadoresHTML = ""; // ----------------------------------------------- // MOSTRAR JUGADORES // ----------------------------------------------- if (jugadoresEquipo.length > 0) { jugadoresEquipo.forEach( function (jugador) { const esHost = jugador.idUsuario == partida.idUsuario; jugadoresHTML += `
${ esHost ? '' : '' } ${escapeHTML( jugador.nombreUsuario )}
${ esHost ? ` HOST ` : "" }
`; } ); } else { jugadoresHTML = `
Sin jugadores
`; } // ----------------------------------------------- // BOTÓN UNIRSE // ----------------------------------------------- let botonUnirseHTML = ""; if (!usuarioYaEstaEnEquipo) { botonUnirseHTML = ` `; } // ----------------------------------------------- // EQUIPO // ----------------------------------------------- equiposHTML += `
${escapeHTML( equipo.nombreEquipo )}
${jugadoresHTML}
${botonUnirseHTML}
`; }); return equiposHTML; } // ===================================================== // CREAR SALA // ===================================================== $("#btnCrearSala").on( "click", function () { const nombreSala = $("#nombreSala").val().trim(); const nombreEquipo1 = $("#nombreEquipo1").val().trim(); const nombreEquipo2 = $("#nombreEquipo2").val().trim(); let valido = true; // ----------------------------------------------- // LIMPIAR ERRORES // ----------------------------------------------- $(".mensaje-error-sala").remove(); $(".input-kahoot") .removeClass("is-invalid"); // ----------------------------------------------- // VALIDAR NOMBRE DE SALA // ----------------------------------------------- if ( nombreSala === "" || nombreSala.length < 3 ) { mostrarError( "#nombreSala", "El nombre de la sala debe tener al menos 3 caracteres." ); valido = false; } // ----------------------------------------------- // VALIDAR EQUIPO 1 // ----------------------------------------------- if ( nombreEquipo1 === "" || nombreEquipo1.length < 2 ) { mostrarError( "#nombreEquipo1", "El nombre del equipo debe tener al menos 2 caracteres." ); valido = false; } // ----------------------------------------------- // VALIDAR EQUIPO 2 // ----------------------------------------------- if ( nombreEquipo2 === "" || nombreEquipo2.length < 2 ) { mostrarError( "#nombreEquipo2", "El nombre del equipo debe tener al menos 2 caracteres." ); valido = false; } // ----------------------------------------------- // COMPROBAR NOMBRES IGUALES // ----------------------------------------------- if ( nombreEquipo1 !== "" && nombreEquipo2 !== "" && nombreEquipo1.toLowerCase() === nombreEquipo2.toLowerCase() ) { mostrarError( "#nombreEquipo2", "Los dos equipos deben tener nombres diferentes." ); valido = false; } // ----------------------------------------------- // SI HAY ERRORES // ----------------------------------------------- if (!valido) { return; } // ----------------------------------------------- // BOTÓN // ----------------------------------------------- const boton = $("#btnCrearSala"); boton .prop("disabled", true) .text("Creando sala..."); // ----------------------------------------------- // PETICIÓN // ----------------------------------------------- $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "crear", nombrePartida: nombreSala, nombreEquipo1: nombreEquipo1, nombreEquipo2: nombreEquipo2, }, success: function (respuesta) { if (respuesta.error) { alert(respuesta.error); boton .prop("disabled", false) .text("Crear sala"); return; } if (respuesta.exito) { $("#modalCrearSala").modal( "hide" ); location.reload(); } }, error: function (xhr, status, error) { console.error( "Error al crear la sala:", error ); alert( "No se ha podido crear la sala." ); boton .prop("disabled", false) .text("Crear sala"); }, }); } ); // ===================================================== // MOSTRAR ERROR // ===================================================== function mostrarError( selector, mensaje ) { const input = $(selector); input.addClass("is-invalid"); input.after(`
${mensaje}
`); } // ===================================================== // LIMPIAR ERRORES AL ESCRIBIR // ===================================================== $(document).on( "input", ".input-kahoot", function () { $(this) .removeClass("is-invalid"); $(this) .next(".mensaje-error-sala") .remove(); } );