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

$users = readJson(USERS_FILE);
$users = array_map('migrateUserSchema', $users);
$orders = readJson(ORDERS_FILE);

$userStats = [];
foreach ($orders as $order) {
    $uid = $order['user_id'] ?? '';
    if ($uid === '') continue;
    if (!isset($userStats[$uid])) {
        $userStats[$uid] = ['paid' => 0, 'pending' => 0, 'failed' => 0];
    }
    $amt = floatval($order['amount'] ?? 0);
    if (($order['status'] ?? '') === 'success') {
        $userStats[$uid]['paid'] += $amt;
    } elseif (($order['status'] ?? '') === 'pending') {
        $userStats[$uid]['pending'] += $amt;
    } else {
        $userStats[$uid]['failed'] += $amt;
    }
}

$users = array_reverse($users);

$pageTitle = 'User Management';
$pageSub = count($users) . ' registered merchants and developer accounts.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <div class="card">
    <div class="card-title">
      <span><i class="fa-solid fa-users-gear"></i> Registered Merchant Directory</span>
      <input type="text" id="user-search" placeholder="Search by name, email..." class="form-control" style="max-width: 280px; display: inline-block;">
    </div>
    <div class="table-card">
      <table class="data-table" id="users-table">
        <thead>
          <tr>
            <th>User Profile</th>
            <th>Email</th>
            <th>Plan Tier</th>
            <th>Expires On</th>
            <th>Account Status</th>
            <th>API Usage</th>
            <th>Keys</th>
            <th>Total Paid</th>
            <th>Pending</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($users as $u):
            $stats = $userStats[$u['id']] ?? ['paid' => 0, 'pending' => 0, 'failed' => 0];
            $isBanned = ($u['status'] ?? '') === 'banned';
          ?>
            <tr class="user-row">
              <td>
                <div style="display: flex; align-items: center; gap: 0.75rem;">
                  <?php if (!empty($u['avatar'])): ?>
                    <img src="<?= htmlspecialchars($u['avatar']) ?>" class="avatar-sm" alt="" style="width: 36px; height: 36px; border-radius: 50%; border: 1px solid var(--border);">
                  <?php else: ?>
                    <div style="width: 36px; height: 36px; border-radius: 50%; background: var(--grad); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 0.9rem;">
                      <?= mb_substr(htmlspecialchars($u['name'] ?? 'U'), 0, 1) ?>
                    </div>
                  <?php endif; ?>
                  <div>
                    <strong style="color: #f8fafc; font-size: 0.92rem; display: block;"><?= htmlspecialchars($u['name'] ?? 'User') ?></strong>
                    <span style="font-size: 0.75rem; color: #64748b; font-family: monospace;">ID: <?= htmlspecialchars(substr($u['id'], 0, 10)) ?></span>
                  </div>
                </div>
              </td>
              <td style="color: #cbd5e1;"><?= htmlspecialchars($u['email']) ?></td>
              <td>
                <span class="badge-status success" style="background: rgba(59, 130, 246, 0.15); color: #60a5fa; border-color: rgba(59, 130, 246, 0.3);">
                  <?= htmlspecialchars($u['plan_label'] ?? 'Free') ?>
                </span>
              </td>
              <td style="font-size: 0.85rem; color: #94a3b8;"><?= htmlspecialchars(date('d M Y', strtotime($u['plan_expires_at'] ?? 'now'))) ?></td>
              <td>
                <span class="badge-status <?= $isBanned ? 'failed' : 'success' ?>">
                  <i class="fa-solid <?= $isBanned ? 'fa-ban' : 'fa-check' ?>"></i> <?= ucfirst($u['status'] ?? 'active') ?>
                </span>
              </td>
              <td style="font-weight: 700; color: #f8fafc;"><?= number_format($u['total_requests'] ?? 0) ?> req</td>
              <td><span style="font-family: monospace; font-weight: 700; color: #a78bfa;"><?= count($u['api_keys'] ?? []) ?>/3</span></td>
              <td style="color:#10b981; font-weight:700;">₹<?= number_format($stats['paid'], 2) ?></td>
              <td style="color:#fbbf24; font-weight:600;">₹<?= number_format($stats['pending'], 2) ?></td>
              <td>
                <a href="user_edit.php?id=<?= urlencode($u['id']) ?>" class="btn btn-outline" style="padding: 0.35rem 0.8rem; font-size: 0.8rem; border-radius: 8px;">
                  <i class="fa-solid fa-pen-to-square"></i> Manage
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($users)): ?>
            <tr><td colspan="10" style="text-align:center; color:var(--muted); padding:30px;">No registered merchants yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
document.getElementById('user-search').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase().trim();
    document.querySelectorAll('.user-row').forEach(row => {
        const text = row.innerText.toLowerCase();
        row.style.display = text.includes(term) ? '' : 'none';
    });
});
</script>

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