<?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)
*/

if (!defined('_PS_VERSION_')) {
    exit;
}

require_once _PS_MODULE_DIR_.'an_theme/classes/InputFactory.php';
require_once _PS_MODULE_DIR_.'an_theme/classes/Validation.php';
require_once _PS_MODULE_DIR_.'an_theme/classes/antheme.php';
require_once _PS_MODULE_DIR_.'an_theme/classes/anThemeFiles.php';

class an_theme extends Module
{
    const ERROR_DEFAULT = -1;

    const PREFIX = 'ant_';

    const CSS_FILE = 'CSS_FILE';
    const CUSTOM_CSS_FILE = 'CUSTOM_CSS_FILE';
    const CUSTOM_JS_FILE = 'CUSTOM_JS_FILE';

    protected $_theme_vars = array();
    protected $_fields = array();
    protected $_theme_fonts = array();
    protected $errors = array();
    protected $inputFactory = null;
    protected $validationMessages = array();
    protected $loadedConfiguration = false;
	
	protected $varsPreset = array('importPresets_presetName', 'importPresets_presetId');

    public $id_shop;
    public $anThemeFiles;
    public $_theme_js;
    public $_theme_css;
    public $_tabbed_fields;


    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        $this->name = 'an_theme';
        $this->tab = 'front_office_features';
        $this->version = '2.5.10';
        $this->author = 'Anvanto';
        $this->need_instance = 0;

        parent::__construct();

        $this->displayName = $this->l('Anvanto Theme Configurator');
        $this->description = $this->l('Anvanto Theme Configurator');
        $this->bootstrap = true;

        $this->setupValidationMessages();
		
        if (Shop::isFeatureActive()) {
            $this->id_shop = Context::getContext()->shop->id;
        } else {
            $this->id_shop = 1;
        }		

        $this->anThemeFiles = new anThemeFiles();        
    }

    public function getAnThemeFiles()
    {
        return $this->anThemeFiles;
    }

    public function install()
    {
        $install = parent::install()
            && $this->registerHook('displayHeader')
            && $this->registerHook('displayBackOfficeHeader')
            && $this->registerHook('actionObjectLanguageAddAfter');
		
        return $install;
    }

    public function uninstall()
    {
		Configuration::deleteByName(self::CSS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id);
        return parent::uninstall();
    }

    protected function setupConfiguration()
    {
        if ($this->loadedConfiguration) {
            return $this;
        }
        
        $this->loadedConfiguration = true;

        return $this->loadThemeFonts()
            ->loadThemeJS()
            ->loadThemeCSS()
            ->loadThemeVars()
            ->loadTabbedFields()
            ->loadFields();
    }

    protected function setupValidationMessages()
    {
        $this->validationMessages = array(
            self::ERROR_DEFAULT => $this->l('An error occurred'),
            AnThemeValidation::ERROR_EMPTY_VALUE => $this->l('Invalid `%s`. Can not be empty!'),
            AnThemeValidation::ERROR_INVALID_NUMBER => $this->l('Invalid `%s`. Should be numeric!'),
            AnThemeValidation::ERROR_INVALID_FLOAT => $this->l('Invalid `%s`. Should be numeric (float)!'),
            AnThemeValidation::ERROR_INVALID_COLOR => $this->l('Invalid `%s`. Should be valid HEX color!')
        );

        return $this;
    }

    public function getValidationErrorByCode($code)
    {
        if (array_key_exists($code, $this->validationMessages)) {
            return $this->validationMessages[$code];
        }

        return $this->validationMessages[self::ERROR_DEFAULT];
    }

    protected function loadConfigFileIfExists($sourceName)
    {
        if (Tools::file_exists_no_cache($this->anThemeFiles->pathConfig . $sourceName . '.php')) {
            return include($this->anThemeFiles->pathConfig . $sourceName . '.php');
        } else if (Tools::file_exists_no_cache(_PS_MODULE_DIR_ . 'an_theme/cfg/' . $sourceName . '.php')) {
            return include(_PS_MODULE_DIR_ . 'an_theme/cfg/' . $sourceName . '.php');
        }

        return [];
    }

    protected function loadThemeFonts()
    {
        $this->_theme_fonts = $this->loadConfigFileIfExists('theme_fonts');
        return $this;
    }

    protected function loadThemeJS()
    {
        $this->_theme_js = $this->loadConfigFileIfExists('theme_js');
        return $this;
    }

    protected function loadThemeCSS()
    {
        $this->_theme_css = $this->loadConfigFileIfExists('theme_css');
        return $this;
    }
    
    protected function loadThemeVars()
    {
        $this->_theme_vars = $this->loadConfigFileIfExists('vars');
        return $this;
    }    

    protected function loadTabbedFields()
    {
        $this->_tabbed_fields = $this->loadConfigFileIfExists('fields');
        return $this;
    }

    protected function loadFields()
    {
        $fields = array_map(function ($tab) {
            return $tab['fields'];
        }, $this->_tabbed_fields);
        $this->_fields = call_user_func_array('array_merge', $fields);

        return $this;
    }

    public function isImageByKey($key)
    {
        $ex = explode('_', $key);
        
        if (
            isset($ex['0'], $ex['1']) && 
            isset($this->_fields[$ex['0']]['options'][$ex['1']]['source']) &&
            $this->_fields[$ex['0']]['options'][$ex['1']]['source'] == 'image'
        ){
            return true;
        }
        return false;
    }

    protected function importConfiguration($configurationSource = '', $defaultPreset = '')
    {
        if ($configurationSource == ''){
			$configurationSource = $this->anThemeFiles->pathPresets . '/configuration.json';
		}

        if (!Tools::file_exists_no_cache($configurationSource)) {
            $configurationSource = $this->local_path . 'configuration.json';
        }

        if (!Tools::file_exists_no_cache($configurationSource)) {
            return false;
        }

        $accepted = $this->getExportConfigurationKeys();
        $configurationJson = Tools::file_get_contents($configurationSource);
        $configuration = (array)json_decode($configurationJson, 1);

        foreach ($configuration as $key => $item) {
            if (in_array($key, $accepted)) {
                if ($this->isImageByKey($key)){
                    $originImageName = $item;
                    $newImageName = $this->anThemeFiles->getNewFileNameExt($originImageName);
                    Tools::copy($this->anThemeFiles->pathImg.$item, $this->anThemeFiles->pathImg . $newImageName);
                    $item = $newImageName;
                    
                    if ($this->getParam($key) != $originImageName){
                        @unlink($this->anThemeFiles->pathImg . $this->getParam($key));
                    }
                }


                $this->getParam($key, $item);
            }
        }
        if ($defaultPreset != ''){
            $this->getParam('importPresets_preset', $defaultPreset);
        }

        return true;
    }

    protected function exportConfiguration($configurationSource = '')
    {
        if ($configurationSource == '' && Tools::file_exists_no_cache($this->anThemeFiles->pathPresets)){
            $configurationSource = $this->anThemeFiles->pathPresets . 'configuration.json';
        } else if ($configurationSource == ''){
            $configurationSource = $this->local_path . 'configuration.json';
        }
        
        $configuration = $this->getConfigFormValuesForExport();
        $configurationJson = json_encode($configuration);
        if (@file_put_contents($configurationSource, $configurationJson)){
            $this->context->controller->confirmations[] = 'Successful export';
            return true;
        }
        return false;
    }

    protected function getConfigFormValuesForExport()
    {
        $unfilteredConfig = $this->getConfigFormValues();
        $filteredConfig = array();

        $acceptedConfigKeys = $this->getExportConfigurationKeys();

        foreach (array_keys($unfilteredConfig) as $key) {
            if (in_array($key, $acceptedConfigKeys)) {
                $filteredConfig[$key] = $unfilteredConfig[$key];
            }
        }

        return $filteredConfig;
    }

    protected function getConfigFormValues()
    {
        $config = array();
        $keys = $this->getConfigKeys();
        $lang = $this->getLangKeys();

        foreach ($keys as $key) {
            if (in_array($key, $lang)) {
                foreach (Language::getLanguages(1, 0, 1) as $id_lang) {
                    $config[$key][$id_lang] = $this->getParamValue($key, $id_lang, $this->context->shop->id);
                }
            } else {
                $config[$key] = $this->getParamValue($key, $this->context->language->id, $this->context->shop->id);
            }
        }

        return $config;
    }

    public function hookActionObjectLanguageAddAfter($params = null)
    {
        $this->setupConfiguration();
        $lang_default = (int)Configuration::get('PS_LANG_DEFAULT');
        $languages = array_map('intval', Language::getLanguages(0, 0, 1));

        if ($params !== null && $params['object'] instanceof Language) {
            $languages[] = (int)$params['object']->id;
        }

        foreach ($this->getLangKeys() as $key) {
            $values[$lang_default] = $this->getParamValue($key, $lang_default);
            
            foreach ($languages as $id_lang) {
                $value = $this->getParamValue($key, $id_lang);

                if ($value === false || empty($value)) {
                    $values[$id_lang] = $values[$lang_default];
                }
            }

            $this->updateParamValue($key, $values);
        }

        return true;
    }

    // For templates
    public function getImage($image)
    {
        $image = $this->getParamValue($image);

        if ($image && Tools::file_exists_no_cache($this->anThemeFiles->pathImg . $image)){
            return $this->anThemeFiles->uriImg . $image;
        }
    }

    // For templates
    public function getImageStatic($image)
    {
        if ($image && Tools::file_exists_no_cache($this->anThemeFiles->pathImg . $image)){
            return $this->anThemeFiles->uriImg . $image;
        }
    }    

	protected function arrayKeyFirst(array $arr) {
		foreach($arr as $key => $unused) {
			return $key;
		}
		return NULL;
	}
    
	protected function importConfigurationInstall(){
		
		$presets = $this->loadPresets();
		$value = $this->arrayKeyFirst($presets);

		if (isset($presets[$value]['folder'])){
			return $this->importConfiguration($presets[$value]['folder'].'/configuration.json', $value);
		} else {
			return $this->importConfiguration();
		}
		
	}

    protected function getConfigKeys()
    {
        $keys = array();
	
        foreach ($this->_fields as $key => $value) {
            foreach (array_keys($value['options']) as $_key) {
                $keys[] = $key.'_'.$_key;
            }
        }
		
		$keys = array_merge($keys, $this->varsPreset);
        return $keys;
    }

    protected function getLangKeys()
    {
        return array_filter($this->getConfigKeys(), function ($key) {
            $buffer = explode('_', $key);
            $key = array_pop($buffer);

            foreach ($this->_fields as $value) {
                if (isset($value['options'][$key])) {
                    return isset($value['options'][$key]['lang']);
                }
            }

            return false;
        });
    }

    protected function getExportConfigurationKeys()
    {
        return $this->getConfigKeys();
    }

    public function hookBackOfficeHeader($params)
    {
        $this->hookDisplayBackOfficeHeader($params);
    }

    public function hookDisplayBackOfficeHeader($params = null)
    {
        if (in_array($this->name, array(Tools::getValue('module_name'), Tools::getValue('configure')))) {
            $this->context->controller->addJquery();
            $this->context->controller->addCSS($this->_path.'/views/css/back.css');
            $this->context->controller->addJS($this->_path.'/views/js/back.js');

            $this->context->controller->addCSS($this->_path.'/views/codemirror/lib/codemirror.css');
            $this->context->controller->addJS($this->_path.'/views/codemirror/lib/codemirror.js');
            $this->context->controller->addJS($this->_path.'/views/codemirror/mode/javascript/javascript.js');
            $this->context->controller->addJS($this->_path.'/views/codemirror/mode/css/css.js');
            $this->context->controller->addCSS($this->_path.'/views/codemirror/codemirror.css');
            $this->context->controller->addJS($this->_path.'/views/codemirror/codemirror.js');


        }

        $mainCssPath = $this->anThemeFiles->getCssJsPath($this->getCSSFileName());
        if (!$mainCssPath){
            $this->setupConfiguration();
            $this->firstStart();
        }
    }

    public function hookDisplayHeader()
    { 
        $this->setupConfiguration();
        $mainCssPath = $this->firstStart();

        foreach ($this->_fields as $field_key => $field) {
            foreach ($field['options'] as $option_key => $option) {
                $field_id = $field_key . '_' . $option_key;
                $value = $this->getParam($field_id, null, null, $this->context->shop->id);

                if (isset($option['type']) && $option['type'] == 'font') {

                    if (isset($this->_theme_fonts[$value]['link'])) {
                        $this->addCssJsFile([
                            'server' => 'remote',
                            'path' => $this->_theme_fonts[$value]['link']
                        ]);
                    } elseif (isset($this->_theme_fonts[$value]['path'])) {                 
                        $this->addCssJsFile([
                            'server' => 'local',
                            'filePath' => $this->anThemeFiles->getFontPath($this->_theme_fonts[$value]['path'])
                        ]);
                    }
                }
                
                if (isset($option['type']) && $option['type'] == 'fileAdd' && $value) {
                    foreach ($option['files'] as $jsCss){
                        if (!isset($jsCss['type'])){
                            $jsCss['type'] = 'js';
                        }
                        $this->addCssJsFile($jsCss, $jsCss['type']);
                    }
                }
                
                if (isset($option['type']) && $option['type'] == 'selectFileAdd') {
                    
                    if (isset($option['files'][$value])){
                        foreach ($option['files'][$value] as $jsCss){
                            if (!isset($jsCss['type'])){
                                $jsCss['type'] = 'js';
                            }
                            $this->addCssJsFile($jsCss, $jsCss['type']);
                        }
                    }
                }
                
                if ($option['source'] == 'exSelect'){
                    
                    if (isset($option['options'][$value]['css'])){
                        foreach ($option['options'][$value]['css'] as $fileCss){
                            $this->addCssJsFile($fileCss);
                        }
                    }

                    if (isset($option['options'][$value]['js'])){
                        foreach ($option['options'][$value]['js'] as $fileJs){
                            $this->addCssJsFile($fileJs, 'js');
                        }
                    }                    
                }
            }
        }

        if ($mainCssPath){
            $this->addCssJsFile(['filePath' => $mainCssPath]);
        }

        if(Configuration::get(self::CUSTOM_CSS_FILE)){
            $this->addCssJsFile([
                'fileName' => Configuration::get(self::CUSTOM_CSS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id), 
                'priority' => 9999 
            ]);
        }

        if(Configuration::get(self::CUSTOM_JS_FILE)){
            $this->addCssJsFile([
                'fileName' => Configuration::get(self::CUSTOM_JS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id), 
                'priority' => 9999
            ], 'js');
        }

        foreach ($this->_theme_js as $js) {
            $this->addCssJsFile($js, 'js');
        }

        foreach ($this->_theme_css as $css) {
            $this->addCssJsFile($css);
        }
        
        foreach ($this->_theme_vars as $key => $val) {
            $this->context->smarty->assign($key, $val);
        }        
    }

    public function importDemoForModule($moduleName)
    {
        if (Module::isEnabled($moduleName) && method_exists(Module::getInstanceByName($moduleName), 'importDemoContent')){
            Module::getInstanceByName($moduleName)->importDemoContent();
        }
    }

    public function firstStart()
    { 
        $mainCssPath = $this->anThemeFiles->getCssJsPath($this->getCSSFileName());
 
        if ($mainCssPath){
            return $mainCssPath;
        }

        $this->importDemoForModule('an_homeslider');
        $this->importDemoForModule('an_homeproducts');
        $this->importDemoForModule('an_advantages');
        $this->importDemoForModule('an_homecategories');
        $this->importDemoForModule('an_trust_badges');
        $this->importDemoForModule('anblog');
       
        $this->setDefaultValues();  
        $this->hookActionObjectLanguageAddAfter();
        $this->importConfigurationInstall();
        $this->updateAnvantoModules();
        $this->updateModulesHooks();
        $this->findCssJsFiles();

        $mainCssPath = $this->anThemeFiles->getCssJsPath($this->getCSSFileName());
        if (!$mainCssPath){
            $this->generateFiles();
            $mainCssPath = $this->anThemeFiles->getCssJsPath($this->getCSSFileName());
        }        

        return $mainCssPath;
    }

    public function addCssJsFile($file, $format = 'css')
    {
        if (!isset($file['server'])){
            $file['server'] = 'local';
        }

        if (!isset($file['media']) && $format == 'css'){
            $file['media'] = 'local';
        }

        if (!isset($file['priority'])){
            $file['priority'] = '200';
        }

        if (!isset($file['position']) && $format == 'js'){
            $file['position'] = 'bottom';
        }

        if (isset($file['path'])){
            $file['fileName'] = basename($file['path']);
        }

        $path = '';
        if (isset($file['fileName'])){
            $path = $this->anThemeFiles->getCssJsPath($file['fileName'], $format);
        }

        if (isset($file['filePath'])){
            $path = $file['filePath'];
        }
        
        if ($file['server'] == 'remote'){
            $path = $file['path'];
        } else if ($path == '' && isset($file['path']) ) {
            $path = 'modules/'.$this->name.'/'.$file['path'];
        }

        if ($path == ''){
            return false;
        }

        if ($format == 'css'){
            $this->context->controller->registerStylesheet(
                'antheme-' . md5($path), 
                $path, 
                $file
            );
        } else {
            $this->context->controller->registerJavascript(
                'antheme-' . md5($path),
                $path, 
                $file
            );
        }
    }

    protected function getCSSFileName()
    {
        return Configuration::get(self::CSS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id);
    }

    protected function updateFileName($key, $fileName)
    {
        if (!$key || $key == ''){
            return false;
        }

        if ($this->isUsedFile($key, $fileName)){
            return false;
        }

        return Configuration::updateValue($key, $fileName, false, $this->context->shop->id_shop_group, $this->context->shop->id);
    }

    public function isUsedFile($key, $fileName, $excludeCurrent = false)
    {
        $shops = Shop::getShops();
        foreach ($shops as $shop){
            $name = Configuration::get($key, null, $shop['id_shop_group'], $shop['id_shop']);
            if (
                ($name == $fileName && ($excludeCurrent && $shop['id_shop'] != $this->context->shop->id)) || 
                ($name == $fileName && !$excludeCurrent)){
                return true;
            }
        }

        return false;
    }

    public function findCssJsFiles()
    {
        $globalCssFileName = $this->anThemeFiles->findFile("antheme-*.css", $this->anThemeFiles->pathCss, $this->anThemeFiles->oldPathCss);
        $customCSSFileName = $this->anThemeFiles->findFile("customcss-*.css", $this->anThemeFiles->pathCss, $this->anThemeFiles->oldPathCss);
        $customjsFileName = $this->anThemeFiles->findFile("customjs-*.js", $this->anThemeFiles->pathJs, $this->anThemeFiles->oldPathJs);
        
        $this->updateFileName(self::CSS_FILE, $globalCssFileName);
        $this->updateFileName(self::CUSTOM_CSS_FILE, $customCSSFileName);
        $this->updateFileName(self::CUSTOM_JS_FILE, $customjsFileName);
    }








    





    protected function getParamValue($key, $id_lang = null, $id_shop = null)
    {
        $input = $this->getInputFactory()->create($key);
        $defaultValue = $input->getData('default', '');
        return Configuration::get(self::PREFIX.$key, $id_lang, null, $id_shop ? $id_shop : $this->context->shop->id, $defaultValue);
    }

    /**
     * Get/Set a parameter
     *
     * @param string $key
     * @param mixed $value
     * @return mixed
     */
    public function getParam($key, $value = null, $id_lang = null, $id_shop = null)
    { 
        if ($value === null) {
            return $this->getParamValue($key, $id_lang, $id_shop);
        }

        try {
            $this->updateParamValue($key, $value, $id_shop);
        } catch (ReflectionException $e) {
            // $this->errors[] = $this->displayError($this->l('Invalid validator. Please contact with developer'));
        }
    }

    protected function updateParamValue($key, $value, $id_shop = null)
    {
        $input = $this->getInputFactory()->create($key);
        $ex_key = explode('_', $key);
        if (isset($this->_fields[$ex_key['0']]['options'][$ex_key['1']]['source'])){
            $source = $this->_fields[$ex_key['0']]['options'][$ex_key['1']]['source'];
        } else {
            $source = '';
        }

        if ($input->validateValue($value)) {
            if ($source == 'switch'){
                if ($value == '1'){
                    $value = true;
                } else {
                    $value = false;
                }
            }
            return Configuration::updateValue(self::PREFIX.$key, $value, null, null, $id_shop ? $id_shop : $this->context->shop->id);
        } else {
            $errors = $input->errors;
            foreach ($errors as &$error) {
                $error = $this->displayError($error);
            }
            $this->errors = array_merge($this->errors, $errors);
        }

        return false;
    }

    /**
     * Upload an image
     *
     * @param string $name
     * @return bool
     */
    protected function uploadImage($name)
    {
        if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name'])) {
            $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
            if (!$tmp_name) {
                return false;
            }

            if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name)) {
                return false;
            }

            if (!ImageManager::checkImageMemoryLimit($tmp_name)) {
                return false;
            }

            $this->anThemeFiles->checkCreateFolder($this->anThemeFiles->pathImg);

            $image = $this->anThemeFiles->getNewFileNameExt($_FILES[$name]['name']);     
            
            if (!ImageManager::resize($tmp_name, $this->anThemeFiles->pathImg . $image)) {
                return false;
            }

            if (count($this->errors)) {
                return false;
            }

            @unlink($tmp_name);
        } else {
            return false;
        }

        return $image;
    }
	
	protected function loadPresets()
	{	
		$presets = [];
		$presetsFolders = glob($this->anThemeFiles->pathPresets . 'import/*');
        if (!$presetsFolders || count($presetsFolders) < 1){
            $presetsFolders = glob(_PS_MODULE_DIR_ . $this->name . '/import/*');
        }
      
		foreach ($presetsFolders as $folderPath){
		
			if (Tools::file_exists_no_cache($folderPath . '/configuration.json')){
				
				$configurationJson = Tools::file_get_contents($folderPath . '/configuration.json');
				$configuration = (array)json_decode($configurationJson, 1);
				
				if (isset($configuration['importPresets_presetName'], $configuration['importPresets_presetId'])){
					$presets[$configuration['importPresets_presetId']]['name'] = $configuration['importPresets_presetName'];
					$presets[$configuration['importPresets_presetId']]['folder'] = $folderPath;
					
					if (Tools::file_exists_no_cache($folderPath . '/preview.jpg')){
						
						$exFolder = explode('/', $folderPath);
						$folder = array_pop($exFolder);

						$presets[$configuration['importPresets_presetId']]['preview'] = '../modules/'.$this->name.'/import/'.$folder.'/preview.jpg';
					} else {
						$presets[$configuration['importPresets_presetId']]['preview'] = '';
					}
				}
			}
		}	
		
		return $presets;
	}
	

    protected function importPreset(){
		
        $id_tab = (int)Tools::getValue('id_tab', 0);
		if (isset($this->_tabbed_fields[$id_tab]['legend']['id']) && $this->_tabbed_fields[$id_tab]['legend']['id'] == 'anthemeimport'){

			foreach ($this->_fields as $field_key => $field) {
				foreach ($field['options'] as $option_key => $option) {
					
					$field_id = $field_key . '_' . $option_key;
					$value = $this->getParam($field_id, null, null, $this->context->shop->id);
					
					if ($option['source'] == 'presets'){

						$presets = $this->loadPresets();
						if (isset($presets[$value]['folder'])){
							$this->importConfiguration($presets[$value]['folder'].'/configuration.json');
						}		
					}
					
				}
			}
		}	
        return true;
    }
	
    
    protected function updateModulesHooks($checkPermission = false){
							
        foreach ($this->_fields as $field_key => $field) {
            foreach ($field['options'] as $option_key => $option) {
                
                $field_id = $field_key . '_' . $option_key;
                $value = $this->getParam($field_id, null, null, $this->context->shop->id);

                if ($option['source'] == 'exSelect' && (!$checkPermission || ($checkPermission && Tools::getIsset($field_id.'_apply')))  ){
                    
                    if (isset($option['options'][$value]['unregisterHook'])){
                        foreach ($option['options'][$value]['unregisterHook'] as $moduleName => $hooks){
                            foreach ($hooks as $hook){
                                Module::getInstanceByName($moduleName)->unregisterHook($hook, array($this->id_shop));
                            }
                        }
                    }
					
					if (!isset($option['options'][$value]['ignoreHooks'])){
						$option['options'][$value]['ignoreHooks'] = array();
					}
					
                    if (isset($option['options'][$value]['unregisterAllHooks'])){
                        foreach ($option['options'][$value]['unregisterAllHooks'] as $moduleName){
							$this->unregisterAllHooksModule($moduleName, $option['options'][$value]['ignoreHooks']);
                        }
                    }						

                    if (isset($option['options'][$value]['registerHook'])){
                        foreach ($option['options'][$value]['registerHook'] as $moduleName => $hooks){
                            if (Module::isInstalled($moduleName)){
                                foreach ($hooks as $hook){
                                    Module::getInstanceByName($moduleName)->registerHook($hook, array($this->id_shop));                                        
                                }
                            }
                        }
                    }
                }
                
            }
        }
        return true;
    }
	
    protected function unregisterAllHooksModule($moduleName, $ignoreHooks = array()){
		
		if ($moduleName == ''){
			return false;
		}
			
		$moduleId = Module::getModuleIdByName($moduleName);
		
        $sql = 'SELECT DISTINCT(`id_hook`) FROM `' . _DB_PREFIX_ . 'hook_module` WHERE `id_module` = ' . (int) $moduleId;
        $result = Db::getInstance()->executeS($sql);
        foreach ($result as $row) {
			
            $hookName = false;
            try {
                $hookName =  hook::getNameById($row['id_hook']);
            } catch (Exception $ex) {
                $hookName = false;
            }            

			if ($hookName && hook::isDisplayHookName($hookName) && !in_array($hookName, $ignoreHooks)){
				 Module::getInstanceByName($moduleName)->unregisterHook($hookName, array($this->id_shop));
			}
        } 
	}	
	
    protected function updateAnvantoModules($checkPermission = false){
							
        foreach ($this->_fields as $field_key => $field) {
            foreach ($field['options'] as $option_key => $option) {
                
                $field_id = $field_key . '_' . $option_key;
                $value = $this->getParam($field_id, null, null, $this->context->shop->id);

                if ($option['source'] == 'exSelect' && (!$checkPermission || ($checkPermission && Tools::getIsset($field_id.'_apply')))  ){

                    // AN Theme Blocks
                    if (isset($option['options'][$value]['toEnableTb'])){
                        foreach ($option['options'][$value]['toEnableTb'] as $blockId){
                            antheme::changeStatusANThemeBlock($blockId, 1);
                        }
                    }
					
                    if (isset($option['options'][$value]['toDisableTb'])){
                        foreach ($option['options'][$value]['toDisableTb'] as $blockId){
                            antheme::changeStatusANThemeBlock($blockId, 0);
                        }
                    }

                    // an_homeproducts - blocks
                    if (isset($option['options'][$value]['enable_an_homeproducts_blocks'])){
                        foreach ($option['options'][$value]['enable_an_homeproducts_blocks'] as $blockId){
                            antheme::changeStatusANHomeProductsBlock($blockId, 1);
                        }
                    }
					
                    if (isset($option['options'][$value]['disable_an_homeproducts_blocks'])){
                        foreach ($option['options'][$value]['disable_an_homeproducts_blocks'] as $blockId){
                            antheme::changeStatusANHomeProductsBlock($blockId, 0);
                        }
                    }  
                    
                    // an_homeproducts - banners
                    if (isset($option['options'][$value]['enable_an_homeproducts_banners'])){
                        foreach ($option['options'][$value]['enable_an_homeproducts_banners'] as $blockId){
                            antheme::changeStatusANHomeProductsBanner($blockId, 1);
                        }
                    }
					
                    if (isset($option['options'][$value]['disable_homeproducts_banners'])){
                        foreach ($option['options'][$value]['disable_homeproducts_banners'] as $blockId){
                            antheme::changeStatusANHomeProductsBanner($blockId, 0);
                        }
                    }    

                    // an_banners
                    if (isset($option['options'][$value]['enable_an_banners'])){
                        foreach ($option['options'][$value]['enable_an_banners'] as $blockId){
                            antheme::changeStatusANBanners($blockId, 1);
                        }
                    }
					
                    if (isset($option['options'][$value]['disable_an_banners'])){
                        foreach ($option['options'][$value]['disable_an_banners'] as $blockId){
                            antheme::changeStatusANBanners($blockId, 0);
                        }
                    }                
                    
                    //  Options
                    if (isset($option['options'][$value]['configurations'])){
                        antheme::updateConfigurations($option['options'][$value]['configurations']);
                    }

                    //  Clear cache
                    if (isset($option['options'][$value]['an_homeproducts_clear_cache'])){
                        antheme::clearCacheAn_homeproducts();
                    }

                }
                
            }
        }
        return true;
    }		
	


    

    /**
     * Select renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function selectRenderer($field_id, $option, $input)
    {
        $options = array(
            'optiongroup' => array(
                'label' => 'label',
                'query' => array()
            ),
            'options' => array(
                'query' => 'options',
                'id' => 'id',
                'name' => 'name'
            )
        );

        $query = array();

        if (isset($option['type']) && $option['type'] == 'font') {
            foreach ($this->_theme_fonts as $key => $font) {
                $query[] = array(
                    'id' => $key,
                    'name' => $font['name'],
                );
            }
        } else if (isset($option['type']) && $option['type'] == 'tpl') {
            $files = glob(_PS_MODULE_DIR_ . $this->name . $option['path'] . '*');

            foreach ($files as $file) {
                $filename = basename($file);

                if (is_file($file) && $filename != 'index.php') {
                    $query[] = array(
                        'id' => $option['path'] . $filename,
                        'name' => $filename,
                    );
                }
            }
        } else {
            foreach ($option['options'] as $option_value => $value) {
                if (is_integer($option_value) && is_scalar($value)) {
                    $query[] = array(
                        'id' => $value,
                        'name' => $value
                    );
                } else if (is_array($value)) {
                    if (isset($value['label'])) {
                        $_query = array();

                        foreach ($value['query'] as $_option_value => $option_name) {
                            if (is_integer($_option_value)) {
                                $_query[] = array(
                                    'id' => $option_name,
                                    'name' => $option_name
                                );
                            } else {
                                $_query[] = array(
                                    'id' => $_option_value,
                                    'name' => $option_name
                                );
                            }
                        }

                        $options['optiongroup']['query'][] = array(
                            'label' => $value['label'],
                            'options' => $_query
                        );
                    }
                } else {
                    $query[] = array(
                        'id' => $option_value,
                        'name' => $value
                    );
                }
            }
        }

        $input['type'] = 'select';

        if (!empty($options['optiongroup']['query'])) {
            $input['options'] = $options;
        } else {
            $input['options'] = array(
                'query' => $query,
                'id' => 'id',
                'name' => 'name',
            );
        }

        return $input;
    }

    /**
     * Switch renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function switchRenderer($field_id, $option, $input)
    {
        $input['type'] = 'switch';
        $input['is_bool'] = true;
        $input['values'] = array(
            array(
                'id' => $field_id . '_on',
                'value' => 1,
                'label' => $this->l('Yes')
            ),
            array(
                'id' => $field_id . '_off',
                'value' => 0,
                'label' => $this->l('No')
            )
        );

        return $input;
    }

    /**
     * exSelect renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function exSelectRenderer($field_id, $option, $input)
    {
        $options = array(
            'optiongroup' => array(
                'label' => 'label',
                'query' => array()
            ),
            'options' => array(
                'query' => 'options',
                'id' => 'id',
                'name' => 'name'
            )
        );

        $query = []; 
        foreach ($option['options'] as $key => $value) {
            $query[] = array(
                'id' => $key,
                'name' => $value['name']
            );
        }

        $input['type'] = 'select';
		$input['typeSub'] = 'exSelect';
		$input['class'] = 'exSelect';

        if (!empty($options['optiongroup']['query'])) {
            $input['options'] = $options;
        } else {
            $input['options'] = array(
                'query' => $query,
                'id' => 'id',
                'name' => 'name',
            );
        }

        return $input;
    }
    
	
    /**
     * selectPresets renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function presetsRenderer($field_id, $option, $input, $helper)
    {
		/*
		$input['type'] = 'free';
		$currentValue = $this->getParam($field_id, null , $this->context->language->id, $this->context->shop->id);
		$presets = $this->loadPresets();
		$html = '';
		$checked = '';
        foreach ($presets as $id => $value) {
			$checked = ($currentValue == $id ? ' checked="checked"' : '');
            $html .= '
                <div class="an_theme-preset-item" style="float: left;">
					<label>
						<img src="'.$value['preview'].'" width="100" /><br/>
						<input type="radio" name="' . $field_id . '" value="' . $id . '"' . $checked . ' /> ' . $value['name'] . '
					</label>
                </div>';
			
        }
		
		
		$helper->fields_value[$field_id] = $html;
		*/
		
 		$input['type'] = 'radio';
		
		$presets = $this->loadPresets();
		
        foreach ($presets as $id => $value) {
            $input['values'][] = array(
                'id' => $id,
                'value' => $id,
				'label' => $value['name'],
            );
			
        }

		return $input; 
    }

    /**
     * Image renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function imageRenderer($field_id, $option, $input)
    {
        $defaultKey = explode('_', $field_id);
        $defaultInput = $this->_fields[$defaultKey[0]]['options'][$defaultKey[1]];
        
        $image = $this->anThemeFiles->pathImg . $this->getParam($field_id, null , $this->context->language->id, $this->context->shop->id);
        $image_url = false;
        $thumb_size = false;

        if (is_file($image) && file_exists($image)) {
            $image_url = '<img src="' . $this->anThemeFiles->uriImg . basename($image) . '?rand=' . rand(1, 1000) . '" class="imgm img-thumbnail" />';
            $thumb_size = filesize($image) / 1000;
        }

        $input['type'] = 'file';
        $input['display_image'] = true;
        $input['image'] = $image_url;
        $input['size'] = $thumb_size;
        $input['format'] = 'medium';

        if (isset($defaultInput['allow_delete']) && $defaultInput['allow_delete'] === true) {
            $input['delete_url'] = $this->context->link->getAdminLink('AdminModules').'&id_tab='.Tools::getValue('id_tab').'&configure='.$this->name.'&delete_image='.$input['name'];
        }

        return $input;
    }

    /**
     * Number renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function numberRenderer($field_id, $option, $input, $helper)
    {
        $input['type'] = 'number';
        return $input;
    }

    protected function floatRenderer($field_id, $option, $input, $helper)
    {
        $input['type'] = 'number';
        $input['step'] = 0.01;

        if (isset($option['step'])) {
            $input['step'] = $option['step'];
        }

        if (isset($option['min'])) {
            $input['min'] = $option['min'];
        }

        if (isset($option['max'])) {
            $input['max'] = $option['max'];
        }

        return $input;
    }
    
    /**
     * Picker renderer
     *
     * @param string $field_id
     * @param array $option
     * @param array $input
     * @return array
     */
    protected function pickerRenderer($field_id, $option, $input, $helper)
    {
        $input['type'] = 'color';
        return $input;
    }

    /**
     * CSS Generator
     *
     * @return void
     */
    protected function generateFiles()
    {
        foreach ($this->_fields as $field_key => $field) {
            foreach ($field['options'] as $option_key => $option) {
                $field_id = $field_key . '_' . $option_key;
                $value = $this->getParam($field_id,null, null, $this->context->shop->id);

                if (isset($option['type']) && $option['type'] == 'font') {
                    $value = isset($this->_theme_fonts[$value]['css']) ? $this->_theme_fonts[$value]['css'] : $this->_theme_fonts[$value]['link'];
                } else {
                    if ($option['source'] == 'switch') {
                        if ($value && isset($option['css'])) {
                            $value = $option['css'];
                        }
                    } else if ($option['source'] == 'color') {
                        if (!Validate::isColor($value)) {
                            $value = 'url(' . $this->_path . $value . ')';
                        }
                    }
                }

                $this->context->smarty->assign($field_id, $value);
            }
        }
        
        $exportFileName = $this->anThemeFiles->generateFileName('css');
        $this->context->smarty->assign('module_path', $this->_path);
        
        $cssGeneratorPathFile = $this->getTemplatePath('css_generator.tpl');
        
        if ($cssGeneratorPathFile == ''){
            return false;
        }
        $cssForExport = @$this->fetch($cssGeneratorPathFile);
        $resultCssSave = @file_put_contents($this->anThemeFiles->getCssDir() . $exportFileName, $cssForExport);
        
        if ($resultCssSave){
            $this->anThemeFiles->killFile($this->getCSSFileName());
            $this->updateFileName(self::CSS_FILE, $exportFileName);
        }

        if (Tools::isSubmit('custom_code_code_css')){
            $this->anThemeFiles->killFile(Configuration::get(self::CUSTOM_CSS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id));
            $customCSSFileName = $this->anThemeFiles->generateFileName('css', 'customcss-');
            $customCode = Tools::getValue('custom_code_code_css');
            if ($customCode != ''){
                @file_put_contents($this->anThemeFiles->getCssDir() . $customCSSFileName, $customCode);
                $this->updateFileName(self::CUSTOM_CSS_FILE, $customCSSFileName);
            } else {
                Configuration::deleteByName(self::CUSTOM_CSS_FILE);
            }
        }

        if (Tools::isSubmit('custom_code_code_js')){
            $this->anThemeFiles->killFile(Configuration::get(self::CUSTOM_JS_FILE, null, $this->context->shop->id_shop_group, $this->context->shop->id));
            $customJSFileName = $this->anThemeFiles->generateFileName('js', 'customjs-');
            $customCode = Tools::getValue('custom_code_code_js');
            if ($customCode != ''){
                @file_put_contents($this->anThemeFiles->getJsDir() . $customJSFileName, $customCode);                
                $this->updateFileName(self::CUSTOM_JS_FILE, $customJSFileName);
            } else {
                Configuration::deleteByName(self::CUSTOM_JS_FILE);
            }
        }

        return true;
    }
   

    /**
     * Generate configuration form
     *
     * @return string
     */
    public function displayForm($fields)
    {
        $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
        $helper = new HelperForm();

        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name . '&id_tab=' . $this->getIdTab();

        $helper->default_form_language = $default_lang;
        $helper->allow_employee_form_lang = $default_lang;
        $helper->title = $this->displayName;
        $helper->submit_action = $this->name;

        $fields_form = array();
        $field_counter = 0;

        foreach ($fields as $field_key => $field) {
            $fields_form[$field_counter]['form'] = array(
                'legend' => array(
                    'title' => $this->l($field['title']),
                ),
                'input' => array(),
                'submit' => array(
                    'title' => $this->l('Save'),
                )
            );

            foreach ($field['options'] as $option_key => $option) {
                
                $field_id = $field_key . '_' . $option_key;
                if (isset($option['type']) && $option['type'] == 'textarea') {

                    $form_group_class = '';
                    $col = 8;

                    // if ($option_key == 'code_css' || $option_key == 'code_js'){
                    //     $form_group_class = 'an-theme-group-custom-code';
                    //     $col = 12;
                    // }                    

                    $input = array(
                        'type' => 'textarea',
                        'form_group_class' => $form_group_class,
                        'col' => $col,                        
                        'rows' => $option['rows'],
                        'label' => $this->l($option['title']),
                        'name' => $field_id,
                        'desc' => $this->l($option['description']),
                        'required' => isset($option['allow_empty']) ? !$option['allow_empty'] : false
                    );

                    $path = $this->anThemeFiles->getCssJsPath(Configuration::get('CUSTOM_' . Tools::strtoupper($option['file_type']) . '_FILE' ), $option['file_type']);
                    $helper->fields_value[$field_id] = Tools::file_get_contents(_PS_ROOT_DIR_ . '/' . $path);
                } else {
                    $input = array(
                        'type' => 'text',
                        'label' => $this->l($option['title']),
                        'name' => $field_id,
                        'desc' => $this->l($option['description']),
                        'required' => isset($option['allow_empty']) ? !$option['allow_empty'] : false
                    );
                    if (isset($option['lang']) && $option['lang'] === true) {
                        $input['lang'] = true;
                        $input['col'] = 6;

                        foreach (Language::getLanguages(1, 0, 1) as $id_lang) {
                            $helper->fields_value[$field_id][$id_lang] = $this->getParam($field_id, null, null, (int)$id_lang, $this->context->shop->id);
                        }
                    } else {
                        $helper->fields_value[$field_id] = $this->getParam($field_id, null, $this->context->language->id, $this->context->shop->id);

                        if ($option['source'] == 'switch' && $helper->fields_value[$field_id] == ''){
                            $helper->fields_value[$field_id] = false;
                        }
                    }
                }

                $renderMethod = $option['source'].'Renderer';

                if (method_exists($this, $renderMethod)) {
                    $input = $this->$renderMethod($field_id, $option, $input, $helper);
                }

                $fields_form[$field_counter]['form']['input'][] = $input;
            }

            $field_counter++;
        }

        $helper->languages = $this->context->controller->getLanguages();
        $helper->tpl_vars = array(
            'base_url' => $this->context->shop->getBaseURL(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        );
        
        return $helper->generateForm($fields_form);
    }

    protected function setDefaultValues()
    {
        foreach ($this->_fields as $field_key => $field) {
            foreach ($field['options'] as $option_key => $option) {
                if (isset($option['default'])) {
                    $this->getParam($field_key.'_'.$option_key, $option['default'], $this->context->language->id, $this->context->shop->id);
                }
            }
        }

        return true;
    }

    protected function deleteImage()
    {
        $image = Tools::getValue('delete_image');
        $path = realpath($this->anThemeFiles->pathImg . $this->getParam($image, null, $this->context->language->id, $this->context->shop->id));

        if ($image !== false) {
            if (Tools::file_exists_no_cache($path)) {
                @unlink($path);
                $this->getParam($image, '', $this->context->language->id, $this->context->shop->id);
            }
        }
    }

    /**
     * Get configuration page
     *
     * @return string
     */
    public function getContent()
    {
        if (Shop::getContextShopID() || Shop::getContextShopGroupID()){

            $this->setupConfiguration();
            $this->firstStart();        
            
            if (Tools::isSubmit('dev')) {
				
				$currentPreset = $this->getParam('importPresets_preset', null, null, $this->context->shop->id);
				$presets = $this->loadPresets();
				if (isset($presets[$currentPreset]['folder'])){
					$this->exportConfiguration($presets[$currentPreset]['folder'].'/configuration.json');
				} else {
					$this->exportConfiguration();
				}

            } else if (Tools::getIsset('delete_image')) {
                $this->deleteImage();
                $this->generateFiles();
            } else if (Tools::getIsset($this->name)) {
                				
				$checkPermission = false;
				if (!Tools::getIsset('importPresets_preset')){
					$checkPermission = true;
				}
				
				$this->postProcess();
				
				$this->importPreset();
				$this->updateAnvantoModules($checkPermission);
                $this->updateModulesHooks($checkPermission);

                $this->generateFiles();
                $this->redirectAfterUpdate();
            }

            return $this->showBackendContentPage();
        } else {
            $this->context->controller->warnings[] = $this->l('Please, select a shop of your multistore first you want to apply changes for');
        }

    }

    protected function redirectAfterUpdate()
    {
        if (empty($this->errors)) {
            $module = 'AdminModules'.(int)Tab::getIdFromClassName('AdminModules').(int)$this->context->employee->id;
            $token = Tools::getAdminToken($module);
            
            $redirectAfter = 'index.php?tab=AdminModules&conf=4&configure='.$this->name.'&id_tab='.$this->getIdTab();
            $redirectAfter .= '&token='.$token;
            
            Tools::redirectAdmin($redirectAfter);
        }
    }

    public function postProcess()
    {
        $id_tab = (int)Tools::getValue('id_tab', 0);

        if ($id_tab >= 0 && isset($this->_tabbed_fields[$id_tab])) {
            foreach ($this->_tabbed_fields[$id_tab]['fields'] as $field_key => $field) {
                if ($field_key != 'custom_code'){
                    foreach ($field['options'] as $option_key => $option) {
                        $field_id = $field_key . '_' . $option_key;

                        if (isset($option['lang']) && $option['lang'] == true) {
                            $value = array();

                            foreach (Language::getLanguages(1, 1, 1) as $id_lang) {
                                $value[$id_lang] = Tools::getValue($field_id.'_'.$id_lang, '');
                            }
                        } elseif (Tools::getIsset($field_id)) {
                            $value = Tools::getValue($field_id);
                        }

                        if (isset($_FILES[$field_id])) {
                            if (!$_FILES[$field_id]['error']) {
                                if ($result = $this->uploadImage($field_id)) {
                                    @unlink($this->anThemeFiles->pathImg . $this->getParam($field_id, null, $this->context->language->id, $this->context->shop->id));
                                    $this->getParam($field_id, $result, $this->context->language->id, $this->context->shop->id);
                                } else {
                                    $this->errors[] = $this->l('Error during file uploading');
                                }
                            }
                        } else {
                            $this->getParam($field_id, $value, $this->context->language->id, $this->context->shop->id);
                        }
                    }
                }
            }
        }		
    }

    protected function showBackendContentPage()
    {
        $idTab = $this->getIdTab();
        $currentTabRaw = $this->_tabbed_fields[$idTab];
        $tabs = array();
        $currentTab = $this->displayError($this->l('The tab does not exist content'));
        $i = 0;

        if (isset($currentTabRaw, $currentTabRaw['fields'])) {
            $currentTab = array(
                'legend' => $currentTabRaw['legend'],
                'form' => $this->displayForm($currentTabRaw['fields'])
            );
        }

        foreach ($this->_tabbed_fields as $tabContainsFields) {
            $tabs[] = array(
                'legend' => $tabContainsFields['legend'],
                'link' => $this->context->link->getAdminLink('AdminModules').'&configure='.$this->name.'&id_tab='.$i++
            );
        }

        $this->context->smarty->assign(array(
            'tabs' => $tabs,
            'id_tab' => $idTab,
            'tab' => $currentTab
        ));
		
		$this->context->smarty->assign('theme', $this->getThemeInfo());
		
        return implode('', (array)$this->errors).$this->display(__FILE__, 'views/templates/admin/form.tpl');
    }

    protected function getIdTab()
    {
        return (int)Tools::getValue('id_tab', 0);
    }

    protected function getInputFactory()
    {
        if (!($this->inputFactory instanceof AnThemeInputFactory)) {
            $this->inputFactory = new AnThemeInputFactory($this->_fields);
        }

        return $this->inputFactory;
    }

        
    public function getImageByGroupId($productId, $id_attribute_group)
    {
        $productObj = new Product($productId, false, (int)$this->context->language->id);	

        $groups = [];
        $attributes_groups = $productObj->getAttributesGroups($this->context->language->id);        
        if (is_array($attributes_groups) && $attributes_groups) {
            $combination_images = $productObj->getCombinationImages($this->context->language->id);

            foreach ($attributes_groups as $k => $row) {

                $groups[$row['id_attribute']]['id_product_attribute' ] = $row['id_product_attribute'];
                $groups[$row['id_attribute']]['img_url'] = '';
                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                    $groups[$row['id_attribute']]['id_image'] = -1;
                    $groups[$row['id_attribute']]['legend'] = '';
                } else {
                    $groups[$row['id_attribute']]['id_image'] = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                    $groups[$row['id_attribute']]['legend'] =  $combination_images[$row['id_product_attribute']][0]['legend'];
                    $groups[$row['id_attribute']]['img_url'] = $this->context->link->getImageLink(
                        $productObj->link_rewrite,  $groups[$row['id_attribute']]['id_image'], 'small_default'
                    );   
                }               
            }
        }    
        
        if (isset($groups[$id_attribute_group])){
            return $groups[$id_attribute_group];
        }

        return false;        
    }
	
    /**
    ** удалить после обновления карточки товара
     */
    public static function getIdProductAttributeByIdAttributes($idProduct, $idAttributes, $findBest = false)
    {
        $idProduct = (int) $idProduct;

        if (!is_array($idAttributes) && is_numeric($idAttributes)) {
            $idAttributes = [(int) $idAttributes];
        }

        if (!is_array($idAttributes) || empty($idAttributes)) {
            //throw new PrestaShopException(sprintf('Invalid parameter $idAttributes with value: "%s"', print_r($idAttributes, true)));
			return false;
        }

        $idAttributesImploded = implode(',', array_map('intval', $idAttributes));
        $idProductAttribute = Db::getInstance()->getValue(
            '
            SELECT
                pac.`id_product_attribute`
            FROM
                `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
            WHERE
                pa.id_product = ' . $idProduct . '
                AND pac.id_attribute IN (' . $idAttributesImploded . ')
            GROUP BY
                pac.`id_product_attribute`
            HAVING
                COUNT(pa.id_product) = ' . count($idAttributes)
        );

        if ($idProductAttribute === false && $findBest) {
            //find the best possible combination
            //first we order $idAttributes by the group position
            $orderred = [];
            $result = Db::getInstance()->executeS(
                '
                SELECT
                    a.`id_attribute`
                FROM
                    `' . _DB_PREFIX_ . 'attribute` a
                    INNER JOIN `' . _DB_PREFIX_ . 'attribute_group` g ON a.`id_attribute_group` = g.`id_attribute_group`
                WHERE
                    a.`id_attribute` IN (' . $idAttributesImploded . ')
                ORDER BY
                    g.`position` ASC'
            );

            foreach ($result as $row) {
                $orderred[] = $row['id_attribute'];
            }

            while ($idProductAttribute === false && count($orderred) > 1) {
                array_pop($orderred);
                $idProductAttribute = Db::getInstance()->getValue(
                    '
                    SELECT
                        pac.`id_product_attribute`
                    FROM
                        `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
                    WHERE
                        pa.id_product = ' . (int) $idProduct . '
                        AND pac.id_attribute IN (' . implode(',', array_map('intval', $orderred)) . ')
                    GROUP BY
                        pac.id_product_attribute
                    HAVING
                        COUNT(pa.id_product) = ' . count($orderred)
                );
            }
        }
		
		

        if (empty($idProductAttribute)) {
			return false;
            //throw new PrestaShopObjectNotFoundException('Can not retrieve the id_product_attribute');
        }

        return $idProductAttribute;
    }	



    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public function getThemeInfo()
	{
		$theme = [];
		$themeFileJson = _PS_THEME_DIR_.'/config/theme.json';
		if (Tools::file_exists_no_cache($themeFileJson)) {
			$theme = (array)json_decode(Tools::file_get_contents($themeFileJson), 1);			
		}

		if (!isset($theme['url_contact_us']) || $theme['url_contact_us'] == ''){
			
			$urlContactUs = 'https://addons.prestashop.com/contact-form.php';

			if (isset($theme['addons_id']) && $theme['addons_id'] != ''){
				$urlContactUs .= '?id_product=' .$theme['addons_id'];
			} elseif (isset($this->url_contact_us) && $this->url_contact_us != ''){
				$urlContactUs = $this->url_contact_us;
			} elseif (isset($this->addons_product_id) && $this->addons_product_id != ''){
				$urlContactUs .= '?id_product=' .$this->addons_product_id;
			}
			
			$theme['url_contact_us'] = $urlContactUs;
		}
		
		if (!isset($theme['url_rate']) || $theme['url_rate'] == ''){
			
			$urlRate = 'https://addons.prestashop.com/ratings.php';

			if (isset($theme['addons_id']) && $theme['addons_id'] != ''){
				$urlRate .= '?id_product=' .$theme['addons_id'];
			} elseif (isset($this->url_rate) && $this->url_rate != ''){
				$urlRate = $this->url_rate;
			} elseif (isset($this->addons_product_id) && $this->addons_product_id != ''){
				$urlRate .= '?id_product=' .$this->addons_product_id;
			}
			
			$theme['url_rate'] = $urlRate;
		}		
		
		return $theme;
	}	
}
