<?php
require_once 'includes/db.php';
require_once 'includes/helpers.php';

if (function_exists('init_secure_session')) {
    init_secure_session();
}

global $pdo;

// Get institution settings
$settings_stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
// Asegurar robustez: si la consulta falla (p. ej., la tabla no existe), proceder con configuraciones vacías.
$institution_settings = ($settings_stmt) ? $settings_stmt->fetch(PDO::FETCH_ASSOC) : [];
$institution_settings = $institution_settings ?: []; // Ensure it's an array even if fetch returns false.

$error = '';

// Generate CSRF token for form display
$csrf_token = get_csrf_token();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check rate limiting
    if (function_exists('check_rate_limit') && !check_rate_limit('login', $_SERVER['REMOTE_ADDR'])) {
        $error = 'Demasiados intentos de inicio de sesión. Por favor, espere un momento.';
        log_security_event('RATE_LIMIT', 'Login rate limit exceeded', ['ip' => $_SERVER['REMOTE_ADDR']]);
    } else {
        $username = sanitize($_POST['username'], 'string', ['max_length' => 100]);
        $password = $_POST['password']; // No sanitizar la contraseña, password_verify lo maneja de forma segura.

        // Check login attempts
        if (function_exists('check_login_attempts') && !check_login_attempts($username)) {
            $error = 'Cuenta bloqueada temporalmente debido a múltiples intentos fallidos.';
            log_security_event('ACCOUNT_LOCKOUT', 'Account locked due to failed attempts', ['username' => $username]);
        }
        if (empty($username) || empty($password)) {
            $error = 'Por favor complete todos los campos.';
            if (function_exists('log_form_error')) {
                log_form_error('login', 'Empty required fields', ['username' => $username]);
            }
        } else {
            // Check if username or email
            $stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.username = ? OR u.email = ?");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch();

            if (!$user || !password_verify($password, $user['password'])) {
                $error = 'Nombre de usuario/correo electrónico o contraseña no válidos.';
                if (function_exists('log_authentication_error')) {
                    log_authentication_error('login', 'Invalid credentials', ['username' => $username]);
                }
                if (function_exists('increment_login_attempts')) {
                    increment_login_attempts($username);
                }
            } else {
                // Credenciales válidas, resetear intentos y verificar estado de la cuenta.
                if (function_exists('reset_login_attempts')) {
                    reset_login_attempts($username);
                }

                $can_login = true; // Asumimos que el usuario puede iniciar sesión por defecto.

                // Verificación especial solo para egresados.
                if ($user['role_name'] == 'egresado') {
                    $stmt = $pdo->prepare("SELECT status FROM graduates WHERE user_id = ?");
                    $stmt->execute([$user['id']]);
                    $graduate = $stmt->fetch();
                    if (!$graduate || ($graduate['status'] ?? 'inactive') !== 'active') {
                        $error = 'Su cuenta de egresado no está activa. Por favor, contacte con el administrador.';
                        $can_login = false; // El egresado no puede iniciar sesión.
                    }
                }

                // Si no hay ninguna restricción, proceder con el inicio de sesión.
                if ($can_login) {
                    // Limpiar cualquier dato de sesión anterior
                    session_unset();
                    session_destroy();
                    session_start();

                    // Regenerar el ID de la sesión para prevenir la fijación de sesión.
                    session_regenerate_id(true);

                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['role'] = $user['role_name'];
                    $_SESSION['last_activity'] = time(); // Para el timeout de inactividad
                    $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'] ?? ''; // Para prevenir session hijacking
                    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? ''; // Para prevenir session hijacking

                    // Debug: Log successful login
                    error_log('DEBUG LOGIN: User ' . $user['username'] . ' logged in successfully, redirecting to ' . $user['role_name'] . ' dashboard');

                    // Redirigir según el rol
                    switch ($user['role_name']) {
                        case 'administrador':
                            header('Location: ' . route_url('admin_dashboard'));
                            break;
                        case 'empresa':
                            header('Location: ' . route_url('company_dashboard'));
                            break;
                        case 'alumno':
                            header('Location: ' . route_url('student_dashboard'));
                            break;
                        case 'profesor':
                            header('Location: ' . route_url('teacher_dashboard'));
                            break;
                        case 'egresado':
                            header('Location: ' . route_url('graduate_dashboard'));
                            break;
                        default:
                            header('Location: index.php');
                    }
                    exit; // Salir inmediatamente después de la redirección
                }
            }
        }
    }
}

?>
<!doctype html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?> | Login
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
    <meta name="color-scheme" content="light dark" />
    <meta name="theme-color"
        content="<?php echo htmlspecialchars($institution_settings['primary_color'] ?? '#79b791'); ?>"
        media="(prefers-color-scheme: light)" />
    <meta name="theme-color"
        content="<?php echo htmlspecialchars($institution_settings['dark_text_color'] ?? '#301014'); ?>"
        media="(prefers-color-scheme: dark)" />
    <?php if ($institution_settings['favicon']): ?>
        <link rel="icon" href="<?php echo htmlspecialchars($institution_settings['favicon']); ?>" type="image/x-icon">
    <?php endif; ?>
    <link rel="preload" href="assets/css/adminlte.css" as="style" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/source-sans-3@5.0.12/index.css"
        integrity="sha256-tXJfXfp6Ewt1ilPzLDtQnJV4hclT9XuaZUKyUvmyr+Q=" crossorigin="anonymous" media="print"
        onload="this.media='all'" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/styles/overlayscrollbars.min.css"
        crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css"
        crossorigin="anonymous" />
    <link rel="stylesheet" href="assets/css/adminlte.css" />
    <link rel="stylesheet" href="assets/css/custom-theme.css" />
    <style>
        :root {
            --primary-blue:
                <?php echo htmlspecialchars($institution_settings['primary_color'] ?? '#27538C'); ?>
                !important;
            --secondary-blue:
                <?php echo htmlspecialchars($institution_settings['secondary_color'] ?? '#204473'); ?>
                !important;
            --accent-blue:
                <?php echo htmlspecialchars($institution_settings['accent_color'] ?? '#9BABBF'); ?>
                !important;
            --success-green:
                <?php echo htmlspecialchars($institution_settings['success_color'] ?? '#28A745'); ?>
                !important;
            --warning-yellow:
                <?php echo htmlspecialchars($institution_settings['warning_color'] ?? '#FFC107'); ?>
                !important;
            --danger-red:
                <?php echo htmlspecialchars($institution_settings['danger_color'] ?? '#DC3545'); ?>
                !important;
            --info-cyan:
                <?php echo htmlspecialchars($institution_settings['info_color'] ?? '#17A2B8'); ?>
                !important;
            --light-bg:
                <?php echo htmlspecialchars($institution_settings['light_bg_color'] ?? '#F2F2F2'); ?>
                !important;
            --dark-text:
                <?php echo htmlspecialchars($institution_settings['dark_text_color'] ?? '#212426'); ?>
                !important;
            --sidebar-bg:
                <?php echo htmlspecialchars($institution_settings['sidebar_bg_color'] ?? '#27538C'); ?>
                !important;
            --navbar-bg:
                <?php echo htmlspecialchars($institution_settings['navbar_bg_color'] ?? '#FFFFFF'); ?>
                !important;
            --card-bg:
                <?php echo htmlspecialchars($institution_settings['card_bg_color'] ?? '#FFFFFF'); ?>
                !important;
            --border:
                <?php echo htmlspecialchars($institution_settings['border_color'] ?? '#E9ECEF'); ?>
                !important;
            --shadow:
                <?php echo htmlspecialchars($institution_settings['shadow_color'] ?? 'rgba(0,0,0,0.1)'); ?>
                !important;
            --hover-bg:
                <?php echo htmlspecialchars($institution_settings['hover_bg_color'] ?? '#F8F9FA'); ?>
                !important;
            --active-bg:
                <?php echo htmlspecialchars($institution_settings['active_bg_color'] ?? '#E9ECEF'); ?>
                !important;
            --celadon:
                <?php echo htmlspecialchars($institution_settings['secondary_color'] ?? '#204473'); ?>
                !important;
            --mint-cream:
                <?php echo htmlspecialchars($institution_settings['light_bg_color'] ?? '#F2F2F2'); ?>
                !important;
            --cambridge-blue:
                <?php echo htmlspecialchars($institution_settings['primary_color'] ?? '#27538C'); ?>
                !important;
            --caput-mortuum:
                <?php echo htmlspecialchars($institution_settings['dark_text_color'] ?? '#212426'); ?>
                !important;
            --black-bean:
                <?php echo htmlspecialchars($institution_settings['dark_text_color'] ?? '#212426'); ?>
                !important;
        }

        /* Custom Login Page Styling */
        .login-page {
            background: var(--sidebar-bg);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }

        .login-page::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background:
                radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
            pointer-events: none;
        }

        .login-page::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3));
            pointer-events: none;
        }

        .login-box {
            width: 100%;
            max-width: 420px;
            margin: 2rem auto;
            z-index: 1;
            position: relative;
        }


        .login-logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .login-logo a {
            font-size: 1.8rem;
            font-weight: 700;
            color: white;
            text-decoration: none;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            letter-spacing: 2px;
            transition: all 0.3s ease;
        }

        .login-logo a:hover {
            color: var(--celadon);
        }

        .login-logo .fas {
            color: var(--cambridge-blue);
            margin-right: 0.5rem;
        }



        .card {
            border: none;
            border-radius: 24px;
            box-shadow: 0 25px 50px var(--shadow), 0 0 0 1px rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            background: var(--card-bg);
            overflow: hidden;
            position: relative;
            transition: all 0.3s ease;
        }

        .card:hover {
            box-shadow: 0 35px 70px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.2);
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(90deg, var(--primary-blue), var(--secondary-blue), var(--celadon));
            border-radius: 24px 24px 0 0;
        }

        .card::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(90deg, var(--celadon), var(--mint-cream));
            border-radius: 0 0 24px 24px;
        }

        .login-card-body {
            padding: 2rem 1.5rem;
            background: linear-gradient(180deg, rgba(237, 244, 237, 0.8), rgba(255, 255, 255, 0.9));
        }

        .login-box-msg {
            font-size: 1.1rem;
            color: var(--caput-mortuum);
            margin-bottom: 1.5rem;
            text-align: center;
            font-weight: 500;
            font-style: italic;
        }

        .input-group {
            margin-bottom: 1rem;
            position: relative;
        }

        .form-control {
            border: 2px solid var(--border);
            border-radius: 12px;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            background: var(--card-bg);
            transition: all 0.3s ease;
            height: auto;
        }

        .form-control:focus {
            border-color: var(--cambridge-blue);
            box-shadow: 0 0 0 0.2rem rgba(121, 183, 145, 0.25);
            background: white;
        }

        .input-group-text {
            background: var(--sidebar-bg) !important;
            color: white !important;
            border: 2px solid var(--border);
            border-left: none;
            border-radius: 0 12px 12px 0;
            padding: 0.75rem 1rem;
            transition: all 0.3s ease;
        }

        .input-group:focus-within .input-group-text {
            background: var(--celadon) !important;
            color: var(--primary-blue);
        }


        .login-page .btn-primary,
        .login-page button.btn-primary {
            background: var(--sidebar-bg);
            border: 2px solid transparent !important;
            border-radius: 50px !important;
            padding: 0.875rem 2.5rem !important;
            font-weight: 700 !important;
            font-size: 1.1rem !important;
            text-transform: uppercase !important;
            letter-spacing: 1px !important;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1) !important;
            position: relative !important;
            overflow: hidden !important;
            color: white !important;
            min-width: 180px !important;
            box-shadow: 0 4px 15px var(--shadow);
        }

        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: var(--celadon) !important;
            transition: left 0.6s ease;
        }

        .btn-primary:hover::before {
            left: 100%;
        }

        .login-page .btn-primary:hover,
        .login-page button.btn-primary:hover {
            box-shadow: 0 12px 35px var(--shadow) !important;
            background: var(--sidebar-bg) !important;
            color: white !important;
        }

        .login-page .btn-primary:focus,
        .login-page button.btn-primary:focus {
            box-shadow: 0 0 0 0.2rem rgba(121, 183, 145, 0.25) !important;
            outline: none !important;
        }

        .login-page .btn-primary:active,
        .login-page button.btn-primary:active {
            box-shadow: 0 4px 15px var(--shadow) !important;
        }

        .alert {
            border-radius: 16px;
            border: none;
            background: linear-gradient(135deg, rgba(220, 53, 69, 0.1), rgba(220, 53, 69, 0.2));
            color: #dc3545;
            padding: 1.25rem 1.75rem;
            margin-bottom: 2rem;
            box-shadow: 0 6px 20px rgba(220, 53, 69, 0.15);
            backdrop-filter: blur(10px);
            border-left: 4px solid #dc3545;
            position: relative;
            overflow: hidden;
        }

        .alert::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #dc3545, #ff6b6b);
        }

        .alert i {
            color: #dc3545;
            margin-right: 0.5rem;
        }

        .login-footer {
            text-align: center;
            margin-top: 2rem;
            color: var(--caput-mortuum);
        }

        .login-footer a {
            color: var(--cambridge-blue);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .login-footer a:hover {
            color: var(--caput-mortuum);
            text-decoration: underline;
        }

        /* Enhanced animations removed */

        /* Responsive Design */
        @media (max-width: 576px) {
            .login-box {
                margin: 1rem;
                width: calc(100% - 2rem);
            }


            .login-logo a {
                font-size: 1.5rem;
            }

            .login-card-body {
                padding: 2rem 1.5rem;
            }

            .login-box-msg {
                font-size: 1rem;
            }

            .form-control,
            .input-group-text {
                padding: 0.625rem 0.875rem;
            }

            .btn-primary {
                padding: 0.75rem 2rem !important;
                font-size: 0.9rem !important;
                min-height: 44px !important;
                width: 100% !important;
                max-width: 200px !important;
            }
        }

        @media (max-width: 480px) {
            .login-logo {
                margin-bottom: 1.5rem;
            }

            .login-logo a {
                font-size: 1.3rem;
            }

            .card {
                border-radius: 15px;
            }

            .login-card-body {
                padding: 1.5rem 1rem;
            }

            .input-group {
                margin-bottom: 1rem;
            }
        }

        /* Logo styling */
        .logo-container {
            position: relative;
            display: inline-block;
            margin-bottom: 1rem;
        }

        .brand-logo {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

        .brand-logo {
            border: 3px solid rgba(255, 255, 255, 0.3);
        }


        /* Enhanced Dark mode support */
        @media (prefers-color-scheme: dark) {
            .login-page {
                background: linear-gradient(135deg, var(--black-bean) 0%, var(--caput-mortuum) 50%, #1a1a1a 100%) !important;
            }

            .card {
                background: rgba(30, 30, 30, 0.98);
                color: #e9ecef;
                border: 1px solid rgba(255, 255, 255, 0.1);
                box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.05);
            }

            .login-card-body {
                background: linear-gradient(180deg, rgba(30, 30, 30, 0.95), rgba(20, 20, 20, 0.95));
            }

            .form-control {
                background: rgba(30, 30, 30, 0.9);
                border-color: var(--caput-mortuum);
                color: #e9ecef;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            }

            .form-control:focus {
                background: rgba(30, 30, 30, 1);
                border-color: var(--celadon);
                box-shadow: 0 0 0 0.2rem rgba(121, 183, 145, 0.25);
                color: #e9ecef;
            }

            .input-group-text {
                background: linear-gradient(135deg, var(--caput-mortuum), var(--black-bean)) !important;
                border-color: var(--caput-mortuum);
            }

            .btn-primary {
                background: linear-gradient(135deg, var(--caput-mortuum), var(--black-bean)) !important;
            }

            .login-logo a {
                color: #e9ecef;
            }

            .login-box-msg {
                color: #e9ecef;
            }

            .alert {
                background: linear-gradient(135deg, rgba(220, 53, 69, 0.2), rgba(220, 53, 69, 0.3));
                color: #ff6b6b;
                border-left-color: #ff6b6b;
            }
        }

        /* Accessibility improvements */
        @media (prefers-reduced-motion: reduce) {

            .login-box,
            .card,
            .btn-primary,
            .brand-logo,
            .logo-glow,
            * {
                animation: none !important;
                transition: none !important;
            }
        }

        /* High contrast mode */
        @media (prefers-contrast: high) {
            .card {
                border: 3px solid var(--caput-mortuum) !important;
            }

            .form-control {
                border: 2px solid var(--caput-mortuum) !important;
            }

            .btn-primary {
                border: 3px solid var(--caput-mortuum) !important;
            }
        }
    </style>
</head>

<body class="login-page">
    <div class="login-box">
        <div class="login-logo">
            <a href="<?php echo route_url('login'); ?>">
                <i class="fas fa-briefcase" style="color: var(--cambridge-blue); margin-right: 0.5rem;"></i>
                <b>Bolsa</b> de Trabajo
            </a>
        </div>
        <div class="card">
            <div class="card-body login-card-body">
                <div class="text-center mb-4">
                    <div class="logo-container">
                        <img src="<?php echo htmlspecialchars($institution_settings['institution_logo'] ?? 'assets/img/logo.png'); ?>"
                            alt="<?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?> Logo"
                            class="brand-logo">
                        <div class="logo-glow"></div>
                    </div>
                </div>
                <p class="login-box-msg">
                    <?php echo htmlspecialchars($institution_settings['institution_description'] ?? 'Conectando alumnos con oportunidades'); ?>
                </p>
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>
                <form action="<?php echo route_url('login'); ?>" method="post">
                    <div class="input-group mb-4">
                        <input type="text" name="username" class="form-control" placeholder="Usuario o Email"
                            required />
                        <div class="input-group-text">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                    <div class="input-group mb-4">
                        <input type="password" name="password" class="form-control" placeholder="Contraseña" required />
                        <div class="input-group-text">
                            <i class="fas fa-lock"></i>
                        </div>
                    </div>
                    <div class="text-center mb-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-sign-in-alt me-2"></i>
                            Entrar
                        </button>
                    </div>
                    <div class="login-footer">
                        <p class="mb-2">
                            <a href="<?php echo route_url('register'); ?>">
                                <i class="fas fa-user-plus me-1"></i>
                                Registrate si eres Egresado
                            </a>
                        </p>
                    </div>
            </div>
        </div>
        <div class="login-footer mt-3">
            <div class="mb-0"
                style="font-size: 0.9rem; color: rgba(255, 255, 255, 0.9); text-shadow: 0 1px 2px rgba(0,0,0,0.3);">
                <div class="d-flex align-items-center justify-content-center gap-2">
                    <img src="assets/img/agouti_logo.png" alt="Agouti Logo" style="height: 24px; width: auto;">
                    Creado por AGOUTI PACA NE EIRL
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/browser/overlayscrollbars.browser.es6.min.js"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.min.js"
        crossorigin="anonymous"></script>
    <script src="assets/js/adminlte.js"></script>
</body>

</html>