<?php 
class ControllerWaitingReview 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');
		$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');
		$request  =& $this->locator->get('request');	
		$tax      =& $this->locator->get('tax');
		$image    =& $this->locator->get('image');
		$view = $this->locator->create('template');
		$view->set('title', 'Waiting for your review');		
		
    	if (!$customer->isLogged()) {
      		$session->set('redirect', $url->ssl('waiting_review'));
	     	$response->redirect($url->ssl('account_login'));
    	}    	
    	
    	if($request->has('page')){
		   $page=$request->get('page');
		}else{
			$page = 1;
		}    
    	
		$customer_id=$customer->getId();
		
	    if (($request->isPost())) {	    	
	    	 $sql = "insert into review set author = '?', country_name = '?', customer_id = '?', product_id = '?', content = '?', rating = '?',points= '?',product_size = '?',product_color = '?',product_material = '?',date_added=now()";
	      	 $database->query($database->parse($sql, $customer->getFullName(),$customer->getCountryName(),$customer_id,$request->get('product_id', 'post'),$request->get('product_review', 'post'),$request->get('rating', 'post'),5,$request->get('product_size', 'post'),$request->get('product_color', 'post'),$request->get('product_material', 'post')));	
	      	 $review_id = $database->getLastId();     		  
      		 $image_posted = $this->getUploadImages();   
  		  	                    
			 foreach ($image_posted as $f_image){				   	
			   $database->query("insert into review_image set review_id = $review_id, review_image_filename='".$f_image['name']."'");	
			   $database->query("update customer set current_points = (current_points +5) where customer_id = $customer_id");		  							 
		     }				      
							 	      		 
			 $database->query("update customer set current_points = (current_points +3) where customer_id = $customer_id");	
		  	 $response->redirect($url->ssl('waiting_review'));			
    	}
    	// collect waiting for reviews
    	$reviewed_products_rows=$database->getRows("select product_id from review where customer_id=$customer_id");       
    	           	
        foreach($reviewed_products_rows as $f_product){
          $reviewed_product_array[]=$f_product['product_id'];
        }
	    if(isset($reviewed_product_array)){
	    	$reviewed_product_set = implode(',', $reviewed_product_array);
	    	$sql="select op.itemcode, op.name, op.price, o.reference, o.date_added from `order_product` op left join `order` o on (op.order_id=o.order_id) where o.order_status_id=3 and o.customer_id=$customer_id and op.itemcode not in ($reviewed_product_set) group by op.itemcode order by op.order_id desc";	    	    	   
	    }else{
	    	$sql="select op.itemcode, op.name, op.price, o.reference, o.date_added from `order_product` op left join `order` o on (op.order_id=o.order_id) where o.order_status_id=3 and o.customer_id=$customer_id group by op.itemcode order by op.order_id desc";	    	
	    }	 
	     
		$waiting_review_rows=$database->getRows($database->splitQuery($sql, $page, 2));	
//	    var_dump($waiting_review_rows);exit; 	 
	    $review_product_data = array ();  
		foreach($waiting_review_rows as $key=>$f_waiting_review){
			$product_info=$database->getRow("select p.sold, i.filename from `product` p left join `image` i on (p.image_id=i.image_id) where p.product_id=".$f_waiting_review['itemcode']);
			$review_product_data[] = array(	
						   	    'product_href' => $url->ssl('product', FALSE, array('product_id' => $f_waiting_review['itemcode'])),  	            			
		                        'product_id'=>$f_waiting_review['itemcode'],
		                        'product_title'=>$f_waiting_review['name'],
		                        'product_price' => $f_waiting_review['price'],
		                        'reference'=>$f_waiting_review['reference'],	
		                        'date_added'=>$f_waiting_review['date_added'],		                        
		                        'thumb' => $image->resize($product_info['filename'], 270, 270),
		                        'sold'=>$product_info['sold'],
		                        'review_info'=>$database->getRow("select avg(rating) as avg,count(review_id) as count from `review` where product_id=".$f_waiting_review['itemcode'])               
		          			);			  
	    }		
      $view->set('waiting_review_products', $review_product_data);	
       
       $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('page', $page);	
  		$view->set('text_results', $language->get('text_results',$page, $database->getPages()));		
  		$view->set('action',  $url->href('waiting_review'));  				
  			
		$template->set('content', $view->fetch('content/waiting_review.tpl'));
		$template->set($module->fetchAccount());	
    	$response->set($template->fetch('layout.tpl')); 
	}

	function getUploadImages() { 
//		ini_set("display_errors", "On");
		date_default_timezone_set('Asia/Hong_Kong');
		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');
		$upload   =& $this->locator->get('upload');
		$image_module    =& $this->locator->get('image');
  
		$image_list = array();
		$image_list[0]='image_1';
		$image_list[1]='image_2';	
    	$image_list[2]='image_3';	
    	$image_list[3]='image_4';	
    	$image_list[4]='image_5';	
		$image_posted = array();
		$i=0;
		while($i<5)
		{
			if ($upload->has($image_list[$i]) )  {			
				if ( $upload->getName($image_list[$i])=='' )
				{
					$i = $i + 1;
					continue;
				}	    	
//var_dump($_FILES);
	    	$size1 = $_FILES[$image_list[$i]]['size']/1024;
	    	if($size1>500)
	    	{
	    	 echo "<script>alert('error, image size over 500KB');window.history.back(-1);</script>";
	    	 break;
	    	} 
	    	$option1 = getimagesize($_FILES[$image_list[$i]]['tmp_name']);  	
	    	if($option1[0]>1200)
	    	{
 			echo "<script>alert('error, image width over 1200 pixel');window.history.back(-1);</script>";
 			 break;
	    	}   	
				$image_name = '';
				$image_path = ''; 
				$int_rand=rand(1000,9999);
				$filename=explode('.',$upload->getName($image_list[$i]));				
 				$image_name = date('YmdHis',time()).rand(1000,9999).'.'.$filename[1];						
				$image_path = DIR_REVIEW_IMAGE.$image_name;				
				if (!$upload->save($image_list[$i], $image_path)) {
					$this->error['file'] = $language->get('error_upload');
					$i = $i + 1;
					continue;					
				}
				if ((strlen($upload->getName($image_list[$i])) < 1) || (strlen($upload->getName($image_list[$i])) > 128)) {
					$this->error['file'] = $language->get('error_filename');
					$i = $i + 1;
					continue;					
				}				
				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/gif', 
					'image/png',
					'image/x-png'
				);		  
				if (!in_array($upload->getType($image_list[$i]), $allowed)) {
					$this->error['file'] = $language->get('error_filetype');
					$i = $i + 1;
					continue;					
				}		  
				if ($upload->hasError($image_list[$i])) {
					$this->error['message'] = $upload->getError('image');
					$i = $i + 1;
					continue;
				}				
				if ( $request->has('image_title_'.$i,'post') )
				{
				$image_posted[] = array( 'id'=>$i,
										 'name' => $image_name,
				                         'path'=>$image_path,										 
										 'title'=>$request->get('image_title_'.$i,'post') );
				}else
				{
				$image_posted[] = array( 'id'=>$i,
										 'name' => $image_name,
				                         'path'=>$image_path  );				
				}
			}			
			$i = $i + 1;
    	}			
	  return $image_posted;
  	}
 
}
?>