<?php
/**
 * @package     Cherry Picker for Virtuemart
 * @subpackage  Manufacturers
 * @author		Maksym Stefanhuck
 * @copyright   Copyright (C) 2009 - 2014 Galt.md. All rights reserved.
 * @license     GNU General Public License version 2 or later; see COPYING.txt
 */

namespace cherrypicker;
defined('_JEXEC') or die;

//require_once(dirname(__FILE__) ."/../defines.php");
require_once('submodule.php');
require_once(CP_BASEPATH .'helpers/sql.php');

use \JRequest;
use \JFactory;
use \JRoute;


// To initialize Virtuemart's VMLANG
if (!class_exists('VmConfig')) {
	require_once(JPATH_ADMINISTRATOR .'/components/com_virtuemart/helpers/config.php');
	\VmConfig::loadConfig();
}

class ManufacturersModel extends Submodule {
	private static $_instance = null;
	private $_list_of_selected = null;
	//private $_url_parameter_name;
	private $_sql_wheres = array();

	//function __construct($url_parameter_name = 'brand') {
	//	parent::__construct();
	//	$this->_url_parameter_name = $url_parameter_name;
	//}

	public static function getInstance() {
		if (! self::$_instance) {
			self::$_instance = new ManufacturersModel();
		}
		return self::$_instance;
	}

	public function submoduleName() {
		return 'manufacturer';
	}

	public function listOfSelected() {
		if ($this->_list_of_selected === null) {
			//return $this->_list_of_selected;

			$selected = array();
			$selected_str = JRequest::getVar('brand', '');
			if ($selected_str) {
				$selected_array = explode('|', $selected_str);
				foreach ($selected_array as $mf)
					if (trim($mf)) $selected[] = $mf;
			}

			$db = JFactory::getDBO();
			$vmmf = (int)JRequest::getVar('virtuemart_manufacturer_id', 0);
			if ($vmmf) {
				$q = "SELECT `slug` FROM `#__virtuemart_manufacturers_". VMLANG ."`".
					" WHERE `virtuemart_manufacturer_id`='$vmmf'";
				$db->setQuery($q);
				$alias = $db->loadResult();
				if ($alias)
					$selected[] = $alias;
			}

			$manufacturers = array();
			if ($selected) {

				$columns = array();
				$joins = array();
				$wheres = array();

				$columns[] = "l.`virtuemart_manufacturer_id` as id";
				$columns[] = "l.`mf_name` as name";
				$columns[] = "l.`slug` as alias";
				//$joins[] = "LEFT JOIN `#__virtuemart_manufacturers_". VMLANG ."` as l"
						//." USING (`virtuemart_manufacturer_id`)";
				//$wheres[] = "m.`published`=1";
				$wheres[] = "l.`slug` IN ('". join("', '", $selected) ."')";
				//if ($image) {
					$columns[] = "media.`file_url` as image";
					$columns[] = "media.`file_url_thumb` as thumb";
					$joins[] = "LEFT JOIN `#__virtuemart_manufacturer_medias` as mm"
							." USING (`virtuemart_manufacturer_id`)";
					$joins[] = "LEFT JOIN `#__virtuemart_medias` as media"
							." ON mm.`virtuemart_media_id`=media.`virtuemart_media_id`";
				//}

				$q = "SELECT ". join(', ', $columns)
					." FROM `#__virtuemart_manufacturers_". VMLANG ."` as l "
					. join(" ", $joins)
					." WHERE ". join(" AND ", $wheres);

			//	$q = "SELECT `virtuemart_manufacturer_id` as id, `mf_name` as name,"
			//		." `slug` as alias"
			//		." FROM `#__virtuemart_manufacturers_". VMLANG ."`"
			//		." WHERE `slug` IN ('". implode("', '", $selected) ."')";


				$db->setQuery($q);
				$manufacturers = $db->loadAssocList();
				//$manufacturers = $db->loadObjectList();
//var_dump($db);
//print_r($manufacturers);
//die;
			}
			$this->_list_of_selected = $manufacturers;
		}

		return $this->_list_of_selected;
	}


	public function selectedIds() {
		$ids = array();
		foreach ($this->listOfSelected() as $manufacturer)
			$ids[] = $manufacturer['id'];
			//$ids[] = $manufacturer->id;
		return $ids;
	}

	public function selectedValues() {
		return $this->listOfSelected();
		$values = array();
		foreach ($this->listOfSelected() as $manufacturer)
			//$values[] = array(
			//	"name" => $manufacturer->name,
			//	"alias" => $manufacturer->alias
			//);
		return $values;
	}

	public function selectedAliases() {
		$values = array();
		foreach ($this->listOfSelected() as $manufacturer)
			$values[] = $manufacturer['alias'];
			//$values[] = $manufacturer->alias;
		return $values;
	}


	public function sqlWheres(/*$table = ''*/) {
		if ($this->_sql_wheres)
			return $this->_sql_wheres;

		//if (! $table)
			//$table = "`#__virtuemart_product_manufacturers`";
			//$column = "`#__virtuemart_product_manufacturers`.`virtuemart_manufacturer_id`";
		$wheres = array();
		$table = Sql::table('#__virtuemart_product_manufacturers');
		$column = Sql::column('virtuemart_manufacturer_id', $table);
		if (( $ids = $this->selectedIds() )) {
			//$wheres = array($table .".`virtuemart_manufacturer_id` IN (".
				//implode(', ', $ids) .")");
			$wheres[] = Sql::where("%s IN (". implode(', ', $ids) .")", $column);
			$this->_sql_wheres = $wheres;
		}

		return $wheres;
	}

	public function sqlJoins(SqlColumn $on_column) {
		$joins = array();
		$table = Sql::table('#__virtuemart_product_manufacturers');
		$joins[] = Sql::join(
			'left',
			$table,
			$on_column,
			Sql::column('virtuemart_product_id', $table)
		);



		//if (! $on_column)
		//	$on_column = "`#__virtuemart_products`.`virtuemart_product_id`";
		//if ($alias) {
		//	$as_alias = " as ". $alias;
		//	$table = $alias;
		//} else {
		//	$as_alias = '';
		//	$table = "`#__virtuemart_product_manufacturers`";
		//}
		//$joins = array("LEFT JOIN `#__virtuemart_product_manufacturers`"
		//	. $as_alias ." ON $on_column=$table.`virtuemart_product_id`"
		//);


		//if ($on_column === '')
		//	$on_column = Sql::column('virtuemart_product_id', '#__virtuemart_products');
		//$table = Sql::table('#__virtuemart_product_manufacturers', $alias);
		//$joins[] = Sql::join(
		//	'left',
		//	$table,
		//	$on_column,
		//	Sql::column('virtuemart_product_id', $table)
		//);

		if ($this->selectedIds())
			return $joins;


		foreach ($this->dependencies() as $dependency)
			if ($dependency->needsDependency($this))
				return $joins;

		return array();
	}


	public function url() {
		//$url = array();
		$url = '';
		//$selectedAliases = $this->selectedAliases();
		if (( $id = JRequest::getVar('virtuemart_manufacturer_id', 0) ))
			$url = 'virtuemart_manufacturer_id='. $id;
		else if (( $selectedAliases = $this->selectedAliases() ))
			$url = 'brand='. join('|', $selectedAliases);
		//return join('&', $url);
		return $url;
	}


	/*
	 * See Parameter model for an example of $only_submodules use
	 */
	public function availableValues($withCount = false, $image = false, $limit = 0, $url = false, $selecttype = 'single', $sort = 'asc', array $only_submodules = array()) {
		$db = JFactory::getDbo();
		//$columns = array();
		//$tables = array();
		$joins = array();
		$wheres = array();
		$query = Sql::query();

		$manufacturers_table = Sql::table('#__virtuemart_manufacturers', 'm');
		$product_manufacturers_table = Sql::table('#__virtuemart_product_manufacturers', 'pm');
		$products_table = Sql::table('#__virtuemart_products', 'p');
		$on_column = Sql::column("virtuemart_product_id", $product_manufacturers_table);
		$manufacturers_column = Sql::column("virtuemart_manufacturer_id", $manufacturers_table);

		$query->select($manufacturers_column, "id")
				->select("l.`mf_name`", "name")
				->select("l.`slug`", "alias")
				->from($manufacturers_table);

		$query->join(
			'left',
			Sql::table('#__virtuemart_manufacturers_'. VMLANG, 'l'),
			$manufacturers_column
		);
		$query->join('left', $product_manufacturers_table, $manufacturers_column);
		$query->where('m.`published`=1');

		if ($image) {
			$query->select("media.`file_url`", "image")
				->select("media.`file_url_thumb`", "thumb");
			$query->join(
				'left',
				Sql::table("#__virtuemart_manufacturer_medias", "mm"),
				$manufacturers_column
			);
			$query->join(
				'left',
				Sql::table("#__virtuemart_medias", "media"),
				Sql::column("virtuemart_media_id", "mm"),
				Sql::column("virtuemart_media_id", "media")
			);
		}

		if ($withCount) {
			$query->select("COUNT(DISTINCT pm.`virtuemart_product_id`) as count");
			$query->join(
				'left',
				$products_table,
				$on_column,
				Sql::column('virtuemart_product_id', $products_table)
			);
			$query->where("(p.`published`=1 OR p.`published` IS NULL)");
			$query->group($manufacturers_column);
		} else {
			$query->distinct(true);
		}


		//$columns[] = "m.`virtuemart_manufacturer_id` as id";
		//$columns[] = "l.`mf_name` as name";
		//$columns[] = "l.`slug` as alias";
		//$tables[] = "`#__virtuemart_manufacturers` as m";
		//$joins[] = "LEFT JOIN `#__virtuemart_manufacturers_". VMLANG ."` as l"
		//		." USING (`virtuemart_manufacturer_id`)";
		//$wheres[] = "m.`published`=1";
		//if ($image) {
		//	$columns[] = "media.`file_url` as image";
		//	$columns[] = "media.`file_url_thumb` as thumb";
		//	$joins[] = "LEFT JOIN `#__virtuemart_manufacturer_medias` as mm"
		//			." USING (`virtuemart_manufacturer_id`)";
		//	$joins[] = "LEFT JOIN `#__virtuemart_medias` as media"
		//			." ON mm.`virtuemart_media_id`=media.`virtuemart_media_id`";
		//}

		//	$joins[] = "LEFT JOIN `#__virtuemart_product_manufacturers` as pm"
		//		." USING (`virtuemart_manufacturer_id`)";
		//if ($withCount) {
		//	$columns[] = "COUNT(DISTINCT pm.`virtuemart_product_id`) as count";
		//	$joins[] = "LEFT JOIN `#__virtuemart_products` as p"
		//		." ON pm.`virtuemart_product_id`=p.`virtuemart_product_id`";

		//	$wheres[] = "(p.`published`=1 OR p.`published` IS NULL)";
		//}

		//$on_column = "pm.`virtuemart_product_id`";
		foreach (Submodule::submodules() as $submodule) {
			$name = $submodule->submoduleName();
			if ( !$only_submodules || isset($only_submodules[$name]) ) {
				if ($name != 'manufacturer') {
					$joins = array_merge($joins, $submodule->sqlJoins($on_column));
					$wheres = array_merge($wheres, $submodule->sqlWheres());
				}
			}
		}

		foreach ($joins as $join) $query->join($join);
		foreach ($wheres as $where) $query->where($where);

		//if ($withCount)
		//	$q = "SELECT ";
		//else
		//	$q = "SELECT DISTINCT ";


		//$q .= join(', ', $columns)
		//	." FROM (". join(', ', $tables) .") "
		//	. join(" ", $joins)
		//	." WHERE ". join(" AND ", $wheres);

		//if ($withCount)
			//$q .= " GROUP BY m.`virtuemart_manufacturer_id`";

		if ($sort) {
			$query->order(Sql::column("name"), ($sort == 'desc') ? "DESC" : "ASC");
		}

		//if ($sort) {
		//	$q .= " ORDER BY name ";
		//	$q .= ($sort == 'desc') ? "DESC" : "ASC";
		//}

		if ($limit)
			$query->limit(0, $limit);
			//$q .= " LIMIT 0, $limit";

		$query->uniquify();

		$db = JFactory::getDBO();
		$db->setQuery((string)$query);
		$values = $db->loadAssocList();

//var_dump($db);
//var_dump($values);
//die;



		// Sort values
		//if ($sort) {
		//	// sort filters by name in multi-dimensional array
		//	$names = array();
		//	foreach ($values as $value) $names[] = $value['name'];

		//	/*
		//	 * Note. You may experiment by using other sort FLAGS,
		//	 * for example: SORT_NATURAL
		//	 * You can get the list of all flags here:
		//	 * http://php.net/manual/en/function.array-multisort.php
		//	 */
		//	$sort_order = ($sort == 'desc') ? SORT_DESC : SORT_ASC;
		//	$sort_flags = defined('SORT_NATURAL') ? SORT_NATURAL : SORT_NUMERIC;
		//	array_multisort($names, $sort_order, $sort_flags, $values);
		//}


		//if ($limit && count($values) > $limit)
			//array_splice($values, $limit);


		if ($url) {
			$environment = Environment::getInstance();
			$url_base = $environment->baseUrl();
			//$selected_parameters_count = 0;
			foreach (Submodule::submodules() as $submodule)
				if ($submodule->submoduleName() != 'manufacturer'
					&& ( $t = $submodule->url() ))
				{
					$url_base .= '&'. $t;
				}


			$selectedAliases = $this->selectedAliases();
			foreach ($values as &$value) {
				$value_url = '';
				$is_selected = in_array($value['alias'], $selectedAliases);
				if ($selecttype == 'multi') {
					if ($is_selected) {
						// todo:
						// if (CP_CHECK_SELECTION_NONZERO && $selected_parameters_count > 1
						// && count($selectedValues) > 1) .. get count
						$result = array_diff($selectedAliases, (array)$value['alias']);
						if ($result)
							$value_url = '&brand='.
								$environment->urlEncode(join('|', $result));
					} else {
						$result = $selectedAliases;
						$result[] = $value['alias'];
						$value_url = '&brand='.
							$environment->urlEncode(join('|', $result));
					}
				} else if (! $is_selected) {
					$value_url = '&brand='. $environment->urlEncode($value['alias']);
				}

				$value['url'] = JRoute::_($url_base . $value_url);
			}

		}

//echo '<pre>';
//print_r($values);
//die;

		return $values;
	}


	public function removeValueUrl($value) {
		$environment = Environment::getInstance();
		$url = $environment->baseUrl();
		foreach (Submodule::submodules() as $submodule)
			if ($submodule->submoduleName() != 'manufacturer'
				&& ( $t = $submodule->url() ))
			{
				$url .= '&'. $t;
			}


		$selectedAliases = $this->selectedAliases();
		$result = array_diff($selectedAliases, (array)$value['alias']);
		if ($result)
			$url .= '&brand='. $environment->urlEncode(join('|', $result));

		return JRoute::_($url);
	}


	public function removeValuesUrl() {
		$environment = Environment::getInstance();
		$url = $environment->baseUrl();
		foreach (Submodule::submodules() as $submodule)
			if ($submodule->submoduleName() != 'manufacturer'
				&& ( $t = $submodule->url() ))
			{
				$url .= '&'. $t;
			}

		return JRoute::_($url);
	}



}
