<?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';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions.php';
requireRol(ROL_ADMIN);

$user      = currentUser();
$db        = getDB();
$pageTitle = 'Audit Log';

// ── Filtros ─────────────────────────────────────────────────
$q      = trim($_GET['q']      ?? '');
$tabla  = trim($_GET['tabla']  ?? '');
$fecha  = trim($_GET['fecha']  ?? '');
$idUser = (int)($_GET['usuario'] ?? 0);
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 50;
$offset = ($page - 1) * $limit;

// ── Construir WHERE ─────────────────────────────────────────
$where = ['1=1']; $params = [];
if ($q)      { $where[] = 'al.accion LIKE :q';       $params[':q']  = '%'.$q.'%'; }
if ($tabla)  { $where[] = 'al.tabla_afectada = :tbl'; $params[':tbl']= $tabla; }
if ($fecha)  { $where[] = 'DATE(al.created_at) = :f'; $params[':f'] = $fecha; }
if ($idUser) { $where[] = 'al.id_usuario = :uid';     $params[':uid']= $idUser; }
$wStr = implode(' AND ', $where);

// ── Total de registros ──────────────────────────────────────
$total = (int)$db->prepare("SELECT COUNT(*) FROM audit_log al WHERE $wStr")->execute($params) ?
         $db->prepare("SELECT COUNT(*) FROM audit_log al WHERE $wStr")->execute($params) ? 0 : 0 : 0;
$stCnt = $db->prepare("SELECT COUNT(*) FROM audit_log al WHERE $wStr");
$stCnt->execute($params);
$total = (int)$stCnt->fetchColumn();
$pages = max(1, ceil($total / $limit));

// ── Logs paginados ──────────────────────────────────────────
$stLog = $db->prepare("
    SELECT al.*,
           COALESCE(CONCAT(u.nombres,' ',u.apellidos), 'Sistema') AS usuario_nombre,
           r.nombre AS rol_nombre
    FROM   audit_log al
    LEFT JOIN usuarios u ON u.id_usuario    = al.id_usuario
    LEFT JOIN roles r    ON r.id_rol        = u.id_rol
    WHERE  $wStr
    ORDER  BY al.created_at DESC
    LIMIT  :lim OFFSET :off
");
$stLog->bindValue(':lim', $limit, PDO::PARAM_INT);
$stLog->bindValue(':off', $offset, PDO::PARAM_INT);
foreach ($params as $k => $v) $stLog->bindValue($k, $v);
$stLog->execute();
$logs = $stLog->fetchAll();

// ── Catálogos para filtros ──────────────────────────────────
$tablas   = $db->query("SELECT DISTINCT tabla_afectada FROM audit_log WHERE tabla_afectada IS NOT NULL ORDER BY tabla_afectada")->fetchAll(PDO::FETCH_COLUMN);
$usuarios = $db->query("SELECT u.id_usuario, CONCAT(u.nombres,' ',u.apellidos) AS nombre FROM usuarios u ORDER BY u.nombres")->fetchAll();

// ── KPIs del audit ──────────────────────────────────────────
$kpis = $db->query("
    SELECT
      COUNT(*)                                              AS total_eventos,
      COUNT(DISTINCT DATE(created_at))                     AS dias_con_actividad,
      COUNT(DISTINCT id_usuario)                           AS usuarios_activos,
      SUM(accion LIKE 'login%')                            AS logins,
      SUM(accion LIKE '%crear%' OR accion LIKE '%insert%') AS creaciones,
      SUM(accion LIKE '%editar%' OR accion LIKE '%update%')AS ediciones,
      SUM(accion LIKE '%eliminar%' OR accion LIKE '%delete%' OR accion LIKE '%anular%') AS eliminaciones
    FROM audit_log
")->fetch();

// ── Actividad por hora (últimas 24h) ────────────────────────
$porHora = $db->query("
    SELECT HOUR(created_at) AS hora, COUNT(*) AS total
    FROM audit_log
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    GROUP BY HOUR(created_at)
    ORDER BY hora
")->fetchAll();
$horaMap = array_column($porHora, 'total', 'hora');
$maxHora = $porHora ? max(array_column($porHora,'total')) : 1;

// ── Acciones más frecuentes ─────────────────────────────────
$topAcciones = $db->query("
    SELECT accion, COUNT(*) AS total
    FROM audit_log
    GROUP BY accion
    ORDER BY total DESC LIMIT 8
")->fetchAll();

// ── Colores por tipo de acción ──────────────────────────────
function colorAccion(string $a): string {
    if (str_contains($a,'login'))   return '#2ea8ff';
    if (str_contains($a,'crear') || str_contains($a,'insert')) return '#3dffa0';
    if (str_contains($a,'editar') || str_contains($a,'update')) return '#f7b93e';
    if (str_contains($a,'eliminar') || str_contains($a,'anular') || str_contains($a,'delete')) return '#ff9d93';
    if (str_contains($a,'logout'))  return '#8b949e';
    if (str_contains($a,'validar') || str_contains($a,'aprobar')) return '#3dffa0';
    return '#c792ea';
}
?>
<!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-admin.css">
</head>
<body>
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'navbar.php'; ?>

<div class="app-shell">
  <?php $sbActivo = 'audit'; include __DIR__ . '/../../includes/sidebar_admin.php'; ?>

  <main class="main-area">
    <div class="page-header d-flex justify-content-between align-items-start flex-wrap gap-2">
      <div>
        <h4><i class="fa fa-shield-halved me-2" style="color:#2ea8ff;"></i>Audit Log</h4>
        <p>Registro completo de acciones del sistema — requisito CACES para auditoría institucional</p>
      </div>
      <div style="display:flex;gap:8px;align-items:center;">
        <span style="font-size:10px;padding:3px 10px;border-radius:20px;font-weight:700;
                     background:#2ea8ff22;color:#2ea8ff;border:1px solid #2ea8ff44;">CACES</span>
        <span style="font-size:22px;font-weight:700;color:#2ea8ff;"><?= number_format($total) ?></span>
        <span style="font-size:12px;color:#8b949e;">eventos totales</span>
      </div>
    </div>

    <!-- ── KPI CARDS ── -->
    <div class="row g-3 mb-4">
      <?php
      $ks = [
        ['v'=>number_format($kpis['total_eventos']),  'l'=>'Total eventos',      'c'=>'#2ea8ff','i'=>'📋'],
        ['v'=>$kpis['usuarios_activos'],              'l'=>'Usuarios registrados','c'=>'#c792ea','i'=>'👥'],
        ['v'=>$kpis['logins'],                        'l'=>'Inicios de sesión',  'c'=>'#3dffa0','i'=>'🔑'],
        ['v'=>$kpis['creaciones'],                    'l'=>'Creaciones',         'c'=>'#3dffa0','i'=>'✅'],
        ['v'=>$kpis['ediciones'],                     'l'=>'Modificaciones',     'c'=>'#f7b93e','i'=>'✏️'],
        ['v'=>$kpis['eliminaciones'],                 'l'=>'Anulaciones',        'c'=>'#ff9d93','i'=>'🚫'],
        ['v'=>$kpis['dias_con_actividad'],            'l'=>'Días con actividad', 'c'=>'#2ea8ff','i'=>'📅'],
      ];
      foreach ($ks as $k): ?>
      <div class="col-6 col-lg-3">
        <div class="stat-card">
          <div><div class="stat-num" style="color:<?= $k['c'] ?>;font-size:20px;"><?= $k['v'] ?></div>
          <div class="stat-label"><?= $k['l'] ?></div></div>
          <div class="stat-icon" style="font-size:18px;"><?= $k['i'] ?></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- ── GRÁFICO ACTIVIDAD 24H + TOP ACCIONES ── -->
    <div class="row g-3 mb-4">

      <!-- Actividad por hora -->
      <div class="col-lg-8">
        <div class="tbl-wrap p-4" style="height:100%;">
          <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;
                      color:#8b949e;margin-bottom:14px;">
            <i class="fa fa-chart-bar me-1"></i>Actividad últimas 24 horas
          </div>
          <div style="display:flex;align-items:flex-end;gap:3px;height:80px;">
            <?php for ($h = 0; $h < 24; $h++):
              $v   = $horaMap[$h] ?? 0;
              $pct = $maxHora > 0 ? round($v / $maxHora * 100) : 0;
              $now = (int)date('H');
              $col = $h === $now ? '#2ea8ff' : ($v > 0 ? '#2ea8ff66' : '#30363d');
            ?>
            <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;">
              <div title="<?= $h ?>:00 — <?= $v ?> eventos"
                   style="width:100%;background:<?= $col ?>;border-radius:3px 3px 0 0;
                           height:<?= max(3,$pct) ?>%;min-height:3px;transition:height .3s;cursor:default;">
              </div>
              <?php if ($h % 4 === 0): ?>
              <div style="font-size:9px;color:#8b949e;"><?= str_pad($h,2,'0',STR_PAD_LEFT) ?></div>
              <?php endif; ?>
            </div>
            <?php endfor; ?>
          </div>
          <div style="font-size:10px;color:#8b949e;margin-top:6px;text-align:right;">
            Hora actual: <?= date('H:i') ?> · Azul brillante = hora actual
          </div>
        </div>
      </div>

      <!-- Top acciones -->
      <div class="col-lg-4">
        <div class="tbl-wrap p-4" style="height:100%;">
          <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;
                      color:#8b949e;margin-bottom:14px;">
            <i class="fa fa-fire me-1"></i>Acciones frecuentes
          </div>
          <?php
          $maxAcc = $topAcciones ? max(array_column($topAcciones,'total')) : 1;
          foreach ($topAcciones as $ac):
            $pct = round($ac['total'] / $maxAcc * 100);
            $col = colorAccion($ac['accion']);
          ?>
          <div style="margin-bottom:10px;">
            <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:3px;">
              <code style="font-size:11px;color:<?= $col ?>;"><?= htmlspecialchars($ac['accion']) ?></code>
              <span style="color:#8b949e;"><?= $ac['total'] ?></span>
            </div>
            <div style="background:#30363d;border-radius:3px;height:4px;">
              <div style="width:<?= $pct ?>%;height:4px;border-radius:3px;background:<?= $col ?>;"></div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>

    <!-- ── FILTROS ── -->
    <form method="GET" class="mb-3">
      <div style="background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px 18px;">
        <div class="row g-2 align-items-end">
          <div class="col-sm-3">
            <label class="form-label">Buscar acción</label>
            <input type="text" name="q" class="form-control form-control-sm"
                   placeholder="login, crear, editar..." value="<?= htmlspecialchars($q) ?>">
          </div>
          <div class="col-sm-2">
            <label class="form-label">Tabla</label>
            <select name="tabla" class="form-select form-select-sm">
              <option value="">Todas</option>
              <?php foreach ($tablas as $t): ?>
              <option value="<?= htmlspecialchars($t) ?>" <?= $tabla===$t?'selected':'' ?>>
                <?= htmlspecialchars($t) ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-sm-2">
            <label class="form-label">Fecha</label>
            <input type="date" name="fecha" class="form-control form-control-sm"
                   value="<?= htmlspecialchars($fecha) ?>">
          </div>
          <div class="col-sm-3">
            <label class="form-label">Usuario</label>
            <select name="usuario" class="form-select form-select-sm">
              <option value="0">Todos los usuarios</option>
              <?php foreach ($usuarios as $u): ?>
              <option value="<?= $u['id_usuario'] ?>" <?= $idUser==$u['id_usuario']?'selected':'' ?>>
                <?= htmlspecialchars($u['nombre']) ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-sm-2 d-flex gap-2">
            <button type="submit" class="btn btn-primary btn-sm flex-fill">
              <i class="fa fa-search me-1"></i>Filtrar
            </button>
            <?php if ($q || $tabla || $fecha || $idUser): ?>
            <a href="audit.php" class="btn btn-outline-secondary btn-sm">✕</a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </form>

    <!-- Conteo -->
    <div style="font-size:12px;color:#8b949e;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center;">
      <span><?= number_format($total) ?> evento(s) · Página <?= $page ?> de <?= $pages ?></span>
      <span>Mostrando <?= count($logs) ?> registros</span>
    </div>

    <!-- ── TABLA AUDIT ── -->
    <div class="tbl-wrap mb-3">
      <table class="table table-borderless mb-0" style="font-size:12px;">
        <thead>
          <tr>
            <th style="width:46px;">#</th>
            <th style="width:140px;">Fecha/Hora</th>
            <th>Usuario</th>
            <th>Acción</th>
            <th>Tabla</th>
            <th style="text-align:center;">ID Reg.</th>
            <th>IP</th>
            <th style="text-align:center;">Detalle</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($logs)): ?>
          <tr>
            <td colspan="8" class="text-center py-5">
              <div style="font-size:28px;margin-bottom:8px;opacity:.4;">🔍</div>
              <div style="color:#8b949e;">Sin registros para el filtro seleccionado.</div>
            </td>
          </tr>
          <?php else: foreach ($logs as $i => $l):
            $col = colorAccion($l['accion']);
            $num = $offset + $i + 1;
          ?>
          <tr style="border-left:3px solid <?= $col ?>; border-left-style:solid;">
            <td style="color:#8b949e;font-family:monospace;"><?= number_format($num) ?></td>
            <td style="font-family:monospace;color:#8b949e;font-size:11px;white-space:nowrap;">
              <div><?= date('d/m/Y', strtotime($l['created_at'])) ?></div>
              <div><?= date('H:i:s', strtotime($l['created_at'])) ?></div>
            </td>
            <td>
              <div style="font-weight:600;"><?= htmlspecialchars($l['usuario_nombre']) ?></div>
              <?php if ($l['rol_nombre']): ?>
              <div style="font-size:10px;color:#8b949e;"><?= htmlspecialchars($l['rol_nombre']) ?></div>
              <?php endif; ?>
            </td>
            <td>
              <code style="font-size:11px;color:<?= $col ?>;background:<?= $col ?>11;
                           border:1px solid <?= $col ?>33;border-radius:4px;padding:2px 8px;">
                <?= htmlspecialchars($l['accion']) ?>
              </code>
            </td>
            <td style="font-family:monospace;color:#8b949e;font-size:11px;">
              <?= htmlspecialchars($l['tabla_afectada'] ?? '—') ?>
            </td>
            <td style="text-align:center;font-family:monospace;color:#8b949e;">
              <?= $l['id_registro'] ?? '—' ?>
            </td>
            <td style="font-family:monospace;font-size:11px;color:#8b949e;">
              <?= htmlspecialchars($l['ip_address'] ?? '—') ?>
            </td>
            <td style="text-align:center;">
              <?php if ($l['datos_antes'] || $l['datos_despues'] || $l['user_agent']): ?>
              <button class="btn btn-sm btn-outline-secondary btn-detalle"
                style="padding:2px 8px;font-size:10px;"
                data-id="<?= $l['id_log'] ?>"
                data-antes='<?= htmlspecialchars($l['datos_antes'] ?? 'null') ?>'
                data-despues='<?= htmlspecialchars($l['datos_despues'] ?? 'null') ?>'
                data-ua='<?= htmlspecialchars($l['user_agent'] ?? '') ?>'
                data-accion='<?= htmlspecialchars($l['accion']) ?>'
                data-usuario='<?= htmlspecialchars($l['usuario_nombre']) ?>'>
                <i class="fa fa-eye"></i>
              </button>
              <?php else: ?>
              <span style="color:#30363d;">—</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

    <!-- ── PAGINACIÓN ── -->
    <?php if ($pages > 1): ?>
    <div style="display:flex;justify-content:center;gap:4px;flex-wrap:wrap;">
      <?php
      $qs = http_build_query(array_filter(['q'=>$q,'tabla'=>$tabla,'fecha'=>$fecha,'usuario'=>$idUser]));
      $prevP = $page > 1 ? $page - 1 : null;
      $nextP = $page < $pages ? $page + 1 : null;
      ?>
      <?php if ($prevP): ?>
      <a href="?<?= $qs ?>&page=<?= $prevP ?>" class="btn btn-sm btn-outline-secondary">
        <i class="fa fa-chevron-left"></i>
      </a>
      <?php endif; ?>
      <?php
      $start = max(1, $page-3); $end = min($pages, $page+3);
      if ($start > 1) echo '<span style="padding:6px 8px;color:#8b949e;">…</span>';
      for ($pg = $start; $pg <= $end; $pg++):
      ?>
      <a href="?<?= $qs ?>&page=<?= $pg ?>"
         class="btn btn-sm <?= $pg===$page?'btn-primary':'btn-outline-secondary' ?>">
        <?= $pg ?>
      </a>
      <?php endfor;
      if ($end < $pages) echo '<span style="padding:6px 8px;color:#8b949e;">…</span>';
      ?>
      <?php if ($nextP): ?>
      <a href="?<?= $qs ?>&page=<?= $nextP ?>" class="btn btn-sm btn-outline-secondary">
        <i class="fa fa-chevron-right"></i>
      </a>
      <?php endif; ?>
      <span style="padding:6px 10px;font-size:12px;color:#8b949e;">
        de <?= number_format($pages) ?> páginas
      </span>
    </div>
    <?php endif; ?>

  </main>
</div>

<!-- ── MODAL DETALLE ── -->
<div class="modal fade" id="modalDetalle" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="fa fa-magnifying-glass me-2" style="color:#2ea8ff;"></i>
          Detalle del evento
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-2 mb-3">
          <div class="col-sm-6">
            <div style="font-size:10px;color:#8b949e;text-transform:uppercase;letter-spacing:.6px;">Acción</div>
            <code id="d-accion" style="font-size:13px;color:#2ea8ff;"></code>
          </div>
          <div class="col-sm-6">
            <div style="font-size:10px;color:#8b949e;text-transform:uppercase;letter-spacing:.6px;">Usuario</div>
            <div id="d-usuario" style="font-size:13px;font-weight:600;"></div>
          </div>
        </div>

        <!-- Datos antes -->
        <div id="blk-antes" style="display:none;margin-bottom:12px;">
          <div style="font-size:10px;color:#ff9d93;font-weight:700;letter-spacing:.6px;
                      text-transform:uppercase;margin-bottom:6px;">
            <i class="fa fa-circle-minus me-1"></i>Datos ANTES del cambio
          </div>
          <pre id="d-antes" style="background:#0d1117;border:1px solid #ff9d9344;border-radius:8px;
                                    padding:12px;font-size:11px;color:#ff9d93;overflow-x:auto;
                                    max-height:200px;white-space:pre-wrap;word-break:break-all;"></pre>
        </div>

        <!-- Datos después -->
        <div id="blk-despues" style="display:none;margin-bottom:12px;">
          <div style="font-size:10px;color:#3dffa0;font-weight:700;letter-spacing:.6px;
                      text-transform:uppercase;margin-bottom:6px;">
            <i class="fa fa-circle-plus me-1"></i>Datos DESPUÉS del cambio
          </div>
          <pre id="d-despues" style="background:#0d1117;border:1px solid #3dffa044;border-radius:8px;
                                      padding:12px;font-size:11px;color:#3dffa0;overflow-x:auto;
                                      max-height:200px;white-space:pre-wrap;word-break:break-all;"></pre>
        </div>

        <!-- User Agent -->
        <div id="blk-ua" style="display:none;">
          <div style="font-size:10px;color:#8b949e;font-weight:700;letter-spacing:.6px;
                      text-transform:uppercase;margin-bottom:6px;">
            <i class="fa fa-globe me-1"></i>Navegador / Dispositivo
          </div>
          <div id="d-ua" style="background:#0d1117;border:1px solid #30363d;border-radius:8px;
                                 padding:10px 12px;font-size:11px;color:#8b949e;word-break:break-all;"></div>
        </div>
      </div>
    </div>
  </div>
</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>
<script>
function prettyJson(str) {
  try { return JSON.stringify(JSON.parse(str), null, 2); }
  catch(e) { return str; }
}

$(function () {
  $(document).on('click', '.btn-detalle', function () {
    var d = $(this).data();
    $('#d-accion').text(d.accion);
    $('#d-usuario').text(d.usuario);

    if (d.antes && d.antes !== 'null') {
      $('#d-antes').text(prettyJson(d.antes));
      $('#blk-antes').show();
    } else { $('#blk-antes').hide(); }

    if (d.despues && d.despues !== 'null') {
      $('#d-despues').text(prettyJson(d.despues));
      $('#blk-despues').show();
    } else { $('#blk-despues').hide(); }

    if (d.ua) { $('#d-ua').text(d.ua); $('#blk-ua').show(); }
    else { $('#blk-ua').hide(); }

    new bootstrap.Modal('#modalDetalle').show();
  });
});
</script>
</body>
</html>