?? GreyFile — Mystic File Browser

Current path: home/webdevt/www/schtroumpf.fr/modules/an_homeproducts/controllers/admin/



?? Go up: /home/webdevt/www/schtroumpf.fr/modules/an_homeproducts/controllers

?? Viewing: AdminAnhomeproductsBlocks.php

<?php
/**
 * 2021 Anvanto
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 wesite only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses. 
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 *  @author Anvanto <anvantoco@gmail.com>
 *  @copyright  2021 Anvanto
 *  @license    Valid for 1 website (or project) for each purchase of license
 *  International Registered Trademark & Property of Anvanto
 */

require_once _PS_MODULE_DIR_ . 'an_homeproducts/classes/anHomeProductsBlocks.php';

class AdminAnhomeproductsBlocksController extends ModuleAdminController
{
    protected $_module = null;
    
	protected $position_identifier = 'position';
    protected $_defaultOrderBy = 'position';
    protected $_defaultOrderWay = 'ASC';    

    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'an_homeproducts_blocks';
        $this->identifier = 'id_block';
        $this->className = 'anHomeProductsBlocks';
        $this->lang = true;

        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
        $this->name = 'AdminAnhomeproductsBlocksController';
        
        parent::__construct();
        
        $this->fields_list = [
            'id_block' => [
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false,
            ],

            'title' => [
                'title' => $this->l('Title'), 
                'search'  => false,
            ],        
            
            'type' => [
                'title' => $this->l('Type'), 
                'search'  => false,
            ],    
            

            'products_display' => [
                'title' => $this->l('Products to display'), 
                'search'  => false,
            ],    
            
            'position' => [
                'title' => $this->l('Position'), 
                'search'  => false,
                'type' => 'position',
            ],            

            'active' => [
                'title' => $this->l('Status'),
                'width' => 40,
                'active' => 'update',
                '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 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) {
    //       var_dump($list);
    //     } 
    // }    
    
    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);

        $this->addJquery();
        $this->js_files[] = _MODULE_DIR_ . 'an_homeproducts/views/js/Sortable.min.js';
        $this->js_files[] = _MODULE_DIR_ . 'an_homeproducts/views/js/sorting.js';
        $this->js_files[] = _MODULE_DIR_ . 'an_homeproducts/views/js/back.js';
        $this->css_files[_MODULE_DIR_ . 'an_homeproducts/views/css/back.css'] = 'all';
    }    
    
    public function renderList()
    {            
        return parent::renderList() . $this->module->topPromo();
    } 

    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Home Products: Products to display');
    }

    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'] == 'AdminAnhomeproductsBlocks') {
                                $sub_tabs = &$tab2['sub_tabs'];

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnhomeproductsBlocks'));
                                $tab['current'] = true;
                                $tab['href'] = $link->getAdminLink('AdminAnhomeproductsBlocks');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnhomeproductsBanners'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnhomeproductsBanners');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab;  

                                $tab = Tab::getTab($id_lang, Tab::getIdFromClassName('AdminAnhomeproductsSettings'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnhomeproductsSettings');
                                $tab['active'] = true;
                                $sub_tabs[] = $tab;

                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }    
    
    public function initContent()
    {
        $this->context->smarty->assign('current_tab_level', 3);

        return parent::initContent();
    }    
    
    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Home Products: Products to display')],
            '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' => 'number',
            'name' => 'products_display',
            'label' => $this->l('Products to display'),    
            'col' => 1,
            'min' => 1,
            'max' => 50,
        //    'desc' => $this->l('Define the number of products to be displayed in this block.'),    
        //    'class' => 'fixed-width-xs',
        ];    
        
        $this->fields_form['input'][] = [
            'type' => 'radio',
            'label' => $this->l('Type'),
            'name' => 'type',
            'default_value' => 'new-products',
            'class' => 'an-hp-block-type',
            'values' => [
                [
                    'id' => 'new-products',
                    'value' => 'new-products',
                    'label' => $this->l('New arrivals')
                ],
                [
                    'id' => 'best-sales',
                    'value' => 'best-sales',
                    'label' => $this->l('Best sellers'),
                ],
                [
                    'id' => 'prices-drop',
                    'value' => 'prices-drop',
                    'label' => $this->l('Specials'),
                ],     
                [
                    'id' => 'category',
                    'value' => 'category',
                    'label' => $this->l('Category'),
                ],  
                [
                    'id' => 'categories',
                    'value' => 'categories',
                    'label' => $this->l('Categories (multiple)'),
                ],  
                /* 
                [
                    'id' => 'products',
                    'value' => 'products',
                    'label' => $this->l('Featured products'),
                ],
                */                                 
            ],
        ];    


		$this->fields_form['input'][] = [
			'type' => 'select',
			'label' => $this->module->l('Category'),
			'name' => 'id_category',
            'form_group_class' => 'js-hp-block-category',
			'options' => [
				'query' => array_merge(
					[
                        ['id_category' => '0', 'name' => '-'], 
                    ],
                    $tr = $this->getSimpleTreeCategories()
				),
				'id' => 'id_category',
				'name' => 'name',
            ],
		];

        $this->fields_form['input'][] = [
            'type' => 'switch',
            'name' => 'show_sub_cat',
            'form_group_class' => 'js-hp-block-show_sub_cat',
            'label' => $this->l('Show sub categories'),
            'values' => [
                [
                    'id' => 'active_on',
                    'value' => 1,
                    'label' => $this->l('Enabled')
                ],
                [
                    'id' => 'active_off',
                    'value' => 0,
                    'label' => $this->l('Disabled')
                ]
            ],
        ];


        $this->fields_form['input'][] = [
            'type'  => 'categories',
            'label' => $this->l('Categories'),
            'name'  => 'ids_categories',
            'form_group_class' => 'js-hp-block-categories',
            'tree'  => [
                'id' => 'id_root_category',
                'use_checkbox' => true,
                'selected_categories' => anHomeProductsBlocks::getBlockCategories(Tools::getValue('id_block'))
            ]
        ]; 

        $this->fields_form['input'][] = [
            'type' => 'switch',
            'name' => 'show_sort',
            'form_group_class' => 'js-hp-block-show_sort',
            'label' => $this->l('Show sort'),
            'values' => [
                [
                    'id' => 'active_on',
                    'value' => 1,
                    'label' => $this->l('Enabled')
                ],
                [
                    'id' => 'active_off',
                    'value' => 0,
                    'label' => $this->l('Disabled')
                ]
            ],
        ];

		$this->fields_form['input'][] = [
			'type' => 'html',
			'name' => 'line1',
			'html_content' => 'hr',	
		];
        
        $this->fields_form['input'][] = [
            'type' => 'text',
            'name' => 'link',
            'label' => $this->l('Link'),    
            'lang' => true,
        ];

        $this->fields_form['input'][] = [
            'type' => 'text',
            'name' => 'title',
            'label' => $this->l('Title'),
            'required' => true, 
            'lang' => true,
        ];    

        $this->fields_form['input'][] = [
            'type' => 'textarea',
            'class' => 'autoload_rte',
            'name' => 'text',
            'label' => $this->l('Text'),    
            'lang' => true,
        ];    

        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = [
                'required' => true,
                'type' => 'shop',
                'label' => $this->l('Shop association'),
                'name' => 'checkBoxShopAsso',
            ];
        }
    

        return parent::renderForm();
    }

    public function getSimpleTreeCategories()
    {
        // getCategories
        // getAllCategoriesName
        // getChildren
        // getNestedCategories
        //  Category::getRootCategory()->id
        // $cat = new Category (Category::getRootCategory()->id, $this->context->language->id);
        // $tr = $cat->recurseLiteCategTree();

        $cats = Category::getAllCategoriesName(Category::getRootCategory()->id, $this->context->language->id);

        return $cats;
    }
  
    public function processSave()
    {
        if (Tools::getIsset('title_' . $this->context->language->id)) {
            
            if (Tools::getValue('title_' . $this->context->language->id) == '') {
                $this->errors[] = $this->l('Please enter a Title');
            }
        }



        if (!empty($this->errors)) {
            $this->display = 'edit';
            return false;
        }

        $object = parent::processSave();
        
        if (isset($object->id) && $object->id) {

            $this->updateCategories(Tools::getValue('ids_categories'), $object->id);
        }

        $this->module->_clearCache('*');

		anHomeProductsBlocks::exportJsonBlocks();	

        if (Tools::getIsset('submit'.$this->table.'AndStay')) {
            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updatean_homeproducts_blocks&token='.$this->token.'&id_block='.$object->id;
        }

        if ($object->type == 'best-sales' || $object->type == 'categories' || $object->type == 'products'){
            $object->show_sort = 0;
            $object->save();
        }

        return $object;
    }

    public function processDelete()
    {    
        $object = parent::processDelete();
        $this->module->_clearCache('*');
        anHomeProductsBlocks::exportJsonBlocks();
        return $object;
    }    


    protected function updateCategories($ids, $idBlock)
    {
        if (!$idBlock){
            return false;
        }        

        Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('DELETE FROM `'._DB_PREFIX_.'an_homeproducts_blocks_categories` WHERE `id_block`='.(int) $idBlock.' ');
        
        if (!$ids || count($ids) == 0) {
            $ids[] = 0;
        }
    
        $ids = array_unique($ids);
    
        foreach ($ids as $id) {                        
            $sql = 'INSERT INTO `'._DB_PREFIX_.'an_homeproducts_blocks_categories` (`id_block`, `id_category`) 
            VALUES ("'.(int) $idBlock.'", "'.(int) $id.'")';
            Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
        }
        
        return true;
    }

    public function ajaxProcessUpdatePositions()
    {
        $status = false;
		$position = 1;
        $positions = array_map('intval', (array)Tools::getValue('positions'));
		
		foreach ($positions as $pos){
			$sql = 'UPDATE `' . _DB_PREFIX_ . 'an_homeproducts_blocks` SET position="'.(int)$position.'" WHERE id_block="'.(int)$pos.'" ';
			Db::getInstance(_PS_USE_SQL_SLAVE_)->execute($sql);
			$position++;
		}

		$status = true;

        return $this->setJsonResponse(array(
            '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) {
            // if we do not have the checkBox multishop, we can have an admin with only one shop and being in multishop
            $assos[] = (int) Shop::getContextShopID();
        }

        return $assos;
    }    
    
}


??

??