<?php
require_once __DIR__ . '/includes/bootstrap.php';

// [PATCH DEMO 2026-07-02] Prellenado del login para la demo embebida (?demo=1).
// Reversion: borrar este bloque y los cambios marcados en los inputs de abajo.
$tf_demo        = (isset($_GET['demo']) && $_GET['demo'] === '1');
$tf_demo_correo = $tf_demo ? 'Rubenmel88@gmail.com'   : '';
$tf_demo_pass   = $tf_demo ? 'Rub3nm3l0' : '';

if (is_logged_in()) redirect(base_url('dashboard.php'));

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();

    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    // IP del cliente, sólo confiando en cabeceras de Cloudflare si la conexión
    // realmente viene de un rango oficial de Cloudflare (anti-spoofing).
    $ip = function_exists('client_ip') ? client_ip() : ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');

    if (!check_rate_limit($ip)) {
        global $CONFIG;
        $mins = (int)($CONFIG['security']['lockout_minutes'] ?? 15);
        $error = "Demasiados intentos fallidos. Espera {$mins} minutos.";
    } else {
        $stmt = db()->prepare("SELECT * FROM users WHERE email = ? AND active = 1 LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            record_login_attempt($ip, $email, true);
            session_regenerate_id(true);
            $_SESSION['user_id'] = (int)$user['id'];
            db()->prepare("UPDATE users SET last_active = NOW() WHERE id = ?")
                ->execute([$user['id']]);
            if (function_exists('audit_log')) {
                audit_log('login_success', 'user', (int)$user['id'], $user['name'] ?? $email, "IP: {$ip}");
            }
            redirect(base_url('dashboard.php'));
        } else {
            record_login_attempt($ip, $email, false);
            if (function_exists('audit_log')) {
                // Log de intento fallido (sin user_id porque no se logró autenticar)
                try {
                    db()->prepare("INSERT INTO audit_log (user_id, user_name, action, entity_type, entity_name, detail, ip) VALUES (NULL, ?, 'login_failed', 'user', ?, ?, ?)")
                        ->execute([$email, $email, "Credenciales inválidas", $ip]);
                } catch (\Throwable) {}
            }
            $error = 'Correo o contraseña incorrectos.';
        }
    }
}

$appName = setting('app_name', 'TaskFlow');
?>
<!DOCTYPE html>
<html lang="es" id="html-root">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0d4f4a">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="<?= e($appName) ?>">
<link rel="manifest" href="<?= e(base_url('manifest.json')) ?>">
<link rel="icon" type="image/png" sizes="64x64"   href="<?= e(base_url('assets/favicon-64.png')) ?>">
<link rel="icon" type="image/png" sizes="192x192" href="<?= e(base_url('assets/icon-192.png')) ?>">
<link rel="icon" type="image/png" sizes="512x512" href="<?= e(base_url('assets/icon-512.png')) ?>">
<link rel="apple-touch-icon" href="<?= e(base_url('assets/icon-192.png')) ?>">
<title>Iniciar sesión — <?= e($appName) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@300;400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= e(base_url('assets/style.css?v=501')) ?>">
<meta name="color-scheme" content="light dark">
<script>(function(){var t=localStorage.getItem('tf_theme')||(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');document.documentElement.setAttribute('data-theme',t);})();</script>
</head>
<body class="login-body">

<div class="login-split">

  <!-- ───────────────  HERO (izquierda)  ─────────────── -->
  <aside class="login-hero">
    <!-- Fondo decorativo -->
    <div class="login-hero-bg" aria-hidden="true">
      <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
        <defs>
          <radialGradient id="g1" cx="20%" cy="20%" r="60%">
            <stop offset="0%" stop-color="rgba(255,255,255,.15)"/>
            <stop offset="100%" stop-color="rgba(255,255,255,0)"/>
          </radialGradient>
          <radialGradient id="g2" cx="80%" cy="80%" r="55%">
            <stop offset="0%" stop-color="rgba(255,255,255,.08)"/>
            <stop offset="100%" stop-color="rgba(255,255,255,0)"/>
          </radialGradient>
        </defs>
        <rect width="200" height="200" fill="url(#g1)"/>
        <rect width="200" height="200" fill="url(#g2)"/>
      </svg>
    </div>

    <div class="login-hero-content">
      <div class="login-brand">
        <div class="login-brand-mark">
          <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="7" height="7" rx="1"/>
            <rect x="14" y="3" width="7" height="7" rx="1"/>
            <rect x="14" y="14" width="7" height="7" rx="1"/>
            <rect x="3" y="14" width="7" height="7" rx="1"/>
          </svg>
        </div>
        <span class="login-brand-name"><?= e($appName) ?></span>
      </div>

      <div class="login-hero-headline">
        <h1>Tu equipo,<br>tu trabajo,<br><span class="login-hero-accent">en flujo.</span></h1>
        <p class="login-hero-tagline">
          Plataforma BPM para gestionar campañas, mayoristas y CEDIS sin perder visibilidad.
        </p>
      </div>

      <ul class="login-hero-features">
        <li>
          <span class="lhf-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
          </span>
          Trazabilidad completa de cada tarea
        </li>
        <li>
          <span class="lhf-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
          </span>
          Procesos repetibles por plantilla
        </li>
        <li>
          <span class="lhf-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
          </span>
          Alertas y SLA automáticos
        </li>
      </ul>
    </div>

    <div class="login-hero-foot">


  <span>© <?= date('Y') ?> Powered by Nexus </span>

    </div>
  </aside>

  <!-- ───────────────  FORMULARIO (derecha)  ─────────────── -->
  <main class="login-form-wrap">
    <div class="login-form-card">

      <!-- Mobile brand (visible solo en chico) -->
      <div class="login-mobile-brand">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <rect x="3" y="3" width="7" height="7" rx="1"/>
          <rect x="14" y="3" width="7" height="7" rx="1"/>
          <rect x="14" y="14" width="7" height="7" rx="1"/>
          <rect x="3" y="14" width="7" height="7" rx="1"/>
        </svg>
        <span><?= e($appName) ?></span>
      </div>

      <header class="login-form-head">
        <h2>Bienvenido de vuelta</h2>
        <p>Ingresa tus credenciales para acceder.</p>
      </header>

      <?php if ($error): ?>
      <div class="login-alert login-alert-error">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
          <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
        </svg>
        <span><?= e($error) ?></span>
      </div>
      <?php endif; ?>

      <?php foreach (flash_get() as $_f): ?>
      <div class="login-alert login-alert-<?= e($_f['type']) ?>">
        <span><?= e($_f['msg']) ?></span>
      </div>
      <?php endforeach; ?>

      <form method="POST" class="login-form" autocomplete="on">
        <?= csrf_input() ?>

        <div class="login-field">
          <label for="email">Correo electrónico</label>
          <div class="login-input-wrap">
            <span class="login-input-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
                <polyline points="22,6 12,13 2,6"/>
              </svg>
            </span>
            <input type="email" name="email" id="email" class="login-input" required autofocus
                   value="<?= e($_POST['email'] ?? $tf_demo_correo) ?>" placeholder="tucorreo@empresa.com" autocomplete="email"> <?php /* [PATCH DEMO] original del value: e($_POST['email'] ?? '') */ ?>
          </div>
        </div>

        <div class="login-field">
          <div class="login-label-row">
            <label for="password">Contraseña</label>
            <a href="<?= e(base_url('forgot.php')) ?>" class="login-forgot">¿Olvidaste tu contraseña?</a>
          </div>
          <div class="login-input-wrap">
            <span class="login-input-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
              </svg>
            </span>
            <input type="password" name="password" id="password" class="login-input" required
                   value="<?= e($tf_demo_pass) ?>"
                   placeholder="••••••••" autocomplete="current-password">
            <button type="button" class="login-toggle-pass" onclick="togglePass()" aria-label="Mostrar/ocultar contraseña">
              <svg id="eye-open" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
              </svg>
              <svg id="eye-closed" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            </button>
          </div>
        </div>

        <button type="submit" class="login-submit">
          <span>Entrar</span>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
            <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>
          </svg>
        </button>
      </form>

      <div class="login-theme-toggle">
        <button type="button" onclick="toggleLoginTheme()" title="Cambiar tema">
          <svg id="login-icon-dark" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
          <svg id="login-icon-light" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/></svg>
        </button>
      </div>

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

<script>
function togglePass() {
  var inp = document.getElementById('password');
  var eo = document.getElementById('eye-open');
  var ec = document.getElementById('eye-closed');
  if (inp.type === 'password') { inp.type = 'text'; eo.style.display='none'; ec.style.display=''; }
  else { inp.type = 'password'; eo.style.display=''; ec.style.display='none'; }
}
function toggleLoginTheme() {
  var current = document.documentElement.getAttribute('data-theme') || 'light';
  var next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  try { localStorage.setItem('tf_theme', next); } catch(e) {}
  syncLoginThemeIcons();
}
function syncLoginThemeIcons() {
  var theme = document.documentElement.getAttribute('data-theme') || 'light';
  var dark = document.getElementById('login-icon-dark');
  var light = document.getElementById('login-icon-light');
  if (dark) dark.style.display = theme === 'dark' ? 'none' : '';
  if (light) light.style.display = theme === 'dark' ? '' : 'none';
}
syncLoginThemeIcons();
</script>
</body>
</html>
