<?php
/**
* 2022 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2022 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

class anBanners extends ObjectModel
{
    /**
     * @var int
     */
    public $id_banner;
    /**
     * @var int
     */
    public $id;

    public $hook;

    public $col = 12;

    public $special_id_banner;

    public $active = 1;
    public $position;
    public $template;
    
    public $title;
    public $text;
    public $link;
    public $image;

    /**
     * @var array
     */

    public static $definition = [
        'table' => 'an_banners',
        'primary' => 'id_banner',
        'multilang' => true,
        'fields' => [
            
            'special_id_banner' => ['type' =>self::TYPE_STRING ],
            'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'position' => ['type' =>self::TYPE_INT ],
            'hook' => ['type' =>self::TYPE_STRING],
            'col' => ['type' =>self::TYPE_STRING,],
            'template' => ['type' =>self::TYPE_STRING ],
            
            'title' => ['type' =>self::TYPE_STRING,'lang' => true ],
            'text' => ['type' =>self::TYPE_HTML,'lang' => true ],
            'link' => ['type' =>self::TYPE_STRING,'lang' => true ],
            'image' => ['type' =>self::TYPE_STRING,'lang' => true ],
        ],
    ];

    public const imgDir = _PS_MODULE_DIR_.'an_banners/img/';
    public const imgUrl = __PS_BASE_URI__.'modules/an_banners/img/';
    public const fileJsonBanners = _PS_MODULE_DIR_ . 'an_banners/banners.json';
    public const tplsDir = _PS_MODULE_DIR_ . 'an_banners/views/templates/front/banners/';
    public const tplsThemeDir = _PS_THEME_DIR_ . 'modules/an_banners/banners/';
    public const tplPath = _PS_MODULE_DIR_ . 'an_banners/views/templates/front/banners/';

    /**
     * Formula constructor.
     *
     * @param null $id
     */

    public function __construct($id = null, $id_lang = null)
    {
        parent::__construct($id, $id_lang);

        $this->imgUrlFile = '';
        $this->width = '';
        $this->height = '';
        if (!is_array($this->image) && $this->image){
            $this->imgUrlFile = self::imgUrl . $this->image;
            $imgInfo = getimagesize(self::imgDir . $this->image);
            if (isset($imgInfo['0'])){
                $this->width = $imgInfo['0'];
            }
            if (isset($imgInfo['1'])){
                $this->height = $imgInfo['1'];
            }
        }

        if ($this->template == ''){
            $this->template = 'default';
        }

        if (Tools::file_exists_no_cache(self::tplsThemeDir . $this->template . '.tpl')){
            $this->tplFilePath = self::tplsThemeDir . $this->template . '.tpl';
        } else if (Tools::file_exists_no_cache(self::tplsDir . $this->template . '.tpl')){
            $this->tplFilePath = self::tplPath . $this->template . '.tpl';
        }

        
    }

    public function add($auto_date = true, $null_values = false)
    {
        if (empty($this->special_id_banner)) {
            $this->special_id_banner = uniqid();
        }
    
        return parent::add($auto_date, $null_values);
    }  

    public static function getBanners($hookName = '', $forExport = false, $all = false)
    {
        $context = Context::getContext();
        
		$sql = '
		SELECT * FROM `' . _DB_PREFIX_ . 'an_banners` sw
		LEFT JOIN `' . _DB_PREFIX_ . 'an_banners_lang` sl 
			ON (sw.`id_banner` = sl.`id_banner`
            AND sl.`id_lang` = ' . (int) $context->language->id . ')
		';	
        
        if (!$all){
            $sql .= 'WHERE sw.`active`=1 ';
        }
        
        if ($hookName != 'all') {
            $sql .= 'AND sw.`hook` = "'.pSQL($hookName).'"';
        }

		if (Shop::isFeatureActive()) {
			$sql .= ' AND sw.`id_banner` IN (
				SELECT sa.`id_banner`
				FROM `' . _DB_PREFIX_ . 'an_banners_shop` sa
				WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}	

        $sql .= ' ORDER BY sw.`position`';
        
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        if ($forExport){
            return $result;
        }

        $banners = [];
        foreach ($result as $id => $banner){
            $obj = new anBanners($banner['id_banner'], $context->language->id);
            $banners[$banner['id_banner']] = (array) $obj;
        }

        return $banners;
    }

    public static function getListTpl()
    {
        $list = [];

        $tplsTheme = glob(self::tplsThemeDir . '*.tpl');
        foreach ($tplsTheme as $tpl){
            $list[] = str_replace('.tpl', '', basename($tpl));
        }

        $tplsMod = glob(self::tplsDir . '*.tpl');
        foreach ($tplsMod as $tpl){
            $list[] = str_replace('.tpl', '', basename($tpl));
        }

        $list = array_unique($list);

        $return = [];
        foreach ($list as $item){
            $return[]['file'] = $item;
        }
    
        return $return;
    }

    public function delete()
    {        
        foreach ($this->image as $imgName){
            @unlink(self::imgDir . $imgName);
        }

        return parent::delete();
    }
    
    public static function exportJsonBanners()
	{
        $banners = self::getBanners('all', true, true);	
        foreach ($banners as $key => $hc){
            $banners[$key]['link'] = '#';
        }        
		@file_put_contents(self::fileJsonBanners, json_encode($banners));
	}	

	public static function importJsonBanners()
	{
		$data = json_decode(Tools::file_get_contents(self::fileJsonBanners), true);
		$context = Context::getContext();
        $languages = Language::getLanguages();

        $hooks = [];

		if ($data){
			
			foreach ($data as $item){
            
				$bannerObj = new anBanners();
				
				$bannerObj->col = $item['col'];
                
				$bannerObj->active = $item['active'];
				$bannerObj->position = $item['position'];
                $bannerObj->hook = $item['hook'];
                $bannerObj->special_id_banner = $item['special_id_banner'];
                $bannerObj->template = $item['template'];
						
				foreach ($languages as $language) {
					$bannerObj->title[$language['id_lang']] = $item['title'];
					$bannerObj->text[$language['id_lang']] = $item['text'];
					$bannerObj->link[$language['id_lang']] = $item['link'];

                    if (!isset($bannerObj->image[$language['id_lang']]) && 
                        isset($item['imagesLang'][$language['id_lang']]) && 
                        $item['imagesLang'][$language['id_lang']] != $item['image']){
                            $bannerObj->image[$language['id_lang']] = $item['imagesLang'][$language['id_lang']];
                    } else {
                        $nameImage = $item['image'];
                        if (is_array($bannerObj->image) && in_array($item['image'], $bannerObj->image) && $item['image'] !='' ){
                            $nameImage = $language['id_lang'] . '_' . $item['image'];
                            copy(self::imgDir . $item['image'], self::imgDir . $nameImage);
                        }
                        $bannerObj->image[$language['id_lang']] = $nameImage;
                    }
				}

				$bannerObj->save();

                $hooks[] = $item['hook'];
			}
		}
        return $hooks;
	}    
}