<?PHP

if(strpos($_SERVER['REQUEST_URI'], '?page=') !== false || isset($_GET['keyword'])){
    Header( "HTTP/1.1 301 Moved Permanently" );
    $url = $_GET['page'] != 1 ? 'page-' . $_GET['page'] . '/' : ''; 
    $u = explode('?', $_SERVER['REQUEST_URI']);
    Header( "Location: " . $u[0]. $url  );
    die;
}
/**
 * Simpla CMS
 *
 * @copyright 	2011 Denis Pikusov
 * @link 		http://simplacms.ru
 * @author 		Denis Pikusov
 *
 * Этот класс использует шаблон products.tpl
 *
 */

require_once('View.php');

class ProductsView extends View
{
 	/**
	 *
	 * Отображение списка товаров
	 *
	 */	
	 
	 public $perPageCustom = 25;
	 
	function fetch()
	{ 
		        // Категории товаров
		$this->design->assign('categories', $this->categories->get_categories_tree());
		
		require_once($_SERVER['DOCUMENT_ROOT'] . '/mobiledetect/Mobile_Detect.php');
        $detect = new Mobile_Detect;
        $this->design->assign('detect', $detect);

		// GET-Параметры
		$category_url = $this->request->get('category', 'string');
		$brand_url    = $this->request->get('brand', 'string');
		$order = $this->request->get('order', 'string');
		//echo '--' . $category_url . '--';die;
		$filter = array();
		$filter['visible'] = 1;
		$seobrand = 0;		
		if($brand_url && $category_url){
			$this->design->assign('rel_canonical', '/catalog/' . $category_url . '/');
		}
		// Если задан бренд, выберем его из базы
		if (!empty($brand_url))
		{
			$brand = $this->brands->get_brand((string)$brand_url);
			if (empty($brand))
				return false;
            
			$this->design->assign('brand', $brand);
			$seobrand = $brand;			
			$filter['brand_id'] = $brand->id;
            			
			$this->design->assign('meta_title', 'Товары для тюнинга '.$brand->name . ' в Санкт-Петербурге');
			$this->design->assign('meta_description', 'В продаже товары для тюнинга автомобилей '.$brand->name . ' - тюнинг центр Atomic Garage');
			$this->design->assign('meta_keywords', 'товары, '.$brand->name . ', тюнинг центр, авто, автомобиль, фары, оптика, санкт-петербург, продажа, установка, замена, ремонт');
			
		}
		// Если выбран бренд из фильтра
		if($brand = $this->request->get('b'))
			$filter['brand_id'] = $brand;
		
		// Выберем текущую категорию
		if (!empty($category_url))
		{
			$category = $this->categories->get_category((string)$category_url); //print_r($category);die;
			if (empty($category) || (!$category->visible && empty($_SESSION['admin']))) return false;
			
			//
				
			if($category->category_h1 == '' ){
				$category->category_h1 = $category->name;
			}
				
			$this->design->assign('category', $category); 
			$filter['category_id'] = $category->children;
			
			/*if(isset($_GET['page']) && $_GET['page'] && $category->id == 24){ 
 				header("HTTP/1.0 404 Not Found");
				header("Status: 404 Not Found");
				Header( "Location: /404/"  );
				die;
 			}*/
		}
		
		$filterForMinPrice = $filter;
		
		if($order == 'views') $filter['sort'] = $order;
		
		//print_r($filter);

		// Цена от ... до....
		$prices = array();
		
		$priceproducts = array();
		foreach($this->products->get_products($filter) as $p)
			$priceproducts[$p->id] = $p;
		$price_products_ids = array_keys($priceproducts);			
		//uuset($priceproducts);		
		$prices = (array)$this->variants->prices_range(array('product_id'=>$price_products_ids));		
		$prices['current_min_price'] = $this->request->get('min_price');
        $prices['current_max_price'] = $this->request->get('max_price');		
		if(!isset($prices['current_min_price']) && empty($prices['current_min_price']))
			$prices['current_min_price'] = $prices['min'];
		if(!isset($prices['current_max_price']) && empty($prices['current_max_price']))
			$prices['current_max_price'] = $prices['max'];				
		$this->design->assign('prices', $prices);
		$filter['min_price'] = $prices['current_min_price'];
        $filter['max_price'] = $prices['current_max_price'];


		// Если задано ключевое слово
		$keyword = $this->request->get('keyword');
		if (!empty($keyword))
		{
			$this->design->assign('keyword', $keyword);
			$filter['keyword'] = $keyword;
		}

		// Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта
		if($sort = $this->request->get('sort', 'string'))
			$_SESSION['sort'] = $sort;		
		if (!empty($_SESSION['sort']))
			$filter['sort'] = $_SESSION['sort'];			
		else
			$filter['sort'] = 'position';	
			
			if($order == 'views') $filter['sort'] = $order;
					
		$this->design->assign('sort', $filter['sort']);
		if($order) $this->design->assign('sort_order', $order);
		
		// Свойства товаров
		if(!empty($category))
		{
			$features = array();
			foreach($this->features->get_features(array('category_id'=>$category->id, 'in_filter'=>1)) as $feature)
			{ 
				$features[$feature->id] = $feature;
				if(($val = strval($this->request->get($feature->id)))!='')
					$filter['features'][$feature->id] = $val;	
			}
			
			$options_filter['visible'] = 1;
			
			$features_ids = array_keys($features);
			if(!empty($features_ids))
				$options_filter['feature_id'] = $features_ids;
			$options_filter['category_id'] = $category->children;
			if(isset($filter['features']))
				$options_filter['features'] = $filter['features'];
			if(!empty($brand))
				$options_filter['brand_id'] = $brand->id;
			
			$options = $this->features->get_options($options_filter);

			foreach($options as $option)
			{
				if(isset($features[$option->feature_id]))
					$features[$option->feature_id]->options[] = $option;
			}
			
			foreach($features as $i=>&$feature)
			{ 
				if(empty($feature->options))
					unset($features[$i]);
			}

			$this->design->assign('features', $features);
 		}

		// Постраничная навигация
		$items_per_page = $this->settings->products_num;		
		// Текущая страница в постраничном выводе
		$current_page = $this->request->get('page', 'int');	
		// Если не задана, то равна 1
		$current_page = max(1, $current_page);
		$this->design->assign('current_page_num', $current_page);
		// Вычисляем количество страниц
		$products_count = $this->products->count_products($filter);
		
		if($category->from_subs){
			$items_per_page = $this->perPageCustom;
			$products_count = count( $this->getFromSubCatecories($category->id, true) );
		}
		
		// Показать все страницы сразу
		if($this->request->get('page') == 'all')
			$items_per_page = $products_count;	
		
		$pages_num = ceil($products_count/$items_per_page);
		$this->design->assign('total_pages_num', $pages_num);
		//echo $pages_num;die;
		if($current_page > $pages_num){
		/*	header("HTTP/1.0 404 Not Found");
			header("Status: 404 Not Found");
			Header( "Location: /404/"  );
			die;*/
			
			 
			
			
			if($pages_num) $this->force404();
		}

		$filter['page'] = $current_page;
		$filter['limit'] = $items_per_page;
		
		///////////////////////////////////////////////
		// Постраничная навигация END
		///////////////////////////////////////////////


		$discount = 0;
		if(isset($_SESSION['user_id']) && $user = $this->users->get_user(intval($_SESSION['user_id'])))
			$discount = $user->discount;
			
		// Товары 
		$products = array();
		
		
		
		if($order == 'min_price' || $order == 'max_price'){
			
			$filter['nolimit'] = 1; 
		
			if($category->id == 246 || $category->id == 15) $products = $this->getFromSubCatecories($category->id);
			else foreach($this->products->get_products($filter) as $p) $products[$p->id] = $p;
			
			$products = $order == 'min_price' ? $this->sortByMinPrice($products, $filter) : $this->sortByMaxPrice($products, $filter);
			
		}else{
			
			foreach($this->products->get_products($filter) as $p) $products[$p->id] = $p;
			
			//if($category->id == 246 || $category->id == 15) $products = $this->getFromSubCatecories($category->id, true);
			if($category->from_subs) $products = $this->getFromSubCatecories($category->id);
			
		}	
			
		
		


		// Если искали товар и найден ровно один - перенаправляем на него
		if(!empty($keyword) && $products_count == 1)
			header('Location: '.$this->config->root_url.'/products/'.$p->url);
		
		
		
		if(!empty($products))
		{ 
			$products_ids = array_keys($products);
			foreach($products as &$product)
			{
				$product->variants = array();
				$product->images = array();
				$product->properties = array();
			}
	
			//$variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true));
			$variants = $this->variants->get_variants(array('product_id'=>$products_ids));
			foreach($variants as &$variant)
			{
				//$variant->price *= (100-$discount)/100;
				$products[$variant->product_id]->variants[] = $variant;
			}
	
			$images = $this->products->get_images(array('product_id'=>$products_ids));
			foreach($images as $image)
				$products[$image->product_id]->images[] = $image;
			foreach($products as &$product)
			{
				if(isset($product->variants[0]))
					$product->variant = $product->variants[0];
				if(isset($product->images[0]))
					$product->image = $product->images[0];
			}
				
								
	
			/*
			$properties = $this->features->get_options(array('product_id'=>$products_ids));
			foreach($properties as $property)
				$products[$property->product_id]->options[] = $property;
			*/

			$this->design->assign('products', $products);
 		}
 		
 		
 		$minPrice = $this->getMinPrice($filterForMinPrice);
		
		// Выбираем бренды, они нужны нам в шаблоне	
		if(!empty($category))
		{
			$brands = $this->brands->get_brands(array('category_id'=>$category->children));
			$category->brands = $brands;		
		}
		
		// Устанавливаем мета-теги в зависимости от запроса
		if($this->page && isset($this->page->meta_title))
		{ //print_r($this->page); die;
			$this->design->assign('meta_title', $this->page->meta_title);
			$this->design->assign('meta_keywords', $this->page->meta_keywords);
			$this->design->assign('meta_description', $this->page->meta_description);
		}
		elseif(isset($category))
		{
			$title = $category->meta_title;
			$desc = $category->meta_description;
			$keys = $category->meta_keywords;
			
			$lowerName = htmlspecialchars(mb_strtolower($category->name, 'utf-8'));
			
			//include $_SERVER['DOCUMENT_ROOT'].'/view/meta.php';  ////  автометы для разделов
			
			if(!$title) $title = '' . $category->name . ' в Санкт-Петербурге | Тюнинг центр Atomic Garage';
			
			if(!$desc && $minPrice != 0) $desc = $category->name . ' - купить в Санкт-Петербурге по цене от '. number_format($minPrice, 0, '', ' ') .' руб. | Низкие цены, большой выбор, доставка по всей России - Интернет-магазин товаров для автомобиля Atomic Garage, +79219589100, +79219589200.';
			if(!$desc && $minPrice == 0) $desc = $category->name . ' - купить в Санкт-Петербурге | Низкие цены, большой выбор, доставка по всей России - Интернет-магазин товаров для автомобиля Atomic Garage, +79219589100, +79219589200.';
			
			if(!$keys) $keys =  $lowerName . ', купить, для автомобиля, авто, санкт-петербург, россия, доставка, цена, установка, тюнинг центр, линзы, оптика, фары, фонари, птф';
			
			$spage = '';
			//if(isset($current_page) && $current_page > 1){
				//$spage = ' страница № '.$current_page;
			//}
			$this->design->assign('meta_title', $title.$spage);
			$this->design->assign('meta_keywords', $keys.$spage);
			$this->design->assign('meta_description', $desc.$spage);
		}
		elseif(isset($brand))
		{
			$this->design->assign('meta_title', $brand->meta_title);
			$this->design->assign('meta_keywords', $brand->meta_keywords);
			$this->design->assign('meta_description', $brand->meta_description);
		}
		elseif(isset($keyword))
		{ 
			$this->design->assign('meta_title', $keyword);
		}
	//	echo '<!--'; print_r ((int)isset($keyword)); echo '-->';
//	echo '<!--'; var_dump ($seobrand); echo '-->';
		if(!$this->page && !isset($category) && !isset($brand) && !isset($keyword) && !$seobrand){ //echo '<!--'; var_dump (isset($keyword)); echo '-->';
			$this->design->assign('meta_title', 'Все товары для тюнинга авто');
			$this->design->assign('meta_keywords', 'все товары, автомобиль, авто, тюнинг центр, atomic garage');
			$this->design->assign('meta_description', 'Товары для тюнинга автомобильной оптики в тюнинг центре Atomic Garage в Санкт-Петербурге');
		}
		
	/*	if($_SESSION['admin']){
			var_dump($category->path[2]->id);
		} */
		///var_dump($products);
			
		$this->body = $this->design->fetch('products.tpl');
		return $this->body;
	}
	
	function getMinPrice($filter){
		$filter['sort'] = 'price';
		$filter['limit'] = 1;
		$products = $this->products->get_products($filter);
		if(empty($products[0])) return 0;
		$minPrice = 0;
		
		$variants = $this->variants->get_variants(array('product_id'=>$products[0]->id));
		foreach($variants as $row){
			if($minPrice == 0 || $minPrice > $row->price) $minPrice = $row->price;
		}
		return $minPrice;
	}
	
	
	function sortByMinPrice($products, $filter){
		$products = $this->setMinMaxPrices($products);

		usort($products, '_usort_ByMinPrice');
		
		return $this->setSortPagination($products, $filter);
	}
	
	function sortByMaxPrice($products, $filter){
		$products = $this->setMinMaxPrices($products);

		usort($products, '_usort_ByMaxPrice');
		
		return $this->setSortPagination($products, $filter);
	}
	
	function setSortPagination($_products, $filter = array()){
		$products = array();
		foreach($_products as $row) $products[$row->id] = $row;
		$count = count($products);
		$onPage = !empty($filter['limit']) ? $filter['limit'] : 50;
		$this->design->assign('total_pages_num', ceil($count / $onPage) );
		$start = isset($_GET['page']) ? ($_GET['page'] - 1) * $onPage : 0;
		$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
		$this->design->assign('current_page_num', $page );
		$products = array_slice($products, $start, $onPage, true);
		return $products;
	}
	
	function setMinMaxPrices($products){
		$products_ids = array_keys($products);
		$variants = $this->variants->get_variants(array('product_id'=>$products_ids));

		foreach($products as &$row){
			$row->minPrice = $row->maxPrice = 0;
			foreach($variants as $var){
				if($var->product_id != $row->id) continue;
				if($var->price != 0 && ( $var->price < $row->minPrice || $row->minPrice == 0) ) $row->minPrice = $var->price;
				if($var->price != 0 && $var->price > $row->maxPrice) $row->maxPrice = $var->price;
			}
		}
		return $products;
	} 
	
	
	function getFromSubCatecories($cid, $returnAll = false){
		$all = $this->getSubCategories($cid);
		$res = mysql_query("SELECT * FROM `s_products_categories` WHERE `category_id` IN(".implode(',', $all).") ");
		$ids = $products = array();
		while($row = mysql_fetch_assoc($res)) $ids[] = $row['product_id'];
		$res = mysql_query("SELECT * FROM `s_products` WHERE `id` IN(".implode(',', $ids).") AND `visible`=1 ORDER BY `position`");
		while($row = mysql_fetch_assoc($res)) $products[$row['id']] = (object)$row; 
		if($returnAll) return $products;
		$count = count($products);
		$onPage = $this->perPageCustom;
		$this->design->assign('total_pages_num', ceil($count / $onPage) );
		$start = isset($_GET['page']) ? ($_GET['page'] - 1) * $onPage : 0;
		$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
		$this->design->assign('current_page_num', $page );
		$products = array_slice($products, $start, $onPage, true);
		return $products;
	}
	
	function getSubCategories($parent_id, $all = array()){
		$res = mysql_query("SELECT * FROM `s_categories` WHERE `parent_id`='$parent_id' AND `visible`=1");
		if(!mysql_num_rows($res)) return $all;
		while($row = mysql_fetch_assoc($res)){
			$all[] = $row['id'];
			$all = $this->getSubCategories($row['id'], $all);
		}
		return $all;
	}

}

function _usort_ByMinPrice($a, $b){
	if($a->minPrice == $b->minPrice)return 0;
	return ($a->minPrice > $b->minPrice) ? 1 : -1;
}

function _usort_ByMaxPrice($a, $b){
	if($a->minPrice == $b->minPrice)return 0;
	return ($a->minPrice > $b->minPrice) ? -1 : 1;
}

