<?php
$page_title = "ইউজার ম্যানেজমেন্ট";
require_once 'includes/auth_check.php';
include 'includes/header.php';

$search_query = "";
$sql = "SELECT u.id, u.full_name, u.mobile, u.balance, u.status, r.level_name FROM users u JOIN reseller_levels r ON u.level_id = r.id WHERE u.role='user'";
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search_query = $_GET['search'];
    $sql .= " AND (u.full_name LIKE ? OR u.mobile LIKE ?)";
}
$sql .= " ORDER BY u.id DESC";

$stmt = $conn->prepare($sql);
if (!empty($search_query)) {
    $search_param = "%" . $search_query . "%";
    $stmt->bind_param("ss", $search_param, $search_param);
}
$stmt->execute();
$users_result = $stmt->get_result();
?>
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>সকল ইউজার</h2>
        <form method="GET" action="users.php" class="d-flex"><input type="text" name="search" class="form-control me-2" placeholder="নাম বা মোবাইল..." value="<?php echo htmlspecialchars($search_query); ?>"><button type="submit" class="btn btn-primary">সার্চ</button></form>
    </div>
    <div class="card"><div class="card-body"><div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="table-light"><tr><th>ID</th><th>নাম</th><th>মোবাইল</th><th>ব্যালেন্স</th><th>লেভেল</th><th>স্ট্যাটাস</th><th>একশন</th></tr></thead>
            <tbody>
                <?php if ($users_result->num_rows > 0): while($user = $users_result->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $user['id']; ?></td>
                    <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($user['mobile']); ?></td>
                    <td><?php echo number_format($user['balance'], 2); ?></td>
                    <td><?php echo htmlspecialchars($user['level_name']); ?></td>
                    <td><span class="badge bg-<?php echo $user['status'] == 'Active' ? 'success' : 'danger'; ?>"><?php echo $user['status']; ?></span></td>
                    <td><a href="edit_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i> এডিট</a></td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="7" class="text-center">কোনো ইউজার খুঁজে পাওয়া যায়নি।</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div></div></div>
</div>
<?php include 'includes/footer.php'; $stmt->close(); $conn->close(); ?>