Files
MVE/views/preferencias/notificaciones.php
2025-07-04 12:57:56 -06:00

634 lines
26 KiB
PHP

<?php include __DIR__ . '/../partials/sidebar_configuracion.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>🔔 Gestión de Notificaciones</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<!-- Animate.css para animaciones adicionales -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
<style>
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
.sidebar .nav-link { font-weight: bold; color: white; transition: all 0.3s ease; }
.sidebar .nav-link:hover,
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
.navbar { position: fixed; top: 0; width: 100%; z-index: 1050; }
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
@media (min-width: 768px) { .content { margin-left: 250px; } }
/* En móviles, sin margen lateral */
@media (max-width: 767.98px) {
.content { margin-left: 0; }
.sidebar .nav-link { font-weight: normal; color: #343a40; background-color: transparent; }
.sidebar .nav-link:hover,
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
}
.card { border-radius: 12px; }
.fade-transition { transition: all 0.3s ease-in-out; }
.section-divider { border-bottom: 1px solid #e9ecef; padding-bottom: 1.5rem; margin-bottom: 1.5rem; }
.section-divider:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.save-indicator { position: fixed; top: 20px; right: 20px; background: #28a745; color: white; padding: 10px 20px; border-radius: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 1050; display: flex; align-items: center; font-size: 14px; transition: all 0.3s ease; }
.success-message { background: #d4edda; color: #155724; padding: 12px 16px; border-radius: 8px; border: 1px solid #c3e6cb; margin-bottom: 20px; }
.error-message { background: #f8d7da; color: #721c24; padding: 12px 16px; border-radius: 8px; border: 1px solid #f5c6cb; margin-bottom: 20px; }
.resumen-config { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; margin-top: 15px; }
.time-input { max-width: 120px; }
.days-selector { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; }
.day-option { flex: 1; min-width: 45px; text-align: center; }
.day-preset { margin-bottom: 15px; }
.day-preset .btn { margin-right: 10px; margin-bottom: 5px; }
.form-check-input:checked { background-color: #0d6efd; border-color: #0d6efd; }
.btn-outline-primary.active { background-color: #0d6efd; border-color: #0d6efd; color: white; }
</style>
</head>
<body>
<div class="content">
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-4 animate__animated animate__fadeInDown title_glow">🔔 Gestión de Notificaciones</h4>
</div>
<!-- Mensajes de éxito o error iniciales -->
<?php if (isset($_GET['success'])): ?>
<div class="success-message">
✅ Las preferencias de notificación se han guardado correctamente.
</div>
<?php endif; ?>
<?php if (isset($_GET['error'])): ?>
<div class="error-message">
❌ Error: <?= htmlspecialchars($_GET['error']) ?>
</div>
<?php endif; ?>
<div class="card shadow-sm p-4 mb-4 bg-white card-hover position-relative h-auto">
<!-- Switch general de notificaciones -->
<div class="section-divider">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="notificaciones"
data-tipo="notificaciones_general"
<?= $notificaciones['notificaciones'] ? 'checked' : '' ?>>
<label class="form-check-label fw-bold" for="notificaciones">
Recibir notificaciones del sistema
</label>
<div class="form-text">Activa o desactiva todas las notificaciones del sistema</div>
</div>
</div>
<!-- Tipos de notificaciones -->
<div id="tipos-notificaciones" class="fade-transition" style="opacity:1;">
<div class="section-divider">
<h6 class="mb-3">📋 Tipos de Notificaciones</h6>
<div class="row">
<?php foreach ($preferencias as $campo => $valor): ?>
<?php if (in_array($campo, ['resumen_diario_hora', 'resumen_diario_dias'])): continue; endif; ?>
<div class="col-md-6 mb-3">
<div class="form-check form-switch">
<input class="form-check-input tipo-notificacion" type="checkbox"
name="<?= $campo ?>" id="<?= $campo ?>"
data-tipo="tipo_notificacion" data-nombre="<?= $campo ?>"
<?= !empty($valor) ? 'checked' : '' ?>>
<label class="form-check-label" for="<?= $campo ?>">
<strong><?= ucwords(str_replace('_', ' ', $campo)) ?></strong>
<div class="form-text">
<?= $tipos[$campo] ?? 'Configuración de ' . str_replace('_', ' ', $campo) ?>
</div>
</label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<!-- Configuración específica del resumen diario -->
<div id="resumen-diario-config" class="fade-transition" style="display: none; opacity: 0;">
<div class="resumen-config">
<h6 class="mb-3">⏰ Configuración del Resumen Diario</h6>
<div class="row">
<div class="col-md-6 mb-3">
<label for="resumen_hora" class="form-label fw-bold">Hora de envío</label>
<input type="time" class="form-control time-input" id="resumen_hora"
name="resumen_hora" value="<?= $preferencias['resumen_diario_hora'] ?? '08:00' ?>">
<div class="form-text">Hora en que se enviará el resumen diario</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label fw-bold">Días de envío</label>
<!-- Botones de preselección -->
<div class="day-preset">
<button type="button" class="btn btn-outline-primary btn-sm preset-btn active" data-preset="L-V">Lunes a Viernes</button>
<button type="button" class="btn btn-outline-primary btn-sm preset-btn" data-preset="TODOS">Todos los días</button>
<button type="button" class="btn btn-outline-primary btn-sm preset-btn" data-preset="PERSONALIZADO"> Personalizado</button>
</div>
<!-- Selector individual de días -->
<div class="days-selector" id="days-selector" style="display: none;">
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="L" id="day-L" name="dias[]">
<label class="form-check-label" for="day-L">L</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="M" id="day-M" name="dias[]">
<label class="form-check-label" for="day-M">M</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="X" id="day-X" name="dias[]">
<label class="form-check-label" for="day-X">X</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="J" id="day-J" name="dias[]">
<label class="form-check-label" for="day-J">J</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="V" id="day-V" name="dias[]">
<label class="form-check-label" for="day-V">V</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="S" id="day-S" name="dias[]">
<label class="form-check-label" for="day-S">S</label>
</div>
</div>
<div class="day-option">
<div class="form-check">
<input class="form-check-input day-checkbox" type="checkbox"
value="D" id="day-D" name="dias[]">
<label class="form-check-label" for="day-D">D</label>
</div>
</div>
</div>
<input type="hidden" id="resumen_dias" name="resumen_dias" value="<?= $preferencias['resumen_diario_dias'] ?? 'L-V' ?>">
<div class="form-text">Días en que se enviará el resumen diario</div>
</div>
</div>
<div class="alert alert-info d-flex align-items-center mt-3">
<i class="fas fa-info-circle me-2"></i>
<small>
El resumen diario se enviará automáticamente a la hora configurada,
únicamente en los días seleccionados y solo si hay actividad de solicitudes.
</small>
</div>
</div>
</div>
</div>
<br>
<!-- Configuración de correo adicional -->
<div class="section-divider">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="notificaciones_extra"
data-tipo="notificaciones_extra"
<?= $notificaciones['notificaciones_extra'] ? 'checked' : '' ?>>
<label class="form-check-label fw-bold" for="notificaciones_extra">Enviar notificaciones a correo adicional</label>
<div class="form-text">Recibe una copia de las notificaciones en un correo adicional</div>
</div>
<!-- Campo informativo del correo adicional -->
<div id="correo-extra-section" class="correo-extra-section fade-transition"
<?= !$notificaciones['notificaciones_extra'] ? 'style="display:none; opacity:0;"' : 'style="opacity:1;"' ?>>
<?php if (!empty($correoExtra)): ?>
<div class="alert alert-info d-flex align-items-center">
<div>
<strong>📧 Correo adicional configurado:</strong><br>
<code><?= htmlspecialchars($correoExtra) ?></code>
<div class="form-text mt-1">
Las notificaciones se enviarán también a este correo.
<a href="/IMPORTADORES/seguridad/index" class="text-decoration-none">Gestionar en Seguridad →</a>
</div>
</div>
</div>
<?php else: ?>
<div class="alert alert-warning d-flex align-items-center">
<div class="me-3">
<i class="fas fa-exclamation-triangle" style="font-size: 1.2em;"></i>
</div>
<div>
<strong>⚠️ No hay correo adicional registrado</strong><br>
<div class="form-text">
Para usar esta función, primero debes registrar un correo adicional en la sección de Seguridad.
<a href="/IMPORTADORES/seguridad/index" class="text-decoration-none">Ir a Seguridad →</a>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<!-- Indicador de guardado -->
<div id="save-indicator" class="save-indicator" style="display: none;">
<span class="indicator-text">Guardando...</span>
<div class="spinner-border spinner-border-sm ms-2" style="display: none;"></div>
</div>
<script>
// Estado global para controlar las peticiones
let isAutoSaving = false;
let saveTimeout = null;
// Referencias a elementos
const saveIndicator = document.getElementById('save-indicator');
const indicatorText = saveIndicator.querySelector('.indicator-text');
const spinner = saveIndicator.querySelector('.spinner-border');
// Función para mostrar indicador de guardado
function showSaveIndicator(type, message) {
// Limpiar clases anteriores
saveIndicator.className = 'save-indicator';
// Agregar clase según el tipo
saveIndicator.classList.add(type);
indicatorText.textContent = message;
// Mostrar/ocultar spinner
if (type === 'saving') {
spinner.style.display = 'inline-block';
} else {
spinner.style.display = 'none';
}
saveIndicator.style.display = 'block';
// Auto-ocultar después de unos segundos (excepto cuando está guardando)
if (type !== 'saving') {
setTimeout(() => {
saveIndicator.style.display = 'none';
}, type === 'error' ? 5000 : 3000);
}
}
// Función para realizar guardado automático
async function autoSave(tipo, data) {
if (isAutoSaving) return;
isAutoSaving = true;
showSaveIndicator('saving', 'Guardando cambios...');
try {
const response = await fetch('/IMPORTADORES/preferencias/guardarPreferenciasAjax', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({
tipo: tipo,
...data
})
});
const result = await response.json();
if (result.success) {
showSaveIndicator('saved', '✓ Cambios guardados');
} else {
throw new Error(result.message || 'Error desconocido');
}
} catch (error) {
console.error('Error al guardar:', error);
showSaveIndicator('error', '✗ Error: ' + error.message);
// En caso de error, podríamos revertir el estado del switch
// pero por ahora solo mostramos el error
} finally {
isAutoSaving = false;
}
}
// Función para mostrar/ocultar secciones con animación
function toggleSection(checkbox, targetId) {
const target = document.getElementById(targetId);
const isChecked = checkbox.checked;
if (isChecked) {
target.style.display = 'block';
setTimeout(() => {
target.style.opacity = '1';
}, 10);
} else {
target.style.opacity = '0';
setTimeout(() => {
target.style.display = 'none';
}, 300);
}
}
// Función para debounce (evitar múltiples guardados rápidos)
function debounce(func, wait) {
return function executedFunction(...args) {
const later = () => {
clearTimeout(saveTimeout);
func(...args);
};
clearTimeout(saveTimeout);
saveTimeout = setTimeout(later, wait);
};
}
// Event listener para switch general de notificaciones
document.getElementById('notificaciones').addEventListener('change', function() {
const isChecked = this.checked;
// Deshabilitar temporalmente otros switches para evitar conflictos
const allSwitches = document.querySelectorAll('.form-check-input');
allSwitches.forEach(sw => sw.disabled = true);
// Guardar cambio
autoSave('notificaciones_general', {
valor: isChecked
}).finally(() => {
// Rehabilitar switches
allSwitches.forEach(sw => sw.disabled = false);
});
// Mostrar/ocultar sección de tipos
toggleSection(this, 'tipos-notificaciones');
// Si se desactivan las notificaciones, también desactivar correo extra
if (!isChecked) {
const correoExtraCheckbox = document.getElementById('notificaciones_extra');
correoExtraCheckbox.checked = false;
toggleSection(correoExtraCheckbox, 'correo-extra-section');
// Desmarcar todos los tipos de notificación
document.querySelectorAll('.tipo-notificacion').forEach(checkbox => {
checkbox.checked = false;
});
// Ocultar configuración de resumen diario
const resumenDiarioConfig = document.getElementById('resumen-diario-config');
if (resumenDiarioConfig) {
resumenDiarioConfig.style.opacity = '0';
setTimeout(() => {
resumenDiarioConfig.style.display = 'none';
}, 300);
}
}
});
// Event listener para switch de correo extra
document.getElementById('notificaciones_extra').addEventListener('change', function() {
const isChecked = this.checked;
const correoExtraSection = document.getElementById('correo-extra-section');
const correoExtraInfo = correoExtraSection.querySelector('.alert');
// Verificar si hay correo registrado antes de activar
if (isChecked && correoExtraInfo && correoExtraInfo.classList.contains('alert-warning')) {
showSaveIndicator('error', 'Primero debes registrar un correo adicional en Seguridad');
this.checked = false;
return;
}
// Deshabilitar switch temporalmente
this.disabled = true;
// Guardar cambio
autoSave('notificaciones_extra', {
valor: isChecked
}).finally(() => {
this.disabled = false;
});
// Mostrar/ocultar sección
toggleSection(this, 'correo-extra-section');
});
// Event listeners para tipos específicos de notificación
document.querySelectorAll('.tipo-notificacion').forEach(checkbox => {
checkbox.addEventListener('change', function() {
const isChecked = this.checked;
const tipoNombre = this.dataset.nombre;
// Verificar que las notificaciones generales estén activadas
const notificacionesGenerales = document.getElementById('notificaciones').checked;
if (!notificacionesGenerales) {
showSaveIndicator('error', 'Primero debes activar las notificaciones generales');
this.checked = false;
return;
}
// Deshabilitar switch temporalmente
this.disabled = true;
// Guardar cambio
autoSave('tipo_notificacion', {
nombre: tipoNombre,
valor: isChecked
}).finally(() => {
this.disabled = false;
});
// Si es el resumen diario, mostrar/ocultar configuración
if (tipoNombre === 'resumen_diario') {
toggleSection(this, 'resumen-diario-config');
}
});
});
// === FUNCIONALIDAD DE RESUMEN DIARIO ===
// Función para mostrar/ocultar configuración del resumen diario
function toggleResumenConfig() {
const resumenCheckbox = document.getElementById('resumen_diario');
const resumenConfig = document.getElementById('resumen-diario-config');
if (resumenCheckbox.checked) {
resumenConfig.style.display = 'block';
setTimeout(() => {
resumenConfig.style.opacity = '1';
}, 10);
} else {
resumenConfig.style.opacity = '0';
setTimeout(() => {
resumenConfig.style.display = 'none';
}, 300);
}
}
// Event listener para el checkbox de resumen diario
document.addEventListener('DOMContentLoaded', function() {
const resumenCheckbox = document.getElementById('resumen_diario');
// Verificar estado inicial al cargar la página
toggleResumenConfig();
// Agregar listener para cambios en el checkbox
resumenCheckbox.addEventListener('change', function() {
toggleResumenConfig();
});
});
// Referencias específicas para resumen diario
const resumenDiario = document.getElementById('resumen_diario');
const resumenDiarioConfig = document.getElementById('resumen-diario-config');
const presetButtons = document.querySelectorAll('.preset-btn');
const daysSelector = document.getElementById('days-selector');
const dayCheckboxes = document.querySelectorAll('.day-checkbox');
const resumenDiasInput = document.getElementById('resumen_dias');
const resumenHoraInput = document.getElementById('resumen_hora');
// Función para actualizar el valor de días seleccionados
function updateResumenDias() {
const selectedDays = Array.from(dayCheckboxes)
.filter(cb => cb.checked)
.map(cb => cb.value);
if (selectedDays.length === 7) {
resumenDiasInput.value = 'TODOS';
} else if (selectedDays.length === 5 &&
['L', 'M', 'X', 'J', 'V'].every(day => selectedDays.includes(day))) {
resumenDiasInput.value = 'L-V';
} else {
resumenDiasInput.value = selectedDays.join(',');
}
}
// Función para cargar preset de días
function loadDaysPreset(preset) {
// Desmarcar todos los checkboxes primero
dayCheckboxes.forEach(cb => cb.checked = false);
// Marcar según el preset
if (preset === 'L-V') {
['L', 'M', 'X', 'J', 'V'].forEach(day => {
const checkbox = document.getElementById(`day-${day}`);
if (checkbox) checkbox.checked = true;
});
} else if (preset === 'TODOS') {
dayCheckboxes.forEach(cb => cb.checked = true);
} else if (preset.includes(',')) {
// Preset personalizado
const days = preset.split(',');
days.forEach(day => {
const checkbox = document.getElementById(`day-${day.trim()}`);
if (checkbox) checkbox.checked = true;
});
}
updateResumenDias();
}
// Función para actualizar botones de preset según selección actual
function updatePresetButtons() {
const currentValue = resumenDiasInput.value;
presetButtons.forEach(btn => btn.classList.remove('active'));
const activeButton = document.querySelector(`[data-preset="${currentValue}"]`);
if (activeButton) {
activeButton.classList.add('active');
daysSelector.style.display = 'none';
} else {
// Es personalizado
const customButton = document.querySelector('[data-preset="PERSONALIZADO"]');
if (customButton) {
customButton.classList.add('active');
daysSelector.style.display = 'flex';
}
}
}
// Función debounced para guardar configuración de resumen
const saveResumenConfig = debounce(async function() {
const hora = resumenHoraInput.value;
const dias = resumenDiasInput.value;
await autoSave('resumen_config', {
hora: hora,
dias: dias
});
}, 1000);
// Event listeners para botones de preset de días
if (presetButtons.length > 0) {
presetButtons.forEach(button => {
button.addEventListener('click', function() {
// Remover clase active de todos los botones
presetButtons.forEach(btn => btn.classList.remove('active'));
// Agregar clase active al botón clickeado
this.classList.add('active');
const preset = this.dataset.preset;
if (preset === 'PERSONALIZADO') {
daysSelector.style.display = 'flex';
} else {
daysSelector.style.display = 'none';
resumenDiasInput.value = preset;
loadDaysPreset(preset);
saveResumenConfig();
}
});
});
}
// Event listeners para checkboxes individuales de días
if (dayCheckboxes.length > 0) {
dayCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
updateResumenDias();
updatePresetButtons();
saveResumenConfig();
});
});
}
// Event listener para cambio de hora
if (resumenHoraInput) {
resumenHoraInput.addEventListener('change', function() {
saveResumenConfig();
});
}
// Inicialización del estado de los días al cargar la página
document.addEventListener('DOMContentLoaded', function() {
if (resumenDiasInput && resumenDiasInput.value) {
loadDaysPreset(resumenDiasInput.value);
updatePresetButtons();
}
});
// === FIN FUNCIONALIDAD DE RESUMEN DIARIO ===
// Prevenir envío accidental del formulario
document.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && e.target.type !== 'submit') {
e.preventDefault();
}
});
// Mensaje de confirmación antes de salir si hay guardado en progreso
window.addEventListener('beforeunload', function(e) {
if (isAutoSaving) {
e.preventDefault();
e.returnValue = 'Hay cambios pendientes de guardar. ¿Estás seguro de que quieres salir?';
return e.returnValue;
}
});
</script>
</body>
</html>