<?php
// Sesión con cookie endurecida (HttpOnly + SameSite + Secure tras proxy https).
if (session_status() == PHP_SESSION_NONE) {
    $esHttps = (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https') || (($_SERVER['HTTPS'] ?? '') == 'on');
    session_set_cookie_params([
        'lifetime'  => 0,
        'path'      => '/',
        'secure'    => $esHttps,
        'httponly'  => true,
        'samesite'  => 'Lax',
    ]);
    session_start();
}
require_once("controladores/login.php");

if (!isset($_SESSION['idusuario'])) {
    if (isset($_COOKIE['recuerdame_syspower'])) {
        // validarCookieRecuerdame (recuerdame.php, cargado vía login.php) valida el
        // token hasheado + expiración y lo rota. El estado de usuario/empresa se
        // verifica en validarSesion() al entrar al panel.
        $idPorCookie = validarCookieRecuerdame();
        if ($idPorCookie > 0) {
            session_regenerate_id(true);
            csrfRotarToken();
            $_SESSION['idusuario'] = $idPorCookie;
            header("Location: admin/dashboard/index.php");
            exit;
        }
    }
}

// ===========================================================================
// PERSONALIZACION del login (logo, nombre, colores)
// ===========================================================================
$empresaNombre = 'SysPower';
$logoPath      = 'assets/img/logo_syspower.png';
$colorPrimario = '#061c6b';
$colorAcento   = '#07ba86';
$landingUrl    = rtrim($_ENV['LANDING_URL'] ?? 'https://syspower.alkes.mx', '/');
?>
<!DOCTYPE html>
<html lang="es" data-theme="dark">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($empresaNombre) ?> · Iniciar sesión</title>
  <link rel="icon" href="assets/img/favicon.ico" type="image/x-icon">
  <link rel="apple-touch-icon" href="/assets/img/apple-touch-icon.png">
  <meta property="og:type" content="website">
  <meta property="og:site_name" content="SysPower">
  <meta property="og:title" content="SysPower | Reinicio remoto de equipos críticos">
  <meta property="og:description" content="Accede a tu panel de SysPower: apaga, enciende y reinicia tus equipos críticos de forma remota, sin VPN.">
  <meta property="og:url" content="https://app.syspower.alkes.mx/">
  <meta property="og:image" content="https://app.syspower.alkes.mx/assets/img/og-image.png">
  <meta property="og:image:type" content="image/png">
  <meta property="og:image:width" content="1200">
  <meta property="og:image:height" content="630">
  <meta property="og:image:alt" content="SysPower">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:image" content="https://app.syspower.alkes.mx/assets/img/og-image.png">

  <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=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" integrity="sha256-pdY4ejLKO67E0CM2tbPtq1DJ3VGDVVdqAR6j3ZwdiE4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.min.css" integrity="sha384-G6vnOaxpYb28Lmi9iAsDDoiSSHhMt09nKfF+FS65kcsWjpXneqmksvE8DTPyPx+0" crossorigin="anonymous">
  <link rel="stylesheet" href="assets/css/login.premium.css?v=<?= filemtime(__DIR__ . '/assets/css/login.premium.css') ?>">

  <style>
    :root { --brand-deep: <?= $colorPrimario ?>; --brand-teal: <?= $colorAcento ?>; }
  </style>

  <?php echo csrfMetaTag(); ?>
  <?php echo $jaxon->getScript(true); ?>
  <?php echo csrfScriptCabecera(); ?>
</head>

<body>
  <div class="bg-stage" aria-hidden="true">
    <div class="bg-image" id="bgImage"></div>
    <span class="nebula n1"></span>
    <span class="nebula n2"></span>
    <span class="nebula n3"></span>
    <canvas id="particles"></canvas>
  </div>

  <button class="theme-toggle" id="themeToggle" type="button" aria-label="Cambiar tema">
    <i class="bi bi-moon-stars-fill"></i>
    <i class="bi bi-sun-fill"></i>
  </button>

  <main class="login-stage">
    <div class="login-card">

      <div class="brand">
        <img src="<?= htmlspecialchars($logoPath) ?>" alt="<?= htmlspecialchars($empresaNombre) ?>" class="brand-logo"
             onerror="this.style.display='none'">
        <div class="brand-name"><?= htmlspecialchars($empresaNombre) ?></div>
      </div>

      <div class="panels">
        <section class="panel is-active" data-panel="login" aria-labelledby="loginTitle">
          <h1 class="panel-title" id="loginTitle">Bienvenido de nuevo</h1>
          <p class="panel-sub">Inicia sesión para continuar a tu panel.</p>

          <form id="login" autocomplete="off" onsubmit="return enviar(event, 'login', 'btnLogin');">
            <div class="field">
              <label for="correo">Correo electrónico</label>
              <div class="control">
                <input name="correo" id="correo" type="email" placeholder="tu@empresa.com" autocomplete="username" inputmode="email" autocapitalize="off" spellcheck="false" enterkeyhint="next" required>
                <i class="ico bi bi-envelope"></i>
              </div>
            </div>

            <div class="field">
              <label for="clave">Contraseña</label>
              <div class="control">
                <input name="clave" id="clave" type="password" placeholder="••••••••" autocomplete="current-password" enterkeyhint="go" required>
                <i class="ico bi bi-lock"></i>
                <button class="eye" type="button" aria-label="Mostrar u ocultar contraseña" onclick="toggleEye(this)">
                  <i class="bi bi-eye"></i>
                </button>
              </div>
            </div>

            <div class="row-options">
              <label class="check">
                <input type="checkbox" name="rememberPasswordCheck" id="rememberPasswordCheck" checked>
                <span class="box"></span>
                <span>Recordarme</span>
              </label>
              <a class="link" href="#" onclick="mostrarPanel('recuperar'); return false;">¿Olvidaste tu contraseña?</a>
            </div>

            <button class="btn-primary" id="btnLogin" type="submit">
              <span class="label">Iniciar sesión</span>
              <span class="spin"><i></i></span>
            </button>
          </form>

          <div class="card-foot">
            ¿No tienes una cuenta?
            <a href="<?= htmlspecialchars($landingUrl) ?>/#versiones">Contrata aquí</a>
          </div>
        </section>

        <!-- ============ PANEL: RECUPERAR ============ -->
        <section class="panel" data-panel="recuperar" aria-labelledby="recTitle">
          <h1 class="panel-title" id="recTitle">Recuperar contraseña</h1>
          <p class="panel-sub">Escribe tu correo y te enviaremos un código para restablecerla.</p>

          <form id="formRecuperar" autocomplete="off" onsubmit="return enviar(event, 'formRecuperar', 'btnRecuperar');">
            <div class="field">
              <label for="rec_correo">Correo electrónico</label>
              <div class="control">
                <input name="correo" id="rec_correo" type="email" placeholder="tu@empresa.com" autocomplete="email" inputmode="email" autocapitalize="off" spellcheck="false" enterkeyhint="send" required>
                <i class="ico bi bi-envelope"></i>
              </div>
            </div>
            <button class="btn-primary" id="btnRecuperar" type="submit">
              <span class="label">Enviar código</span>
              <span class="spin"><i></i></span>
            </button>
          </form>

          <button class="btn-ghost" type="button" onclick="mostrarPanel('login')">
            <i class="bi bi-arrow-left"></i> Volver al inicio de sesión
          </button>
        </section>

        <!-- ============ PANEL: RESET ============ -->
        <section class="panel" data-panel="reset" aria-labelledby="resTitle">
          <h1 class="panel-title" id="resTitle">Nueva contraseña</h1>
          <p class="panel-sub" id="reset_destino">Escribe el código que recibiste y tu nueva contraseña.</p>

          <form id="formReset" autocomplete="off" onsubmit="return enviar(event, 'formReset', 'btnReset');">
            <input type="hidden" name="correo" id="reset_correo" value="">

            <div class="field">
              <label for="reset_pin">Código de verificación</label>
              <div class="control">
                <input name="pin" id="reset_pin" class="pin" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="6"
                       autocomplete="one-time-code" placeholder="••••••" enterkeyhint="next" required>
              </div>
            </div>

            <div class="field">
              <label for="reset_password">Nueva contraseña</label>
              <div class="control">
                <input name="password" id="reset_password" type="password" placeholder="Mínimo 8 caracteres" autocomplete="new-password" enterkeyhint="next" required>
                <i class="ico bi bi-lock"></i>
                <button class="eye" type="button" aria-label="Mostrar u ocultar contraseña" onclick="toggleEye(this)">
                  <i class="bi bi-eye"></i>
                </button>
              </div>
            </div>

            <div class="field">
              <label for="reset_password2">Confirmar contraseña</label>
              <div class="control">
                <input name="password2" id="reset_password2" type="password" placeholder="Repite la contraseña" autocomplete="new-password" enterkeyhint="done" required>
                <i class="ico bi bi-shield-lock"></i>
              </div>
            </div>

            <button class="btn-primary" id="btnReset" type="submit">
              <span class="label">Restablecer contraseña</span>
              <span class="spin"><i></i></span>
            </button>
          </form>

          <button class="btn-ghost" type="button" id="btnReenviar" onclick="reenviarCodigo()">
            <i class="bi bi-arrow-repeat"></i> <span>¿No te llegó? Reenviar código</span>
          </button>
          <button class="btn-ghost" type="button" onclick="mostrarPanel('login')">
            <i class="bi bi-arrow-left"></i> Volver al inicio de sesión
          </button>
        </section>
      </div>
    </div>

    <p class="powered-by">
      Powered by <a href="https://alkes.mx" target="_blank" rel="noopener">Alkes</a>
    </p>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.min.js" integrity="sha384-MiWVG0sygCleiUgKKQos54LaVZa9ob4yvQvktfCC1R2m+hzhbIPoSGM2pR+lJOLh" crossorigin="anonymous"></script>
  <script>
    function aplicarTema(tema) {
      document.documentElement.setAttribute('data-theme', tema);
      try { localStorage.setItem('syspower_login_theme', tema); } catch (e) {}
    }
    (function () {
      var g = 'dark';
      try { g = localStorage.getItem('syspower_login_theme') || 'dark'; } catch (e) {}
      aplicarTema(g);
    })();
    document.getElementById('themeToggle').addEventListener('click', function () {
      var a = document.documentElement.getAttribute('data-theme');
      aplicarTema(a === 'dark' ? 'light' : 'dark');
    });

    // ===================== PANELES (login / recuperar / reset) =====================
    function mostrarPanel(panel) {
      var nombre = panel || 'login';
      document.querySelectorAll('.panel').forEach(function (p) {
        p.classList.toggle('is-active', p.getAttribute('data-panel') === nombre);
      });
      window.scrollTo(0, 0);
      // En pantallas táctiles no se enfoca solo: el teclado taparía la tarjeta.
      if (window.matchMedia('(pointer: fine)').matches) {
        var activo = document.querySelector('.panel.is-active');
        var input = activo && activo.querySelector('input:not([type=hidden])');
        if (input) { setTimeout(function () { input.focus(); }, 60); }
      }
    }

    // Lo invoca el backend tras solicitar la recuperación de contraseña
    var cuentaReenvio = null;
    window.mostrarPanelReset = function (correo) {
      document.getElementById('reset_correo').value = correo;
      document.getElementById('reset_pin').value = '';
      document.getElementById('reset_destino').textContent = 'Si ' + correo + ' está registrado, te enviamos un código. Escríbelo aquí con tu nueva contraseña.';
      mostrarPanel('reset');
      iniciarEsperaReenvio(60);
    };

    // El reenvío espera 60 s: el servidor no manda otro código antes de ese tiempo.
    function iniciarEsperaReenvio(segundos) {
      var btn = document.getElementById('btnReenviar');
      var txt = btn.querySelector('span');
      clearInterval(cuentaReenvio);
      var resta = segundos;
      btn.disabled = true;
      function pintar() { txt.textContent = resta > 0 ? 'Reenviar código en ' + resta + ' s' : '¿No te llegó? Reenviar código'; }
      pintar();
      cuentaReenvio = setInterval(function () {
        resta--;
        pintar();
        if (resta <= 0) { clearInterval(cuentaReenvio); btn.disabled = false; }
      }, 1000);
    }

    function reenviarCodigo() {
      var correo = document.getElementById('reset_correo').value;
      if (correo) { Jaxonlogin.recuperarPassword({ correo: correo }); }
    }

    function toggleEye(btn) {
      var input = btn.parentElement.querySelector('input');
      var icon = btn.querySelector('i');
      if (input.type === 'password') { input.type = 'text'; icon.classList.remove('bi-eye'); icon.classList.add('bi-eye-slash'); }
      else { input.type = 'password'; icon.classList.remove('bi-eye-slash'); icon.classList.add('bi-eye'); }
    }

    // ===================== ENVIO (estado loading + Jaxon) =====================
    function enviar(e, formId, btnId) {
      e.preventDefault();
      var btn = document.getElementById(btnId);
      btn.classList.add('is-loading');
      btn.disabled = true;
      // Reabilita por si el backend responde con error (no recarga la página)
      setTimeout(function () { btn.classList.remove('is-loading'); btn.disabled = false; }, 4000);

      var valores = jaxon.getFormValues(formId);
      if (formId === 'login')              { Jaxonlogin.login(valores); }
      else if (formId === 'formRecuperar') { Jaxonlogin.recuperarPassword(valores); }
      else if (formId === 'formReset')     { Jaxonlogin.restablecerPassword(valores); }
      return false;
    }

    (function () {
      var canvas = document.getElementById('particles');
      if (!canvas) return;
      var ctx = canvas.getContext('2d'), particulas = [], w, h, dpr;
      var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      function color() { return getComputedStyle(document.documentElement).getPropertyValue('--star').trim() || 'rgba(255,255,255,0.9)'; }
      function resize() {
        dpr = Math.min(window.devicePixelRatio || 1, 2);
        w = canvas.clientWidth; h = canvas.clientHeight;
        canvas.width = w * dpr; canvas.height = h * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        var n = Math.min(120, Math.floor((w * h) / 14000)); particulas = [];
        for (var i = 0; i < n; i++) particulas.push({ x: Math.random() * w, y: Math.random() * h, r: Math.random() * 1.6 + 0.3, vx: (Math.random() - 0.5) * 0.12, vy: (Math.random() - 0.5) * 0.12, a: Math.random() * 0.6 + 0.2, tw: Math.random() * 0.02 + 0.004 });
      }
      function frame() {
        ctx.clearRect(0, 0, w, h); var c = color();
        for (var i = 0; i < particulas.length; i++) { var p = particulas[i]; p.x += p.vx; p.y += p.vy; p.a += p.tw; if (p.a > 0.85 || p.a < 0.15) p.tw *= -1; if (p.x < 0) p.x = w; if (p.x > w) p.x = 0; if (p.y < 0) p.y = h; if (p.y > h) p.y = 0; ctx.globalAlpha = p.a; ctx.fillStyle = c; ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill(); }
        ctx.globalAlpha = 1; if (!reduce) requestAnimationFrame(frame);
      }
      window.addEventListener('resize', resize); resize(); if (reduce) frame(); else requestAnimationFrame(frame);
    })();
  </script>
</body>
</html>
