<?php
ob_start();
// auth/login.php
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config'   . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'auth.php';
startSession();

// ── Seguridad: headers + HTTPS ───────────────────────────────
securityHeaders();
// forzarHttps(); // ← Descomenta cuando el servidor tenga certificado SSL

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

// Si ya está logueado, redirigir a su dashboard
if (isLoggedIn()) {
    header('Location: ' . ROL_REDIRECT[$_SESSION['user']['id_rol']]);
    exit;
}

// Capturar y sanear el token de instituto (?inst=CV234)
$instToken = preg_replace('/[^A-Za-z0-9_\\-]/', '', $_GET['inst'] ?? $_POST['inst'] ?? '');

// Cargar datos del instituto según el token de la URL
// Si no hay token o el token no coincide con ningún instituto activo → bloquear acceso
$db = getDB();
$instValido = false;

if ($instToken !== '') {
    $stI = $db->prepare(
        "SELECT nombre, logo, ciudad, provincia FROM institutos WHERE token = :tk AND activo = 1 LIMIT 1"
    );
    $stI->execute([':tk' => $instToken]);
    $inst = $stI->fetch() ?: [];
    $instValido = !empty($inst);
} else {
    $inst = [];
    $instValido = false;
}

// ── Sin código de institución válido → mostrar página de error y detener todo ──
if (!$instValido) {
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>SIGVPT — Acceso no permitido</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"/>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet"/>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Plus Jakarta Sans', sans-serif;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #0c2d4e 0%, #1a5f8a 60%, #2196c9 100%);
      padding: 24px;
    }
    .err-card {
      background: #fff;
      border-radius: 20px;
      padding: 3rem 2.5rem;
      max-width: 480px;
      width: 100%;
      text-align: center;
      box-shadow: 0 20px 60px rgba(0,0,0,.35);
    }
    .err-icon-wrap {
      width: 80px; height: 80px;
      border-radius: 50%;
      background: #fef2f2;
      border: 2px solid #fecaca;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
    }
    .err-icon-wrap i { font-size: 32px; color: #dc2626; }
    .err-titulo {
      font-size: 22px;
      font-weight: 800;
      color: #0c2d4e;
      margin-bottom: 8px;
    }
    .err-sub {
      font-size: 14px;
      color: #64748b;
      line-height: 1.6;
      margin-bottom: 24px;
    }
    .err-code {
      background: #f8fafc;
      border: 1px solid #e2e8f0;
      border-radius: 10px;
      padding: 12px 16px;
      font-size: 13px;
      color: #475569;
      margin-bottom: 24px;
      display: flex;
      align-items: center;
      gap: 8px;
      text-align: left;
    }
    .err-code i { color: #94a3b8; flex-shrink: 0; }
    .err-url {
      font-family: monospace;
      font-size: 12px;
      background: #f1f5f9;
      border: 1px solid #e2e8f0;
      border-radius: 8px;
      padding: 10px 14px;
      color: #0c2d4e;
      word-break: break-all;
      margin-bottom: 8px;
      text-align: left;
    }
    .err-url span { color: #dc2626; font-weight: 700; }
    .err-url-ok {
      font-family: monospace;
      font-size: 12px;
      background: #f0fdf4;
      border: 1px solid #bbf7d0;
      border-radius: 8px;
      padding: 10px 14px;
      color: #065f46;
      word-break: break-all;
      margin-bottom: 24px;
      text-align: left;
    }
    .err-url-ok span { color: #059669; font-weight: 700; }
    .err-footer {
      font-size: 11px;
      color: #94a3b8;
      margin-top: 20px;
    }
    .badge-error {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      background: #fef2f2;
      border: 1px solid #fecaca;
      color: #dc2626;
      font-size: 11px;
      font-weight: 700;
      letter-spacing: .5px;
      text-transform: uppercase;
      padding: 4px 12px;
      border-radius: 20px;
      margin-bottom: 16px;
    }
  </style>
</head>
<body>
  <div class="err-card">

    <div class="err-icon-wrap">
      <i class="fa fa-link-slash"></i>
    </div>

    <div class="badge-error">
      <i class="fa fa-triangle-exclamation"></i>
      Código de acceso requerido
    </div>

    <div class="err-titulo">Dirección incorrecta</div>
    <div class="err-sub">
      Esta dirección no es válida para acceder al sistema.<br>
      Se requiere un <strong>código de acceso institucional</strong> para ingresar al sistema.
    </div>

    <div class="err-code">
      <i class="fa fa-circle-xmark"></i>
      <div>
        <div style="font-weight:700;color:#dc2626;margin-bottom:3px;">URL sin código de acceso:</div>
        <div class="err-url">
          <?= htmlspecialchars(strtok((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on'?'https':'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],'?')) ?>
          <br><span>← Falta el parámetro ?inst=CODIGO</span>
        </div>
        <div style="font-weight:700;color:#059669;margin-bottom:3px;margin-top:10px;">URL correcta:</div>
        <div class="err-url-ok">
          <?= htmlspecialchars(strtok((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on'?'https':'http').'://'.$_SERVER['HTTP_HOST'].strtok($_SERVER['REQUEST_URI'],'?'))) ?>
          <span>?inst=<em>TU_CODIGO</em></span>
        </div>
      </div>
    </div>

    <div class="err-sub" style="font-size:13px;background:#fffbeb;border:1px solid #fcd34d;
                                border-radius:10px;padding:12px 16px;color:#78350f;">
      <i class="fa fa-info-circle me-2" style="color:#d97706;"></i>
      Solicita el enlace de acceso a tu institución. Cada instituto tiene su propio código único de acceso.
    </div>

    <div class="err-footer">
      &copy; <?= date('Y') ?> — SIGVPT · Sistema de Gestión de Vinculación, Prácticas Pre-Profesionales y Titulación
    </div>
  </div>
</body>
</html>
<?php
    exit; // Detener todo procesamiento adicional
}
// ── Fin bloqueo — a partir de aquí $inst es válido ──────────

// Siglas: primera letra de cada palabra relevante (> 3 chars)
$instNombre = $inst['nombre'] ?? 'SIGVP';
$palabras   = array_filter(explode(' ', $instNombre), fn($p) => strlen($p) > 3);
$siglas     = strtoupper(implode('', array_map(fn($p) => $p[0], array_slice($palabras, 0, 4))));
$instLogo   = !empty($inst['logo']) ? BASE_URL . '/uploads/institutos/' . $inst['logo'] : null;
$instPais   = 'Ecuador';

$error = '';
$msg_map = [
    'no_auth'  => 'Debes iniciar sesión para continuar.',
    'timeout'  => 'Tu sesión expiró. Inicia sesión de nuevo.',
    'logout'   => 'Sesión cerrada correctamente.',
];
$info = $msg_map[$_GET['msg'] ?? ''] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ── Validar CSRF token ───────────────────────────────────────────
    $csrfPost = $_POST['csrf_token'] ?? '';
    if (!hash_equals($csrfToken, $csrfPost)) {
        $error = 'Error de seguridad. Recarga la página e intenta de nuevo.';
    } else {

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

    if (!$email || !$password) {
        $error = 'Completa todos los campos.';
    } else {
        $result = login($email, $password);
        if ($result['ok']) {
            // Regenerar CSRF tras login exitoso
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            header('Location: ' . $result['redirect']);
            exit;
        }
        $error = $result['msg'];
    }

    } // fin validación CSRF
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>SIGVP — Iniciar Sesión</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"/>
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
  <style>
    :root {
      --sky-deep:   #0c2d4e;
      --sky-mid:    #1a5f8a;
      --sky-bright: #2196c9;
      --sky-light:  #5bc4ef;
      --sky-pale:   #d0edf8;
      --sky-bg:     #e8f6fc;
      --card:       #ffffff;
      --border:     #b8ddef;
      --border-hi:  #7ac8e8;
      --muted:      #5a8ea8;
      --text:       #0c2d4e;
      --text-2:     #4a7f9a;
      --accent:     #1a5f8a;
      --accent2:    #17a8d8;
    }

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

    body {
      font-family: 'Plus Jakarta Sans', sans-serif;
      min-height: 100vh;
      display: flex;
      align-items: stretch;
      color: var(--text);
      overflow: hidden;
    }

    /* ═══════════════════════════════════════
       PANEL IZQUIERDO — video de fondo YouTube
    ═══════════════════════════════════════ */
    .left-panel {
      flex: 1;
      position: relative;
      background: #0c2d4e;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 48px;
      overflow: hidden;
    }

    /* Contenedor del video YouTube */
    .yt-bg {
      position: absolute;
      inset: 0;
      z-index: 0;
      pointer-events: none;
      overflow: hidden;
    }
    .yt-bg iframe {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 177.78vh;
      height: 100vh;
      min-width: 100%;
      min-height: 56.25vw;
      transform: translate(-50%, -50%);
      border: none;
      pointer-events: none;
    }

    /* Overlay oscuro para legibilidad del texto */
    .yt-overlay {
      position: absolute;
      inset: 0;
      background: linear-gradient(
        150deg,
        rgba(6,20,40,.88) 0%,
        rgba(12,45,78,.82) 40%,
        rgba(26,95,138,.75) 100%
      );
      z-index: 1;
    }

    /* Círculos decorativos */
    .left-panel::before {
      content: '';
      position: absolute;
      width: 520px; height: 520px;
      border-radius: 50%;
      border: 1.5px solid rgba(255,255,255,.10);
      top: -120px; left: -120px;
    }
    .left-panel::after {
      content: '';
      position: absolute;
      width: 380px; height: 380px;
      border-radius: 50%;
      border: 1.5px solid rgba(255,255,255,.08);
      bottom: -80px; right: -80px;
    }

    .deco-ring {
      position: absolute;
      border-radius: 50%;
      border: 1px solid rgba(255,255,255,.07);
      z-index: 2;
    }
    .deco-ring-1 { width: 260px; height: 260px; top: 40%; left: 55%; transform: translate(-50%,-50%); }
    .deco-ring-2 { width: 160px; height: 160px; bottom: 18%; left: 12%; }
    .deco-ring-3 { width: 90px;  height: 90px;  top: 15%; right: 10%; }

    /* Puntos flotantes */
    .deco-dot {
      position: absolute;
      border-radius: 50%;
      background: rgba(255,255,255,.18);
      z-index: 2;
    }
    .deco-dot-1 { width:10px; height:10px; top:22%; left:18%; animation: float 6s ease-in-out infinite; }
    .deco-dot-2 { width:6px;  height:6px;  top:65%; left:70%; animation: float 8s ease-in-out infinite .5s; }
    .deco-dot-3 { width:8px;  height:8px;  top:80%; left:30%; animation: float 7s ease-in-out infinite 1s; }
    .deco-dot-4 { width:5px;  height:5px;  top:35%; right:15%; animation: float 9s ease-in-out infinite 2s; }

    @keyframes float {
      0%,100% { transform: translateY(0); }
      50%      { transform: translateY(-12px); }
    }

    /* Contenido del panel izquierdo */
    .left-content { position: relative; z-index: 2; text-align: center; color: #fff; max-width: 340px; }

    .brand-icon {
      width: 72px; height: 72px;
      border-radius: 20px;
      background: rgba(0,0,0,.4);
      backdrop-filter: blur(12px);
      border: 1.5px solid rgba(255,255,255,.35);
      display: inline-flex; align-items: center; justify-content: center;
      margin-bottom: 20px;
      box-shadow: 0 8px 32px rgba(0,0,0,.45), 0 0 0 1px rgba(255,255,255,.08);
    }
    .brand-icon i { font-size: 28px; color: #fff; filter: drop-shadow(0 2px 6px rgba(0,0,0,.5)); }

    .brand-name {
      font-size: 42px; font-weight: 800; letter-spacing: -1.5px;
      line-height: 1;
      text-shadow: 0 2px 16px rgba(0,0,0,.7), 0 0 40px rgba(0,0,0,.4);
    }
    .brand-name span { color: var(--sky-light); }

    .brand-tagline {
      font-size: 13px; color: rgba(255,255,255,.92);
      margin-top: 10px; line-height: 1.6; letter-spacing: .3px;
      text-shadow: 0 1px 8px rgba(0,0,0,.6);
    }

    /* Chips de features */
    .feature-chips { display: flex; flex-direction: column; gap: 10px; margin-top: 36px; }
    .feature-chip {
      background: rgba(0,0,0,.35);
      border: 1px solid rgba(255,255,255,.25);
      border-radius: 10px;
      padding: 11px 16px;
      display: flex; align-items: center; gap: 12px;
      text-align: left;
      backdrop-filter: blur(6px);
      -webkit-backdrop-filter: blur(6px);
    }
    .feature-chip i { font-size: 15px; color: #7dd3fc; width: 18px; text-align: center; filter: drop-shadow(0 0 4px rgba(125,211,252,.6)); }
    .feature-chip span { font-size: 12.5px; color: #ffffff; font-weight: 600; text-shadow: 0 1px 4px rgba(0,0,0,.5); }

    /* ═══════════════════════════════════════
       PANEL DERECHO — formulario
    ═══════════════════════════════════════ */
    .right-panel {
      width: 480px;
      min-width: 480px;
      background: var(--sky-bg);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 48px 40px;
      position: relative;
      overflow-y: auto;
    }

    /* Patrón de puntos sutil */
    .right-panel::before {
      content: '';
      position: absolute;
      inset: 0;
      background-image: radial-gradient(circle, rgba(33,150,201,.12) 1px, transparent 1px);
      background-size: 24px 24px;
      pointer-events: none;
    }

    .form-wrap {
      width: 100%;
      max-width: 380px;
      position: relative;
      z-index: 1;
      animation: slideIn .45s cubic-bezier(.22,.68,0,1.1) both;
    }
    @keyframes slideIn {
      from { opacity: 0; transform: translateX(20px); }
      to   { opacity: 1; transform: translateX(0); }
    }

    /* Cabecera del form */
    .form-header { margin-bottom: 28px; }

    /* Identidad institucional */
    .inst-brand {
      display: flex;
      align-items: center;
      gap: 14px;
      margin-bottom: 14px;
    }
    .inst-logo {
      width: 62px;
      height: 62px;
      object-fit: contain;
      border-radius: 12px;
      border: 1.5px solid var(--border);
      background: #fff;
      padding: 4px;
      box-shadow: 0 2px 10px rgba(12,45,78,.10);
      flex-shrink: 0;
    }
    .inst-logo-fallback {
      width: 62px;
      height: 62px;
      border-radius: 12px;
      border: 1.5px solid var(--border);
      background: var(--sky-pale);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      box-shadow: 0 2px 10px rgba(12,45,78,.10);
    }
    .inst-logo-fallback i { font-size: 26px; color: var(--sky-mid); }
    .inst-info { display: flex; flex-direction: column; gap: 2px; }
    .inst-name {
      font-size: 14.5px;
      font-weight: 700;
      color: var(--sky-deep);
      line-height: 1.35;
      letter-spacing: -.2px;
    }
    .inst-name strong { color: var(--sky-mid); }
    .inst-sigla {
      font-size: 10.5px;
      font-weight: 600;
      color: var(--muted);
      letter-spacing: .5px;
      text-transform: uppercase;
    }
    .form-header-divider {
      height: 1.5px;
      background: linear-gradient(90deg, var(--border) 0%, transparent 100%);
      border-radius: 2px;
      margin-bottom: 10px;
    }
    .form-header-sub { font-size: 12.5px; color: var(--muted); }

    /* Card glassmorphism */
    .card-login {
      background: rgba(255,255,255,.92);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border: 1.5px solid rgba(184,221,239,.8);
      border-radius: 18px;
      padding: 30px;
      box-shadow:
        0 2px 4px rgba(12,45,78,.04),
        0 12px 40px rgba(26,95,138,.10),
        inset 0 1px 0 rgba(255,255,255,.95);
    }

    /* Labels */
    .form-label {
      font-size: 11px; font-weight: 700;
      letter-spacing: .7px; color: var(--muted);
      text-transform: uppercase; margin-bottom: 6px;
      display: block;
    }

    /* Inputs */
    .form-control {
      background: rgba(232,246,252,.7);
      border: 1.5px solid var(--border);
      color: var(--text);
      border-radius: 10px;
      padding: 10px 14px;
      font-size: 13.5px;
      font-family: 'Plus Jakarta Sans', sans-serif;
      transition: border-color .2s, box-shadow .2s, background .2s;
      width: 100%;
    }
    .form-control::placeholder { color: #9ac5da; }
    .form-control:focus {
      background: #fff;
      border-color: var(--accent2);
      box-shadow: 0 0 0 3.5px rgba(23,168,216,.14);
      outline: none;
      color: var(--text);
    }

    .input-group-text {
      background: rgba(232,246,252,.7);
      border: 1.5px solid var(--border);
      color: var(--muted);
      border-right: none;
      border-radius: 10px 0 0 10px;
      padding: 0 13px;
      font-size: 13px;
      transition: border-color .2s, background .2s;
    }
    .input-group .form-control {
      border-left: none;
      border-radius: 0 10px 10px 0;
    }
    .input-group:focus-within .input-group-text {
      border-color: var(--accent2);
      background: #fff;
      color: var(--accent2);
    }
    .input-group:focus-within .form-control {
      border-color: var(--accent2);
    }

    /* Toggle contraseña */
    .toggle-pass {
      cursor: pointer;
      background: rgba(232,246,252,.7);
      border: 1.5px solid var(--border);
      border-left: none;
      border-radius: 0 10px 10px 0 !important;
      color: var(--muted);
      padding: 0 12px;
      transition: color .2s, background .2s, border-color .2s;
      display: flex; align-items: center;
    }
    .toggle-pass:hover { color: var(--accent2); background: #fff; }
    .input-group:focus-within .toggle-pass { border-color: var(--accent2); background: #fff; }

    /* Botón principal */
    .btn-login {
      width: 100%;
      background: linear-gradient(135deg, var(--sky-deep) 0%, var(--sky-mid) 50%, var(--sky-bright) 100%);
      border: none;
      color: #fff;
      border-radius: 10px;
      padding: 12px;
      font-size: 14px;
      font-weight: 700;
      font-family: 'Plus Jakarta Sans', sans-serif;
      letter-spacing: .3px;
      transition: opacity .2s, transform .15s, box-shadow .2s;
      box-shadow: 0 4px 16px rgba(26,95,138,.35);
      cursor: pointer;
    }
    .btn-login:hover   { opacity: .92; transform: translateY(-2px); box-shadow: 0 8px 24px rgba(26,95,138,.4); }
    .btn-login:active  { transform: translateY(0); }
    .btn-login:disabled{ opacity: .55; cursor: not-allowed; }

    /* Alertas */
    .alert-custom {
      border-radius: 10px; font-size: 13px; padding: 10px 14px;
      border: 1.5px solid; display: flex; align-items: center; gap: 9px;
      font-weight: 500;
    }
    .alert-err  { background: #fff5f5; border-color: #fca5a5; color: #b91c1c; }
    .alert-info { background: #eff8ff; border-color: #93c5fd; color: #1d4ed8; }
    .alert-ok   { background: #f0fdf4; border-color: #86efac; color: #15803d; }

    /* Divider */
    .divider { border-color: var(--border); margin: 18px 0 12px; }

    /* Demo pills */
    .demo-section-label {
      font-size: 10.5px; color: var(--muted); margin-bottom: 8px;
      letter-spacing: .6px; font-weight: 700; text-transform: uppercase;
    }
    .demo-pills { display: flex; flex-wrap: wrap; gap: 5px; }
    .demo-pill {
      background: rgba(208,237,248,.5);
      border: 1.5px solid var(--border);
      border-radius: 7px;
      padding: 4px 9px;
      font-size: 10.5px;
      cursor: pointer;
      transition: border-color .15s, background .15s, transform .1s, color .15s;
      font-family: 'JetBrains Mono', monospace;
      color: var(--muted);
      font-weight: 500;
    }
    .demo-pill:hover {
      border-color: var(--accent2);
      background: rgba(23,168,216,.08);
      color: var(--accent);
      transform: translateY(-1px);
    }
    .demo-pill .role { color: var(--sky-deep); font-weight: 700; }

    /* Footer */
    .login-footer {
      text-align: center;
      margin-top: 20px;
      font-size: 10.5px;
      color: var(--muted);
      letter-spacing: .2px;
    }

    /* Spinner */
    .spinner-border { width: 1rem; height: 1rem; }

    /* Badge de rol seleccionado */
    .role-badge {
      display: none;
      align-items: center;
      gap: 8px;
      background: linear-gradient(135deg, rgba(26,95,138,.10) 0%, rgba(23,168,216,.12) 100%);
      border: 1.5px solid var(--border-hi);
      border-radius: 9px;
      padding: 7px 13px;
      margin-bottom: 12px;
      font-size: 12px;
      font-weight: 600;
      color: var(--sky-deep);
      animation: fadeSlide .25s ease both;
    }
    .role-badge.visible { display: flex; }
    .role-badge i { font-size: 13px; color: var(--accent2); }
    .role-badge .rb-label { font-size: 10px; color: var(--muted); letter-spacing: .5px; text-transform: uppercase; font-weight: 700; }
    .role-badge .rb-name  { font-size: 13px; font-weight: 800; color: var(--sky-mid); letter-spacing: -.2px; }
    @keyframes fadeSlide {
      from { opacity: 0; transform: translateY(-6px); }
      to   { opacity: 1; transform: translateY(0); }
    }

    /* ── Responsive: colapsar panel izquierdo en móvil ── */
    @media (max-width: 768px) {
      body { overflow-y: auto; flex-direction: column; }
      .left-panel { display: none; }
      .right-panel { width: 100%; min-width: unset; padding: 32px 20px; min-height: 100vh; }
    }
  </style>
</head>
<body>

  <!-- ═══ PANEL IZQUIERDO ═══ -->
  <div class="left-panel">

    <!-- Video YouTube de fondo -->
    <div class="yt-bg">
      <iframe id="ytBg"
          src="https://www.youtube.com/embed/RGYsiD97JzE?autoplay=1&mute=1&loop=1&playlist=RGYsiD97JzE&controls=0&showinfo=0&rel=0&modestbranding=1&iv_load_policy=3&disablekb=1&enablejsapi=1"
          allow="autoplay; encrypted-media"
        allowfullscreen
        title="background video">
      </iframe>
    </div>
    <div class="yt-overlay"></div>
    <div class="deco-ring deco-ring-1"></div>
    <div class="deco-ring deco-ring-2"></div>
    <div class="deco-ring deco-ring-3"></div>
    <div class="deco-dot deco-dot-1"></div>
    <div class="deco-dot deco-dot-2"></div>
    <div class="deco-dot deco-dot-3"></div>
    <div class="deco-dot deco-dot-4"></div>

    <div class="left-content">

      <!-- Branding SIGVPT centrado -->
      <div class="brand-icon">
        <i class="fa fa-graduation-cap"></i>
      </div>
      <div class="brand-name">SIG<span>VPT</span></div>
      <div class="brand-tagline">
        Sistema de Gestión de<br>Vinculación, Prácticas<br>Pre-Profesionales y Titulación
      </div>

      <div class="feature-chips">
        <div class="feature-chip">
          <i class="fa fa-briefcase"></i>
          <span>Gestión integral de prácticas pre-profesionales</span>
        </div>
        <div class="feature-chip">
          <i class="fa fa-link"></i>
          <span>Seguimiento de proyectos de vinculación</span>
        </div>
        <div class="feature-chip">
          <i class="fa fa-file-shield"></i>
          <span>Expedientes digitales y trazabilidad CES</span>
        </div>
        <div class="feature-chip">
          <i class="fa fa-users"></i>
          <span>Coordinación multi-rol en tiempo real</span>
        </div>
      </div>
    </div>
  </div>

  <!-- ═══ PANEL DERECHO — FORMULARIO ═══ -->
  <div class="right-panel">
    <div class="form-wrap">

      <div class="form-header">
        <div style="text-align:center;margin-bottom:6px;">

          <?php if ($instLogo): ?>
          <!-- Logo del instituto cargado por token -->
          <img src="<?= htmlspecialchars($instLogo) ?>"
               alt="Logo <?= htmlspecialchars($instNombre) ?>"
               style="width:72px;height:72px;object-fit:contain;border-radius:14px;
                      border:1.5px solid var(--border);background:#fff;padding:4px;
                      box-shadow:0 4px 16px rgba(26,95,138,.18);margin-bottom:10px;display:block;margin-left:auto;margin-right:auto;">
          <?php else: ?>
          <!-- Fallback: ícono genérico -->
          <div style="width:64px;height:64px;border-radius:16px;
                      background:linear-gradient(135deg,#0c2d4e,#1a5f8a);
                      display:inline-flex;align-items:center;justify-content:center;
                      box-shadow:0 4px 16px rgba(26,95,138,.30);margin-bottom:10px;">
            <i class="fa fa-graduation-cap" style="font-size:24px;color:#fff;"></i>
          </div>
          <?php endif; ?>

          <div style="font-size:15px;font-weight:800;color:var(--sky-deep);letter-spacing:-.3px;line-height:1.3;margin-bottom:4px;max-width:260px;margin-left:auto;margin-right:auto;">
            <?= htmlspecialchars($instNombre) ?>
          </div>
          <?php if ($siglas): ?>
          <div style="font-size:10px;color:var(--muted);letter-spacing:.6px;font-weight:600;text-transform:uppercase;margin-bottom:2px;">
            <?= htmlspecialchars($siglas) ?>
          </div>
          <?php endif; ?>
          <div style="font-size:10.5px;color:var(--muted);line-height:1.5;font-weight:500;margin-top:4px;">
            Sistema de Gestión de Vinculación,<br>Prácticas Pre-Profesionales y Titulación
          </div>
        </div>
        <div class="form-header-divider"></div>
        <p class="form-header-sub">Ingresa tus credenciales para acceder al sistema</p>
      </div>

      <div class="card-login">

        <?php if ($error): ?>
        <div class="alert-custom alert-err mb-3">
          <i class="fa fa-circle-exclamation fa-sm"></i> <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <?php if ($info && !$error): ?>
        <?php $cls = str_contains($info,'cerrada') ? 'alert-ok' : 'alert-info'; ?>
        <div class="alert-custom <?= $cls ?> mb-3">
          <i class="fa fa-info-circle fa-sm"></i> <?= htmlspecialchars($info) ?>
        </div>
        <?php endif; ?>

        <form method="POST" id="loginForm"
              action="login.php<?= $instToken ? '?inst=' . htmlspecialchars($instToken) : '' ?>"
              novalidate>

          <?php if ($instToken): ?>
          <input type="hidden" name="inst" value="<?= htmlspecialchars($instToken) ?>">
          <?php endif; ?>
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

          <div class="mb-3">
            <label class="form-label">Correo electrónico o Cédula</label>
            <div class="input-group">
              <span class="input-group-text"><i class="fa fa-user fa-sm"></i></span>
              <input type="text" name="email" id="email" class="form-control"
                     placeholder="usuario@institución.edu.ec  ó  0912345678"
                     value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                     autocomplete="username" required/>
            </div>
          </div>

          <div class="mb-4">
            <label class="form-label">Contraseña</label>
            <div class="input-group">
              <span class="input-group-text"><i class="fa fa-lock fa-sm"></i></span>
              <input type="password" name="password" id="password" class="form-control"
                     placeholder="••••••••" autocomplete="current-password" required/>
              <button type="button" class="btn toggle-pass" id="togglePass">
                <i class="fa fa-eye fa-sm" id="eyeIcon"></i>
              </button>
            </div>
          </div>

          <!-- Badge de rol seleccionado -->
          <div class="role-badge" id="roleBadge">
            <i class="fa fa-id-badge"></i>
            <div>
              <div class="rb-label">Rol de acceso</div>
              <div class="rb-name" id="roleBadgeName"></div>
            </div>
          </div>

          <button type="submit" class="btn-login" id="btnLogin">
            <span id="btnText"><i class="fa fa-right-to-bracket me-2"></i>Iniciar sesión</span>
            <span id="btnSpin" style="display:none">
              <span class="spinner-border spinner-border-sm me-2 align-middle"></span>Verificando...
            </span>
          </button>

        </form>



      </div><!-- /.card-login -->

      <div class="login-footer">
        &copy; <?= date('Y') ?> &mdash; Sistema de Gestión de Vinculación, Prácticas Pre-Profesionales y Titulación
      </div>

    </div><!-- /.form-wrap -->
  </div><!-- /.right-panel -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function(){
  // Toggle contraseña
  $('#togglePass').on('click', function(){
    var inp = $('#password');
    var isPass = inp.attr('type') === 'password';
    inp.attr('type', isPass ? 'text' : 'password');
    $('#eyeIcon').toggleClass('fa-eye fa-eye-slash');
  });

  // Detección de rol desactivada por seguridad
  // (no se exponen correos ni roles en el código fuente)
  function detectRole(val) {
    // No hacer nada — evita exponer usuarios del sistema
  }

  // Detectar al escribir y al pegar
  $('#email').on('input paste', function(){
    var self = this;
    setTimeout(function(){ detectRole($(self).val()); }, 10);
  });

  // Si ya hay valor al cargar (PHP post-back)
  detectRole($('#email').val());

  // Spinner al enviar
  $('#loginForm').on('submit', function(){
    var email = $.trim($('#email').val());
    var pass  = $('#password').val();
    if(!email || !pass){ return; }
    $('#btnText').hide();
    $('#btnSpin').show();
    $('#btnLogin').prop('disabled', true);
  });
});
</script>
</body>
</html>