<?php
declare(strict_types=1);

require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/session_staff.php";

if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

$next = trim((string)($_GET['next'] ?? $_POST['next'] ?? ''));

// Compatível com PHP 7
if ($next === '' || substr($next, 0, 1) !== '/') {
  $next = APP_BASE . "/painel.php";
}

$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $usuario = trim((string)($_POST['usuario'] ?? ''));
  $senha   = (string)($_POST['senha'] ?? '');

  $st = $pdo->prepare("SELECT id, nome, usuario, senha_hash, role, ativo FROM staff_users WHERE usuario=? LIMIT 1");
  $st->execute([$usuario]);
  $u = $st->fetch(PDO::FETCH_ASSOC);

  if (!$u || (int)$u['ativo'] !== 1 || !password_verify($senha, (string)$u['senha_hash'])) {
    $error = "Usuário ou senha inválidos.";
  } else {
    $role = (string)$u['role'];

    $_SESSION['staff'] = [
      'id' => (int)$u['id'],
      'nome' => (string)$u['nome'],
      'usuario' => (string)$u['usuario'],
      'role' => $role,
      'perms' => staff_role_perms($role),
      'login_em' => date('Y-m-d H:i:s'),
    ];

    header("Location: " . $next);
    exit;
  }
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  <title>Login • Staff</title>

  <style>
    :root{
      /* ===== Win10 Dark (flat) ===== */
      --bg:#0f0f10;
      --text:#f3f3f3;
      --muted:rgba(243,243,243,.70);

      --card: rgba(32,32,34,.92);
      --input: rgba(18,18,20,.92);

      --line: rgba(255,255,255,.12);
      --line2: rgba(255,255,255,.08);

      --accent:#60cdff;
      --danger:#ff5a5f;

      --radius:18px;
      --tap: 48px;
      --focus: 0 0 0 3px rgba(96,205,255,.18);
    }

    *{ box-sizing:border-box; }
    html,body{ height:100%; }

    body{
      margin:0;
      font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
      color:var(--text);
      background: var(--bg);
      display:grid;
      place-items:center;
      padding:18px;
    }

    .wrap{ width:min(460px, 100%); }

    .card{
      border:1px solid var(--line);
      border-radius:var(--radius);
      overflow:hidden;
      background: var(--card);
    }

    .topbar{
      padding:16px 18px;
      display:flex;
      align-items:center;
      gap:12px;
      border-bottom:1px solid var(--line2);
      background: rgba(255,255,255,.03);
    }

    .badge{
      width:42px; height:42px;
      border-radius:14px;
      background: rgba(255,255,255,.06);
      border:1px solid var(--line);
      display:grid;
      place-items:center;
      flex:0 0 auto;
    }

    .title h1{ margin:0; font-size:18px; font-weight:900; letter-spacing:.2px; }
    .title p{ margin:4px 0 0; font-size:12px; color:var(--muted); }

    form{ margin:0; padding:16px 18px 18px; }

    .err{
      margin:0 0 12px;
      padding:10px 12px;
      border-radius:14px;
      background: rgba(255,90,95,.12);
      border:1px solid rgba(255,90,95,.34);
      color:#ffd2d2;
      font-size:13px;
    }

    .field{ margin-top:12px; }
    label{ display:block; margin:0 0 6px; font-size:12px; color:var(--muted); }

    .input{
      width:100%;
      padding:12px 12px;
      border-radius:14px;
      border:1px solid var(--line);
      background: var(--input);
      color: var(--text);
      outline:none;
      transition: box-shadow .15s ease, border-color .15s ease, background .15s ease;
    }
    .input:focus{
      border-color: rgba(96,205,255,.55);
      box-shadow: var(--focus);
    }

    .row{ margin-top:14px; display:flex; gap:10px; }

    .btn{
      width:100%;
      height:56px;
      border-radius:14px;
      border:1px solid rgba(96,205,255,.26);
      background: rgba(96,205,255,.14);
      color: var(--text);
      font-weight:950;
      cursor:pointer;
      transition: transform .06s ease, background .12s ease, border-color .12s ease;
    }
    .btn:hover{
      background: rgba(96,205,255,.18);
      border-color: rgba(96,205,255,.34);
    }
    .btn:active{ transform: translateY(1px); }

    .foot{
      margin-top:12px;
      padding-top:12px;
      border-top:1px solid var(--line2);
      color:var(--muted);
      font-size:12px;
      line-height:1.35;
    }
    .mono{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }

    @media (prefers-reduced-motion: reduce){
      *{ transition:none !important; scroll-behavior:auto !important; }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <div class="topbar">
        <div class="badge" aria-hidden="true">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M12 2l8 4v6c0 5-3.4 9.4-8 10-4.6-.6-8-5-8-10V6l8-4z"
                  stroke="rgba(243,243,243,.92)" stroke-width="1.6"/>
            <path d="M9.2 12.1l2 2 3.8-4"
                  stroke="rgba(96,205,255,.95)" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <div class="title">
          <h1>Login • Staff</h1>
          <p>Acesso unificado aos módulos</p>
        </div>
      </div>

      <form method="post" autocomplete="on">
        <?php if($error): ?>
          <div class="err"><?=h($error)?></div>
        <?php endif; ?>

        <input type="hidden" name="next" value="<?=h($next)?>">

        <div class="field">
          <label for="u">Usuário</label>
          <input id="u" class="input" name="usuario" autocomplete="username" required>
        </div>

        <div class="field">
          <label for="p">Senha</label>
          <input id="p" class="input" name="senha" type="password" autocomplete="current-password" required>
        </div>

        <div class="row">
          <button class="btn" type="submit">Entrar</button>
        </div>

        <div class="foot">
          Redirecionamento após login:
          <div class="mono" style="margin-top:6px; word-break:break-all; opacity:.9;"><?=h($next)?></div>
        </div>
      </form>
    </div>
  </div>
</body>
</html>
