<?php
// modules/auditor/dashboard.php
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'auth.php';
requireRol(ROL_AUDITOR);

$user      = currentUser();
$db        = getDB();
$pageTitle = 'Auditoría CACES';

$totalLogs = (int)$db->query("SELECT COUNT(*) FROM audit_log")->fetchColumn();

// ── Parámetros de filtro (GET) ─────────────────────────────
$filtroAccion = trim($_GET['accion'] ?? '');
$filtroFecha  = trim($_GET['fecha']  ?? '');

// ── Query del audit_log con filtros ───────────────────────
$where  = [];
$params = [];

if ($filtroAccion !== '') {
    $where[]               = "al.accion LIKE :accion";
    $params[':accion']     = '%' . $filtroAccion . '%';
}
if ($filtroFecha !== '') {
    $where[]              = "DATE(al.created_at) = :fecha";
    $params[':fecha']     = $filtroFecha;
}

$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $db->prepare("
    SELECT al.created_at, al.accion, al.tabla_afectada,
           al.id_registro, al.ip_address,
           CONCAT(u.nombres, ' ', u.apellidos) AS usuario
    FROM   audit_log al
    LEFT   JOIN usuarios u ON u.id_usuario = al.id_usuario
    $whereSQL
    ORDER  BY al.created_at DESC
    LIMIT  100
");
$stmt->execute($params);
$logs = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head><?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-auditor.css">
</head>
<body>
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'navbar.php'; ?>
<div class="app-shell">
  <aside class="sidebar">
    <div class="sidebar-label">Auditor</div>
    <a href="dashboard.php" class="active"><span class="icon"><i class="fa fa-shield-halved"></i></span> Dashboard</a>

    <!-- ── Auditoría — Violeta ── -->
    <div class="sidebar-group g-auditoria">
      <span class="sg-label"><i class="fa fa-shield-halved me-1"></i>Auditoría</span>
      <a href="dashboard.php" class="active"><span class="icon"><i class="fa fa-list-check"></i></span> Audit Log</a>
    </div>

    <!-- ── Reportes — Amarillo ── -->
    <div class="sidebar-group g-reportes">
      <span class="sg-label"><i class="fa fa-chart-bar me-1"></i>Reportes</span>
      <a href="reportes.php"><span class="icon"><i class="fa fa-chart-bar"></i></span> Reportes</a>
    </div>

    <div class="sidebar-sep"></div>
    <a href="<?= BASE_URL ?>/auth/logout.php"><span class="icon"><i class="fa fa-right-from-bracket"></i></span> Salir</a>
  </aside>
  <main class="main-area">
    <div class="page-header"><h4>Auditoría CACES 🔍</h4><p>Registro de acciones del sistema — solo lectura</p></div>

    <div class="row g-3 mb-4">
      <div class="col-sm-4">
        <div class="stat-card"><div><div class="stat-num" style="color:#c792ea;"><?= number_format($totalLogs) ?></div><div class="stat-label">Registros en audit_log</div></div><div class="stat-icon">📑</div></div>
      </div>
      <div class="col-sm-4">
        <div class="stat-card"><div><div class="stat-num" style="color:#f7b93e;"><?= count($logs) ?></div><div class="stat-label">Mostrando ahora</div></div><div class="stat-icon">🔎</div></div>
      </div>
    </div>

    <!-- Filtros como form GET -->
    <form method="GET" class="d-flex gap-2 mb-3 flex-wrap">
      <input type="text" name="accion" class="form-control" style="max-width:220px;"
             placeholder="Filtrar por acción..." value="<?= htmlspecialchars($filtroAccion) ?>"/>
      <input type="date" name="fecha" class="form-control" style="max-width:180px;"
             value="<?= htmlspecialchars($filtroFecha) ?>"/>
      <button type="submit" class="btn btn-primary"><i class="fa fa-search me-1"></i>Filtrar</button>
      <?php if ($filtroAccion || $filtroFecha): ?>
        <a href="dashboard.php" class="btn btn-outline-secondary"><i class="fa fa-xmark me-1"></i>Limpiar</a>
      <?php endif; ?>
    </form>

    <div class="tbl-wrap">
      <table class="table table-borderless mb-0">
        <thead>
          <tr>
            <th>Fecha</th>
            <th>Usuario</th>
            <th>Acción</th>
            <th>Tabla</th>
            <th>IP</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($logs)): ?>
          <tr><td colspan="5" class="text-center text-muted py-4">Sin registros encontrados</td></tr>
          <?php else: foreach ($logs as $log): ?>
          <tr>
            <td style="font-family:'JetBrains Mono',monospace;font-size:11px;white-space:nowrap;">
              <?= htmlspecialchars($log['created_at']) ?>
            </td>
            <td style="font-size:13px;"><?= htmlspecialchars($log['usuario'] ?? '—') ?></td>
            <td><code style="color:var(--yellow);font-size:12px;"><?= htmlspecialchars($log['accion']) ?></code></td>
            <td style="font-family:'JetBrains Mono',monospace;font-size:11px;color:#8b949e;">
              <?= htmlspecialchars($log['tabla_afectada'] ?? '—') ?>
            </td>
            <td style="font-family:'JetBrains Mono',monospace;font-size:11px;color:#8b949e;">
              <?= htmlspecialchars($log['ip_address'] ?? '—') ?>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </main>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>
