<?php

/**
 * Created by Aurélien RICHAUD (15/09/2016 09:03)
 */
class AdminCartRulesController extends AdminCartRulesControllerCore
{
    /**
     * @param int|string $productRuleGroupId
     * @param int|string $productRuleId
     * @param string $productRuleType
     * @param array<int|string> $selected
     *
     * @return false|string
     */
    public function getProductRuleDisplay(
        $productRuleGroupId,
        $productRuleId,
        $productRuleType,
        $selected = []
    ) {
        $context = \Context::getContext();

        \assert(null !== $context);

        $context->smarty->assign(
            [
                'product_rule_group_id' => (int) $productRuleGroupId,
                'product_rule_id' => (int) $productRuleId,
                'product_rule_type' => $productRuleType,
            ]
        );

        switch ($productRuleType) {
            case 'products':
                // Ajoute la référence à côté du nom dans les selecteurs de produits
                $products = ['selected' => [],
                    'unselected' => [], ];
                $results = \Db::getInstance()->executeS(
                    '
                SELECT DISTINCT CONCAT(name, " (", reference, ")") AS name, p.id_product as id
                FROM ' . _DB_PREFIX_ . 'product p
                LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
                    ON (p.`id_product` = pl.`id_product`
                        AND pl.`id_lang` = ' . (int) $context->language->id . \Shop::addSqlRestrictionOnLang('pl') . ')
                ' . \Shop::addSqlAssociation('product', 'p') . '
                WHERE id_lang = ' . (int) $context->language->id . '
                ORDER BY name'
                );
                if (!\is_array($results)) {
                    $results = [];
                }
                foreach ($results as $row) {
                    $products[in_array($row['id'], $selected) ? 'selected'
                        : 'unselected'][]
                        = $row;
                }
                $context->smarty->assign(
                    'product_rule_itemlist',
                    $products
                );
                $chooseContent = $this->createTemplate(
                    'product_rule_itemlist.tpl'
                )->fetch();
                $context->smarty->assign(
                    'product_rule_choose_content',
                    $chooseContent
                );
                break;
            case 'manufacturers':
            case 'suppliers':
            case 'categories':
            case 'attributes':
            default:
                return parent::getProductRuleDisplay(
                    $productRuleGroupId,
                    $productRuleId,
                    $productRuleType,
                    $selected
                );
        }

        return $this->createTemplate('product_rule.tpl')->fetch();
    }
}
