<?php
$pageTitle  = 'Users';
$activePage = 'users';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

$perPage = 20;
$page    = max(1, (int)($_GET['page'] ?? 1));
$search  = trim($_GET['q'] ?? '');
$offset  = ($page - 1) * $perPage;

if ($search !== '') {
    $like  = "%{$search}%";
    $count = $pdo->prepare("SELECT COUNT(*) FROM users WHERE first_name LIKE ? OR CAST(chat_id AS CHAR) LIKE ?");
    $count->execute([$like, $like]);
    $total = $count->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT u.*, (SELECT 1 FROM subscriptions s WHERE s.chat_id = u.chat_id AND s.status='active' AND s.expires_at > NOW() LIMIT 1) AS has_sub
        FROM users u
        WHERE u.first_name LIKE ? OR CAST(u.chat_id AS CHAR) LIKE ?
        ORDER BY u.created_at DESC LIMIT ? OFFSET ?");
    $stmt->execute([$like, $like, $perPage, $offset]);
} else {
    $total = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $stmt  = $pdo->prepare("
        SELECT u.*, (SELECT 1 FROM subscriptions s WHERE s.chat_id = u.chat_id AND s.status='active' AND s.expires_at > NOW() LIMIT 1) AS has_sub
        FROM users u
        ORDER BY u.created_at DESC LIMIT ? OFFSET ?");
    $stmt->execute([$perPage, $offset]);
}

$users      = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalPages = (int)ceil($total / $perPage);

require_once __DIR__ . '/_header.php';
?>

<div class="page-header d-flex justify-content-between align-items-center">
    <div>
        <h4 class="fw-bold mb-0">Users
            <span class="badge bg-primary ms-1" style="font-size:.65rem;vertical-align:middle"><?= number_format($total) ?></span>
        </h4>
    </div>
</div>

<!-- Search -->
<div class="card table-card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="d-flex gap-2 flex-wrap">
            <input type="text" name="q" class="form-control" placeholder="Search by name or chat ID…"
                   value="<?= htmlspecialchars($search) ?>" style="max-width:300px">
            <button class="btn btn-primary px-3" type="submit"><i class="bi bi-search"></i></button>
            <?php if ($search): ?>
            <a href="users.php" class="btn btn-outline-secondary">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Chat ID</th>
                    <th>Credits</th>
                    <th>Sub</th>
                    <th>BMI</th>
                    <th>Goal</th>
                    <th>Diet</th>
                    <th>Joined</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td class="fw-semibold"><?= htmlspecialchars($u['first_name'] ?? '—') ?></td>
                <td><code style="font-size:.8rem"><?= $u['chat_id'] ?></code></td>
                <td>
                    <span class="badge <?= ((int)$u['credits'] > 0) ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?>">
                        <?= (int)$u['credits'] ?> cr
                    </span>
                </td>
                <td>
                    <?php if ($u['has_sub']): ?>
                    <span class="badge bg-warning-subtle text-warning" title="Active subscriber">⭐</span>
                    <?php else: ?>
                    <span class="text-muted" style="font-size:.75rem">—</span>
                    <?php endif; ?>
                </td>
                <td><?= $u['bmi'] ?? '—' ?></td>
                <td><?= htmlspecialchars(str_replace('_', ' ', $u['goal'] ?? '—')) ?></td>
                <td><?= htmlspecialchars($u['diet'] ?? '—') ?></td>
                <td class="text-muted" style="font-size:.8rem">
                    <?= $u['created_at'] ? date('d M Y', strtotime($u['created_at'])) : '—' ?>
                </td>
                <td>
                    <a href="user.php?id=<?= $u['chat_id'] ?>" class="btn btn-sm btn-outline-primary py-0 px-2">View</a>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($users)): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No users found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="card-footer bg-white border-0 py-2">
        <nav>
            <ul class="pagination pagination-sm mb-0 justify-content-end flex-wrap gap-1">
            <?php for ($i = 1; $i <= min($totalPages, 30); $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                    <a class="page-link" href="?q=<?= urlencode($search) ?>&page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/_footer.php'; ?>
