<?php
// /gabinete/src/views/documentos/index.php
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

/* === Debug temporário === */
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

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

// Protege rota
if (empty($_SESSION['user_id'])) {
  header('Location: ' . $BASE_PATH . '/login.php', true, 302);
  exit;
}

$dir = __DIR__; // /gabinete/src/views/documentos
$nome = $_SESSION['nome'] ?? 'Usuário';

/* Rotas conhecidas (ajuste os nomes conforme seus arquivos reais) */
$routes = array(
  'lista' => $dir . '/lista.php',
  'upload' => $dir . '/upload.php',
  'create' => $dir . '/create.php',
  'novo' => $dir . '/create.php',
  'detalhes' => $dir . '/detalhes.php',
  'editar' => $dir . '/editar.php',
  'form' => $dir . '/form.php',
  'visualizar' => $dir . '/visualizar.php',
  'categorias' => $dir . '/categorias.php',
  'midia' => $dir . '/midia.php',
);

/* Param p */
$p = isset($_GET['p']) ? strtolower(preg_replace('/[^a-z0-9_]/i', '', $_GET['p'])) : '';

/* Mapa público (URL) somente do que existe fisicamente */
$existing = array();
foreach ($routes as $key => $abs) {
  if (file_exists($abs)) {
    $existing[$key] = $BASE_PATH . '/src/views/documentos/' . basename($abs);
  }
}

/* 1) Se veio p válido -> redireciona */
if ($p !== '' && isset($existing[$p])) {
  header('Location: ' . $existing[$p], true, 302);
  exit;
}

/* 2) Sem p: se existir lista.php, manda pra lá */
if ($p === '' && isset($existing['lista'])) {
  header('Location: ' . $existing['lista'], true, 302);
  exit;
}

/* 3) Senão: mostra hub com links do que existe (evita tela branca) */
?>
<!doctype html>
<html lang="pt-br">

<head>
  <meta charset="utf-8">
  <title>Documentos</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"
    }

    header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 14px 18px;
      background: linear-gradient(180deg, var(--navy), var(--navy-2));
      color: #fff
    }

    .btn {
      display: inline-block;
      padding: 10px 14px;
      border-radius: 12px;
      background: #fff;
      color: #0f172a;
      font-weight: 700;
      text-decoration: none;
      border: 1px solid rgba(0, 0, 0, .06)
    }

    .wrap {
      max-width: 1180px;
      margin: 0 auto;
      padding: 18px
    }

    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 14px
    }

    .card {
      background: #fff;
      border: 1px solid #eaeef3;
      border-radius: 14px;
      padding: 16px;
      text-decoration: none;
      color: inherit
    }

    .empty {
      padding: 16px;
      border: 1px dashed #cbd5e1;
      border-radius: 12px;
      background: #fff
    }

    footer {
      margin-top: 24px;
      padding: 16px;
      background: #fff;
      border-top: 1px solid #eaeef3;
      color: #0f172a;
      display: flex;
      justify-content: space-between
    }

    .muted {
      color: #64748b
    }
  </style>
</head>

<body>
  <header>
    <div><strong>Documentos & Multimídia</strong></div>
    <div>Olá, <?php echo htmlspecialchars($nome); ?> •
      <a class="btn" href="<?php echo htmlspecialchars($BASE_PATH . '/src/views/dashboard/index.php'); ?>">Voltar ao
        painel</a>
    </div>
  </header>

  <main class="wrap">
    <?php if (!empty($existing)): ?>
      <p class="muted" style="margin:0 0 12px">Escolha uma das páginas detectadas:</p>
      <div class="grid">
        <?php
        $labels = array(
          'lista' => 'Listar documentos',
          'upload' => 'Enviar arquivo',
          'create' => 'Novo documento',
          'novo' => 'Novo documento',
          'detalhes' => 'Detalhes',
          'editar' => 'Editar',
          'form' => 'Formulário',
          'visualizar' => 'Visualizar',
          'categorias' => 'Categorias',
          'midia' => 'Mídia'
        );
        $order = array('lista', 'upload', 'create', 'novo', 'detalhes', 'editar', 'form', 'visualizar', 'categorias', 'midia');
        foreach ($order as $k) {
          if (!isset($existing[$k]))
            continue;
          $href = $existing[$k];
          $label = isset($labels[$k]) ? $labels[$k] : ucfirst($k);
          echo '<a class="card" href="' . htmlspecialchars($href) . '">
                  <div style="font-size:12px;color:#64748b">Atalho</div>
                  <h3 style="margin:6px 0 8px 0;font-size:16px">' . htmlspecialchars($label) . '</h3>
                  <div class="muted" style="font-size:12px">Abrir: ' . htmlspecialchars(basename($href)) . '</div>
                </a>';
        }
        ?>
      </div>
    <?php else: ?>
      <div class="empty">
        <strong>Nenhuma subpágina detectada nesta pasta.</strong><br>
        Crie ao menos um destes arquivos em <code>/src/views/documentos/</code> e recarregue:
        <ul style="margin:8px 0 0 18px">
          <li><code>lista.php</code> (recomendado)</li>
          <li><code>upload.php</code>, <code>create.php</code>, <code>detalhes.php</code>, <code>editar.php</code>…</li>
        </ul>
      </div>
    <?php endif; ?>
  </main>

  <footer>
    <div>© 2025 Gabinete • Sistema interno</div>
    <div>by Universo Base 🚀</div>
  </footer>
</body>

</html>