<?php 
class ControllerSearch extends Controller { 
	function index() { 
		$config   =& $this->locator->get('config');
		$currency =& $this->locator->get('currency');
		$customer =& $this->locator->get('customer');
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$image    =& $this->locator->get('image');
		$module   =& $this->locator->get('module');
		$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');	
	    $request  =& $this->locator->get('request');	
		if ($request->has('search', 'get')) {
			$session->set('search.search', $request->get('search', 'get'));
	  	}
	
    	$language->load('controller/search.php');
		$template->set('title', $language->get('heading_title'));
    	$view = $this->locator->create('template');
    	$view->set('heading_title', $language->get('heading_title'));
    	$view->set('text_critea', $language->get('text_critea'));
    	$view->set('text_search', $language->get('text_search'));
		$view->set('text_keywords', $language->get('text_keywords'));
		$view->set('text_error', $language->get('text_error'));
		$view->set('entry_search', $language->get('entry_search'));
    	$view->set('entry_description', $language->get('entry_description'));
    	$view->set('entry_page', $language->get('entry_page'));
    	$view->set('button_search', $language->get('button_search'));
    	$view->set('action', $url->href('search', 'page'));
		$view->set('search', $session->get('search.search'));
		$view->set('description', $session->get('search.description'));
		if ($session->get('search.search')) {
      		if(!$session->get('search.description')) {
      			$page=$session->get('search.page');
        		$sql = "select pd.product_id,pd.name from product_description pd where pd.language_id = '?' and pd.name like '?'";      		
$results = $database->getRows($database->splitQuery($database->parse($sql, $language->getId(), '%' . trim($session->get('search.search')) . '%'), $page, $config->get('config_max_rows')));
            if(!$results) {
                 $sql = "select pt.product_id,pt.tags as name from product_to_tags pt where pt.tags like '?'";   
                 $results = $database->getRows($database->splitQuery($database->parse($sql, trim($session->get('search.search')) . '%'), $page, $config->get('config_max_rows'))); 
              }
				foreach($results as $k=>$v){
      		    	$product_info=$database->getRow("select p.price,p.image_id,p.sold,p.quantity,p.tax_class_id,p.status from product p where p.product_id='".$v['product_id']."'");
      		    	$product_image=$database->getRow("select i.filename from image i where i.image_id='".$product_info['image_id']."'");
      		    	$results[$k]=array(
      		    	  'product_id'=>$v['product_id'],
      		    	  'name'=>$v['name'],
      		    	  'price'=>$product_info['price'],
      		    	  'sold'=>$product_info['sold'],
      		    	  'quantity'=>$product_info['quantity'],
      		    	  'status'=>$product_info['status'],
      		    	  'tax_class_id'=>$product_info['tax_class_id'],
      		    	  'image_id'=>$product_info['image_id'],
      		    	  'filename'=>$product_image['filename'],
      		    	);
      		    }
      		} else { 
      			$sql = "select pd.product_id,pd.name from product_description pd where pd.language_id = '?' and pd.name like '?' or pd.description like '?'";      		
				$results = $database->getRows($database->splitQuery($database->parse($sql, $language->getId(), '%' . trim($session->get('search.search')) . '%', '%' . trim($session->get('search.search')) . '%'), $session->get('search.page'), $config->get('config_max_rows')));
      		    foreach($results as $k=>$v){
      		    	$product_info=$database->getRow("select p.price,p.image_id,p.sold,p.quantity,p.tax_class_id,p.status from product p where p.product_id='".$v['product_id']."'");
      		    	$product_image=$database->getRow("select i.filename from image i where i.image_id='".$product_info['image_id']."'");
      		    	$results[$k]=array(
      		    	  'product_id'=>$v['product_id'],
      		    	  'name'=>$v['name'],
      		    	  'price'=>$product_info['price'],
      		    	  'sold'=>$product_info['sold'],
      		    	  'quantity'=>$product_info['quantity'],
      		    	   'status'=>$product_info['status'],
      		    	  'tax_class_id'=>$product_info['tax_class_id'],
      		    	  'image_id'=>$product_info['image_id'],
      		    	  'filename'=>$product_image['filename'],
      		    	);
      		    }
        		
      		    
      		}
			$product_data = array();
			$quantity = 0;
			// search item code
			if(is_numeric(trim($session->get('search.search'))))
			{
				
				$item_code =trim($session->get('search.search'));
				
				if(strlen($item_code)>=8){
					$item_results = $database->getRows("select p.product_id,p.price,p.sold,p.quantity,p.tax_class_id,p.image_id,p.status from product p where p.sku='".$item_code."'");
					
				}else{
					$item_results = $database->getRows("select p.product_id,p.price,p.sold,p.quantity,p.tax_class_id,p.image_id,p.status from product p where p.product_id='".$item_code."'");
					
				}
				if ($item_results)
				{       
						foreach ($item_results as $item_result) {	
							
					    $product_desc=$database->getRow("select pd.name from product_description pd where pd.product_id='".$item_result['product_id']."'");
					    $image_info=$database->getRow("select i.filename from image i where i.image_id='".$item_result['image_id']."'");
						$product_data[] = array(	
							'name'  => $product_desc['name'],
							'product_id'=>$item_result['product_id'],	
							'quantity'  => $item_result['quantity'],	
							'status'=>$item_result['status'],
							'href'  => $url->href('product', FALSE, array('product_id' => $item_result['product_id'])),
							'thumb' => $image->resize($image_info['filename'], $config->get('config_image_width'), $config->get('config_image_height')),	
							'price' => $currency->format($tax->calculate($item_result['price'], $item_result['tax_class_id'])),													
	                        'market_price' => $currency->format($tax->calculate($item_result['price']*1.4, $item_result['tax_class_id'])),
	                        'sold' => $item_result['sold']
						);	
						};				
				}
			}else
			{
				// count search times
				$keyword = explode(' ', $session->get('search.search'));
				$database->query("update search_keyword set hot=hot+1 where keyword='".$keyword[0]."'");
				$search_query = $database->countAffected();
				if ($search_query<=0)
				{
					$database->query("INSERT INTO search_keyword (`keyword` ,`hot` )VALUES ('".$keyword[0]."','1')");
				}
			}
				
			if ($results) {
				$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));
        		foreach ($results as $result) {
          			$product_data[] = array(
            			'name'  => $result['name'],
            			'product_id'=>$result['product_id'],
            			'quantity'  => $result['quantity'],
            			'status'=>$result['status'],
            			'href'  => $url->href('product', FALSE, array('product_id' => $result['product_id'])),
            			'thumb' => $image->resize($result['filename'], $config->get('config_image_width'), $config->get('config_image_height')),
            			'price' => $currency->format($tax->calculate($result['price'], $result['tax_class_id'])),
            			'market_price' =>$currency->format($tax->calculate($result['price']*1.4, $result['tax_class_id'])),
            			'sold' => $result['sold']
            			
          			);
        		}
        	    foreach ($product_data as $k=>$v){					
						$product_data[$k]['review']=$database->getRow("select sum(rating) as sum,avg(rating) as avg,count(review_id) as total from `review` where product_id='".$v['product_id']."'");
			    }	
       			$view->set('products', $product_data);
 		       	$view->set('page', $session->get('search.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);
			}else
			{			
				if (count($product_data)>0)
				{   
					 foreach ($product_data as $k=>$v){					
						$product_data[$k]['review']=$database->getRow("select sum(rating) as sum,avg(rating) as avg,count(review_id) as total from `review` where product_id='".$v['product_id']."'");
			         }
				    $view->set('text_results', '1-1 results');
					$view->set('products', $product_data);
					$view->set('page', 1);
        			$page_data = array();
					$view->set('pages', $page_data);				
				}
			}
		}
		
		$template->set('content', $view->fetch('content/search.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('search', 'post')) {
			$session->set('search.search', $request->get('search', 'post'));
	  	} 
		if ($request->has('description', 'post')) {
			$session->set('search.description', $request->get('description', 'post'));
	  	} else {
			$session->delete('search.description');
		}
      	if (($request->has('page', 'post')) || ($request->has('search', 'post'))) {
        	$session->set('search.page', $request->get('page', 'post'));
      	}	
		$response->redirect($url->ssl('search'));
	}
}
?>