<?php require_once '../includes/header.php';

// --- Filters & Pagination ---
$page       = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage    = 15;
$offset     = ($page - 1) * $perPage;

$search     = trim($_GET['search'] ?? '');
$subActive  = $_GET['is_active'] ?? '';   // 1 = only subscribed, 0 = no active sub
$isVerified = $_GET['is_verified'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($search !== '') {
    $escaped = addcslashes($search, '%_');
    $pat     = "%$escaped%";
    $where  .= " AND (u.reseller_name LIKE :sn OR u.shop_name LIKE :ss OR u.email LIKE :se OR u.phone LIKE :sp)";
    $params[':sn'] = $pat;
    $params[':ss'] = $pat;
    $params[':se'] = $pat;
    $params[':sp'] = $pat;
}

// --- Active filter based on active subscription ---
if ($subActive === '1') {
    // Only users with an active subscription (not expired/cancelled)
    $where .= " AND EXISTS (
        SELECT 1 FROM user_subscriptions us_s
        WHERE us_s.user_id = u.id
          AND us_s.status = 'active'
          AND us_s.expires_at > NOW()
    )";
} elseif ($subActive === '0') {
    // Users without any active subscription
    $where .= " AND NOT EXISTS (
        SELECT 1 FROM user_subscriptions us_s
        WHERE us_s.user_id = u.id
          AND us_s.status = 'active'
          AND us_s.expires_at > NOW()
    )";
}

if ($isVerified !== '') {
    $where .= " AND u.is_verified = :v";
    $params[':v'] = (int)$isVerified;
}

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM users u $where");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

// Fetch users with wallet balance and active plan (already fetched)
$usersStmt = $pdo->prepare("
    SELECT u.*,
           COALESCE((SELECT SUM(CASE WHEN type='credit' THEN amount ELSE -amount END)
                      FROM wallet_transactions WHERE user_id = u.id),0) AS wallet_balance,
           (SELECT GROUP_CONCAT(sp.plan_name SEPARATOR ', ')
            FROM user_subscriptions us
            JOIN subscription_plans sp ON us.plan_id = sp.id
            WHERE us.user_id = u.id
              AND us.status = 'active'
              AND us.expires_at > NOW()
            LIMIT 1) AS active_plan
    FROM users u
    $where
    ORDER BY u.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$usersStmt->execute($params);
$users = $usersStmt->fetchAll();
?>

<h1 class="h2 mb-4">Resellers</h1>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Filter card -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control"
                       placeholder="Name / Shop / Email / Phone"
                       value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Active (Subscribed)</label>
                <select name="is_active" class="form-select">
                    <option value="">All</option>
                    <option value="1" <?= $subActive === '1' ? 'selected' : '' ?>>Yes</option>
                    <option value="0" <?= $subActive === '0' ? 'selected' : '' ?>>No</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Verified</label>
                <select name="is_verified" class="form-select">
                    <option value="">All</option>
                    <option value="1" <?= $isVerified === '1' ? 'selected' : '' ?>>Yes</option>
                    <option value="0" <?= $isVerified === '0' ? 'selected' : '' ?>>No</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
            <div class="col-md-2">
                <a href="users.php" class="btn btn-outline-secondary w-100">Reset</a>
            </div>
        </form>
    </div>
</div>

<!-- Users table -->
<div class="card shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Name / Shop</th>
                        <th>Phone / Email</th>
                        <th>Wallet</th>
                        <th>Active Plan</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($users)): ?>
                    <tr><td colspan="7" class="text-center py-3">No resellers found.</td></tr>
                <?php else: foreach ($users as $u): 
                    // Derived active status from active_plan existence
                    $hasActiveSub = !empty($u['active_plan']);
                ?>
                    <tr>
                        <td><?= $u['id'] ?></td>
                        <td>
                            <strong><?= htmlspecialchars($u['reseller_name']) ?></strong>
                            <br><small class="text-muted"><?= htmlspecialchars($u['shop_name']) ?></small>
                        </td>
                        <td>
                            <?= htmlspecialchars($u['phone']) ?><br>
                            <small class="text-muted"><?= htmlspecialchars($u['email']) ?></small>
                        </td>
                        <td>৳<?= number_format($u['wallet_balance'], 2) ?></td>
                        <td><?= htmlspecialchars($u['active_plan'] ?? '—') ?></td>
                        <td>
                            <?php if ($hasActiveSub): ?>
                                <span class="badge bg-success">Active</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Inactive</span>
                            <?php endif; ?>
                            <?php if ($u['is_verified']): ?>
                                <span class="badge bg-info ms-1">Verified</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <a href="user_details.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i> Details</a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <li class="page-item <?= $page == 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&is_active=<?= $subActive ?>&is_verified=<?= $isVerified ?>">&laquo;</a>
        </li>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&is_active=<?= $subActive ?>&is_verified=<?= $isVerified ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page == $totalPages ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&is_active=<?= $subActive ?>&is_verified=<?= $isVerified ?>">&raquo;</a>
        </li>
    </ul>
</nav>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>