<?php
/**
* 2024 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2024 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_.'anblog/loader.php';

class anblog extends Module
{
    const PREFIX = 'an_bl_';

    public $_tabs = [
        [
            'class_name' => 'AdminAnblogManagement',
            'parent' => 'IMPROVE',
            'name' => 'Anvanto Blog Pro',
            'icon' => 'create',
            'displayTab' => false,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogBlogs',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Posts',
            'displayTab' => true,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogCategories',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Categories',
            'displayTab' => true,
            'active' => 1
        ],   
        [
            'class_name' => 'AdminAnblogComments',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Comments',
            'displayTab' => true,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogWidgets',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Widgets',
            'displayTab' => true,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogImportexport',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Import / Export',
            'displayTab' => true,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogSettings',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Settings',
            'displayTab' => true,
            'active' => 1
        ],
        [
            'class_name' => 'AdminAnblogAjax',
            'parent' => 'AdminAnblogManagement',
            'name' => 'Anblog: ajax',
            'displayTab' => false,
            'active' => 0
        ]                                  
    ];    

    public function __construct()
    {
        $this->name = 'anblog';
        $this->tab = 'front_office_features';
        $this->version = '3.4.28';
        $this->author = 'Anvanto';
        $this->module_key = 'c4eeba6dfce602f34ec16e1ccf830b1a';
        $this->need_instance = 0;
        $this->bootstrap = true;
        $this->new174 = version_compare(_PS_VERSION_, '1.7.4.0', '>=') ?  true : false;
        $this->new = version_compare(_PS_VERSION_, '1.7.0.0', '>=') ?  true : false;
        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);

        $this->secure_key = Tools::encrypt($this->name);

        parent::__construct();

        $this->displayName = $this->l('Anvanto Blog Pro');
        $this->description = $this->l('Blog for your store');

        $this->defaultSettings = include _PS_MODULE_DIR_ . $this->name . '/config.php';

        $this->valuesWithLang = ['blog_link_title', 'meta_title', 'meta_description', 'meta_keywords', 'category_rewrite', 'detail_rewrite'];
		
		$this->imageTypes = [
			[
				'name' => 'anblog_default',
				'width' => 885,
				'height' => 620,
			],
			[
				'name' => 'anblog_thumb',
				'width' => 885,
				'height' => 620,
			],	
			[
				'name' => 'anblog_listing_leading_img',
				'width' => 405,
				'height' => 285,
			],
			[
				'name' => 'anblog_listing_secondary_img',
				'width' => 253,
				'height' => 177,
			]
		];

        $this->tabDisplayTranslate = [
            'AdminAnblogBlogs' => $this->l('Posts'),
            'AdminAnblogCategories' => $this->l('Categories'),
            'AdminAnblogComments' => $this->l('Comments'),
            'AdminAnblogWidgets' => $this->l('Widgets'),
            'AdminAnblogImportexport' => $this->l('Import / Export'),
            'AdminAnblogSettings' => $this->trans('Settings', [], 'Admin.Global')
        ];          
    }

    public function install()
    {
        /* Adds Module */
        $defaultSettings = include _PS_MODULE_DIR_ . $this->name . '/config.php';

        $valuesWithLang = ['blog_link_title', 'meta_title', 'meta_description', 'meta_keywords', 'category_rewrite', 'detail_rewrite'];
        $languages = Language::getLanguages(false);

        foreach ($defaultSettings as $key => $value) {
            if (in_array($key, $valuesWithLang)) {

                $valueLang = [];

                foreach ($languages  as $language){
                    $valueLang[$language['id_lang']] = $value;
                }      

                Configuration::updateValue(anblog::PREFIX . $key, $valueLang);

            } else {
                Configuration::updateValue(anblog::PREFIX . $key, $value);
            }
        } 

        if (parent::install()) {
            $this->registerANHook();
            $res = true;

            Configuration::updateValue('ANBLOG_CATEORY_MENU', 1);
            
            Configuration::updateValue('link_rewrite', 'blog');
			
			//	Delete old routers
			Configuration::deleteByName('PS_ROUTE_module-anblog-category');
			Configuration::deleteByName('PS_ROUTE_module-anblog-blog');
			Configuration::deleteByName('PS_ROUTE_module-anblog-list');
			
			
            /* Creates tables */
            if (Configuration::get(anblog::PREFIX . 'soft_reset') == 0) {
                $res &= $this->installImageTypes();
                $res &= $this->createTables();
            }
                
            $res &= $this->installConfig();
            
            Configuration::updateValue('AP_INSTALLED_ANBLOG', '1');
            //DONGND: check thumb column, if not exist auto add
            if (Db::getInstance()->executeS(
                'SHOW TABLES LIKE \'%anblog_blog%\''
            )
                && count(
                    Db::getInstance()->executes(
                        'SELECT "thumb" FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "'._DB_NAME_.'"
                         AND TABLE_NAME = "'._DB_PREFIX_.'anblog_blog" AND COLUMN_NAME = "thumb"'
                    )
                )<1
            ) {
                Db::getInstance()->execute(
                    'ALTER TABLE `'._DB_PREFIX_.'anblog_blog` ADD `thumb` varchar(255) DEFAULT NULL'
                );
            }

            foreach ($this->_tabs as $tab) {
                $this->tabAdd($tab, $this);
            }

            return (bool)$res;
        }
        return false;
    }

    public function importDemoContent()
    {
        anBlogWidgets::importJsonWidgets(new anBlogContentTheme());
    }

    public function installImageTypes()
    {
        $res = true;

        $imageType = new ImageType();
        $imageType->products = 0;
        $imageType->categories = 0;
        $imageType->manufacturers = 0;
        $imageType->suppliers = 0;
        $imageType->stores = 0;		
		
		foreach ($this->imageTypes as $item){
			$imageType->name = $item['name'];
			$imageType->width = $item['width'];
			$imageType->height = $item['height'];
			$res &= $imageType->add();
		}
		
        return $res;
    }

    public function checkAndCreateImagesPresets()
    {

        if (!count(Db::getInstance()->executeS(
            'SELECT *
             FROM `'._DB_PREFIX_.'image_type`
             WHERE `name`LIKE \'anblog_%\''
        ))) {
            $this->installImageTypes();
        }
    }
    /**
     *
     */
    public function hookDisplayBackOfficeHeader()
    {
        $this->context->controller->addCss($this->_path . 'views/css/admin/blogmenu.css');

        if (Dispatcher::getInstance()->getController() == 'AdminThemes') {
            $this->checkAndCreateImagesPresets();
        }
    }

    public function hookGSitemapAppendUrls($params)
    {
        if(Configuration::get(anblog::PREFIX . 'enable_google_sitemap')){
            return anBlogSitemap::gSitemapCreateLinks($params['lang']);
        }

        return false;
    }

    public function getIdGuest(){
 		
		$idCustomer = Context::getContext()->cookie->id_guest;
		
		$cookie = Context::getContext()->cookie;
		
		if ($idCustomer){
			return $idCustomer;
		} else {
			if (!$cookie->__isset(self::PREFIX.'_id_guest') | $cookie->__get(self::PREFIX.'_id_guest') == ''){
				$idCustomer = '111' . tools::passwdGen(5, 'NUMERIC');
				$cookie->__set(self::PREFIX.'_id_guest', $idCustomer);
				$cookie->setExpire(time() + 60 * 60 * 24 * 180);
				$cookie->write();
			
			} else {
				$idCustomer = $cookie->__get(self::PREFIX.'_id_guest');
			
			}
		}

		return $idCustomer;
	}

    public function getContent()
    {
        Tools::redirectAdmin($this->context->link->getAdminLink('AdminAnblogSettings'));
    }

    /**
     * @return bool
     */
    public function _prepareHook()
    {
        $helper = AnblogHelper::getInstance();

        $category = new Anblogcat(Tools::getValue('id_anblogcat'), $this->context->language->id);

        $tree = $category->getFrontEndTree((int)$category->id_anblogcat > 1 ? $category->id_anblogcat : 1, $helper);
        $this->smarty->assign('tree', $tree);
        if ($category->id_anblogcat) {
            // validate module
            $this->smarty->assign('currentCategory', $category);
        }

        return true;
    }

    public function hookDisplayHeader()
    {
        $this->context->controller->registerStylesheet('anblog_css_widget', 'modules/anblog/views/css/widget.css', ['server' => 'local', 'priority' => 150]);
        $this->context->controller->registerStylesheet('anblog_css', 'modules/anblog/views/css/front.css', ['server' => 'local', 'priority' => 150]);        
        $this->context->controller->registerStylesheet('anblog_css_custom', 'modules/anblog/views/css/custom.css', ['server' => 'local', 'priority' => 150]);        
    }

    public function hookDisplayLeftColumn($params)
    { 
        if (isset($params['content']) && $params['content'] == 'listing'){
            if (Configuration::get(anblog::PREFIX . 'left_cat_listing')){
                $this->smarty->assign('an_left_category', $this->leftCategoryBlog());
            }
            if (Configuration::get(anblog::PREFIX . 'left_tags_listing')){
                $this->smarty->assign('an_left_tag', $this->lefTagBlog());
            }
            if (Configuration::get(anblog::PREFIX . 'left_recent_listing')){
                $this->smarty->assign('an_left_recent', $this->leftRecentBlog());
            }
        }

        if (isset($params['content']) && $params['content'] == 'post'){
            if (Configuration::get(anblog::PREFIX . 'left_cat_post')){
                $this->smarty->assign('an_left_category', $this->leftCategoryBlog());
            }
            if (Configuration::get(anblog::PREFIX . 'left_tags_post')){
                $this->smarty->assign('an_left_tag', $this->lefTagBlog());
            }
            if (Configuration::get(anblog::PREFIX . 'left_recent_post')){
                $this->smarty->assign('an_left_recent', $this->leftRecentBlog());
            }
        }

        $this->context->smarty->assign('anblog_imageTypes', $this->getImageTypesForTpl());

        return $this->display(__FILE__, 'views/templates/hook/column-main.tpl');
    }

    /**
     * @return string
     */
    public function leftCategoryBlog()
    {
        $html = '';


        if (/*Configuration::get('ANBLOG_CATEORY_MENU') && */$this->_prepareHook()) {
            $html .= $this->display(__FILE__, 'views/templates/hook/column-categories.tpl');
        }
        return $html;
    }

    /**
     * @return string
     */
    public function leftRecentBlog()
    {
        $html = '';

        $config = AnblogConfig::getInstance();
        $helper = AnblogHelper::getInstance();

        $limit = (int)Configuration::get(anblog::PREFIX . 'limit_recent_blog', 5);
        $leading_blogs = AnblogBlog::getListBlogs(
            null,
            $this->context->language->id,
            1,
            $limit,
            'date_add',
            'DESC',
            array(),
            true
        );
        foreach ($leading_blogs as $key => $blog) {
            $blog = AnblogHelper::buildBlog($helper, $blog, 'anblog_listing_secondary_img', $config);
            $leading_blogs[$key] = $blog;
        }

        $this->smarty->assign('recent_posts', $leading_blogs);
        $html .= $this->display(__FILE__, 'views/templates/hook/column-recent.tpl');

        return $html;
    }

    /**
     * @return string
     */
    public function lefTagBlog()
    {

        $html = '';
        $helper = AnblogHelper::getInstance();

        $leading_blogs = AnblogBlog::getListBlogs(
            null,
            $this->context->language->id,
            1,
            100000,
            'date_add',
            'DESC',
            array(),
            true
        );

        $tags_temp = array();
        foreach ($leading_blogs as $value) {
            $tags_temp = array_merge($tags_temp, explode(",", $value['tags']));
        }

        $tags_temp = array_unique($tags_temp);
        $tags = array();
        foreach ($tags_temp as $tag_temp) {
            $tags[] = array(
                'name' => $tag_temp,
                'link' => $helper->getBlogTagLink($tag_temp)
            );
        }

        $this->smarty->assign('anblogtags', $tags);
        $html .= $this->display(__FILE__, 'views/templates/hook/column-tags.tpl');

        return $html;
    }

    /**
     * @param null $name
     * @return string
     */
    protected function getCacheId($name = null)
    {
        $name = ($name ? $name.'|' : '').implode('-', Customer::getGroupsStatic($this->context->customer->id));
        return parent::getCacheId($name);
    }

    /**
     * @param $params
     * @return string
     */
    public function hookdisplayRightcolumn($params)
    {
        return $this->hookdisplayLeftColumn($params);
    }

    /**
     * @see Module::uninstall()
     */
    public function uninstall()
    {
        $res = true;

        $this->tabDelete(['class_name' => 'AdminAnblogPosts']);
        $this->tabDelete(['class_name' => 'AdminAnblogCategories']);
        $this->tabDelete(['class_name' => 'AdminAnblogComments']);
        $this->tabDelete(['class_name' => 'AdminAnblogSettings']);
        $this->tabDelete(['class_name' => 'AdminAnblogWidgets']);
        $this->tabDelete(['class_name' => 'AdminAnblogImportexport']);
        $this->tabDelete(['class_name' => 'AdminAnblogAjax']);
        $this->tabDelete(['class_name' => 'AdminAnblogManagement']);

        if (Configuration::get(anblog::PREFIX . 'soft_reset') == 0) {
            foreach (ImageType::getImagesTypes() as $type) {
                if ($type['name'] == 'anblog_default'
                    || $type['name'] == 'anblog_thumb'
                    || $type['name'] == 'anblog_listing_leading_img'
                    || $type['name'] == 'anblog_listing_secondary_img'
                ) {
                    $imageType = new ImageType($type['id_image_type']);
                    $res &= $imageType->delete();
                }
            }

            Db::getInstance()->execute(
                '
                DROP TABLE IF EXISTS
                `'._DB_PREFIX_.'anblogcat`,
                `'._DB_PREFIX_.'anblogcat_lang`,
                `'._DB_PREFIX_.'anblogcat_shop`,
                `'._DB_PREFIX_.'anblog_comment`,
                `'._DB_PREFIX_.'anblog_blog`,
                `'._DB_PREFIX_.'anblog_blog_lang`,
                `'._DB_PREFIX_.'anblog_hooks`,
                `'._DB_PREFIX_.'anblog_blog_categories`,
                `'._DB_PREFIX_.'anblog_blog_widgets`,
                `'._DB_PREFIX_.'anblog_blog_widgets_relations`,
                `'._DB_PREFIX_.'anblog_blog_widgets_lang`,
                `'._DB_PREFIX_.'anblog_blog_widgets_shop`,
                `'._DB_PREFIX_.'anblog_likes`,
                `'._DB_PREFIX_.'anblog_blog_shop`'
            );
        }
        
        return parent::uninstall();
    }

    /**
     * Creates tables
     */
    protected function createTables()
    {
        $res = 1;
        include_once dirname(__FILE__).'/install/install.php';
        return $res;
    }

    /**
     * @return int
     */
    protected function installSample()
    {
        $res = 1;
        include_once dirname(__FILE__).'/install/sample.php';
        return $res;
    }

    /**
     * @return int
     */
    protected function installConfig()
    {
        $res = 1;
        include_once dirname(__FILE__).'/config.php';
        return $res;
    }

    /**
     * Hook ModuleRoutes
     */
    public function hookModuleRoutes($route = '', $detail = array())
    {        
        if ($this->context->controller instanceof AdminController && !Tools::getIsset('controller')) {
            return false;
        }//TODO check this

        $config = AnblogConfig::getInstance();
        $routes = array();
		
		$category_rewrite = Configuration::get(anblog::PREFIX . 'category_rewrite', Context::getContext()->language->id);
		$detail_rewrite = Configuration::get(anblog::PREFIX . 'detail_rewrite', Context::getContext()->language->id);
		

        $endPrefixMain = '';
        if (Configuration::get(anblog::PREFIX . 'main_end_prefix')){
            $endPrefixMain = '.html';
        }
        $routes['module-anblog-list'] = array(
            'controller' => 'list',
            'rule' => _AN_BLOG_REWRITE_ROUTE_.$endPrefixMain,
            'keywords' => array(
            ),
            'params' => array(
                'fc' => 'module',
                'module' => 'anblog'
            )
        );

        $routes['module-anblog-sitemap'] = array(
            'controller' => 'sitemap',
            'rule' => 'module/anblog/sitemap.xml',
            'keywords' => array(
            ),
            'params' => array(
                'fc' => 'module',
                'module' => 'anblog'
            )
        );
        
        if (Configuration::get('PS_REWRITING_SETTINGS')) {
            // URL HAVE ID

            if ($detail_rewrite != ''){
                $detail_rewrite = '/'. $detail_rewrite;
            }


            $endPrefix = '';
            if (Configuration::get(anblog::PREFIX . 'cat_post_end_prefix')){
                $endPrefix = '.html';
            }
            
            $routes['module-anblog-blog'] = array(
                'controller' => 'blog',
                'rule' => _AN_BLOG_REWRITE_ROUTE_.$detail_rewrite.'/{rewrite}'.$endPrefix,
                'keywords' => array(
                    'id' => array('regexp' => '[0-9]+', 'param' => 'id'),
                    'rewrite' => array('regexp' => '[_a-zA-Z0-9-\pL]*', 'param' => 'rewrite'),
                ),
                'params' => array(
                    'fc' => 'module',
                    'module' => 'anblog',
                    
                )
            );

			if ($category_rewrite !=''){
				$category_rewrite = '/'.$category_rewrite;
			}
			
            $categoryRule = _AN_BLOG_REWRITE_ROUTE_.$category_rewrite.'/{rewrite}';
            if ($endPrefix == ''){
                $categoryRule .= '/';
            } else {
                $categoryRule .= $endPrefix;
            }

            $routes['module-anblog-category'] = array(
                'controller' => 'category',
                'rule' => $categoryRule,
                'keywords' => array(
                    'id' => array('regexp' => '[0-9]+', 'param' => 'id'),
                    'rewrite' => array('regexp' => '[_a-zA-Z0-9-\pL]*', 'param' => 'rewrite'),
                ),
                'params' => array(
                    'fc' => 'module',
                    'module' => 'anblog',
                )
            );
        } else {
            // REMOVE ID FROM URL
            $category_rewrite = 'category_rewrite'.'_'.Context::getContext()->language->id;
            $category_rewrite = Configuration::get(anblog::PREFIX . $category_rewrite, 'category');
            $detail_rewrite = 'detail_rewrite'.'_'.Context::getContext()->language->id;
            $detail_rewrite = Configuration::get(anblog::PREFIX . $detail_rewrite, 'detail');

            $routes['module-anblog-blog'] = array(
                'controller' => 'blog',
                'rule' => _AN_BLOG_REWRITE_ROUTE_.'/'.$detail_rewrite.'/{rewrite}-b{id}.html',
                'keywords' => array(
                    'id' => array('regexp' => '[0-9]+', 'param' => 'id'),
                    'rewrite' => array('regexp' => '[_a-zA-Z0-9-\pL]*', 'param' => 'rewrite'),
                ),
                'params' => array(
                    'fc' => 'module',
                    'module' => 'anblog',
                )
            );

            $routes['module-anblog-category'] = array(
                'controller' => 'category',
                'rule' => _AN_BLOG_REWRITE_ROUTE_.'/'.$category_rewrite.'/{rewrite}-c{id}.html',
                'keywords' => array(
                    'id' => array('regexp' => '[0-9]+', 'param' => 'id'),
                    'rewrite' => array('regexp' => '[_a-zA-Z0-9-\pL]*', 'param' => 'rewrite'),
                ),
                'params' => array(
                    'fc' => 'module',
                    'module' => 'anblog',
                )
            );
        }
        return $routes;
    }

    /**
     * Run only one when install/change Theme_of_AN
     */
    public function hookActionAdminBefore($params)
    {
        $this->unregisterHook('actionAdminBefore');
        if (isset($params) && isset($params['controller']) && isset($params['controller']->theme_manager)) {
            // Validate : call hook from theme_manager
        } else {
            // Other module call this hook -> duplicate data
            return;
        }

        // FIX : update Prestashop by 1-Click module -> NOT NEED RESTORE DATABASE
        $ap_version = Configuration::get('AP_CURRENT_VERSION');
        if ($ap_version != false) {
            $ps_version = Configuration::get('PS_VERSION_DB');
            $versionCompare =  version_compare($ap_version, $ps_version);
            if ($versionCompare != 0) {
                // Just update Prestashop
                Configuration::updateValue('AP_CURRENT_VERSION', $ps_version);
                return;
            }
        }

        // INSERT HOOK FROM MODULE_DATASAMPLE
        if ($hook_from_theme == false) {
            $this->registerANHook();
        }

        // WHEN INSTALL MODULE, NOT NEED RESTORE DATABASE IN THEME
        $install_module = (int)Configuration::get('AP_INSTALLED_ANBLOG', 0);
        if ($install_module) {
            Configuration::updateValue('AP_INSTALLED_ANBLOG', '0');// next : allow restore sample
            return;
        }
    }

    /**
     * Common method
     * Resgister all hook for module
     */
    public function registerANHook()
    {
        $res = true;
        $res &= $this->registerHook('displayHeader');
        $res &= $this->registerHook('moduleRoutes');
        $res &= $this->registerHook('displayBackOfficeHeader');
        $res &= $this->registerHook('displayHome');
        $res &= $this->registerHook('displayHomeAfter');
        $res &= $this->registerHook('displayContentWrapperBottom');
        $res &= $this->registerHook('displayFooterProduct');
		$res &= $this->registerHook('displayBlogWidget');
		$res &= $this->registerHook('gSitemapAppendUrls');


        // Multishop create new shop
    //    $res &= $this->registerHook('actionAdminShopControllerSaveAfter');
        return $res;
    }

    public function regenerateThumbs()
    {
        $query = '
		SELECT  c.id_anblog_blog, c.image
		FROM  '._DB_PREFIX_.'anblog_blog c';
        $data = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);

        if (count($data)) {
            foreach ($data as $post) {
                $anblogImage = new AnblogImage($post);
                $anblogImage->delete(true);
            }
        }
    }

    public function hookDisplayHome($params)
    {
        return $this->getWidgets('DisplayHome');
    }
    
    public function hookDisplayHomeAfter($params)
    {
        return $this->getWidgets('displayHomeAfter');
    }

    public function hookDisplayBlogWidget($params)
    {
        return $this->getWidgets('displayBlogWidget');
    }

    public function hookDisplayContentWrapperBottom($params)
    {
        $searchResul = '';
        if (Configuration::get(anblog::PREFIX . 'show_search_result')){
            $searchResul = $this->getSearchResult();
        }
        return $searchResul . $this->getWidgets('displayContentWrapperBottom');
    }

    public function hookDisplayFooterProduct($params)
    {
        if (isset($params['product']['id_product'])){
            return $this->getWidgets('displayFooterProduct', $params['product']['id_product']);
        }
    }

    public function getSearchResult()
    {
        if ($this->context->controller->getPageName() != 'search'){
            return;
        }

        $s = Tools::getValue('s');

        $config = AnblogConfig::getInstance();
        
        $articles = []; 

        $limit = 3;
        $sort = 'new';
        
        $articles = AnblogBlog::getListBlogs(
            false,
            $this->context->language->id,
            1,
            $limit,
            'date_add',
            'DESC',
            array(),
            true,
            null,
            $sort,
            $s
        );                

        $config = AnblogConfig::getInstance();
        $helper = AnblogHelper::getInstance();

        foreach ($articles as $key => $article) {
            $article = AnblogHelper::buildBlog($helper, $article, 'anblog_listing_leading_img', $config);
            $articles[$key] = $article;
        }

        $this->smarty->assign('widget',
        [
            'title' => $this->l('Search results from Blog'),
            'show_read_more' => false,
            'slider' => false,
            'posts' => $articles,
        ]);

        $this->smarty->assign('config', $config);
        $this->smarty->assign('anblog_main_page', AnblogHelper::getInstance()->getFontBlogLink());
        $this->smarty->assign('anblog_imageTypes', $this->getImageTypesForTpl());

        return $this->display(__FILE__, 'views/templates/hook/widget.tpl');
    }

	


    public function getPostsBlogs($id_anblogcat, $limit, $sort = ''){
        
        $config = AnblogConfig::getInstance();
        
        $articles = []; 

        $articles = AnblogBlog::getListBlogs(
            $id_anblogcat,
            $this->context->language->id,
            1,
            $limit,
            'date_add',
            'DESC',
            array(),
            true,
            null,
            $sort
        );                

        $config = AnblogConfig::getInstance();
        $helper = AnblogHelper::getInstance();

        foreach ($articles as $key => $article) {
            $article = AnblogHelper::buildBlog($helper, $article, 'anblog_listing_leading_img', $config);
            $articles[$key] = $article;
        }

        return $articles;
        
    } 
    
    public function getWidgets($hookName, $idProduct = '')
    {
        $showOn = anBlogWidgets::$showOn;
   
        $pageName = $this->context->controller->getPageName();
        $idShowOn = '';
        foreach ($showOn as $key => $val){
            if (in_array($pageName, $val['pageName']) && in_array($hookName, $val['hook'])){
                $idShowOn = $key;
            }
        }

        if ($idShowOn == ''){
            return;
        }

        $categoryId = false;
        if ($pageName == 'category' && $idShowOn == 2){
            $category = $this->context->controller->getCategory();
            $categoryId = $category->id;
        }

        if ($idProduct != '' && $idShowOn == 3 || $categoryId){
            $blogWidgets = anBlogWidgets::getWidgetsByIdProduct($idShowOn, $idProduct, $categoryId);
        } else {
            $blogWidgets = anBlogWidgets::getBlogWidgets($idShowOn);
        }

        if (count($blogWidgets) == 0){
            return;
        }

        $config = AnblogConfig::getInstance();

        $widgetHtml = '';
        foreach ($blogWidgets as $widget){
            if ($widget['limit'] > 0) {
                $articles = $this->getPostsBlogs($widget['id_anblogcat'], $widget['limit'], $widget['sort']);
                
                $this->smarty->assign('widget',
                    [
                        'title' => $widget['title'],
                        'show_read_more' => $widget['show_read_more'],
                        'slider' => $widget['slider'],
                        'posts' => $articles,
                    ]
                );
                $this->smarty->assign('config', $config);
                $this->smarty->assign('anblog_main_page', AnblogHelper::getInstance()->getFontBlogLink());
                $this->smarty->assign('anblog_imageTypes', $this->getImageTypesForTpl());
                $widgetHtml = $widgetHtml . $this->display(__FILE__, 'views/templates/hook/widget.tpl');
            }
        }

        return $widgetHtml;
    }

    /**
     * @param array $params
     * @return string
    */

    public function getImageTypesForTpl()
    {
        $imageTypes = [];
        foreach ($this->imageTypes as $it){
            $imageTypes[$it['name']] = $it;
        }
        return $imageTypes;
    }

    public function translateFrontBlog()
    {
        return array(
            'thanks' => $this->l('Thanks for your comment, it will be published soon!'),
            'error' => $this->l('An error occurred while sending the comment. Please recorrect data in fields!'),
            'recapcha' => $this->l('Please submit reCAPTCHA'),
            'blog' => $this->l('Blog'),
        );
    }
	
	public function checkIssetImageTypes()
	{
		$existingImageTypes = Db::getInstance()->executeS('
                SELECT *
                FROM `'._DB_PREFIX_.'image_type`
                WHERE `name`LIKE \'anblog_%\'');

		$existingImageTypesNames = [];
		foreach ($existingImageTypes as $item){
			$existingImageTypesNames[] = $item['name'];
		}
		
		$errorImageTypes = [];
 		foreach ($this->imageTypes as $id => $item){
			if (!in_array($item['name'], $existingImageTypesNames)){
				$errorImageTypes[] = 'Image type "' . $item['name'] . '" does not exist.';
			}
		}
		
		return $errorImageTypes;
	}
	
    public function getAllConfig()
    {
        $allConfig = [];

        foreach ($this->defaultSettings as $key => $value) {
            if (in_array($key, $this->valuesWithLang)) {
                $allConfig[$key] = Configuration::get(anblog::PREFIX . $key , $this->context->language->id, $value);
            } else {
                $allConfig[$key] = Configuration::get(anblog::PREFIX . $key , null, $value);
            }
        } 

        return $allConfig;
    }




    ////////////////////////////////////////////////////////////////////////////////////////

    public function createAdminTabs($tabs, $controller_name)
    {
        $id_lang = $this->context->language->id;
        $link = $this->context->link;

        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'] == $controller_name) {
                                $sub_tabs = &$tab2['sub_tabs'];

                                foreach ($this->_tabs as $moduleTab){
                                    if (isset($moduleTab['displayTab']) && $moduleTab['displayTab']){
                                        $tab = Tab::getTab($id_lang, Tab::getIdFromClassName($moduleTab['class_name']));
                                        $tab['current'] = false;
                                        if ($controller_name == $moduleTab['class_name']){
                                            $tab['current'] = true;
                                        }
                                        $tab['href'] = $link->getAdminLink($moduleTab['class_name']);
                                        $tab['active'] = true;

                                        if (isset($this->tabDisplayTranslate[$moduleTab['class_name']])){
                                            $tab['name'] = $this->tabDisplayTranslate[$moduleTab['class_name']];
                                        } else {
                                            $tab['name'] = $moduleTab['name'];
                                        }

                                        $sub_tabs[] = $tab;
                                    }
                                }

                                break;
                            }
                        }
                    //    break;
                    }
                }
              //  break;
            }
        }

        return $tabs;
    }

    public function tabAdd($tab, $module)
    {
        if (count($tab) == 0){
            return false;
        }

        $languages = Language::getLanguages();
        
        $_tab = new Tab();
        $_tab->active = $tab['active'];
        $_tab->class_name = $tab['class_name'];
        if (isset($tab['icon'])){
            $_tab->icon = $tab['icon'];
        }
        $_tab->id_parent = Tab::getIdFromClassName($tab['parent']);
        if (empty($_tab->id_parent)) {
            $_tab->id_parent = 0;
        }

        $_tab->module = $module->name;
        foreach ($languages as $language) {
            $_tab->name[$language['id_lang']] = $module->l($tab['name']);
        }

        $_tab->add();

        return true;
    }

    public function tabDelete($tab)
    {
        if (count($tab) == 0){
            return false;
        }        
        
        $_tab_id = Tab::getIdFromClassName($tab['class_name']);
        $_tab = new Tab($_tab_id);
        $_tab->delete();

        return true;
    }    
}
