Files
MVE/views/preferencias/notificaciones.php
2025-05-27 10:11:12 -06:00

471 lines
18 KiB
PHP

<?php
include __DIR__ . '/../partials/sidebar_configuracion.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Dashboard | Configuración</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>
<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; /* Alineado con la altura de la navbar */
z-index: 1040; /* Asegura que esté por encima del contenido */
}
.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; /* Ajusta debajo de navbar */
padding: 40px 20px;
position: relative;
z-index: 1;
background-color: #f4f6f9; /* Asegura fondo uniforme */
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; /* Ancho del sidebar */
}
}
/* 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;
}
.section-divider {
border-left: 4px solid #007bff;
padding-left: 15px;
margin: 20px 0;
}
.fade-transition {
transition: opacity 0.3s ease-in-out;
}
.correo-extra-section {
background-color: #f8f9fa;
border-radius: 8px;
padding: 15px;
margin-top: 15px;
}
.success-message {
background-color: #d4edda;
color: #155724;
padding: 10px;
border-radius: 5px;
margin-bottom: 20px;
border: 1px solid #c3e6cb;
}
.error-message {
background-color: #f8d7da;
color: #721c24;
padding: 10px;
border-radius: 5px;
margin-bottom: 20px;
border: 1px solid #f5c6cb;
}
/* Estilos para indicadores de guardado */
.save-indicator {
position: fixed;
top: 20px;
right: 20px;
padding: 10px 15px;
border-radius: 8px;
font-weight: 500;
z-index: 9999;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.save-indicator.saving {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.save-indicator.saved {
background-color: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
.save-indicator.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.spinner-border-sm {
width: 1rem;
height: 1rem;
}
/* Estilo para switches deshabilitados temporalmente */
.form-check-input:disabled {
opacity: 0.6;
}
/* Animación sutil para switches */
.form-check-input {
transition: all 0.2s ease;
}
</style>
</head>
<body>
<div class="content">
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0">🔔 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">
<!-- 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"
<?= !$notificaciones['notificaciones'] ? 'style="display:none; opacity:0;"' : 'style="opacity:1;"' ?>>
<div class="section-divider">
<h6 class="mb-3">📋 Tipos de Notificaciones</h6>
<div class="row">
<?php foreach ($tipos as $clave => $descripcion): ?>
<div class="col-md-6 mb-3">
<div class="form-check form-switch">
<input class="form-check-input tipo-notificacion" type="checkbox"
name="<?= $clave ?>" id="<?= $clave ?>"
data-tipo="tipo_notificacion" data-nombre="<?= $clave ?>"
<?= ($preferencias[$clave] ?? 0) ? 'checked' : '' ?>>
<label class="form-check-label" for="<?= $clave ?>">
<strong><?= ucwords(str_replace('_', ' ', $clave)) ?></strong>
<div class="form-text"><?= htmlspecialchars($descripcion) ?></div>
</label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<!-- 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 class="me-3">
<i class="fas fa-envelope" style="font-size: 1.2em;"></i>
</div>
<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);
}
}
// 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;
});
}
});
// 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;
});
});
});
// Prevenir envío accidental del formulario (aunque ya no lo necesitamos)
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>