<?php
/**
* 2023 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2023 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

require_once _PS_MODULE_DIR_ . 'anblog/classes/anblogcat.php';

class AdminAnblogCategoriesController extends ModuleAdminController
{
    protected $_module = null;
    
    protected $position_identifier = 'position';
    protected $_defaultOrderBy = 'position';
    protected $_defaultOrderWay = 'ASC';   
    
    protected $allow_export = false;

    public function __construct()
    {
        $this->bootstrap = true;
        $this->context = Context::getContext();
        $this->table = 'anblogcat';
        $this->identifier = 'id_anblogcat';
        $this->className = 'Anblogcat';
        $this->lang = true;

        $this->parent_id = (int)Tools::getValue('id_parent');

        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
        $this->name = 'AdminAnblogCategoriesController';
        
        parent::__construct();

        $parentId = 1;

        if ($this->parent_id){
            $parentId = $this->parent_id;
        } 

        $this->_where .= ' AND a.id_parent = ' . $parentId . ' ';
        
        $this->fields_list = [
            'id_anblogcat' => [
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false,
            ],           
            
            'image' => [
                'title' => $this->l('Image'), 
                'width' => 25,
                'search'  => false,
                'type' => 'image',
            ], 
            
            'title' => [
                'title' => $this->l('Name'), 
                'width' => 25,
                'search'  => false,
            ], 

            'content_text' => [
                'title' => $this->l('Description'), 
                'width' => 25,
                'search'  => false,
            ], 

            'position' => [
                'title' => $this->l('Position'), 
                'search'  => false,
                'position' => true
            ],   

            'active' => [
                'title' => $this->l('Status'),
                'width' => 40,
                'active' => 'update',
                'align' => 'center',
                'type' => 'bool',
				'search'  => false,
                'orderby' => false
            ],

            'viewBut' => [
                'title' => $this->l('View'), 
                'search'  => false,
                'type' => 'image',
            ] 
        ];

        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) {

            if ($list['image'] !='' && Tools::file_exists_no_cache( _ANBLOG_BLOG_IMG_DIR_.'c/'. $list['image'])) {				
                $list['image'] =  _ANBLOG_BLOG_IMG_URI_.'/c/'. $list['image'];
            } else {
                $list['image'] = '';
            }

            $this->context->smarty->assign(['image' => $list['image']]);
            $list['image'] = $this->module->display(_PS_MODULE_DIR_.'anblog', 'views/templates/admin/list-img.tpl');

            $list['content_text'] = strip_tags($list['content_text']);

            $obj = new anblogcat($list['id_anblogcat']);
            $child = $obj->getChild($list['id_anblogcat']);  

            if (count($child) != 0) {
                $this->context->smarty->assign('widget', [
                    'action' => 'Sub categories',
                    'href' => $this->context->link->getAdminLink('AdminAnblogCategories'). '&id_parent='. $list['id_anblogcat'] ,
                ]);

                $list['viewBut'] = $this->module->display(_PS_MODULE_DIR_.'anblog', 'views/templates/admin/list_action_view.tpl');
            }

        } 
    }    
    
    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);
        $this->addJqueryPlugin('tagify');
        $this->js_files[] = _MODULE_DIR_ . 'anblog/views/js/admin/back.js';
        $this->css_files[_MODULE_DIR_ . 'anblog/views/css/admin/back.css'] = 'all';  

    }
    
    public function renderList()
    {                    
        $this->initToolbar();
        if (!$this->loadObject(true)) {
            return false;
        }

        return parent::renderList();
    } 

    
    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Categories');
    }
   
    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'] = true;
                                $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'] = false;
                                $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()
    {
        $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 . '&addanblogcat&token=' . $this->token,
                'desc' => $this->trans('Add new', array(), 'Admin.Actions'),
                'icon' => 'process-icon-new',
            );

            $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'
            );
        }
        parent::initPageHeaderToolbar();
    }   
    
    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 

        $thumb = '';

        if ($this->object->image) {
            $thumb = _ANBLOG_BLOG_IMG_URI_.'/c/'. $this->object->image;
        } 

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Categories')],
            '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' => 'text',
            'label' => $this->l('Title'),
            'default' => '',
            'name' => 'title',
            'id' => 'name', 
            'lang' => true,
            'required' => true,
            'class' => 'copyMeta2friendlyURL',
            'hint' => $this->l('Invalid characters:').' &lt;&gt;;=#{}'
        ];

        $this->fields_form['input'][] = [
            'type' => 'text',
            'label' => $this->l('Friendly URL'),
            'name' => 'link_rewrite',
            'required' => true,
            'lang' => true,
            'default' => '',
            'hint' => $this->l('Only letters and the minus (-) character are allowed')
        ];
        
        $this->context->smarty->assign(['PS_ALLOW_ACCENTED_CHARS_URL' => (int)Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL')]);        

        $obj = $this->object;
        $cats = $obj->getDropdown(null, $obj->id_parent);       

        $this->fields_form['input'][] = [
            'type' => 'select',
            'label' => $this->l('Parent ID'),
            'name' => 'id_parent',
            'options' => [
                'query' => $cats,
                'id' => 'id',
                'name' => 'title'
            ],
            'default' => 'url',
        ];
        
        $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' => 'menu_class',
            'label' => $this->l('Additional CSS class'),   
            'lang' => false,
        ];

        $this->fields_form['input'][] = [
            'type' => 'file',
            'label' => $this->l('Image'),
            'required' => false,
            'name' => 'file_icon',
            'thumb' => $thumb,
            'form_group_class' => 'ab-bi-image'
        ]; 

        $this->fields_form['input'][] = [
            'type' => 'textarea',
            'class' => 'autoload_rte',
            'name' => 'content_text',
            'label' => $this->l('Description'),    
            'lang' => true,
        ];

        $this->fields_form['input'][] = [
            'type' => 'text',
            'name' => 'meta_title',
            'label' => $this->l('Meta title'),
            'required' => true,    
            'lang' => true,
        ];  

        $this->fields_form['input'][] = [
            'type' => 'text',
            'name' => 'meta_description',
            'label' => $this->l('Meta description'),  
            'lang' => true,
        ];  

        $this->fields_form['input'][] = [
            'type' => 'tags',
            'label' => $this->l('Meta keywords'),
            'name' => 'meta_keywords',
            'lang' => true,
            'default' => '',
            'hint' => $this->l('Invalid characters:') . ' &lt;&gt;;=#{}',
            'desc' => $this->l('To add a keyword, enter the keyword and then press "Enter"'),
        ];  

        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 (isset($_FILES['file_icon']) && isset($_FILES['file_icon']['tmp_name'])
                && !empty($_FILES['file_icon']['tmp_name'])) {
            if ($error = $this->validateUpload($_FILES['file_icon'])) {
                $this->errors[] = $error;                 
            }
        }
          

        if (!empty($this->errors)) {
            $this->display = 'edit';
            return false;
        }        
        
        $isUpdateImage = false;

        $object = parent::processSave();


        if (isset($object->id) && $object->id) {

            if(tools::getValue('image_del')){ 
                @unlink(_ANBLOG_BLOG_IMG_DIR_.'c/'. $object->image);
                $object->image = '';
                $isUpdateImage = true;
            }

            if (isset($_FILES['file_icon']) && !empty($_FILES['file_icon']['tmp_name'])) {

				$ext = substr($_FILES['file_icon']['name'], strrpos($_FILES['file_icon']['name'], '.') + 1);

				$image = md5(uniqid()) . '.'.$ext;

				if (!move_uploaded_file($_FILES['file_icon']['tmp_name'], _ANBLOG_BLOG_IMG_DIR_.'c/'. $image)) {
					return $this->displayError(
						$this->trans('An error occurred while attempting to upload the file.', [], 'Admin.Notifications.Error')
						);
				} else {
					@unlink(_ANBLOG_BLOG_IMG_DIR_.'c/'. $object->image);
					$object->image = $image;
				}

                $isUpdateImage = true;
			}
        }
        
        if ($isUpdateImage){
            $object->save();		
        }  

        if (Tools::getIsset('submit'.$this->table.'AndStay') && empty($this->errors)) {
            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updateanblogcat&token='.$this->token.'&id_anblogcat='.$object->id;
        }
        
        return $object;
    }

    

    public function processDelete()
    {    
        $object = parent::processDelete();
        
        if (isset($object->id) && $object->id) {
            if ($object->image){
                unlink(_ANBLOG_BLOG_IMG_DIR_.'c/'. $object->image);	
            }
		}	

        return $object;
    }  

    public function validateUpload($file)
    {
        $maxFileSize = 4000000;
        $types = ['gif', 'jpg', 'jpeg', 'jpe', 'png', 'svg', 'webp'];

        // if ((int) $maxFileSize > 0 && $file['size'] > (int) $maxFileSize) {
        //     return Context::getContext()->getTranslator()->trans('Image is too large (%1$d kB). Maximum allowed: %2$d kB', [$file['size'] / 1024, $maxFileSize / 1024], 'Admin.Notifications.Error');
        // }

        if (!ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
            return Context::getContext()->getTranslator()->trans('Image format not recognized, allowed formats are: .gif, .jpg, .png, .svg, .webp', [], 'Admin.Notifications.Error');
        }  

        if ($file['error']) {
            return Context::getContext()->getTranslator()->trans('Error while uploading image; please change your server\'s settings. (Error code: %s)', [$file['error']], 'Admin.Notifications.Error');
        }   
        
        return false;
    }     

    public function ajaxProcessUpdatePositions()
    {
        $status = false;
		$position = 0;
        $widget = (array)Tools::getValue('anblogcat');

        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(array(
            'success' => $status,
            'message' => $this->l($status ? 'Blocks reordered successfully' : 'An error occurred')
        ));
    }

    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;
    }      
}
