<?php
session_start();

include 'db.php';

if (!isset($_SESSION['username']) || $_SESSION['username'] !== "admin@admin.com") {
    header("Location: login.php");
    exit;
}

/* 🔧 Nyalakan error saat debug (boleh dimatikan setelah beres) */
error_reporting(E_ALL);
ini_set('display_errors', 1);

$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . htmlspecialchars($conn->connect_error));
}

/* --- Pencarian --- */
$q = trim($_GET['q'] ?? '');
$where = "";
$params = [];
$types  = "";
if ($q !== "") {
    $where = "WHERE admin LIKE ? OR aksi LIKE ? OR keterangan LIKE ?";
    $like = "%".$q."%";
    $params = [$like, $like, $like];
    $types  = "sss";
}

/* --- Pagination (angka disisipkan langsung, bukan bind) --- */
$per_page = 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per_page;

/* --- Hitung total baris --- */
$total_rows = 0;
$sql_count = "SELECT COUNT(*) AS jml FROM admin_log " . ($where ? $where : "");
$stmt_count = $conn->prepare($sql_count);
if (!$stmt_count) {
    die("Gagal prepare COUNT: " . htmlspecialchars($conn->error));
}
if ($where) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$res_count = $stmt_count->get_result();
if ($res_count) {
    $total_rows = (int)($res_count->fetch_assoc()['jml'] ?? 0);
} else {
    // fallback tanpa mysqlnd
    $stmt_count->bind_result($jml);
    if ($stmt_count->fetch()) { $total_rows = (int)$jml; }
}
$stmt_count->close();
$total_pages = max(1, (int)ceil($total_rows / $per_page));

/* --- Ambil data: LIMIT/OFFSET disisipkan aman (angka) --- */
$sql = "SELECT id, admin, aksi, waktu, keterangan
        FROM admin_log
        " . ($where ? $where : "") . "
        ORDER BY waktu DESC
        LIMIT {$per_page} OFFSET {$offset}";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Gagal prepare SELECT: " . htmlspecialchars($conn->error));
}
if ($where) { $stmt->bind_param($types, ...$params); }
$stmt->execute();

/* --- Ambil hasil (kompatibel mysqlnd / non-mysqlnd) --- */
$rows = [];
if (method_exists($stmt, 'get_result')) {
    $result = $stmt->get_result();
    if ($result) {
        while ($r = $result->fetch_assoc()) { $rows[] = $r; }
    }
} else {
    $stmt->store_result();
    $stmt->bind_result($id, $admin, $aksi, $waktu, $keterangan);
    while ($stmt->fetch()) {
        $rows[] = [
            'id' => $id,
            'admin' => $admin,
            'aksi' => $aksi,
            'waktu' => $waktu,
            'keterangan' => $keterangan
        ];
    }
}
$stmt->close();

/* --- Helper format tanggal --- */
function tglIndo($dt) {
    $bulan = [1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    $ts = strtotime($dt);
    if (!$ts) return htmlspecialchars($dt);
    $d = (int)date('j', $ts);
    $m = (int)date('n', $ts);
    $y = date('Y', $ts);
    $time = date('H:i:s', $ts);
    return $d.' '.$bulan[$m].' '.$y.' '.$time;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Log Aktivitas Admin</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background: linear-gradient(135deg, #f5f7fa, #e4e9f7); font-family: 'Verdana', sans-serif; }
    .card { border-radius: 1rem; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
    th { background-color: #0d6efd; color: #fff; }
    .table-hover tbody tr:hover { background-color: #f5f8ff; }
    .search-input { max-width: 360px; }
  </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top shadow">
  <div class="container">
    <a class="navbar-brand fw-bold" href="admin_dashboard.php">⬅️ Dashboard</a>
    <span class="navbar-text">Log Aktivitas Admin</span>
  </div>
</nav>
<div style="margin-top: 80px;"></div>

<div class="container mt-3">
  <div class="card p-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
      <h3 class="text-primary m-0">📘 Log Aktivitas Administrator</h3>
      <form class="d-flex gap-2" method="get" action="">
        <input name="q" value="<?= htmlspecialchars($q) ?>" class="form-control search-input" type="search" placeholder="Cari admin/aksi/keterangan...">
        <button class="btn btn-primary" type="submit">Cari</button>
        <?php if ($q !== ""): ?>
          <a class="btn btn-outline-secondary" href="log_admin.php">Reset</a>
        <?php endif; ?>
      </form>
    </div>

    <?php if (count($rows) > 0): ?>
      <div class="table-responsive">
        <table class="table table-bordered table-hover align-middle text-center">
          <thead>
            <tr>
              <th style="width:80px;">ID</th>
              <th style="width:14%;">Waktu</th>
              <th style="width:16%;">Admin</th>
              <th style="width:14%;">Aksi</th>
              <th>Keterangan</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><?= htmlspecialchars(tglIndo($r['waktu'])) ?></td>
              <td><?= htmlspecialchars($r['admin']) ?></td>
              <td><?= htmlspecialchars($r['aksi']) ?></td>
              <td class="text-start"><?= nl2br(htmlspecialchars($r['keterangan'])) ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <nav aria-label="Halaman log" class="mt-3">
        <ul class="pagination justify-content-center">
          <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?q=<?= urlencode($q) ?>&page=<?= $page-1 ?>">Sebelumnya</a>
          </li>
          <?php
          $total_pages = max(1, $total_pages);
          $start = max(1, $page - 3);
          $end   = min($total_pages, $page + 3);
          for ($p=$start; $p<=$end; $p++): ?>
            <li class="page-item <?= $p == $page ? 'active' : '' ?>">
              <a class="page-link" href="?q=<?= urlencode($q) ?>&page=<?= $p ?>"><?= $p ?></a>
            </li>
          <?php endfor; ?>
          <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
            <a class="page-link" href="?q=<?= urlencode($q) ?>&page=<?= $page+1 ?>">Berikutnya</a>
          </li>
        </ul>
      </nav>
      <div class="text-center text-muted small">Total log: <?= number_format($total_rows) ?></div>
    <?php else: ?>
      <p class="text-center text-muted mb-0">Belum ada aktivitas yang tercatat.</p>
    <?php endif; ?>

  </div>
</div>

<footer class="text-center mt-5 text-muted small">
  <p>&copy; <?= date('Y'); ?> Toko Online Maju Jaya — Admin Log</p>
</footer>

</body>
</html>
<?php
$conn->close();
