<?php
/*******************************
 * Panel Código (IMAP) - Disney OTP (validación exacta)
 * - El correo debe coincidir EXACTO como está en el panel (incluye + y case)
 * - Si falla la validación: NO abre IMAP
 * - Si pasa: busca el OTP más reciente (6 dígitos) y lo muestra con fecha grande ⏰
 * Versión: 2025-09-04
 *******************************/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Bogota');
session_start();

set_time_limit(300);
ini_set('default_socket_timeout', 15);
imap_timeout(IMAP_OPENTIMEOUT, 12);
imap_timeout(IMAP_READTIMEOUT, 12);
imap_timeout(IMAP_WRITETIMEOUT, 12);

// ====== Estado / UI ======
$status      = [];
$metaHtml    = '';
$codigoHtml  = '';
$mensajeHtml = '';
$buscando    = false; // solo TRUE después de autenticar OK

// Para mantener lo que escribe el usuario en el formulario
$ultimoUsuarioIngresado = '';
$ultimaClaveIngresada   = '';

// ====== Helpers ======
function can_connect($host, $port = 993, $timeout = 5) {
  $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
  if ($fp) { fclose($fp); return true; }
  return false;
}
function decodeBody($body, $encoding) {
  switch ((int)$encoding) {
    case 2: return imap_binary($body);
    case 3: return imap_base64($body);
    case 4: return imap_qprint($body);
    default: return $body;
  }
}
function decodeSubjectSafe($rawSubject) {
  if (empty($rawSubject)) return '';
  $parts = imap_mime_header_decode($rawSubject);
  $out = '';
  $valid = array_map('strtolower', mb_list_encodings());
  foreach ($parts as $p) {
    $cs = strtoupper(trim($p->charset ?? 'UTF-8'));
    if (!$cs || $cs === 'DEFAULT' || !in_array(strtolower($cs), $valid)) $cs = 'UTF-8';
    $out .= mb_convert_encoding($p->text, 'UTF-8', $cs);
  }
  return $out;
}
function timingSafeEquals($a,$b){
  if(function_exists('hash_equals')) return hash_equals($a,$b);
  if(!is_string($a) || !is_string($b)) return false;
  if(strlen($a)!==strlen($b)) return false;
  $res=0; for($i=0;$i<strlen($a);$i++) $res|=ord($a[$i])^ord($b[$i]);
  return $res===0;
}
function normalizarCorreoBasico($e){ // solo limpia espacios
  return trim((string)$e);
}

// ====== IMAP servers ======
$imapServers = [
'andoguez.com'                  => ['host' => 'mail.andoguez.com',     'username' => 'admin@andoguez.com',     'password' => 'ANDRES12345@.'],
'blan.pro'                      => ['host' => 'mail.bomyn.com',        'username' => 'admin@bomyn.com',        'password' => 'ANDRES12345@.'],
'bloss.live'                    => ['host' => 'mail.bloss.live',       'username' => 'admin@bloss.live',       'password' => 'ANDRES12345@.'],
'blossen.com'                   => ['host' => 'mail.blossen.com',      'username' => 'admin@blossen.com',      'password' => 'ANDRES12345@.'],
'bomyn.com'                     => ['host' => 'mail.bomyn.com',        'username' => 'admin@bomyn.com',        'password' => 'ANDRES12345@.'],
'boomacount.net'                => ['host' => 'mail.boomacount.net',   'username' => 'admin@boomacount.net',   'password' => 'ANDRES12345@.'],
'breyles.com.co'                => ['host' => 'mail.breyles.com.co',   'username' => 'admin@breyles.com.co',   'password' => 'ANDRES12345@.'],
'cassacam.com'                  => ['host' => 'mail.cassacam.com',     'username' => 'admin@cassacam.com',     'password' => 'ANDRES12345@.'],
'casspim.com'                   => ['host' => 'mail.casspim.com',      'username' => 'admin@casspim.com',      'password' => 'ANDRES12345@.'],
'cassprime.com'                 => ['host' => 'mail.cassprime.com',    'username' => 'admin@cassprime.com',    'password' => 'ANDRES12345@.'],
'cassplus.co'                   => ['host' => 'mail.cassplus.co',      'username' => 'admin@cassplus.co',      'password' => 'ANDRES12345@.'],
'cassrun.com'                   => ['host' => 'mail.cassrun.com',      'username' => 'admin@cassrun.com',      'password' => 'ANDRES12345@.'],
'casston.com'                   => ['host' => 'mail.casston.com',      'username' => 'admin@casston.com',      'password' => 'ANDRES12345@.'],
'crotman.com'                   => ['host' => 'mail.crotman.com',      'username' => 'admin@crotman.com',      'password' => 'ANDRES12345@.'],
'crotmen.com'                   => ['host' => 'mail.crotmen.com',      'username' => 'admin@crotmen.com',      'password' => 'ANDRES12345@.'],
'crismoren.com'                 => ['host' => 'mail.crismoren.com',    'username' => 'admin@crismoren.com',    'password' => 'ANDRES12345@.'],
'darprim.com'                   => ['host' => 'mail.darprim.com',      'username' => 'admin@darprim.com',      'password' => 'ANDRES12345@.'],
'daykgv.com'                    => ['host' => 'mail.daykgv.com',       'username' => 'admin@daykgv.com',       'password' => 'ANDRES12345@.'],
'digitalworld26.com'            => ['host' => 'mail.digitalworld26.com','username' => 'admin@digitalworld26.com','password' => 'ANDRES12345@.'],
'disneyk.com'                   => ['host' => 'mail.disneyk.com',      'username' => 'admin@disneyk.com',      'password' => 'ANDRES12345@.'],
'fodenx.com.co'                 => ['host' => 'mail.fodenx.com.co',    'username' => 'admin@fodenx.com.co',    'password' => 'ANDRES12345@.'],
'hincca.com'                    => ['host' => 'mail.crotman.com',      'username' => 'admin@crotman.com',      'password' => 'ANDRES12345@.'],
'innurban.com.co'               => ['host' => 'mail.innurban.com.co',  'username' => 'admin@innurban.com.co',  'password' => 'BREINER12345@'],
'karpoolbar.com'                => ['host' => 'mail.crotman.com',      'username' => 'admin@crotman.com',      'password' => 'ANDRES12345@.'],
'kgvcolombia.com'               => ['host' => 'mail.kgvcolombia.com',  'username' => 'admin@kgvcolombia.com',  'password' => 'ANDRES12345@.'],
'kgvpro.co'                     => ['host' => 'mail.kgvpro.co',        'username' => 'admin@kgvpro.co',        'password' => 'ANDRES12345@.'],
'kgvweb.com'                    => ['host' => 'mail.kgvweb.com',       'username' => 'admin@kgvweb.com',       'password' => 'ANDRES12345@.'],
'mosflow.com'                   => ['host' => 'mail.mosflow.com',      'username' => 'admin@mosflow.com',      'password' => 'ANDRES12345@.'],
'multipross.com'                => ['host' => 'mail.multipross.com',   'username' => 'admin@multipross.com',   'password' => 'ANDRES12345@.'],
'mundoprim.com'                 => ['host' => 'mail.mundoprim.com',    'username' => 'admin@mundoprim.com',    'password' => 'ANDRES12345@.'],
'orega.live'                    => ['host' => 'mail.orega.live',       'username' => 'admin@orega.live',       'password' => 'ANDRES12345@.'],
'panbano.com'                   => ['host' => 'mail.panbano.com',      'username' => 'admin@panbano.com',      'password' => 'ANDRES12345@.'],
'pepeblender.com'               => ['host' => 'mail.crotman.com',      'username' => 'admin@crotman.com',      'password' => 'ANDRES12345@.'],
'pepevampiro.com.co'            => ['host' => 'mail.fodenx.com.co',    'username' => 'admin@fodenx.com.co',    'password' => 'ANDRES12345@.'],
'percloro.com'                  => ['host' => 'mail.crotman.com',      'username' => 'admin@crotman.com',      'password' => 'ANDRES12345@.'],
'peryes.com.co'                 => ['host' => 'mail.peryes.com.co',    'username' => 'admin@peryes.com.co',    'password' => 'ANDRES12345@.'],
'piniguini.com.co'              => ['host' => 'mail.cassrun.com',      'username' => 'admin@cassrun.com',      'password' => 'ANDRES12345@.'],
'prruebas.com'                  => ['host' => 'mail.prruebas.com',     'username' => 'admin@prruebas.com',     'password' => 'ANDRES12345@.'],
'puntilla.com.co'               => ['host' => 'mail.puntilla.com.co',  'username' => 'admin@puntilla.com.co',  'password' => 'ANDRES12345@.'],
'restablecimientosnetyotras.com'=> ['host' => 'mail.restablecimientosnetyotras.com','username' => 'admin@restablecimientosnetyotras.com','password' => 'ANDRES12345@.'],
'tegatea.com.co'                => ['host' => 'mail.tegatea.com.co',   'username' => 'admin@tegatea.com.co',   'password' => 'ANDRES12345@.'],
'tegateapepe.com.co'            => ['host' => 'mail.prruebas.com',     'username' => 'admin@prruebas.com',     'password' => 'ANDRES12345@.'],
'terquillo.com.co'              => ['host' => 'mail.orega.live',       'username' => 'admin@orega.live',       'password' => 'ANDRES12345@.'],
'tulijo.com'                    => ['host' => 'mail.tulijo.com',       'username' => 'admin@tulijo.com',       'password' => 'ANDRES12345@.'],
'toncass.com'                   => ['host' => 'mail.toncass.com',      'username' => 'admin@toncass.com',      'password' => 'ANDRES12345@.'],
'vivicass.com'                  => ['host' => 'mail.vivicass.com',     'username' => 'admin@vivicass.com',     'password' => 'ANDRES12345@.'],
'vixca.co'                      => ['host' => 'mail.vixca.co',         'username' => 'admin@vixca.co',         'password' => 'ANDRES12345@.'],
'vixcasts.com'                  => ['host' => 'mail.vixcasts.com',     'username' => 'admin@vixcasts.com',     'password' => 'ANDRES12345@.'],
'vixlion.com'                   => ['host' => 'mail.vixlion.com',      'username' => 'admin@vixlion.com',      'password' => 'ANDRES12345@.'],
'willamot.com'                  => ['host' => 'mail.willamot.com',     'username' => 'admin@willamot.com',     'password' => 'ANDRES12345@.'],
'ymails.cl'                     => ['host' => 'mail.innurban.com.co',  'username' => 'admin@innurban.com.co',  'password' => 'BREINER12345@'],
'ytmail.in'                     => ['host' => 'mail.ytmail.in',        'username' => 'admin@ytmail.in',        'password' => 'ANDRES12345@.'],
'ytmail.us'                     => ['host' => 'mail.ytmail.us',        'username' => 'admin@ytmail.us',        'password' => 'ANDRES12345@.'],
'amexi.top'                     => ['host' => 'mail.amexi.top',        'username' => 'admin@amexi.top',        'password' => 'ANDRES1003@#'],
'brixo.top'                     => ['host' => 'mail.brixo.top',        'username' => 'admin@brixo.top',        'password' => 'ANDRES1003@#'],
'dexor.top'                     => ['host' => 'mail.dexor.top',        'username' => 'admin@dexor.top',        'password' => 'ANDRES1003@#'],

// ---- Correos personales (Outlook/Gmail/Hotmail) al final ----
'amentretenimiento@outlook.com' => ['host' => 'mail.vixlion.com',      'username' => 'admin@vixlion.com',      'password' => 'ANDRES12345@.'],
'bohmx16@gmail.com'             => ['host' => 'imap.gmail.com',        'username' => 'bohmx16@gmail.com',      'password' => 'uikudwbxsdsqojjw'],
'carlitosperespaes@gmail.com'   => ['host' => 'imap.gmail.com',        'username' => 'carlitosperespaes@gmail.com', 'password' => 'hzlplwcstlqkpbgi'],
'dianaperez86f@outlook.com'     => ['host' => 'mail.vixlion.com',      'username' => 'admin@vixlion.com',      'password' => 'ANDRES12345@.'],
'espalzaluisa435@gmail.com'     => ['host' => 'imap.gmail.com',        'username' => 'espalzaluisa435@gmail.com', 'password' => 'uumdzhuzlembnsly'],
'helpnet2001@hotmail.com'       => ['host' => 'mail.ytmail.us',        'username' => 'admin@ytmail.us',        'password' => 'ANDRES12345@.'],
'karinaperez75d@outlook.com'    => ['host' => 'imap.gmail.com',        'username' => 'pabloquintero34044@gmail.com', 'password' => 'lkremlywhebtrshq'],
'magpmount@gmail.com'           => ['host' => 'mail.boomacount.net',   'username' => 'admin@boomacount.net',   'password' => 'ANDRES12345@.'],
'nueca028@gmail.com'            => ['host' => 'imap.gmail.com',        'username' => 'nueca028@gmail.com',     'password' => 'tmxyjvdzaqchqodz'],
'pabloquintero34044@gmail.com'  => ['host' => 'imap.gmail.com',        'username' => 'pabloquintero34044@gmail.com', 'password' => 'lkremlywhebtrshq'],
'perlagarcia13940@gmail.com'    => ['host' => 'imap.gmail.com',        'username' => 'perlagarcia13940@gmail.com', 'password' => 'ezruojmrhanwvjeg'],
'zapatajuan2447@outlook.com'    => ['host' => 'mail.prruebas.com',     'username' => 'admin@prruebas.com',     'password' => 'ANDRES12345@.'],
    
];
$defaultIMAP = ['host'=>'mail.restablecimientosnetyotras.com','username'=>'admin@restablecimientosnetyotras.com','password'=>'ANDRES12345@.'];

// ====== BD ======
$DB_HOST = "localhost";
$DB_USER = "toncass_cod";
$DB_PASS = "altamar599";
$DB_NAME = "toncass_cod";
$mysqli  = new mysqli($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
if ($mysqli->connect_error) { http_response_code(500); die("❌ Error BD."); }
$mysqli->set_charset('utf8mb4');

// ====== Proceso principal ======
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $usuarioRaw = $_POST['usuario'] ?? '';
  $contrasena = (string)($_POST['contrasena'] ?? '');

  // Guardar lo que escribió el usuario (para repoblar el form)
  $ultimoUsuarioIngresado = normalizarCorreoBasico($usuarioRaw);
  $ultimaClaveIngresada   = (string)$contrasena;

  if ($ultimoUsuarioIngresado === '' || $ultimaClaveIngresada === '') {
    $mensajeHtml = "<div class='warn'>⚠️ Debes ingresar correo y clave.</div>";
  } else {
// ---- Validación en DB (case-insensitive en correo, respeta el +) ----
$usuarioIngresado = trim($_POST['usuario']);
$contrasena       = trim($_POST['contrasena']);

// normalizamos solo a minúsculas
$usuarioLower = strtolower($usuarioIngresado);

$stmt = $mysqli->prepare("
    SELECT usuario, contrasena 
    FROM usuarios_disney 
    WHERE LOWER(usuario) = ? 
    LIMIT 1
");
$stmt->bind_param("s", $usuarioLower);
$stmt->execute();
$res    = $stmt->get_result();
$cuenta = $res->fetch_assoc();
$stmt->close();

    if (!$cuenta) {
      $mensajeHtml = "<div class='warn'>🚫 Esta cuenta no tiene acceso. Verifica que el correo esté EXACTO como en el panel.</div>";
    } else {
      // Comparación robusta de clave (respeta mayúsculas/minúsculas; limpia espacios invisibles)
      $claveIngresada = preg_replace('/\h+/u', ' ', trim((string)$ultimaClaveIngresada));
      $claveBD        = preg_replace('/\h+/u', ' ', trim((string)$cuenta['contrasena']));

      if (!timingSafeEquals($claveBD, $claveIngresada)) {
        $mensajeHtml = "<div class='warn'>🔒 Clave incorrecta. Comunícate con tu proveedor.</div>";
      } else {
        // ====== Autenticado → resolver servidor IMAP y buscar OTP ======
        $buscando = true;

        $dominio      = strtolower(explode('@', $ultimoUsuarioIngresado)[1] ?? '');
        $correoExacto = $ultimoUsuarioIngresado;                  // exacto (con + si lo trae)
        $correoBase   = preg_replace('/\+[^@]+(?=@)/', '', $correoExacto);

        if (isset($imapServers[$dominio]))          { $imapConfig = $imapServers[$dominio]; $origen='dominio'; }
        elseif (isset($imapServers[$correoExacto])) { $imapConfig = $imapServers[$correoExacto]; $origen='correo'; }
        elseif (isset($imapServers[$correoBase]))   { $imapConfig = $imapServers[$correoBase]; $origen='alias+'; }
        else                                        { $imapConfig = $defaultIMAP; $origen='default'; }

        $host = $imapConfig['host']; $user = $imapConfig['username']; $pass = $imapConfig['password'];
        $status[] = "Cuenta: ".htmlspecialchars($correoExacto);
        $status[] = "Servidor ($origen): {$host}:993 (SSL)";

        if (!can_connect($host)) {
          $mensajeHtml = "<div class='info'>⏳ Cargando... espere de 1 a 3 minutos.<br>Si no aparece, intente de nuevo.</div><script>setTimeout(()=>location.reload(),20000);</script>";
        } else {
          $inbox = @imap_open("{".$host.":993/imap/ssl}INBOX", $user, $pass, 0, 1, ['DISABLE_AUTHENTICATOR'=>'GSSAPI,NTLM']);
          if (!$inbox) {
            $mensajeHtml = "<div class='warn'>❌ Error IMAP: ".htmlspecialchars(imap_last_error())."</div>";
          } else {
            $status[] = "Conexión IMAP exitosa.";

            // ====== UIDs más nuevos (hasta 100) ======
            $uids = @imap_search($inbox, "ALL", SE_UID);
            if ($uids === false || empty($uids)) {
              $total = imap_num_msg($inbox);
              $start = max(1, $total - 150);
              $uids = [];
              for ($i = $total; $i >= $start; $i--) { $uids[] = imap_uid($inbox, $i); }
            } else {
              rsort($uids); // más nuevos primero
            }
            $uids = array_slice($uids, 0, 100);

            if (empty($uids)) {
              $mensajeHtml = "<div class='info'>⏳ Cargando... espere de 1 a 3 minutos.<br>Si no aparece, intente de nuevo.</div><script>setTimeout(()=>location.reload(),20000);</script>";
            } else {
              $encontro = false;

              foreach ($uids as $uid) {
                if (!imap_ping($inbox)) { $mensajeHtml = "<div class='warn'>⚠️ Sesión IMAP cerrada.</div>"; break; }

                $msgn = imap_msgno($inbox, $uid);
                $ov   = imap_fetch_overview($inbox, $uid, FT_UID);
                $hdr  = @imap_headerinfo($inbox, $msgn);
                $str  = @imap_fetchstructure($inbox, $msgn);

                // Solo de últimos 15 minutos
                $msgTime = isset($ov[0]->date) ? strtotime($ov[0]->date) : time();
                if (time() - $msgTime > 900) { continue; }

                // CUERPO (prefiere HTML)
                $body = '';
                if ($str && isset($str->parts)) {
                  foreach ($str->parts as $i => $p) {
                    if (isset($p->subtype) && strtoupper($p->subtype)==='HTML') {
                      $raw = imap_fetchbody($inbox, $uid, $i+1, FT_UID);
                      $body = decodeBody($raw, $p->encoding ?? 0);
                      break;
                    }
                  }
                }
                if ($body==='') {
                  $raw = imap_body($inbox, $uid, FT_UID);
                  $body = decodeBody($raw, $str->encoding ?? 0);
                }

                // Validar destinatario EXACTO (incluye + si lo trae)
                $esMismoDestino = false;
                $destinatarios = [];
                if ($hdr && isset($hdr->to)) $destinatarios = array_merge($destinatarios, $hdr->to);
                if ($hdr && isset($hdr->cc)) $destinatarios = array_merge($destinatarios, $hdr->cc);

                foreach ($destinatarios as $dest) {
                  $rcpt = strtolower(($dest->mailbox ?? '').'@'.($dest->host ?? ''));
                  if ($rcpt === strtolower($correoExacto)) { $esMismoDestino = true; break; }
                }

                if (!$esMismoDestino) {
                  $rawHdr = @imap_fetchheader($inbox, $msgn);
                  if ($rawHdr && preg_match_all('/^(Delivered-To|X-Original-To|X-Envelope-To):\s*([^\r\n]+)/mi', $rawHdr, $m)) {
                    foreach ($m[2] as $v) {
                      if (strtolower(trim($v)) === strtolower($correoExacto)) { $esMismoDestino = true; break; }
                    }
                  }
                }

                if (!$esMismoDestino) {
                  $checkBody = strtolower(strip_tags($body));
                  $checkBody = preg_replace('/\s+/', ' ', $checkBody);
                  if (strpos($checkBody, strtolower($correoExacto)) !== false) $esMismoDestino = true;
                }
                if (!$esMismoDestino) continue;

                // Limpieza HTML y extracción 6 dígitos
                $cleanHtml = preg_replace('/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/i', ' ', $body);
                $cleanHtml = preg_replace('/#[0-9a-fA-F]{6}\b/', ' ', $cleanHtml);
                $txt = html_entity_decode(strip_tags($cleanHtml), ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $txt = preg_replace('/\s+/', ' ', $txt);

                // Señales Disney (remitente o asunto)
                $isDisneySender=false; $senders=[];
                if ($hdr && isset($hdr->from))     $senders=array_merge($senders,$hdr->from);
                if ($hdr && isset($hdr->sender))   $senders=array_merge($senders,$hdr->sender);
                if ($hdr && isset($hdr->reply_to)) $senders=array_merge($senders,$hdr->reply_to);
                foreach ($senders as $a){
                  $h=strtolower($a->host??'');
                  if (preg_match('/(^|\.)disneyplus\.com$|(^|\.)disney\.com$/',$h)){ $isDisneySender=true; break; }
                }
                $subject = decodeSubjectSafe($ov[0]->subject ?? '');
                $hasDisney = (stripos($subject,'disney')!==false || stripos($subject,'disney+')!==false || stripos($subject,'disney plus')!==false);

                // Sacar último 6-dígitos
                $codigo = null;
                if ($isDisneySender || $hasDisney) {
                  if (preg_match('/\b\d{6}\b/', $txt, $m)) { $codigo = $m[0]; }
                }

                if ($codigo) {
                  $fecha = date("Y-m-d H:i:s", $msgTime);
                  $from  = '';
                  if ($hdr && !empty($hdr->from)) {
                    $f = $hdr->from[0];
                    $from = htmlspecialchars(trim(($f->personal??''))." <{$f->mailbox}@{$f->host}>");
                  }
                  $asunto = htmlspecialchars($subject);

                  $metaHtml = "<div class='meta'>
                    <div><b>Remitente:</b> {$from}</div>
                    <div><b>Fecha:</b> {$fecha}</div>
                    <div><b>Asunto:</b> {$asunto}</div>
                  </div>";

                  $codigoHtml = "<div class='codeTitle'>Código de tu cuenta</div>
                  <div id='codigoDisney' class='codeBig'>{$codigo}</div>
                  <div class='fechaBig'>⏰ {$fecha}</div>
                  <script>
                    (function(){
                      try {
                        var t = document.getElementById('codigoDisney').textContent.trim();
                        if (t && navigator.clipboard) { navigator.clipboard.writeText(t); }
                      } catch(e){}
                    })();
                  </script>";

                  $encontro = true;
                  break; // más reciente válido
                }
              } // foreach

              if (empty($encontro)) {
                $mensajeHtml = "<div class='info'>⏳ Cargando... espere de 1 a 3 minutos.<br>Si no aparece, intente de nuevo.</div><script>setTimeout(()=>location.reload(),20000);</script>";
              }
            }
            @imap_close($inbox);
          }
        }
      }
    }
  }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Código</title>
<style>
  :root{ --bg1:#1a0550; --bg2:#4b1d95; --card:#160a3a; --text:#e9e7ff; --muted:#b9b5d9; --accent:#7c3aed; }
  html,body{height:100%}
  body{
    margin:0; font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif; color:var(--text);
    background: radial-gradient(1200px 800px at 70% 30%, rgba(255,255,255,.08), transparent 60%),
                linear-gradient(160deg, var(--bg1), var(--bg2));
  }
  .status{
    position:fixed; top:10px; left:10px; z-index:10;
    background:rgba(15,10,35,.9); border:1px solid rgba(255,255,255,.15);
    padding:8px 10px; border-radius:8px; box-shadow:0 8px 24px rgba(0,0,0,.35);
    font-size:13px; line-height:1.4;
  }
  .wrap{max-width:1100px; margin:0 auto; padding:110px 20px 40px;}
  .grid{display:grid; grid-template-columns: 1.2fr 1fr; gap:28px;}
  @media (max-width:900px){ .grid{grid-template-columns:1fr; } .status{position:static; margin:10px; } .wrap{padding-top:20px;} }

  .meta{
    background:rgba(15,10,40,.55); border:1px solid rgba(255,255,255,.12);
    border-radius:12px; padding:16px 18px; backdrop-filter: blur(4px);
  }
  .meta b{color:#fff}
  .codeBox{
    background:rgba(15,10,40,.55); border:1px solid rgba(255,255,255,.12);
    border-radius:16px; padding:20px; text-align:center;
  }
  .codeTitle{color:var(--muted); font-weight:700; margin-bottom:10px; letter-spacing:.5px}
  .codeBig{font-size:68px; font-weight:900; letter-spacing:8px}
  .fechaBig{
    font-size: 2em; font-weight: bold; margin-top: 10px; color: #ffd37a; text-align: center;
  }
  .formCard{
    margin-top:16px; background:var(--card); border:1px solid rgba(255,255,255,.12);
    border-radius:16px; padding:18px 18px 22px;
  }
  .lbl{font-weight:700; margin:10px 0 6px; color:#ddd; text-align:left}
  .in{width:100%; padding:12px; border-radius:10px; border:1px solid rgba(255,255,255,.2);
      background:#1f1140; color:#fff; outline:none}
  .btn{margin-top:14px; width:100%; padding:12px; border:0; border-radius:10px;
       background:var(--accent); color:#fff; font-weight:800; cursor:pointer}
  .showpass{ margin-top:8px; font-size:13px; display:flex; align-items:center; gap:6px; color:#ddd; }
  .info,.warn{ text-align:center; margin-top:18px; font-size:18px}
  .info{ color:#ffd37a }
  .warn{ color:#ffaaaa }
</style>
</head>
<body>

<?php if(!empty($status)): ?>
  <div class="status">
    <?php foreach($status as $s){ echo "• ".htmlspecialchars($s)."<br>"; } ?>
  </div>
<?php endif; ?>

<div class="wrap">
  <div class="grid">
    <div>
      <?php
        // Solo mostramos “Esperando…” si estamos buscando (autenticación OK)
        echo $metaHtml ?: ($buscando ? "<div class='meta'><div>Esperando correo reciente… (1–3 minutos)</div></div>" : "");
        echo $mensajeHtml;
      ?>
    </div>

    <div>
      <div class="codeBox">
        <?php echo $codigoHtml ?: "<div class='codeTitle'>Código de tu cuenta</div><div class='codeBig'>__</div>"; ?>
      </div>

      <form class="formCard" method="POST" autocomplete="off">
        <div class="lbl">Correo completo:</div>
        <input class="in" type="email" name="usuario" required
               value="<?php echo htmlspecialchars($ultimoUsuarioIngresado, ENT_QUOTES, 'UTF-8'); ?>">

        <div class="lbl">Contraseña:</div>
        <input class="in" id="pass" type="password" name="contrasena" required
               value="<?php echo htmlspecialchars($ultimaClaveIngresada, ENT_QUOTES, 'UTF-8'); ?>">
        <label class="showpass"><input type="checkbox" id="togglePass"> Mostrar clave</label>

        <button class="btn" type="submit">Consultar código</button>
      </form>
    </div>
  </div>
</div>

<script>
document.getElementById('togglePass')?.addEventListener('change', function(){
  const p = document.getElementById('pass');
  if (!p) return;
  p.type = this.checked ? 'text' : 'password';
});
</script>

</body>
</html>