<?php 
class ControllerTopSellers extends Controller { 

	function index() {
		$config   = $this->locator->get('config');
		$customer =& $this->locator->get('customer');      
		$language =& $this->locator->get('language');
		$module   =& $this->locator->get('module');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$template =& $this->locator->get('template');
		$url      =& $this->locator->get('url');
		$currency =& $this->locator->get('currency');
		$database =& $this->locator->get('database');	
		$image    = $this->locator->get('image');
		$request   =& $this->locator->get('request');
		
    	$view = $this->locator->create('template');
    	$view->set('heading_title', "Top Sellers"); 
			 	  	 
		if($request->has('page')){
		  	$session->set('top_sellers.page', $request->get('page'));
		} 
        $page =$session->get('top_sellers.page');
        $page=($page==NULL)?1:$page;		 	  
	     
	     $sql = "SELECT p.product_id, p.price, p.sold, i.filename, pd.name FROM `product` p LEFT JOIN `product_description` pd ON (p.product_id=pd.product_id) LEFT JOIN `image` i on (p.image_id=i.image_id) WHERE p.sold>1";	 
//		$product_count=$database->countRows($sql);
	     $exe_sql = $database->splitQuery($sql, $page, 20); // $config->get('config_max_rows')

	     $hot_product_rows = $database->getRows($exe_sql);	 
	     
	     $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);  			      

	     $hot_product_array2 = array ();	
	     
	     foreach($hot_product_rows as $key=>$f_product){
	     	$hot_product_array2 [] = array(
	     		'product_id' => $f_product['product_id'],
					'href'  =>  $url->ssl('product', FALSE, array('product_id' => $f_product['product_id'])),
					'title' => $f_product['name'],
					'thumb' => $image->resize($f_product['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
					'price' => $currency->format($f_product['price']), 
					'market_price' => $currency->format(1.7*$f_product['price']),	
					'sold' => $f_product['sold'].(($f_product['sold']<2)?' PC' : ' PCS'),
					'review_info'=>$database->getRow("select avg(rating) as avg, count(review_id) as count from `review` where product_id=".$f_product['product_id']),
					);
	     }

	     $view->set('top_sellers_array2', $hot_product_array2);				
		 $view->set('page', $page);	
		 $view->set('text_results', $language->get('text_results',$page, $database->getPages()));		
		 $view->set('action', $url->href('top_sellers'));	
  		 $template->set('content', $view->fetch('content/top_sellers.tpl'));    	
		 $template->set($module->fetchPublic());
		 $response->set($template->fetch('layout.tpl')); 
  	      }
	}
?>