<?php
/**
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2018 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

require _PS_MODULE_DIR_.'/psmassedit/classes/MassEditActivity.php';
if (!defined('_PS_VERSION_')) {
    exit;
}

class Psmassedit extends Module
{
    public function __construct()
    {
        // Settings
        $this->name = 'psmassedit';
        $this->version = '1.2.0';
        $this->author = 'PrestaShop';
        $this->need_instance = 0;

        $this->module_key = 'd5ba409e2db819b65bd158a88bf5dfec';
        $this->author_address = '0x64aa3c1e4034d07015f639b0e171b0d7b27d01aa';

        $this->controller_name = 'AdminPsMassEdit';
        $this->controller_tab_name = 'AdminPsMassEditTab';

        // bootstrap -> always set to true
        $this->bootstrap = true;

        parent::__construct();

        $this->output = '';

        $this->displayName = $this->l('Product Bulk Edit');
        $this->description = $this->l('The Product Bulk Edit module allows you to apply a bulk change to products : change the price, the stock or add a new category. Configure these operations as permanent or scheduled to be applied and reversed on specific dates.');
        $this->ps_version = (bool)version_compare(_PS_VERSION_, '1.7', '>=');

        // Settings paths
        $this->js_path = $this->_path.'views/js/';
        $this->css_path = $this->_path.'views/css/';
        $this->img_path = $this->_path.'views/img/';
        $this->docs_path = $this->_path.'docs/';
        $this->logo_path = $this->_path.'logo.png';
        $this->module_path = $this->_path;

        // Confirm uninstall
        $this->confirmUninstall = $this->l('Are you sure you want to uninstall this module?');
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
        $this->tab = $this->name;
    }

    /**
     * install()
     *
     * @param none
     * @return bool
     */
    public function install()
    {
        // some stuff

        include(dirname(__FILE__).'/sql/install.php'); // sql querries

        $now = new \DateTime('now');
        \Configuration::updateValue('PS_MASS_EDIT_DATE_INSTALL', $now->format('Y-m-d H:i:s'));

        // register hook used by the module
        if (parent::install() && $this->installTab()) {
            return true;
        } else { // if something wrong return false
            $this->_errors[] = $this->l('There was an error during the uninstallation. Please contact us through Addons website.');
            return false;
        }
    }

    /**
     * uninstall()
     *
     * @param none
     * @return bool
     */
    public function uninstall()
    {
        include(dirname(__FILE__).'/sql/uninstall.php'); // sql querriers

        \Configuration::deleteByName('PS_MASS_EDIT_DATE_INSTALL');

        // unregister hook
        if (parent::uninstall() &&
            $this->uninstallTab()) {
            return true;
        } else {
            $this->_errors[] = $this->l('There was an error during the desinstallation. Please contact us through Addons website');
            return false;
        }
        return parent::uninstall();
    }

    /**
     * This method is often use to create an ajax controller
     *
     * @param none
     * @return bool
     */
    public function installTab()
    {
        $token = Tools::encrypt(microtime());
        Configuration::updateValue('PSMASSEDIT_CRON_TOKEN', $token);

        $catalog = Tab::getInstanceFromClassName('AdminCatalog');
        $tab = new Tab();
        $tab->active = 1;
        $tab->class_name = $this->controller_tab_name;
        $tab->name = array();
        foreach (Language::getLanguages(true) as $lang) {
            $tab->name[$lang['id_lang']] = $this->displayName;
        }
        $tab->id_parent = $catalog->id;
        $tab->module = $this->name;
        $result = $tab->add();

        if ($result === false) {
            return false;
        }

        if (!$this->ps_version) {
            $tab = new Tab();
            $tab->active = 0;
            $tab->class_name = $this->controller_name;
            $tab->name = array();
            foreach (Language::getLanguages(true) as $lang) {
                $tab->name[$lang['id_lang']] = $this->displayName;
            }
            $tab->id_parent = 0;
            $tab->module = $this->name;
            $result = $tab->add();
        }

        return $result;
    }

    /**
     * uninstall tab
     *
     * @param none
     * @return bool
     */
    public function uninstallTab()
    {
        Configuration::deleteByName('PSMASSEDIT_CRON_TOKEN');
        $id_tab = (int)Tab::getIdFromClassName($this->controller_tab_name);
        if ($id_tab) {
            $tab = new Tab($id_tab);
            if (Validate::isLoadedObject($tab)) {
                return ($tab->delete());
            } else {
                $return = false;
            }
        } else {
            $return = true;
        }

        return ($return);
    }

    /**
     * load dependencies
     */
    public function loadAsset()
    {
        $controller = Context::getContext()->controller;
        // Load CSS
        $css = array(
            $this->css_path.'font-awesome.min.css',
            $this->css_path.'faq.css',
            $this->css_path.'menu.css',
            $this->css_path.'back.css',
            $this->css_path.'select2.min.css',
            $this->css_path.'select2-bootstrap.min.css',
            $this->css_path.'sweetalert.css',
            $this->css_path.$this->name.'.css',
            $this->css_path.'datepicker.css',
            '//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css'
        );

        $this->context->controller->addCSS($css, 'all');

        // Load JS
        $jss = array(
            $this->js_path.'vue.min.js',
            $this->js_path.'vue-paginate.min.js',
            $this->js_path.'faq.js',
            $this->js_path.'menu.js',
            $this->js_path.'back.js',
            $this->js_path.'sweetalert.min.js',
            $this->js_path.'select2.full.min.js',
            //$this->js_path.'jquery-3.3.1.js',
            $this->js_path.'jquery.dataTables.min.js',
            _PS_ROOT_DIR_.'js/tiny_mce/tiny_mce.js',
            _PS_ROOT_DIR_.'js/admin/tinymce.inc.js',
            $this->context->controller->addJqueryUI('ui.datepicker'),
            '//cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js'
        );

        // prestashop plugin
        //$controller->addJqueryPlugin('select2');
        $controller->addJqueryPlugin('colorpicker');
        $controller->addJqueryUI('ui.sortable');


        $this->context->controller->addJS($jss);

        // Clean memory
        unset($jss, $css);
    }

    /**
     * FAQ API
     */
    public function loadFaq()
    {
        include_once('classes/APIFAQClass.php');
        $api = new APIFAQ();
        $faq = $api->getData($this->module_key, $this->version);
        return $faq;
    }

    /**
     * Load the configuration form
     */
    public function getContent()
    {
        $faq = $this->loadFaq();
        $this->loadAsset();

        // some stuff useful in smarty
        $context = Context::getContext();
        $id_lang = $this->context->language->id;
        $id_shop = $context->shop->id;
        if ($this->ps_version) {
            $params = array('configure' => $this->name);
            $moduleAdminLink = Context::getContext()->link->getAdminLink('AdminModules', true, false, $params);
        } else {
            $moduleAdminLink = Context::getContext()->link->getAdminLink('AdminModules', true).'&configure='.$this->name.'&module_name='.$this->name;
        }
        // controller ajax url
        $link = new Link();
        $controller_url = $link->getAdminLink($this->controller_name);

        $iso_lang = Language::getIsoById($id_lang);
        //get readme
        $doc = $this->docs_path.'readme_'.$iso_lang.'.pdf';

        //get tuto
        $tuto = $this->docs_path.'tuto/tuto_'.$iso_lang.'.pdf';


        // get current page
        $currentPage = 'conf';
        $page = Tools::getValue('page');
        if (!empty($page)) {
            $currentPage = Tools::getValue('page');
        }

        $AllCategs = Category::getCategories($id_lang, false);
        $AllActivity = MassEditActivity::getActivity($id_shop);

        $url_cron = (Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://'; // SSl or not
        $url_cron .= $this->context->shop->domain_ssl.__PS_BASE_URI__; // domain name + subdirectory
        $url_cron .= 'index.php?fc=module&module=psmassedit&controller=Cron&token='.configuration::get('PSMASSEDIT_CRON_TOKEN');

        $showRateModule = \DateTime::createFromFormat('Y-m-d H:i:s', \Configuration::get('PS_MASS_EDIT_DATE_INSTALL'));
        $now = new \DateTime('now');
        $numberOfDays = (int)$now->diff($showRateModule)->format('%a');
        $showRateModule = $numberOfDays > 7 && $numberOfDays < 92;

        // assign var to smarty
        $this->context->smarty->assign(array(
            'cron_url' => $url_cron,
            'Categories' => Category::getAllCategoriesName(null, $id_lang),
            'AllActivities' => $AllActivity,
            'AllCategs' => $AllCategs,
            'module_name' => $this->name,
            'id_shop' => $id_shop,
            'module_version' => $this->version,
            'moduleAdminLink' => $moduleAdminLink,
            'id_lang' => $id_lang,
            'psmassedit_controller_url' => $controller_url,
            'psmassedit_controller_name' => $this->controller_name,
            'apifaq' => $faq,
            'doc' => $doc,
            'tuto' => $tuto,
            'module_display' => $this->displayName,
            'module_path' => $this->module_path,
            'logo_path' => $this->logo_path,
            'img_path' => $this->img_path,
            'languages' => $this->context->controller->getLanguages(),
            'defaultFormLanguage' => (int) $this->context->employee->id_lang,
            'currentPage' => $currentPage,
            'products' => $this->getProducts(),
            'ps_base_dir' => _PS_BASE_URL_,
            'ps_version' => _PS_VERSION_,
            'isPs17' => $this->ps_version,
            'showRateModule' => $showRateModule,
            'currentLangIsoCode' => $this->context->language->iso_code,
            'img_path' => $this->_path.'views/img/',
        ));

        $this->output .= $this->context->smarty->fetch($this->local_path.'views/templates/admin/menu.tpl');

        return $this->output;
    }

    public function getProducts()
    {
        $id_lang = (int)Context::getContext()->language->id;
        $link = new Link();

        $products = Product::getProducts($id_lang, 0, 'all', 'name', 'ASC');

        $select2list = array();
        foreach ($products as $product) {
            $cover = Product::getCover($product['id_product']);
            $productCover = $link->getImageLink($product['name'], $product['id_product'].'-'.$cover['id_image']);
            array_push($select2list, array(
                'id_product' => $product['id_product'],
                'productName' => $product['name'],
                'imgUrl' => $productCover
            ));
        }

        return $select2list;
    }

    // load css and js in front -> ps17 only
    public function hookActionFrontControllerSetMedia()
    {
        if (version_compare(_PS_VERSION_, '1.7.0.0') >= 0) {
            $current_page = $this->context->controller->php_self;
            $currentCmsPage = 0;
            if ($current_page == 'cms') {
                $currentCmsPage = Context::getContext()->controller->cms->id_cms;
            }

            if ((Configuration::get('PS_INSTA_ON_PRODUCT_PAGE') && $current_page == 'product') ||
                (Configuration::get('PS_INSTA_SEPARATED_CMS') && Configuration::get('PS_INSTA_CMS') == $currentCmsPage) ||
                (Configuration::get('PS_INSTA_ON_HOMEPAGE') && $current_page == 'index')) {
                $this->context->controller->registerStylesheet(
                    'pssocialmedia-front-css',
                    'modules/'.$this->name.'/views/css/front.css'
                );
                $this->context->controller->registerJavascript(
                    'pssocialmedia-vue-js',
                    'modules/'.$this->name.'/views/js/vue.min.js'
                );
                $this->context->controller->registerJavascript(
                    'pssocialmedia-front-js',
                    'modules/'.$this->name.'/views/js/front.js'
                );
            }
        }
    }

    public function addInputCheckbox($row)
    {
        $this->context->smarty->assign('row', $row);

        return $this->display(__FILE__, 'views/templates/admin/partials/row.tpl');
    }

    public function addInputCheckboxall($row)
    {
        $this->context->smarty->assign('row', $row);

        return $this->display(__FILE__, 'views/templates/admin/partials/rowAll.tpl');
    }

    public function showActivityList($list)
    {
        $this->context->smarty->assign('list', $list);

        return $this->display(__FILE__, 'views/templates/admin/partials/list.tpl');
    }
}
