<?php
/**
* 2022 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2022 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

require_once _PS_MODULE_DIR_ . 'an_productextratabs/classes/anProductTabsLabels.php';

class AdminProducttabsLabelsController extends ModuleAdminController
{
    protected $_module = null;
    
    protected $position_identifier = 'position';
    protected $_defaultOrderBy = 'position';
    protected $_defaultOrderWay = 'ASC';   
    protected $bulk_actions = [];
    
    protected $allow_export = true;

    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'an_productextratabs_labels';
        $this->identifier = 'id_label';
        $this->className = 'anProductTabsLabels';
        $this->lang = true;

        $this->addRowAction('edit');
        $this->addRowAction('delete');
        
        $this->name = 'AdminProducttabsLabelsController';
        
        parent::__construct();
        
        $this->fields_list = [
            'id_label' => [
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false,
            ],

            'label' => [
                'title' => $this->l('Label'), 
                'search'  => false,
            ],                         

            'position' => [
                'title' => $this->l('Position'), 
                'search'  => false,
                'position' => true
            ],                      

            'relation' => [
                'title' => $this->l('Relation'), 
                'search'  => false,
                'width' => 150,
            ], 

            'active' => [
                'title' => $this->l('Active'),
                'width' => 40,
                'active' => 'status',
                'align' => 'center',
                'type' => 'bool',
                'search'  => false,
                'orderby' => false
            ],     
        ];

        if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL) {
            $this->_where .= ' AND a.' . $this->identifier . ' IN (
                SELECT sa.' . $this->identifier . '
                FROM `' . _DB_PREFIX_ . $this->table . '_shop` sa
                WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
            )';
        }
    }

    public function l($string, $class = null, $addslashes = false, $htmlentities = true)
    {
        return parent::l($string, pathinfo(__FILE__, PATHINFO_FILENAME), $addslashes, $htmlentities);
    }    

    public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
    {
        parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);

        foreach ($this->_list as &$list) {

            $this->context->smarty->assign([
                'color' => $list['color'],
                'color_background' => $list['color_background'],
                'label' => $list['label']
            ]);
            $list['label'] = $this->module->display(_PS_MODULE_DIR_. $this->module->name, 'views/templates/admin/list-color.tpl');

            switch ($list['relation']){
                case 1:
                    $list['relation'] = $this->l('Categories');
                    break;        

                case 2:
                    $list['relation'] = $this->l('Products');
                    break;    
                    
                default:
                    $list['relation'] = $this->l('all');
            }            
        } 

    }    
    
    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);

        $this->addJquery();
        $this->js_files[] = _MODULE_DIR_ . 'an_productextratabs/views/js/back_labels.js';
        $this->css_files[_MODULE_DIR_ . 'an_productextratabs/views/css/back.css'] = 'all';
    }    
    
    public function renderList()
    {                    
        return parent::renderList() . $this->module->topPromo();
    } 

    

    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Product Tabs: Labels');
    }

    public function initHeader()
    {
        parent::initHeader();

        $id_lang = $this->context->language->id;
        $link = $this->context->link;
        $tabs = &$this->context->smarty->tpl_vars['tabs']->value;

        foreach ($tabs as &$tab0) {
            if ($tab0['class_name'] == 'IMPROVE') {
                foreach ($tab0['sub_tabs'] as &$tab1) {
                    if ($tab1['class_name'] == 'AdminParentModulesSf') {
                        
                        foreach ($tab1['sub_tabs'] as &$tab2) {
                            if ($tab2['class_name'] == 'AdminProducttabsLabels') {
                                $sub_tabs = &$tab2['sub_tabs'];

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminProductTabs'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminProductTabs');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Tabs');
                                $sub_tabs[] = $tab;  

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminProductTabstemplates'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminProductTabstemplates');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Tab templates');
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminProducttabsSettings'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminProducttabsSettings');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Settings');
                                $sub_tabs[] = $tab;

                                
                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminProducttabsLabels'));
                                $tab['current'] = true;
                                $tab['href'] = $link->getAdminLink('AdminProducttabsLabels');
                                $tab['active'] = true;
                                $tab['name'] = $this->l('Labels');
                                $sub_tabs[] = $tab;

                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }  
    
    public function initContent()
    {
        $this->context->smarty->assign('current_tab_level', 3);

        return parent::initContent();
    }    

    public function initPageHeaderToolbar()
    {
        parent::initPageHeaderToolbar();
    }    
    
    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Product Tabs: Labels')],
            'input' => [],
            'buttons' => [
                [
                    'type' => 'submit',
                    'title' => $this->l('Save'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table
                ],
                [
                    'type' => 'submit',
                    'title' => $this->l('Save and stay'),
                    'icon' => 'process-icon-save',
                    'class' => 'pull-right',
                    'name' => 'submit'.$this->table.'AndStay'
                ],
            ],
        );

        $this->fields_form['input'][] = [
            'type' => 'switch',
            'name' => 'active',
            'label' => $this->l('Active'),
            'values' => [
                [
                    'id' => 'active_on',
                    'value' => 1,
                    'label' => $this->l('Enabled')
                ],
                [
                    'id' => 'active_off',
                    'value' => 0,
                    'label' => $this->l('Disabled')
                ]
            ],
        ];   
        
        $this->fields_form['input'][] = [
            'type' => 'text',
            'name' => 'label',
            'label' => $this->l('Label'),    
            'lang' => true,
        ]; 

        $this->fields_form['input'][] = [
            'type' => 'color',
            'label' => $this->trans('Color'),
            'name' => 'color',
        ];
        
        $this->fields_form['input'][] = [
            'type' => 'color',
            'label' => $this->trans('Color background'),
            'name' => 'color_background',
        ]; 
        
        $this->fields_form['input'][] = [
            'type' => 'radio',
            'label' => 'Relation',
            'name' => 'relation',
            'class' => 'an-sz-type-view',
            'values' => [
                [
                    'id' => 'relation_all',
                    'value' => '0',
                    'label' => $this->l('All'),
                ], 
                [
                    'id' => 'relation_categories',
                    'value' => '1',
                    'label' => $this->l('Categories')
                ], 
                [
                    'id' => 'relation_products',
                    'value' => '2',
                    'label' => $this->l('Products')
                ]
            ]
        ];    

		$this->fields_form['input'][] = array(
			'type' => 'anSearchProductsList',
			'ignore' => true,
			'name' => 'productIds[]',
			'class' => 'js-an_productfields_products js-an_productfields-searchProducts-components',
			'classSarchInput' => 'js-an_productfields-search-input',
            'label' => '',
            'searchProdutsController' => $this->context->link->getAdminLink('AdminProducttabsAjax', true, [], ['ajax'=>1, 'action' =>'searchProducts'])
		);

		$this->fields_form['input'][] = array(
			'type' => 'text',
			'ignore' => true,
			'label' => $this->l('Products'),
			'name' => 'products_input',
			'size' => 50,
			'maxlength' => 50,
			'col' => 4,
			'class' => 'js-an_productfields-search-input js-an_productfields-searchProducts-components',
            'desc' => $this->l('Search for a product by typing the first letters of his name')
		);

        $this->fields_value['productIds[]'] = anProductTabsLabels::getProducsByIdLabels(Tools::getValue('id_label'));
          
        $this->fields_form['input'][] = [
            'type'  => 'categories',
            'label' => $this->l('Categories'),
            'name'  => 'id_categories',
            'class' => 'js-sz-block-categories',
            'tree'  => [
                'id' => 'id_root_category',
                'use_checkbox' => true,
                'selected_categories' => anProductTabsLabels::getRelationCategories(Tools::getValue('id_label'))
            ]
        ];    
        
        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = [
                'required' => true,
                'type' => 'shop',
                'label' => $this->l('Shop association'),
                'name' => 'checkBoxShopAsso',
            ];
        }
       
        return parent::renderForm();
    }
  
    public function processSave()
    {
        if (!empty($this->errors)) {
            $this->display = 'edit';

            return false;
        }        
        
        $object = parent::processSave();
        
        if (isset($object->id) && $object->id) {
            
            switch (Tools::getValue('relation')){
                
                case 1:
                    $this->updateCategoriesProducts(Tools::getValue('id_categories'), $object->id, 1);
                    break;
                    
                case 2:
                    $this->updateCategoriesProducts(Tools::getValue('productIds'), $object->id, 2);
                    break;    

                default:
                    $this->updateCategoriesProducts([], $object->id, 0);
            }

            $fileName = configuration::get(an_productextratabs::PREFIX.'_css_file_name');

            @unlink(_PS_MODULE_DIR_. $this->module->name . '/views/css/' . $fileName);

            $allLabels = anProductTabsLabels::getAllLabels();

            $this->context->smarty->assign(['labels' => $allLabels]);
            $cssCode = @$this->module->display(_PS_MODULE_DIR_. $this->module->name, '/views/templates/admin/css_generate.tpl');
            
            $fileName = $this->generateFileName();

            $file = _PS_MODULE_DIR_. $this->module->name .'/views/css/' .$fileName;
    
            @file_put_contents($file, $cssCode);
      
            Configuration::updateValue(an_productextratabs::PREFIX.'_css_file_name', $fileName);
        }        

        if (Tools::getIsset('submit'.$this->table.'AndStay')) {
            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).
            '&conf=4&update'.$this->table.'&token='.$this->token.'&'.$this->identifier.'='.$object->id;
        }
        
        return $object;
    }

    public function generateFileName($format = 'css', $prefix = 'anpt-')
    {
        return $prefix . md5(uniqid() . context::getContext()->shop->id) . '.' . $format;
    }

    public function updateCategoriesProducts($ids = [], $id_label = 0, $type = 0)
    {
        if (!$id_label){
            return false;
        }        
        
        Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('DELETE FROM `'._DB_PREFIX_.'an_productextratabs_labels_relations` WHERE `id_label`='.(int) $id_label.' ');
        
        if (!$ids || count($ids) == 0) {
            $ids[] = 0;
        }
    
        $ids = array_unique($ids);
    
        foreach ($ids as $id) {                        
            $sql = 'INSERT INTO `'._DB_PREFIX_.'an_productextratabs_labels_relations`  (`id_label`, `id_type`, `type`) 
            VALUES ("'.(int) $id_label.'", "'.(int) $id.'", "'.(int) $type.'" )';
            Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
        }
        
        return true;
    }    

    public function ajaxProcessUpdatePositions()
    {
        $status = false;
		$position = 0;
        $widget = (array)Tools::getValue('label');
        
        foreach ($widget as $key => $item){
            $ids = explode('_', $item);
			$sql = 'UPDATE `' . _DB_PREFIX_ . $this->table .'` SET position="'.(int) $position.'" WHERE '.$this->identifier.'="'.(int) $ids['2'].'" ';
			Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
			$position++;
        }

        if (count($widget) > 0){
            $status = true;
        }

        return $this->setJsonResponse([
            'success' => $status,
            'message' => $this->l($status ? 'Blocks reordered successfully' : 'An error occurred')
        ]);
    }

    protected function setJsonResponse($response)
    {
        header('Content-Type: application/json; charset=utf8');
        print(json_encode($response));
        exit;
    }    

    protected function updateAssoShop($id_object)
    {
        if (!Shop::isFeatureActive()) {
            return;
        }

        $assos_data = $this->getSelectedAssoShop($this->table, $id_object);

        $exclude_ids = $assos_data;

        foreach (Db::getInstance()->executeS('SELECT id_shop FROM ' . _DB_PREFIX_ . 'shop') as $row) {
            if (!$this->context->employee->hasAuthOnShop($row['id_shop'])) {
                $exclude_ids[] = $row['id_shop'];
            }
        }

        Db::getInstance()->delete($this->table . '_shop', '`' . $this->identifier . '` = ' . (int) $id_object . ($exclude_ids ? ' AND id_shop NOT IN (' . implode(', ', $exclude_ids) . ')' : ''));

        $insert = array();

        foreach ($assos_data as $id_shop) {
            $insert[] = array(
                $this->identifier => $id_object,
                'id_shop' => (int) $id_shop,
            );
        }

        return Db::getInstance()->insert($this->table . '_shop', $insert, false, true, Db::INSERT_IGNORE);
    }

    protected function getSelectedAssoShop($table)
    {
        if (!Shop::isFeatureActive()) {
            return array();
        }

        $shops = Shop::getShops(true, null, true);

        if (count($shops) == 1 && isset($shops[0])) {
            return array($shops[0], 'shop');
        }

        $assos = array();

        if (Tools::isSubmit('checkBoxShopAsso_' . $table)) {
            foreach (Tools::getValue('checkBoxShopAsso_' . $table) as $id_shop => $value) {
                $assos[] = (int) $id_shop;
            }
        } else if (Shop::getTotalShops(false) == 1) {
            
            $assos[] = (int) Shop::getContextShopID();
        }

        return $assos;
    }      
}

    
    
   