1334 lines
40 KiB
JavaScript
1334 lines
40 KiB
JavaScript
document.addEventListener("DOMContentLoaded", function () {
|
|
// Manejo del formulario de login
|
|
const loginForm = document.getElementById("loginForm");
|
|
if (loginForm) {
|
|
loginForm.addEventListener("submit", handleLogin);
|
|
}
|
|
|
|
// Configuración inicial del dashboard
|
|
if (document.body.classList.contains("admin")) {
|
|
initializeDashboard();
|
|
}
|
|
});
|
|
|
|
// Función para manejar el login
|
|
function handleLogin(e) {
|
|
e.preventDefault();
|
|
const formData = new FormData(this);
|
|
|
|
fetch(this.action, {
|
|
method: "POST",
|
|
body: formData,
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
window.location.href = data.redirect;
|
|
} else {
|
|
alert(data.message);
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
}
|
|
|
|
// Inicialización del dashboard
|
|
function initializeDashboard() {
|
|
setupSidebarNavigation();
|
|
loadInitialData();
|
|
|
|
const activeSection = document.querySelector(".sidebar-menu li.active");
|
|
if (activeSection) {
|
|
const sectionId = activeSection.getAttribute("data-section");
|
|
showSection(sectionId, true);
|
|
}
|
|
}
|
|
|
|
// Configuración del menú lateral
|
|
function setupSidebarNavigation() {
|
|
document.querySelectorAll(".sidebar-menu li").forEach((item) => {
|
|
if (item.getAttribute("data-section")) {
|
|
item.addEventListener("click", function () {
|
|
const section = this.getAttribute("data-section");
|
|
showSection(section);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
// Carga de datos iniciales
|
|
function loadInitialData() {
|
|
const profesorId = getProfesorId();
|
|
|
|
if (!profesorId) {
|
|
console.error("No se pudo obtener el ID del profesor");
|
|
return;
|
|
}
|
|
|
|
fetch(`api/cursos.php?profesor_id=${profesorId}`)
|
|
.then((response) => response.json())
|
|
.then((courses) => {
|
|
// Cargar estudiantes y diplomas
|
|
Promise.all([
|
|
fetch(`api/alumnos.php?profesor_id=${profesorId}`).then((res) =>
|
|
res.json()
|
|
),
|
|
fetch(`api/diplomas.php?profesor_id=${profesorId}`).then((res) =>
|
|
res.json()
|
|
),
|
|
]).then(([students, diplomas]) => {
|
|
updateProfessorStats(courses, students, diplomas);
|
|
});
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
}
|
|
|
|
// Actualización de estadísticas
|
|
function updateProfessorStats(courses, students, diplomas) {
|
|
document.getElementById("active-courses-count").textContent = courses.length;
|
|
document.getElementById("students-count").textContent = students.length;
|
|
document.getElementById("diplomas-count").textContent = diplomas.length || 0;
|
|
}
|
|
|
|
// Obtención del ID del profesor
|
|
function getProfesorId() {
|
|
try {
|
|
// 1. Verificar en el elemento del DOM (primera opción)
|
|
const profesorElement = document.getElementById("current-profesor");
|
|
if (profesorElement && profesorElement.dataset.id) {
|
|
return profesorElement.dataset.id;
|
|
}
|
|
|
|
// 2. Verificar en sessionStorage/localStorage
|
|
const storedUser =
|
|
sessionStorage.getItem("currentUser") ||
|
|
localStorage.getItem("currentUser");
|
|
if (storedUser) {
|
|
const user = JSON.parse(storedUser);
|
|
if (user && user.profesor_id) {
|
|
return user.profesor_id;
|
|
}
|
|
}
|
|
|
|
console.log(
|
|
"No se encontró el ID del profesor en el DOM o en el almacenamiento"
|
|
);
|
|
return null;
|
|
} catch (error) {
|
|
console.error("Error en getProfesorId:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function showModal(title, content, buttons = []) {
|
|
const modalHtml = `
|
|
<div class="modal-overlay" id="modal-overlay">
|
|
<div class="modal">
|
|
<div class="modal-header">
|
|
<h3>${title}</h3>
|
|
<button class="close-btn" onclick="closeModal()">×</button>
|
|
</div>
|
|
<div class="modal-body">${content}</div>
|
|
<div class="modal-footer">
|
|
${buttons
|
|
.map(
|
|
(btn) => `
|
|
<button class="btn ${btn.class}"
|
|
onclick="${
|
|
typeof btn.handler === "function"
|
|
? `(${btn.handler.toString()})()`
|
|
: btn.handler
|
|
}">
|
|
${btn.text}
|
|
</button>
|
|
`
|
|
)
|
|
.join("")}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
const modalContainer = document.createElement("div");
|
|
modalContainer.innerHTML = modalHtml;
|
|
document.body.appendChild(modalContainer);
|
|
document.body.style.overflow = "hidden";
|
|
}
|
|
|
|
function closeModal() {
|
|
const modal = document.getElementById("modal-overlay");
|
|
if (modal) {
|
|
modal.remove();
|
|
document.body.style.overflow = "";
|
|
}
|
|
}
|
|
|
|
function showToast(type, message) {
|
|
const toast = document.createElement("div");
|
|
toast.className = `toast toast-${type}`;
|
|
toast.textContent = message;
|
|
document.body.appendChild(toast);
|
|
|
|
setTimeout(() => {
|
|
toast.classList.add("fade-out");
|
|
setTimeout(() => toast.remove(), 300);
|
|
}, 3000);
|
|
}
|
|
|
|
// Manejo de secciones
|
|
function showSection(sectionId, isInitialLoad = false) {
|
|
updateActiveMenu(sectionId);
|
|
|
|
const sectionElement = document.getElementById(`${sectionId}-content`);
|
|
if (!sectionElement) return;
|
|
|
|
document.querySelectorAll(".content-section").forEach((s) => {
|
|
s.classList.remove("active");
|
|
});
|
|
sectionElement.classList.add("active");
|
|
|
|
// Cargar siempre los datos del dashboard al acceder
|
|
if (sectionId === "dashboard") {
|
|
loadInitialData();
|
|
} else {
|
|
loadDynamicContent(sectionId, sectionElement);
|
|
}
|
|
}
|
|
|
|
function updateActiveMenu(sectionId) {
|
|
document.querySelectorAll(".sidebar-menu li").forEach((li) => {
|
|
li.classList.remove("active");
|
|
});
|
|
|
|
const activeItem = document.querySelector(
|
|
`.sidebar-menu li[data-section="${sectionId}"]`
|
|
);
|
|
if (activeItem) activeItem.classList.add("active");
|
|
}
|
|
|
|
// Carga de contenido dinámico
|
|
function loadDynamicContent(sectionId, container) {
|
|
container.innerHTML = '<div class="loader">Cargando...</div>';
|
|
|
|
switch (sectionId) {
|
|
case "dashboard":
|
|
loadDashboardContent(container);
|
|
break;
|
|
case "courses":
|
|
loadProfessorCourses(container);
|
|
break;
|
|
case "students":
|
|
loadStudentsManagement(container);
|
|
break;
|
|
case "diplomas":
|
|
loadDiplomasSection(container);
|
|
break;
|
|
default:
|
|
container.innerHTML =
|
|
'<div class="card"><h2>Sección no implementada</h2></div>';
|
|
}
|
|
}
|
|
|
|
// Carga del dashboard
|
|
async function loadDashboardContent(container, forceReload = false) {
|
|
try {
|
|
// Mostrar loader
|
|
container.innerHTML = '<div class="loader">Cargando datos...</div>';
|
|
|
|
// Obtener siempre los datos frescos del servidor
|
|
const profesorId = getProfesorId();
|
|
if (!profesorId) {
|
|
throw new Error("Debes iniciar sesión nuevamente");
|
|
}
|
|
|
|
// Usar caché solo si no es un forceReload
|
|
const cacheKey = `dashboardData-${profesorId}`;
|
|
if (!forceReload && sessionStorage.getItem(cacheKey)) {
|
|
const cachedData = JSON.parse(sessionStorage.getItem(cacheKey));
|
|
renderDashboard(container, cachedData);
|
|
return;
|
|
}
|
|
|
|
// Obtener datos frescos
|
|
const [coursesRes, studentsRes, diplomasRes] = await Promise.all([
|
|
fetch(`api/cursos.php?profesor_id=${profesorId}&t=${Date.now()}`),
|
|
fetch(`api/alumnos.php?t=${Date.now()}`),
|
|
fetch(`api/diplomas.php?profesor_id=${profesorId}&t=${Date.now()}`),
|
|
]);
|
|
|
|
const [coursesData, studentsData, diplomasData] = await Promise.all([
|
|
coursesRes.json(),
|
|
studentsRes.json(),
|
|
diplomasRes.json(),
|
|
]);
|
|
|
|
if (
|
|
!coursesData.success ||
|
|
!studentsData.success ||
|
|
!diplomasData.success
|
|
) {
|
|
throw new Error("Error en los datos recibidos");
|
|
}
|
|
|
|
const dashboardData = {
|
|
cursos: coursesData.data,
|
|
alumnos: studentsData.data,
|
|
diplomas: diplomasData.data,
|
|
lastUpdated: new Date().toLocaleTimeString(),
|
|
};
|
|
|
|
// Guardar en caché y renderizar
|
|
sessionStorage.setItem(cacheKey, JSON.stringify(dashboardData));
|
|
renderDashboard(container, dashboardData);
|
|
} catch (error) {
|
|
console.error("Error:", error);
|
|
container.innerHTML = `
|
|
<div class="card error-card">
|
|
<h2>Error al cargar datos</h2>
|
|
<p>${error.message}</p>
|
|
<button class="btn" onclick="loadDashboardContent(this.parentElement.parentElement, true)">
|
|
Reintentar
|
|
</button>
|
|
</div>`;
|
|
}
|
|
}
|
|
function renderDashboard(container, data) {
|
|
const activeCourses = data.cursos.filter((c) => c.estado === "activo");
|
|
const totalStudents = data.alumnos.length;
|
|
const totalDiplomas = data.diplomas.length;
|
|
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<div class="card-header">
|
|
<h2>Resumen General</h2>
|
|
<small class="text-muted">Actualizado: ${
|
|
data.lastUpdated
|
|
}</small>
|
|
<button class="btn btn-sm" onclick="loadDashboardContent(this.closest('.content-section'), true)">
|
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
|
<path d="M23 4v6h-6"></path>
|
|
<path d="M1 20v-6h6"></path>
|
|
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
|
|
</svg>
|
|
Actualizar
|
|
</button>
|
|
</div>
|
|
<div class="stats">
|
|
<p><strong>Resumen:</strong></p>
|
|
<p>• <span class="stat-number">${
|
|
activeCourses.length
|
|
}</span> cursos activos</p>
|
|
<p>• <span class="stat-number">${totalStudents}</span> alumnos registrados</p>
|
|
<p>• <span class="stat-number">${totalDiplomas}</span> diplomas emitidos</p>
|
|
</div>
|
|
</div>
|
|
<div class="card">
|
|
<h2>Mis Cursos Activos</h2>
|
|
${renderCoursesPreview(activeCourses)}
|
|
</div>`;
|
|
}
|
|
|
|
// Gestión de cursos
|
|
function loadProfessorCourses(container) {
|
|
fetch(`api/cursos.php?profesor_id=${getProfesorId()}`)
|
|
.then((response) => response.json())
|
|
.then((res) => {
|
|
if (!res.success) throw new Error("No se pudieron cargar los cursos");
|
|
const courses = res.data;
|
|
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Mis Cursos</h2>
|
|
<form id="courseForm">
|
|
<label>Nombre del Curso *</label>
|
|
<input type="text" name="nombre" required>
|
|
|
|
<label>Descripción</label>
|
|
<textarea name="descripcion" maxlength="250" rows="4" style="width: 100%; padding: 0.75rem; margin: 0.5rem 0 1rem 0; border: 1px solid #e2e8f0; border-radius: 6px; font-family: 'Inter', sans-serif;"></textarea>
|
|
|
|
<label>Tipo de Curso *</label>
|
|
<select id="courseType" name="tipo" required>
|
|
<option value="inyeccion">Inyección</option>
|
|
<option value="pildora">Píldora</option>
|
|
<option value="tratamiento">Tratamiento</option>
|
|
</select>
|
|
|
|
<div id="competencesField" name="competencias" class="oculto">
|
|
<label>Competencias Asociadas *</label>
|
|
<input type="text" name="competencias" placeholder="Ej. Análisis de datos, Comunicación efectiva">
|
|
</div>
|
|
|
|
<label>Estado</label>
|
|
<select name="estado">
|
|
<option value="activo">Activo</option>
|
|
<option value="completado">Completado</option>
|
|
<option value="archivado">Archivado</option>
|
|
</select>
|
|
|
|
<div class="action-buttons">
|
|
<button class="btn btn-success" type="submit">Guardar</button>
|
|
<button class="btn btn-outline" type="button" id="cancelCourseBtn" style="display:none; margin-left:8px; background-color: #f44336;">
|
|
Cancelar
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
<div class="card">
|
|
<h2>Lista de Cursos</h2>
|
|
<div class="table-container">
|
|
<table class="courses-table">
|
|
<thead>
|
|
<tr>
|
|
<th>Nombre</th>
|
|
<th>Descripción</th>
|
|
<th>Tipo</th>
|
|
<th>Estado</th>
|
|
<th>Acciones</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${courses
|
|
.map(
|
|
(course) => `
|
|
<tr>
|
|
<td>${course.nombre}</td>
|
|
<td class="description-cell">${course.descripcion || "-"}</td>
|
|
<td><span class="badge ${getCourseTypeClass(course.tipo)}">${formatCourseType(course.tipo)}</span></td>
|
|
<td>
|
|
<span class="badge ${
|
|
course.estado === "activo"
|
|
? "active"
|
|
: course.estado === "completado"
|
|
? "completed"
|
|
: course.estado === "archivado"
|
|
? "archived"
|
|
: "inactive"
|
|
}">${course.estado}</span>
|
|
</td>
|
|
<td>
|
|
<div class="action-buttons">
|
|
<button class="btn btn-sm" onclick="editCourse(${course.id})">Editar</button>
|
|
<button class="btn btn-sm btn-danger" onclick="deleteCourse(${course.id})">Eliminar</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
`
|
|
)
|
|
.join("")}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>`;
|
|
|
|
setupCourseForm();
|
|
})
|
|
.catch((err) => {
|
|
console.error("Error al cargar cursos:", err);
|
|
container.innerHTML = `<div class="card error-card">No se pudieron cargar los cursos</div>`;
|
|
});
|
|
}
|
|
|
|
function formatCourseType(type) {
|
|
const types = {
|
|
pildora: "Píldora",
|
|
inyeccion: "Inyección",
|
|
tratamiento: "Tratamiento"
|
|
};
|
|
return types[type] || type;
|
|
}
|
|
|
|
function setupCourseForm() {
|
|
const courseTypeSelect = document.getElementById('courseType');
|
|
const competencesField = document.getElementById('competencesField');
|
|
const competenciasInput = competencesField
|
|
? competencesField.querySelector('input[name="competencias"]')
|
|
: null;
|
|
|
|
if (courseTypeSelect && competenciasInput) {
|
|
courseTypeSelect.addEventListener('change', function () {
|
|
const isTratamiento = this.value === 'tratamiento';
|
|
competencesField.classList.toggle('oculto', !isTratamiento);
|
|
competenciasInput.required = isTratamiento;
|
|
if (!isTratamiento) {
|
|
competenciasInput.value = '';
|
|
}
|
|
});
|
|
|
|
const isTratamiento = courseTypeSelect.value === 'tratamiento';
|
|
competencesField.classList.toggle('oculto', !isTratamiento);
|
|
competenciasInput.required = isTratamiento;
|
|
}
|
|
|
|
const form = document.getElementById("courseForm");
|
|
if (!form) return;
|
|
|
|
const cancelBtn = document.getElementById("cancelCourseBtn");
|
|
if (cancelBtn) {
|
|
cancelBtn.addEventListener("click", function () {
|
|
form.reset();
|
|
competencesField.classList.add("oculto");
|
|
form.dataset.editing = "false";
|
|
delete form.dataset.courseId;
|
|
form.querySelector("button[type='submit']").textContent = "Guardar";
|
|
cancelBtn.style.display = "none";
|
|
});
|
|
}
|
|
|
|
form.addEventListener("submit", function (e) {
|
|
e.preventDefault();
|
|
const formData = new FormData(this);
|
|
const jsonData = {
|
|
nombre: formData.get("nombre"),
|
|
descripcion: formData.get("descripcion"),
|
|
competencias: formData.get("competencias"),
|
|
tipo: formData.get("tipo"),
|
|
estado: formData.get("estado"),
|
|
profesor_id: getProfesorId(),
|
|
};
|
|
|
|
const isEdit = form.dataset.editing === "true";
|
|
const courseId = form.dataset.courseId;
|
|
|
|
if (isEdit) {
|
|
updateCourse(courseId, jsonData);
|
|
} else {
|
|
createCourse(jsonData);
|
|
}
|
|
});
|
|
}
|
|
|
|
window.createCourse = function (data) {
|
|
fetch("api/cursos.php", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(data),
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
showSection("courses");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
};
|
|
|
|
window.updateCourse = function (id, data) {
|
|
data.id = id;
|
|
|
|
fetch("api/cursos.php", {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(data),
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
showSection("courses");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
};
|
|
|
|
window.editCourse = function (id) {
|
|
fetch(`api/cursos.php?profesor_id=${getProfesorId()}`)
|
|
.then((response) => response.json())
|
|
.then((res) => {
|
|
const course = res.data.find((c) => c.id == id);
|
|
if (!course) return;
|
|
|
|
const form = document.getElementById("courseForm");
|
|
form.nombre.value = course.nombre;
|
|
form.descripcion.value = course.descripcion || "";
|
|
form.tipo.value = course.tipo;
|
|
form.estado.value = course.estado || "activo";
|
|
|
|
const competencesField = document.getElementById("competencesField");
|
|
const competenciasInput = competencesField.querySelector('input[name="competencias"]');
|
|
if (course.tipo === "tratamiento") {
|
|
competencesField.classList.remove("oculto");
|
|
competenciasInput.value = course.competencias || "";
|
|
competenciasInput.required = true;
|
|
} else {
|
|
competencesField.classList.add("oculto");
|
|
competenciasInput.value = "";
|
|
competenciasInput.required = false;
|
|
}
|
|
|
|
form.dataset.editing = "true";
|
|
form.dataset.courseId = id;
|
|
form.querySelector("button[type='submit']").textContent = "Actualizar Curso";
|
|
document.getElementById("cancelCourseBtn").style.display = "inline-block";
|
|
form.scrollIntoView({ behavior: "smooth" });
|
|
});
|
|
};
|
|
|
|
|
|
window.deleteCourse = function (id) {
|
|
if (!confirm("¿Estás seguro de eliminar este curso?")) return;
|
|
|
|
fetch(`api/cursos.php?id=${id}`, {
|
|
method: "DELETE",
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
showSection("courses");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
};
|
|
|
|
// Gestión de alumnos
|
|
function loadStudentsManagement(container) {
|
|
container.innerHTML = '<div class="loader">Cargando alumnos...</div>';
|
|
|
|
fetch("api/alumnos.php")
|
|
.then((response) => {
|
|
if (!response.ok) throw new Error("Error en la respuesta del servidor");
|
|
return response.json();
|
|
})
|
|
.then((data) => {
|
|
if (!data.success)
|
|
throw new Error(data.error || "Error al obtener alumnos");
|
|
|
|
container.innerHTML = `
|
|
<div class="students-management">
|
|
${renderStudentForm()}
|
|
${renderStudentsTable(data.data || [])}
|
|
</div>
|
|
`;
|
|
|
|
setupStudentForm();
|
|
(data.data || []).forEach((alumno) => loadStudentCourses(alumno.id));
|
|
})
|
|
.catch((error) => {
|
|
console.error("Error:", error);
|
|
container.innerHTML = `
|
|
<div class="card error-card">
|
|
<h2>Error al cargar alumnos</h2>
|
|
<p>${error.message}</p>
|
|
<button class="btn" onclick="loadStudentsManagement(this.closest('.content-section'))">
|
|
Reintentar
|
|
</button>
|
|
</div>`;
|
|
});
|
|
}
|
|
|
|
|
|
function renderStudentForm() {
|
|
return `
|
|
<div class="card">
|
|
<h2>Gestión de Alumnos</h2>
|
|
<form id="studentForm">
|
|
<div class="form-grid">
|
|
<div class="form-group">
|
|
<label for="nombre">Nombre*</label>
|
|
<input type="text" id="nombre" name="nombre" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="email">Email*</label>
|
|
<input type="email" id="email" name="email" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="telefono">Teléfono</label>
|
|
<input type="tel" id="telefono" name="telefono">
|
|
</div>
|
|
</div>
|
|
|
|
<div class="form-grid">
|
|
<div class="form-group">
|
|
<label for="tipoCurso">Tipo de Curso*</label>
|
|
<select id="tipoCurso" required>
|
|
<option value="">Seleccionar tipo</option>
|
|
<option value="inyeccion">Inyección</option>
|
|
<option value="pildora">Píldora</option>
|
|
<option value="tratamiento">Tratamiento</option>
|
|
</select>
|
|
</div>
|
|
|
|
<div class="form-group">
|
|
<label for="curso">Curso*</label>
|
|
<select id="curso" required>
|
|
<option value="">Selecciona primero un tipo</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="form-actions">
|
|
<button type="button" class="btn btn-outline" onclick="resetStudentForm()" id="cancelBtn" style="display:none;">
|
|
Cancelar
|
|
</button>
|
|
<button type="submit" class="btn">
|
|
<span id="submitText">Guardar</span>
|
|
<span class="spinner-border spinner-border-sm" id="submitSpinner" style="display:none;"></span>
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>`;
|
|
}
|
|
|
|
function setupStudentForm() {
|
|
const form = document.getElementById("studentForm");
|
|
if (!form) return;
|
|
|
|
// Referencias a selects
|
|
const tipoCurso = document.getElementById("tipoCurso");
|
|
const curso = document.getElementById("curso");
|
|
|
|
// Cargar cursos dinámicamente
|
|
tipoCurso.addEventListener("change", () => {
|
|
const tipo = tipoCurso.value;
|
|
curso.innerHTML = '<option value="">Cargando...</option>';
|
|
fetch(`api/cursos.php?tipo=${tipo}`)
|
|
.then((res) => res.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
curso.innerHTML = '<option value="">Seleccionar curso</option>';
|
|
data.data.forEach((c) => {
|
|
const opt = document.createElement("option");
|
|
opt.value = c.id;
|
|
opt.textContent = c.nombre;
|
|
curso.appendChild(opt);
|
|
});
|
|
} else {
|
|
curso.innerHTML = '<option value="">Sin resultados</option>';
|
|
}
|
|
})
|
|
.catch(() => {
|
|
curso.innerHTML = '<option value="">Error al cargar</option>';
|
|
});
|
|
});
|
|
|
|
// Guardar alumno
|
|
form.addEventListener("submit", function (e) {
|
|
e.preventDefault();
|
|
submitStudentForm(); // ✅ Usa función unificada que detecta si es edición o nuevo
|
|
});
|
|
|
|
const searchInput = document.getElementById("studentSearch");
|
|
if (searchInput) {
|
|
searchInput.addEventListener("input", function () {
|
|
filterStudents(this.value.toLowerCase());
|
|
});
|
|
}
|
|
}
|
|
|
|
function submitStudentForm() {
|
|
const form = document.getElementById("studentForm");
|
|
const submitBtn = form.querySelector('button[type="submit"]');
|
|
const submitText = document.getElementById("submitText");
|
|
const spinner = document.getElementById("submitSpinner");
|
|
|
|
// Mostrar spinner
|
|
submitText.textContent = "Procesando...";
|
|
spinner.style.display = "inline-block";
|
|
submitBtn.disabled = true;
|
|
|
|
const formData = new FormData(form);
|
|
const jsonData = {
|
|
nombre: formData.get("nombre"),
|
|
email: formData.get("email"),
|
|
telefono: formData.get("telefono"),
|
|
curso_id: document.getElementById("curso").value, // ✅ Cambio aquí
|
|
};
|
|
|
|
const isEdit = form.dataset.editing === "true";
|
|
const studentId = form.dataset.studentId;
|
|
const url = "api/alumnos.php";
|
|
const method = isEdit ? "PUT" : "POST";
|
|
|
|
if (isEdit) {
|
|
jsonData.id = studentId;
|
|
}
|
|
|
|
fetch(url, {
|
|
method: method,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(jsonData),
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (!data.success)
|
|
throw new Error(data.error || "Error al guardar alumno");
|
|
|
|
showToast(
|
|
"success",
|
|
data.message || (isEdit ? "Alumno actualizado" : "Alumno creado")
|
|
);
|
|
resetStudentForm();
|
|
loadStudentsManagement(document.querySelector("#students-content"));
|
|
})
|
|
.catch((error) => {
|
|
showToast("error", error.message || "Error en el servidor");
|
|
})
|
|
.finally(() => {
|
|
submitText.textContent = "Guardar";
|
|
spinner.style.display = "none";
|
|
submitBtn.disabled = false;
|
|
});
|
|
}
|
|
|
|
window.createStudent = function (data) {
|
|
fetch("api/alumnos.php", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(data),
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
showSection("students");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
};
|
|
|
|
window.updateStudent = function (id, data) {
|
|
data.id = id;
|
|
|
|
fetch("api/alumnos.php", {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(data),
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
showSection("students");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Error:", error));
|
|
};
|
|
|
|
window.editStudent = function (id) {
|
|
fetch(`api/alumnos.php`)
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (!data.success)
|
|
throw new Error(data.error || "Error al obtener alumnos");
|
|
|
|
const alumno = data.data.find((a) => a.id == id);
|
|
if (!alumno) throw new Error("Alumno no encontrado");
|
|
|
|
const form = document.getElementById("studentForm");
|
|
form.nombre.value = alumno.nombre;
|
|
form.email.value = alumno.email;
|
|
form.telefono.value = alumno.telefono || "";
|
|
|
|
form.dataset.editing = "true";
|
|
form.dataset.studentId = id;
|
|
|
|
document.getElementById("submitText").textContent = "Actualizar";
|
|
document.getElementById("cancelBtn").style.display = "inline-block";
|
|
|
|
// 👇 Precargar tipo y curso si el alumno tiene asignación
|
|
fetch(`api/alumnos-cursos.php?alumno_id=${id}`)
|
|
.then((res) => res.json())
|
|
.then((asignaciones) => {
|
|
if (asignaciones.success && asignaciones.data.length > 0) {
|
|
const curso = asignaciones.data[0];
|
|
const tipoCursoSelect = document.getElementById("tipoCurso");
|
|
const cursoSelect = document.getElementById("curso");
|
|
|
|
tipoCursoSelect.value = curso.tipo;
|
|
tipoCursoSelect.dispatchEvent(new Event("change"));
|
|
|
|
setTimeout(() => {
|
|
cursoSelect.value = curso.id;
|
|
}, 300);
|
|
}
|
|
});
|
|
|
|
form.scrollIntoView({ behavior: "smooth" });
|
|
})
|
|
.catch((error) => {
|
|
showToast("error", error.message || "Error al cargar alumno");
|
|
});
|
|
};
|
|
|
|
window.deleteStudent = function (id) {
|
|
if (!id) {
|
|
showToast("error", "ID de alumno no proporcionado");
|
|
return;
|
|
}
|
|
|
|
fetch(`api/alumnos.php?id=${id}`, {
|
|
method: "DELETE",
|
|
})
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (!data.success)
|
|
throw new Error(data.error || "Error al eliminar alumno");
|
|
|
|
showToast("success", data.message || "Alumno eliminado");
|
|
closeModal();
|
|
loadStudentsManagement(document.querySelector("#students-content"));
|
|
})
|
|
.catch((error) => {
|
|
showToast("error", error.message || "Error al eliminar alumno");
|
|
});
|
|
};
|
|
|
|
|
|
window.confirmDeleteStudent = function (id) {
|
|
showModal(
|
|
"Confirmar eliminación",
|
|
"¿Estás seguro de eliminar este alumno? Esta acción no se puede deshacer.",
|
|
[
|
|
{
|
|
text: "Cancelar",
|
|
class: "btn-outline",
|
|
handler: "closeModal",
|
|
},
|
|
{
|
|
text: "Eliminar",
|
|
class: "btn-danger",
|
|
handler: "deleteStudent(" + id + ")"
|
|
},
|
|
]
|
|
);
|
|
};
|
|
|
|
window.resetStudentForm = function () {
|
|
const form = document.getElementById("studentForm");
|
|
form.reset();
|
|
form.dataset.editing = "false";
|
|
delete form.dataset.studentId;
|
|
|
|
document.getElementById("submitText").textContent = "Guardar";
|
|
document.getElementById("cancelBtn").style.display = "none";
|
|
};
|
|
function filterStudents(searchTerm) {
|
|
const rows = document.querySelectorAll(".students-table tbody tr");
|
|
|
|
rows.forEach((row) => {
|
|
const nombre = row.cells[0].textContent.toLowerCase();
|
|
const email = row.cells[1].textContent.toLowerCase();
|
|
const telefono = row.cells[2].textContent.toLowerCase();
|
|
|
|
if (
|
|
nombre.includes(searchTerm) ||
|
|
email.includes(searchTerm) ||
|
|
telefono.includes(searchTerm)
|
|
) {
|
|
row.style.display = "";
|
|
} else {
|
|
row.style.display = "none";
|
|
}
|
|
});
|
|
}
|
|
|
|
//alumnos-cursos
|
|
|
|
function renderStudentsTable(alumnos) {
|
|
if (alumnos.length === 0) {
|
|
return `
|
|
<div class="card">
|
|
<div class="no-data">
|
|
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#64748b">
|
|
<path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
|
|
<circle cx="8.5" cy="7" r="4"></circle>
|
|
<line x1="18" y1="8" x2="23" y2="13"></line>
|
|
<line x1="23" y1="8" x2="18" y2="13"></line>
|
|
</svg>
|
|
<h3>No hay alumnos registrados</h3>
|
|
<p>Comienza agregando tu primer alumno</p>
|
|
</div>
|
|
</div>`;
|
|
}
|
|
|
|
return `
|
|
<div class="card">
|
|
<div class="card-header">
|
|
<h2>Lista de Alumnos</h2>
|
|
<div class="header-actions">
|
|
<div class="search-box">
|
|
<input type="text" id="studentSearch" placeholder="Buscar alumno...">
|
|
</div>
|
|
|
|
</div>
|
|
</div>
|
|
<div class="table-responsive">
|
|
<table class="students-table">
|
|
<thead>
|
|
<tr>
|
|
<th>Nombre</th>
|
|
<th>Email</th>
|
|
<th>Teléfono</th>
|
|
<th>Cursos</th>
|
|
<th>Acciones</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${alumnos
|
|
.map(
|
|
(alumno) => `
|
|
<tr>
|
|
<td>${alumno.nombre}</td>
|
|
<td>${alumno.email}</td>
|
|
<td>${alumno.telefono || "-"}</td>
|
|
<td>
|
|
<div class="course-badges" id="courses-${alumno.id}">
|
|
${renderCourseBadges(alumno.id)}
|
|
</div>
|
|
</td>
|
|
<td>
|
|
<div class="action-buttons">
|
|
<button class="btn btn-sm btn-edit" onclick="editStudent(${
|
|
alumno.id
|
|
})">
|
|
Editar
|
|
</button>
|
|
<button class="btn btn-sm btn-danger" onclick="confirmDeleteStudent(${
|
|
alumno.id
|
|
})">
|
|
Eliminar
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
`
|
|
)
|
|
.join("")}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>`;
|
|
}
|
|
|
|
function renderCourseBadges(alumnoId) {
|
|
return '<div class="loader-sm"></div>'; // Se cargará dinámicamente
|
|
}
|
|
|
|
async function loadStudentCourses(alumnoId) {
|
|
try {
|
|
const response = await fetch(
|
|
`api/alumnos-cursos.php?alumno_id=${alumnoId}`
|
|
);
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
const container = document.getElementById(`courses-${alumnoId}`);
|
|
if (container) {
|
|
container.innerHTML =
|
|
data.data
|
|
.map(
|
|
(curso) => `
|
|
<span class="badge course-badge">
|
|
${curso.nombre}
|
|
<button class="badge-remove" onclick="unassignStudent(${alumnoId}, ${curso.id})">
|
|
×
|
|
</button>
|
|
</span>
|
|
`
|
|
)
|
|
.join("") || '<span class="text-muted">Sin cursos</span>';
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("Error loading student courses:", error);
|
|
}
|
|
}
|
|
|
|
window.showAssignStudentModal = async function () {
|
|
try {
|
|
console.log("Mostrando modal de vinculación");
|
|
|
|
const profesorId = getProfesorId();
|
|
if (!profesorId) {
|
|
console.error("No se pudo obtener el ID del profesor");
|
|
showToast("error", "No se pudo identificar al profesor");
|
|
return;
|
|
}
|
|
|
|
// Mostrar loader mientras se cargan los datos
|
|
const tempModalContent = `<div class="loader">Cargando datos...</div>`;
|
|
showModal("Vincular Alumnos a Curso", tempModalContent);
|
|
|
|
// Cargar cursos y alumnos en paralelo
|
|
const [cursosRes, alumnosRes] = await Promise.all([
|
|
fetch(`api/cursos.php?profesor_id=${profesorId}`),
|
|
fetch("api/alumnos.php"),
|
|
]);
|
|
|
|
const [cursosData, alumnosData] = await Promise.all([
|
|
cursosRes.json(),
|
|
alumnosRes.json(),
|
|
]);
|
|
|
|
if (!cursosData || !alumnosData || !alumnosData.success) {
|
|
closeModal();
|
|
throw new Error("Error al cargar datos necesarios");
|
|
}
|
|
|
|
// Crear contenido del modal
|
|
const modalHtml = `
|
|
<div class="form-group">
|
|
<label>Seleccionar Curso</label>
|
|
<select id="selectCurso" class="form-control">
|
|
${cursosData
|
|
.map(
|
|
(curso) => `<option value="${curso.id}">${curso.nombre}</option>`
|
|
)
|
|
.join("")}
|
|
</select>
|
|
</div>
|
|
|
|
<div class="form-group">
|
|
<label>Seleccionar Alumnos</label>
|
|
<div class="checkbox-group">
|
|
${
|
|
alumnosData.data.length > 0
|
|
? alumnosData.data
|
|
.map(
|
|
(alumno) => `
|
|
<label>
|
|
<input type="checkbox" name="alumnos" value="${alumno.id}">
|
|
${alumno.nombre} (${alumno.email})
|
|
</label>
|
|
`
|
|
)
|
|
.join("")
|
|
: "<p>No hay alumnos disponibles</p>"
|
|
}
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
// Actualizar el contenido del modal
|
|
const modalBody = document.querySelector(".modal-body");
|
|
if (modalBody) {
|
|
modalBody.innerHTML = modalHtml;
|
|
}
|
|
|
|
// Crear el footer si no existe
|
|
let modalFooter = document.querySelector(".modal-footer");
|
|
if (!modalFooter) {
|
|
modalFooter = document.createElement("div");
|
|
modalFooter.className = "modal-footer";
|
|
document.querySelector(".modal").appendChild(modalFooter);
|
|
}
|
|
|
|
// Actualizar el contenido del footer
|
|
modalFooter.innerHTML = `
|
|
<button class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
|
|
<button class="btn btn-primary" onclick="assignStudentsToCourse()">Confirmar Vinculación</button>
|
|
`;
|
|
|
|
// Función para vincular alumnos seleccionados
|
|
window.assignStudentsToCourse = async function () {
|
|
const cursoId = document.getElementById("selectCurso").value;
|
|
const selectedAlumnos = Array.from(
|
|
document.querySelectorAll('input[name="alumnos"]:checked')
|
|
).map((input) => input.value);
|
|
|
|
if (selectedAlumnos.length === 0) {
|
|
showToast("warning", "Selecciona al menos un alumno");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch("api/alumnos-cursos.php", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
curso_id: cursoId,
|
|
alumnos: selectedAlumnos,
|
|
}),
|
|
});
|
|
|
|
const result = await response.json();
|
|
if (result.success) {
|
|
showToast("success", "Alumnos vinculados exitosamente");
|
|
closeModal();
|
|
loadStudentsManagement(document.querySelector("#students-content"));
|
|
} else {
|
|
showToast("error", result.error || "Error al vincular");
|
|
}
|
|
} catch (error) {
|
|
console.error("Error al vincular:", error);
|
|
showToast("error", "Error al realizar la vinculación");
|
|
}
|
|
};
|
|
} catch (error) {
|
|
console.error("Error en showAssignStudentModal:", error);
|
|
closeModal();
|
|
showToast("error", "Error al cargar datos para vinculación");
|
|
}
|
|
};
|
|
|
|
window.unassignStudent = async function (alumnoId, cursoId) {
|
|
if (confirm("¿Desvincular este alumno del curso?")) {
|
|
try {
|
|
const response = await fetch(
|
|
`api/alumnos-cursos.php?alumno_id=${alumnoId}&curso_id=${cursoId}`,
|
|
{
|
|
method: "DELETE",
|
|
}
|
|
);
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
showToast("success", data.message);
|
|
loadStudentCourses(alumnoId);
|
|
} else {
|
|
showToast("error", data.error || "Error al desvincular");
|
|
}
|
|
} catch (error) {
|
|
showToast("error", "Error en la conexión");
|
|
}
|
|
}
|
|
};
|
|
|
|
// Gestión de diplomas
|
|
function loadDiplomasSection(container) {
|
|
container.innerHTML = '<div class="loader">Cargando diplomas...</div>';
|
|
|
|
fetch(`api/diplomas.php?profesor_id=${getProfesorId()}`)
|
|
.then((response) => {
|
|
if (!response.ok) throw new Error("Error en la respuesta del servidor");
|
|
return response.json();
|
|
})
|
|
.then((data) => {
|
|
if (!data.success)
|
|
throw new Error(data.error || "Error al obtener diplomas");
|
|
|
|
if (data.data.length === 0) {
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Diplomas Emitidos</h2>
|
|
<p>No hay diplomas registrados aún</p>
|
|
</div>`;
|
|
return;
|
|
}
|
|
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Diplomas Emitidos</h2>
|
|
<div class="table-container">
|
|
<table class="diplomas-table">
|
|
<thead>
|
|
<tr>
|
|
<th>Alumno</th>
|
|
<th>Email</th>
|
|
<th>Curso</th>
|
|
<th>Tipo</th>
|
|
<th>Fecha</th>
|
|
<th>Código</th>
|
|
<th>Acciones</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${data.data
|
|
.map(
|
|
(diploma) => `
|
|
<tr>
|
|
<td>${diploma.alumno_nombre}</td>
|
|
<td>${diploma.alumno_email}</td>
|
|
<td>${diploma.curso_nombre}</td>
|
|
<td><span class="badge ${getCourseTypeClass(
|
|
diploma.curso_tipo
|
|
)}">${diploma.curso_tipo}</span></td>
|
|
<td>${diploma.fecha_formateada}</td>
|
|
<td class="code">${diploma.codigo_unico}</td>
|
|
<td>
|
|
<button class="btn btn-sm" onclick="downloadDiploma('${
|
|
diploma.codigo_unico
|
|
}')">
|
|
Descargar
|
|
</button>
|
|
<button class="btn btn-sm" onclick="resendDiploma('${
|
|
diploma.codigo_unico
|
|
}')">
|
|
Reenviar
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
`
|
|
)
|
|
.join("")}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>`;
|
|
})
|
|
.catch((error) => {
|
|
console.error("Error:", error);
|
|
container.innerHTML = `
|
|
<div class="card error-card">
|
|
<h2>Error al cargar diplomas</h2>
|
|
<p>${error.message}</p>
|
|
<button class="btn" onclick="loadDiplomasSection(this.parentElement)">
|
|
Reintentar
|
|
</button>
|
|
</div>`;
|
|
});
|
|
}
|
|
|
|
// Funciones auxiliares
|
|
function generateCoursesPreview(courses) {
|
|
if (!courses.length) return "<p>No tienes cursos activos</p>";
|
|
|
|
return `
|
|
<div class="table-container">
|
|
<table class="preview-table">
|
|
<thead>
|
|
<tr>
|
|
<th>Nombre</th>
|
|
<th>Tipo</th>
|
|
<th>Estado</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${courses
|
|
.map(
|
|
(course) => `
|
|
<tr>
|
|
<td>${course.nombre || "Sin nombre"}</td>
|
|
<td><span class="badge ${getCourseTypeClass(course.tipo)}">${
|
|
course.tipo || "N/A"
|
|
}</span></td>
|
|
<td><span class="badge ${
|
|
course.estado === "activo" ? "active" : "inactive"
|
|
}">${course.estado || "N/A"}</span></td>
|
|
</tr>
|
|
`
|
|
)
|
|
.join("")}
|
|
</tbody>
|
|
</table>
|
|
</div>`;
|
|
}
|
|
|
|
function getCourseTypeClass(type) {
|
|
const types = {
|
|
inyeccion: "type-inyeccion",
|
|
pildora: "type-pildora",
|
|
tratamiento: "type-tratamiento",
|
|
};
|
|
return types[type] || "";
|
|
}
|
|
|
|
// Funciones globales para diplomas
|
|
window.downloadDiploma = function (codigo) {
|
|
window.open(`certificado.php?codigo=${codigo}`, "_blank");
|
|
};
|
|
|
|
window.resendDiploma = function (codigo) {
|
|
fetch(`api/diplomas.php?action=resend&codigo=${codigo}`)
|
|
.then((response) => response.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
alert("Diploma reenviado exitosamente");
|
|
} else {
|
|
alert("Error: " + (data.error || "No se pudo reenviar el diploma"));
|
|
}
|
|
})
|
|
.catch((error) => {
|
|
console.error("Error:", error);
|
|
alert("Error al reenviar el diploma");
|
|
});
|
|
};
|