<?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;
}

class AnBlockInform extends ObjectModel
{
    /**
     * @var int
     */
    public $id_widget;
    /**
     * @var int
     */
    public $id;
    /**
     * @var int
     */
    public $active = 1;
    public $type = 'popup';
    public $position = 0;
    public $relation = 0;

    public $file_name;
    public $blockinform_title;
    public $blockinform_content;
    public $blockinform_popup;
    public $blockinform_link;

    /**
     * @var array
     */
    public static $definition = array(
        'table' => 'an_blockinform',
        'primary' => 'id_widget',
        'multilang' => true,
        'fields' => array(
            'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
            'type' => array('type' =>self::TYPE_STRING ),
            'position' => ['type' =>self::TYPE_INT ],

            'relation' => array('type' =>self::TYPE_INT ),

            'file_name' => array('type' =>self::TYPE_STRING ),
            'blockinform_title' => array('type' =>self::TYPE_STRING,'lang' => true ),
            'blockinform_content' => array('type' =>self::TYPE_HTML,'lang' => true ),
            'blockinform_popup' => array('type' =>self::TYPE_HTML,'lang' => true ),
            'blockinform_link' => array('type' =>self::TYPE_HTML,'lang' => true ),
        ),
    );

    public const fileJsonBlocks = _PS_MODULE_DIR_ . 'an_blockinform/blockinform.json';
    public const imgDir = _PS_MODULE_DIR_.'an_blockinform/img/';
    public const imgUrl = __PS_BASE_URI__.'modules/an_blockinform/img/';
    public const modulePath = _MODULE_DIR_ . 'an_blockinform/';

    /**
     * Formula constructor.
     *
     * @param null $id
     */
    
    public function __construct($id = null)
    {
        parent::__construct($id);
    }
    
    
    public static function getBlocksByIdProduct($id_product, $pathImg = true)
    {
        $context = Context::getContext();
        $cats = Product::getProductCategories($id_product);

		$sql = '
		SELECT * FROM `' . _DB_PREFIX_ . 'an_blockinform_relations` szwr, `' . _DB_PREFIX_ . 'an_blockinform` sw
		LEFT JOIN `' . _DB_PREFIX_ . 'an_blockinform_lang` sl 
			ON (sw.`id_widget` = sl.`id_widget`
            AND sl.`id_lang` = ' . (int) $context->language->id . ')
		WHERE sw.`active`=1
			AND sw.`id_widget` = szwr.`id_widget` AND sw.`relation` = szwr.`type` AND (';
        
        if (count($cats) > 0){
            $sql .= '(szwr.`type` = 1 AND szwr.`id_type` IN (' . implode(', ', $cats) . ')   ) OR ';
        }

        $sql .= '
				(szwr.`type` = 2 AND szwr.`id_type` = '.(int) $id_product.') OR 
				(szwr.`type` = 0 AND szwr.`id_type` = 0)
				)
		';	
	
		if (Shop::isFeatureActive()) {
			$sql .= ' AND sw.`id_widget` IN (
				SELECT sa.`id_widget`
				FROM `' . _DB_PREFIX_ . 'an_blockinform_shop` sa
				WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}
       
        $sql .= ' GROUP BY sw.`id_widget`';
        $sql .= ' ORDER BY sw.`position`';

        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        if($pathImg){  
            foreach($result as $id => $val){
                if ($val['file_name'] !=''){
                    $result[$id]['file_name'] = self::imgUrl . $val['file_name'];
                }
               
            }
        } 

        return $result;
    }

	public static function getProducsByIdField($id_widget = 0)
	{
		if (!$id_widget){
			return [];
		}
		
		$sql = '
		SELECT  *, p.*
		FROM `' . _DB_PREFIX_ . 'an_blockinform_relations` awl
		
        LEFT JOIN `' . _DB_PREFIX_ . 'product` p
            ON (p.`id_product` = awl.`id_type`)
		
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
            ON (p.`id_product` = pl.`id_product`
            AND pl.`id_lang` = ' . (int) Context::getContext()->language->id . Shop::addSqlRestrictionOnLang('pl') . ')		
		
		WHERE awl.`id_widget` = ' . (int) $id_widget . '  AND awl.`type`="2" ';
		
		
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);

		return Product::getProductsProperties(Context::getContext()->language->id, $result);
	} 

	public static function getRelationCategories($id_widget = 0)
	{
		if (!$id_widget){
			return [];
		}
		
		$sql = '
		SELECT `id_type`
		FROM `' . _DB_PREFIX_ . 'an_blockinform_relations` awl		
		WHERE awl.`id_widget` = ' . (int) $id_widget . ' AND awl.`type`="1"  ';
		
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);
		
		$cats = [];
		if ($result) {
			foreach ($result as $item){
				$cats[] = $item['id_type'];
			}
		}
		
		return $cats;		
	}  

    public static function getBlockinForm()
    {
        $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'an_blockinform` aut
        LEFT JOIN `' . _DB_PREFIX_ . 'an_blockinform_lang` autl
        ON (autl.`id_widget` = aut.`id_widget` 
        AND autl.`id_lang` = '.(int) Context::getContext()->language->id.' )
        WHERE  aut.`active` = 1 '; 

        $sql .= ' ORDER BY aut.`position`';
        
        if (Shop::isFeatureActive()) {
			$sql .= ' AND aut.`id_widget` IN (
				SELECT uts.`id_widget`
				FROM `' . _DB_PREFIX_ . 'an_blockinform_shop` uts
				WHERE uts.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}
        
        $bloks = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        foreach ($bloks as $key => $block){
            $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'an_blockinform_relations` WHERE `id_widget` = ' . (int) $block['id_widget'] . '';
            $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
            $bloks[$key]['relations'] = $res;

            $sql_lang = 'SELECT * FROM `' . _DB_PREFIX_ . 'an_blockinform_lang` WHERE `id_widget` = ' . (int) $block['id_widget'] . '';
            $res_lang = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql_lang);
            $langContent = [];
            foreach ($res_lang as $item){
                $item['iso_code'] = Language::getIsoById($item['id_lang']);
                $langContent[$item['iso_code']] = $item;
            }
            $bloks[$key]['languages'] = $langContent;
        }

        return $bloks;
    }   

    public static function exportJsonBlocks()
	{
        $blocks = self::getBlockinForm();
		@file_put_contents(self::fileJsonBlocks, json_encode($blocks, JSON_PRETTY_PRINT));
	}	

    public static function importJsonBlocks()
    {
        $data = json_decode(Tools::file_get_contents(self::fileJsonBlocks), true);
        $languages = Language::getLanguages();

        if ($data) {
            foreach ($data as $item){

                $blockObj = new anBlockInform();
                
                $blockObj->active = $item['active'];
                $blockObj->type = $item['type'];
                $blockObj->file_name = $item['file_name'];
                $blockObj->relation = $item['relation'];

                // Default
                foreach ($languages as $language) {
                    $blockObj->blockinform_title[$language['id_lang']] = $item['blockinform_title'];
                    $blockObj->blockinform_content[$language['id_lang']] = $item['blockinform_content'];
                    $blockObj->blockinform_popup[$language['id_lang']] = $item['blockinform_popup'];
                    $blockObj->blockinform_link[$language['id_lang']] = $item['blockinform_link'];
                }

                // But
                foreach ($item['languages'] as $key => $block) {

                    $langId = Language::getIdByIso($block['iso_code']);

                    if ($block['blockinform_title'] !=''){
                        $blockObj->blockinform_title[$langId] = $block['blockinform_title'];
                    }

                    if ($block['blockinform_content'] !=''){
                        $blockObj->blockinform_content[$langId] = $block['blockinform_content'];
                    }

                    if ($block['blockinform_popup'] !=''){
                        $blockObj->blockinform_popup[$langId] = $block['blockinform_popup'];
                    }

                    if ($block['blockinform_link'] !=''){
                        $blockObj->blockinform_link[$langId] = $block['blockinform_link'];
                    }
                }

                $blockObj->save();

                foreach ($item['relations'] as $key => $block){
                    $sql = 'INSERT INTO `'._DB_PREFIX_.'an_blockinform_relations`  (`id_widget`, `id_type`, `type`) 
                    VALUES ("'.(int) $blockObj->id.'","'.(int) $block['id_type'].'","'.(int) $block['type'].'" )';
                    Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
                } 
            }   
        }
    }

    public function delete()
    {        
        @unlink(self::imgDir . $this->file_name);
        anBlockinform::exportJsonBlocks();	
        return parent::delete();
    }

}
