<?php
$active = 'sessions';
$pageTitle = 'Vendor Sessions';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$vendor_id = (int)($_GET['vendor_id'] ?? 0);
$action = $_POST['action'] ?? '';
$token_id = (int)($_POST['token_id'] ?? 0);
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'revoke' && $token_id) {
  $stmt = $pdo->prepare("DELETE FROM vendor_tokens WHERE id=?");
  $stmt->execute([$token_id]);
  $msg = "<div class='alert alert-success'>Session revoked.</div>";
}

$where = [];
$params = [];
if ($vendor_id) { $where[] = "vt.vendor_id=?"; $params[] = $vendor_id; }

$sql = "SELECT vt.*, v.vendor_code, v.name vendor_name
        FROM vendor_tokens vt
        JOIN vendors v ON v.id=vt.vendor_id";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY vt.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tokens = $stmt->fetchAll(PDO::FETCH_ASSOC);

$activeCount = $pdo->query("SELECT COUNT(*) FROM vendor_tokens WHERE expires_at > NOW()")->fetchColumn();
?>
<div class="page-header d-flex justify-content-between align-items-center">
  <div>
    <h1>Vendor Sessions</h1>
    <p class="subtitle">Active login tokens (<?php echo $activeCount; ?> valid)</p>
  </div>
</div>

<?php echo $msg; ?>

<form class="row g-2 mb-3">
  <div class="col-md-2"><input class="form-control" name="vendor_id" type="number" placeholder="Vendor ID" value="<?php echo $vendor_id ?: ''; ?>"></div>
  <div class="col-auto"><button class="btn btn-dark" type="submit">Filter</button></div>
</form>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Vendor</th><th>Token (first 16)</th><th>Created</th><th>Expires</th><th>Status</th><th class="text-end">Actions</th></tr></thead>
        <tbody>
          <?php foreach ($tokens as $t): ?>
          <tr>
            <td>#<?php echo $t['id']; ?></td>
            <td><strong><?php echo htmlspecialchars($t['vendor_code']); ?></strong> <?php echo htmlspecialchars($t['vendor_name']); ?></td>
            <td><code><?php echo htmlspecialchars(substr($t['token'], 0, 16)) . '...'; ?></code></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($t['created_at'])); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($t['expires_at'])); ?></td>
            <td><span class="badge bg-<?php echo strtotime($t['expires_at']) > time() ? 'success' : 'secondary'; ?>"><?php echo strtotime($t['expires_at']) > time() ? 'Active' : 'Expired'; ?></span></td>
            <td class="text-end">
              <?php if (strtotime($t['expires_at']) > time()): ?>
              <form method="post" class="d-inline" onsubmit="return confirm('Revoke this session? Vendor will need to login again.');">
                <input type="hidden" name="action" value="revoke">
                <input type="hidden" name="token_id" value="<?php echo $t['id']; ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Revoke</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($tokens)): ?><tr><td colspan="7" class="text-muted">No sessions</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
