let usuarioYaEstaEnEquipo = false; let intervaloSala = null; let botonAbandonarReferencia = null; $(document).ready(function () { comprobarSalaUsuario(); }); // ===================================================== // COMPROBAR SI EL USUARIO YA ESTÁ EN UNA SALA // ===================================================== function comprobarSalaUsuario() { $("#cargandoSalas").remove(); $.ajax({ url: "controladores/controladorEquipoxUsuario.php", type: "POST", dataType: "json", data: { orden: "obtenerSalaUsuario", }, success: function (respuesta) { if (respuesta.error || !respuesta.asociado) { usuarioYaEstaEnEquipo = false; $("#contenedorCrearSala").show(); cargarSalas(); } else { usuarioYaEstaEnEquipo = true; $("#contenedorCrearSala").hide(); cargarSalaUsuario(respuesta.idPartida); } }, error: function (xhr, status, error) { console.error( "Error al comprobar la sala del usuario:", error ); usuarioYaEstaEnEquipo = false; $("#contenedorCrearSala").show(); cargarSalas(); }, }); } // ===================================================== // CARGAR SALA DEL USUARIO // ===================================================== function cargarSalaUsuario(idPartida) { // Primera carga completa cargarSalaCompleta(idPartida); // Evitar intervalos duplicados if (intervaloSala) { clearInterval(intervaloSala); } intervaloSala = setInterval(function () { actualizarSalaUsuario(idPartida); }, 5000); } // ===================================================== // CARGA COMPLETA DE LA SALA // ===================================================== function cargarSalaCompleta(idPartida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "buscar", idPartida: idPartida, }, success: function (partida) { if (partida.error) { console.error(partida.error); return; } cargarInformacionSalaCompleta(partida); }, error: function (xhr, status, error) { console.error( "Error al obtener la sala:", error ); }, }); } // ===================================================== // OBTENER EQUIPOS Y JUGADORES // ===================================================== function cargarInformacionSalaCompleta(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) { mostrarSala(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 SALA CADA 5 SEGUNDOS // ===================================================== function actualizarSalaUsuario(idPartida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", data: { orden: "buscar", idPartida: idPartida, }, success: function (partida) { if (partida.error) { console.error(partida.error); return; } cargarInformacionSala(partida); }, error: function (xhr, status, error) { console.error( "Error al actualizar la sala:", error ); }, }); } // ===================================================== // OBTENER INFORMACIÓN PARA ACTUALIZACIÓN // ===================================================== function cargarInformacionSala(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) { mostrarEquipos( 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 ); }, }); } // ===================================================== // MOSTRAR SALA COMPLETA // ===================================================== function mostrarSala(partida, equipos, jugadores) { const contenedor = $("#contenedorSalas"); let equiposHTML = ""; equipos.forEach(function (equipo) { const jugadoresEquipo = jugadores.filter(function (jugador) { return jugador.idEquipo == equipo.idEquipo; }); let jugadoresHTML = ""; 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
`; } equiposHTML += `
${escapeHTML(equipo.nombreEquipo)}
${jugadoresHTML}
`; }); const esHost = partida.idUsuario == idUsuarioSesion; let botonIniciarHTML = ""; if (esHost) { botonIniciarHTML = ` ¡Iniciar Partida! `; } const salaHTML = `
${escapeHTML(partida.nombrePartida)}
${equiposHTML}
${ esHost ? botonIniciarHTML : "" }
`; // IMPORTANTE: // El usuario está dentro de una única sala. // Por eso aquí SÍ queremos reemplazar. contenedor.html(salaHTML); } // ===================================================== // UNIRSE A UN EQUIPO // ===================================================== $(document).on( "click", ".btn-unirse-equipo", function () { const boton = $(this); const idEquipo = boton.data("id-equipo"); const idPartida = boton.data("id-partida"); boton .prop("disabled", true) .text("Uniéndose..."); $.ajax({ url: "controladores/controladorEquipoxUsuario.php", type: "POST", dataType: "json", data: { orden: "registrarUsuarioEnEquipo", idEquipo: idEquipo, }, success: function (respuesta) { if (respuesta.error) { alert(respuesta.error); boton .prop("disabled", false) .text("Unirse"); return; } usuarioYaEstaEnEquipo = true; $("#contenedorCrearSala").hide(); $("#contenedorSalas").empty(); cargarSalaUsuario(idPartida); }, error: function (xhr, status, error) { console.error( "Error al unirse al equipo:", error ); alert( "No se ha podido unir al equipo." ); boton .prop("disabled", false) .text("Unirse"); }, }); } ); // ===================================================== // ABANDONAR SALA - ABRIR MODAL // ===================================================== $(document).on( "click", ".btn-abandonar-sala", function () { botonAbandonarReferencia = $(this); const esHost = $(this).data("es-host") === true || $(this).data("es-host") === "true"; const titulo = $("#modalAbandonarSalaLabel"); const mensaje = $("#modalAbandonarSalaMensaje"); const botonConfirmar = $("#btnConfirmarAbandonar"); if (esHost) { titulo.text("¿Abandonar la sala?"); mensaje.text( "Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores." ); botonConfirmar.text( "Sí, terminar partida" ); } else { titulo.text("¿Abandonar la sala?"); mensaje.text( "Si sales de la sala, perderás tu lugar en el equipo." ); botonConfirmar.text("Sí, salir"); } const modal = new bootstrap.Modal( document.getElementById( "modalAbandonarSala" ) ); modal.show(); } ); // ===================================================== // CONFIRMAR ABANDONAR SALA // ===================================================== $(document).on( "click", "#btnConfirmarAbandonar", function () { const modalEl = document.getElementById( "modalAbandonarSala" ); const modalInstance = bootstrap.Modal.getInstance(modalEl); const btnConfirmar = $(this); btnConfirmar .prop("disabled", true) .text("Saliendo..."); $.ajax({ url: "controladores/controladorEquipoxUsuario.php", type: "POST", dataType: "json", data: { orden: "salirDeSala", }, success: function (respuesta) { btnConfirmar .prop("disabled", false) .text("Sí, salir"); if (modalInstance) { modalInstance.hide(); } if (respuesta.error) { alert(respuesta.error); return; } usuarioYaEstaEnEquipo = false; if (intervaloSala) { clearInterval(intervaloSala); intervaloSala = null; } $("#contenedorCrearSala").show(); cargarSalas(); }, error: function (xhr, status, error) { console.error( "Error al salir de la sala:", error ); alert( "No se pudo salir de la sala." ); btnConfirmar .prop("disabled", false) .text("Sí, salir"); if (modalInstance) { modalInstance.hide(); } }, }); } ); // ===================================================== // AUXILIARES // ===================================================== function escapeHTML(texto) { return $("
") .text(texto ?? "") .html(); } function mostrarEquipos( partida, equipos, jugadores ) { let equiposHTML = ""; equipos.forEach(function (equipo) { const jugadoresEquipo = jugadores.filter(function (jugador) { return ( jugador.idEquipo == equipo.idEquipo ); }); let jugadoresHTML = ""; 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
`; } equiposHTML += `
${escapeHTML( equipo.nombreEquipo )}
${jugadoresHTML}
`; }); $("#contenedorSalas .equipos") .html(equiposHTML); }