<?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;
}

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;

require_once _PS_MODULE_DIR_ . 'an_homecategories/classes/anHomecatFiles.php';
require_once _PS_MODULE_DIR_ . 'an_homecategories/classes/AnHomecategories.php';

class an_homecategories extends Module implements WidgetInterface
{ 
    const PREFIX = 'an_hc_';

    protected $_tabs = array(

        array(
            'class_name' => 'AdminHomeCategories',
            'parent' => 'AdminParentModulesSf',
            'name' => 'Home categories',
            'active' => 0
        ),

        array(
            'class_name' => 'AdminHomecategoriesSettings',
            'parent' => 'AdminParentModulesSf',
            'name' => 'Settings',
            'active' => 0
        ),
    ); 

    public function __construct()
    {
        $this->name = 'an_homecategories';
        $this->tab = 'others';
        $this->version = '1.0.7';
        $this->author = 'Anvanto';
        $this->need_instance = 0;

        $this->bootstrap = true;
        $this->module_key = '';

        parent::__construct();

        $this->displayName = $this->l('Home Categories');
        $this->description = $this->l('Home Categories');

        $this->confirmUninstall = $this->l('Are you sure you want to uninstall the module?');

        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);

        $this->modulePath = _MODULE_DIR_ . 'an_homecategories/'; 

        $this->filesManager = new anHomecatFiles();
    }


    public function install()
    {
        $sql = include _PS_MODULE_DIR_ . $this->name . '/sql/install.php';
		foreach ($sql as $_sql) {
			Db::getInstance()->Execute($_sql);
		} 

        $languages = Language::getLanguages();
        foreach ($this->_tabs as $tab) {
            $_tab = new Tab();
            $_tab->active = $tab['active'];
            $_tab->class_name = $tab['class_name'];
            $_tab->id_parent = Tab::getIdFromClassName($tab['parent']);
            if (empty($_tab->id_parent)) {
                $_tab->id_parent = 0;
            }

            $_tab->module = $this->name;
            foreach ($languages as $language) {
                $_tab->name[$language['id_lang']] = $this->l($tab['name']);
            }

            $_tab->add();
        }    

        $this->importDemoContent();

        return parent::install()
            && $this->registerHook('displayHome')
            && $this->registerHook('displayHeader');
    }

    
    public function uninstall()
    {
        $sql = include _PS_MODULE_DIR_ . $this->name .  '/sql/uninstall.php';
		foreach ($sql as $_sql) {
			Db::getInstance()->Execute($_sql);
		} 

        foreach ($this->_tabs as $tab) {
            $_tab_id = Tab::getIdFromClassName($tab['class_name']);
            $_tab = new Tab($_tab_id);
            $_tab->delete();
        } 

        return parent::uninstall();
    }

    public function importDemoContent()
    {
        if (AnHomecategories::getCount() > 0){
            return false;
        }
        
        AnHomecategories::importJsonHomecategories($this->filesManager);
        $this->importJsonSettings();
    }

    public function exportJsonSettings()
	{ 
		$settings = [
            'slider' => Configuration::get(an_homecategories::PREFIX . 'slider', Context::getContext()->language->id),
            'slider_nav' => Configuration::get(an_homecategories::PREFIX . 'slider_nav', Context::getContext()->language->id),
            'slider_dots' => Configuration::get(an_homecategories::PREFIX . 'slider_dots', Context::getContext()->language->id),
            'slider_loop' => Configuration::get(an_homecategories::PREFIX . 'slider_loop', Context::getContext()->language->id),
            'title' => Configuration::get(an_homecategories::PREFIX . 'title', Context::getContext()->language->id),
            'text' => Configuration::get(an_homecategories::PREFIX . 'text', Context::getContext()->language->id),
        ];

		@file_put_contents($this->filesManager->getSettingsFilePath(), json_encode($settings, JSON_PRETTY_PRINT));
	}	

    public function importJsonSettings()
    {
        $data = json_decode($this->filesManager->getSettingsFile(), true);

        if ($data){
            $languages = Language::getLanguages(false);
            foreach ($data as $id => $value){
                if($id == 'title' || $id == 'text' || $id == 'link'){

                    $valueTitleLeft = [];
                    foreach ($languages as $lang) {
                        $valueTitle[$lang['id_lang']] = $value;
                    }
                    Configuration::updateValue(an_homecategories::PREFIX . $id, $valueTitle);
                } else {
                    Configuration::updateValue(an_homecategories::PREFIX . $id, $value);
                }
            }
        }
    }
	
  
    public function renderWidget($hookName, array $params)
    {

        $settings = [
            'slider' => Configuration::get(an_homecategories::PREFIX . 'slider', Context::getContext()->language->id),
            'slider_nav' => Configuration::get(an_homecategories::PREFIX . 'slider_nav', Context::getContext()->language->id),
            'slider_dots' => Configuration::get(an_homecategories::PREFIX . 'slider_dots', Context::getContext()->language->id),
            'slider_loop' => Configuration::get(an_homecategories::PREFIX . 'slider_loop', Context::getContext()->language->id),
            'title' => Configuration::get(an_homecategories::PREFIX . 'title', Context::getContext()->language->id),
            'text' => Configuration::get(an_homecategories::PREFIX . 'text', Context::getContext()->language->id),
        ];

        $widget['homecategories'] = $this->getWidgetVariables($hookName, $params);
        $widget['settings'] = $settings;
        
        $this->smarty->assign('widget', $widget);
        return $this->fetch('module:' . $this->name . '/views/templates/front/widget.tpl');
    }

    

    public function getWidgetVariables($hookName, array $params)
    {			
        return AnHomecategories::getHomecategories();
    }

    public function hookHeader()
    {
        $this->hookDisplayHeader();
    }

    public function hookDisplayHeader()
    {
	
        $this->context->controller->addJquery();
		
        if (Configuration::get(self::PREFIX . 'slider')){
            
            $this->context->controller->registerStylesheet(
                "an_owl_css_carusel",
                $this->getCSJSFilePath('owl.carousel.min.css'),
                ['server' => 'local', 'priority' => 150]
            );
    
            $this->context->controller->registerJavascript(
                "an_owl_js_carusel",
                $this->getCSJSFilePath('owl.carousel.min.js'),
                array('server' => 'local', 'priority' => 150)
            ); 
    
            $this->context->controller->registerJavascript(
                $this->name . "_js_init_slider",
                'modules/' . $this->name . '/views/js/init.slider.js',
                array('server' => 'local', 'priority' => 150)
            );
        }

		$this->context->controller->registerStylesheet(
			$this->name . "_css",
			'modules/' . $this->name . '/views/css/front.css',
			['server' => 'local', 'priority' => 150]
		);
    }

    public function getCSJSFilePath($file = '')
    {
        if ($file == ''){
            return false;
        }

        $ex = explode('.', $file);
        $fileType = end($ex);
        
        if (Tools::file_exists_no_cache(_PS_THEME_DIR_.'/assets/lib/' . $file)){
            $path = 'themes/'._THEME_NAME_.'/assets/lib/' . $file;   
        } else if (Tools::file_exists_no_cache('modules/anthemeblocks/views/' . $fileType . '/' . $file)){
            $path = 'modules/anthemeblocks/views/' . $fileType . '/' . $file; 
        } else {    
            $path = 'modules/' . $this->name . '/views/' . $fileType . '/' . $file;      
        } 

        return $path;
    }

    public function getContent()
	{
	    Tools::redirectAdmin($this->context->link->getAdminLink('AdminHomeCategories'));
	}

    public function topPromo()
	{		
		$this->context->smarty->assign('theme', $this->getThemeInfo());
        return $this->display(__FILE__, 'views/templates/admin/top.tpl');
	}
	
	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;
	}
}
