<?php

class ControllerProduct extends Controller
{
    public $data = array();

    public function index()
    {
        $cart = &$this->locator->get('cart');
        $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');
        $session = &$this->locator->get('session');
        $response = &$this->locator->get('response');
        $shipping = &$this->locator->get('shipping');
        $tax = &$this->locator->get('tax');
        $template = &$this->locator->get('template');
        $view = $this->locator->create('template');
        $url = &$this->locator->get('url');
        $customer = &$this->locator->get('customer');
        $language->load('controller/product.php');

        date_default_timezone_set('Asia/Hong_Kong');

        $product_id = isset($_REQUEST['product_id']) ? $_REQUEST['product_id'] : 0;

        $product_info = $database->getRow("select product_id,price,quantity,sold,shipping,weight,date_added,tax_class_id,viewed,uploader,model,vedio,sku,image_id,status from product p where product_id = $product_id");
        if (!$product_info) {
            $view->set('heading_title', $language->get('title_error'));
            $view->set('text_error', $language->get('text_error'));
            $view->set('button_continue', $language->get('button_continue'));
            $view->set('continue', $url->href(''));
            $template->set($module->fetchPublic());
            $template->set('content', $view->fetch('content/error.tpl'));

            return $response->set($template->fetch('layout.tpl'));
        }
        $cart_total = $cart->getTotal();
        $review_total = $database->countRows("select * from review where product_id=$product_id");
        $view->set('review_total', $review_total);
        $question_total = $database->countRows("select * from question where product_id=$product_id");
        $view->set('question_total', $question_total);

        $product_desc = $database->getRow("select name,description from product_description where product_id = $product_id");
        $product_image = $database->getRow('select image_id,filename from image where image_id='.$product_info['image_id']);
        $product_info['name'] = $product_desc['name'];
        $product_info['description'] = $product_desc['description'];
        $product_info['image_id'] = $product_image['image_id'];
        $product_info['filename'] = $product_image['filename'];

        $query = array(
            'path' => $request->get('path'),
            'product_id' => $request->get('product_id'),
        );

        $view->set('action', $url->href('product', false, $query));
        $view->set('product_name', $product_info['name']);
        $view->set('product_id', $product_id);
        $view->set('price', $currency->format($tax->calculate($product_info['price'], $product_info['tax_class_id'], $config->get('config_tax'))));
        $view->set('market_price', $currency->format($tax->calculate($product_info['price'] * 1.6, $product_info['tax_class_id'], $config->get('config_tax'))));
        $view->set('sold', $product_info['sold']);
        $view->set('date_added', $product_info['date_added']);
        $view->set('quantity', $product_info['quantity']);
        $view->set('status', $product_info['status']);
        $view->set('weight', $product_info['weight']);      
        $view->set('first_image', $product_info['filename']);
        $view->set('weight', $product_info['weight']);
        $view->set('model', $product_info['model']);
        $view->set('sku', $product_info['sku']);
        $view->set('vedio', $product_info['vedio']);
        $view->set('description', $product_info['description']);
        $view->set('href_addtowishlist', $url->ssl('my_wishlist', 'addtowishlist', array ('product_id'=>$product_id)) );
        $view->set('customer_logged', $customer->isLogged());

        $discount_info = $database->getRows("select product_discount_id,discount,quantity from product_to_discount where product_id = $product_id");
        $discounts = array();
        foreach ($discount_info as $discount) {
            $discounts[] = array(
                     'piece' => $discount['quantity'],
                     'discount' => $currency->format($tax->calculate($discount['discount'], $product_info['tax_class_id'], $config->get('config_tax'))),
                     );
        }
        $view->set('discounts', $discounts);

        $options = array();
        $results = $database->getRows("select product_to_option_id,product_id,option_id,option_value_id,price,prefix,sort_order from product_to_option where product_id = $product_id order by sort_order");
        foreach ($results as $result) {
            $options[$result['option_id']][] = array(
                  'product_to_option_id' => $result['product_to_option_id'],
                  'option_value_id' => $result['option_value_id'],
                  'price' => $result['price'],
                  'prefix' => $result['prefix'],
            );
        }

        $option_data = array();
        foreach ($options as $key => $values) {
            $option_value_data = array();
            foreach ($values as $value) {
                $option_value_info = $database->getRow("select option_value_id,option_id,name from option_value where option_value_id = '".(int) $value['option_value_id']."' and option_id = '".(int) $key."' and language_id = '".(int) $language->getId()."'");
                $option_value_data[] = array(
                    'product_to_option_id' => $value['product_to_option_id'],
                    'option_value_id' => $value['option_value_id'],
                    'name' => $option_value_info['name'],
                    'price' => (($value['price'] != '0.00') ? $currency->format($tax->calculate($value['price'], $product_info['tax_class_id'], $config->get('config_tax'))) : null),
                    'prefix' => $value['prefix'],
                  );
            }

            $option = $database->getRow("select option_id,name from `option` where option_id = $key");
            $option_data[] = array(
                  'option_id' => $key,
                  'name' => $option['name'],
                  'value' => $option_value_data,
            );
        }
        $view->set('options', $option_data);

        $popup_images = array(); $thumb_images = array(); $desc_images = array();
        $results = $database->getRows("select pti.image_id, i.filename from `product_to_image` pti left join `image` i on (pti.image_id=i.image_id) where pti.product_id = $product_id ORDER BY pti.`image_id` ASC");
        foreach ($results as $key=>$result) {
           
            $popup_images[] =  $image->resize($result['filename'], 360, 400);
            $thumb_images[] =  $image->resize($result['filename'], 100, 100);
            if( ((count($results))==1) || ($key>0) ) {
            	$desc_images[] = CDN_IMAGE.$result['filename']; 
            }           
           
        }
//		print_r($popup_images); print_r($thumb_images); print_r($desc_images); exit;
        $view->set('popup_images', $popup_images);
        $view->set('thumb_images', $thumb_images);
        $view->set('desc_images', $desc_images);          

		$view->set($module->fetchTemplate('question'));
        $view->set($module->fetchTemplate('review'));

        $template->set('content', $view->fetch('content/product.tpl'));
        $template->set($module->fetchPublic());

        $response->set($template->fetch('layout.tpl'));
    }

    public function ajax_addtocart()
    {
        $response  =& $this->locator->get('response');
        $request = &$this->locator->get('request');
        $currency =& $this->locator->get('currency');

        $product_id = $request->get('product_id');
        $quantity = $request->get('quantity');
        $options = $request->get('options');
        $option_pieces = explode('.', $options);

        $cart = &$this->locator->get('cart');
        $cart->add($product_id, $quantity, $option_pieces);
      
        $json['cart_count']	= $cart->countProducts();
        $json['cart_total']	= $currency->format($cart->getTotal()); 
        $response->set(json_encode($json));

    }

    public function ajax_addtowishlist()
    {
    	date_default_timezone_set('Asia/Hong_Kong');
    	
        $database =& $this->locator->get('database');
        $response  =&$this->locator->get('response');
        $request = &$this->locator->get('request');
        $customer = &$this->locator->get('customer');

        $customer_id  = $customer->getId();
        $product_id = $request->get('product_id');
        $options = $request->get('options');
        if (!empty($options)) {
            $key = $product_id . ':' . $options;
        } else {
            $key = $product_id;
        }          

        $wishlist_row= $database->query("insert into wishlist set product_id = '$key', customer_id = $customer_id, date_added = now()");     
        $json['wishlist_count']	= $database->countRows("select wishlist_id from wishlist where customer_id = $customer_id");
        $response->set(json_encode($json));
    }

    public function ajax_addquestion()
    {
        ob_clean();
        ob_end_flush();
        //   echo "<script>alert('HTTP_REFERER=".$_SERVER['HTTP_REFERER']."');</script>";
        $currency = &$this->locator->get('currency');
        $customer = &$this->locator->get('customer');
        $database = &$this->locator->get('database');
        $module = &$this->locator->get('module');
        $request = &$this->locator->get('request');
        $response = &$this->locator->get('response');
        $url = &$this->locator->get('url');

        $args = array(
            'product_id' => $request->get('product_id'),
            'author' => trim($request->get('question_author', 'POST')),
            'email' => trim($request->get('question_email', 'POST')),
            'question' => strip_tags($request->get('question_content', 'POST')),
            );

        if (!$request->get('product_id') || !$request->get('question_author', 'POST') || !$request->get('question_email', 'POST') || !$request->get('question_content', 'POST')) {
            echo "<script>alert('Question update failed, args are empty!');</script>";
            exit;
        }
        $sql = "insert into question set product_id = '?', author = '?', email = '?', text = '?', date_added = now()";
        $database->query($database->parse($sql, $args['product_id'], $args['author'], $args['email'], $args['question']));
        $g_show['data'] = $args;
        $html = '<li class="question question-element clearfix">
                    <div class="pr-qa">
                        <b class="pr-question_nr">Q</b>
                          <div class="pr-question_title">'.$args['question'].'</div>
                          <div class="pr-question_author">
                            <span class="pr-question_author_name">'.$args['author'].'</span>
                          <i class="pr-question_author_date">'.date('M d, Y', time()).'</i>
                          </div>
                      </div>
                  </li>';
        echo $html;
        exit;
    }

    public function ajax_reviews_list()
    {
        $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');
        $session  =& $this->locator->get('session');
        $response =& $this->locator->get('response');
        $shipping =& $this->locator->get('shipping');
        $tax      =& $this->locator->get('tax');
        $url      =& $this->locator->get('url');
        $customer =& $this->locator->get('customer');
        $template = $this->locator->create('template');
        $product_id = (int) $request->get('product_id');
        $page =$request->has('p', 'get')?$request->get('p', 'get'):1;
        $product_reviews = $database->getRows($database->splitQuery("select * from `review` where product_id=$product_id order by date_added desc", $page, 10));

        foreach ($product_reviews as $k=>$review) {
            switch ($review['product_size']) {
                case 1:
                    {
                        $product_reviews[$k]['product_size']=$review['product_size']*16; break;
                    }
                case 2:
                    {
                        $product_reviews[$k]['product_size']=$review['product_size']*25; break;
                    }
                case 3:
                    {
                        $product_reviews[$k]['product_size']=$review['product_size']*28.5; break;
                    }
                default:
                    {
                        break;
                    }
            }
            switch ($review['product_color']) {
                case 1:
                    {
                        $product_reviews[$k]['product_color']=$review['product_color']*16; break;
                    }
                case 2:
                    {
                        $product_reviews[$k]['product_color']=$review['product_color']*25; break;
                    }
                case 3:
                    {
                        $product_reviews[$k]['product_color']=$review['product_color']*28.5; break;
                    }
                default:
                    {
                        break;
                    }
            }
            switch ($review['product_material']) {
                case 1:
                    {
                        $product_reviews[$k]['product_material']=$review['product_material']*16; break;
                    }
                case 2:
                    {
                        $product_reviews[$k]['product_material']=$review['product_material']*25; break;
                    }
                case 3:
                    {
                        $product_reviews[$k]['product_material']=$review['product_material']*28.5; break;
                    }
                default:
                    {
                        break;
                    }
           }
           $product_reviews[$k]['images']=$database->getRows("select review_image_filename from `review_image` where review_id=".$review['review_id']);
           foreach ($product_reviews[$k]['images'] as $i=>$f_review_image) {
            $product_reviews[$k]['images'][$i]=CDN_REVIEW_IMAGE.$f_review_image['review_image_filename'];
           }
           $country_info=$database->getRow("select country_id,name,icon from country where name='".$review['country_name']."' ");
           $product_reviews[$k]['country_info']=array(
                'country_id'=>$country_info['country_id'],
                'country_name'=>$country_info['name'],
                'icon'=>CDN_COUNTRY_IMAGE.$country_info['icon']
            );
        }
        $review=$database->getRow("select avg(rating) as avg from `review` where product_id=$product_id");
        $rating_stars[]=round($review['avg'],1);
        for ($i = 1; $i <= 5; $i++) {
            $star_rows=$database->countRows("select review_id as total from `review` where rating=$i and product_id=$product_id");
            $rating_stars[]=$star_rows;
        }

        $gShow['page'] = $page;
        $gShow['count'] = count($product_reviews);
        $gShow['data'] = $product_reviews;
        $gShow['rating_stars'] = $rating_stars;
        $response->set(json_encode($gShow));
    }
    
    function ajax_helpful_yes()
    {
    	$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$customer =& $this->locator->get('customer');			
		
		$review_id = $request->get('review_id');
		$search_help_yes = $database->getRow("SELECT * FROM review_yes_no WHERE review_id = $review_id and review_ip LIKE '".$_SERVER['REMOTE_ADDR']."' and help_yes=1");
		if($search_help_yes){
			$database->query("UPDATE review set helpful_yes=helpful_yes-1 WHERE review_id=$review_id");
			$database->query("delete review_yes_no FROM `review_yes_no` WHERE id=".$search_help_yes['id']);
			
		} else {
			$database->query("UPDATE review set helpful_yes=helpful_yes+1 where review_id=$review_id");
			$database->query("INSERT INTO review_yes_no SET review_id=$review_id, review_ip='".$_SERVER['REMOTE_ADDR']."', help_yes=1");
			
		}
		$review_info=$database->getRow("SELECT helpful_yes FROM review WHERE review_id=$review_id");
		echo $review_info['helpful_yes'];
		
    }

    function ajax_helpful_no()
    {
    	$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$customer =& $this->locator->get('customer');
		
		
		$review_id = $request->get('review_id');
		$search_help_no = $database->getRow("SELECT * FROM review_yes_no WHERE review_ip LIKE '".$_SERVER['REMOTE_ADDR']."' and review_id = $review_id and help_no=1");
		if($search_help_no){
			
			$database->query("UPDATE review set helpful_no=helpful_no-1 WHERE review_id=$review_id");
			$database->query("delete review_yes_no FROM `review_yes_no` WHERE id=".$search_help_no['id']);
			
		} else {
			$sql="UPDATE review set helpful_no=helpful_no+1 where review_id=$review_id"; 
			$database->query("$sql");
			$database->query("INSERT INTO review_yes_no SET review_id=$review_id, review_ip = '".$_SERVER['REMOTE_ADDR']."', help_no=1");
			
		}
		$review_info=$database->getRow("SELECT helpful_no FROM review WHERE review_id=$review_id");
		echo $review_info['helpful_no'];
		
    }
}
