<?php
require_once __DIR__ . '/../includes/bootstrap.php';
admin_require_login();

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

// Handle revoke
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'revoke') {
    $licId = (int)($_POST['lic_id'] ?? 0);
    $reason = trim($_POST['reason'] ?? 'Revoked by admin');
    if ($licId > 0) {
        db_exec(
            "UPDATE licenses SET status = 'revoked', revoke_reason = ? WHERE id = ?",
            [$reason, $licId]
        );
        admin_log('revoke_license', (string)$licId, $reason);
    }
    header('Location: /admin/licenses.php');
    exit;
}

$statusFilter = $_GET['status'] ?? '';
$search       = trim($_GET['q'] ?? '');
$where = []; $params = [];
if ($statusFilter !== '') { $where[] = 'l.status = ?'; $params[] = $statusFilter; }
if ($search !== '') {
    $where[] = '(l.email LIKE ? OR l.order_id LIKE ?)';
    $like = '%'.$search.'%'; $params[] = $like; $params[] = $like;
}
$whereSQL = $where ? 'WHERE '.implode(' AND ', $where) : '';

$rows = db_query(
    "SELECT l.id, l.order_id, l.email, l.plan, l.status, l.issued_at, l.expiry_at,
            l.revoke_reason, r.registration_id, r.business_name
     FROM licenses l
     LEFT JOIN registrations r ON r.id = l.registration_id
     {$whereSQL}
     ORDER BY l.issued_at DESC LIMIT 200",
    $params
);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BizNode Admin — Licenses</title>
<link rel="stylesheet" href="/admin/assets/style.css">
</head>
<body>
<?php include __DIR__ . '/partials/nav.php'; ?>
<main class="main">
  <h1 class="page-title">Licenses</h1>

  <form method="GET" class="filter-bar">
    <input type="text" name="q" value="<?= h($search) ?>" placeholder="Search email / order ID…" class="form-input filter-input">
    <select name="status" class="form-input filter-select">
      <option value="">All statuses</option>
      <?php foreach (['active','expired','revoked','suspended'] as $s): ?>
        <option value="<?= $s ?>" <?= $statusFilter === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
      <?php endforeach; ?>
    </select>
    <button type="submit" class="btn btn-outline">Filter</button>
    <a href="/admin/licenses.php" class="btn btn-ghost">Clear</a>
  </form>

  <p class="result-count"><?= count($rows) ?> licenses</p>

  <table class="data-table">
    <thead><tr>
      <th>Order ID</th><th>Business</th><th>Email</th><th>Plan</th>
      <th>Status</th><th>Issued</th><th>Expires</th><th>Actions</th>
    </tr></thead>
    <tbody>
    <?php foreach ($rows as $r): ?>
      <tr>
        <td><code><?= h($r['order_id']) ?></code></td>
        <td><?= h($r['business_name'] ?? '—') ?></td>
        <td><?= h($r['email']) ?></td>
        <td><?= h($r['plan']) ?></td>
        <td>
          <span class="badge badge-<?= $r['status'] ?>"><?= h($r['status']) ?></span>
          <?php if ($r['revoke_reason']): ?>
            <br><small class="text-muted"><?= h($r['revoke_reason']) ?></small>
          <?php endif; ?>
        </td>
        <td><?= h(substr($r['issued_at'], 0, 16)) ?></td>
        <td><?= h(substr($r['expiry_at'], 0, 16)) ?></td>
        <td>
          <div class="action-btns">
            <a href="/admin/generate_license.php?view=<?= h($r['order_id']) ?>"
               class="btn btn-sm btn-outline">View Files</a>
            <?php if ($r['status'] === 'active'): ?>
            <button type="button" class="btn btn-sm btn-danger"
                    onclick="revokeConfirm(<?= (int)$r['id'] ?>)">Revoke</button>
            <?php endif; ?>
          </div>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($rows)): ?><tr><td colspan="8" class="empty">No licenses found.</td></tr><?php endif; ?>
    </tbody>
  </table>
</main>

<!-- Revoke modal (inline form) -->
<form method="POST" id="revokeForm" style="display:none">
  <input type="hidden" name="action"  value="revoke">
  <input type="hidden" name="lic_id"  id="revokeId">
  <input type="hidden" name="reason"  id="revokeReason" value="Revoked by admin">
</form>
<script>
function revokeConfirm(id) {
  var reason = prompt('Revoke reason (shown to user):', 'License revoked by administrator');
  if (reason === null) return;
  document.getElementById('revokeId').value     = id;
  document.getElementById('revokeReason').value = reason || 'Revoked by admin';
  document.getElementById('revokeForm').submit();
}
</script>
</body>
</html>
