<?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 AnSizeGuideWidgets extends ObjectModel
{
    /**
     * @var int
     */
    public $id_widget;
    /**
     * @var int
     */
    public $id;
    /**
     * @var int
     */
    public $active = 1;
    public $position;
	public $relation = 0;
	public $show_on = 0;
    public $sizeguide_title;
    public $sizeguide_content;

    /**
     * @var array
     */
    public static $definition = array(
        'table' => 'an_size_guide_widgets',
        'primary' => 'id_widget',
        'multilang' => true,
        'fields' => array(
            'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
	
            'position' => array('type' =>self::TYPE_INT ),
            'relation' => array('type' =>self::TYPE_INT ),
            'show_on' => array('type' =>self::TYPE_INT ),

            'sizeguide_title' => array('type' =>self::TYPE_STRING,'lang' => true ),
            'sizeguide_content' => array('type' =>self::TYPE_HTML,'lang' => true ),
        ),
    );

    /**
     * Formula constructor.
     *
     * @param null $id
     */
    public function __construct($id = null, $id_lang = null)
    {
        parent::__construct($id, $id_lang);
    }
	
	public static function getSizeGuide($id_product = 0, $hookName = '')
	{
		$cats = Product::getProductCategories($id_product);
        $context = Context::getContext();

        $productObj = new Product($id_product);

        $idManufacturer = 0;
        if (isset($productObj->id_manufacturer)){
            $idManufacturer = $productObj->id_manufacturer;
        }
        
        $sql_show_on = '';
        if ($hookName == 'displayProductPriceBlock'){
            $sql_show_on = 'AND sw.`show_on`= 1';
        }

        $sql = '
		SELECT * FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_relations` szwr, `' . _DB_PREFIX_ . 'an_size_guide_widgets` sw
		LEFT JOIN `' . _DB_PREFIX_ . 'an_size_guide_widgets_lang` sl 
			ON (sw.`id_widget` = sl.`id_widget`
            AND sl.`id_lang` = ' . (int) $context->language->id . ')
		WHERE sw.`active`=1 '.$sql_show_on.'

			AND sw.`id_widget` = szwr.`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` = 3 AND szwr.`id_type` = '.(int) $idManufacturer.') OR 
        (szwr.`type` = 0 AND szwr.`id_type` = 0)';
        $sql .= ')';
	
		if (Shop::isFeatureActive()) {
			$sql .= ' AND sw.`id_widget` IN (
				SELECT sa.`id_widget`
				FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_shop` sa
				WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}	

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



        foreach ($result as &$sizeguide){
            $sizeguide['ajaxController'] = $context->link->getModuleLink('an_sizeguide', 'ajax', [
                'token' => Tools::getToken(false), 
                'action' => 'getSizeGuide',
                'id_widget' => $sizeguide['id_widget']
            ], true);

        }

        if (!$result) {
            return [];
        } else {
			return $result;
		}		
	}
		
    public static function getSizeGuideById($id_widget = 0)
	{
        $context = Context::getContext();

        $sql = '
		SELECT * FROM  `' . _DB_PREFIX_ . 'an_size_guide_widgets` sw
		LEFT JOIN `' . _DB_PREFIX_ . 'an_size_guide_widgets_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` = '.(int) $id_widget.'
		';	
	
		if (Shop::isFeatureActive()) {
			$sql .= ' AND sw.`id_widget` IN (
				SELECT sa.`id_widget`
				FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_shop` sa
				WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}	
		
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        if (!$result) {
            return [];
        } else {
			return $result;
		}		
	}	

    public static function getRelationsByIdWidget($widget, $type, $onlyIds = false)
    {
        if (!$widget){
            return [];
        }
        
        $sql = '
        SELECT  *
        FROM `' . _DB_PREFIX_ . 'an_size_guide_widgets_relations` awl
        WHERE awl.`widget` = ' . (int) $widget . ' AND awl.`type`='.(int) $type.' ';
        
        
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);

        if (!$onlyIds){
            return $result;
        }

        $relations = [];
        foreach ($result as $item){
            $relations[$item['id_type']] = $item;
        }

        return $relations;
    }

    public static function updateCategoriesProducts($ids = [], $widget = 0, $type = 0)
    {
        if (!$widget){
            return false;
        }        

        Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('DELETE FROM `'._DB_PREFIX_.'an_size_guide_widgets_relations` WHERE `widget`='.(int) $widget.' ');
           
        if (!$ids || count($ids) == 0) {
            $ids[] = 0;
        }
        
        $ids = array_unique($ids);

        foreach ($ids as $id) {                        
            $sql = 'INSERT INTO `'._DB_PREFIX_.'an_size_guide_widgets_relations`  (`widget`, `id_type`, `type`) 
            VALUES ("'.(int) $widget.'", "'.(int) $id.'", "'.(int) $type.'" )';
            Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql);
        }
        
        return true;
    }
}
