<?php
/**
*  @author    WebDigify
*  @copyright 2015-2017 WebDigify. All Rights Reserved.
*  @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/

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

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;

require_once(_PS_MODULE_DIR_.'wdcompare/classes/CompareProduct.php');

class Wdcompare extends Module
{
    private $templateFile;
    private $link;

    public function __construct()
    {
        $this->name = 'wdcompare';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'WebDigify';
        $this->controllers = array('compare');
        $this->bootstrap = true;
        $this->need_instance = 0;

        parent::__construct();

        $this->displayName = $this->l('WD - Compare Products');
        $this->description = $this->l('Adds Product Compare function to store.');

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

        $this->link = $this->context->link;

        $this->templateFile = 'module:wdcompare/views/templates/hook/wdcompare.tpl';
    }

    public function install()
    {
        $this->createTables();

        Configuration::updateValue('WDCOMPARATOR_ENABLE', 1);
        Configuration::updateValue('WDCOMPARATOR_PRODUCTLIST', 1);
        Configuration::updateValue('WDCOMPARATOR_PRODUCTPAGE', 1);
        Configuration::updateValue('WDCOMPARATOR_HEADER', 1);
        Configuration::updateValue('WDCOMPARATOR_MAXITEM', '3');

        return parent::install()
            && $this->registerHook('displaywdcompareButton')
            && $this->registerHook('displaywdcompareHeader')
            && $this->registerHook('displaywdcompare')
            && $this->registerHook('displayHeader');
    }

    public function uninstall()
    {
        $this->deleteTables();

        Configuration::deleteByName('WDCOMPARATOR_ENABLE');
        Configuration::deleteByName('WDCOMPARATOR_PRODUCTLIST');
        Configuration::deleteByName('WDCOMPARATOR_PRODUCTPAGE');
        Configuration::deleteByName('WDCOMPARATOR_HEADER');
        Configuration::deleteByName('WDCOMPARATOR_MAXITEM');

        return parent::uninstall();
    }

    protected function createTables()
    {
        $res = (bool)Db::getInstance()->execute('
            CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'wdcompare` (
            `id_compare` int(10) unsigned NOT NULL AUTO_INCREMENT,
            `id_customer` int(10) unsigned NOT NULL,
            PRIMARY KEY (`id_compare`)
            ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
        ');

        $res &= Db::getInstance()->execute('
            CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'wdcompare_product` (
            `id_compare` int(10) unsigned NOT NULL,
            `id_product` int(10) unsigned NOT NULL,
            `date_add` datetime NOT NULL,
            `date_upd` datetime NOT NULL,
            PRIMARY KEY (`id_compare`, `id_product`)
            ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
        ');

        return $res;
    }

    protected function deleteTables()
    {
        return Db::getInstance()->execute('
            DROP TABLE IF EXISTS `'._DB_PREFIX_.'wdcompare`, `'._DB_PREFIX_.'wdcompare_product`;
        ');
    }

    public function getContent()
    {
        return $this->postProcess().$this->renderForm();
    }

    protected function renderForm()
    {
        $helper = new HelperForm();

        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->module = $this;
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitwdcompare';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');

        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFormValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );

        return $helper->generateForm(array($this->getConfigForm()));
    }

    protected function getConfigForm()
    {
        return array(
            'form' => array(
                'legend' => array(
                    'title' => $this->l('Settings'),
                    'icon' => 'icon-cogs',
                ),
                'input' => array(
                    array(
                        'type' => 'switch',
                        'label' => $this->l('Enable Product Comparison'),
                        'name' => 'WDCOMPARATOR_ENABLE',
                        '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('Display Compare Button in Product List'),
                        'name' => 'WDCOMPARATOR_PRODUCTLIST',
                        '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('Display Compare Button in Product Page'),
                        'name' => 'WDCOMPARATOR_PRODUCTPAGE',
                        '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('Display Compare Link in Header'),
                        'name' => 'WDCOMPARATOR_HEADER',
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => 1,
                                'label' => $this->l('Enabled'),
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => 0,
                                'label' => $this->l('Disabled'),
                            ),
                        ),
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Product comparison'),
                        'validation' => 'isUnsignedId',
                        'name' => 'WDCOMPARATOR_MAXITEM',
                        'required' => true,
                        'cast' => 'intval',
                        'hint' => $this->l('Set the maximum number of products that can be selected for comparison. Set to "0" to disable this feature.'),
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                ),
            ),
        );
    }

    protected function getConfigFormValues()
    {
        $data = array(
            'WDCOMPARATOR_ENABLE' => Tools::getValue('WDCOMPARATOR_ENABLE', Configuration::get('WDCOMPARATOR_ENABLE')),
            'WDCOMPARATOR_PRODUCTLIST' => Tools::getValue('WDCOMPARATOR_PRODUCTLIST', Configuration::get('WDCOMPARATOR_PRODUCTLIST')),
            'WDCOMPARATOR_PRODUCTPAGE' => Tools::getValue('WDCOMPARATOR_PRODUCTPAGE', Configuration::get('WDCOMPARATOR_PRODUCTPAGE')),
            'WDCOMPARATOR_HEADER' => Tools::getValue('WDCOMPARATOR_HEADER', Configuration::get('WDCOMPARATOR_HEADER')),
            'WDCOMPARATOR_MAXITEM' => Tools::getValue('WDCOMPARATOR_MAXITEM', Configuration::get('WDCOMPARATOR_MAXITEM')),
        );
        return $data;
    }

    protected function postProcess()
    {
        if (((bool)Tools::isSubmit('submitwdcompare')) == true) {
            Configuration::updateValue('WDCOMPARATOR_ENABLE', (int)(Tools::getValue('WDCOMPARATOR_ENABLE')));
            Configuration::updateValue('WDCOMPARATOR_PRODUCTLIST', (int)(Tools::getValue('WDCOMPARATOR_PRODUCTLIST')));
            Configuration::updateValue('WDCOMPARATOR_PRODUCTPAGE', (int)(Tools::getValue('WDCOMPARATOR_PRODUCTPAGE')));
            Configuration::updateValue('WDCOMPARATOR_HEADER', (int)(Tools::getValue('WDCOMPARATOR_HEADER')));
            Configuration::updateValue('WDCOMPARATOR_MAXITEM', Tools::getValue('WDCOMPARATOR_MAXITEM'));
            $this->_clearCache($this->templateFile);
            return $this->displayConfirmation($this->l('The settings have been updated.'));
        }
        return '';
    }

    public function hookDisplayHeader()
    {
        if (Configuration::get('WDCOMPARATOR_ENABLE') && Configuration::get('WDCOMPARATOR_MAXITEM') > 0) {
            $this->context->controller->registerJavascript('module-compare', 'modules/'.$this->name.'/views/js/products-comparison.js', array('position' => 'bottom', 'priority' => 150));
            $this->context->controller->registerStylesheet('wdcompare', 'modules/'.$this->name.'/views/css/wdcompare.css');

            $compared_products = array();
            if (Configuration::get('WDCOMPARATOR_MAXITEM') && isset($this->context->cookie->id_compare)) {
                $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
            }
            
            $comparator_max_item = (int)Configuration::get('WDCOMPARATOR_MAXITEM');
            
            $productcompare_max_item = sprintf($this->l('You cannot add more than %d product(s) to the product comparison'), $comparator_max_item);
            Media::addJsDef(
                array(
                    'compareUrl' => $this->link->getModuleLink('wdcompare', 'compare'),
                    'compareAdd' => $this->l('The product has been added to product comparison'),
                    'compareRemove' => $this->l('The product has been removed from the product comparison.'),
                    'compareView' => $this->l('Compare'),
                    'comparedProductsIds' => ($compared_products != NULL && count($compared_products)>0) ? $compared_products : array(),
                    'comparator_max_item' => $comparator_max_item,
                    'compared_products' => ($compared_products != NULL && count($compared_products)>0) ? $compared_products : array(),
                    'max_item' => $productcompare_max_item,
                )
            );
        }
    }

    public function hookDisplaywdcompareButton($params)
    {
        if (Configuration::get('WDCOMPARATOR_ENABLE') && Configuration::get('WDCOMPARATOR_MAXITEM') > 0) {
            $page_name = Dispatcher::getInstance()->getController();
            if ((Configuration::get('WDCOMPARATOR_PRODUCTLIST') && $page_name != 'product') || (Configuration::get('WDCOMPARATOR_PRODUCTPAGE') && $page_name == 'product')) {
                $id_product = $params['product']['id_product'];
                $compared_products = array();
                if (Configuration::get('WDCOMPARATOR_MAXITEM') && isset($this->context->cookie->id_compare)) {
                    $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
                }
                $added = false;
                if ($compared_products != NULL && count($compared_products) > 0 && in_array($id_product, $compared_products)) {
                    $added = true;
                }
                $this->smarty->assign(array(
                    'added' => $added,
                    'id_product' => $id_product,
                ));
                return $this->display(__FILE__, 'wdcompare-button.tpl');
            }
        }
    }

    public function hookDisplaywdcompare($params)
    {
        if (Configuration::get('WDCOMPARATOR_ENABLE') && Configuration::get('WDCOMPARATOR_MAXITEM') > 0) {
            $compared_products = array();
            if (Configuration::get('WDCOMPARATOR_MAXITEM') && isset($this->context->cookie->id_compare)) {
                $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
            }

            $this->smarty->assign(array(
                'compareUrl' => $this->link->getModuleLink('wdcompare', 'compare'),
                'compared_products'   => is_array($compared_products) ? $compared_products : array(),
                'comparator_max_item' => Configuration::get('WDCOMPARATOR_MAXITEM'),
            ));

            return ($this->display(__FILE__, 'product-compare.tpl'));
        }
    }

    public function hookDisplaywdcompareHeader($params)
    {
        if (Configuration::get('WDCOMPARATOR_ENABLE') && Configuration::get('WDCOMPARATOR_HEADER') && Configuration::get('WDCOMPARATOR_MAXITEM') > 0) {
            $compared_products = array();
            if (Configuration::get('WDCOMPARATOR_MAXITEM') && isset($this->context->cookie->id_compare)) {
                $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
            }

            $this->smarty->assign(array(
                'compareUrl' => $this->link->getModuleLink('wdcompare', 'compare'),
                'compared_products'   => is_array($compared_products) ? $compared_products : array(),
                'comparator_max_item' => Configuration::get('WDCOMPARATOR_MAXITEM'),
            ));

            return ($this->display(__FILE__, 'product-compare-header.tpl'));
        }
    }

    public function prepareVariables()
    {
        return array(
            'WDCOMPARATOR_ENABLE' => (int)Configuration::get('WDCOMPARATOR_ENABLE'),
            'WDCOMPARATOR_PRODUCTLIST' => (int)Configuration::get('WDCOMPARATOR_PRODUCTLIST'),
            'WDCOMPARATOR_PRODUCTPAGE' => (int)Configuration::get('WDCOMPARATOR_PRODUCTPAGE'),
            'WDCOMPARATOR_HEADER' => (int)Configuration::get('WDCOMPARATOR_HEADER'),
            'WDCOMPARATOR_MAXITEM' => Configuration::get('WDCOMPARATOR_MAXITEM'),
        );
    }
}
