<?php
require_once 'auth_check.php';
require_once 'config.php';

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';
$page = isset($_GET['page']) ? max(1,(int)$_GET['page']) : 1;
$perPage = 25;
$offset = ($page-1)*$perPage;

$conds = [];
if ($search !== '') {
    $s = mysqli_real_escape_string($koneksi, $search);
    $conds[] = "(username LIKE '%$s%' OR token LIKE '%$s%')";
}
if ($status_filter !== '') {
    $sf = mysqli_real_escape_string($koneksi, $status_filter);
    $conds[] = "status='$sf'";
}
$where = $conds ? 'WHERE '.implode(' AND ',$conds) : '';

$countQ = mysqli_query($koneksi, "SELECT COUNT(*) as c FROM data_sucses $where");
$totalRows = 0;
if ($countQ) { $r = mysqli_fetch_assoc($countQ); $totalRows = $r['c']; }
$totalPages = max(1, ceil($totalRows / $perPage));

$jobs = [];
$q = mysqli_query($koneksi, "SELECT id,username,userid,token,status,authid,info,tgl FROM data_sucses $where ORDER BY id DESC LIMIT $offset,$perPage");
if ($q) while ($row = mysqli_fetch_assoc($q)) $jobs[] = $row;
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Jobs - Admin Panel</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
  <?php include 'topbar.php'; ?>
  <div class="page-body">
    <div class="page-header"><h2>Job History</h2></div>

    <div class="card">
      <div class="card-header">
        <form method="GET" class="search-form">
          <input type="text" name="search" placeholder="Search username or token..." value="<?= htmlspecialchars($search) ?>">
          <select name="status" style="width:auto">
            <option value="">All Status</option>
            <option value="PENDING" <?= $status_filter==='PENDING'?'selected':'' ?>>Pending</option>
            <option value="SUCCESS" <?= $status_filter==='SUCCESS'?'selected':'' ?>>Success</option>
            <option value="FAILED" <?= $status_filter==='FAILED'?'selected':'' ?>>Failed</option>
          </select>
          <button type="submit" class="btn btn-primary">Filter</button>
          <a href="jobs.php" class="btn btn-outline">Clear</a>
        </form>
        <span class="text-muted"><?= $totalRows ?> jobs</span>
      </div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr><th>ID</th><th>Username</th><th>Service</th><th>Token</th><th>Status</th><th>Date</th><th>Action</th></tr>
          </thead>
          <tbody>
            <?php foreach($jobs as $j): ?>
            <tr>
              <td><?= $j['id'] ?></td>
              <td><?= htmlspecialchars($j['username']) ?></td>
              <td><?= htmlspecialchars($j['authid']) ?></td>
              <td><code style="font-size:11px"><?= $j['token']==='none'?'<span class="text-muted">Pending...</span>':htmlspecialchars(substr($j['token'],0,30)) ?></code></td>
              <td><span class="badge badge-<?= $j['status']==='SUCCESS'?'success':($j['status']==='PENDING'?'warning':'danger') ?>"><?= htmlspecialchars($j['status']) ?></span></td>
              <td class="text-muted" style="font-size:12px"><?= htmlspecialchars($j['tgl']) ?></td>
              <td><button class="btn btn-xs btn-outline" onclick='showInfo(<?= json_encode($j["info"]) ?>)'>Info</button></td>
            </tr>
            <?php endforeach; ?>
            <?php if(empty($jobs)): ?>
            <tr><td colspan="7" class="text-center text-muted" style="padding:30px">No jobs found</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <?php if($totalPages > 1): ?>
      <div class="pagination">
        <?php for($i=1;$i<=$totalPages;$i++): ?>
        <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_filter) ?>" class="page-btn <?= $i==$page?'active':'' ?>"><?= $i ?></a>
        <?php endfor; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Info Modal -->
<div class="modal" id="infoModal">
  <div class="modal-backdrop" onclick="closeModal('infoModal')"></div>
  <div class="modal-box" style="max-width:500px">
    <div class="modal-header"><h3>Job Info</h3><button onclick="closeModal('infoModal')">✕</button></div>
    <pre id="infoContent" style="background:var(--bg-secondary);padding:16px;border-radius:8px;overflow:auto;font-size:12px;white-space:pre-wrap"></pre>
    <div class="modal-footer"><button class="btn btn-outline" onclick="closeModal('infoModal')">Close</button></div>
  </div>
</div>

<div id="toast" class="toast"></div>
<script src="assets/script.js"></script>
<script>
function showInfo(info) {
  try { document.getElementById('infoContent').textContent = JSON.stringify(JSON.parse(info), null, 2); }
  catch(e) { document.getElementById('infoContent').textContent = info; }
  openModal('infoModal');
}
</script>
</body>
</html>
