<?php

/**
 * Simpla CMS
 *
 * @copyright	2011 Denis Pikusov
 * @link		http://simplacms.ru
 * @author		Denis Pikusov
 *
 * @editor	2014 Vitaly Raevsky
 * @link	http://bwdesign.ru
 * @email	vitaly.raevsky@gmail.com
 *
 */
 
require_once('Simpla.php');

class Features extends Simpla
{	
	
	function get_features($filter = array())
	{
		$category_id_filter = '';	
		if(isset($filter['category_id']))
			$category_id_filter = $this->db->placehold('AND id in(SELECT feature_id FROM __categories_features AS cf WHERE cf.category_id in(?@))', (array)$filter['category_id']);
			
		$in_filter_filter = '';	
		if(isset($filter['in_filter']))
			$in_filter_filter = $this->db->placehold(' AND f.in_filter=?', intval($filter['in_filter']));
		if(isset($filter['on_main']))
			$in_filter_filter.= $this->db->placehold(' AND f.on_main=?', intval($filter['on_main']));
		if(isset($filter['on_prod']))
			$in_filter_filter.= $this->db->placehold(' AND f.on_prod=?', intval($filter['on_prod']));

		
		$id_filter = '';	
		if(!empty($filter['id']))
			$id_filter = $this->db->placehold('AND f.id in(?@)', (array)$filter['id']);
		
		// Выбираем свойства
		$query = $this->db->placehold("SELECT id, name, position, in_filter
					, on_prod, on_main, multiselect, in_variant, in_compare, isrange, slider, unit, istext, image, nameselect
									 FROM __features AS f
									WHERE 1
									$category_id_filter $in_filter_filter $id_filter ORDER BY f.position");
		$this->db->query($query);
		return $this->db->results();
	}
		
	function get_feature($id)
	{
		// Выбираем свойство
		$query = $this->db->placehold("SELECT id, name, position, in_filter
						, on_prod, on_main, multiselect, in_variant, in_compare, isrange, slider, unit, istext, image, nameselect
						 FROM __features WHERE id=? LIMIT 1", $id);
		$this->db->query($query);
		$feature = $this->db->result();

		return $feature;
	}
	
	function get_feature_categories($id)
	{
		$query = $this->db->placehold("SELECT cf.category_id as category_id FROM __categories_features cf
										WHERE cf.feature_id = ?", $id);
		$this->db->query($query);
		return $this->db->results('category_id');	
	}
	
	public function add_feature($feature)
	{
		$query = $this->db->placehold("INSERT INTO __features SET ?%", $feature);
		$this->db->query($query);
		$id = $this->db->insert_id();
		$query = $this->db->placehold("UPDATE __features SET position=id WHERE id=? LIMIT 1", $id);
		$this->db->query($query);
		return $id;
	}
		
	public function update_feature($id, $feature)
	{
		$query = $this->db->placehold("UPDATE __features SET ?% WHERE id in(?@) LIMIT ?", (array)$feature, (array)$id, count((array)$id));
		$this->db->query($query);
		return $id;
	}
	
	public function delete_feature($id = array())
	{
		if(!empty($id))
		{
			$query = $this->db->placehold("DELETE FROM __features WHERE id=? LIMIT 1", intval($id));
			$this->db->query($query);
			$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=?", intval($id));
			$this->db->query($query);	
			$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", intval($id));
			$this->db->query($query);	
			$query = $this->db->placehold("DELETE FROM __variants_options WHERE id_feature=?", intval($id));
			$this->db->query($query);	
		}
	}
	

	public function delete_option($product_id, $feature_id)
	{
		$query = $this->db->placehold("DELETE FROM __options WHERE product_id=? AND feature_id=? LIMIT 1", intval($product_id), intval($feature_id));
		$this->db->query($query);
	}

	
	public function update_option($product_id, $feature_id, $value)
	{	 
		if($value != '')
			$query = $this->db->placehold("REPLACE INTO __options SET value=?, product_id=?, feature_id=?", $value, intval($product_id), intval($feature_id));
		else
			$query = $this->db->placehold("DELETE FROM __options WHERE feature_id=? AND product_id=?", intval($feature_id), intval($product_id));
		return $this->db->query($query);
	}


	public function add_feature_category($id, $category_id)
	{
		$query = $this->db->placehold("INSERT IGNORE INTO __categories_features SET feature_id=?, category_id=?", $id, $category_id);
		$this->db->query($query);
	}
			
	public function update_feature_categories($id, $categories)
	{
		$id = intval($id);
		$query = $this->db->placehold("DELETE FROM __categories_features WHERE feature_id=?", $id);
		$this->db->query($query);
		
		
		if(is_array($categories))
		{
			$values = array();
			foreach($categories as $category)
				$values[] = "($id , ".intval($category).")";
	
			$query = $this->db->placehold("INSERT INTO __categories_features (feature_id, category_id) VALUES ".implode(', ', $values));
			$this->db->query($query);

			// Удалим значения из options 
			$query = $this->db->placehold("DELETE o FROM __options o
			                               LEFT JOIN __products_categories pc ON pc.product_id=o.product_id
			                               WHERE o.feature_id=? AND pc.category_id not in(?@)", $id, $categories);
			$this->db->query($query);
		}
		else
		{
			// Удалим значения из options 
			$query = $this->db->placehold("DELETE o FROM __options o WHERE o.feature_id=?", $id);
			$this->db->query($query);
		}
	}
			

	public function get_options($filter = array())
	{
		$feature_id_filter = '';
		$product_id_filter = '';
		$category_id_filter = '';
		$visible_filter = '';
		$brand_id_filter = '';
		$features_filter = '';
		$in_filter_filter = '';

		if(empty($filter['feature_id']) && empty($filter['product_id']))
			return array();
		
		$group_by = '';
		if(isset($filter['feature_id']))
			$group_by = 'GROUP BY feature_id, value';
			
		if(isset($filter['feature_id']))
			$feature_id_filter = $this->db->placehold('AND po.feature_id in(?@)', (array)$filter['feature_id']);

		if(isset($filter['product_id']))
			$product_id_filter = $this->db->placehold('AND po.product_id in(?@)', (array)$filter['product_id']);

		if(isset($filter['category_id']))
			$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id=po.product_id AND pc.category_id in(?@)', (array)$filter['category_id']);

		if(isset($filter['visible']))
			$visible_filter = $this->db->placehold('INNER JOIN __products p ON p.id=po.product_id AND visible=?', intval($filter['visible']));

		if(isset($filter['brand_id']))
			$brand_id_filter = $this->db->placehold('AND po.product_id in(SELECT id FROM __products WHERE brand_id in(?@))', (array)$filter['brand_id']);

		if(isset($filter['on_main']))
			$in_filter_filter.= $this->db->placehold(' AND f.on_main=?', intval($filter['on_main']));

		if(isset($filter['on_prod']))
			$in_filter_filter.= $this->db->placehold(' AND f.on_prod=?', intval($filter['on_prod']));


		if(isset($filter['features']))
			foreach($filter['features'] as $feature=>$value)
			{
				$features_filter .= $this->db->placehold('AND (po.feature_id=? OR po.product_id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? )) ', $feature, $feature, $value);
			}
		
		$query = $this->db->placehold("SELECT po.product_id, po.feature_id, po.value, count(po.product_id) as count
						, f.on_prod, f.on_main, f.multiselect, f.in_variant, f.in_compare, f.isrange, f.slider, f.unit, f.istext, f.image 
		    FROM __options po LEFT JOIN __features f ON f.id=po.feature_id
		    $visible_filter
			$category_id_filter
			WHERE 1 $feature_id_filter $product_id_filter $brand_id_filter $features_filter $in_filter_filter GROUP BY po.feature_id, po.value ORDER BY value=0, -value DESC, value");

		$this->db->query($query);
		$res = $this->db->results();
		$all = array();
		foreach($res AS $k=>$re){
			if($re->isrange==1){
				$v = floatval(ereg_replace("[^-0-9\.]","",$re->value));
				$all[$re->feature_id][] = $v;
				$res[$k]->value = $v;
			}
		}
		foreach($res AS $k=>$re){
			if($re->isrange==1)
				if(sizeof($all[$re->feature_id]) > 0){
					$res[$k]->min = min($all[$re->feature_id]);
					$res[$k]->max = max($all[$re->feature_id]);
				}else{
					$res[$k]->min = 0;
					$res[$k]->max = 0;
				}
		}

		return $res;
	}
	
	public function get_product_options($product_id, $face = 0)
	{
		$and = '';
		if($face){
			$and =' AND f.on_prod = 1 ';
		}
		$query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.product_id
						, f.on_prod, f.on_main, f.multiselect, f.in_variant, f.in_compare, f.isrange, f.slider, f.unit, f.istext, f.image , f.nameselect
										FROM __options po LEFT JOIN __features f ON f.id=po.feature_id ".$and." 
										WHERE po.product_id in(?@) ORDER BY f.position", (array)$product_id);

		$this->db->query($query);
		$res = $this->db->results();
		foreach($res AS $k=>$re){
			if($re->isrange==1){
				$res[$k]->value = floatval(ereg_replace("[^-0-9\.]","",$re->value));
			}
		}

		return $res;
	}
	

	public function delete_image($id)
	{
		$query = $this->db->placehold("SELECT image FROM __features WHERE id=?", intval($id));
		$this->db->query($query);
		$filename = $this->db->result('image');
		if(!empty($filename))
		{
			$query = $this->db->placehold("UPDATE __features SET image=NULL WHERE id=?", $id);
			$this->db->query($query);
			$query = $this->db->placehold("SELECT count(*) as count FROM __features WHERE image=? LIMIT 1", $filename);
			$this->db->query($query);
			$count = $this->db->result('count');
			if($count == 0)
			{			
				@unlink($this->config->root_dir.$this->config->features_images_dir.$filename);		
			}
		}
	}

	public function delete_variant_options($product_id)
	{
		$query = $this->db->placehold("DELETE o FROM __variants_options o
			                            LEFT JOIN __variants va ON va.id = o.id_veriant
										WHERE va.product_id in(?@)", (array)$product_id);
		$this->db->query($query);
	}

	
	public function update_variant_option($id_veriant, $feature_id, $value)
	{	 
		if($value != '')
			$query = $this->db->placehold("REPLACE INTO __variants_options SET value=?, id_veriant=?, id_feature=?", $value, intval($id_veriant), intval($feature_id));
		else
			$query = $this->db->placehold("DELETE FROM __variants_options WHERE id_feature=? AND id_veriant=?", intval($feature_id), intval($id_veriant));
		return $this->db->query($query);
	}
	
	public function get_product_variant_options($product_id)
	{
		$query = $this->db->placehold("SELECT f.id as feature_id, f.name, po.value, po.id_veriant, f.nameselect FROM __features f LEFT JOIN __variants_options po ON f.id=po.id_feature LEFT JOIN __variants va ON va.id = po.id_veriant
										WHERE va.product_id in(?@) ORDER BY po.position, f.position ", (array)$product_id);

		$this->db->query($query);
		$res = $this->db->results();

		return $res;
	}
	
}
