<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

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

start_session();

/* =========================
   Helpers seguros (inline)
========================= */
function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function csrf_token_local(): string {
  if (empty($_SESSION['csrf_login'])) {
    $_SESSION['csrf_login'] = bin2hex(random_bytes(32));
  }
  return (string)$_SESSION['csrf_login'];
}
function csrf_check_local(): void {
  $token = (string)($_POST['csrf'] ?? '');
  $sess  = (string)($_SESSION['csrf_login'] ?? '');
  if ($token === '' || $sess === '' || !hash_equals($sess, $token)) {
    http_response_code(419);
    die("CSRF inválido. Recargá la página e intentá nuevamente.");
  }
}

/* =========================
   Redirección segura (?next=)
========================= */
$next = (string)($_GET['next'] ?? '');
if ($next !== '') {
  if ($next[0] !== '/' || str_starts_with($next, '//') || str_contains($next, "\n") || str_contains($next, "\r")) {
    $next = '';
  }
}
$defaultNext = '/Comercio/public/dashboard.php';
$redirectTo = $next !== '' ? $next : $defaultNext;

if (!empty($_SESSION['uid'])) {
  header('Location: ' . $defaultNext);
  exit;
}

/* =========================
   Rate limit por sesión
========================= */
$MAX_ATTEMPTS = 6;
$WINDOW_SEC   = 10 * 60;
$LOCK_SEC     = 5 * 60;

if (!isset($_SESSION['login_rl'])) {
  $_SESSION['login_rl'] = [
    'fails' => 0,
    'first_fail_at' => 0,
    'locked_until' => 0,
  ];
}
$rl = &$_SESSION['login_rl'];

$now = time();
if (($rl['locked_until'] ?? 0) > $now) {
  $remain = (int)$rl['locked_until'] - $now;
  $error = "Demasiados intentos. Probá de nuevo en {$remain}s.";
  $locked = true;
} else {
  $locked = false;
  if (!empty($rl['first_fail_at']) && ($now - (int)$rl['first_fail_at']) > $WINDOW_SEC) {
    $rl['fails'] = 0;
    $rl['first_fail_at'] = 0;
  }
}

$error = $error ?? null;
$identifier_old = '';

/* =========================
   Procesar login
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$locked) {
  csrf_check_local();

  $id = trim((string)($_POST['identifier'] ?? ''));
  $pw = (string)($_POST['password'] ?? '');
  $identifier_old = $id;

  $id = preg_replace('/\s+/', ' ', $id) ?? $id;

  if ($id === '' || $pw === '') {
    $error = "Completá usuario/cédula y contraseña.";
  } else {
    $ok = login($id, $pw);

    if ($ok) {
      $rl['fails'] = 0;
      $rl['first_fail_at'] = 0;
      $rl['locked_until'] = 0;
      $_SESSION['csrf_login'] = bin2hex(random_bytes(32));

      header('Location: ' . $redirectTo);
      exit;
    }

    if (empty($rl['first_fail_at'])) $rl['first_fail_at'] = $now;
    $rl['fails'] = (int)$rl['fails'] + 1;

    if ($rl['fails'] >= $MAX_ATTEMPTS) {
      $rl['locked_until'] = $now + $LOCK_SEC;
      $error = "Demasiados intentos. Se bloqueó temporalmente el acceso por seguridad.";
    } else {
      $left = max(0, $MAX_ATTEMPTS - (int)$rl['fails']);
      $error = "Usuario/Cédula o contraseña incorrectos. Intentos restantes: {$left}.";
    }
  }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Acceso · Sistema Académico Unificado</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">

  <style>
    :root{
      --brand-blue:#0d6efd;
      --brand-yellow:#FCCB07;
      --ink:#0b1220;
      --muted:#6b7280;
      --card: rgba(255,255,255,.90);
    }

    body{
      min-height:100vh;
      background:
        radial-gradient(1100px 600px at 18% 6%, rgba(13,110,253,.35), transparent 60%),
        radial-gradient(950px 560px at 88% 10%, rgba(252,203,7,.40), transparent 58%),
        linear-gradient(135deg, rgba(13,110,253,.10) 0%, rgba(255,255,255,1) 55%);
      display:flex;
      align-items:center;
      color: var(--ink);
    }

    .glass{
      background: var(--card);
      backdrop-filter: blur(12px);
      border: 1px solid rgba(17,24,39,.10);
      box-shadow: 0 22px 60px rgba(17,24,39,.16);
      border-radius: 22px;
    }

    /* Panel institucional más vivo */
    .brand{
      background: linear-gradient(135deg, var(--brand-blue) 0%, #084298 42%, var(--brand-yellow) 100%);
      color:#fff;
      border-radius: 22px;
      padding: 20px;
      box-shadow: 0 22px 60px rgba(17,24,39,.20);
      position:relative;
      overflow:hidden;
    }
    .brand:before{
      content:"";
      position:absolute;
      right:-90px; top:-90px;
      width:320px; height:320px;
      background: radial-gradient(circle, rgba(255,255,255,.30), transparent 70%);
      transform: rotate(10deg);
      pointer-events:none;
    }
    .brand:after{
      content:"";
      position:absolute;
      left:-130px; bottom:-160px;
      width:420px; height:420px;
      background: radial-gradient(circle, rgba(255,255,255,.18), transparent 70%);
      pointer-events:none;
    }

    .logos{
      display:flex;
      align-items:center;
      gap:16px;
    }
    .brand-logo{
      height: 108px;
      width:auto;
      border-radius: 18px;
      background:#fff;
      padding:10px;
      box-shadow: 0 16px 36px rgba(0,0,0,.28), 0 0 0 3px rgba(255,255,255,.45);
    }
    @media (min-width: 992px){
      .brand-logo{ height: 128px; }
    }

    .btn-brand{
      color:#111 !important;
      border: 1px solid rgba(17,24,39,.12) !important;
      background: linear-gradient(90deg, var(--brand-blue), var(--brand-yellow)) !important;
      font-weight: 900;
      letter-spacing:.2px;
      box-shadow: 0 16px 34px rgba(13,110,253,.18), 0 16px 34px rgba(252,203,7,.18);
    }
    .btn-brand:hover{ filter: saturate(1.08) brightness(1.02); }
    .btn-brand:disabled{ opacity:.72; cursor:not-allowed; }

    .form-control:focus{
      border-color: rgba(13,110,253,.55);
      box-shadow: 0 0 0 .2rem rgba(13,110,253,.16);
    }

    .small-muted{ color: var(--muted); }
    .caps{
      display:none;
      font-size:.85rem;
      color:#b45309;
    }

    .badge-soft{
      background: rgba(255,255,255,.18);
      border: 1px solid rgba(255,255,255,.30);
      color:#fff;
      border-radius:999px;
      padding:6px 10px;
      font-weight:700;
      backdrop-filter: blur(8px);
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="row justify-content-center g-3">
      <div class="col-12 col-md-10 col-lg-9 col-xl-8">
        <div class="row g-3 align-items-stretch">

          <!-- Lado institucional -->
          <div class="col-12 col-lg-6">
            <div class="brand h-100 d-flex flex-column justify-content-between">
              <div class="d-flex align-items-start gap-3 position-relative">
                <div class="logos">
                  <img class="brand-logo" src="/Comercio/public/assets/logo.png" alt="Escuela Nacional de Comercio">
                  <img class="brand-logo" src="/Comercio/public/assets/logo_caazapa.png" alt="Colegio Nacional Prof. Carlos A. Ramírez F.">
                </div>
              </div>

              <div class="mt-4 position-relative">
                <div class="text-uppercase small opacity-75">Sistema Académico Unificado</div>
                <div class="h3 fw-bold mb-1">Caazapá</div>
                <div class="opacity-75">Escuela Nacional de Comercio · Colegio Nacional Prof. Carlos A. Ramírez F.</div>

                <div class="d-flex gap-2 flex-wrap mt-3">
                  <span class="badge-soft"><i class="bi bi-fingerprint me-1"></i>Asistencia biométrica</span>
                  <span class="badge-soft"><i class="bi bi-shield-check me-1"></i>Acceso seguro</span>
                  <span class="badge-soft"><i class="bi bi-journal-check me-1"></i>Gestión académica</span>
                </div>

                <div class="small opacity-75 mt-3">
                  Ingresá con tu <b>usuario</b> o <b>cédula</b> y tu contraseña.
                </div>
              </div>
            </div>
          </div>

          <!-- Form login -->
          <div class="col-12 col-lg-6">
            <div class="glass p-4 h-100">
              <div class="d-flex align-items-center justify-content-between mb-2">
                <div class="h5 fw-bold mb-0">Acceso al sistema</div>
                <span class="badge text-bg-primary"><i class="bi bi-lock me-1"></i>Login</span>
              </div>
              <div class="small-muted mb-3">Alumnos, tutores y personal autorizado.</div>

              <?php if (!empty($error)): ?>
                <div class="alert alert-danger">
                  <i class="bi bi-exclamation-triangle me-1"></i>
                  <?= h($error) ?>
                </div>
              <?php endif; ?>

              <?php if (!empty($next)): ?>
                <div class="alert alert-info py-2 small mb-3">
                  <i class="bi bi-info-circle me-1"></i>
                  Al iniciar sesión, volverás a: <b><?= h($next) ?></b>
                </div>
              <?php endif; ?>

              <form method="post" autocomplete="off" class="mt-2" id="loginForm">
                <input type="hidden" name="csrf" value="<?= h(csrf_token_local()) ?>">

                <div class="mb-3">
                  <label class="form-label">Usuario o Cédula</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                    <input class="form-control" name="identifier" placeholder="Ej: admin o 1234567"
                           value="<?= h($identifier_old) ?>" required autofocus>
                  </div>
                  <div class="small text-muted mt-1">Podés ingresar con <b>username</b> o con tu <b>CI</b>.</div>
                </div>

                <div class="mb-2">
                  <label class="form-label">Contraseña</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                    <input class="form-control" type="password" name="password" required id="pw">
                    <button class="btn btn-outline-secondary" type="button" id="togglePw" title="Mostrar/ocultar">
                      <i class="bi bi-eye"></i>
                    </button>
                  </div>
                  <div class="caps mt-2" id="capsWarn"><i class="bi bi-capslock me-1"></i>Caps Lock activado</div>
                </div>

                <button class="btn btn-brand w-100 py-2 mt-3" type="submit" id="btnSubmit" <?= $locked ? 'disabled' : '' ?>>
                  <span id="btnText"><i class="bi bi-box-arrow-in-right me-1"></i>Ingresar</span>
                  <span id="btnLoading" class="d-none"><span class="spinner-border spinner-border-sm me-2"></span>Ingresando...</span>
                </button>

                <div class="text-center small-muted mt-3">
                  ¿Problemas de acceso? Contactar a Secretaría.
                </div>
              </form>

              <hr class="my-4">

              <div class="d-flex justify-content-between small-muted">
                <span><i class="bi bi-geo-alt me-1"></i>Caazapá</span>
                <span><?= h(date('Y')) ?> · Sistema Unificado</span>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Show/Hide password
  const pw = document.getElementById('pw');
  const toggle = document.getElementById('togglePw');
  toggle?.addEventListener('click', () => {
    const isPass = pw.type === 'password';
    pw.type = isPass ? 'text' : 'password';
    toggle.innerHTML = isPass ? '<i class="bi bi-eye-slash"></i>' : '<i class="bi bi-eye"></i>';
  });

  // Caps lock warning
  const capsWarn = document.getElementById('capsWarn');
  pw?.addEventListener('keyup', (e) => {
    const caps = e.getModifierState && e.getModifierState('CapsLock');
    capsWarn.style.display = caps ? 'block' : 'none';
  });

  // Loading state
  const form = document.getElementById('loginForm');
  const btnText = document.getElementById('btnText');
  const btnLoading = document.getElementById('btnLoading');
  const btnSubmit = document.getElementById('btnSubmit');

  form?.addEventListener('submit', () => {
    btnSubmit.disabled = true;
    btnText.classList.add('d-none');
    btnLoading.classList.remove('d-none');
  });
</script>
</body>
</html>