<?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 anBlogWidgets extends ObjectModel
{
    /**
     * @var int
     */
    public $id_anblog_blog_widgets;
    /**
     * @var int
     */
    public $id;

    public $id_anblogcat;

    public $snow_on;
    public $sort = 'new';
    public $slider;
    public $limit = 3;
    public $title;
    public $relation = 0;
    public $show_read_more = 0;

    /**
     * @var array
     */

    public static $definition = [
        'table' => 'anblog_blog_widgets',
        'primary' => 'id_anblog_blog_widgets',
        'multilang' => true,
        'fields' => [
            'id_anblogcat' => ['type' =>self::TYPE_INT ],
            'snow_on' => ['type' =>self::TYPE_INT ],
            'sort' => ['type' =>self::TYPE_STRING ],
            'slider' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'limit' => ['type' =>self::TYPE_INT ],
            'title' => ['type' =>self::TYPE_STRING,'lang' => true, 'validate' => 'isString', 'required' => true, 'size' => 256 ],

            'relation' => ['type' =>self::TYPE_INT],
            'show_read_more' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool']
        ],
    ];

    public static $showOn = [
        '1' => [
            'id' => 'index',
            'name' => 'Home Page (displayHome)',
            'hook' => ['DisplayHome'],
            'pageName' => ['index'],
        ],

        '4' => [
            'id' => 'index',
            'name' => 'Home Page (displayHomeAfter)',
            'hook' => ['displayHomeAfter'],
            'pageName' => ['index'],
        ],    
        
        '5' => [
            'id' => 'index',
            'name' => 'Home Page (displayBlogWidget)',
            'hook' => ['displayBlogWidget'],
            'pageName' => ['index'],
        ],          

        '2' => [
            'id' => 'category',
            'name' => 'Category page',
            'hook' => ['displayContentWrapperBottom'],
            'pageName' => ['category', 'prices-drop', 'best-sales', 'new-products', 'manufacturer'],
        ],

        '3' => [
            'id' => 'product',
            'name' => 'Product page',
            'hook' => ['displayFooterProduct'],
            'pageName' => ['product'],
        ],
    ];

    public static function getBlogWidgets($idShowOn = '', $all = false)
    {
        $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets` abw
        LEFT JOIN `' . _DB_PREFIX_ . 'anblog_blog_widgets_lang` abwl
        ON (abwl.`id_anblog_blog_widgets` = abw.`id_anblog_blog_widgets` 
        AND abwl.`id_lang` = '.(int) Context::getContext()->language->id.' )'; 
        
        if ($idShowOn != ''){
            $sql .= 'WHERE abw.`snow_on`= "'. pSQL($idShowOn) .'" ';
        }
        
        if (Shop::isFeatureActive()) {
			$sql .= ' AND abw.`id_anblog_blog_widgets` IN (
				SELECT abws.`id_anblog_blog_widgets`
				FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets_shop` abws
				WHERE abws.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}

        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        return $result;
    } 

    public static function getWidgetsByIdProduct($idShowOn, $id_product, $categoryId = false)
    {
        $context = Context::getContext();
        $cats = product::getProductCategories($id_product);
      
        if ($categoryId){
            $cats[] = $categoryId;
        }
    
        $sql = '
        SELECT * FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets_relations` szwr, `' . _DB_PREFIX_ . 'anblog_blog_widgets` sw
        LEFT JOIN `' . _DB_PREFIX_ . 'anblog_blog_widgets_lang` sl 
            ON (sw.`id_anblog_blog_widgets` = sl.`id_anblog_blog_widgets`
            AND sl.`id_lang` = ' . (int) $context->language->id . ')
            WHERE sw.`id_anblog_blog_widgets` = szwr.`id_anblog_blog_widgets` 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)
                )
            AND sw.`snow_on` = '.$idShowOn.'
        ';    
        
        if (Shop::isFeatureActive()) {
            $sql .= ' AND sw.`id_anblog_blog_widgets` IN (
                SELECT sa.`id_anblog_blog_widgets`
                FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets_shop` sa
                WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
            )';
        }
       
        $sql .= ' GROUP BY sw.`id_anblog_blog_widgets`';

        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
        
        if (!$result){
            return [];
        }

        return $result;
    }


    public static function getProducsByIdWidgets($id_anblog_blog_widgets = 0)
    {
        if (!$id_anblog_blog_widgets){
            return [];
        }
        
        $sql = '
        SELECT  *, p.*
        FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets_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_anblog_blog_widgets` = ' . (int) $id_anblog_blog_widgets . '  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_anblog_blog_widgets = 0)
    {
        if (!$id_anblog_blog_widgets){
            return [];
        }
        
        $sql = '
        SELECT `id_type`
        FROM `' . _DB_PREFIX_ . 'anblog_blog_widgets_relations` awl        
        WHERE awl.`id_anblog_blog_widgets` = ' . (int) $id_anblog_blog_widgets . ' 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 exportJsonWidgets($fileManager)
	{
		$widgets = self::getBlogWidgets('', 'all');	
		@file_put_contents($fileManager->getContentFilePath(), json_encode($widgets, JSON_PRETTY_PRINT));
	}	

    public static function importJsonWidgets($fileManager)
	{
		$data = json_decode($fileManager->getContentFile(), true);
		$context = Context::getContext();

		if (!$data){
            return;
        }

        foreach ($data as $item){
            
            $widgetObj = new anBlogWidgets();
            $widgetObj->id_anblogcat = $item['id_anblogcat'];
            $widgetObj->snow_on = $item['snow_on'];
            $widgetObj->sort = $item['sort'];
            $widgetObj->slider = $item['slider'];
            $widgetObj->limit = $item['limit'];
            $widgetObj->relation = $item['relation'];

            $languages = Language::getLanguages();
            foreach ($languages as $language) {
                $widgetObj->title[$language['id_lang']] = $item['title'];
            }				
            $widgetObj->save();

            Db::getInstance()->insert('anblog_blog_widgets_shop', [
                'id_anblog_blog_widgets' => (int) $widgetObj->id, 
                'id_shop' => (int) Context::getContext()->shop->id
            ]); 
        }
		
	} 
}
