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

$page = max(1, (int)($_GET['page'] ?? 1));
$limit = max(10, (int)($_GET['limit'] ?? 50));
$offset = ($page - 1) * $limit;
$search = trim($_GET['search'] ?? '');

$where = "WHERE 1=1";
$params = [];
if ($search !== '') {
    $where .= " AND (name LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Get total count
$stmtCount = getDB()->prepare("SELECT COUNT(*) FROM users $where");
$stmtCount->execute($params);
$totalUsers = $stmtCount->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

// Fetch paginated users
$stmt = getDB()->prepare("SELECT * FROM users $where ORDER BY id DESC LIMIT $limit OFFSET $offset");
$stmt->execute($params);
$usersRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
$users = array_map('migrateUserSchema', $usersRaw);

// Fetch stats ONLY for these specific users
$userStats = [];
if (!empty($users)) {
    $userIds = array_column($users, 'id');
    $placeholders = implode(',', array_fill(0, count($userIds), '?'));
    
    $rows = getDB()->prepare("SELECT user_id, 
        SUM(CASE WHEN status='success' THEN amount ELSE 0 END) AS paid, 
        SUM(CASE WHEN status='pending' THEN amount ELSE 0 END) AS pending, 
        SUM(CASE WHEN status NOT IN ('success','pending') THEN amount ELSE 0 END) AS failed 
        FROM orders WHERE user_id IN ($placeholders) GROUP BY user_id");
    $rows->execute($userIds);
    foreach ($rows->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $userStats[$r['user_id']] = $r;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Manage Users — Admin Control Panel"; include __DIR__ . '/admin-style.php'; ?>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">

      <div style="margin-bottom:24px;">
        <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
          <i data-lucide="users" style="color:var(--color-primary);width:24px;height:24px;"></i> All Users (<?= number_format($totalUsers) ?>)
        </h1>
        <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Manage developer accounts, view API key counts and payment volumes.</p>
      </div>

      <div class="card" style="padding:0;overflow:hidden;">
        <div style="padding:22px 28px 18px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
          <div>
            <div class="card-title"><i data-lucide="shield" style="width:18px;height:18px;color:var(--color-primary);"></i> User Roster</div>
            <div class="card-sub">Click 'Manage' to ban/unban, change passwords or add API keys</div>
          </div>
          <div style="display:flex; gap:10px; align-items:center;">
            <form method="GET" action="users.php" style="position:relative; margin:0;">
              <i data-lucide="search" style="position:absolute;left:10px;top:50%;transform:translateY(-50%);width:14px;height:14px;color:var(--color-ink-mute);"></i>
              <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search name or email..." class="form-input" style="padding-left:32px; height:32px; font-size:13px; width:200px; border-radius:var(--r-md);">
            </form>
            <a href="dashboard.php" class="btn btn-secondary" style="font-size:13px;padding:6px 14px;"><i data-lucide="arrow-left" style="width:14px;height:14px;"></i> Overview</a>
          </div>
        </div>

        <div class="table-container" style="margin:0;border-radius:0 0 var(--r-xl) var(--r-xl);">
          <table class="table">
            <thead>
              <tr>
                <th>Avatar</th>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
                <th>Requests</th>
                <th>API Keys</th>
                <th>Paid (₹)</th>
                <th>Pending (₹)</th>
                <th style="text-align:right;">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($users)): ?>
              <tr><td colspan="9">
                <div class="empty-state">
                  <div class="empty-state-icon"><i data-lucide="users"></i></div>
                  <div class="empty-state-title">No users found</div>
                  <div class="empty-state-sub">Developer signups will appear here</div>
                </div>
              </td></tr>
              <?php else: foreach ($users as $u):
                $stats = $userStats[$u['id']] ?? ['paid' => 0, 'pending' => 0, 'failed' => 0];
              ?>
              <tr>
                <td>
                  <?php if (!empty($u['avatar'])): ?>
                    <img src="<?= htmlspecialchars($u['avatar']) ?>" style="width:36px;height:36px;border-radius:50%;object-fit:cover;border:1px solid var(--color-hairline);" alt="">
                  <?php else: ?>
                    <div style="width:36px;height:36px;border-radius:50%;background:#1e3a8a;color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:15px;">
                      <?= strtoupper(substr($u['name'] ?? 'U', 0, 1)) ?>
                    </div>
                  <?php endif; ?>
                </td>
                <td style="font-weight:600;color:var(--color-ink);"><?= htmlspecialchars($u['name']) ?></td>
                <td style="color:var(--color-ink-secondary);"><?= htmlspecialchars($u['email']) ?></td>
                <td><span class="badge <?= $u['status'] === 'banned' ? 'badge-danger' : 'badge-success' ?>"><?= ucfirst($u['status']) ?></span></td>
                <td class="tnum" style="font-weight:500;"><?= number_format($u['total_requests'] ?? 0) ?></td>
                <td class="tnum"><span class="badge badge-soft"><?= count($u['api_keys']) ?> key<?= count($u['api_keys']) !== 1 ? 's' : '' ?></span></td>
                <td class="tnum" style="color:var(--color-success-text);font-weight:700;">₹<?= number_format($stats['paid'], 2) ?></td>
                <td class="tnum" style="color:var(--color-warning-text);font-weight:600;">₹<?= number_format($stats['pending'], 2) ?></td>
                <td style="text-align:right;"><a href="user-edit.php?id=<?= urlencode($u['id']) ?>" class="btn btn-secondary" style="font-size:12px;padding:5px 12px;"><i data-lucide="edit" style="width:13px;height:13px;"></i> Manage</a></td>
              </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
        <div style="padding: 16px 24px; border-top: 1px solid var(--color-hairline); display: flex; justify-content: space-between; align-items: center;">
          <div style="font-size: 13px; color: var(--color-ink-mute);">
            Showing <?= count($users) ?> of <?= number_format($totalUsers) ?> users
          </div>
          <div style="display: flex; gap: 8px;">
            <?php if ($page > 1): ?>
              <a href="users.php?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>" class="btn btn-secondary" style="font-size:12px; padding:6px 12px;">Previous</a>
            <?php endif; ?>
            <?php if ($page < $totalPages): ?>
              <a href="users.php?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>" class="btn btn-secondary" style="font-size:12px; padding:6px 12px;">Next</a>
            <?php endif; ?>
          </div>
        </div>
      </div>

    </div>
  </main>
</div>
<script>
    if (window.lucide) { lucide.createIcons(); }
</script>
</body>
</html>
