<?php
require_once 'admin_init.php';
// =================================================================
// ADMIN PANEL - USER MANAGEMENT (Search & Delete Added, Mobile Friendly)
// =================================================================
require_once 'includes/header.php';
$conn = $conn_header;

// --- ডিলিট লজিক ---
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $user_id_to_delete = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($user_id_to_delete) {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param('i', $user_id_to_delete);
        if ($stmt->execute()) {
            $_SESSION['message'] = "<div class='message success'>User deleted successfully!</div>";
        } else {
            $_SESSION['message'] = "<div class='message error'>Error deleting user: " . $stmt->error . "</div>";
        }
        $stmt->close();
        // ডিলিট করার পর URL থেকে action এবং id প্যারামিটার সরিয়ে দেওয়া
        header("Location: users.php");
        exit;
    }
}

// --- সার্চ এবং ফিল্টার লজিক ---
$search_query = "";
$where_clause = "WHERE 1";
if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
    $search_term = trim($_GET['search']);
    $search_query = $search_term;
    $escaped_search_term = $conn->real_escape_string($search_term);
    
    if (strpos($escaped_search_term, '@') === 0) {
        $escaped_search_term = substr($escaped_search_term, 1);
    }
    
    $where_clause = "WHERE `first_name` LIKE '%{$escaped_search_term}%' 
                      OR `username` LIKE '%{$escaped_search_term}%' 
                      OR `chat_id` = '{$escaped_search_term}'";
}

// সকল ব্যবহারকারীর তথ্য ডাটাবেস থেকে আনা
$users = $conn->query("SELECT * FROM users {$where_clause} ORDER BY id DESC");
?>
<style>
    .table-container { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
    .search-bar { margin-bottom: 20px; display: flex; gap: 10px; }
    .search-bar input { flex-grow: 1; padding: 10px; border: 1px solid #ccc; border-radius: 5px; }
    .btn { padding: 10px 15px; border: none; border-radius: 5px; color: #fff; background-color: var(--primary-blue); cursor: pointer; }

    .responsive-table { width: 100%; border-collapse: collapse; }
    .responsive-table th, .responsive-table td { padding: 12px; border-bottom: 1px solid #ddd; text-align: left; }
    .responsive-table th { background-color: #f8f9fa; }
    td img.profile-pic { width: 40px; height: 40px; border-radius: 50%; vertical-align: middle; margin-right: 10px; }
    
    .action-btn { padding: 5px 10px; border: none; border-radius: 5px; color: #fff; text-decoration: none; font-size: 0.9em; display: inline-block; margin-top: 5px; margin-right: 5px; }
    .btn-edit { background-color: #ffc107; }
    .btn-delete { background-color: #dc3545; }

    .message { padding: 15px; margin-bottom: 20px; border-radius: 5px; border: 1px solid transparent; }
    .success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; }
    .error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; }

    @media screen and (max-width: 768px) {
        .responsive-table thead { display: none; }
        .responsive-table, .responsive-table tbody, .responsive-table tr, .responsive-table td { display: block; width: 100%; }
        .responsive-table tr { background: #fff; border: 1px solid #ddd; border-radius: 10px; margin-bottom: 15px; padding: 15px; box-sizing: border-box; }
        .responsive-table td { padding: 8px 0; border: none; display: flex; justify-content: space-between; align-items: center; }
        .responsive-table td:before { content: attr(data-label); font-weight: 600; margin-right: 10px; color: #333; }
        .responsive-table td.user-info-cell { display: flex; align-items: center; justify-content: flex-start; padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid #eee; }
        .responsive-table td.user-info-cell:before { display: none; }
        .responsive-table td.user-info-cell .user-details { display: flex; flex-direction: column; }
        .responsive-table td.user-info-cell .user-details strong { font-size: 1.1em; }
    }
</style>

<h2><i class="fas fa-users"></i> User Management</h2>

<?php
// সেশন থেকে মেসেজ দেখানো
if (isset($_SESSION['message'])) {
    echo $_SESSION['message'];
    unset($_SESSION['message']); // মেসেজটি দেখানোর পর সেশন থেকে মুছে ফেলা
}
?>

<div class="table-container">
    <div class="search-bar">
        <form method="GET" action="" style="display: contents;">
            <input type="text" name="search" placeholder="Search by Name, Username, or Chat ID..." value="<?php echo htmlspecialchars($search_query); ?>">
            <button type="submit" class="btn">Search</button>
        </form>
    </div>

    <table class="responsive-table">
        <thead>
            <tr>
                <th>User</th>
                <th>Chat ID</th>
                <th>Balance</th>
                <th>Joined On</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($users && $users->num_rows > 0): ?>
                <?php while($user = $users->fetch_assoc()): ?>
                <tr>
                    <td data-label="User" class="user-info-cell">
                        <img src="<?php echo htmlspecialchars($user['profile_photo_url'] ?? 'default_avatar.png'); ?>" alt="Avatar" class="profile-pic">
                        <div class="user-details">
                            <strong><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></strong>
                            <span>@<?php echo htmlspecialchars($user['username'] ?? 'N/A'); ?></span>
                        </div>
                    </td>
                    <td data-label="Chat ID"><?php echo $user['chat_id']; ?></td>
                    <td data-label="Balance"><?php echo number_format($user['total_balance'], 2); ?> SHIB</td>
                    <td data-label="Joined On"><?php echo date("d M, Y", strtotime($user['created_at'])); ?></td>
                    <td data-label="Actions">
                        <a href="edit_user.php?id=<?php echo $user['id']; ?>" class="action-btn btn-edit">Edit</a>
                        <a href="users.php?action=delete&id=<?php echo $user['id']; ?>" class="action-btn btn-delete" 
                           onclick="return confirm('Are you sure you want to delete this user permanently? This cannot be undone.')">
                            Delete
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="5" style="text-align: center;">No users found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

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