
<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') { header('Location: /smproduce/auth/login.php'); exit; }
$log_file = __DIR__ . '/../config/activity_log.json';
$entries = [];
if (file_exists($log_file)) {
  $json = file_get_contents($log_file);
  $entries = json_decode($json, true) ?: [];
}
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<h3 class="mb-3">Activity Log</h3>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <span>All actions (last 90 days)</span>
    <button id="btn-print-logs" class="btn btn-sm btn-outline-primary">Print</button>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table id="tbl-logs" class="table table-striped table-hover mb-0 align-middle">
        <thead class="table-light">
          <tr>
            <th>Time (UTC)</th><th>User</th><th>Action</th><th>Target</th><th>Details</th><th>IP</th>
          </tr>
          <tr>
            <th><input class="form-control form-control-sm col-filter" data-col-index="0" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="1" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="2" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="3" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="4" placeholder="Filter"></th>
            <th><input class="form-control form-control-sm col-filter" data-col-index="5" placeholder="Filter"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($entries as $e): ?>
            <tr>
              <td><?= htmlspecialchars($e['timestamp'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['user'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['action'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['target'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['details'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['ip'] ?? '') ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($entries)): ?>
            <tr><td colspan="6" class="text-center text-muted py-4">No entries yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
const tLogs = initManagedTable('#tbl-logs');
document.getElementById('btn-print-logs').addEventListener('click', () => window.print());
</script>

<?php include('../includes/footer.php'); ?>
