<?php
// superadmin/login.php
// Acceso: http://localhost/SIGVP/superadmin/login.php
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

// ── Forzar HTTPS en producción (descomentar en servidor real) ───────────────
// if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
//     header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
//     exit;
// }

// Sesión separada para superadmin
session_name('sigvp_sa_sess');
session_start();

// Si ya está logueado redirigir al dashboard
if (!empty($_SESSION['superadmin'])) {
    header('Location: dashboard.php'); exit;
}

// ── CSRF token ──────────────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// ── Brute force protection (sesión + log de IP) ─────────────────────────────
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

if (!isset($_SESSION['sa_attempts']))      $_SESSION['sa_attempts']     = 0;
if (!isset($_SESSION['sa_blocked_until'])) $_SESSION['sa_blocked_until'] = 0;

$bloqueado = time() < $_SESSION['sa_blocked_until'];
$espera    = $bloqueado ? ceil(($_SESSION['sa_blocked_until'] - time()) / 60) : 0;
$error     = '';

if ($bloqueado) {
    $error = "Demasiados intentos. Espera {$espera} minuto(s).";

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ── Verificar CSRF ──────────────────────────────────────────────────────
    $csrfPost = $_POST['csrf_token'] ?? '';
    if (!hash_equals($_SESSION['csrf_token'], $csrfPost)) {
        $error = 'Token de seguridad inválido. Recarga la página e intenta de nuevo.';
    } else {

        $email = trim($_POST['email'] ?? '');
        $pass  = $_POST['password'] ?? '';

        if (!$email || !$pass) {
            $error = 'Ingresa email y contraseña.';
        } else {
            $db = getDB();
            $st = $db->prepare("
                SELECT id_superadmin, nombre, email, password_hash
                FROM   superadmins
                WHERE  email = :e AND activo = 1
                LIMIT  1
            ");
            $st->execute([':e' => $email]);
            $sa = $st->fetch(PDO::FETCH_ASSOC);

            if ($sa && password_verify($pass, $sa['password_hash'])) {
                // ── Login correcto ──────────────────────────────────────────
                $_SESSION['sa_attempts']      = 0;
                $_SESSION['sa_blocked_until'] = 0;
                // Regenerar CSRF y session ID para evitar session fixation
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                session_regenerate_id(true);

                $_SESSION['superadmin'] = [
                    'id'       => $sa['id_superadmin'],
                    'nombre'   => $sa['nombre'],
                    'email'    => $sa['email'],
                    'login_at' => time(),
                    'ip'       => $ip,
                ];

                $db->prepare("UPDATE superadmins SET ultimo_login = NOW() WHERE id_superadmin = :id")
                   ->execute([':id' => $sa['id_superadmin']]);

                error_log("[SIGVP][SA] Login exitoso — IP: {$ip} — email: {$email}");
                header('Location: dashboard.php'); exit;
            }

            // ── Login fallido ───────────────────────────────────────────────
            $_SESSION['sa_attempts']++;
            error_log("[SIGVP][SA] Intento fallido #{$_SESSION['sa_attempts']} — IP: {$ip} — email: {$email}");

            if ($_SESSION['sa_attempts'] >= 5) {
                $_SESSION['sa_blocked_until'] = time() + (15 * 60);
                $_SESSION['sa_attempts']      = 0;
                error_log("[SIGVP][SA] BLOQUEO activado — IP: {$ip}");
                $error = 'Demasiados intentos fallidos. Acceso bloqueado por 15 minutos.';
            } else {
                $r     = 5 - $_SESSION['sa_attempts'];
                $error = "Credenciales incorrectas. Intentos restantes: {$r}";
            }
        }
    }
}
?>
<!DOCTYPE html>
<?php
// ── Headers de seguridad HTTP ───────────────────────────────────────────────
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src https://cdnjs.cloudflare.com; script-src 'self' 'unsafe-inline';");
?>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SIGVP — Super Administrador</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{min-height:100vh;display:flex;align-items:center;justify-content:center;
     background:linear-gradient(135deg,#0f172a 0%,#1e1b4b 50%,#312e81 100%);
     font-family:'Segoe UI',sans-serif;}
.card{background:#fff;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.4);
      width:100%;max-width:400px;overflow:hidden;}
.card-top{background:linear-gradient(135deg,#1e1b4b,#4338ca);
          padding:32px 28px 24px;text-align:center;}
.ico{width:64px;height:64px;background:rgba(255,255,255,.15);border:2px solid rgba(255,255,255,.3);
     border-radius:16px;display:flex;align-items:center;justify-content:center;
     margin:0 auto 14px;font-size:1.6rem;}
.card-top h4{color:#fff;font-weight:700;margin:0 0 4px;font-size:18px;}
.card-top .badge-sa{display:inline-block;background:#fbbf24;color:#78350f;font-size:10px;
                    font-weight:700;padding:2px 10px;border-radius:20px;
                    letter-spacing:.5px;text-transform:uppercase;margin-top:6px;}
.card-body{padding:28px;}
.form-label{font-size:11px;font-weight:700;color:#555;text-transform:uppercase;
            letter-spacing:.5px;display:block;margin-bottom:6px;}
.input-wrap{position:relative;}
.input-wrap .ico2{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:.9rem;}
.input-wrap input{width:100%;padding:10px 12px 10px 36px;border-radius:10px;
                  border:1.5px solid #e0e0e0;font-size:.9rem;outline:none;
                  transition:border-color .2s,box-shadow .2s;}
.input-wrap input:focus{border-color:#4338ca;box-shadow:0 0 0 3px rgba(67,56,202,.12);}
.btn-login{width:100%;background:linear-gradient(90deg,#1e1b4b,#4338ca);border:none;
           color:#fff;border-radius:10px;padding:12px;font-weight:700;font-size:.95rem;
           cursor:pointer;box-shadow:0 3px 12px rgba(67,56,202,.35);transition:.2s;}
.btn-login:hover{opacity:.9;}
.btn-login:disabled{opacity:.5;cursor:not-allowed;}
.err{background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;border-radius:10px;
     padding:10px 14px;font-size:.84rem;margin-bottom:14px;display:flex;align-items:center;gap:8px;}
.back{text-align:center;margin-top:16px;font-size:.8rem;}
.back a{color:#6b7280;text-decoration:none;}
.back a:hover{color:#4338ca;}
.warning-strip{background:#fef3c7;border:1px solid #fcd34d;border-radius:8px;
               padding:8px 12px;font-size:11px;color:#92400e;margin-bottom:14px;
               display:flex;gap:6px;align-items:flex-start;}
.attempts-bar{height:3px;background:#e5e7eb;border-radius:3px;margin-top:10px;overflow:hidden;}
.attempts-fill{height:100%;border-radius:3px;transition:width .4s;
               background:linear-gradient(90deg,#10b981,#f59e0b,#ef4444);}
.secure-badge{display:flex;align-items:center;justify-content:center;gap:5px;
              font-size:10px;color:#9ca3af;margin-top:14px;}
.secure-badge i{color:#10b981;}
</style>
</head>
<body>
<div class="card">
  <div class="card-top">
    <div class="ico"><i class="fas fa-shield-halved" style="color:#fff"></i></div>
    <h4>Panel de Control</h4>
    <div class="badge-sa">Super Administrador</div>
  </div>
  <div class="card-body">
    <div class="warning-strip">
      <i class="fas fa-triangle-exclamation" style="color:#d97706;margin-top:1px;"></i>
      <span>Acceso restringido. Solo personal autorizado de SIGVP puede ingresar aquí.</span>
    </div>

    <?php if ($error): ?>
    <div class="err">
      <i class="fas <?= $bloqueado ? 'fa-clock' : 'fa-circle-exclamation' ?>"></i>
      <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <form method="POST">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
      <div class="mb-3" style="margin-bottom:14px;">
        <label class="form-label">Correo electrónico</label>
        <div class="input-wrap">
          <i class="fas fa-envelope ico2"></i>
          <input type="email" name="email" placeholder="Tu correo electrónico" required
                 <?= $bloqueado ? 'disabled' : '' ?>>
        </div>
      </div>
      <div class="mb-3" style="margin-bottom:20px;">
        <label class="form-label">Contraseña</label>
        <div class="input-wrap">
          <i class="fas fa-lock ico2"></i>
          <input type="password" name="password" id="passInput"
                 placeholder="••••••••" required
                 style="padding-right:42px;"
                 <?= $bloqueado ? 'disabled' : '' ?>>
          <button type="button" onclick="togglePass()"
            style="position:absolute;right:10px;top:50%;transform:translateY(-50%);
                   background:none;border:none;color:#9ca3af;cursor:pointer;font-size:.95rem;">
            <i class="fas fa-eye" id="passEye"></i>
          </button>
        </div>
      </div>
      <button type="submit" class="btn-login" <?= $bloqueado ? 'disabled' : '' ?>>
        <i class="fas fa-right-to-bracket me-2"></i>Acceder al panel
      </button>

      <?php if ($_SESSION['sa_attempts'] > 0 && !$bloqueado): ?>
      <div class="attempts-bar" title="Intentos fallidos">
        <div class="attempts-fill"
             style="width:<?= ($_SESSION['sa_attempts'] / 5) * 100 ?>%"></div>
      </div>
      <div style="font-size:10px;color:#9ca3af;text-align:center;margin-top:4px;">
        <?= $_SESSION['sa_attempts'] ?>/5 intentos fallidos
      </div>
      <?php endif; ?>
    </form>

    <div class="back">
      <a href="<?= BASE_URL ?>/auth/login.php">
        <i class="fas fa-arrow-left" style="font-size:.8rem;"></i> Volver al login de institutos
      </a>
    </div>
    <div class="secure-badge">
      <i class="fas fa-shield-halved"></i> Conexión protegida · CSRF · Sesión cifrada
    </div>
  </div>
</div>
<script>
function togglePass(){
  const i = document.getElementById('passInput');
  const e = document.getElementById('passEye');
  i.type = i.type === 'password' ? 'text' : 'password';
  e.className = i.type === 'text' ? 'fas fa-eye-slash' : 'fas fa-eye';
}
</script>
</body>
</html>