<?php

include_once _PS_MODULE_DIR_.'chcreateur/config/define.inc.php';


class Chcreaimages extends ObjectModel
{
    public $id;
    public $id_images;
    public $id_chcreaposts;
    public $name;
	public $type;

    public static $definition = [
		'table' => 'chcrea_images',
		'primary' => 'id_images',
		'multilang' => false,
		'fields' => [
            'id_chcreaposts' => ['type' => self::TYPE_INT, 'validate' => 'isunsignedInt'],
			'name' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => false],
			'type' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => false],
		],
	];

	public function __construct($id = null, $id_lang = null, $id_shop = null)
	{
		parent::__construct($id, $id_lang, $id_shop);
	}

	public function record()
	{

	}

	public function addUnique()
	{
		$exist = $this->getByPosts();
		if ( count($exist) > 0 ) {
			$ids = [];
			foreach($exist as $img) {
				$ids[] = $img['id_images'];
			}
			$this->deleteSelection($ids);
		}

		return $this->add();
	}


	public function getByPosts()
	{
		$sql  = ' SELECT * ';
		$sql .= ' FROM `'._DB_PREFIX_.'chcrea_images` ';
		$sql .= ' WHERE `id_chcreaposts` = '.$this->id_chcreaposts;
		$sql .= ' AND `type` = "'.$this->type.'"';

		return Db::getInstance()->executeS($sql);
	}

	public function getGallery($id_chcreaposts)
	{
		$this->id_chcreaposts = $id_chcreaposts;
		$this->type = 'gallery';

		return $this->getByPosts();
	}

	public function getUrls($id_chcreaposts, $type = 'post')
	{
		$this->id_chcreaposts = $id_chcreaposts;
		$this->type = $type;

		$result = $this->getByPosts();
		$imgs = [];  
		foreach($result as $img) {
			$imgs[] = chcrea_img_uri.$this->id_chcreaposts.'/'.$img['name'];
		}
		return $imgs;
	}

	public function getAllUrls($id_chcreaposts, $type = 'post')
	{
		$this->id_chcreaposts = $id_chcreaposts;
		$this->type = $type;

		$result = $this->getByPosts();
		$imgs = [];  

		$GetAllImageTypes = Chcreaimagetypeclass::GetAllImageTypes($this->type);
		

		if ( count($result) == 1 ) {
			if (isset($GetAllImageTypes) && !empty($GetAllImageTypes)) {
				foreach ($GetAllImageTypes as $imagetype) {
					$name = $imagetype['name'].'-'.$result[0]['name'];
					$imgs[0][$imagetype['name']] = chcrea_img_uri.$this->id_chcreaposts.'/'.$name;
					if (!$this->ImageExists($name)) {
						$imgs[0][$imagetype['name']] = chcrea_img_uri.$this->id_chcreaposts.'/'.$imagetype['name'].'-noimage.jpg';
					}
				}
			}
		}
		if ( count($result) > 1 ) {
			if (isset($GetAllImageTypes) && !empty($GetAllImageTypes)) {
				foreach($result as $key => $img) {
					foreach ($GetAllImageTypes as $imagetype) {
						$name = $imagetype['name'].'-'.$img['name'];
						$imgs[$key][$imagetype['name']] = chcrea_img_uri.$this->id_chcreaposts.'/'.$name;
						if (!$this->ImageExists($name)) {
							$imgs[$key][$imagetype['name']] = chcrea_img_uri.$this->id_chcreaposts.'/'.$imagetype['name'].'-noimage.jpg';
						}
					}
				}
			}
		}
		return $imgs;
	}

	public function ImageExists($file = null)
	{
		if (null == $file) {
			return false;
		}
		$image = chcrea_img_dir.$this->id_chcreaposts.'/'.$file;
		if (file_exists($image)) {
			return true;
		}
		return false;
	}

	public function getPath($dir=null)
	{
		if($dir == null) {
			$dir = chcrea_img_dir.$this->id_chcreaposts.'/';
			if ( !file_exists($dir) ) {
				$oldmask = umask(000);
				mkdir($dir                                                                                                                                                                                                                    );
				chmod($dir, 0775);
				umask($oldmask);
			}
		}
		return $dir;
	}

	/**
	 * @param mixed $name
	 * @param mixed $dir=null
	 * 
	 * @return $array
	 */
	public function uploadGallery($name, $id_chcreaposts, $dir=null)
	{
		$this->id_chcreaposts = $id_chcreaposts;
		$this->type = 'gallery';

		$dir = $this->getPath($dir);

		$results_imgs = false;
		if (isset($_FILES[$name]) && isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name'])) {

			$GetAllImageTypes = Chcreaimagetypeclass::GetAllImageTypes('gallery');

			foreach ($_FILES[$name]['name'] as $fileskey => $filesvalue) {
				// start upload
				if (isset($_FILES[$name]) && isset($_FILES[$name]['tmp_name'][$fileskey]) && !empty($_FILES[$name]['tmp_name'][$fileskey])) {
					$ext = substr($_FILES[$name]['name'][$fileskey], strrpos($_FILES[$name]['name'][$fileskey], '.') + 1);
					$basename_file_name = basename($_FILES[$name]["name"][$fileskey]);
					$strlen = strlen($basename_file_name);
					$strlen_ext = strlen($ext);
					$basename_file_name = substr($basename_file_name, 0, ($strlen-$strlen_ext));
					$link_rewrite_file_name = Tools::link_rewrite($basename_file_name);
					$file_name = $link_rewrite_file_name.'.'.$ext;
					$path = $dir.$file_name;

					if(move_uploaded_file($_FILES[$name]['tmp_name'][$fileskey], $path)) {
						if(isset($GetAllImageTypes) && !empty($GetAllImageTypes)) {
							foreach($GetAllImageTypes as $imagetype) {
								ImageManager::resize(
									$path, 
									$dir.$imagetype['name'].'-'.$file_name, 
									(int)$imagetype['width'], 
									(int)$imagetype['height'], $ext
								);
							}
						}
						$this->name = $file_name;
						if ( $this->add() ) {
							$results_imgs = true;
						}
					}
				}
				// end upload
			}
			return $results_imgs;
		} else {
			return $results_imgs;
		}
	}

		/**
	 * @param mixed $name
	 * @param mixed $dir=null
	 * 
	 * @return $string
	 */
	public function uploadMedia($name, $id_chcreaposts, $dir=null)
	{
		$this->id_chcreaposts = $id_chcreaposts;
		$this->type = 'post';

		$dir = $this->getPath($dir);

		$file_name = false;
		if (isset($_FILES[$name]) && isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name'])) {
			$ext = substr($_FILES[$name]['name'], strrpos($_FILES[$name]['name'], '.') + 1);
			$basename_file_name = basename($_FILES[$name]["name"]);
			$strlen = strlen($basename_file_name);
			$strlen_ext = strlen($ext);
			$basename_file_name = substr($basename_file_name, 0, ($strlen-$strlen_ext));
			$link_rewrite_file_name = Tools::link_rewrite($basename_file_name);
			$file_name = $link_rewrite_file_name.'.'.$ext;
			$path = $dir.$file_name;
			$GetAllImageTypes = Chcreaimagetypeclass::GetAllImageTypes('main');
			if(!move_uploaded_file($_FILES[$name]['tmp_name'], $path)) {
				return false;
			} else {
				if(isset($GetAllImageTypes) && !empty($GetAllImageTypes)) {
					foreach($GetAllImageTypes as $imagetype) {
						ImageManager::resize($path, $dir.$imagetype['name'].'-'.$file_name, (int)$imagetype['width'], (int)$imagetype['height'], $ext);
					}
				}
				$this->name = $file_name;
				if ( $this->addUnique() ) {
					return true;
				}
				return false;
			}
		} else {
			return $file_name;
		}
	}
}