<?php
session_start();
if (isset($_SESSION['attuid']) && isset($_SESSION['rol'])) {
    switch ($_SESSION['rol']) {
        case 'admin':
        case 'adminTi':
            header('Location: frontend/admin/panel-admin.php');
            exit;
        case 'coordinador':
            header('Location: frontend/admin/panel-admin.php');
            exit;
        case 'reclutador':
            header('Location: frontend/recruiter/dashboard.php');
            exit;
        case 'capturista':
            header('Location: frontend/capturista/capture.php');
            exit;
        case 'capturistaRH':
            header('Location: frontend/plantilla/buscador-empleado.php');
            exit;
        case 'contabilidad':
            header('Location: frontend/contabilidad/altas.php');
            exit;
        case 'subdistribuidor':
            header('Location: frontend/subdistribuidor/candidatos.php');
            exit;    
        default:
            session_destroy();
            header('Location: index.php');
            exit;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | Reclutador Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css" rel="stylesheet">
    <link href="frontend/assets/css/login.css" rel="stylesheet">
</head>
<body class="bg-light animate__animated animate__fadeIn">
<div class="login-wrapper">
    <div class="login-card animate__animated animate__fadeInUp">
        <div class="login-logo">
            <i class="fas fa-users fa-2x"></i>
        </div>
        <div class="login-title">SACC</div>
        <div class="login-subtitle">Sistema de Aspirantes Candidatos y Contratados</div>
        <form id="loginForm" autocomplete="off">
            <div class="mb-4">
                <label class="form-label" for="attuid">ATTUID</label>
                <div class="input-group has-validation">
                    <span class="input-group-text"><i class="fas fa-id-badge"></i></span>
                    <input type="text" name="attuid" id="attuid" class="form-control" required autofocus>
                </div>
            </div>
            <div class="mb-4">
                <label class="form-label" for="password">Contraseña</label>
                <div class="input-group has-validation">
                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                    <input type="password" name="password" id="password" class="form-control" required>
                    <button class="btn" type="button" id="togglePassword" tabindex="-1" aria-label="Mostrar/Ocultar contraseña">
                        <i class="fas fa-eye" id="eyeIcon"></i>
                    </button>
                </div>
            </div>
            <button type="submit" class="btn btn-primary w-100 py-2 position-relative">
                <span id="loginText"><i class="fas fa-sign-in-alt me-2"></i>Ingresar</span>
                <span class="spinner-border spinner-border-sm ms-2" id="loginSpinner" role="status" aria-hidden="true"></span>
            </button>
            <div id="errorMessage" class="alert alert-danger mt-3 d-none"></div>
        </form>
        <div class="login-footer">
            Sistema de reclutamiento v1.5.6
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('loginForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const attuid = document.getElementById('attuid').value;
    const password = document.getElementById('password').value;
    const errorMessage = document.getElementById('errorMessage');
    const spinner = document.getElementById('loginSpinner');
    const loginText = document.getElementById('loginText');
    errorMessage.classList.add('d-none');
    spinner.style.display = 'inline-block';
    loginText.style.opacity = '0.5';
    if (!attuid || !password) {
        errorMessage.textContent = 'Por favor, complete todos los campos.';
        errorMessage.classList.remove('d-none');
        spinner.style.display = 'none';
        loginText.style.opacity = '1';
        return;
    }
    const formData = new FormData();
    formData.append('attuid', attuid);
    formData.append('password', password);
    fetch('backend/auth/login.php', {
        method: 'POST',
        body: formData
    })
    .then(async response => {
        let data;
        try {
            data = await response.json();
        } catch (e) {
            // Si la respuesta no es JSON, mostrar error claro
            spinner.style.display = 'none';
            loginText.style.opacity = '1';
            errorMessage.textContent = 'Error inesperado: la respuesta del servidor no es válida.';
            errorMessage.classList.remove('d-none');
            return;
        }
        spinner.style.display = 'none';
        loginText.style.opacity = '1';
        if (data.success) {
            // Obtener el rol desde la respuesta o de la sesión (en este contexto, del formulario)
            const attuid = document.getElementById('attuid').value;
            // El backend no envía el rol, pero la redirección sí depende del rol, así que lo inferimos por la URL de redirección
            const isAdminTi = data.redirect && data.redirect.includes('adminTi');
            const isContabilidad = data.redirect && data.redirect.includes('contabilidad');
            const isSubdistribuidor = data.redirect && data.redirect.includes('subdistribuidor');
            if (data.expiredPositions && !(isAdminTi || isContabilidad || isSubdistribuidor)) {
                // Bloquear el login y mostrar el modal SOLO para roles afectados
                const modal = new bootstrap.Modal(document.getElementById('expiredPositionsModal'), {backdrop: 'static', keyboard: false});
                modal.show();
                document.getElementById('loginForm').querySelectorAll('input, button').forEach(el => el.disabled = true);
                document.getElementById('continueExpiredPositions').onclick = function() {
                    // Verificar si hay posiciones vencidas antes de redirigir
                    
                    fetch('frontend/posiciones/posiciones_temporales_vencidas.php?checkOnly=1')
                        .then(response => response.json())
                        .then(data => {
                            if (data && data.hasExpiredPositions) {
                                window.location.href = 'frontend/posiciones/posiciones_temporales_vencidas.php';
                            } else {
                                window.location.href = 'frontend/posiciones/index.php';
                            }
                        })
                        .catch(() => {
                            // Si hay error, ir a la vista normal
                            window.location.href = 'frontend/posiciones/index.php';
                        });  window.location.href = 'frontend/posiciones/index.php';
                };
            } else {
                window.location.href = data.redirect;
            }
        } else {
            errorMessage.textContent = data.message || 'Credenciales incorrectas';
            errorMessage.classList.remove('d-none');
        }
    })
    .catch(error => {
        spinner.style.display = 'none';
        loginText.style.opacity = '1';
        errorMessage.textContent = 'Error al conectar con el servidor';
        errorMessage.classList.remove('d-none');
    });
});
document.getElementById('togglePassword').addEventListener('click', function () {
    const passwordField = document.getElementById('password');
    const eyeIcon = document.getElementById('eyeIcon');
    const isPassword = passwordField.type === 'password';
    passwordField.type = isPassword ? 'text' : 'password';
    eyeIcon.classList.toggle('fa-eye');
    eyeIcon.classList.toggle('fa-eye-slash');
});

// Modal para posiciones vencidas
const modalHtml = `
<div class="modal fade" id="expiredPositionsModal" tabindex="-1" aria-labelledby="expiredPositionsLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="expiredPositionsLabel">¡Atención!</h5>
      </div>
      <div class="modal-body">
        Tienes posiciones temporales ya vencidas, favor de validar.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary w-100" id="continueExpiredPositions">Continuar</button>
      </div>
    </div>
  </div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', modalHtml);
</script>
</body>
</html>
