440 lines
13 KiB
JavaScript
440 lines
13 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') || document.body.classList.contains('user')) {
|
|
initializeDashboard();
|
|
}
|
|
});
|
|
|
|
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));
|
|
}
|
|
|
|
function initializeDashboard() {
|
|
// Configurar eventos del menú lateral
|
|
setupSidebarNavigation();
|
|
|
|
// Cargar datos iniciales
|
|
loadInitialData();
|
|
|
|
// Mostrar la sección activa inicial
|
|
const activeSection = document.querySelector('.sidebar-menu li.active');
|
|
if (activeSection) {
|
|
const sectionId = activeSection.getAttribute('data-section');
|
|
showSection(sectionId, true); // true indica que es la carga inicial
|
|
}
|
|
}
|
|
|
|
function setupSidebarNavigation() {
|
|
document.querySelectorAll('.sidebar-menu li').forEach(item => {
|
|
item.addEventListener('click', function() {
|
|
const section = this.getAttribute('data-section');
|
|
showSection(section);
|
|
});
|
|
});
|
|
}
|
|
|
|
function loadInitialData() {
|
|
fetch('api/cursos.php')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (document.body.classList.contains('admin')) {
|
|
updateAdminStats(data);
|
|
} else {
|
|
updateUserStats(data);
|
|
}
|
|
})
|
|
.catch(error => console.error('Error:', error));
|
|
}
|
|
|
|
function updateAdminStats(courses) {
|
|
document.getElementById('active-courses-count').textContent = courses.length;
|
|
// Aquí puedes agregar más llamadas para estudiantes y diplomas
|
|
// fetch('api/estudiantes.php')...
|
|
// fetch('api/diplomas.php')...
|
|
}
|
|
|
|
function updateUserStats(courses) {
|
|
document.getElementById('user-courses-count').textContent = courses.length;
|
|
const approvedCourses = courses.filter(c => c.estado === 'Aprobado');
|
|
document.getElementById('user-diplomas-count').textContent = approvedCourses.length;
|
|
window.userCourses = courses;
|
|
|
|
// Mostrar los primeros 5 cursos en el dashboard
|
|
renderDashboardCourses(courses.slice(0, 5));
|
|
setupDashboardPagination(courses);
|
|
setupDashboardSearch();
|
|
}
|
|
function renderDashboardCourses(courses) {
|
|
const tbody = document.getElementById('dashboard-courses-body');
|
|
if (!tbody) return;
|
|
|
|
tbody.innerHTML = courses.map(course => `
|
|
<tr>
|
|
<td>${course.nombre}</td>
|
|
<td>${course.fecha_inicio || '-'}</td>
|
|
<td>${course.fecha_fin || '-'}</td>
|
|
<td>
|
|
${course.estado === 'Aprobado' ?
|
|
`<button class="btn download-btn" data-course-id="${course.id}">Descargar</button>` :
|
|
'No disponible'}
|
|
</td>
|
|
</tr>
|
|
`).join('');
|
|
|
|
// Configurar eventos de descarga
|
|
document.querySelectorAll('.download-btn').forEach(btn => {
|
|
btn.addEventListener('click', function() {
|
|
const courseId = this.getAttribute('data-course-id');
|
|
window.open(`certificado.php?course_id=${courseId}`, '_blank');
|
|
});
|
|
});
|
|
}
|
|
|
|
function setupDashboardPagination(allCourses) {
|
|
let currentPage = 1;
|
|
const perPage = 5;
|
|
const totalPages = Math.ceil(allCourses.length / perPage);
|
|
|
|
function updatePagination() {
|
|
const start = (currentPage - 1) * perPage;
|
|
const end = start + perPage;
|
|
renderDashboardCourses(allCourses.slice(start, end));
|
|
|
|
document.getElementById('page-info').textContent = `Página ${currentPage} de ${totalPages}`;
|
|
document.getElementById('prev-page').disabled = currentPage === 1;
|
|
document.getElementById('next-page').disabled = currentPage === totalPages || totalPages === 0;
|
|
}
|
|
|
|
document.getElementById('prev-page')?.addEventListener('click', () => {
|
|
if (currentPage > 1) {
|
|
currentPage--;
|
|
updatePagination();
|
|
}
|
|
});
|
|
|
|
document.getElementById('next-page')?.addEventListener('click', () => {
|
|
if (currentPage < totalPages) {
|
|
currentPage++;
|
|
updatePagination();
|
|
}
|
|
});
|
|
|
|
updatePagination();
|
|
}
|
|
|
|
function setupDashboardSearch() {
|
|
const searchBtn = document.getElementById('dashboard-search-btn');
|
|
const searchInput = document.getElementById('dashboard-course-search');
|
|
|
|
if (searchBtn && searchInput) {
|
|
searchBtn.addEventListener('click', () => {
|
|
const term = searchInput.value.toLowerCase();
|
|
const filtered = window.userCourses.filter(course =>
|
|
course.nombre.toLowerCase().includes(term) ||
|
|
course.tipo.toLowerCase().includes(term) ||
|
|
course.estado.toLowerCase().includes(term)
|
|
);
|
|
|
|
setupDashboardPagination(filtered);
|
|
});
|
|
|
|
// Permitir búsqueda al presionar Enter
|
|
searchInput.addEventListener('keypress', (e) => {
|
|
if (e.key === 'Enter') {
|
|
searchBtn.click();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
function showSection(sectionId, isInitialLoad = false) {
|
|
// Actualizar menú activo
|
|
updateActiveMenu(sectionId);
|
|
|
|
// Mostrar la sección correspondiente
|
|
const sectionElement = getSectionElement(sectionId);
|
|
if (sectionElement) {
|
|
toggleSections(sectionElement);
|
|
|
|
// Solo cargar contenido dinámico si no es la carga inicial del dashboard
|
|
if (!(isInitialLoad && sectionId === 'dashboard')) {
|
|
if (sectionId === 'dashboard') {
|
|
// Recargar los datos del dashboard
|
|
loadInitialData();
|
|
} else {
|
|
loadDynamicContent(sectionId, sectionElement);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateActiveMenu(sectionId) {
|
|
document.querySelectorAll('.sidebar-menu li').forEach(li => {
|
|
li.classList.remove('active');
|
|
});
|
|
document.querySelector(`.sidebar-menu li[data-section="${sectionId}"]`).classList.add('active');
|
|
}
|
|
|
|
function getSectionElement(sectionId) {
|
|
if (sectionId === 'dashboard') {
|
|
return document.getElementById('dashboard-content');
|
|
}
|
|
return document.getElementById(`${sectionId}-content`);
|
|
}
|
|
|
|
function toggleSections(activeSection) {
|
|
document.querySelectorAll('.content-section').forEach(section => {
|
|
section.classList.remove('active');
|
|
});
|
|
activeSection.classList.add('active');
|
|
}
|
|
|
|
function loadDynamicContent(sectionId, container) {
|
|
// Mostrar loader mientras se carga
|
|
container.innerHTML = '<div class="loader">Cargando...</div>';
|
|
|
|
switch(sectionId) {
|
|
case 'courses':
|
|
loadAdminCourses(container);
|
|
break;
|
|
case 'students':
|
|
loadAdminStudents(container);
|
|
break;
|
|
case 'my-courses':
|
|
loadUserCourses(container);
|
|
break;
|
|
case 'diplomas':
|
|
loadUserDiplomas(container);
|
|
break;
|
|
case 'profile':
|
|
loadProfileSection(container);
|
|
break;
|
|
default:
|
|
container.innerHTML = '<div class="card"><h2>Sección no implementada</h2></div>';
|
|
}
|
|
}
|
|
|
|
// Funciones para cargar contenido específico
|
|
function loadAdminCourses(container) {
|
|
fetch('api/cursos.php')
|
|
.then(response => response.json())
|
|
.then(courses => {
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Gestión de Cursos</h2>
|
|
<form id="courseForm">
|
|
<label>Nombre del Curso</label>
|
|
<input type="text" name="nombre" placeholder="Ej. Seguridad Informática" required>
|
|
|
|
<label>Tipo de Curso</label>
|
|
<select id="courseType" name="tipo" required>
|
|
<option value="">Seleccionar</option>
|
|
<option value="pildora">Píldora</option>
|
|
<option value="inyeccion">Inyección</option>
|
|
<option value="tratamiento">Tratamiento</option>
|
|
</select>
|
|
|
|
<div id="competencesField" class="oculto">
|
|
<label>Competencias Asociadas</label>
|
|
<input type="text" name="competencias" placeholder="Ej. Análisis de datos, Comunicación efectiva">
|
|
</div>
|
|
|
|
<button class="btn" type="submit">Guardar Curso</button>
|
|
</form>
|
|
</div>
|
|
<div class="card">
|
|
<h2>Lista de Cursos</h2>
|
|
<div class="course-list">
|
|
${generateCoursesList(courses)}
|
|
</div>
|
|
</div>`;
|
|
|
|
setupCourseForm();
|
|
})
|
|
.catch(error => {
|
|
container.innerHTML = '<div class="card"><h2>Error al cargar los cursos</h2></div>';
|
|
console.error('Error:', error);
|
|
});
|
|
}
|
|
|
|
function loadUserCourses(container) {
|
|
const courses = window.userCourses || [];
|
|
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Mis Cursos</h2>
|
|
<div class="search-container">
|
|
<input type="text" id="courseSearch" placeholder="Buscar cursos..." class="search-input">
|
|
<button class="btn" id="searchButton">Buscar</button>
|
|
</div>
|
|
<div class="course-list">
|
|
${courses.length > 0 ?
|
|
courses.map(course => generateCourseCard(course)).join('') :
|
|
'<p>No tienes cursos registrados.</p>'}
|
|
</div>
|
|
</div>`;
|
|
|
|
setupCourseSearch();
|
|
}
|
|
|
|
function loadUserDiplomas(container) {
|
|
const courses = (window.userCourses || []).filter(c => c.estado === 'Aprobado');
|
|
|
|
container.innerHTML = `
|
|
<div class="card">
|
|
<h2>Mis Diplomas</h2>
|
|
${courses.length > 0 ?
|
|
courses.map(course => generateDiplomaCard(course)).join('') :
|
|
'<p>No tienes diplomas disponibles todavía.</p>'}
|
|
</div>`;
|
|
|
|
setupDiplomaDownloads();
|
|
}
|
|
|
|
// Funciones auxiliares
|
|
function generateCoursesList(courses) {
|
|
return courses.map(course => `
|
|
<div class="course-card">
|
|
<h3>${course.nombre}</h3>
|
|
<p>Tipo: ${course.tipo}</p>
|
|
<p>ID: ${course.id}</p>
|
|
</div>
|
|
`).join('');
|
|
}
|
|
|
|
function generateCourseCard(course) {
|
|
return `
|
|
<div class="course-card">
|
|
<h3>${course.nombre}</h3>
|
|
<p>Tipo: ${course.tipo}</p>
|
|
<p>Estado: ${course.estado}</p>
|
|
${course.competencias ? `<p>Competencias: ${course.competencias}</p>` : ''}
|
|
<p>Profesor: ${course.profesor || 'No asignado'}</p>
|
|
<p>Fecha: ${course.fecha_inicio} a ${course.fecha_fin}</p>
|
|
</div>`;
|
|
}
|
|
|
|
function generateDiplomaCard(course) {
|
|
return `
|
|
<div class="diploma-preview">
|
|
<h3>Diploma de ${course.nombre}</h3>
|
|
<p>Fecha: ${course.fecha_fin || 'Completado'}</p>
|
|
<p>Profesor: ${course.profesor || 'No especificado'}</p>
|
|
<button class="btn download-btn"
|
|
data-course-id="${course.id}"
|
|
data-course-name="${course.nombre}">
|
|
Descargar Diploma
|
|
</button>
|
|
</div>`;
|
|
}
|
|
|
|
// Configuración de eventos dinámicos
|
|
function setupCourseForm() {
|
|
const courseTypeSelect = document.getElementById('courseType');
|
|
if (courseTypeSelect) {
|
|
courseTypeSelect.addEventListener('change', function() {
|
|
const competencesField = document.getElementById('competencesField');
|
|
if (competencesField) {
|
|
competencesField.classList.toggle('oculto', this.value !== 'tratamiento');
|
|
}
|
|
});
|
|
}
|
|
|
|
const courseForm = document.getElementById('courseForm');
|
|
if (courseForm) {
|
|
courseForm.addEventListener('submit', function(e) {
|
|
e.preventDefault();
|
|
const formData = new FormData(this);
|
|
const jsonData = {};
|
|
formData.forEach((value, key) => jsonData[key] = value);
|
|
|
|
fetch('api/cursos.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(jsonData)
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success) {
|
|
alert('Curso creado exitosamente');
|
|
showSection('courses');
|
|
} else {
|
|
alert('Error al crear el curso');
|
|
}
|
|
})
|
|
.catch(error => console.error('Error:', error));
|
|
});
|
|
}
|
|
}
|
|
|
|
function setupCourseSearch() {
|
|
const searchButton = document.getElementById('searchButton');
|
|
if (searchButton) {
|
|
searchButton.addEventListener('click', function() {
|
|
const searchTerm = document.getElementById('courseSearch').value.toLowerCase();
|
|
const courses = window.userCourses || [];
|
|
const filteredCourses = courses.filter(course =>
|
|
course.nombre.toLowerCase().includes(searchTerm) ||
|
|
(course.profesor && course.profesor.toLowerCase().includes(searchTerm))
|
|
);
|
|
|
|
const courseList = document.querySelector('.course-list');
|
|
if (courseList) {
|
|
courseList.innerHTML = filteredCourses.length > 0 ?
|
|
filteredCourses.map(course => generateCourseCard(course)).join('') :
|
|
'<p>No se encontraron cursos que coincidan con la búsqueda.</p>';
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
function setupDiplomaDownloads() {
|
|
document.querySelectorAll('.download-btn').forEach(btn => {
|
|
btn.addEventListener('click', function() {
|
|
|
|
|
|
// Mostrar mensaje de carga
|
|
const originalText = this.innerHTML;
|
|
this.innerHTML = '<span class="loading-text">Generando diploma...</span>';
|
|
this.disabled = true;
|
|
|
|
// Abrir en nueva pestaña en lugar de usar fetch
|
|
window.open(`certificado.php`, '_blank');
|
|
|
|
// Restaurar botón después de un breve retraso
|
|
setTimeout(() => {
|
|
this.innerHTML = originalText;
|
|
this.disabled = false;
|
|
}, 2000);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Funciones de secciones no implementadas (para completar)
|
|
function loadAdminStudents(container) {
|
|
container.innerHTML = '<div class="card"><h2>Gestión de Estudiantes</h2><p>Sección en desarrollo</p></div>';
|
|
}
|
|
|
|
function loadProfileSection(container) {
|
|
container.innerHTML = '<div class="card"><h2>Perfil de Usuario</h2><p>Sección en desarrollo</p></div>';
|
|
} |