<?php

// Параметры:
/** @var int $f_Component_ID */
/** @var int $f_Item_ID */
$component_id = (int)$f_Component_ID;
$item_ids = join(', ', array_map('intval', (array)$f_Item_ID));

$limit = 10;

$orders_table = (int)nc_netshop::get_instance()->get_setting('OrderComponentID');

$sql = "SELECT `Item_ID`, `Class_ID`, COUNT(`ID`) AS `Count` FROM `Netshop_RecentGoods`
         WHERE `User_ID` IN (
                    SELECT DISTINCT m.`User_ID`
                      FROM `Netshop_OrderGoods` AS `og`
                           INNER JOIN `Message{$orders_table}` AS `m`
                                   ON (og.`Order_Component_ID` = $orders_table
                                   AND m.`Message_ID` = og.`Order_ID`)
                     WHERE og.`Item_Type` = $component_id
                       AND og.`Item_ID` IN ($item_ids)
                       AND m.`User_ID` <> 0
              )
          AND NOT (`Class_ID` = $component_id AND `Item_ID` IN ($item_ids))
        GROUP BY `Item_ID`, `Class_ID`
        ORDER BY `Count` DESC LIMIT $limit";

$rows = (array)nc_db()->get_results($sql, ARRAY_A);

$goods = new nc_netshop_item_collection();
$goods->set_index_property('_ItemKey'); // обеспечит уникальность товаров в коллекции

foreach ($rows as $row) {
    try {
        $item = nc_netshop_item::by_id($row['Class_ID'], $row['Item_ID']);
        if (!$item['Sub_Class_ID']) { throw new Exception(''); } // seems that the item data is missing
        if ($item->has_parent()) { $item = $item['_Parent']; }
        $goods->add($item);
    }
    catch (Exception $e) {}
}

if (count($goods)) {
    echo '<div class="tpl-widget-netshop-viewed-together">',
         '<h2>Покупатели, которые выбрали этот товар, также смотрели</h2>',
         '<div class="tpl-block-list-objects">';

    foreach ($goods as $item) {
        echo nc_core::get_object()->widget->generate('netshop_item', array('Item' => $item));
    }

    echo '</div></div>';
}
