<?php
// raspadita/login.php — Login UI estilo CASINO / JUEGOS DE AZAR (consume API JSON)

declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');

if (isset($_SESSION['ingreso']) && $_SESSION['ingreso'] === 'YES' && (int)($_SESSION['raspadita'] ?? 0) === 1) {
  header("Location: admin.php"); exit;
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Login · Raspaditas</title>

  <link rel="shortcut icon" href="../resources/img/crud.ico">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

  <style>
    :root{
      --bg0:#07040f;
      --bg1:#0a0520;
      --card: rgba(10, 8, 26, .72);
      --card2: rgba(18, 14, 40, .78);
      --text:#e5e7eb;
      --muted:#9aa6bf;
      --border: rgba(255,255,255,.12);
      --shadow: 0 22px 80px rgba(0,0,0,.65);

      --neon1:#22d3ee; /* cyan */
      --neon2:#a855f7; /* purple */
      --neon3:#f59e0b; /* amber */

      --ring: rgba(34, 211, 238, .25);
      --inputBg: rgba(255,255,255,.06);
      --inputText:#e5e7eb;
    }

    body{
      min-height:100vh;
      display:flex;
      align-items:center;
      justify-content:center;
      color: var(--text);
      background:
        radial-gradient(900px 520px at 15% 10%, rgba(168,85,247,.22), transparent 55%),
        radial-gradient(820px 520px at 85% 20%, rgba(34,211,238,.18), transparent 55%),
        radial-gradient(900px 620px at 50% 95%, rgba(245,158,11,.12), transparent 60%),
        linear-gradient(180deg, var(--bg0), var(--bg1));
      overflow:hidden;
      padding: 18px;
    }

    /* Glow grid (casino vibe) */
    body::before{
      content:"";
      position:absolute; inset:0;
      background-image:
        linear-gradient(rgba(255,255,255,.05) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255,255,255,.05) 1px, transparent 1px);
      background-size: 48px 48px;
      opacity:.12;
      mask-image: radial-gradient(circle at 50% 25%, rgba(0,0,0,1), rgba(0,0,0,0.25) 60%, transparent 80%);
      pointer-events:none;
    }

    .wrap{
      width:min(520px, 100%);
      position:relative;
      z-index:2;
    }

    /* Floating neon chips */
    .chip{
      position:absolute;
      width: 120px; height: 120px;
      border-radius: 50%;
      border: 2px dashed rgba(255,255,255,.18);
      box-shadow:
        0 0 0 6px rgba(255,255,255,.05) inset,
        0 0 40px rgba(34,211,238,.14);
      background: radial-gradient(circle at 35% 35%, rgba(255,255,255,.12), rgba(255,255,255,.02) 55%, transparent 70%);
      opacity:.85;
      animation: float 10s ease-in-out infinite;
      pointer-events:none;
    }
    .chip.c1{left:-40px; top:-50px; box-shadow:0 0 40px rgba(168,85,247,.18); animation-duration: 12s;}
    .chip.c2{right:-50px; top:30px; box-shadow:0 0 40px rgba(34,211,238,.18); animation-duration: 10s;}
    .chip.c3{left:40%; bottom:-70px; box-shadow:0 0 40px rgba(245,158,11,.18); animation-duration: 14s;}
    @keyframes float{
      0%,100%{ transform: translate(0,0) rotate(0deg); }
      50%{ transform: translate(18px,-14px) rotate(8deg); }
    }

    .card{
      border-radius: 24px;
      border: 1px solid var(--border);
      background: linear-gradient(180deg, var(--card), var(--card2));
      box-shadow: var(--shadow);
      backdrop-filter: blur(10px);
      overflow:hidden;
      position:relative;
    }

    /* Neon border */
    .card::before{
      content:"";
      position:absolute; inset:-2px;
      background: linear-gradient(135deg, rgba(34,211,238,.45), rgba(168,85,247,.40), rgba(245,158,11,.35));
      filter: blur(12px);
      opacity:.55;
      z-index:0;
    }
    .card .card-body{ position:relative; z-index:1; }

    .header{
      display:flex;
      align-items:flex-start;
      justify-content:space-between;
      gap:12px;
      margin-bottom: 12px;
    }

    .brand{
      display:flex;
      gap:12px;
      align-items:center;
    }

    .logo{
      width:56px;height:56px;border-radius: 18px;
      display:flex;align-items:center;justify-content:center;
      background: radial-gradient(circle at 30% 30%, rgba(34,211,238,.25), rgba(168,85,247,.18));
      border:1px solid rgba(255,255,255,.14);
      box-shadow: 0 0 30px rgba(34,211,238,.16);
      color: var(--text);
      font-size: 24px;
    }

    .title{
      font-weight: 900;
      letter-spacing: .4px;
      font-size: 1.18rem;
      line-height: 1.1;
      color: #ffffff; /* ✅ blanco */
    }

    .badge-soft{
      display:inline-flex;
      align-items:center;
      gap:8px;
      padding:.4rem .65rem;
      border-radius: 999px;
      border: 1px solid rgba(255,255,255,.14);
      background: rgba(255,255,255,.06);
      color: var(--muted);
      font-size: .9rem;
      user-select:none;
    }

    .field{ position:relative; }
    .field .ico{
      position:absolute;
      left: 14px;
      top: 50%;
      transform: translateY(-50%);
      color: rgba(255,255,255,.65);
      font-size: 1rem;
      pointer-events:none;
    }

    .form-label{ color: rgba(255,255,255,.82); font-weight: 700; }
    .form-control{
      border-radius: 16px;
      padding: .95rem 1rem .95rem 2.75rem;
      background: var(--inputBg);
      color: var(--inputText);
      border: 1px solid rgba(255,255,255,.14);
      font-size: 1.06rem;
    }
    .form-control::placeholder{ color: rgba(255,255,255,.45); }
    .form-control:focus{
      box-shadow: 0 0 0 .22rem var(--ring);
      border-color: rgba(34,211,238,.55);
    }

    .toggle{
      cursor:pointer;
      user-select:none;
      color: rgba(255,255,255,.7);
      font-size: .92rem;
    }

    .actions{
      display:flex;
      align-items:center;
      justify-content:flex-start; /* ✅ ya no hay texto a la derecha */
      gap:12px;
      margin-top: .35rem;
    }
    .form-check-label{ color: var(--muted); }

    /* Jackpot button */
    .btn-jackpot{
      border:0;
      border-radius: 16px;
      padding: .95rem 1rem;
      font-weight: 900;
      letter-spacing: .4px;
      color: #0b1020;
      background: linear-gradient(135deg, var(--neon3), #ffe08a, var(--neon3));
      background-size: 200% 200%;
      box-shadow:
        0 18px 40px rgba(245,158,11,.22),
        0 0 0 1px rgba(255,255,255,.10) inset;
      transition: transform .12s ease, box-shadow .12s ease;
    }
    .btn-jackpot:hover{
      transform: translateY(-1px);
      box-shadow:
        0 24px 55px rgba(245,158,11,.28),
        0 0 0 1px rgba(255,255,255,.12) inset;
      animation: shine 1.1s ease infinite;
    }
    @keyframes shine{
      0%{background-position: 0% 50%;}
      50%{background-position: 100% 50%;}
      100%{background-position: 0% 50%;}
    }

    .alert{
      border-radius: 16px;
      border: 1px solid rgba(255,255,255,.14);
      background: rgba(239,68,68,.10);
      color: #fecaca;
    }

    /* Overlay loader */
    .overlay{
      position:fixed; inset:0;
      display:none;
      align-items:center;
      justify-content:center;
      background: rgba(0,0,0,.55);
      backdrop-filter: blur(6px);
      z-index: 9999;
      padding: 16px;
    }
    .overlay-card{
      width:min(440px, 100%);
      border-radius: 18px;
      border: 1px solid rgba(255,255,255,.14);
      background: rgba(15,23,42,.78);
      box-shadow: 0 20px 70px rgba(0,0,0,.6);
      padding: 18px;
      display:flex;
      align-items:center;
      gap:12px;
      color: var(--text);
    }
    .spinner-border{width:1.15rem;height:1.15rem;}
  </style>
</head>
<body>

<div class="wrap">
  <div class="chip c1"></div>
  <div class="chip c2"></div>
  <div class="chip c3"></div>

  <!-- Loader overlay -->
  <div class="overlay" id="overlay">
    <div class="overlay-card">
      <div class="spinner-border" role="status" aria-hidden="true"></div>
      <div>
        <div class="fw-bold">Validando acceso…</div>
        <div class="text-muted" style="font-size:.92rem;color:rgba(255,255,255,.65)!important;">No cierres esta ventana</div>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-body p-4 p-md-5">

      <div class="header">
        <div class="brand">
          <div class="logo"><i class="fa-solid fa-dice"></i></div>
          <div>
            <div class="title">RASPADITAS · ADMIN</div>
          </div>
        </div>

        <div class="badge-soft" title="Solo personal autorizado">
          <i class="fa-solid fa-shield-halved"></i>
          <span>Seguro</span>
        </div>
      </div>

      <div id="alertBox" class="alert d-none" role="alert"></div>

      <form id="frmLogin" onsubmit="return false;">
        <label class="form-label">Usuario</label>
        <div class="field mb-3">
          <i class="fa-solid fa-user ico"></i>
          <input id="usuario" class="form-control" autocomplete="username" placeholder="Ingrese su usuario" required>
        </div>

        <label class="form-label d-flex align-items-center justify-content-between">
          <span>Clave</span>
          <span class="toggle" id="togglePass"><i class="fa-regular fa-eye"></i> ver</span>
        </label>
        <div class="field mb-2">
          <i class="fa-solid fa-key ico"></i>
          <input id="clave" type="password" class="form-control" autocomplete="current-password" placeholder="Ingrese su clave" required>
        </div>

        <div class="actions mb-3">
          <div class="form-check m-0">
            <input class="form-check-input" type="checkbox" value="1" id="rememberMe">
            <label class="form-check-label" for="rememberMe">Recordarme</label>
          </div>
        </div>

        <button id="btnLogin" class="btn btn-jackpot w-100" type="button" onclick="doLogin()">
          <i class="fa-solid fa-right-to-bracket"></i> ENTRAR
        </button>
      </form>

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

<script>
  const API_LOGIN = "api/login.php";
  const LS_USER  = "raspadita_remember_user";

  function showError(msg){
    const box = document.getElementById('alertBox');
    box.textContent = msg || 'Error';
    box.classList.remove('d-none');
  }
  function hideError(){
    document.getElementById('alertBox').classList.add('d-none');
  }
  function setLoading(on){
    document.getElementById('overlay').style.display = on ? 'flex' : 'none';
    const btn = document.getElementById('btnLogin');
    btn.disabled = !!on;
    btn.innerHTML = on
      ? '<i class="fa-solid fa-circle-notch fa-spin"></i> VALIDANDO…'
      : '<i class="fa-solid fa-right-to-bracket"></i> ENTRAR';
  }

  document.getElementById('togglePass').addEventListener('click', ()=>{
    const input = document.getElementById('clave');
    const isPass = input.type === 'password';
    input.type = isPass ? 'text' : 'password';
    document.getElementById('togglePass').innerHTML = isPass
      ? '<i class="fa-regular fa-eye-slash"></i> ocultar'
      : '<i class="fa-regular fa-eye"></i> ver';
    input.focus();
  });

  document.getElementById('frmLogin').addEventListener('keydown', (e)=>{
    if (e.key === 'Enter') { e.preventDefault(); doLogin(); }
  });

  (function init(){
    const savedUser = localStorage.getItem(LS_USER) || "";
    if (savedUser.trim()) {
      document.getElementById('usuario').value = savedUser;
      document.getElementById('rememberMe').checked = true;
      document.getElementById('clave').focus();
    } else {
      document.getElementById('usuario').focus();
    }
  })();

  async function doLogin(){
    hideError();

    const usuario = (document.getElementById('usuario').value || '').trim();
    const clave   = (document.getElementById('clave').value || '').trim();
    const remember = document.getElementById('rememberMe').checked;

    if(!usuario || !clave){
      showError('Ingrese usuario y clave.');
      return;
    }

    try{
      if (remember) localStorage.setItem(LS_USER, usuario);
      else localStorage.removeItem(LS_USER);
    }catch(e){}

    setLoading(true);

    try{
      const r = await fetch(API_LOGIN, {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        credentials: 'include',                 // ✅ importante para sesión por cookie
        body: JSON.stringify({usuario, clave, remember})
      });

      const txt = await r.text();
      let data = null;
      try { data = JSON.parse(txt); }
      catch(e){ data = {success:false, message: txt || 'Respuesta no válida'}; }

      if(!r.ok || !data?.success){
        showError(data?.message || 'No se pudo iniciar sesión.');
        setLoading(false);
        return;
      }

      // ✅ usar redirect que manda el API:
      const go = (data.redirect && String(data.redirect).trim()) ? data.redirect : 'admin.php';
      window.location.href = go;

    }catch(err){
      showError('Error de red. ' + (err?.message || ''));
      setLoading(false);
    }
  }
</script>