<?php
require_once '../../includes/auth.php';
require_once '../../includes/database.php';
requireRole('auxiliar');

// Obtener datos del usuario
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Auxiliar';
$usuarioId = $_SESSION['user_id'] ?? 0;

// Procesar el formulario de cambio de contraseña
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validaciones
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error = 'Todos los campos son obligatorios';
    } elseif ($new_password !== $confirm_password) {
        $error = 'Las nuevas contraseñas no coinciden';
    } elseif (strlen($new_password) < 8) {
        $error = 'La nueva contraseña debe tener al menos 8 caracteres';
    } else {
        // Obtener el hash actual de la contraseña
        $user = $db->fetchOne("SELECT password FROM usuarios WHERE id = ?", [$usuarioId]);
        
        if ($user && password_verify($current_password, $user['password'])) {
            // Actualizar la contraseña
            $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $db->update("usuarios", ['password' => $new_password_hash], ['id' => $usuarioId]);
            
            $success = 'Contraseña actualizada correctamente';
        } else {
            $error = 'La contraseña actual es incorrecta';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cambiar Contraseña - <?= $nombreColegio ?></title>
    
    <!-- Cargar Font Awesome desde CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Cargar Bootstrap CSS local -->
    <link href="<?= APP_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">

    <!-- Estilos personalizados para auxiliar con la paleta de colores del dashboard -->
    <style>
        :root {
            --primary: #2c3e50;
            --secondary: #3498db;
            --accent: #e74c3c;
            --light: #ecf0f1;
            --dark: #34495e;
            --success: #2ecc71;
            --warning: #f39c12;
            --sidebar-width: 280px;
            --header-height: 70px;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            display: flex;
            min-height: 100vh;
            margin: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* Sidebar para auxiliar */
        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(to bottom, var(--primary), var(--dark));
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            transition: all 0.3s ease;
            box-shadow: 3px 0 15px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }

        .logo-container {
            padding: 20px 25px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            background-color: rgba(0, 0, 0, 0.1);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo i {
            font-size: 28px;
            color: var(--secondary);
        }

        .logo h1 {
            font-size: 22px;
            font-weight: 600;
        }

        .menu-section {
            padding: 25px 0;
        }

        .menu-title {
            padding: 0 25px 10px;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: rgba(255, 255, 255, 0.6);
            font-weight: 500;
        }

        .menu-items {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .menu-item {
            padding: 12px 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
            border-left: 4px solid transparent;
            position: relative;
        }

        .menu-item:hover {
            background-color: rgba(255, 255, 255, 0.05);
            border-left-color: var(--secondary);
        }

        .menu-item.active {
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: var(--secondary);
        }

        .menu-item i {
            width: 24px;
            text-align: center;
            font-size: 18px;
            color: var(--secondary);
        }

        .menu-item span {
            font-size: 16px;
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            padding-bottom: 30px;
        }

        /* Header */
        .header {
            height: var(--header-height);
            background-color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            position: sticky;
            top: 0;
            z-index: 90;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .toggle-menu {
            display: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--dark);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--secondary), var(--primary));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        .user-details {
            display: flex;
            flex-direction: column;
        }

        .user-name {
            font-weight: 600;
            font-size: 15px;
        }

        .user-role {
            font-size: 13px;
            color: #7f8c8d;
        }

        /* Content Area */
        .content {
            padding: 30px;
        }

        /* Formulario de cambio de contraseña */
        .password-form {
            max-width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }

        .password-form h2 {
            color: var(--dark);
            margin-bottom: 25px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--secondary);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark);
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border 0.3s;
        }

        .form-group input:focus {
            border-color: var(--secondary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .btn-submit {
            background-color: var(--secondary);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-submit:hover {
            background-color: #2980b9;
        }

        /* Footer */
        .footer {
            padding: 20px 30px;
            text-align: center;
            color: #7f8c8d;
            font-size: 14px;
            border-top: 1px solid #eee;
            margin-top: 30px;
            background: white;
        }

        /* Mensajes de error/éxito */
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        /* Responsive Design */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .toggle-menu {
                display: block;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar para auxiliar -->
    <div class="sidebar">
        <div class="logo-container">
            <div class="logo">
                <i class="fas fa-graduation-cap"></i>
                <h1><?= $nombreColegio ?></h1>
            </div>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Principal</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/dashboard.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-home"></i>
                        <span>Menu</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/notificaciones.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-inbox"></i>
                        <span>Buzón de Mensajería</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Funciones</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/asistencia.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-clipboard-check"></i>
                        <span>Tomar Asistencia</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/lista_alumnos.php?action=new" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-newspaper"></i>
                        <span>Lista de Alumnos</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-envelope"></i>
                        <span>Enviar Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/historial_de_correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-history"></i>
                        <span>Historial de Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correo_administrativo.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-users"></i>
                        <span>Correo Administrativo</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Administración</h3>
            <ul class="menu-items">
                <li class="menu-item active">
                    <a href="<?= APP_URL ?>/modules/auxiliar/cambiar_contrasena.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-key"></i>
                        <span>Cambiar Contraseña</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/auth/logout.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Cerrar Sesión</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <header class="header">
            <div class="header-left">
                <div class="toggle-menu">
                    <i class="fas fa-bars"></i>
                </div>
            </div>

            <div class="header-right">
                <div class="user-info">
                    <div class="user-avatar">
                        <?=
                        substr($usuarioNombre, 0, 1) .
                            (strpos($usuarioNombre, ' ') !== false ?
                                substr($usuarioNombre, strpos($usuarioNombre, ' ') + 1, 1) :
                                substr($usuarioNombre, 1, 1))
                        ?>
                    </div>
                    <div class="user-details">
                        <div class="user-name"><?= $usuarioNombre ?></div>
                        <div class="user-role">Auxiliar</div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Content Area -->
        <div class="content">
            <div class="password-form">
                <h2><i class="fas fa-key mr-2"></i> Cambiar Contraseña</h2>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i> <?= $error ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> <?= $success ?>
                    </div>
                <?php endif; ?>
                
                <form method="POST" action="">
                    <div class="form-group">
                        <label for="current_password"><i class="fas fa-lock"></i> Contraseña Actual</label>
                        <input type="password" id="current_password" name="current_password" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="new_password"><i class="fas fa-key"></i> Nueva Contraseña</label>
                        <input type="password" id="new_password" name="new_password" required>
                        <small class="text-muted">Mínimo 8 caracteres</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password"><i class="fas fa-key"></i> Confirmar Nueva Contraseña</label>
                        <input type="password" id="confirm_password" name="confirm_password" required>
                    </div>
                    
                    <button type="submit" class="btn-submit">
                        <i class="fas fa-save"></i> Guardar Cambios
                    </button>
                </form>
            </div>
        </div>

        <!-- Footer -->
        <footer class="footer">
            <p>Sistema Escolar Integrado v3.0 © <?= date('Y') ?> - Todos los derechos reservados</p>
        </footer>
    </div>

    <script src="<?= APP_URL ?>/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.querySelector('.toggle-menu').addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('active');
        });

        // Validación de contraseña en tiempo real
        document.getElementById('new_password').addEventListener('input', function() {
            const password = this.value;
            const feedback = document.getElementById('password-strength');
            
            if (password.length === 0) {
                if (feedback) feedback.textContent = '';
            } else if (password.length < 8) {
                if (feedback) feedback.textContent = 'La contraseña es demasiado corta';
            } else {
                if (feedback) feedback.textContent = 'La contraseña es válida';
            }
        });

        // Validar que las contraseñas coincidan
        document.getElementById('confirm_password').addEventListener('input', function() {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = this.value;
            
            if (confirmPassword && newPassword !== confirmPassword) {
                this.setCustomValidity('Las contraseñas no coinciden');
            } else {
                this.setCustomValidity('');
            }
        });
    </script>
</body>
</html>