<?php
// login.php — Página de login de la intranet favala.es (multi-paso con 2FA)

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';

// Si ya está autenticado, redirigir al portal
if (auth_is_logged_in()) {
    $redir = filter_input(INPUT_GET, 'redir', FILTER_SANITIZE_URL) ?? BASE_PATH . '/';
    if (!str_starts_with($redir, BASE_PATH . '/') && $redir !== BASE_PATH) {
        $redir = BASE_PATH . '/';
    }
    header('Location: ' . $redir);
    exit;
}

$error   = '';
$step    = 'credentials';   // 'credentials' | 'push' | 'totp'
$txn_id  = '';
$redir   = filter_input(INPUT_GET, 'redir', FILTER_SANITIZE_URL) ?? BASE_PATH . '/';
if (!str_starts_with($redir, BASE_PATH . '/') && $redir !== BASE_PATH) {
    $redir = BASE_PATH . '/';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'step1';

    if ($action === 'step1') {
        // ── Fase 1: validar usuario + contraseña ──────────────────────────────
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        $redir    = filter_input(INPUT_POST, 'redir', FILTER_SANITIZE_URL) ?? BASE_PATH . '/';
        if (!str_starts_with($redir, BASE_PATH . '/') && $redir !== BASE_PATH) {
            $redir = BASE_PATH . '/';
        }

        $result = auth_login_step1($username, $password);

        if (isset($result['success']) && $result['success'] === false) {
            $error = $result['error'];
        } elseif ($result['step'] === 'done') {
            // Sin 2FA configurado (degradación) → acceso directo
            header('Location: ' . $redir);
            exit;
        } elseif ($result['step'] === 'push') {
            $step   = 'push';
            $txn_id = $result['txn'];
        } elseif ($result['step'] === 'totp') {
            $step = 'totp';
        }

    } elseif ($action === 'step2_totp') {
        // ── Fase 2: verificar código OTP ──────────────────────────────────────
        $otp   = trim($_POST['otp'] ?? '');
        $redir = filter_input(INPUT_POST, 'redir', FILTER_SANITIZE_URL) ?? BASE_PATH . '/';
        if (!str_starts_with($redir, BASE_PATH . '/') && $redir !== BASE_PATH) {
            $redir = BASE_PATH . '/';
        }

        if ($otp === '') {
            $step  = 'totp';
            $error = 'Introduce el código de tu autenticador.';
        } else {
            $result = auth_login_step2_totp($otp);
            if ($result['success']) {
                header('Location: ' . $redir);
                exit;
            }
            $step  = 'totp';
            $error = $result['error'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Intranet — favala.es</title>
<meta name="robots" content="noindex, nofollow">
<style>
  :root {
    --bg:        #040c06;
    --surface:   #0d1f10;
    --border:    #1a3d20;
    --green:     #3a7d44;
    --green-hi:  #5cb368;
    --text:      #c8e6cc;
    --muted:     #6b9e72;
    --danger:    #c0392b;
    --danger-bg: #2c0d0a;
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    background: var(--bg);
    color: var(--text);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 1rem;
  }

  /* Starfield */
  body::before {
    content: '';
    position: fixed;
    inset: 0;
    background-image:
      radial-gradient(1px 1px at 20% 30%, rgba(90,200,100,.6) 0%, transparent 100%),
      radial-gradient(1px 1px at 80% 10%, rgba(90,200,100,.4) 0%, transparent 100%),
      radial-gradient(1px 1px at 50% 70%, rgba(90,200,100,.5) 0%, transparent 100%),
      radial-gradient(1px 1px at 10% 80%, rgba(90,200,100,.3) 0%, transparent 100%),
      radial-gradient(1px 1px at 90% 60%, rgba(90,200,100,.4) 0%, transparent 100%),
      radial-gradient(1px 1px at 35% 55%, rgba(90,200,100,.3) 0%, transparent 100%),
      radial-gradient(1px 1px at 65% 40%, rgba(90,200,100,.5) 0%, transparent 100%),
      radial-gradient(1px 1px at 75% 85%, rgba(90,200,100,.3) 0%, transparent 100%);
    pointer-events: none;
    z-index: 0;
  }

  .login-card {
    position: relative;
    z-index: 1;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 2.5rem 2rem;
    width: 100%;
    max-width: 380px;
    box-shadow: 0 8px 32px rgba(0,0,0,.6), 0 0 0 1px rgba(58,125,68,.15);
  }

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

  .logo-icon {
    font-size: 2.5rem;
    line-height: 1;
    margin-bottom: .5rem;
  }

  .logo h1 {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--green-hi);
    letter-spacing: 0.05em;
    text-transform: uppercase;
  }

  .logo p {
    font-size: .8rem;
    color: var(--muted);
    margin-top: .25rem;
  }

  .separator {
    border: none;
    border-top: 1px solid var(--border);
    margin-bottom: 1.5rem;
  }

  label {
    display: block;
    font-size: .8rem;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .05em;
    margin-bottom: .4rem;
  }

  input[type=text], input[type=password], input[type=number] {
    width: 100%;
    background: rgba(0,0,0,.4);
    border: 1px solid var(--border);
    border-radius: 6px;
    color: var(--text);
    padding: .65rem .85rem;
    font-size: .95rem;
    outline: none;
    transition: border-color .2s;
    margin-bottom: 1.2rem;
  }

  input[type=text]:focus, input[type=password]:focus, input[type=number]:focus {
    border-color: var(--green);
  }

  input[type=submit], button.btn-primary {
    width: 100%;
    background: var(--green);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: .75rem;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    letter-spacing: .03em;
    transition: background .2s;
    margin-top: .4rem;
  }

  input[type=submit]:hover, button.btn-primary:hover { background: var(--green-hi); }

  .error {
    background: var(--danger-bg);
    border: 1px solid var(--danger);
    border-radius: 6px;
    color: #e74c3c;
    padding: .7rem 1rem;
    font-size: .88rem;
    margin-bottom: 1.2rem;
    display: flex;
    gap: .5rem;
    align-items: center;
  }

  .footer-note {
    text-align: center;
    margin-top: 1.5rem;
    font-size: .75rem;
    color: var(--muted);
  }

  .back-link {
    display: block;
    text-align: center;
    margin-top: .75rem;
    font-size: .8rem;
    color: var(--muted);
    text-decoration: none;
  }
  .back-link:hover { color: var(--green-hi); }

  /* Push waiting screen */
  .push-waiting {
    text-align: center;
    padding: .5rem 0 1rem;
  }
  .push-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
    animation: pulse 2s ease-in-out infinite;
  }
  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50%       { opacity: .5; }
  }
  .push-waiting h2 {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--green-hi);
    margin-bottom: .5rem;
  }
  .push-waiting p {
    font-size: .88rem;
    color: var(--muted);
    margin-bottom: 1.5rem;
    line-height: 1.5;
  }
  .push-status {
    font-size: .85rem;
    color: var(--muted);
    margin-top: .8rem;
  }
</style>
</head>
<body>

<div class="login-card">
  <div class="logo">
    <div class="logo-icon">🔐</div>
    <h1>Intranet</h1>
    <p>República Independiente de Internet</p>
  </div>
  <hr class="separator">

  <?php if ($error): ?>
  <div class="error">
    <span>⚠</span>
    <span><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
  </div>
  <?php endif; ?>

<?php if ($step === 'credentials'): ?>
  <!-- ── Paso 1: usuario + contraseña ── -->
  <form method="POST" action="" autocomplete="on">
    <input type="hidden" name="action" value="step1">
    <input type="hidden" name="redir" value="<?= htmlspecialchars($redir, ENT_QUOTES, 'UTF-8') ?>">

    <label for="username">Usuario</label>
    <input type="text" id="username" name="username"
           value="<?= htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
           autocomplete="username" autofocus required>

    <label for="password">Contraseña</label>
    <input type="password" id="password" name="password"
           autocomplete="current-password" required>

    <input type="submit" value="Entrar">
  </form>
  <div class="footer-note">Dominio FAVALA · Autenticación LDAP + 2FA</div>

<?php elseif ($step === 'push'): ?>
  <!-- ── Paso 2a: esperar aprobación push ── -->
  <div class="push-waiting">
    <div class="push-icon">📱</div>
    <h2>Aprueba en tu móvil</h2>
    <p>Se ha enviado una notificación a la app <strong>pi-authenticator</strong>.<br>
       Tienes 5 minutos para aprobar el acceso.</p>
    <div class="push-status" id="push-status">Esperando aprobación…</div>
  </div>
  <a class="back-link" href="<?= htmlspecialchars(BASE_PATH . '/login.php?redir=' . urlencode($redir), ENT_QUOTES, 'UTF-8') ?>">← Volver al login</a>

  <script>
  (function() {
    const txn   = <?= json_encode($txn_id) ?>;
    const redir = <?= json_encode($redir) ?>;
    const statusEl = document.getElementById('push-status');
    let attempts = 0;
    const maxAttempts = 30; // 5 min × 10s

    function poll() {
      fetch(<?= json_encode(BASE_PATH . '/poll.php') ?> + '?txn=' + encodeURIComponent(txn), {
        credentials: 'same-origin'
      })
      .then(r => r.json())
      .then(data => {
        if (data.status === 'approved') {
          statusEl.textContent = '✔ Aprobado. Redirigiendo…';
          window.location.href = redir;
        } else if (data.status === 'expired') {
          statusEl.textContent = '⚠ Sesión caducada. Recarga la página.';
        } else {
          attempts++;
          if (attempts < maxAttempts) {
            setTimeout(poll, 3000);
          } else {
            statusEl.textContent = '⏱ Tiempo agotado. Vuelve a hacer login.';
          }
        }
      })
      .catch(() => {
        attempts++;
        if (attempts < maxAttempts) setTimeout(poll, 3000);
      });
    }
    setTimeout(poll, 2000);
  })();
  </script>

<?php elseif ($step === 'totp'): ?>
  <!-- ── Paso 2b: introducir código TOTP ── -->
  <form method="POST" action="" autocomplete="off">
    <input type="hidden" name="action" value="step2_totp">
    <input type="hidden" name="redir" value="<?= htmlspecialchars($redir, ENT_QUOTES, 'UTF-8') ?>">

    <label for="otp">Código de verificación</label>
    <input type="number" id="otp" name="otp" placeholder="123456"
           inputmode="numeric" pattern="[0-9]{6}" maxlength="6"
           autocomplete="one-time-code" autofocus required>

    <input type="submit" value="Verificar">
  </form>
  <a class="back-link" href="<?= htmlspecialchars(BASE_PATH . '/login.php?redir=' . urlencode($redir), ENT_QUOTES, 'UTF-8') ?>">← Volver al login</a>

<?php endif; ?>

  <a class="back-link" href="/">← Volver a la web pública</a>
</div>

</body>
</html>
