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

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

// Handle block / unblock actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['reg_id'] ?? 0);

    if ($action === 'block' && $id > 0) {
        db_exec("UPDATE registrations SET status = 'blocked' WHERE id = ?", [$id]);
        admin_log('block_registration', (string)$id);
    } elseif ($action === 'unblock' && $id > 0) {
        db_exec("UPDATE registrations SET status = 'trial' WHERE id = ? AND status = 'blocked'", [$id]);
        admin_log('unblock_registration', (string)$id);
    }
    header('Location: /admin/registrations.php');
    exit;
}

// Filters
$statusFilter = $_GET['status'] ?? '';
$search       = trim($_GET['q'] ?? '');

$where  = [];
$params = [];

if ($statusFilter !== '') {
    $where[]  = 'status = ?';
    $params[] = $statusFilter;
}
if ($search !== '') {
    $where[]  = '(email LIKE ? OR business_name LIKE ? OR registration_id LIKE ?)';
    $like     = '%' . $search . '%';
    $params   = array_merge($params, [$like, $like, $like]);
}

$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$rows = db_query(
    "SELECT id, registration_id, business_name, owner_name, email, phone,
            business_type, city, country, telegram_id,
            registered_at, trial_expires_at, status, ip_address
     FROM registrations {$whereSQL}
     ORDER BY registered_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 — Registrations</title>
<link rel="stylesheet" href="/admin/assets/style.css">
</head>
<body>
<?php include __DIR__ . '/partials/nav.php'; ?>
<main class="main">
  <h1 class="page-title">Registrations</h1>

  <!-- Filters -->
  <form method="GET" class="filter-bar">
    <input type="text" name="q" value="<?= h($search) ?>" placeholder="Search email / business / ID…" class="form-input filter-input">
    <select name="status" class="form-input filter-select">
      <option value="">All statuses</option>
      <?php foreach (['trial','converted','expired','blocked'] 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/registrations.php" class="btn btn-ghost">Clear</a>
  </form>

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

  <table class="data-table">
    <thead><tr>
      <th>Registration ID</th><th>Business</th><th>Owner</th><th>Email</th>
      <th>Status</th><th>Registered</th><th>Trial Expires</th><th>IP</th><th>Actions</th>
    </tr></thead>
    <tbody>
    <?php foreach ($rows as $r): ?>
    <?php $now = new DateTime; $exp = new DateTime($r['trial_expires_at']); $days = max(0,(int)$now->diff($exp)->format('%r%a')); ?>
      <tr>
        <td><code><?= h($r['registration_id']) ?></code></td>
        <td><?= h($r['business_name']) ?><br><small class="text-muted"><?= h($r['business_type']) ?>, <?= h($r['city']) ?></small></td>
        <td><?= h($r['owner_name']) ?></td>
        <td><?= h($r['email']) ?><?php if ($r['telegram_id']): ?><br><small class="text-muted">TG: <?= h($r['telegram_id']) ?></small><?php endif; ?></td>
        <td>
          <span class="badge badge-<?= $r['status'] ?>"><?= h($r['status']) ?></span>
          <?php if ($r['status'] === 'trial'): ?>
            <small class="text-muted"><?= $days ?>d left</small>
          <?php endif; ?>
        </td>
        <td><?= h(substr($r['registered_at'], 0, 16)) ?></td>
        <td><?= h(substr($r['trial_expires_at'], 0, 16)) ?></td>
        <td><small><?= h($r['ip_address']) ?></small></td>
        <td>
          <div class="action-btns">
            <?php if ($r['status'] !== 'blocked'): ?>
            <form method="POST">
              <input type="hidden" name="reg_id" value="<?= (int)$r['id'] ?>">
              <input type="hidden" name="action"  value="block">
              <button type="submit" class="btn btn-sm btn-danger"
                onclick="return confirm('Block this registration?')">Block</button>
            </form>
            <?php else: ?>
            <form method="POST">
              <input type="hidden" name="reg_id" value="<?= (int)$r['id'] ?>">
              <input type="hidden" name="action"  value="unblock">
              <button type="submit" class="btn btn-sm btn-outline">Unblock</button>
            </form>
            <?php endif; ?>
            <a href="/admin/generate_license.php?email=<?= urlencode($r['email']) ?>&reg_id=<?= h($r['registration_id']) ?>&biz=<?= urlencode($r['business_name']) ?>"
               class="btn btn-sm btn-primary">Generate License</a>
          </div>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($rows)): ?>
      <tr><td colspan="9" class="empty">No registrations found.</td></tr>
    <?php endif; ?>
    </tbody>
  </table>
</main>
</body>
</html>
