<?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_banners/classes/anBanners.php';

class AdminAnBannersController 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_banners';
        $this->identifier = 'id_banner';
        $this->className = 'anBanners';
        $this->lang = true;

        $this->addRowAction('edit');
        $this->addRowAction('delete');
 
        $this->name = 'AdminAnBannersController';
        
        parent::__construct();

        $this->fields_list = [
            'id_banner' => [
                'title' => $this->l('ID'), 
                'width' => 25,
                'search'  => false,
            ],

            'image' => [
                'title' => $this->l('Image'), 
                'search'  => false,
                'type' => 'image',
            ], 

            'title' => [
                'title' => $this->l('Title'), 
                'search'  => false,
            ], 

            'col' => [
                'title' => $this->l('Col'), 
                'search'  => false,
            ],
            
            'hook' => [
                'title' => $this->l('Hook'), 
                '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) {
                       
            if ($list['image'] !='' && Tools::file_exists_no_cache(anBanners::imgDir.$list['image'])) {				
				$list['image'] = anBanners::imgUrl.$list['image'];
            }
			
			$this->context->smarty->assign([
				'image' => $list['image'],
			]);
			
			$list['image'] = $this->module->display(_PS_MODULE_DIR_.'an_banners', 'views/templates/admin/list-img.tpl');

        } 
    }    
    
    public function setMedia($isNewTheme = false)
    {
        parent::setMedia($isNewTheme);

        $this->addJquery();
        $this->js_files[] = _MODULE_DIR_ . 'an_banners/views/js/Sortable.min.js';
        $this->js_files[] = _MODULE_DIR_ . 'an_banners/views/js/sorting.js';
    }    
    
    public function renderList()
    {            
        return parent::renderList() . $this->module->topPromo();
    } 

    public function initToolBarTitle()
    {
        $this->toolbar_title[] = $this->l('Banners');
    }

    public function initHeader()
    {
        parent::initHeader();
    }    
    
    public function renderForm()
    {
        $this->initToolbar();
         if (!$this->loadObject(true)) {
            return;
        } 

        $this->fields_form = array(
            'tinymce' => false,
            'legend' => ['title' => $this->l('Banners')],
            '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')
                ]
            ],
        ];   

        $bannerTpls = anBanners::getListTpl();
        if (count($bannerTpls) > 1){
            $this->fields_form['input'][] = [
                'type' => 'select',
                'label' => $this->module->l('Template'),
                'name' => 'template',
                'options' => [
                    'query' => array_merge(

                        anBanners::getListTpl()
                    ),
                    'id' => 'file',
                    'name' => 'file',
                ],
            ]; 
        }

        $this->fields_form['input'][] = [
            'col' => 6,
            'type' => 'select',
            'name' => 'hook',
            'label' => $this->module->l('Select hook'),
            'options' => [
                'query' => $this->module->getHooksQuery(),
                'id' => 'name',
                'name' => 'name'
            ],  
        ];

        $listCols = [];
        for ($i=3; $i <= 12; $i++){
            $listCols[] = ['id' => $i, 'name' => $i];
        }

		$this->fields_form['input'][] = [
			'type' => 'select',
			'label' => $this->module->l('Col'),
			'name' => 'col',
			'options' => [
				'query' => array_merge(
					[   ['id' => 'div', 'name' => 'div'],
                        ['id' => '2', 'name' => '2'], 
                    ],
                    $listCols
				),
				'id' => 'id',
				'name' => 'name',
            ],
		];

        $this->fields_form['input'][] = [
            'type' => 'file_lang',
            'label' => $this->l('Image'),
            'lang' => true,
            'name' => 'image',
            'display_image' => true,
            'delete_url' => '',
        ];

        $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'),    
            '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 processSave()
    {
        $languages = Language::getLanguages(false);
        $isUpdateImage = false;

        foreach ($languages as $lang) {
            if (isset($_FILES['image_'.$lang['id_lang']]) && isset($_FILES['image_'.$lang['id_lang']]['tmp_name'])
                    && !empty($_FILES['image_'.$lang['id_lang']]['tmp_name'])) {
                if ($error = $this->validateUpload($_FILES['image_'.$lang['id_lang']])) {
                    $this->errors[] = $error;                 
                }
            }
        }

        if (!empty($this->errors)) {
            $this->display = 'edit';
            return false;
        }        
        
        $object = parent::processSave();
        
        if (isset($object->id) && $object->id) {

            $this->module->registerHook($object->hook);
            
            $deleteImage = Tools::getValue('delete_image');
            if ($deleteImage && is_array($deleteImage)){
                
                foreach ($deleteImage as $id){
                    @unlink(anBanners::imgDir . $object->image[$id]);
                    $object->image[$id] = '';
                }
                $isUpdateImage = true;
            }

            foreach ($languages as $lang) {

                if (isset($_FILES['image_'.$lang['id_lang']]) && isset($_FILES['image_'.$lang['id_lang']]['tmp_name'])
                    && !empty($_FILES['image_'.$lang['id_lang']]['tmp_name'])) {

                    $ext = substr($_FILES['image_'.$lang['id_lang']]['name'], strrpos($_FILES['image_'.$lang['id_lang']]['name'], '.') + 1);
                    $fileName = md5(uniqid()) . '_' . $lang['id_lang'] . '.' . $ext;

                    if (!move_uploaded_file($_FILES['image_'.$lang['id_lang']]['tmp_name'], anBanners::imgDir . $fileName)) {

                    }
                    
                    if (isset($object->image[$lang['id_lang']]) && $object->image[$lang['id_lang']] !=''){
                       @unlink(anBanners::imgDir . $object->image[$lang['id_lang']]);
                    }
                    $object->image[$lang['id_lang']] = $fileName;
                   
                    $isUpdateImage = true;
                }
            }

			if ($isUpdateImage){
                $object->save();		
			}   
        }

        anBanners::exportJsonBanners();	

        if (Tools::getIsset('submit'.$this->table.'AndStay')) {
            $this->redirect_after = $this->context->link->getAdminLink($this->controller_name).'&conf=4&updatean_homeproducts_banners&token='.$this->token.'&id_banner='.$object->id;
        }
        
        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', [], '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 processDelete()
    {    
        $object = parent::processDelete();
        anBanners::exportJsonBanners();	
        return $object;
    }    

    public function ajaxProcessUpdatePositions()
    {
        $status = false;
		$position = 1;
        $positions = array_map('intval', (array)Tools::getValue('positions'));
		
		foreach ($positions as $pos){
			$sql = 'UPDATE `' . _DB_PREFIX_ . 'an_banners` SET position="'.(int)$position.'" WHERE `id_banner`="'.(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;
    }    
    
}
