<?php 
class ControllerList extends Controller {  
	function index() { 
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$module   =& $this->locator->get('module');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$tax      =& $this->locator->get('tax');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');		
		$cart     =& $this->locator->get('cart');	
		$language->load('controller/list.php');	
		$sort_by=$request->get('sort_by');
	    $category_id = (int)((!$request->get('path')) ? '0' : (int)end(explode('_', $request->get('path'))));
		$category_info = $database->getRow("select distinct name from category c left join category_description cd on (c.category_id = cd.category_id) where c.category_id = '" . $category_id . "' and cd.language_id = '" . (int)$language->getId() . "'");
	     $amount=$request->get('amount');
	   if ($request->isPost()) {
      		$cart->add($request->get('product_id', 'post'), $request->get('quantity','post'), $request->get('option', 'post')); 
      		$response->redirect($url->href('cart'));
    	}
		if ($category_info) {
		    if ($category_id!=0)
			{
				$database->query("update category set viewed = viewed + 1 where category_id='" . $category_id . "'");
			}		
	  		$template->set('title', $category_info['name']);
      		$view = $this->locator->create('template');
      		$breadcrumb = array();
      		$breadcrumb[] = array(
        		'href'      => $url->href(''),
        		'text'      => $language->get('text_home'),
        		'separator' => FALSE
      		);
      		foreach (explode('_', $request->get('path')) as $category_id) {
        		$result = $database->getRow("select cd.name, c.path from category c left join category_description cd on c.category_id = cd.category_id where c.category_id = '" . (int)$category_id . "' and c.status = 1 and cd.language_id = '" . (int)$language->getId() . "'");
        		$breadcrumb[] = array(
          			'href'      => $url->href('list', FALSE, array('path' => $result['path'])),
          			'text'      => $result['name'],
          			'separator' => '->'
        		);
      		} 

			if (($database->countRows("select product_id from product where status = 1 and category_id = '" . (int)end(explode('_', $request->get('path'))) . "'")) || ($database->countRows("select category_id from category where parent_id = '" . (int)end(explode('_', $request->get('path'))) . "'"))) {
        		$view->set('breadcrumbs', $breadcrumb);
        		$category_data = array();        		
				$results = $database->getRows("select c.category_id,cd.name,i.filename from category c left join category_description cd on (c.category_id = cd.category_id) left join image i on (c.image_id = i.image_id) where c.parent_id = '" . (int)(!$request->get('path') ? '0' : (int)end(explode('_', $request->get('path')))) . "' and c.status = 1 and  cd.language_id = '" . (int)$language->getId() . "' order by c.sort_order");		
        		foreach ($results as $result) {
          			$category_data[] = array(
            			'name'  => $result['name'],
            			'href'  => $url->href('list', FALSE, array('path' => ($request->get('path')) ? $request->get('path') . '_' . $result['category_id'] : $result['category_id'])),
            			'thumb' => $image->resize($result['filename'], $config->get('config_image_width'), $config->get('config_image_height'))
          			);
        		}

        		$view->set('categories', $category_data);				
				$product_data = array();     
				if($sort_by==1)
				{					
				    $results = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,shelf_on_time,image_id,category_id from product where category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and quantity>=0 and status = 1 order by sold desc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('sort.page')), $amount>0?$amount:$config->get('config_max_rows')));
				}
				elseif($sort_by==2)
				{					
				    $results = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,shelf_on_time,image_id,category_id from product where category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and quantity>=0 and status = 1 order by price asc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('sort.page')), $amount>0?$amount:$config->get('config_max_rows')));
				}
			    elseif($sort_by==3)
				{					
				    $results = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,shelf_on_time,image_id,category_id from product where category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and quantity>=0 and status = 1 order by price desc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('sort.page')), $amount>0?$amount:$config->get('config_max_rows')));
				}
				elseif($sort_by==4)
			    {
			    	$shelf_on_time=time()-86400*30;	
		        	$product_count = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,shelf_on_time,image_id,category_id from product where shelf_on_time>='".$shelf_on_time."' and  category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and quantity>=0 and status = 1 order by shelf_on_time desc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('sort.page')), $amount>0?$amount:$config->get('config_max_rows')));

			    	if(count($product_count)<1){
			        	$results = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,shelf_on_time,image_id,category_id from product where category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and quantity>=0 and status = 1 order by shelf_on_time desc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('sort.page')), $amount>0?$amount:$config->get('config_max_rows')));
			        }
			        else{
			        	$results=$product_count;
			        }
			    }	
				else 
				{
					$results = $database->getRows($database->splitQuery("select product_id,price,sold,tax_class_id,quantity,category_id,shelf_on_time,image_id from product where quantity>=0 and p.status = 1 and p2c.category_id = '" . (int)end(explode('_', $request->get('path'))) . "' order by shelf_on_time desc", ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('list.page')), $amount>0?$amount:$config->get('config_max_rows')));  
				}
				foreach ($results as $result) {
          			$query = array(
            			'path'       => $request->get('path'),
            			'product_id' => $result['product_id']
          			);
					$product_desc_info=$database->getRow("select pd.name from product_description pd where pd.product_id='".$result['product_id']."'");
				    $image_info=$database->getRow("select i.filename from image i where i.image_id='".$result['image_id']."'");   
					
						//reviews
					$reviews_resulte = $database->getRows("select rating,review_id,product_id from review where product_id =". $result['product_id']);
					$reviews_count = 0;
					$rating = 0;
					if($reviews_resulte){
						foreach ($reviews_resulte as $key=>$reviews){
							$reviews_count = $reviews_count+1;
							$rating = $rating+$reviews['rating'];
						}
					}
					//print($reviews_count);
          			$product_data[] = array(
            			'name'  => $product_desc_info['name'],
            			'reviews_count' => $reviews_count,
            			'reviews_rating' => $rating,
						'product_id' => $result['product_id'],
            			'href'  => $url->href('product', FALSE, $query),
            			'thumb' => $image->resize($image_info['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
            			'price' => $currency->format($tax->calculate($result['price'], $result['tax_class_id'], $config->get('config_tax'))),
            			'sold' =>  $result['sold'],
            			'quantity' =>  $result['quantity'],
            			'shelf_on_time'=>$result['shelf_on_time'],
            			'market_price' => $currency->format($tax->calculate($result['price']*1.4, $result['tax_class_id'], $config->get('config_tax')))
          			);
        		}
        		foreach ($product_data as $k=>$v){					
						$product_data[$k]['feedback']=$database->getRow("select sum(rating) as sum,avg(rating) as avg,count(feedback_id) as total from `feedback` where product_id='".$v['product_id']."'");
			    }	
        		$view->set('products', $product_data);
        		$view->set('heading_title', $category_info['name']);
        		$view->set('text_product', $language->get('text_product'));
        		if(($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('list.page'))==null)
				{
					$page = 1;
				}else{
					$page = ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('list.page'));
				}
        		$view->set('text_results', $database->getTotal());
	      		$view->set('entry_page', $language->get('entry_page'));      			
				$view->set('action', $url->href('list', 'page', array('path' => $request->get('path'),'sort_by'=>$request->get('sort_by'))));				
				// record last viewed category, it can be use to return back 
				$session->set('last_view_category',$url->href('list', 'page', array('path' => $request->get('path'))));			
				$view->set('page', ($request->has('path') ? $session->get('sort.' . $request->get('path') . '.page') : $session->get('list.page')));							
				$page_data = array();
      			for ($i = 1; $i <= $database->getPages(); $i++) {
        			$page_data[] = array(
          				'text'  => $language->get('text_pages', $i, $database->getPages()),
          				'value' => $i
        			);
      			}

      			$view->set('pages', $page_data);	
      			$view->set('sort_by',$request->get('sort_by'));	
      			$view->set('amount', $amount);
      			$view->set('view_controller','list');
      			$view->set('path', $request->get('path'));	
				$template->set('content', $view->fetch('content/list.tpl'));			
				$template->set($module->fetchPublic());
    			$response->set($template->fetch('layout.tpl')); 				
      		} else {
        		$template->set('title', $category_info['name']);
				$view = $this->locator->create('template');
        		$view->set('heading_title', $category_info['name']);
        		$view->set('text_error', $language->get('text_empty'));
        		$view->set('button_continue', $language->get('button_continue'));
        		$view->set('breadcrumbs', $breadcrumb);
        		$view->set('continue', $url->href(''));		
				$template->set('content', $view->fetch('content/error.tpl'));			
				$template->set($module->fetchPublic());
    			$response->set($template->fetch('layout.tpl')); 				
      		}
    	} else {
	  		$template->set('title', $language->get('text_error'));	
      		$view = $this->locator->create('template');
      		$view->set('heading_title', $language->get('text_error'));
      		$view->set('text_error', $language->get('text_error'));
      		$view->set('button_continue', $language->get('button_continue'));
      		$view->set('continue', $url->href(''));	  
	  		$template->set('content', $view->fetch('content/error.tpl'));    	
			$template->set($module->fetchPublic());
    		$response->set($template->fetch('layout.tpl')); 	
		}
  	}
	
	function page() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$url      =& $this->locator->get('url');	
		if ($request->has('page', 'post')) {
			$session->set(($request->has('path') ? 'sort.' . $request->get('path') . '.page' : 'list.page'), $request->get('page', 'post'));
		}
		$response->redirect($url->ssl('list', FALSE, array('path' => $request->get('path'),'sort_by'=>$request->get('sort_by'))));
	}
}
?>
