<?php
/**
 * @intranet-file login.php
 * @intranet-file-version 2026.03.13.1
 * @intranet-file-date 2026-03-13
 * @intranet-file-owner CSIF Intranet
 */
ini_set('session.use_strict_mode', '1');
$secureCookie = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => $secureCookie,
    'httponly' => true,
    'samesite' => 'Lax',
]);
ini_set('session.gc_maxlifetime', '3600');
session_start();

// Importar lógica desde la carpeta common
require_once 'common/url.php';
require_once 'common/user_preferences.php';
require_once 'common/auth.php';
require_once 'common/captcha.php';

$error = '';

if ((string) ($_GET['expired'] ?? '') === '1') {
    $error = 'Tu sesion ha caducado por inactividad. Vuelve a iniciar sesion.';
}

/**
 * Devuelve true si $ip (IPv4) pertenece a la red $cidr (ej: 10.100.0.0/16).
 */
function ipv4InCidr(string $ip, string $cidr): bool {
    if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        return false;
    }

    $parts = explode('/', $cidr, 2);
    if (count($parts) !== 2) {
        return false;
    }
    [$net, $maskBits] = $parts;
    $maskBits = (int)$maskBits;
    if (!filter_var($net, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || $maskBits < 0 || $maskBits > 32) {
        return false;
    }

    $ipLong  = ip2long($ip);
    $netLong = ip2long($net);
    if ($ipLong === false || $netLong === false) {
        return false;
    }

    $mask = $maskBits === 0 ? 0 : (-1 << (32 - $maskBits));
    return (($ipLong & $mask) === ($netLong & $mask));
}

/**
 * Obtener IP del cliente.
 * - Por defecto usa REMOTE_ADDR.
 * - Si REMOTE_ADDR es un proxy interno (10.100.0.0/16) y hay X-Forwarded-For, toma el primer IPv4 válido.
 *   Esto evita que clientes externos se "cuelen" como internos si hay proxy inverso.
 */
function getClientIp(): string {
    $remote = $_SERVER['REMOTE_ADDR'] ?? '';
    $xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';

    if ($remote && ipv4InCidr($remote, '10.100.0.0/16') && $xff) {
        foreach (explode(',', $xff) as $candidate) {
            $candidate = trim($candidate);
            if (filter_var($candidate, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                return $candidate;
            }
        }
    }
    return $remote;
}

$clientIp = getClientIp();

/**
 * Bypass de captcha SOLO para LAN 10.100.0.0/16,
 * EXCEPTO para IPs de salida de la VPN (NAT) u otros saltos internos.
 * Añade aquí más IPs si tu VPN usa varias salidas.
 */
$captchaBypassCidr = '10.100.0.0/16';
$captchaBypassExcludeIps = [
    '10.100.21.3', // Servidor VPN (REMOTE_ADDR visto por la intranet cuando entras por VPN)
];

$captchaRequired = true;
if ($clientIp && ipv4InCidr($clientIp, $captchaBypassCidr) && !in_array($clientIp, $captchaBypassExcludeIps, true)) {
    $captchaRequired = false;
}

// Si el captcha no es requerido (red interna), no lo generamos ni lo pedimos.
if (!$captchaRequired && isset($_SESSION['captcha_text'])) {
    unset($_SESSION['captcha_text']);
}

// Si ya está logueado, redirigir al dashboard
if (isset($_SESSION['username'])) {
    if (intranet_enforce_session_timeout()) {
        header('Location: ' . app_url('dashboard.php'));
        exit();
    }

    $error = 'Tu sesion ha caducado por inactividad. Vuelve a iniciar sesion.';
}

// Inicializar captcha si no existe (solo si es requerido)
if ($captchaRequired && !isset($_SESSION['captcha_text'])) {
    generateCaptchaString();
}

// Procesar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim($_POST['username'] ?? '');
    $pass = $_POST['password'] ?? '';

    // 1. Validar Captcha (solo si se requiere)
    if ($captchaRequired) {
        $captchaInput = strtoupper(trim($_POST['captcha'] ?? ''));
        $captchaSession = $_SESSION['captcha_text'] ?? '';
        if ($captchaInput !== $captchaSession) {
            $error = "El código de seguridad es incorrecto.";
            generateCaptchaString(); // Regenerar para evitar fuerza bruta
        }
    }

    // 2. Autenticar LDAP (si no hay error de captcha o no se requiere)
    if ($error === '') {
        $auth = authenticateUser($user, $pass);

        if ($auth['success']) {
            // Guardar datos en sesión
            $_SESSION['username'] = $auth['data']['username'];
            $_SESSION['givenName'] = $auth['data']['givenName'];

            // Guardamos el array completo de roles y el rol principal
            $_SESSION['roles'] = $auth['data']['roles'];
            $_SESSION['primaryRole'] = $auth['data']['primaryRole'];

            // Departamentos (grupos AD dept_*)
            $_SESSION['departments'] = $auth['data']['departments'] ?? [];
            $_SESSION['primaryDepartment'] = $auth['data']['primaryDepartment'] ?? null;

            $_SESSION['loginTime'] = $auth['data']['loginTime'];
            try {
                $pdo = db();
                $userThemeMode = intranet_user_theme_mode($pdo, (string) $_SESSION['username']);
                $userSessionTimeout = intranet_user_session_timeout_minutes($pdo, (string) $_SESSION['username']);
            } catch (Throwable $e) {
                $userThemeMode = INTRANET_THEME_MODE_DEFAULT;
                $userSessionTimeout = INTRANET_SESSION_TIMEOUT_DEFAULT_MINUTES;
            }

            // Limpiar captcha
            unset($_SESSION['captcha_text']);
            session_regenerate_id(true);
            intranet_set_session_theme_mode($userThemeMode);
            intranet_set_session_timeout_minutes($userSessionTimeout);
            intranet_touch_session_activity();

            // Redirigir
            header('Location: ' . app_url('dashboard.php'));
            exit();
        } else {
            $error = $auth['msg'];
            if ($captchaRequired) {
                generateCaptchaString(); // Regenerar captcha en fallo
            }
        }
    }
}

// Generar imagen para mostrar (solo si es requerido)
$captchaImage = $captchaRequired && isset($_SESSION['captcha_text'])
    ? generateCaptchaImage($_SESSION['captcha_text'])
    : '';
?>

<!DOCTYPE html>
<html lang="es" <?= intranet_theme_html_attr($_SESSION['theme_mode'] ?? INTRANET_THEME_MODE_DEFAULT); ?>>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Acceso Seguro | Intranet</title>
    <?= intranet_theme_bootstrap_script_tag($_SESSION['theme_mode'] ?? INTRANET_THEME_MODE_DEFAULT); ?>
    <!-- Referencia a la carpeta correcta de estilos -->
    <link rel="stylesheet" href="styles/css/style.css">
    <link rel="stylesheet" href="styles/css/theme-vars.css">
</head>
<body class="login-body">

<div class="login-container">
    <div class="login-header">
        <!-- LOGO IMAGEN -->
        <img src="styles/images/logo.png" alt="Logo Institucional" class="login-logo-img">
        
        <h2>Bienvenido</h2>
        <p>Introduce tus credenciales corporativas</p>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-error">
            <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="<?php echo htmlspecialchars(app_url('login.php'), ENT_QUOTES, 'UTF-8'); ?>" autocomplete="on">
        <div class="form-group">
            <label for="username">Usuario</label>
            <input type="text" id="username" name="username" class="form-control" placeholder="Ej: jgarcia" required autofocus autocomplete="username" autocapitalize="none" spellcheck="false" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
        </div>

        <div class="form-group">
            <label for="password">Contraseña</label>
            <input type="password" id="password" name="password" class="form-control" placeholder="••••••••" required autocomplete="current-password">
        </div>

        <?php if ($captchaRequired): ?>
        <div class="form-group">
            <label>Seguridad</label>
            <div class="captcha-container">
                <img src="data:image/png;base64,<?php echo $captchaImage; ?>" alt="Captcha" class="captcha-img">
                <input type="text" name="captcha" class="form-control" placeholder="Introduce el código de la imagen" required autocomplete="off">
            </div>
        </div>
        <?php endif; ?>

        <button type="submit" class="btn-primary">Iniciar Sesión</button>
    </form>
</div>

</body>
</html>
