<?php
/**
*
* @author     Patryk Marek <info@prestadev.pl>
* @copyright  2013 - 2017 Patryk Marek
* @link       http://prestadev.pl
* @package    Product attributes list for PrestaShop 1.5.x and 1.6.x and 1.7.x
* @version    1.0.3
* @license    Do not edit, modify or copy this file, if you wish to customize it, contact us at info@prestadev.pl
* @date       28-10-2017
*
*/

class PdProductAttributesListAjaxModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        $this->ajax = true;
        parent::initContent();
    }

    public function displayAjax()
    {
        $this->createCart();
    }

    public function createCart()
    {
        $module = new PdProductAttributesList();
        if (Tools::getValue('secure_key') == $module->secure_key) {
            $action = Tools::getValue('action');
            if ($action == 'addProductsToCart') {
                $products = (array)Tools::getValue('products');
                $context = Context::getContext();
                if ((int)$context->cart->id == 0) {
                    $cart = new Cart();
                    $cart->id_currency = $this->context->currency->id;
                    $cart->add();
                    $context->cart = $cart;
                    $context->cookie->id_cart = $cart->id;
                    $context->cookie->write();
                } else {
                    $cart = $context->cart;
                }

                $result = false;
                if (is_array($products) && sizeof($products)) {
                    $n = 0;
                    $res = [];
                    foreach ($products as $p) {
                        $product =  new Product($p['id_product'], false, $this->context->language->id, $this->context->shop->id);
                        $n++;
                        $res[$n]['response'] = $this->context->cart->updateQty(
                            $p['quantity'],
                            $p['id_product'],
                            $p['id_product_attribute'],
                            $p['id_customization']
                        );
                        $res[$n]['id_product'] = $p['id_product'];
                        $res[$n]['id_product_attribute'] = $p['id_product_attribute'];
                        $res[$n]['quantity'] = $p['quantity'];
                        $res[$n]['product_name'] = $product->name;
                        $res[$n]['max_quantity'] = StockAvailable::getQuantityAvailableByProduct($p['id_product'], $p['id_product_attribute'], $this->context->shop->id);
                        $res[$n]['combination_name'] = $this->getAttributeCombinationsFullNameById($p['id_product'], $p['id_product_attribute'], $this->context->language->id, true);
                    }
                    $result = [true];
                }

                die(json_encode($res));
            }
        }
    }

    public function getAttributeCombinationsFullNameById($id_product, $id_product_attribute, $id_lang, $groupByIdAttributeGroup = true)
    {
        if (!Combination::isFeatureActive()) {
            return [];
        }


        $sql = 'SELECT CONCAT(agl.`name`, al.`name`) AS combination_name, agl.`name` AS group_name, al.`name` AS attribute_name,
                    a.`id_attribute`, a.`position`
                FROM `' . _DB_PREFIX_ . 'product_attribute` pa
                ' . Shop::addSqlAssociation('product_attribute', 'pa') . '
                LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute`
                LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute`
                LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
                LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int) $id_lang . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int) $id_lang . ')
                WHERE pa.`id_product` = ' . (int) $id_product . '
                AND pa.`id_product_attribute` = ' . (int) $id_product_attribute . '
                GROUP BY pa.`id_product_attribute`' . ($groupByIdAttributeGroup ? ',ag.`id_attribute_group`' : '') . '
                ORDER BY pa.`id_product_attribute`';

        $res = Db::getInstance()->executeS($sql);
        $combination_name = '';
        foreach ($res as $key => $row) {
            $combination_name .= $row['group_name'] . ': '.$row['attribute_name'].', ';
        }

        if (empty($combination_name)) {
            $module = new PdProductAttributesList();
            return $module->l('No variant');
        } else {
            return rtrim($combination_name, ', ');
        }
    }
}
