<?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_.'anblog/loader.php';

class AdminAnblogWidgetsController extends ModuleAdminController
{
    protected $_module = null;
	
	protected $position_identifier = 'id_anblog_blog_widgets';

    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'anblog_blog_widgets';
        $this->identifier = 'id_anblog_blog_widgets';
        $this->className = 'anBlogWidgets';
        $this->lang = true;

        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
        $this->name = 'AdminAnblogWidgetsController';
        
        parent::__construct();
        
        $this->fields_list = [
            'id_anblog_blog_widgets' => [
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false,
            ], 
            
            'title' => [
                'title' => $this->l('Title'), 
                'width' => 25,
                'search'  => false,
            ], 

            'id_anblogcat' => [
                'title' => $this->l('Category'), 
                'width' => 25,
                'search'  => false,
            ],
            
            'relation' => [
                'title' => $this->l('Relation'), 
                'search'  => false,
                'width' => 150,
            ], 
            
            'snow_on' => [
                'title' => $this->l('Show on'), 
                'width' => 25,
                'search'  => false,
            ], 

            'sort' => [
                'title' => $this->l('Sort'), 
                'width' => 25,
                'search'  => false,
            ], 

            // 'slider' => [
            //     'title' => $this->l('Slider'),
            //     'width' => 40,
            //     'active' => 'update',
            //     'align' => 'center',
            //     'type' => 'bool',
			// 	'search'  => false,
            //     'orderby' => false
            // ], 

            'limit' => [
                'title' => $this->l('Limit'), 
                'width' => 25,
                'search'  => 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);

        $showOn = anBlogWidgets::$showOn;

        $obj = new anblogcat();
        $obj->getTree();
        $menus = $obj->getDropdown(null, $obj->id_parent, false);
        array_shift($menus);		
		
		$itemHome['-'] = ['id'=>'', 'title' => '-', 'selected' => ''];
		$menus = array_merge($itemHome, $menus);

        foreach ($this->_list as &$list) {
            foreach ($showOn as $key => $item){
                if ($list['snow_on'] == $key){
                    $list['snow_on'] = $item['name'];
                }
            }
            if (!$list['id_anblogcat']){
                $list['id_anblogcat'] = '-';
            }
            foreach ($menus as $key => $item){
                if ($list['id_anblogcat'] == $item['id']){
                    $list['id_anblogcat'] = $item['title'];
                }
            }

            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_ . 'anblog/views/js/back_widgets.js';
        $this->css_files[_MODULE_DIR_ . 'anblog/views/css/back.css'] = 'all';
    }   
    
    public function renderList()
    {                    
        $this->initToolbar();
        if (!$this->loadObject(true)) {
            return false;
        }
        
        return parent::renderList() . $this->renderView();
    } 

    
    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Widgets');
    }
   
    public function initHeader()
    {
        parent::initHeader();

        $idLang = $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'] == 'AdminAnblogManagement') {
                        foreach ($tab1['sub_tabs'] as &$tab2) {
                            if ($tab2['class_name'] == $this->controller_name) {
                                $sub_tabs = &$tab2['sub_tabs'];

                                $tab = Tab::getTab($idLang, Tab::getIdFromClassName('AdminAnblogBlogs'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnblogBlogs');
                                $tab['name'] = $this->l('Posts');
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($idLang, Tab::getIdFromClassName('AdminAnblogCategories'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnblogCategories');
                                $tab['name'] = $this->l('Categories');
                                $sub_tabs[] = $tab;

                                $tab = Tab::getTab($idLang, Tab::getIdFromClassName('AdminAnblogComments'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnblogComments');
                                $tab['name'] = $this->l('Comments');
                                $sub_tabs[] = $tab;                              
                                
                                $tab = Tab::getTab($idLang, Tab::getIdFromClassName('AdminAnblogSettings'));
                                $tab['current'] = false;
                                $tab['href'] = $link->getAdminLink('AdminAnblogSettings');
                                $tab['name'] = $this->l('Settings');
                                $sub_tabs[] = $tab; 

                                $tab = Tab::getTab($idLang, Tab::getIdFromClassName('AdminAnblogWidgets'));
                                $tab['current'] = true;
                                $tab['href'] = $link->getAdminLink('AdminAnblogWidgets');
                                $tab['name'] = $this->l('Widgets');
                                $sub_tabs[] = $tab; 

                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
       
    }       
    
    public function initContent()
    {
        $this->context->smarty->assign('current_tab_level', 3);
        return parent::initContent();
    } 

    public function initPageHeaderToolbar()
    {
        $link = $this->context->link;

        $code = '';
        if (sizeof(Language::getLanguages(true, true)) > 1) {
            $code = $this->context->language->iso_code .  '/';
        }                                                                                                                   

        if (empty($this->display)) {
            $this->page_header_toolbar_btn['add_field'] = array(
                'href' => self::$currentIndex . '&addanblog_blog_widgets&token=' . $this->token,
                'desc' => $this->trans('Add new', array(), 'Admin.Actions'),
                'icon' => 'process-icon-new',
            );
        }

        if (empty($this->display)) {
            $this->page_header_toolbar_btn['open_the_blog'] = array(
                'href' => $this->context->shop->getBaseURL(true) . $code . Configuration::get('link_rewrite', 'blog') . '.html',
                'desc' => $this->trans('Open the blog', array(), 'Admin.Actions'),
                'icon' => 'icon-book',
                'target' => '_blank'
            );
        }


        return parent::initPageHeaderToolbar();
    }  
    
    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 

        $values = [];

        $showOn = anBlogWidgets::$showOn;

        foreach ($showOn as $key => $item){
            $values[] = [
                'id' => $key,
                'name' => $item['name']
            ];
        }

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Widgets')],
            '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'][] = [
            'col' => 6,
			'type' => 'text',
			'name' => 'title',
			'label' => $this->l('Title'),	
			'lang' => true,
        ];

        $this->fields_form['input'][] = [
			'type' => 'select',
            'label' => $this->l('Show on'),
            'name' => 'snow_on',
            'options' => ['query' => $values,
                'id' => 'id',
                'name' => 'name'],
            'default' => '',
		];

        $this->fields_form['input'][] = [
			'type' => 'radio',
			'label' => $this->l('Sort'),
			'name' => 'sort',
			'values' => [
				[
					'id' => 'new',
					'value' => 'new',
					'label' => $this->l('New')
				],
				[
					'id' => 'popular',
					'value' => 'popular',
					'label' => $this->l('Popular'),
				],            
			],
        ];

        // $this->fields_form['input'][] = [
        //     'type' => 'switch',
        //     'name' => 'slider',
        //     'label' => $this->l('Slider'),
        //     'values' => [
        //         [
        //             'id' => 'slider_on',
        //             'value' => 1,
        //             'label' => $this->l('Enabled')
        //         ],
        //         [
        //             'id' => 'slider_off',
        //             'value' => 0,
        //             'label' => $this->l('Disabled')
        //         ]
        //     ],
        // ];

        $obj = new anblogcat();
        $obj->getTree();
        $menus = $obj->getDropdown(null, $obj->id_parent, false);
        array_shift($menus);		
		
		$itemHome['-'] = ['id'=>'', 'title' => '-', 'selected' => ''];
		$menus = array_merge($itemHome, $menus);

        $this->fields_form['input'][] = [
            'type' => 'select',
            'label' => $this->l('Category'),
            'name' => 'id_anblogcat',
            'options' => ['query' => $menus,
                'id' => 'id',
                'name' => 'title'],
            'default' => '',
        ];

        $this->fields_form['input'][] = [
            'type' => 'number',
            'label' => $this->l('Limit'),
            'name' => 'limit',
            'lang' => false,
            'col' => 2,
            'min' => 1,
            'max' => 10,
        ];

        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = [
                'required' => true,
                'type' => 'shop',
                'label' => $this->l('Shop association'),
                'name' => 'checkBoxShopAsso',
            ];
        }

        $this->fields_form['input'][] = [
            'type' => 'radio',
            'label' => 'Relation',
            'name' => 'relation',
            'class' => 'an-sz-type-view',
            'form_group_class' => 'js-anblog-relation-group js-anblog-relation',
            '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-anblog_products js-anblog-searchProducts-components',
            'form_group_class' => 'js-anblog-relation-group',
			'classSarchInput' => 'js-anblog-search-input',
            'label' => '',
            'searchProdutsController' => $this->context->link->getAdminLink('AdminAnblogAjax', 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-anblog-search-input js-anblog-searchProducts-components',
            'form_group_class' => 'js-anblog-relation-group',
            'desc' => $this->l('Search for a product by typing the first letters of his name')
		);

        $this->fields_value['productIds[]'] = anBlogWidgets::getProducsByIdWidgets(Tools::getValue('id_anblog_blog_widgets'));
          
        $this->fields_form['input'][] = [
            'type'  => 'categories',
            'label' => $this->module->l('Categories'),
            'name'  => 'id_categories',
            'class' => 'js-sz-block-categories',
            'form_group_class' => 'js-anblog-relation-group',
            'tree'  => [
                'id' => 'id_root_category',
                'use_checkbox' => true,
                'selected_categories' => anBlogWidgets::getRelationCategories(Tools::getValue('id_anblog_blog_widgets'))
            ]
        ];    

        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);
            }
  
            if (Tools::getIsset('submit'.$this->table.'AndStay')) {
                $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updateanblog_blog_widgets&token='.$this->token.'&id_anblog_blog_widgets='.$object->id;
            }
        }

        return $object;
    }

    

    public function processDelete()
    {    
        $object = parent::processDelete();

        return $object;
    }  

    public function updateCategoriesProducts($ids = [], $id_anblog_blog_widgets = 0, $type = 0)
    {
        if (!$id_anblog_blog_widgets){
            return false;
        }        
        
        Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('DELETE FROM `'._DB_PREFIX_.'anblog_blog_widgets_relations` WHERE `id_anblog_blog_widgets`='.(int) $id_anblog_blog_widgets.' ');
        
        if (!$ids || count($ids) == 0) {
            $ids[] = 0;
        }
    
        $ids = array_unique($ids);
    
        foreach ($ids as $id) {                        
            $sql = 'INSERT INTO `'._DB_PREFIX_.'anblog_blog_widgets_relations`  (`id_anblog_blog_widgets`, `id_type`, `type`) 
            VALUES ("'.(int) $id_anblog_blog_widgets.'", "'.(int) $id.'", "'.(int) $type.'" )';
            Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
        }
        
        return true;
    }    

    protected function getSettingsForm()
    {
        $obj = new anblogcat();
        $obj->getTree();
        $menus = $obj->getDropdown(null, $obj->id_parent, false);
        array_shift($menus);		
		
		$itemHome['-'] = ['id'=>'', 'title' => '-', 'selected' => ''];
		$menus = array_merge($itemHome, $menus);

        $form['form']['legend'] = [
            'title' => $this->l('Widget'),
        ];

        $form['form']['submit'] = [
            'name' => 'save',
            'title' => $this->l('Save'),
        ];

        $form['form']['input'][] = [
            'type' => 'switch',
            'label' => $this->l('Display Home'),
            'name' => anblog::PREFIX . 'show_in_DisplayHome',
            'required' => false,
            'class' => 't',
            'is_bool' => true,
            'default' => '0',
            'values' => [
                [
                    'id' => 'show_in_DisplayHome_on',
                    'value' => 1,
                    'label' => $this->l('Enabled')
                ],
                [
                    'id' => 'show_in_DisplayHome_off',
                    'value' => 0,
                    'label' => $this->l('Disabled')
                ]
            ],
        ];

        $form['form']['input'][] = [
            'type' => 'select',
            'label' => $this->l('Category'),
            'name' => anblog::PREFIX . 'categories_DisplayHome_blog',
            'options' => ['query' => $menus,
                'id' => 'id',
                'name' => 'title'],
            'default' => '',
        ];

        $form['form']['input'][] = [
            'type' => 'number',
            'label' => $this->l('Display Home posts limit'),
            'name' => anblog::PREFIX . 'limit_DisplayHome_blog',
            'lang' => false,
            'col' => 2,
            'min' => 1,
            'max' => 10,
        ];

        return $form;
    }

    public function renderView()
    {
        $languages = $this->context->controller->getLanguages();
  
        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->name_controller = $this->name;
        $helper->submit_action = $this->name;
        $helper->currentIndex = $this->context->link->getAdminLink($this->controller_name,  true, [], ['whereDisplay' => Tools::getValue('whereDisplay'),]);
        $helper->token = Tools::getAdminTokenLite('AdminAnblogWidgets');
        $helper->default_form_language = $this->context->language->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;

        $helper->override_folder = 'anblog_widgets/';
        $helper->setTpl($this->override_folder);
        
        $helper->tpl_vars = [
            'uri' => $this->module->getPathUri(),
            'languages' => $languages,
            'id_language' => $this->context->language->id
        ];

        $form = $this->getSettingsForm();

        
        foreach ($form['form']['input'] as $input){
            if (isset($input['lang']) && $input['lang']){
                $value = [];
                foreach ($languages  as $language){
                    $value[$language['id_lang']] = Configuration::get($input['name'], $language['id_lang']);
                }
                $helper->tpl_vars['fields_value'][$input['name']] = $value;
            } else {
                $helper->tpl_vars['fields_value'][$input['name']] = Configuration::get($input['name']);
            }
        }

        return $helper->generateForm([$form]);		
	}

    public function postProcess()
    {    
        $form = $this->getSettingsForm();
        
        if (Tools::isSubmit($form['form']['submit']['name'])) {

            $languages = Language::getLanguages(false);
            
            foreach ($form['form']['input'] as $input){

                $html = false;
                if (isset($input['html']) && $input['html']){
                    $html = true;
                }

                if (isset($input['lang']) && $input['lang']){
                    $value = [];
                    foreach ($languages  as $language){
                        $value[$language['id_lang']] = Tools::getValue($input['name'].'_' . $language['id_lang']);
                    }
        
                    Configuration::updateValue($input['name'], $value, $html);
                } else {
                    Configuration::updateValue($input['name'], Tools::getValue($input['name']), $html);
                }
            }

            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name,  true, [], ['whereDisplay' => Tools::getValue('whereDisplay'),]);
        }
		return parent::postProcess();
    }

    protected function setJsonResponse($response)
    {
        header('Content-Type: application/json; charset=utf8');
        $this->ajaxDie(json_encode($response));
    } 

    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;
    }      
}
