<?php
// index.php — Pantalla de Login · rifa_prueba
// Si ya hay sesión activa puedes redirigir al panel:
// session_start();
// if (isset($_SESSION['ingreso']) && $_SESSION['ingreso'] === 'YES') {
//   header('Location: ./views/pages/ventas.php'); exit;
// }
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Sistema de Gestión · Login</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.0.0/css/all.min.css" rel="stylesheet">
<style>
  :root{--bg:#f5f6fb;--card:#fff;--text:#212529;--muted:#6c757d;--fz:16px}
  .dark{--bg:#0e1320;--card:#141a2a;--text:#e6e8ee;--muted:#9aa4b2}
  html,body{height:100%}
  body{background:var(--bg);color:var(--text);display:flex;align-items:center;justify-content:center;padding:16px;font-size:var(--fz)}
  #box{width:100%;max-width:420px;background:var(--card);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.12);padding:16px}
  .brand{display:flex;align-items:center;gap:.5rem;font-weight:600;font-size:1.1rem;margin:0}
  .text-muted{color:var(--muted)!important}
  .input-group-text,.form-control{border-radius:.5rem}
  .toggle-password{cursor:pointer}
  .alert{display:none;margin-bottom:.75rem}
  .caps{display:none;font-size:.9rem;color:#dc3545;margin:.25rem 0 0}
  footer{margin-top:.5rem;text-align:center;color:var(--muted);font-size:.9rem}
  .dark .form-control,.dark .input-group-text{background:#10172a;color:var(--text);border-color:#253455}
  .dark .form-control::placeholder{color:#8f97a7}
</style>
</head>
<body>
<main id="box">
  <div class="d-flex justify-content-between align-items-center mb-1">
    <h1 class="brand"><i class="fas fa-tachometer-alt"></i> Gestión</h1>
    <button id="toggle-dark" class="btn btn-sm btn-outline-secondary" type="button" title="Modo oscuro">
      <i class="fa-solid fa-moon"></i>
    </button>
  </div>
  <p class="text-muted mb-2">Inicia sesión para continuar…</p>

  <div id="msg" class="alert alert-danger" role="alert">
    <i class="fas fa-exclamation-circle"></i> <span></span>
  </div>

  <form id="frm" autocomplete="on">
    <div class="mb-2 input-group">
      <span class="input-group-text"><i class="fas fa-user"></i></span>
      <input type="text" id="usuario" name="usuario" class="form-control" placeholder="Usuario" required>
    </div>
    <div class="mb-1 input-group">
      <span class="input-group-text"><i class="fas fa-lock"></i></span>
      <input type="password" id="pass" name="pass" class="form-control" placeholder="Contraseña" required>
      <span class="input-group-text toggle-password" title="Mostrar/ocultar"><i class="fas fa-eye-slash"></i></span>
    </div>
    <div id="caps" class="caps"><i class="fa-solid fa-keyboard"></i> Bloq Mayús activado</div>

    <div class="d-flex justify-content-between align-items-center my-2">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="1" id="remember">
        <label class="form-check-label" for="remember">Recordarme</label>
      </div>
    </div>

    <button type="button" class="btn btn-primary w-100" id="btn">
      <span class="txt">Iniciar sesión</span>
    </button>
  </form>

  <footer>&copy; 2025 Sistema de Gestión Digital</footer>
</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
(function(){
  const $b=$('body'),$f=$('#frm'),$u=$('#usuario'),$p=$('#pass'),$btn=$('#btn'),$txt=$btn.find('.txt'),$msg=$('#msg'),$msgTxt=$('#msg span');

  // Modo oscuro persistente
  const DARK='ui.theme.dark'; if(localStorage.getItem(DARK)==='1')$b.addClass('dark');
  $('#toggle-dark').on('click',()=>{ $b.toggleClass('dark'); localStorage.setItem(DARK,$b.hasClass('dark')?'1':'0'); });

  // Recordarme (solo usuario)
  const RK='login.remember', RU='login.remember.user';
  if(localStorage.getItem(RK)==='1'){ $('#remember').prop('checked',true); const su=localStorage.getItem(RU)||''; if(su)$u.val(su); }
  $('#remember').on('change',function(){ const on=$(this).is(':checked'); localStorage.setItem(RK,on?'1':'0'); if(!on)localStorage.removeItem(RU); });

  // Mensajes
  function showErr(t){ $msgTxt.text(t||'Usuario o clave incorrecta. Intente nuevamente.'); $msg.stop(true,true).fadeIn(120); }
  function hideErr(){ $msg.hide(); }

  // Loader botón
  function loading(s){
    if(s){ $btn.prop('disabled',true).prepend('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>'); $txt.text('Iniciando…'); }
    else{ $btn.prop('disabled',false).find('.spinner-border').remove(); $txt.text('Iniciar sesión'); }
  }

  // CapsLock hint
  $p.on('keydown keyup',e=>{ const s=e.getModifierState&&e.getModifierState('CapsLock'); $('#caps').toggle(!!s); });

  // Toggle password
  $('.toggle-password').on('click',function(){ const i=$(this).find('i'); const t=$p.attr('type')==='password'?'text':'password'; $p.attr('type',t); i.toggleClass('fa-eye fa-eye-slash'); });

  // Enter para enviar
  $(document).on('keydown',e=>{ if(e.key==='Enter'){ e.preventDefault(); if(!$btn.is(':disabled')) enviar(); }});

  // Click botón
  $btn.on('click',enviar);

  function enviar(){
    hideErr();
    const usuario=($u.val()||'').trim(), pass=($p.val()||'').trim();
    if(!usuario||!pass){ showErr('Por favor, completa todos los campos.'); return; }
    if($('#remember').is(':checked')){ localStorage.setItem(RU,usuario); localStorage.setItem(RK,'1'); }

    loading(true);
    $.ajax({
      url:'/rifa/controllers/usuario.php', // ajusta si tu carpeta base cambia
      type:'POST',
      dataType:'text', // backend devuelve 0/1/2
      data:{boton:'ingresar', usuario, pass}
    }).done(function(resp){
      const r=(resp||'').trim();
      if(r==='0'){ window.location.href='./pages/ventas.php'; return; }
      if(r==='2'){ showErr('La IP actual no coincide con la registrada para este usuario.'); return; }
      showErr('Usuario o clave incorrecta. Intente nuevamente.');
    }).fail(function(){
      showErr('Hubo un error al procesar la solicitud. Intenta nuevamente.');
    }).always(function(){ loading(false); });
  }
})();
</script>
</body>
</html>
