<?php 
class ControllerGallery 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');			
		$language->load('controller/gallery.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() . "'");
	
		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('sort', FALSE, array('path' => $result['path'])),
          			'text'      => $result['name'],
          			'separator' => '->'
        		);
      		} 

			if (($database->countRows("select * from product where status = 1 and category_id = '" . (int)end(explode('_', $request->get('path'))) . "'")) || ($database->countRows("select * from category where parent_id = '" . (int)end(explode('_', $request->get('path'))) . "'"))) {
        		$view->set('breadcrumbs', $breadcrumb);
        		$category_data = array();        		
				$results = $database->getRows("select * 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('sort', 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 p.*,pd.*,i.* 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.quantity>=0 and p.status = 1 and p.category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and p.date_available < now() and p.status = '1' order by p.sold desc", ($request->has('path') ? $session->get('gallery.' . $request->get('path') . '.page') : $session->get('gallery.page')), $config->get('config_max_rows')));
				}
				if($sort_by==2)
				{
					$results = $database->getRows($database->splitQuery("select p.*,pd.*,i.*  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.quantity>=0 and p.status = 1 and p.category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and p.date_available < now() and p.status = '1' order by p.price asc", ($request->has('path') ? $session->get('gallery.' . $request->get('path') . '.page') : $session->get('gallery.page')), $config->get('config_max_rows')));
				}
			    if($sort_by==3)
				{
					$results = $database->getRows($database->splitQuery("select p.*,pd.*,i.*  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.quantity>=0 and p.status = 1 and p.category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and p.date_available < now() and p.status = '1' order by p.price desc", ($request->has('path') ? $session->get('gallery.' . $request->get('path') . '.page') : $session->get('gallery.page')), $config->get('config_max_rows')));
				}
				else 
				{
					$results = $database->getRows($database->splitQuery("select p.*,pd.*,i.*  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.quantity>=0 and p.status = 1 and p.category_id = '" . (int)end(explode('_', $request->get('path'))) . "' and p.date_available < now() and p.status = '1' order by p.product_id desc", ($request->has('path') ? $session->get('gallery.' . $request->get('path') . '.page') : $session->get('gallery.page')), $config->get('config_max_rows')));
				}
				foreach ($results as $result) {
          			$query = array(
            			'path'       => $request->get('path'),
            			'product_id' => $result['product_id']
          			);

					$prefix_product_name = $result['name'];				
					
					//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'  => $prefix_product_name,
            			'reviews_count' => $reviews_count,
            			'reviews_rating' => $rating,
						'product_id' => $result['product_id'],
            			'href'  => $url->href('product', FALSE, $query),
            			'thumb' => CDN_IMAGE.$result['filename'],
            			'price' => $currency->format($tax->calculate($result['price'], $result['tax_class_id'], $config->get('config_tax'))),
            			'sold' =>  $result['sold'],
            			'quantity' =>  $result['quantity'],
            			'market_price' => $currency->format($tax->calculate($result['price']*1.4, $result['tax_class_id'], $config->get('config_tax')))
          			);
        		}
        		$view->set('products', $product_data);
        		$view->set('heading_title', $category_info['name']);
        		$view->set('text_product', $language->get('text_product'));
        		$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));
	      		$view->set('entry_page', $language->get('entry_page'));      			
				$view->set('action', $url->href('gallery', '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('sort', 'page', array('path' => $request->get('path'))));				
				$view->set('page', ($request->has('path') ? $session->get('gallery.' . $request->get('path') . '.page') : $session->get('gallery.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('path', $request->get('path'));	
				$template->set('content', $view->fetch('content/gallery.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') ? 'gallery.' . $request->get('path') . '.page' : 'gallery.page'), $request->get('page', 'post'));
		}
		$response->redirect($url->ssl('gallery', FALSE, array('path' => $request->get('path'),'sort_by'=>$request->get('sort_by'))));
	}
}
?>
