    //Function lấy tất cả bill theo hàng hoá 
    public function getAllBillByHangHoa($data) { 

        $limit = 15;
        // Thêm ?? 1 để tránh lỗi nếu không truyền lên param page
        $page  = max(1, (int)($data["page"] ?? 1));
        $skip  = ($page - 1) * $limit;

        // Chuyển ID hàng hoá sang dạng ObjectId
        $hangHoaId = new MongoDB\BSON\ObjectId($data["id_hang_hoa"]);
        $hangHoaIdStr = (string) $data["id_hang_hoa"]; // Lấy chuỗi để so sánh lúc tính toán

        // ===== 1. FILTER =====
        $filter = [
            'status' => 'done', // Status luôn là done
            // Tìm các bill mà trong mảng hàng hoá có chứa id_hang_hoa này
            'hang_hoa_bill_tong.id_hang_hoa' => $hangHoaId 
        ];

        // ===== 2. LỌC THEO THỜI GIAN =====
        if (!empty($data["start_date"]) || !empty($data["end_date"])) {
            $timeFilter = [];
            
            if (!empty($data["start_date"])) {
                // Convert chuỗi ngày sang MongoDB\BSON\UTCDateTime (00:00:00)
                $timeFilter['$gte'] = TimeHelper::convertTimeToObject($data["start_date"] . " 00:00:00");
            }
            
            if (!empty($data["end_date"])) {
                // Convert chuỗi ngày sang MongoDB\BSON\UTCDateTime (23:59:59)
                $timeFilter['$lte'] = TimeHelper::convertTimeToObject($data["end_date"] . " 23:59:59");
            }
            
            $filter['created_time'] = $timeFilter;
        }

        $pipeline = [
            ['$match' => $filter],

            // Lookup chi nhánh để lấy tên chi nhánh hiển thị
            ['$lookup' => [
                'from' => 'chi_nhanh',
                'localField' => 'id_chi_nhanh',
                'foreignField' => '_id',
                'as' => 'cn'
            ]],
            ['$unwind' => ['path' => '$cn', 'preserveNullAndEmptyArrays' => true]],

            // Lookup khách hàng để lấy tên khách hàng
            ['$lookup' => [
                'from' => 'khach_hang',
                'localField' => 'id_khach_hang',
                'foreignField' => '_id',
                'as' => 'kh'
            ]],
            ['$unwind' => ['path' => '$kh', 'preserveNullAndEmptyArrays' => true]],

            ['$sort' => ['created_time' => -1]],
            ['$skip' => $skip],
            ['$limit' => $limit],

            ['$project' => [
                '_id'                => 1,
                'ten_nhan_vien'      => 1,
                'ten_chi_nhanh'      => '$cn.ten_chi_nhanh',
                'ten_khach_hang'     => '$kh.ten_khach_hang',
                'id_khach_hang'      => 1,
                'created_time'       => 1,
                'tong_tien_bill'     => 1,
                'hang_hoa_bill_tong' => 1, // BẮT BUỘC PHẢI LẤY RA ĐỂ TÍNH LỢI NHUẬN
                'ghi_chu'            => 1,
            ]]
        ];

        $items = iterator_to_array($this->collection->aggregate($pipeline));

        // ===== 3. TÍNH TOÁN LỢI NHUẬN =====
        // Duyệt qua từng bill lấy được để gắn thêm field `loi_nhuan` vào món hàng
        foreach ($items as &$bill) {
            $tong_loi_nhuan_cua_hang_hoa_nay = 0; // Đếm tổng lợi nhuận của sp này trong bill (phòng trường hợp trùng ID)

            if (!empty($bill['hang_hoa_bill_tong'])) {
                // Ép kiểu về array để dễ thao tác (nếu $bill đang là BSON Document)
                $bill['hang_hoa_bill_tong'] = json_decode(json_encode($bill['hang_hoa_bill_tong']), true);

                foreach ($bill['hang_hoa_bill_tong'] as &$hh) {
                    // Lấy ID hiện tại của món hàng an toàn
                    $currentId = isset($hh['id_hang_hoa']['$oid']) ? $hh['id_hang_hoa']['$oid'] : (string)$hh['id_hang_hoa'];

                    // Chỉ tính lợi nhuận cho đúng mặt hàng đang được filter
                    if ($currentId === $hangHoaIdStr) {
                        $gia_ban = isset($hh['gia_ban']) ? (float)$hh['gia_ban'] : 0;
                        $don_gia_goc = isset($hh['don_gia_goc']) ? (float)$hh['don_gia_goc'] : 0;
                        $chiet_khau = isset($hh['chiet_khau']) ? (float)$hh['chiet_khau'] : 0;
                        $chi_phi_khac = isset($hh['chi_phi_khac']) ? (float)$hh['chi_phi_khac'] : 0;
                        $so_luong = isset($hh['so_luong']) ? (int)$hh['so_luong'] : 1;
                        $chiet_khau_type = isset($hh['chiet_khau_type']) ? $hh['chiet_khau_type'] : 'amount';

                        $loi_nhuan = 0;
                        // Tính toán theo công thức
                        if ($chiet_khau_type === 'percent') {
                            $loi_nhuan = ($gia_ban - ($gia_ban * $chiet_khau / 100) - $don_gia_goc - $chi_phi_khac) * $so_luong;
                        } else {
                            $loi_nhuan = ($gia_ban - $don_gia_goc - $chiet_khau - $chi_phi_khac) * $so_luong;
                        }

                        // Gắn thêm field vào item hàng hoá
                        $hh['loi_nhuan'] = $loi_nhuan;
                        $tong_loi_nhuan_cua_hang_hoa_nay += $loi_nhuan;
                    }
                }
            }
            
            // (Tuỳ chọn) Bạn có thể gắn thẳng tổng lợi nhuận của SP này ra ngoài root của bill để FE dễ hiển thị
            $bill['loi_nhuan'] = $tong_loi_nhuan_cua_hang_hoa_nay;
        }
        unset($bill, $hh); // Xoá tham chiếu để an toàn bộ nhớ

        // ===== 4. ĐẾM TỔNG =====
        $countResult = iterator_to_array(
            $this->collection->aggregate([
                ['$match' => $filter],
                ['$count' => 'total']
            ])
        );

        $totalItems = $countResult[0]['total'] ?? 0;
        $totalPages = (int)ceil($totalItems / $limit);

        return [
            "list_bill"  => JSONHelper::removeOid($items),
            "pagination" => [
                "page"        => $page,
                "total_items" => $totalItems,
                "total_pages" => $totalPages
            ]
        ];
    }