<?php
// public/admin_login.php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';

/* ============================================================
 * CONFIGURAÇÃO DE SESSÃO — (mais estável para tablets)
 * ============================================================ */
$life = 8 * 3600; // 8 horas

@ini_set('session.gc_maxlifetime', (string)$life);
@ini_set('session.cookie_lifetime', (string)$life);

session_name('ARAP_SESS');
session_set_cookie_params([
  'lifetime' => $life,
  'path'     => '/',
  'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off', // true se sempre https
  'httponly' => true,
  'samesite' => 'Lax'
]);

session_start_safe();

/* ============================================================
 * SE JÁ ESTIVER LOGADO → redireciona conforme tipo
 * ============================================================ */
if (!empty($_SESSION['user_id'])) {
  $tipo = $_SESSION['tipo'] ?? $_SESSION['tipo_usuario'] ?? '';
  $eh_presidente = (int)($_SESSION['eh_presidente'] ?? 0);

  if ($tipo === 'operador') {
    header('Location: /arapiraca/admin.php');
    exit;
  }
  if ($tipo === 'presidente' || $eh_presidente === 1) {
    header('Location: /arapiraca/presidente.php');
    exit;
  }
  header('Location: /arapiraca/vereador.php');
  exit;
}

/** LOGO (somente no topo) */
$LOGO = '/arapiraca/assets/leggov.png';

$error = null;
$timeoutMsg = (isset($_GET['timeout']) && $_GET['timeout'] == '1')
  ? 'Sua sessão expirou por inatividade. Faça login novamente.'
  : null;

/* ============================================================
 * LOGIN — POST
 * ============================================================ */
if (is_post()) {
  $email = strtolower(trim($_POST['email'] ?? ''));
  $senha = $_POST['senha'] ?? '';

  $stmt = $pdo->prepare("
        SELECT id, nome, email, senha_hash, tipo_usuario, ativo,
               COALESCE(eh_presidente,0) AS eh_presidente,
               COALESCE(nao_vota,0)      AS nao_vota
        FROM usuarios
        WHERE TRIM(LOWER(email)) = :e
        LIMIT 1
    ");
  $stmt->execute([':e' => $email]);
  $u = $stmt->fetch();

  if (!$u) {
    $error = "Credenciais inválidas.";
  } elseif ((int)$u['ativo'] !== 1) {
    $error = "Usuário inativo.";
  } elseif (!is_string($u['senha_hash']) || strlen($u['senha_hash']) < 55) {
    $error = "Senha inválida (hash corrompido).";
  } elseif (!password_verify($senha, $u['senha_hash'])) {
    $error = "Credenciais inválidas.";
  } else {

    // Rehash oportunista
    if (password_needs_rehash($u['senha_hash'], PASSWORD_BCRYPT, ['cost' => 10])) {
      $novo = password_hash($senha, PASSWORD_BCRYPT, ['cost' => 10]);
      $pdo->prepare("UPDATE usuarios SET senha_hash=:h WHERE id=:id")
        ->execute([':h' => $novo, ':id' => $u['id']]);
    }

    // Grava sessão
    login_user([
      'id'            => $u['id'],
      'nome'          => $u['nome'],
      'email'         => $u['email'],
      'tipo'          => $u['tipo_usuario'],
      'tipo_usuario'  => $u['tipo_usuario'],
      'eh_presidente' => (int)$u['eh_presidente'],
      'nao_vota'      => (int)$u['nao_vota'],
    ]);

    // Redireciona conforme tipo
    $dest = 'vereador.php';
    if ($u['tipo_usuario'] === 'operador') {
      $dest = 'admin.php';
    } elseif ($u['tipo_usuario'] === 'presidente' || (int)$u['eh_presidente'] === 1) {
      $dest = 'presidente.php';
    }
    header('Location: /arapiraca/' . $dest);
    exit;
  }
}
?>
<!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 - Sistema de Votação</title>
  <link rel="stylesheet" href="/arapiraca/assets/style.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <style>
    *,
    *::before,
    *::after {
      box-sizing: border-box;
    }

    :root {
      --brand: #2563eb;
      --brand-600: #1d4ed8;
      --bg: #eef2f8;
      --card: #fff;
      --muted: #64748b;
      --text: #0f172a;
      --border: #e5e7eb;
      --danger: #ef4444;
      --rad: 16px;
      --shadow: 0 18px 50px rgba(2, 6, 23, .08), 0 2px 10px rgba(2, 6, 23, .05);
    }

    html,
    body {
      height: 100%
    }

    body {
      margin: 0;
      overflow-x: hidden;
      background:
        radial-gradient(900px 420px at -10% -10%, #d7defa 0 60%, transparent 61%),
        radial-gradient(960px 480px at 110% 0%, #ffc6cf 0 55%, transparent 56%),
        linear-gradient(180deg, #e2e7ef 0%, #d9dee8 100%);
      background-color: #e2e6f0;
      color: var(--text);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Inter, system-ui, Arial, sans-serif;
    }

    .nav {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0 8px;
      background: #fff;
      border-bottom: 1px solid var(--border);
      position: sticky;
      top: 0;
      z-index: 5;
    }

    .nav .brand-wrap {
      display: flex;
      align-items: center;
      gap: 8px
    }

    .nav img {
      height: 100px;
      width: auto;
      object-fit: contain;
      display: block;
    }

    .nav strong {
      font-weight: 800;
      color: #0f172a;
    }

    .wrap {
      max-width: 1100px;
      margin: 8px auto;
      padding: 0 12px;
    }

    .grid {
      display: grid;
      gap: 16px;
      grid-template-columns: 1fr 420px;
      align-items: stretch;
    }

    .grid>* {
      height: 100%
    }

    .card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: var(--rad);
      box-shadow: var(--shadow);
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }

    .card .hd {
      padding: 14px 16px;
      font-weight: 800;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      gap: 12px
    }

    .card .bd {
      padding: 16px
    }

    .field {
      position: relative;
      margin-bottom: 12px
    }

    .field .icon {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: #9aa3b2
    }

    .input {
      width: 100%;
      padding: 12px 14px 12px 40px;
      border: 2px solid var(--border);
      border-radius: 12px;
      background: #fff;
      font-size: 1rem;
      outline: none;
    }

    .input:focus {
      border-color: #bad0ff;
      box-shadow: 0 0 0 3px rgba(37, 99, 235, .15)
    }

    .toggle-pass {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: #9aa3b2;
      cursor: pointer
    }

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 12px 14px;
      border-radius: 12px;
      border: 0;
      cursor: pointer;
      background: var(--brand);
      color: #fff;
      font-weight: 800;
      box-shadow: 0 8px 18px rgba(37, 99, 235, .15);
      width: 100%;
      justify-content: center;
    }

    .btn:hover {
      background: var(--brand-600)
    }

    .err {
      color: var(--danger);
      font-weight: 800;
      margin: -4px 0 8px
    }

    .small {
      font-size: .875rem
    }

    .tiny {
      font-size: .82rem;
      color: #64748b
    }

    .alert {
      background: #fff8e1;
      border: 1px solid #fde68a;
      color: #92400e;
      padding: 10px 12px;
      border-radius: 12px;
      font-weight: 800;
      margin: 0 0 10px;
    }

    .info {
      background: linear-gradient(130deg, #1d4ed8, #2563eb);
      color: #fff;
      border: 0
    }

    .info .hd {
      border: 0;
      color: #fff
    }

    .info .bd {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      gap: 12px
    }

    .tip {
      background: rgba(255, 255, 255, .18);
      border: 1px solid rgba(255, 255, 255, .35);
      border-radius: 12px;
      padding: 12px 14px;
      color: #eef2ff;
      margin-top: 8px;
      font-weight: 600;
    }
  </style>
</head>

<body>
  <div class="nav">
    <div class="brand-wrap">
      <img src="<?= htmlspecialchars($LOGO, ENT_QUOTES) ?>" alt="Logo" onerror="this.style.display='none'">
      <strong>Sistema de Votação</strong>
    </div>
  </div>

  <div class="wrap">
    <div class="grid">
      <div class="card">
        <div class="hd">Entrar</div>
        <div class="bd">
          <?php if ($timeoutMsg): ?>
            <div class="alert"><i class="fa-solid fa-clock-rotate-left"></i> <?= h($timeoutMsg) ?></div>
          <?php endif; ?>

          <p class="tiny">Acesse o painel do <strong>Sistema de Votação</strong>.</p>

          <?php if ($error): ?><p class="err"><?= h($error) ?></p><?php endif; ?>

          <form method="post" autocomplete="off">
            <label class="small">E-mail</label>
            <div class="field">
              <i class="fa-regular fa-envelope icon"></i>
              <input class="input" type="email" name="email" required value="<?= h($_POST['email'] ?? '') ?>">
            </div>

            <label class="small">Senha</label>
            <div class="field">
              <i class="fa-solid fa-lock icon"></i>
              <input class="input" id="senha" type="password" name="senha" required>
              <i class="fa-regular fa-eye toggle-pass" id="togglePass" title="Mostrar/ocultar"></i>
            </div>

            <button class="btn" type="submit"><i class="fa-solid fa-right-to-bracket"></i> Entrar</button>

            <div class="tiny" style="margin-top:10px">
              Operador: <em>admin@camara.gov.br</em> / <em>123456</em> ·
              Vereador: <em>ana.costa@camara.gov.br</em> / <em>123</em>
            </div>

            <div class="tiny" style="margin-top:8px">
              Suporte: <a href="https://wa.me/5582987373538" target="_blank" style="font-weight:900;color:#16a34a;text-decoration:none">WhatsApp (82) 98737-3538</a>
            </div>
          </form>
        </div>
      </div>

      <div class="card info">
        <div class="hd"><i class="fa-solid fa-building-columns"></i>&nbsp;Câmara Municipal</div>
        <div class="bd">
          <div>
            <p>Gestão de <strong>sessões</strong>, <strong>matérias</strong> e <strong>votação</strong> em tempo real,
              com painel público e controle de quórum.</p>

            <div class="tip">
              <i class="fa-solid fa-circle-info"></i>&nbsp;
              Se você não conseguir entrar, confirme com o administrador se seu usuário
              está <em>ativo</em> e a senha foi definida.
            </div>
          </div>
          <div class="tiny" style="opacity:.9">
            © <?= date('Y') ?> Câmara Municipal — Sistema de Votação
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    const pass = document.getElementById('senha');
    const toggle = document.getElementById('togglePass');
    if (toggle) {
      toggle.addEventListener('click', () => {
        const isPwd = pass.type === 'password';
        pass.type = isPwd ? 'text' : 'password';
        toggle.classList.toggle('fa-eye');
        toggle.classList.toggle('fa-eye-slash');
      });
      toggle.classList.add('fa-eye');
    }
  </script>
</body>

</html>