<?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)
*/

require_once _PS_MODULE_DIR_ . 'an_homecategories/classes/anHomecatFiles.php';

class AnHomecategories extends ObjectModel
{
    public $id_homecategory;
 
    public $id;
    
    public $active = 1;
    public $position;

    public $image;
    
    public $title;
    public $link;
    public $text_link;
    public $text;

    public static $definition = [
        'table' => 'an_homecategories',
        'primary' => 'id_homecategory',
        'multilang' => true,
        'fields' => [
            
            'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'position' => ['type' =>self::TYPE_INT ],
            
            'image' => ['type' =>self::TYPE_STRING],

            'title' => ['type' =>self::TYPE_STRING,'lang' => true ],
            'link' => ['type' =>self::TYPE_STRING,'lang' => true ],
            'text_link' => ['type' =>self::TYPE_STRING,'lang' => true ],
            'text' => ['type' =>self::TYPE_HTML,'lang' => true ],
            
        ],
    ];

    public const imgDir = _PS_MODULE_DIR_.'an_homecategories/img/';
    public const imgUrl = __PS_BASE_URI__.'modules/an_homecategories/img/';


    public const fileJsonSettings = _PS_MODULE_DIR_ . 'an_homecategories/settings.json';

    public function __construct($id = null)
    {
        parent::__construct($id);
    }

    public static function getHomecategories($pathImg = true)
    {
        
        $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'an_homecategories` ah
        LEFT JOIN `' . _DB_PREFIX_ . 'an_homecategories_lang` ahl
        ON (ahl.`id_homecategory` = ah.`id_homecategory` 
        AND ahl.`id_lang` = '.(int) Context::getContext()->language->id.' )
        WHERE  ah.`active` = 1 '; 
        
        if (Shop::isFeatureActive()) {
			$sql .= ' AND ah.`id_homecategory` IN (
				SELECT ahs.`id_homecategory`
				FROM `' . _DB_PREFIX_ . 'an_homecategories_shop` ahs
				WHERE ahs.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}

        $sql .= ' ORDER BY ah.`position`';

        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        if($pathImg){  
            foreach($result as $id => $val){
                if ($val['image'] !=''){
                    $result[$id]['image'] = self::imgUrl . $val['image'];
                    $imgInfo = getimagesize(self::imgDir . $val['image']);
                    $result[$id]['width'] = $imgInfo['0'];
                    $result[$id]['height'] = $imgInfo['1'];
                }
            }
        }    

        return $result;         
    }   

    public function delete()
    {        
        @unlink(self::imgDir . $this->image);
        return parent::delete();
    }  

    public static function exportJsonHomecategories($filesManager)
	{
		$homecategories = self::getHomecategories(false);	
        
        foreach ($homecategories as $key => $hc){
           // $obj = new AnHomecategories($advantage['id_homecategory']);
           $homecategories[$key]['link'] = '#';
        }

		@file_put_contents($filesManager->getContentFilePath(), json_encode($homecategories, JSON_PRETTY_PRINT));
	}	

	public static function importJsonHomecategories($filesManager)
	{
		$data = json_decode($filesManager->getContentFile(), true);
		$context = Context::getContext();

		if ($data){
			
			foreach ($data as $item){
            
				$homecategoriesObj = new AnHomecategories();
				$homecategoriesObj->active = $item['active'];
				$homecategoriesObj->position = $item['position'];

                $homecategoriesObj->image = $item['image'];
				
				$languages = Language::getLanguages();
				foreach ($languages as $language) {
					$homecategoriesObj->title[$language['id_lang']] = $item['title'];
					$homecategoriesObj->text[$language['id_lang']] = $item['text'];
					$homecategoriesObj->link[$language['id_lang']] = $item['link'];
				}				

				$homecategoriesObj->save();

                Db::getInstance()->insert('an_homecategories_shop', [
                    'id_homecategory' => (int) $homecategoriesObj->id, 
                    'id_shop' => (int) Context::getContext()->shop->id
                ]);  
			}
		}
	}  
    
    public static function getCount()
    {
        
        $sql = 'SELECT count(*) FROM `' . _DB_PREFIX_ . 'an_homecategories` ah
        LEFT JOIN `' . _DB_PREFIX_ . 'an_homecategories_lang` ahl
        ON (ahl.`id_homecategory` = ah.`id_homecategory` 
        AND ahl.`id_lang` = '.(int) Context::getContext()->language->id.' )
        '; 
        
        if (Shop::isFeatureActive()) {
			$sql .= ' WHERE ah.`id_homecategory` IN (
				SELECT ahs.`id_homecategory`
				FROM `' . _DB_PREFIX_ . 'an_homecategories_shop` ahs
				WHERE ahs.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);       
    }

}