<?php

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

use PrestaShop\PrestaShop\Adapter\Category\CategoryProductSearchProvider;
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;


class Chcreapost extends ObjectModel
{
	public $id;
	public $id_chcreaposts;
	public $post_author;
	public $post_date;
	public $post_modified;
	public $comment_status;
	public $post_password;
	public $post_format;
	public $comment_count;
	public $post_title;
	public $post_excerpt;
	public $post_content;
	public $post_img;
	public $link_rewrite;
	public $position;
	public $active;
	public $video;
	public $audio;
	public $gallery;
	public $meta_title;
	public $meta_description;
	public $meta_keyword;
	public $related_products;
	public static $definition = [
		'table' => 'chcreaposts',
		'primary' => 'id_chcreaposts',
		'multilang' => true,
		'fields' => [
			'post_title' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'meta_title' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'post_excerpt' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'meta_description' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'meta_keyword' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'post_content' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml', 'lang' => true],
			'link_rewrite' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'lang' => true],
			'related_products' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'],
			'video' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'],
			'audio' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'],
			'gallery' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'],
			'post_password' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
			'post_format' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
			'post_date' => ['type' => self::TYPE_DATE, 'validate' => 'isString'],
			'post_modified' => ['type' => self::TYPE_DATE, 'validate' => 'isString'],
			'post_img' => ['type' => self::TYPE_DATE, 'validate' => 'isString'],
			'post_author' => ['type' => self::TYPE_INT, 'validate' => 'isunsignedInt'],
			'comment_status' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
			'comment_count' => ['type' => self::TYPE_INT, 'validate' => 'isunsignedInt'],
			'position' => ['type' => self::TYPE_INT, 'validate' => 'isunsignedInt'],
			'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
		],
	];

	public function __construct($id = null, $id_lang = null, $id_shop = null)
	{
		
		
		
		// print("<pre>".print_r($_POST, true)."</pre>");
		// exit();
		
		Shop::addTableAssociation('chcreaposts', ['type' => 'shop']);
		parent::__construct($id, $id_lang, $id_shop);
	}

	/**
	 * @param bool $null_values
	 * 
	 * @return [type]
	 */
	public function update($null_values = false)
	{
		 //print('<pre>'.print_r($_POST,true).'</pre>');
		//  print('<pre>'.print_r($_FILES,true).'</pre>');
		//  exit();

		if (isset($_FILES['post_img'], $_FILES['post_img']['tmp_name']) && !empty($_FILES['post_img']['tmp_name'][0])) {
			$Chcreaimages = new Chcreaimages();
			if ( !$Chcreaimages->uploadMedia('post_img', $this->id) ) {
				return false;
			}
		}
		if (isset($_POST['related_products_temp']) && !empty($_POST['related_products_temp']) && is_array($_POST['related_products_temp'])) {
			$this->related_products = @implode(',', $_POST['related_products_temp']);
		}

		if (isset($_POST['gallery_temp_delete']) && !empty($_POST['gallery_temp_delete'])) {
			$gallery_temp_delete = @explode(',', $_POST['gallery_temp_delete']);
			if ( count($gallery_temp_delete) > 0 ) {
				$Chcreaimages = new Chcreaimages();
				$Chcreaimages->deleteSelection($gallery_temp_delete);
			}
		}

		if ( isset($_FILES['gallery_temp'], $_FILES['gallery_temp']['tmp_name']) && !empty($_FILES['gallery_temp']['tmp_name'][0]) ) {
				$Chcreaimages = new Chcreaimages();
			if ( !$Chcreaimages->uploadGallery('gallery_temp', $this->id) ) {
				return false;
			}
		}

		$this->post_modified = date('Y-m-d H:i:s');

		// if (empty($this->post_img) && isset($this->id)) {
		// 	$chcreapost = new Chcreapost($this->id);
		// 	$this->post_img = $chcreapost->post_img;
		// }

		return parent::update($null_values);
	}

	/**
	 * @param bool $autodate
	 * @param bool $null_values
	 * 
	 * @return [type]
	 */
	public function add($autodate = true, $null_values = false)
	{
		if (isset($_POST['related_products_temp']) && !empty($_POST['related_products_temp']) && is_array($_POST['related_products_temp'])) {
			$this->related_products = @implode(',', $_POST['related_products_temp']);
		}
		$this->post_author = (int) Context::getContext()->employee->id;
		$this->post_date = date('Y-m-d H:i:s');
		$this->post_modified = date('Y-m-d H:i:s');

		if ($this->position <= 0) {
				$this->position = self::getHigherPosition() + 1;
		}


		if (!parent::add($autodate, $null_values)
				|| !Validate::isLoadedObject($this)) {
			return false;
		}

		if (isset($_FILES['post_img'], $_FILES['post_img']['tmp_name']) && !empty($_FILES['post_img']['tmp_name'][0])) {
			$Chcreaimages = new Chcreaimages();
			if ( !$Chcreaimages->uploadMedia('post_img', $this->id) ) {
				return false;
			}
			
		}
		if ( isset($_FILES['gallery_temp'], $_FILES['gallery_temp']['tmp_name']) && !empty($_FILES['gallery_temp']['tmp_name'][0]) ) {
			$Chcreaimages = new Chcreaimages();
			if ( !$Chcreaimages->uploadGallery('gallery_temp', $this->id) ) {
				return false;
			}
		}

		return true;
	}

	public function getSrcFromIframe($video_temp)
	{
		$sContent = htmlspecialchars($video_temp);

		$dom = new DomDocument;

		@$dom->loadHTML( $video_temp );

		$elems = $dom->getElementsByTagName('iframe');

		if ( count($elems) < 0 ) {
			return null;
		}

		foreach ( $elems as $elm ) {
			if ( $elm->hasAttribute('src') )
				$srcs[] = $elm->getAttribute('src');
		}

		return $srcs;
	}

	public static function getHigherPosition()
    {
        $sql = 'SELECT MAX(`position`)
        FROM `'._DB_PREFIX_.'chcreaposts`';

        $position = DB::getInstance()->getValue($sql);

        return (is_numeric($position)) ? $position : -1;
    }

	/**
	 * @return [type]
	 */
	public static function getAllSelections($limit=null)
	{
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		
		//$sql  = ' SELECT xc.`id_chcreaposts`,xcl.`post_title`,xcl.`link_rewrite` ';
		$sql  = ' SELECT * ';
		$sql .= ' FROM `'._DB_PREFIX_.'chcreaposts` xc';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.')';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.')';
		$sql .= ' WHERE xc.`active` = 1 ';
		$sql .= ' ORDER BY xc.`position` ASC';
		if ( $limit != null ) {
			$sql .= ' LIMIT '.$limit;
		}

		$queryexec = Db::getInstance()->executeS($sql);

		if (isset($queryexec) && !empty($queryexec)) {
			$i = 0;
			foreach ($queryexec as $qlvalue) {
				if (isset($qlvalue) && !empty($qlvalue)) {
					foreach ($qlvalue as $qkey => $qvalue) {
						$results[$i][$qkey] = $qvalue;
						// start Image
						if ('post_img' == $qkey) {
							$Chcreaimages = new Chcreaimages();
							$tmp = $Chcreaimages->getAllUrls($qlvalue['id_chcreaposts'], 'post');

							$results[$i]['post_img'] = array_shift($tmp);
						}
						// end Image
						if ('post_author' == $qkey) {
							$post_author_arr = new Employee((int) $qvalue);
							$results[$i]['post_author_arr']['lastname'] = $post_author_arr->lastname;
							$results[$i]['post_author_arr']['firstname'] = $post_author_arr->firstname;
						}
						// TODO
						$results[$i]['link'] = self::getBaseLink($id_shop) . Configuration::get('CHCREATEUR_URL') . '/' . $qlvalue['id_chcreaposts'] . '_' . $qlvalue['link_rewrite'];
						//$results[$i]['post_tags'] = self::GetPostTagsResults($qlvalue['id_xipposts'], 'tag');
						if (isset($qlvalue['audio']) && !empty($qlvalue['audio'])) {
							$results[$i]['audio'] = self::getSrcFromIframe($qlvalue['audio']);
						}
						if (isset($qlvalue['video']) && !empty($qlvalue['video'])) {
							$results[$i]['video'] = self::getSrcFromIframe($qlvalue['video']);
						}

						if ('gallery' == $qkey) {
							$Chcreaimages = new Chcreaimages();
							$results[$i]['gallery_lists'] = $Chcreaimages->getAllUrls($qlvalue['id_chcreaposts'], 'gallery');
						}

					}
				}
				++$i;
			}
		}

		return $results;
	}

	public static function getSinglePost($id_chcreaposts = null, $post_type = 'post')
	{
		if (null == $id_chcreaposts) {
			return false;
		}
		$results = [];
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;

		$sql = 'SELECT * FROM `'._DB_PREFIX_.'chcreaposts` xc
			   INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.')
			   INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.')
			   ';
		$sql .= ' WHERE xc.id_chcreaposts = '.(int) $id_chcreaposts;

		$queryexec = Db::getInstance()->getrow($sql);

		if (isset($queryexec) && !empty($queryexec)) {
			foreach ($queryexec as $qkey => $qvalue) {
				$results[$qkey] = $qvalue;
				// start Image
				if ('post_img' == $qkey) {
					$Chcreaimages = new Chcreaimages();
					$tmp = $Chcreaimages->getAllUrls($id_chcreaposts, 'post');
					$results['post_img'] = array_shift($tmp);
				}
				// end Image
				if ( 'link_rewrite' == $qkey ) {
					$results['link'] = self::getBaseLink($id_shop) . Configuration::get('CHCREATEUR_URL').'/' . $id_chcreaposts . '_' . $qvalue;
				}
				if ('post_author' == $qkey) {
					$post_author_arr = new Employee((int) $qvalue);
					$results['post_author_arr']['lastname'] = $post_author_arr->lastname;
					$results['post_author_arr']['firstname'] = $post_author_arr->firstname;
				}
				if ('audio' == $qkey && !empty($qvalue)) {
					$results['audio'] = self::getSrcFromIframe($qvalue);
				}
				if ('video' == $qkey && !empty($qvalue)) {
					$results['video'] = self::getSrcFromIframe($qvalue);
				}
				if ('gallery' == $qkey) {
					$Chcreaimages = new Chcreaimages();
					$results['gallery_lists'] = $Chcreaimages->getAllUrls($id_chcreaposts, 'gallery');
				}
				if ('related_products' == $qkey) {
					if ( !empty($qvalue) ) {
						$prod_temp = @explode(',', $qvalue);
						$results['related_products'] = self::getViewedProducts($prod_temp);	
					} else {
						unset($results['related_products']);
					}
				}
			}
		}
		return $results;
	}


	public static function getsinglepath($id_chcreaposts = null, $post_type = 'post')
	{
		if (null == $id_chcreaposts) {
			return false;
		}
		$pipe = (Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>');
		$posts = self::get_the_title($id_chcreaposts, $post_type);
		//$category_default = $posts['category_default'] ? $posts['category_default'] : null;
		//$categories = self::get_the_category($category_default);
		// TODO title categorie
		$title = "Notre createur"; //$categories['name'] ? $categories['name'] : '';
		//
		$name = $posts['post_title'];
		$params['id'] = $categories['id_xipcategory'] ? $categories['id_xipcategory'] : 0;
		$params['rewrite'] = $categories['link_rewrite'] ? $categories['link_rewrite'] : '';
		$params['page_type'] = 'category';
		$params['subpage_type'] = $post_type ? $post_type : 'post';
		$link = xipblog::XipBlogCategoryLink($params);
		$meta_title = Configuration::get(xipblog::$xipblogshortname.'meta_title');
		$meta_title = (isset($meta_title) ? $meta_title : 'Blog');
		$blog_url = xipblog::XipBlogLink();
		$full_paths = '<a href="'.$blog_url.'" title="'.$meta_title.'" data-gg="">'.$meta_title.'</a><span class="navigation-pipe">'.$pipe.'</span>';

		$str = '<a href="'.$link.'" title="'.$title.'" data-gg="">'.$title.'</a><span class="navigation-pipe">'.$pipe.'</span>'.$name;

		return $full_paths.$str;
	}

	public static function getTopPosition()
	{
		$sql = 'SELECT MAX(`position`)
				FROM `'._DB_PREFIX_.'chcreaposts`';
		$position = DB::getInstance()->getValue($sql);

		return (is_numeric($position)) ? $position : -1;
	}

	public function updatePosition($way, $position)
	{
		if (!$res = Db::getInstance()->executeS(
			'
			SELECT `id_chcreaposts`, `position`
			FROM `'._DB_PREFIX_.'chcreaposts`
			ORDER BY `position` ASC'
		)) {
			return false;
		}
		if (!empty($res)) {
			foreach ($res as $chcreaposts) {
				if ((int) $chcreaposts['id_chcreaposts'] == (int) $this->id) {
					$moved_chcreaposts = $chcreaposts;
				}
			}
		}

		if (!isset($moved_chcreaposts) || !isset($position)) {
			return false;
		}
		$queryx = ' UPDATE `'._DB_PREFIX_.'chcreaposts`
		SET `position`= `position` '.($way ? '- 1' : '+ 1').'
		WHERE `position`
		'.($way
		? '> '.(int) $moved_chcreaposts['position'].' AND `position` <= '.(int) $position
		: '< '.(int) $moved_chcreaposts['position'].' AND `position` >= '.(int) $position.'
		');
		$queryy = ' UPDATE `'._DB_PREFIX_.'chcreaposts`
		SET `position` = '.(int) $position.'
		WHERE `id_chcreaposts` = '.(int) $moved_chcreaposts['id_chcreaposts'];

		return Db::getInstance()->execute($queryx)
		&& Db::getInstance()->execute($queryy);
	}


	public static function get_the_title($id_chcreaposts = null, $post_type = 'post')
	{
		if (null == $id_chcreaposts) {
			return false;
		}
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		$sql = 'SELECT xc.`id_chcreaposts`,xcl.`post_title`,xcl.`link_rewrite` FROM `'._DB_PREFIX_.'chcreaposts` xc
		INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.')
		INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.')
		';
		$sql .= ' WHERE xc.`post_type` = "'.($post_type ? pSQL($post_type) : 'post').'" AND xc.`id_chcreaposts` = '.$id_chcreaposts;

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

	public static function get_the_id($rewrite = null, $post_type = 'post')
	{
		if (null == $rewrite) {
			return false;
		}
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		$sql = 'SELECT xc.`id_chcreaposts` FROM `'._DB_PREFIX_.'chcreaposts` xc INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.') INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.') ';
		$sql .= ' WHERE xc.`post_type` = "'.($post_type ? pSQL($post_type) : 'post').'" AND xcl.`link_rewrite` = "'.pSQL($rewrite).'" ';
		$rslts = Db::getInstance()->getrow($sql);

		return isset($rslts['id_chcreaposts']) ? $rslts['id_chcreaposts'] : null;
	}

	public function getNextPost($position)
	{
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		$sql = ' SELECT * FROM `'._DB_PREFIX_.'chcreaposts` xc ';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.')';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.')';
		$sql .= ' WHERE xc.`position` > '.$position;
		$sql .= ' AND xc.`active` = 1';
		$sql .= ' ORDER BY xc.`position` ASC';
		$rslt = Db::getInstance()->getrow($sql);
		if (empty($rslt)) {
			return null;
		}
		$rslt['link'] = '/'.Configuration::get('CHCREATEUR_URL').'/'.$rslt['id_chcreaposts'].'_'.$rslt['link_rewrite'];

		return $rslt;
	}

	public function getPreviousPost($position)
	{
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		$sql = ' SELECT * FROM `'._DB_PREFIX_.'chcreaposts` xc ';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.')';
		$sql .= ' INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.')';
		$sql .= ' WHERE xc.`position` < '.$position;
		$sql .= ' AND xc.`active` = 1';
		$sql .= ' ORDER BY xc.`position` DESC';


		//print($sql);

		$rslt = Db::getInstance()->getrow($sql);
		if (empty($rslt)) {
			return null;
		}
		$rslt['link'] = '/'.Configuration::get('CHCREATEUR_URL').'/'.$rslt['id_chcreaposts'].'_'.$rslt['link_rewrite'];

		return $rslt;
	}

	public static function PostExists($id_chcreaposts = null, $post_type = 'post')
	{
		if (null == $id_chcreaposts || 0 == $id_chcreaposts) {
			return false;
		}
		$sql = 'SELECT xc.`id_chcreaposts` FROM `'._DB_PREFIX_.'chcreaposts` xc WHERE xc.`post_type` = "'.($post_type ? $post_type : 'post').'" AND xc.active = 1 AND xc.`id_chcreaposts` = '.$id_chcreaposts;
		$rslts = Db::getInstance()->getrow($sql);

		return (isset($rslts['id_chcreaposts']) && !empty($rslts['id_chcreaposts'])) ? true : false;
	}

	public static function get_the_rewrite($id = null, $post_type = 'post')
	{
		if (null == $id) {
			return false;
		}
		$id_lang = (int) Context::getContext()->language->id;
		$id_shop = (int) Context::getContext()->shop->id;
		$sql = 'SELECT xcl.`link_rewrite` FROM `'._DB_PREFIX_.'chcreaposts` xc INNER JOIN `'._DB_PREFIX_.'chcreaposts_lang` xcl ON (xc.`id_chcreaposts` = xcl.`id_chcreaposts` AND xcl.`id_lang` = '.$id_lang.') INNER JOIN `'._DB_PREFIX_.'chcreaposts_shop` xcs ON (xc.`id_chcreaposts` = xcs.`id_chcreaposts` AND xcs.`id_shop` = '.$id_shop.') ';
		$sql .= ' WHERE xc.`post_type` = "'.($post_type ? $post_type : 'post').'" AND xc.`id_chcreaposts` = "'.$id.'" ';
		$rslts = Db::getInstance()->getrow($sql);

		return isset($rslts['link_rewrite']) ? $rslts['link_rewrite'] : null;
	}

	public static function ImageExists($file = null)
	{
		if (null == $file) {
			return false;
		}
		$image = chcrea_img_dir.$file;
		if (file_exists($image)) {
			return true;
		}

		return false;
	}

	public static function PostCountUpdate($id = null)
	{
		if (null == $id || 0 == $id) {
			return false;
		}
		$sql = 'UPDATE '._DB_PREFIX_.'chcreaposts as xc SET xc.comment_count = (xc.comment_count+1) where xc.id_chcreaposts = '.(int) $id;
		if (Db::getInstance()->execute($sql)) {
			return true;
		}

		return false;
	}


	/**
	 * @param mixed $productIds
	 * 
	 * @return [type]
	 */
	protected function getViewedProducts($productIds)
	{
		if (!empty($productIds)) {
			$context = Context::getContext();
			$assembler = new ProductAssembler($context);

			$presenterFactory = new ProductPresenterFactory($context);
			$presentationSettings = $presenterFactory->getPresentationSettings();
			$presenter = new ProductListingPresenter(
				new ImageRetriever(
					$context->link
				),
				$context->link,
				new PriceFormatter(),
				new ProductColorsRetriever(),
				$context->getTranslator()
			);

			$products_for_template = [];

			if (is_array($productIds)) {
				foreach ($productIds as $productId) {
					// if ($this->currentProductId !== $productId) {
					$products_for_template[] = $presenter->present(
						$presentationSettings,
						$assembler->assembleProduct(['id_product' => $productId]),
						$context->language
					);
					// }
				}
			}
			return $products_for_template;
		}
		return false;
	}


	public static function getBaseLink($id_shop = null, $ssl = null, $relative_protocol = false)
	{
		static $force_ssl = null;

		if ($ssl === null) {
			if ($force_ssl === null) {
				$force_ssl = (Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE'));
			}
			$ssl = $force_ssl;
		}

		if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && $id_shop !== null) {
			$shop = new Shop($id_shop);
		} else {
			$shop = Context::getContext()->shop;
		}

		if ($relative_protocol) {
			$base = '//'.($ssl ? $shop->domain_ssl : $shop->domain);
		} else {
			$base = (($ssl) ? 'https://'.$shop->domain_ssl : 'http://'.$shop->domain);
		}

		return $base.$shop->getBaseURI();
	}
}
