<?php
// /gabinete/src/views/dashboard/index.php — COMPLETO e autônomo
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

// Carrega configurações para pegar BASE_URL correta
require_once __DIR__ . '/../../../src/config/config.php';
$BASE_PATH = rtrim(BASE_URL, '/');

/** Proteção: exige login */
if (empty($_SESSION['user_id'])) {
  header('Location: ' . $BASE_PATH . '/login.php', true, 302);
  exit;
}

/** Helpers */
function lower_compat($s)
{
  return function_exists('mb_strtolower') ? mb_strtolower($s, 'UTF-8') : strtolower($s);
}

/** Converte nivel_acesso (ex.: Acesso_Total, Eleitor_Documentos, etc.) em lista de módulos */
function nivelParaModulos($nivel)
{
  $nivel = trim((string) $nivel);
  if ($nivel === '')
    return array();

  // 1. Casos Especiais (Admin ou AcessoTotal)
  // Verifica se contém 'Admin' ou 'AcessoTotal' (case-insensitive)
  if (stripos($nivel, 'Admin') !== false || stripos($nivel, 'AcessoTotal') !== false || stripos($nivel, 'Acesso_Total') !== false) {
    return array('agendas', 'documentos', 'eleitores', 'contas', 'rh', 'admin', 'configuracoes');
  }

  // 2. Mapeamento dos ENUMs do Banco (CamelCase)
  if (stripos($nivel, 'AgendaFinanceiroDocumentos') !== false) {
    return array('agendas', 'contas', 'documentos');
  }
  if (stripos($nivel, 'EleitorDocumentos') !== false) {
    return array('eleitores', 'documentos');
  }
  if (stripos($nivel, 'DocumentosFinanceiroRH') !== false) {
    return array('documentos', 'contas', 'rh');
  }

  // 3. Fallback: Tenta quebrar por tokens (para compatibilidade antiga)
  $tokens = preg_split('/[_\s,+]+/u', $nivel, -1, PREG_SPLIT_NO_EMPTY);
  $map = array(
    'agenda' => 'agendas',
    'agendas' => 'agendas',
    'documento' => 'documentos',
    'documentos' => 'documentos',
    'eleitor' => 'eleitores',
    'eleitores' => 'eleitores',
    'financeiro' => 'contas',
    'contas' => 'contas',
    'rh' => 'rh',
    'admin' => 'admin',
    'administrador' => 'admin',
    'config' => 'configuracoes',
    'configuracoes' => 'configuracoes'
  );

  $mods = array();
  foreach ($tokens as $t) {
    $t = trim(lower_compat($t));
    if ($t !== '' && isset($map[$t])) {
      $mods[$map[$t]] = true;
    }
  }
  return array_keys($mods);
}

/** Dados do usuário */
$nome = isset($_SESSION['nome']) ? $_SESSION['nome'] : 'Usuário';
$nivel = isset($_SESSION['nivel_acesso']) ? $_SESSION['nivel_acesso'] : '';

// Buscar foto do usuário
$foto = null;
if (isset($_SESSION['user_id'])) {
  try {
    // Usa a conexão global $pdo definida em src/config/db.php
    // O arquivo db.php já foi incluído indiretamente?
    // O index.php do dashboard inclui config.php, mas não db.php explicitamente.
    // Vamos incluir db.php para garantir acesso ao $pdo.
    require_once __DIR__ . '/../../../src/config/db.php';

    if (isset($pdo)) {
      $stmt = $pdo->prepare("SELECT foto FROM usuarios WHERE id = ?");
      $stmt->execute([$_SESSION['user_id']]);
      $user = $stmt->fetch(PDO::FETCH_ASSOC);

      if ($user && !empty($user['foto'])) {
        $foto = $user['foto'];
      }
    }
  } catch (PDOException $e) {
    // Em caso de erro, continua sem foto
    $foto = null;
    // Opcional: logar erro
    // error_log("Erro ao buscar foto: " . $e->getMessage());
  }
}

/**
 * Mapa de módulos → destino
 * OBS: Contas agora fica em /gabinete/contas/index.php (fora de src/views)
 */
$MODULES = array(
  'agendas' => array('label' => 'Agenda', 'url' => $BASE_PATH . '/src/views/agendas/index.php'),
  'documentos' => array('label' => 'Documentos', 'url' => $BASE_PATH . '/src/views/documentos'),
  'eleitores' => array('label' => 'Eleitores', 'url' => $BASE_PATH . '/src/views/eleitores'),
  'contas' => array('label' => 'Financeiro (Contas)', 'url' => $BASE_PATH . '/contas/index.php'), // << AQUI!
  'rh' => array('label' => 'RH', 'url' => $BASE_PATH . '/src/views/rh/index.php'),
  // 'admin' => array('label' => 'Admin', 'url' => $BASE_PATH . '/src/views/admin/dashboard.php'),
  // 'configuracoes' => array('label' => 'Configurações', 'url' => $BASE_PATH . '/src/views/configuracoes/index.php')
);

$modsVisiveis = nivelParaModulos($nivel);

$logoutUrl = $BASE_PATH . '/logout.php';
$logoSrc = $BASE_PATH . '/public/images/logo.png';

/** Ícones (SVG inline) */
function icon_svg($key)
{
  $icons = array(
    'agendas' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="M7 2a1 1 0 0 0-1 1v1H5a3 3 0 0 0-3 3v11a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3h-1V3a1 1 0 1 0-2 0v1H8V3a1 1 0 0 0-1-1ZM4 9h16v9a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9Zm3 3h4v2H7v-2Z"/></svg>',
    'documentos' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="M6 2a2 2 0 0 0-2 2v16c0 1.103.897 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6Zm8 2.5L18.5 9H14V4.5ZM8 12h8v2H8v-2Zm0 4h8v2H8v-2Z"/></svg>',
    'eleitores' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4Zm0 2c-4.418 0-8 2.239-8 5v1h16v-1c0-2.761-3.582-5-8-5Z"/></svg>',
    'contas' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="M3 5h18v2H3V5Zm0 6h18v8H3v-8Zm2 2v4h14v-4H5Z"/></svg>',
    'rh' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="M12 12a5 5 0 1 0-5-5 5 5 0 0 0 5 5Zm-8 9v-1c0-3.314 3.582-6 8-6s8 2.686 8 6v1H4Z"/></svg>',
    'admin' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="m12 2 3 7 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1 3-7Z"/></svg>',
    'configuracoes' => '<svg viewBox="0 0 24 24" width="24" height="24"><path fill="#fff" d="m12 8 1.414 1.414L16 9.414l-.586 2.172L17 13l-1.586 1.414L16 16.586l-2.172-.586L12 17l-1.414-1.414L8.414 16l.586-2.172L7 13l1.586-1.414L8.414 9.414l2.172.586L12 8Z"/></svg>'
  );
  return isset($icons[$key]) ? $icons[$key] : $icons['configuracoes'];
}

/** Cores sólidas por módulo */
function card_bg($key)
{
  $map = array(
    'agendas' => '#1e3a8a', // navy
    'documentos' => '#0f766e', // teal
    'eleitores' => '#7c3aed', // violet
    'contas' => '#b45309', // amber-700
    'rh' => '#9d174d', // rose-800
    'admin' => '#374151', // gray-700
    'configuracoes' => '#065f46'  // emerald-800
  );
  return isset($map[$key]) ? $map[$key] : '#065f46';
}
?>
<!doctype html>
<html lang="pt-br">

<head>
  <meta charset="utf-8">
  <title>Início</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    :root {
      --navy: #0B1F3A;
      --navy-2: #102B54;
      --ink: #0f172a;
      --muted: #64748b;
      --bg: #f6f7fb;
    }

    * {
      box-sizing: border-box
    }

    body {
      margin: 0;
      background: var(--bg);
      color: var(--ink);
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, "Noto Sans";
    }

    a {
      color: inherit
    }

    /* HEADER */
    .site-header {
      position: sticky;
      top: 0;
      z-index: 50;
      display: flex;
      align-items: center;
      gap: 16px;
      justify-content: space-between;
      padding: 14px 18px;
      background: linear-gradient(180deg, var(--navy), var(--navy-2));
      color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, .15)
    }

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

    .logo-box {
      width: 250px;
      height: 50px;
      border-radius: 10px;
      background: rgba(255, 255, 255, .15);
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden
    }

    .logo-box img {
      max-height: 46px;
      object-fit: contain
    }

    .h-title {
      font-weight: 700;
      letter-spacing: .3px
    }

    .h-actions {
      display: flex;
      align-items: center;
      gap: 10px
    }

    .icon-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      border-radius: 10px;
      background: rgba(255, 255, 255, .14);
      border: 1px solid rgba(255, 255, 255, .2)
    }

    .btn-logout {
      text-decoration: none;
      padding: 10px 14px;
      border-radius: 12px;
      background: #ffffff;
      border: 0;
      color: #0f172a;
      font-weight: 700;
      box-shadow: 0 1px 1px rgba(0, 0, 0, .05)
    }

    /* PAGE */
    .page-wrap {
      padding: 22px;
      max-width: 1180px;
      margin: 0 auto;
    }

    .hello {
      font-size: 18px;
      font-weight: 700;
      margin-top: 8px;
    }

    .sub {
      color: var(--muted);
      margin-bottom: 18px;
    }

    /* CARDS */
    .cards {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 18px;
    }

    .card {
      display: block;
      padding: 18px;
      border-radius: 16px;
      color: #fff;
      text-decoration: none;
      background: var(--card-bg);
      box-shadow: 0 8px 20px rgba(0, 0, 0, .10);
      border: 1px solid rgba(255, 255, 255, .18);
      transition: transform .12s ease, box-shadow .12s ease, filter .12s ease, opacity .12s ease;
      position: relative;
      overflow: hidden;
    }

    .card:hover {
      transform: translateY(-3px);
      filter: saturate(1.02);
      box-shadow: 0 12px 24px rgba(0, 0, 0, .16);
    }

    .card .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      margin-bottom: 12px;
    }

    .card .icon {
      width: 42px;
      height: 42px;
      border-radius: 12px;
      background: rgba(255, 255, 255, .18);
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .card .title {
      font-weight: 800;
      letter-spacing: .2px;
    }

    .card .desc {
      font-size: 12px;
      opacity: .95;
    }

    /* FOOTER */
    .site-footer {
      margin-top: 30px;
      padding: 18px;
      background: #ffffff;
      color: #0f172a;
      border-top: 1px solid #eaeef3;
    }

    .foot-inner {
      max-width: 1180px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
    }
  </style>
</head>

<body>

  <!-- HEADER -->
  <header class="site-header">
    <div class="h-left">

      <div class="logo-box">
        <?php if (!empty($logoSrc)): ?>
          <img src="<?php echo htmlspecialchars($logoSrc); ?>" alt="Logo">
        <?php else: ?>
          <span style="font-weight:800;color:#fff;opacity:.9">GABINETE</span>
        <?php endif; ?>
      </div>
      <div class="h-title">Painel</div>
    </div>

    <div class="h-actions">
      <div class="icon-btn" aria-hidden="true">
        <svg viewBox="0 0 24 24" width="20" height="20" fill="#fff" opacity=".9">
          <path d="M12 22a2.5 2.5 0 0 0 2.45-2h-4.9A2.5 2.5 0 0 0 12 22Zm6-6V11a6 6 0 0 0-12 0v5l-2 2v1h16v-1l-2-2Z" />
        </svg>
      </div>
      <div class="icon-btn" style="width:auto;padding:0 12px;gap:8px;color:#fff;font-weight:700">
        <?php if (!empty($foto) && file_exists($_SERVER['DOCUMENT_ROOT'] . $BASE_PATH . '/' . $foto)): ?>
          <img src="<?php echo htmlspecialchars($BASE_PATH . '/' . $foto); ?>" alt="Foto do usuário"
            style="width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,0.3);">
        <?php else: ?>
          <svg viewBox="0 0 24 24" width="20" height="20" fill="#fff" opacity=".9">
            <path d="M12 12a5 5 0 1 0-5-5 5 5 0 0 0 5 5Zm-8 9v-1c0-3.314 3.582-6 8-6s8 2.686 8 6v1H4Z" />
          </svg>
        <?php endif; ?>
        <span><?php echo htmlspecialchars($nome); ?></span>
      </div>
      <a class="btn-logout" href="<?php echo htmlspecialchars($logoutUrl); ?>">Sair</a>
    </div>
  </header>

  <!-- MAIN -->
  <main class="page-wrap">
    <div class="hello">Bem-vindo, <?php echo htmlspecialchars($nome); ?>!</div>
    <div class="sub">Nível de acesso: <strong><?php echo htmlspecialchars($nivel); ?></strong></div>

    <?php if (empty($modsVisiveis)): ?>
      <div style="padding:16px;border:1px solid #e5e9f2;border-radius:12px;background:#fff;">
        Nenhum módulo disponível para o seu nível de acesso.
      </div>
    <?php else: ?>
      <div class="cards">
        <?php foreach ($modsVisiveis as $m):
          if (!isset($MODULES[$m])) {
            continue;
          }
          $label = $MODULES[$m]['label'];
          $url = $MODULES[$m]['url'];
          $icon = icon_svg($m);
          $bg = card_bg($m);
          ?>
          <a class="card" href="<?php echo htmlspecialchars($url); ?>" style="--card-bg: <?php echo $bg; ?>;">
            <div class="top">
              <div class="icon"><?php echo $icon; ?></div>
              <div
                style="font-size:11px;background:rgba(255,255,255,.22);padding:6px 8px;border-radius:999px;border:1px solid rgba(255,255,255,.35)">
                Acesso</div>
            </div>
            <div class="title"><?php echo htmlspecialchars($label); ?></div>
            <div class="desc">Acessar <?php echo htmlspecialchars($label); ?></div>
          </a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </main>

  <!-- FOOTER -->
  <footer class="site-footer">
    <div class="foot-inner">
      <div>© 2025 Gabinete • Sistema interno</div>
      <div>by Universo Base 🚀</div>
    </div>
  </footer>

</body>

</html>