<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_link') {
    $code = $_POST['code'] ?? '';
    $links = readJson(SHORTLINKS_FILE);
    if (isset($links[$code])) {
        unset($links[$code]);
        writeJson(SHORTLINKS_FILE, $links);
    }
    header('Location: payment_links.php');
    exit;
}

$links = readJson(SHORTLINKS_FILE);
$users = readJson(USERS_FILE);
$usersById = [];
foreach ($users as $u) {
    $usersById[$u['id']] = $u;
}

$links = array_values($links);
usort($links, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
$baseUrl = getBaseUrl();

$pageTitle = 'Payment Links';
$pageSub = count($links) . ' generated links, newest first. Each points to a checkout using its owner\'s own API key.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <div class="card table-card">
    <table class="data-table">
      <tr>
        <th>Short link</th>
        <th>Owner</th>
        <th>Target</th>
        <th>Status</th>
        <th>Clicks</th>
        <th>Created</th>
        <th>Actions</th>
      </tr>
      <?php foreach ($links as $link):
        $owner = $usersById[$link['owner_user_id'] ?? ''] ?? null;
        $shortUrl = $baseUrl . '/s.php?c=' . urlencode($link['code']);
        $expired = isShortlinkExpired($link);
      ?>
        <tr>
          <td><a href="<?= htmlspecialchars($shortUrl) ?>" target="_blank" rel="noopener" class="mono" style="font-size:12.5px;"><?= htmlspecialchars($shortUrl) ?></a></td>
          <td><?= $owner ? htmlspecialchars($owner['name'] . ' (' . $owner['email'] . ')') : '<span class="text-muted">Unknown user</span>' ?></td>
          <td style="max-width:260px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="<?= htmlspecialchars($link['target_url']) ?>"><?= htmlspecialchars($link['target_url']) ?></td>
          <td><span class="badge <?= $expired ? 'badge-red' : 'badge-green' ?>"><?= $expired ? 'Expired' : 'Active' ?></span></td>
          <td><?= number_format($link['clicks'] ?? 0) ?></td>
          <td><?= htmlspecialchars($link['created_at'] ?? '-') ?></td>
          <td>
            <form method="POST" onsubmit="return confirm('Delete this payment link? It will stop working immediately.');" style="display:inline;">
              <input type="hidden" name="action" value="delete_link">
              <input type="hidden" name="code" value="<?= htmlspecialchars($link['code']) ?>">
              <button type="submit" class="btn btn-danger btn-sm">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($links)): ?>
        <tr><td colspan="7" class="empty-row">No payment links generated yet.</td></tr>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>
