<?php
// ============================================================
// configuracoes_logs.php
// Tela de Logs de Auditoria — Apenas Administrador
// Menu: Configurações → Logs de Auditoria
// ============================================================

require_once __DIR__ . '/5_config/config.php';

$usuario = verificarAuth();
$db = getDB();

// Verificar se é admin
if ($usuario['perfil'] !== 'admin') {
    http_response_code(403);
    die(json_encode(['erro' => 'Acesso negado. Apenas administradores podem acessar logs.']));
}

// Inicializar auditoria
Auditoria::inicializar($db, $usuario['id'], $usuario['nome'], $usuario['perfil']);

// Filtros
$filtro_usuario = $_GET['filtro_usuario'] ?? '';
$filtro_data_inicio = $_GET['filtro_data_inicio'] ?? '';
$filtro_data_fim = $_GET['filtro_data_fim'] ?? '';
$filtro_operacao = $_GET['filtro_operacao'] ?? '';
$filtro_tabela = $_GET['filtro_tabela'] ?? '';
$pagina = (int)($_GET['pagina'] ?? 1);
$por_pagina = 50;

// Construir query com filtros
$sql = "SELECT * FROM auditoria WHERE 1=1";
$params = [];

if ($filtro_usuario) {
    $sql .= " AND usuario_nome LIKE ?";
    $params[] = "%$filtro_usuario%";
}

if ($filtro_data_inicio) {
    $sql .= " AND DATE(criado_em) >= ?";
    $params[] = $filtro_data_inicio;
}

if ($filtro_data_fim) {
    $sql .= " AND DATE(criado_em) <= ?";
    $params[] = $filtro_data_fim;
}

if ($filtro_operacao) {
    $sql .= " AND operacao = ?";
    $params[] = $filtro_operacao;
}

if ($filtro_tabela) {
    $sql .= " AND tabela = ?";
    $params[] = $filtro_tabela;
}

// Contar total
$stmt_count = $db->prepare(str_replace('SELECT *', 'SELECT COUNT(*) as total', $sql));
$stmt_count->execute($params);
$total = $stmt_count->fetch()['total'];
$total_paginas = ceil($total / $por_pagina);

// Paginar
$offset = ($pagina - 1) * $por_pagina;
$sql .= " ORDER BY criado_em DESC LIMIT ? OFFSET ?";
$params[] = $por_pagina;
$params[] = $offset;

$stmt = $db->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll();

// Obter lista de usuários para filtro
$stmt_usuarios = $db->query("SELECT DISTINCT usuario_nome FROM auditoria ORDER BY usuario_nome");
$usuarios_lista = $stmt_usuarios->fetchAll(PDO::FETCH_COLUMN);

// Obter lista de tabelas para filtro
$stmt_tabelas = $db->query("SELECT DISTINCT tabela FROM auditoria ORDER BY tabela");
$tabelas_lista = $stmt_tabelas->fetchAll(PDO::FETCH_COLUMN);

$pagina_titulo = 'Logs de Auditoria';
require_once __DIR__ . '/1_frontend/layout.php';
?>

<div class="space-y-6">

  <!-- Cabeçalho -->
  <div>
    <h1 class="text-2xl font-bold text-actsafe-text">🔍 Logs de Auditoria</h1>
    <p class="text-sm text-gray-500 mt-0.5">Rastreamento completo de operações no sistema — Total: <strong><?= number_format($total) ?></strong> registros</p>
  </div>

  <!-- Filtros -->
  <div class="card">
    <form method="GET" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        
        <!-- Filtro: Usuário -->
        <div>
          <label class="block text-sm font-medium text-actsafe-text mb-2">Usuário</label>
          <select name="filtro_usuario" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue">
            <option value="">Todos</option>
            <?php foreach ($usuarios_lista as $u): ?>
              <option value="<?= sanitizar($u) ?>" <?= $filtro_usuario === $u ? 'selected' : '' ?>>
                <?= sanitizar($u) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Filtro: Data Início -->
        <div>
          <label class="block text-sm font-medium text-actsafe-text mb-2">Data Início</label>
          <input type="date" name="filtro_data_inicio" value="<?= sanitizar($filtro_data_inicio) ?>" 
                 class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue">
        </div>

        <!-- Filtro: Data Fim -->
        <div>
          <label class="block text-sm font-medium text-actsafe-text mb-2">Data Fim</label>
          <input type="date" name="filtro_data_fim" value="<?= sanitizar($filtro_data_fim) ?>" 
                 class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue">
        </div>

        <!-- Filtro: Operação -->
        <div>
          <label class="block text-sm font-medium text-actsafe-text mb-2">Operação</label>
          <select name="filtro_operacao" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue">
            <option value="">Todas</option>
            <option value="INSERT" <?= $filtro_operacao === 'INSERT' ? 'selected' : '' ?>>INSERT (Criar)</option>
            <option value="UPDATE" <?= $filtro_operacao === 'UPDATE' ? 'selected' : '' ?>>UPDATE (Atualizar)</option>
            <option value="DELETE" <?= $filtro_operacao === 'DELETE' ? 'selected' : '' ?>>DELETE (Deletar)</option>
          </select>
        </div>

        <!-- Filtro: Tabela -->
        <div>
          <label class="block text-sm font-medium text-actsafe-text mb-2">Tabela</label>
          <select name="filtro_tabela" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue">
            <option value="">Todas</option>
            <?php foreach ($tabelas_lista as $t): ?>
              <option value="<?= sanitizar($t) ?>" <?= $filtro_tabela === $t ? 'selected' : '' ?>>
                <?= sanitizar($t) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

      </div>

      <div class="flex gap-2">
        <button type="submit" class="btn-primary">
          <i data-lucide="search" class="w-4 h-4"></i> Filtrar
        </button>
        <a href="?pagina=1" class="btn-outline">
          <i data-lucide="x" class="w-4 h-4"></i> Limpar
        </a>
      </div>
    </form>
  </div>

  <!-- Tabela de Logs -->
  <div class="card overflow-x-auto">
    <?php if (empty($logs)): ?>
      <div class="text-center py-12">
        <i data-lucide="inbox" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
        <p class="text-gray-500">Nenhum registro encontrado com os filtros aplicados.</p>
      </div>
    <?php else: ?>
      <table class="w-full text-sm">
        <thead>
          <tr class="border-b-2 border-gray-200">
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">Operação</th>
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">Usuário</th>
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">Tabela</th>
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">Descrição</th>
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">Hora</th>
            <th class="text-left py-3 px-4 font-semibold text-actsafe-text">IP</th>
            <th class="text-center py-3 px-4 font-semibold text-actsafe-text">Ação</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($logs as $log): 
            $badge_op = $log['operacao'] === 'INSERT' ? 'bg-green-100 text-green-700' : 
                        ($log['operacao'] === 'UPDATE' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700');
            $icon_op = $log['operacao'] === 'INSERT' ? '➕' : 
                       ($log['operacao'] === 'UPDATE' ? '🔄' : '🗑️');
          ?>
          <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
            <td class="py-3 px-4">
              <span class="inline-block px-2 py-1 rounded text-xs font-semibold <?= $badge_op ?>">
                <?= $icon_op ?> <?= $log['operacao'] ?>
              </span>
            </td>
            <td class="py-3 px-4">
              <div class="font-medium text-actsafe-text"><?= sanitizar($log['usuario_nome']) ?></div>
              <div class="text-xs text-gray-500"><?= sanitizar($log['usuario_perfil']) ?></div>
            </td>
            <td class="py-3 px-4">
              <code class="bg-gray-100 px-2 py-1 rounded text-xs"><?= sanitizar($log['tabela']) ?></code>
            </td>
            <td class="py-3 px-4">
              <div class="text-gray-700"><?= sanitizar($log['descricao']) ?></div>
              <?php if ($log['dados_depois']): ?>
                <div class="text-xs text-gray-500 mt-1">
                  📋 Dados: <?= substr(sanitizar($log['dados_depois']), 0, 50) ?>...
                </div>
              <?php endif; ?>
            </td>
            <td class="py-3 px-4 text-gray-600 text-xs whitespace-nowrap">
              <?= date('d/m/Y H:i:s', strtotime($log['criado_em'])) ?>
            </td>
            <td class="py-3 px-4 text-gray-600 text-xs">
              <?= sanitizar($log['ip_address']) ?>
            </td>
            <td class="py-3 px-4 text-center">
              <button type="button" onclick="verDetalhes(<?= $log['id'] ?>, <?= htmlspecialchars(json_encode($log), ENT_QUOTES, 'UTF-8') ?>)" 
                      class="text-actsafe-blue hover:text-actsafe-blue-dark text-sm font-medium">
                Ver detalhes
              </button>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>

      <!-- Paginação -->
      <?php if ($total_paginas > 1): ?>
      <div class="flex items-center justify-between mt-6 pt-4 border-t border-gray-200">
        <div class="text-sm text-gray-600">
          Mostrando <strong><?= ($offset + 1) ?></strong> a <strong><?= min($offset + $por_pagina, $total) ?></strong> de <strong><?= number_format($total) ?></strong> registros
        </div>
        <div class="flex gap-2">
          <?php if ($pagina > 1): ?>
            <a href="?pagina=1&filtro_usuario=<?= urlencode($filtro_usuario) ?>&filtro_data_inicio=<?= urlencode($filtro_data_inicio) ?>&filtro_data_fim=<?= urlencode($filtro_data_fim) ?>&filtro_operacao=<?= urlencode($filtro_operacao) ?>&filtro_tabela=<?= urlencode($filtro_tabela) ?>" 
               class="btn-outline text-sm">Primeira</a>
            <a href="?pagina=<?= $pagina - 1 ?>&filtro_usuario=<?= urlencode($filtro_usuario) ?>&filtro_data_inicio=<?= urlencode($filtro_data_inicio) ?>&filtro_data_fim=<?= urlencode($filtro_data_fim) ?>&filtro_operacao=<?= urlencode($filtro_operacao) ?>&filtro_tabela=<?= urlencode($filtro_tabela) ?>" 
               class="btn-outline text-sm">← Anterior</a>
          <?php endif; ?>
          
          <span class="px-3 py-2 text-sm font-medium text-actsafe-text">
            Página <?= $pagina ?> de <?= $total_paginas ?>
          </span>

          <?php if ($pagina < $total_paginas): ?>
            <a href="?pagina=<?= $pagina + 1 ?>&filtro_usuario=<?= urlencode($filtro_usuario) ?>&filtro_data_inicio=<?= urlencode($filtro_data_inicio) ?>&filtro_data_fim=<?= urlencode($filtro_data_fim) ?>&filtro_operacao=<?= urlencode($filtro_operacao) ?>&filtro_tabela=<?= urlencode($filtro_tabela) ?>" 
               class="btn-outline text-sm">Próxima →</a>
            <a href="?pagina=<?= $total_paginas ?>&filtro_usuario=<?= urlencode($filtro_usuario) ?>&filtro_data_inicio=<?= urlencode($filtro_data_inicio) ?>&filtro_data_fim=<?= urlencode($filtro_data_fim) ?>&filtro_operacao=<?= urlencode($filtro_operacao) ?>&filtro_tabela=<?= urlencode($filtro_tabela) ?>" 
               class="btn-outline text-sm">Última</a>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>
    <?php endif; ?>
  </div>

</div>

<!-- Modal de Detalhes -->
<div id="modalDetalhes" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
  <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full max-h-96 overflow-y-auto">
    <div class="sticky top-0 bg-gray-50 px-6 py-4 border-b border-gray-200 flex items-center justify-between">
      <h2 class="text-lg font-bold text-actsafe-text">Detalhes do Registro</h2>
      <button onclick="fecharModal()" class="text-gray-400 hover:text-gray-600">
        <i data-lucide="x" class="w-5 h-5"></i>
      </button>
    </div>
    <div id="conteudoModal" class="px-6 py-4 space-y-4">
      <!-- Preenchido via JavaScript -->
    </div>
  </div>
</div>

<script>
function verDetalhes(id, log) {
  const modal = document.getElementById('modalDetalhes');
  const conteudo = document.getElementById('conteudoModal');

  const dadosAntes = log.dados_antes ? JSON.parse(log.dados_antes) : null;
  const dadosDepois = log.dados_depois ? JSON.parse(log.dados_depois) : null;

  let html = `
    <div class="grid grid-cols-2 gap-4">
      <div>
        <p class="text-xs text-gray-500 uppercase font-semibold">Operação</p>
        <p class="text-lg font-bold text-actsafe-text">${log.operacao}</p>
      </div>
      <div>
        <p class="text-xs text-gray-500 uppercase font-semibold">Usuário</p>
        <p class="text-lg font-bold text-actsafe-text">${log.usuario_nome}</p>
      </div>
      <div>
        <p class="text-xs text-gray-500 uppercase font-semibold">Tabela</p>
        <p class="text-lg font-bold text-actsafe-text">${log.tabela}</p>
      </div>
      <div>
        <p class="text-xs text-gray-500 uppercase font-semibold">Registro ID</p>
        <p class="text-lg font-bold text-actsafe-text">${log.registro_id || '—'}</p>
      </div>
      <div class="col-span-2">
        <p class="text-xs text-gray-500 uppercase font-semibold">Descrição</p>
        <p class="text-gray-700">${log.descricao}</p>
      </div>
      <div class="col-span-2">
        <p class="text-xs text-gray-500 uppercase font-semibold">Data/Hora</p>
        <p class="text-gray-700">${new Date(log.criado_em).toLocaleString('pt-BR')}</p>
      </div>
      <div class="col-span-2">
        <p class="text-xs text-gray-500 uppercase font-semibold">IP Address</p>
        <p class="text-gray-700">${log.ip_address}</p>
      </div>
  `;

  if (dadosAntes) {
    html += `
      <div class="col-span-2">
        <p class="text-xs text-gray-500 uppercase font-semibold">Dados Antes</p>
        <pre class="bg-gray-100 p-3 rounded text-xs overflow-x-auto">${JSON.stringify(dadosAntes, null, 2)}</pre>
      </div>
    `;
  }

  if (dadosDepois) {
    html += `
      <div class="col-span-2">
        <p class="text-xs text-gray-500 uppercase font-semibold">Dados Depois</p>
        <pre class="bg-gray-100 p-3 rounded text-xs overflow-x-auto">${JSON.stringify(dadosDepois, null, 2)}</pre>
      </div>
    `;
  }

  html += `</div>`;

  conteudo.innerHTML = html;
  modal.classList.remove('hidden');
}

function fecharModal() {
  document.getElementById('modalDetalhes').classList.add('hidden');
}

document.getElementById('modalDetalhes').addEventListener('click', (e) => {
  if (e.target === document.getElementById('modalDetalhes')) {
    fecharModal();
  }
});
</script>

<?php require_once __DIR__ . '/1_frontend/layout_footer.php'; ?>
