<?php
// FILE NÀY: banhang/mobile_views/customers.php
$is_selection_mode = isset($_GET['select']) && $_GET['select'] === 'true';

if (!isset($danh_sach_khach_hang)) {
     // (MỚI) Dùng query thật từ CSDL (từ file pos_ajax.php)
     $stmt = $conn->prepare("SELECT c.ID, c.customer_name, c.customer_phone, c.customer_addr, c.customer_code, c.customer_group,
                                   SUM(o.total_money) AS total_mua, SUM(o.lack) AS total_no 
                            FROM cms_customers c 
                            LEFT JOIN cms_orders o ON c.ID = o.customer_id AND o.deleted = 0 
                            GROUP BY c.ID ORDER BY c.customer_name ASC");
     $stmt->execute();
     $result = $stmt->get_result();
     $danh_sach_khach_hang = $result->fetch_all(MYSQLI_ASSOC);
     $stmt->close();
}
?>

<?php if (!$is_selection_mode): ?>
    <a href="#" class="fab">
        <i class="fa-solid fa-plus"></i>
    </a>
<?php endif; ?>

<div class="filter-bar">
    <div class="search-box">
        <i class="fa-solid fa-search"></i>
        <input type="text" id="customer-search-input" placeholder="Tìm tên, SĐT khách hàng...">
    </div>
</div>

<div class="list-container" id="customer-list-container">
    <?php foreach ($danh_sach_khach_hang as $kh): ?>
        <?php
            $customer_json_data = htmlspecialchars(json_encode([
                'id' => $kh['ID'],
                'name' => $kh['customer_name'],
                'group' => $kh['customer_group'] ?? 1
            ]), ENT_QUOTES, 'UTF-8');
            
            // Dữ liệu để tìm kiếm
            $search_data = strtolower($kh['customer_name'] . $kh['customer_phone']);
        ?>
        <div class="list-card customer-card-item" data-search="<?php echo htmlspecialchars($search_data); ?>">
            <div class="list-card-header">
                <i class="fa-solid fa-user-circle customer-avatar"></i>
                <div class="list-card-title">
                    <span><?php echo htmlspecialchars($kh['customer_name']); ?></span>
                    <span class="sub-text"><?php echo htmlspecialchars($kh['customer_phone']); ?></span>
                </div>
                
                <?php if ($is_selection_mode): ?>
                    <button class="btn-select-customer" data-customer-json="<?php echo $customer_json_data; ?>">
                        Chọn
                    </button>
                <?php endif; ?>
            </div>
            <div class="list-card-body">
                <div class="list-stat-item">
                    <span class="label">Tổng mua</span>
                    <span class="value"><?php echo number_format($kh['total_mua'] ?? 0, 0, ',', '.'); ?> đ</span>
                </div>
                <div class="list-stat-item">
                    <span class="label">Còn nợ</span>
                    <span class="value <?php echo (($kh['total_no'] ?? 0) > 0) ? 'danger' : ''; ?>"><?php echo number_format($kh['total_no'] ?? 0, 0, ',', '.'); ?> đ</span>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php if ($is_selection_mode): ?>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // (MỚI) Xử lý chọn khách hàng
        document.querySelectorAll('.btn-select-customer').forEach(button => {
            button.addEventListener('click', function() {
                const customerData = JSON.parse(this.dataset.customerJson);
                localStorage.setItem('pos_customer', JSON.stringify(customerData));
                window.location.href = 'pos_mobile.php';
            });
        });

        // (MỚI) Xử lý live search
        const searchInput = document.getElementById('customer-search-input');
        const listContainer = document.getElementById('customer-list-container');
        const allCards = listContainer.querySelectorAll('.customer-card-item');

        function normalizeText(text) {
            return text.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
        }

        searchInput.addEventListener('keyup', function() {
            const searchTerm = normalizeText(this.value);
            
            allCards.forEach(card => {
                const searchData = card.dataset.search.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
                if (searchData.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });
</script>
<?php endif; ?>