<?php
/**
* @author      Krzysztof Pecak
* @copyright   2017 Krzysztof Pecak
* @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
use PrestaShop\PrestaShop\Adapter\Manufacturer\ManufacturerProductSearchProvider;
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;

class AngarManproduct extends Module
{
    public function __construct()
    {
        $this->name = 'angarmanproduct';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'AngarThemes';
        $this->spacer_size ='4';
        $this->need_instance = 0;


        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('AT - Manufacturer');
        $this->description = $this->l('Displays products from selected manufacturers in left column');

        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
    }

    public function install()
    {
        return parent::install()
            && Configuration::updateValue('AT_MANPRODUCT_ID', implode(',', array(1)))
            && Configuration::updateValue('AT_MANPRODUCT_LIMIT', '8')
            && Configuration::updateValue('AT_MANPRODUCT_VISIBLE', '4')
            && Configuration::updateValue('AT_MANPRODUCT_MOVE', '1')
            && Configuration::updateValue('AT_MANPRODUCT_LOOP', '0')
            && Configuration::updateValue('AT_MANPRODUCT_AUTO', '0')
            && Configuration::updateValue('AT_MANPRODUCT_PAUSE', '3000')
            && $this->registerHook('displayLeftColumn')
            && $this->registerHook('displayBeforeBodyClosingTag')
            && $this->registerHook('displayHeader')
            && $this->disableDevice(Context::DEVICE_MOBILE);
    }

    public function uninstall()
    {
        // Delete configuration
        return Configuration::deleteByName('AT_MANPRODUCT_ID')
        && Configuration::deleteByName('AT_MANPRODUCT_LIMIT')
        && Configuration::deleteByName('AT_MANPRODUCT_VISIBLE')
        && Configuration::deleteByName('AT_MANPRODUCT_MOVE')
        && Configuration::deleteByName('AT_MANPRODUCT_LOOP')
        && Configuration::deleteByName('AT_MANPRODUCT_AUTO')
        && Configuration::deleteByName('AT_MANPRODUCT_PAUSE')
        && parent::uninstall();
    }

    public function hookDisplayHeader($params)
    {
        $this->context->controller->addCSS(($this->_path).'views/css/at_manproduct.css', 'all');
    }

    public function hookDisplayLeftColumn($params)
    {

        $manSelected = Configuration::get('AT_MANPRODUCT_ID');		
        $manuArray = explode(',', $manSelected);
        $arrayMan = array();

        $id_lang = (int) Context::getContext()->language->id;
        $id_shop = (int) Context::getContext()->shop->id;
        $arrayManProduct = array();
        foreach ($manuArray as $id_manufacturer) {
            $manufacturer = new Manufacturer((int)$id_manufacturer);
            $manufacturer->link_rewrite = Tools::link_rewrite($manufacturer->name);
            $products = $this->getProducts($id_manufacturer);
			$arrayManProduct[] = array('id' => $id_manufacturer, 'name'=> $manufacturer->name, 'product' => $products);
        }

        //if (!$this->isCached('views/templates/front/at_manproduct.tpl', $this->getCacheId())) {
            $this->smarty->assign(array(
                'manProducts' => $arrayManProduct
            ));
        //}

        //return $this->display(__FILE__, 'views/templates/front/at_manproduct.tpl', $this->getCacheId());
		return $this->display(__FILE__, 'views/templates/front/at_manproduct.tpl');
    }
	
	protected function getProducts($id_manufacturer)
    {
        $manufacturer = new Manufacturer($id_manufacturer);

        $searchProvider = new ManufacturerProductSearchProvider(
            $this->context->getTranslator(),
            $manufacturer
        );

        $context = new ProductSearchContext($this->context);

        $query = new ProductSearchQuery();

        $nProducts = Configuration::get('AT_MANPRODUCT_LIMIT');
        if ($nProducts < 0) {
            $nProducts = 12;
        }

        $query
            ->setResultsPerPage($nProducts)
            ->setPage(1)
        ;

        if (Configuration::get('HOME_FEATURED_RANDOMIZE')) {
            $query->setSortOrder(SortOrder::random());
        } else {
            $query->setSortOrder(new SortOrder('product', 'position', 'asc'));
        }

        $result = $searchProvider->runQuery(
            $context,
            $query
        );

        $assembler = new ProductAssembler($this->context);

        $presenterFactory = new ProductPresenterFactory($this->context);
        $presentationSettings = $presenterFactory->getPresentationSettings();
        $presenter = new ProductListingPresenter(
            new ImageRetriever(
                $this->context->link
            ),
            $this->context->link,
            new PriceFormatter(),
            new ProductColorsRetriever(),
            $this->context->getTranslator()
        );

        $products_for_template = [];

        foreach ($result->getProducts() as $rawProduct) {
            $products_for_template[] = $presenter->present(
                $presentationSettings,
                $assembler->assembleProduct($rawProduct),
                $this->context->language
            );
        }

        return $products_for_template;
    }

    public function hookDisplayBeforeBodyClosingTag($params)
    {
        if (!$this->isCached('views/templates/front/at_manproduct_script.tpl', $this->getCacheId())) {
            $this->smarty->assign(array(
                'visible' => Configuration::get('AT_MANPRODUCT_VISIBLE'),
                'move' => Configuration::get('AT_MANPRODUCT_MOVE'),
                'loop' => Configuration::get('AT_MANPRODUCT_LOOP'),
                'auto' => Configuration::get('AT_MANPRODUCT_AUTO'),
                'pause' => Configuration::get('AT_MANPRODUCT_PAUSE')
            ));
        }

        return $this->display(__FILE__, 'views/templates/front/at_manproduct_script.tpl', $this->getCacheId());
    }

    public function getContent()
    {
        $html = '';
        // If we try to update the settings
        if (Tools::isSubmit('submitModule')) {
            Configuration::updateValue('AT_MANPRODUCT_ID', implode(',', Tools::getValue('at_manproduct_id')));
            Configuration::updateValue('AT_MANPRODUCT_LIMIT', Tools::getValue('at_manproduct_limit'));
            Configuration::updateValue('AT_MANPRODUCT_VISIBLE', Tools::getValue('at_manproduct_visible'));
            Configuration::updateValue('AT_MANPRODUCT_MOVE', Tools::getValue('at_manproduct_move'));
            Configuration::updateValue('AT_MANPRODUCT_LOOP', Tools::getValue('at_manproduct_loop'));
            Configuration::updateValue('AT_MANPRODUCT_AUTO', Tools::getValue('at_manproduct_auto'));
            Configuration::updateValue('AT_MANPRODUCT_PAUSE', Tools::getValue('at_manproduct_pause'));
            $this->_clearCache('views/templates/front/at_manproduct.tpl');
            $this->_clearCache('views/templates/front/at_manproduct_script.tpl');
            $html .= $this->displayConfirmation($this->l('Configuration updated'));
        }

        $html .= $this->renderForm();

        return $html;
    }

    private function getManufacturerOption($id_lang = false)
    {
        $id_lang = $id_lang ? (int) $id_lang : (int) Context::getContext()->language->id;
        $data = Manufacturer::getManufacturers(true, $id_lang, true, false, false, false);
        $manuCurrent = Configuration::get('AT_MANPRODUCT_ID');
        $manuCurrent = explode(',', $manuCurrent);
        
        foreach ($data as &$item) {			
            $this->man_array[] = array("key"=>(int) $item['id_manufacturer'], "name"=>$item['name']);			
        }
    }

    public $man_array;
    
    public function renderForm()
    {
		$this->man_array = array();
        $this->getManufacturerOption((int)Context::getContext()->language->id, (int)Context::getContext()->shop->id);
        //print_r($this->man_array);
        
        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->l('Settings'),
                    'icon' => 'icon-cogs'
                ),
                'description' => $this->l('This module displays products from the manufacturer on the home page.'),

                'description' => $this->l('This module displays products from the manufacturer on the home page.').'<br/>'.
                        $this->l('Tip: If "Inifinite loop" does not work properly add more products to the manufacturer.'),
                'input' => array(

                    array(
                        'label' => $this->l('Select manufacturers:'),
                        'desc'     => $this->l('Press ctrl to select several manufacturers'),
                        'type' => 'select',
                        'name' => 'at_manproduct_id[]',
                        'multiple' => true,
                        'size' => 12,
                        'options' => array(
                            'query' => $this->man_array,
                            'id' => 'key',
                            'name' => 'name'
                        )
                    ),

                    array(
                        'type' => 'text',
                        'class'    => 'fixed-width-xl',
                        'label' => $this->l('Products quantity:'),
                        'name' => 'at_manproduct_limit',
                    ),

                    array(
                        'type' => 'text',
                        'class'    => 'fixed-width-xl',
                        'label' => $this->l('Products visible:'),
                        'name' => 'at_manproduct_visible',
                    ),

                    array(
                        'type' => 'text',
                        'class'    => 'fixed-width-xl',
                        'label' => $this->l('Products moved by click:'),
                        'name' => 'at_manproduct_move',
                    ),

                    array(
                        'type' => 'text',
                        'class'    => 'fixed-width-xl',
                        'label' => $this->l('Pause (milliseconds):'),
                        'name' => 'at_manproduct_pause',
                    ),

                    array(
                        'type' => 'switch',
                        'desc'     => $this->l('In the manufacturer must be more than 4 products or this option will not work properly'),
                        'label' => $this->l('Infinite loop:'),
                        'name' => 'at_manproduct_loop',
                        'is_bool' => true,
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => 1,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => 0,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),

                    array(
                        'type' => 'switch',
                        'label' => $this->l('Auto start:'),
                        'name' => 'at_manproduct_auto',
                        'is_bool' => true,
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => 1,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => 0,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),

                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                )
            ),
        );

        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
        $helper->default_form_language = $lang->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $this->fields_form = array();

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitModule';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );

        return $helper->generateForm(array($fields_form));
    }

    public function getConfigFieldsValues()
    {
        return array(
            'at_manproduct_id[]' => Tools::getValue('at_manproduct_id', explode(',', Configuration::get('AT_MANPRODUCT_ID'))),
            'at_manproduct_limit' => Tools::getValue('at_manproduct_limit', Configuration::get('AT_MANPRODUCT_LIMIT')),
            'at_manproduct_visible' => Tools::getValue('at_manproduct_visible', Configuration::get('AT_MANPRODUCT_VISIBLE')),
            'at_manproduct_move' => Tools::getValue('at_manproduct_move', Configuration::get('AT_MANPRODUCT_MOVE')),
            'at_manproduct_loop' => Tools::getValue('at_manproduct_loop', Configuration::get('AT_MANPRODUCT_LOOP')),
            'at_manproduct_auto' => Tools::getValue('at_manproduct_auto', Configuration::get('AT_MANPRODUCT_AUTO')),
            'at_manproduct_pause' => Tools::getValue('at_manproduct_pause', Configuration::get('AT_MANPRODUCT_PAUSE')),
        );
    }
}
