<?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)
*/

class anHomeSlides extends ObjectModel
{
    /**
     * @var int
     */
    public $id_slide;
    /**
     * @var int
     */
    public $id;
    /**
     * @var int
     */
    public $id_parent;
    public $active = 1;
    public $show_button = 1;
    public $position;
    
    public $title;
    public $text;
    public $link;
    public $image;
    public $text_of_button;

    /**
     * @var array
     */
    public static $definition = [
        'table' => 'an_homeslider_slides',
        'primary' => 'id_slide',
        'multilang' => true,
        'fields' => [
            
            'id_parent' => ['type' => self::TYPE_INT],
            'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'show_button' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'position' => ['type' =>self::TYPE_INT ],

            'text_of_button' => ['type' =>self::TYPE_STRING,'lang' => true ],
            
            '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_homeslider/img/';
    public const imgUrl = __PS_BASE_URI__.'modules/an_homeslider/img/';

    /**
     * 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);
           $this->width = $imgInfo['0'];
           $this->height = $imgInfo['1'];
        }
    }
    

    public static function getSlides($idSlider = false, $pathImg = true, $allShops = false)
    {
        $context = Context::getContext();
        
		$sql = '
		SELECT * FROM `' . _DB_PREFIX_ . 'an_homeslider_slides` sw
		LEFT JOIN `' . _DB_PREFIX_ . 'an_homeslider_slides_lang` sl 
			ON (sw.`id_slide` = sl.`id_slide`
            AND sl.`id_lang` = ' . (int) $context->language->id . ')
		WHERE sw.`active`=1 
		';
        
        if ($idSlider) {
            $sql .= 'AND sw.`id_parent`=' . (int) $idSlider;
        }

		if (Shop::isFeatureActive() && !$allShops) {
			$sql .= ' AND sw.`id_slide` IN (
				SELECT sa.`id_slide`
				FROM `' . _DB_PREFIX_ . 'an_homeslider_slides_shop` sa
				WHERE sa.id_shop IN (' . implode(', ', Shop::getContextListShopID()) . ')
			)';
		}	

        $sql .= ' ORDER BY sw.`position`';
		
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        foreach($result as $id => $val){
            $result[$id] = str_replace('[span]', '<span>', $result[$id]);
            $result[$id] = str_replace('[/span]', '</span>', $result[$id]);
            $result[$id]['width'] = '';
            $result[$id]['height'] = '';
            if ($pathImg && $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'];            
            }

            $uploadImageName = trim(strip_tags($val['image']));
            $extension = pathinfo($uploadImageName, PATHINFO_EXTENSION);
            $result[$id]['format'] = $extension;
         }
 

        return $result;
    }

    public static function deleteSlidesByIdSlider($idSlider) 
    {
        $slides = self::getSlides($idSlider);
        foreach ($slides as $slide) {
            $obj = new anHomeSlides($slide['id_slide']);
            $obj->delete();  
        }
        
    }


    public function delete()
    {        
        foreach ($this->image as $imgName){
            @unlink(self::imgDir . $imgName);
        }

        

        return parent::delete();
    }	

    public static function importJsonSlides($slides, $id_slider)
	{
		if (!$slides){
            return false;
        }
			
        foreach ($slides as $slide){

            $slideObj = new anHomeSlides();
            $slideObj->id_parent = $id_slider;
            $slideObj->active = $slide['active'];
            $slideObj->position = $slide['position'];
            $slideObj->show_button = $slide['show_button'];
            
            $languages = Language::getLanguages();
            foreach ($languages as $language) {
                $slideObj->title[$language['id_lang']] = $slide['title'];
                $slideObj->text[$language['id_lang']] = $slide['text'];
                $slideObj->link[$language['id_lang']] = $slide['link'];
                $slideObj->text_of_button[$language['id_lang']] = $slide['text_of_button'];



                
                if (!isset($slideObj->image[$language['id_lang']]) && 
                isset($slide['imagesLang'][$language['id_lang']]) && 
                $slide['imagesLang'][$language['id_lang']] != $slide['image']){
                    $slideObj->image[$language['id_lang']] = $slide['imagesLang'][$language['id_lang']];
                } else {
                    $nameImage = $slide['image'];
                    if (!Tools::file_exists_no_cache(self::imgDir . $slide['image'])){
                        $nameImage = '';
                    }

                    if ($nameImage != ''  && 
                        is_array($slideObj->image) && 
                        in_array($slide['image'], $slideObj->image)
                    ){
                        $ext = substr($slide['image'], strrpos($slide['image'], '.') + 1);
                        $nameImage = $language['id_lang'] . '_' . md5(uniqid()) .'.'.$ext;
                        Tools::copy(self::imgDir . $slide['image'], self::imgDir . $nameImage);
                    }
                    $slideObj->image[$language['id_lang']] = $nameImage;
                }
            }				

            $slideObj->save();

            Db::getInstance()->insert('an_homeslider_slides_shop', [
                'id_slide' => (int) $slideObj->id, 
                'id_shop' => (int) Context::getContext()->shop->id
            ]);    
        }
        
        return true;
	}








	    
}