<?php
class ControllerProductProduct extends Controller {
	private $error = array(); 
	
	public function index() { 
		$this->language->load('product/product');
	
		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),			
			'separator' => false
		);
		
		$this->load->model('catalog/category');	
		
			//  Affiliate System -- Add on Starts Here
		if($this->config->get('config_affiliatepoints'))
		{
			if(isset($this->request->get['tracking']))
			{
				$this->load->model('affiliate/affiliate');			
				$this->session->data['referral_code'] = $this->request->get['tracking'];
				$affiliate_id=$this->model_affiliate_affiliate->getAffiliateId($this->session->data['referral_code']);
				if($affiliate_id){
					$this->session->data['referral_id'] = $affiliate_id;
					$this->model_affiliate_affiliate->AddUrlCount($affiliate_id);
					$this->data['mybanner'] = $this->model_affiliate_affiliate->getBannerURL($affiliate_id);
					if(strpos($this->data['mybanner'],'home')===false){
						//$this->redirect($this->data['mybanner']);
					}
				}
			}
		}
		//  Affiliate System -- Add on Ends   Here

		
		if (isset($this->request->get['path'])) {
			$path = '';
				
			foreach (explode('_', $this->request->get['path']) as $path_id) {
				if (!$path) {
					$path = $path_id;
				} else {
					$path .= '_' . $path_id;
				}
				
				$category_info = $this->model_catalog_category->getCategory($path_id);
				
				if ($category_info) {
					$this->data['breadcrumbs'][] = array(
						'text'      => $category_info['name'],
						'href'      => $this->url->link('product/category', 'path=' . $path),
						'separator' => $this->language->get('text_separator')
					);
				}
			}
		}
		
		$this->load->model('catalog/manufacturer');	
		
		if (isset($this->request->get['manufacturer_id'])) {
			$this->data['breadcrumbs'][] = array( 
				'text'      => $this->language->get('text_brand'),
				'href'      => $this->url->link('product/manufacturer'),
				'separator' => $this->language->get('text_separator')
			);	
				
			$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($this->request->get['manufacturer_id']);

			if ($manufacturer_info) {	
				$this->data['breadcrumbs'][] = array(
					'text'	    => $manufacturer_info['name'],
					'href'	    => $this->url->link('product/manufacturer/product', 'manufacturer_id=' . $this->request->get['manufacturer_id']),					
					'separator' => $this->language->get('text_separator')
				);
			}
		}
		
		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_tag'])) {
			$url = '';
			
			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}
						
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
						
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}
			
			if (isset($this->request->get['filter_category_id'])) {
				$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
			}	
						
			$this->data['breadcrumbs'][] = array(
				'text'      => $this->language->get('text_search'),
				'href'      => $this->url->link('product/search', $url),
				'separator' => $this->language->get('text_separator')
			);	
		}
		
		if (isset($this->request->get['product_id'])) {
			$product_id = $this->request->get['product_id'];
		} else {
			$product_id = 0;
		}
		
		$this->load->model('catalog/product');
		
		$product_info = $this->model_catalog_product->getProduct($product_id);
		
		$this->data['product_info'] = $product_info;
		
		$this->defaultProductData();
		
		if ($product_info) {
			$url = '';
			
			if (isset($this->request->get['path'])) {
				$url .= '&path=' . $this->request->get['path'];
			}
			
			if (isset($this->request->get['manufacturer_id'])) {
				$url .= '&manufacturer_id=' . $this->request->get['manufacturer_id'];
			}			

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}
						
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
			
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}	
						
			if (isset($this->request->get['filter_category_id'])) {
				$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
			}
												
			$this->data['breadcrumbs'][] = array(
				'text'      => $product_info['name'],
				'href'      => $this->url->link('product/product', $url . '&product_id=' . $this->request->get['product_id']),
				'separator' => $this->language->get('text_separator')
			);			
			
			$this->document->setTitle($product_info['name']);
			$this->document->setDescription($product_info['meta_description']);
			$this->document->setKeywords($product_info['meta_keyword']);
			$this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');
			
			$this->data['heading_title'] = $product_info['name'];
			
			$this->data['text_select'] = $this->language->get('text_select');
			$this->data['text_manufacturer'] = $this->language->get('text_manufacturer');
			$this->data['text_model'] = $this->language->get('text_model');
			$this->data['text_reward'] = $this->language->get('text_reward');
			$this->data['text_points'] = $this->language->get('text_points');	
			$this->data['text_discount'] = $this->language->get('text_discount');
			$this->data['text_stock'] = $this->language->get('text_stock');
			$this->data['text_price'] = $this->language->get('text_price');
			$this->data['text_tax'] = $this->language->get('text_tax');
			$this->data['text_discount'] = $this->language->get('text_discount');
			$this->data['text_option'] = $this->language->get('text_option');
			$this->data['text_qty'] = $this->language->get('text_qty');
			$this->data['text_minimum'] = sprintf($this->language->get('text_minimum'), $product_info['minimum']);
			$this->data['text_or'] = $this->language->get('text_or');
			$this->data['text_write'] = $this->language->get('text_write');
			$this->data['text_note'] = $this->language->get('text_note');
			$this->data['text_share'] = $this->language->get('text_share');
			$this->data['text_wait'] = $this->language->get('text_wait');
			$this->data['text_tags'] = $this->language->get('text_tags');
			
			$this->data['entry_name'] = $this->language->get('entry_name');
			$this->data['entry_review'] = $this->language->get('entry_review');
			$this->data['entry_rating'] = $this->language->get('entry_rating');
			$this->data['entry_good'] = $this->language->get('entry_good');
			$this->data['entry_bad'] = $this->language->get('entry_bad');
			$this->data['entry_captcha'] = $this->language->get('entry_captcha');
			
			$this->data['button_cart'] = $this->language->get('button_cart');
			$this->data['button_wishlist'] = $this->language->get('button_wishlist');
			$this->data['button_compare'] = $this->language->get('button_compare');			
			$this->data['button_upload'] = $this->language->get('button_upload');
			$this->data['button_continue'] = $this->language->get('button_continue');
			
			$this->load->model('catalog/review');

			$this->data['tab_description'] = $this->language->get('tab_description');
			$this->data['tab_attribute'] = $this->language->get('tab_attribute');
			$this->data['tab_review'] = sprintf($this->language->get('tab_review'), $this->model_catalog_review->getTotalReviewsByProductId($this->request->get['product_id']));
			$this->data['tab_related'] = $this->language->get('tab_related');
			
			$this->data['product_id'] = $this->request->get['product_id'];
			$this->data['manufacturer'] = $product_info['manufacturer'];
			$this->data['manufacturers'] = $this->url->link('product/manufacturer/product', 'manufacturer_id=' . $product_info['manufacturer_id']);
			$this->data['model'] = $product_info['model'];
			$this->data['reward'] = $product_info['reward'];
			$this->data['points'] = $product_info['points'];
			
			if ($product_info['quantity'] <= 0) {
				$this->data['stock'] = $product_info['stock_status'];
			} elseif ($this->config->get('config_stock_display')) {
				$this->data['stock'] = $product_info['quantity'];
			} else {
				$this->data['stock'] = $this->language->get('text_instock');
			}
			
			$this->load->model('tool/image');
			
				if ($product_info['image']) {
					$this->data['popup'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
				} else {	
					$this->data['popup'] = '';
				}
				if ($product_info['image']) {
					$this->data['thumb'] = $this->model_tool_image->resize($product_info['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
					$this->data['realImage'] = $product_info['image'];
		//		$this->data['thumb'] = $product_info['image'] ;
				} else {
					$this->data['thumb'] = '';
				}

			if(isset($this->session->data[$this->request->get['product_id'].'new_product_image']))
			//if(0)
			{
			//	$this->log->write('Session Image : ' . $this->session->data[$this->request->get['product_id'].'new_product_image'] );
				$this->data['popup'] = $this->model_tool_image->resize(str_replace('image/','',$this->session->data[$this->request->get['product_id'].'new_product_image']), $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
				$this->data['thumb'] = $this->model_tool_image->resize(str_replace('image/','',$this->session->data[$this->request->get['product_id'].'new_product_image']), $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
		//		$this->data['popup'] = str_replace('image/','',$this->session->data[$this->request->get['product_id'].'new_product_image']);
		//		$this->data['thumb'] = str_replace('image/','',$this->session->data[$this->request->get['product_id'].'new_product_image']);
			//	$this->log->write('Session Image : ' . str_replace('image/','',$this->session->data[$this->request->get['product_id'].'new_product_image']) );

			}

			$this->data['images'] = array();
			
			$results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
			
			foreach ($results as $result) {
				$this->data['images'][] = array(
					'popup' => $this->model_tool_image->resize($result['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height')),
					'thumb' => $this->model_tool_image->resize($result['image'], $this->config->get('config_image_additional_width'), $this->config->get('config_image_additional_height'))
				);
			}	
						
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$this->data['price'] = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
				if(isset($this->session->data[$this->request->get['product_id'].'new_product_image'])){
					if(isset($this->session->data[$this->request->get['product_id'].'new_price'])){
						$this->data['price'] = 	$this->currency->format($this->tax->calculate($this->session->data[$this->request->get['product_id'].'new_price'], $product_info['tax_class_id'], $this->config->get('config_tax'))) ;
					}
				}
			} else {
				$this->data['price'] = false;
			}
						
			if ((float)$product_info['special']) {
				$this->data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
			} else {
				$this->data['special'] = false;
			}
			
			if ($this->config->get('config_tax')) {
				$this->data['tax'] = $this->currency->format((float)$product_info['special'] ? $product_info['special'] : $product_info['price']);
			} else {
				$this->data['tax'] = false;
			}
	
			$discounts = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);
			
			$this->data['discounts'] = array(); 
			
			foreach ($discounts as $discount) {
				$this->data['discounts'][] = array(
					'quantity' => $discount['quantity'],
					'price'    => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')))
				);
			}
			
			$this->data['options'] = array();
			
			foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
				if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') { 
					$option_value_data = array();
					
					foreach ($option['option_value'] as $option_value) {
						if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
							$option_value_data[] = array(
								'product_option_value_id' => $option_value['product_option_value_id'],
								'option_value_id'         => $option_value['option_value_id'],
								'name'                    => $option_value['name'],
								'image'                   => $this->model_tool_image->resize($option_value['image'], 50, 50),
								'price'                   => (float)$option_value['price'] ? $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax'))) : false,
								'price_prefix'            => $option_value['price_prefix']
							);
						}
					}
					
					$this->data['options'][] = array(
						'product_option_id' => $option['product_option_id'],
						'option_id'         => $option['option_id'],
						'name'              => $option['name'],
						'type'              => $option['type'],
						'option_value'      => $option_value_data,
						'required'          => $option['required']
					);					
				} elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
					$this->data['options'][] = array(
						'product_option_id' => $option['product_option_id'],
						'option_id'         => $option['option_id'],
						'name'              => $option['name'],
						'type'              => $option['type'],
						'option_value'      => $option['option_value'],
						'required'          => $option['required']
					);						
				}
			}
			
			//New Codes Starts
			$this->data['metals'] = array();
			
			foreach ($this->model_catalog_product->getProductMetal($this->data['product_id']) as $metal) { 
				$metal_available = array();
				foreach ($this->model_catalog_product->getProductMetalAvail($this->data['product_id'],$metal['metal']) as $metalavail) {
					$metal_available[] = array(						
						'product_metalavail_id'  => $metalavail['product_metalavail_id'],
						'metal'  			 => $metalavail['metal'],
						'metal_id'           => $metalavail['metal_id'],
						'metal_code'         => $metalavail['metal_code'],
						'image'  			 => $metalavail['image'],
						'metal_image'  		 => $metalavail['metal_image'],
						'defaultnew'         => $metalavail['defaultnew'],
						'price'  			 => $metalavail['price'],
						'currency'           => $metalavail['currency']
					);
				}
				$this->data['metals'][] = array(
						'metal'  			 => $metal['metal'],
						'weight'             => $metal['weight'],
						'metal_available'   => $metal_available
				);
			}

			$this->data['gemstones'] = array();
			
			foreach ($this->model_catalog_product->getProductGemstones($this->data['product_id']) as $gemstone) { 
				$gemstone_available = array();
				foreach ($this->model_catalog_product->getProductGemstonesAvail($this->data['product_id'],$gemstone['gem']) as $gemstone_avail) {
					$gemstone_available[] = array(	
						'product_gemavail_id' => $gemstone_avail['product_gemavail_id'],
						'gem'  			 	 => $gemstone_avail['gem'],
						'gemstone_id'    	 => $gemstone_avail['gemstone_id'], 
						'image'  			 => $gemstone_avail['image'],
						'image1'  			 => $gemstone_avail['image1'],
						'defaultnew'         => $gemstone_avail['defaultnew']
					);
				}
				$this->data['gemstones'][] = array(
						'gem'  				 => $gemstone['gem'],
						'weight'             => $gemstone['weight'],
						'gemstone_available' => $gemstone_available
				);
			}
			//New Codes Ends
			
			if ($product_info['minimum']) {
				$this->data['minimum'] = $product_info['minimum'];
			} else {
				$this->data['minimum'] = 1;
			}
			
			$this->data['review_status'] = $this->config->get('config_review_status');
			$this->data['reviews'] = sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']);
			$this->data['rating'] = (int)$product_info['rating'];
			$this->data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');
			$this->data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
			
			$this->data['products'] = array();
			
			$results = $this->model_catalog_product->getProductRelated($this->request->get['product_id']);
			
			foreach ($results as $result) {
				if ($result['image']) {
					$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_related_width'), $this->config->get('config_image_related_height'));
				} else {
					$image = false;
				}
				
				if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
					$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
				} else {
					$price = false;
				}
						
				if ((float)$result['special']) {
					$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
				} else {
					$special = false;
				}
				
				if ($this->config->get('config_review_status')) {
					$rating = (int)$result['rating'];
				} else {
					$rating = false;
				}
							
				$this->data['products'][] = array(
					'product_id' => $result['product_id'],
					'thumb'   	 => $image,
					'name'    	 => $result['name'],
					'price'   	 => $price,
					'special' 	 => $special,
					'rating'     => $rating,
					'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
					'href'    	 => $this->url->link('product/product', 'product_id=' . $result['product_id']),
				);
			}	
			
			$this->data['tags'] = array();
					
			$results = $this->model_catalog_product->getProductTags($this->request->get['product_id']);
			
			foreach ($results as $result) {
				$this->data['tags'][] = array(
					'tag'  => $result['tag'],
					'href' => $this->url->link('product/search', 'filter_tag=' . $result['tag'])
				);
			}
			
			$this->model_catalog_product->updateViewed($this->request->get['product_id']);
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/product.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/product/product.tpl';
			} else {
				$this->template = 'default/template/product/product.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
		} else {
			$url = '';
			
			if (isset($this->request->get['path'])) {
				$url .= '&path=' . $this->request->get['path'];
			}
			
			if (isset($this->request->get['manufacturer_id'])) {
				$url .= '&manufacturer_id=' . $this->request->get['manufacturer_id'];
			}			

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}	
					
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
							
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}
					
			if (isset($this->request->get['filter_category_id'])) {
				$url .= '&filter_category_id=' . $this->request->get['filter_category_id'];
			}
								
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->language->get('text_error'),
				'href'      => $this->url->link('product/product', $url . '&product_id=' . $product_id),
        		'separator' => $this->language->get('text_separator')
      		);			
		
      		$this->document->setTitle($this->language->get('text_error'));

      		$this->data['heading_title'] = $this->language->get('text_error');

      		$this->data['text_error'] = $this->language->get('text_error');

      		$this->data['button_continue'] = $this->language->get('button_continue');

      		$this->data['continue'] = $this->url->link('common/home');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
    	}
  	}
	
	public function review() {
    	$this->language->load('product/product');
		
		$this->load->model('catalog/review');

		$this->data['text_no_reviews'] = $this->language->get('text_no_reviews');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}  
		
		$this->data['reviews'] = array();
		
		$review_total = $this->model_catalog_review->getTotalReviewsByProductId($this->request->get['product_id']);
			
		$results = $this->model_catalog_review->getReviewsByProductId($this->request->get['product_id'], ($page - 1) * 5, 5);
      		
		foreach ($results as $result) {
        	$this->data['reviews'][] = array(
        		'author'     => $result['author'],
				'text'       => strip_tags($result['text']),
				'rating'     => (int)$result['rating'],
        		'reviews'    => sprintf($this->language->get('text_reviews'), (int)$review_total),
        		'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
        	);
      	}			
			
		$pagination = new Pagination();
		$pagination->total = $review_total;
		$pagination->page = $page;
		$pagination->limit = 5; 
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('product/product/review', 'product_id=' . $this->request->get['product_id'] . '&page={page}');
			
		$this->data['pagination'] = $pagination->render();
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/review.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/product/review.tpl';
		} else {
			$this->template = 'default/template/product/review.tpl';
		}
		
		$this->response->setOutput($this->render());
	}
	
	public function write() {
		$this->language->load('product/product');
		
		$this->load->model('catalog/review');
		
		$json = array();
		
		if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
			$json['error'] = $this->language->get('error_name');
		}
		
		if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
			$json['error'] = $this->language->get('error_text');
		}

		if (!$this->request->post['rating']) {
			$json['error'] = $this->language->get('error_rating');
		}

		if (!isset($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
			$json['error'] = $this->language->get('error_captcha');
		}
				
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !isset($json['error'])) {
			$this->model_catalog_review->addReview($this->request->get['product_id'], $this->request->post);
			
			$json['success'] = $this->language->get('text_success');
		}
		
		$this->response->setOutput(json_encode($json));
	}
	
	
	public function newproduct() {

		if (isset($this->request->get['product_id'])){
			$product_id = $this->request->get['product_id'];
		} else {
			$product_id = 0;
		}
		
		$this->load->model('catalog/product');
		
		$results = $this->model_catalog_product->getProductnewproduct($product_id);
		$newproductprice=$this->request->post['newproductprice'];		
		$newproductimage=$this->request->post['newproductimage'];	
		
		$this->log->write('In New Product Price Section : ' . $newproductprice );	
		$this->log->write('In New Product Image   : ' . $newproductimage );	
		$newproduct_id=$this->model_catalog_product->updateProductnewproduct($product_id,$newproductprice,$newproductimage );
		
		$json = array();		
		
		$json['product_id'] = $newproduct_id;
		$this->log->write(' New Product ID CReated --------   : ' . $json['product_id']  );	

		$this->response->setOutput(json_encode($json));
		  
	}

	public function defaultProductData() {

		$prdimage = array();
		$metals_array =  array();
		$gemstones_array =  array();
		$product_details =  array();
		$new_product_details =  array();
			
		$prdname = $this->request->get['product_id'] ;
		$imageCount = $this->model_catalog_product->getProductImageCount($this->request->get['product_id']);
		
		$metals = $this->model_catalog_product->getProductMetalAvalability($this->request->get['product_id']);
		foreach ($metals as $metal) {	// Load Default Metal Data
			if( $metal['defaultnew'] )
			{
				$product_details[] = array(
					'type' => 'M',
					'id' => $metal['metal'],
					'value' => $metal['product_metalavail_id'],						
					'image' => $metal['image'],						
					'price' => $metal['price']
				);			
//				$this->log->write('xxx - '. $metal['metal'] . '='. $metal['product_metalavail_id'] );
				$prdname = $prdname . '_M' . $metal['metal'] . '-' . $metal['product_metalavail_id'];
			}
		}
		$gemstones = $this->model_catalog_product->getProductGemstonesAvalability($this->request->get['product_id']);
		foreach ($gemstones as $gemstone) {	// Load Gemstone Metal Data
			if( $gemstone['defaultnew'] )
			{
				$product_details[] = array(
					'type' => 'G',
					'id' => $gemstone['gem'],
					'value' => $gemstone['product_gemavail_id'],
					'image' => $gemstone['image']
				);	
//					$this->log->write('xxx - '. $gemstone['gem'] . '=' . $gemstone['product_gemavail_id'] );
				$prdname = $prdname . '_G' . $gemstone['gem'] . '-' . $gemstone['product_gemavail_id'];
			}
		}
		
		for($i=1;$i<=$imageCount;$i++){
			$prdname_AddlImage[$i] = $prdname . $i .'.png';
		}
		$prdname =$prdname .'.png';
		

		$this->session->data['product_details']=$product_details;
		
		//$product_db_image = $this->session->data[$this->request->get['product_id'].'new_product_image'];
		
		//$this->log->write($product_db_image . " === " . 'data/'. $prdname );

	//	if( isset($this->session->data[$this->request->get['product_id'].'new_product_image']) ) // && (strlen($this->session->data[$this->request->get['product_id'].'new_product_image'])-strlen($prdname) <= 3)  )
		if(false)
		{
		
				//$this->session->data[$this->request->get['product_id'].'new_product_image_jpg']= $product_db_image;
				//$this->session->data[$this->request->get['product_id'].'new_price']= $new_price;

		}else{
	//	{
		
			$this->load->model('tool/image1');	

			$im ='';
			$stamp='';
			$product_cost=0;
			$im = imagecreatefrompng('./image/TEMP/no_image.png');		
			
			for($i=1;$i<=$imageCount;$i++){
				$im_AddlImage[$i] = imagecreatefrompng('./image/TEMP/no_image.png');			
			}	
			// Create a New Product Image and update this to database
			$ix=0;
			foreach ($product_details as $product_detail) {
				$cost=0;
				if($product_detail['type']=='M')	// Process the selected metal
			  	{
					$cost = $this->model_catalog_product->getProductMetalCost($product_detail['value']);
					//$weightcost = $this->model_catalog_product->getMetalWeightCost($product_detail['value']);
					$this->log->write(' Select Metal Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $cost );
					//$cost = $metal['price'];		
				}else{									// if Metal Selected;
					$cost = $this->model_catalog_product->getProductGemstoneCost($product_detail['value']);
					//$weightcost = $this->model_catalog_product->getGemStoneWeightCost($product_detail['value']);
					$this->log->write(' Select Gem Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $cost );
					//$cost = $gemstone['price'];		
				}
	
				$product_cost += $cost ;
				$new_product_details[] = array(
					'type'  => $product_detail['type'],
					'id' 	=> $product_detail['id'],
					'value' => $product_detail['value'],
					'price' => $cost
				);			
				

				//$this->model_tool_image->resize(DIR_IMAGE. $product_detail['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'), DIR_IMAGE. $product_detail['image']);
		
				$new_image  = $this->resize( $product_detail['image'], 400 , 400 );
				
				$stamp = imagecreatefrompng('image/' . $new_image );
				//$stamp->resize(400, 400);
				
				$stamp_AddlImage[] = '';
				

				for($i=1;$i<=$imageCount;$i++){
					$stamp_AddlImage[$i] = '';
					$new_image  = $this->resize( str_replace('V1','V'.($i+1),$product_detail['image']), 400 , 400 );
					$stamp_AddlImage[$i] = imagecreatefrompng('image/' . $new_image );				
				}
		
				$marge_right = 0;
				$marge_bottom = 0;
				$sx = imagesx($stamp);
				$sy = imagesy($stamp);
				imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
				
				for($i=1;$i<=$imageCount;$i++){
					$sx = imagesx($stamp_AddlImage[$i]);
					$sy = imagesy($stamp_AddlImage[$i]);
					imagecopy($im_AddlImage[$i], $stamp_AddlImage[$i], imagesx($im_AddlImage[$i]) - $sx - $marge_right, imagesy($im_AddlImage[$i]) - $sy - $marge_bottom, 0, 0, imagesx($stamp_AddlImage[$i]), imagesy($stamp_AddlImage[$i]));
				}
				$ix++ ;
			}
			
			$this->session->data['product_details']=$new_product_details;
			$this->log->write( 'Product cost : '. $product_cost );

			$product_SettingCost=$this->model_catalog_product->getProductSettingCost($this->request->get['product_id']);
			$product_cost += $product_SettingCost;
			$this->log->write( 'Labour Setting Cost Calculated : '. $product_SettingCost );

			$product_weightCost=$this->model_catalog_product->getProductWeightCost($this->request->get['product_id']);
			$product_cost += $product_weightCost;
		
			$this->log->write( 'WeightCost Calculated : '. $product_weightCost );
			
			$this->log->write( 'Product Cost : '. $product_cost );
			
			$product_cost = $this->config->get('additionalCosts')  + $product_cost ;
			$this->log->write( 'Additional Cost  : '. $this->config->get('additionalCosts') . ' ; Additional Cost Added : '. $product_cost );
			
			$product_cost=$this->model_catalog_product->getProductMarkupCost($this->request->get['product_id'],$product_cost );
			$this->log->write( '-------------------------------------------' );
			$this->log->write( 'Product Final Price  : '. $product_cost );
			$this->log->write( '-------------------------------------------' );

			$this->model_catalog_product->updateProductPrice($this->request->get['product_id'],$product_cost);
	
			$newimagename = 'image/TEMP/'. $prdname;

			imagepng($im , $newimagename);
			$this->png2jpg(DIR_IMAGE. 'TEMP/' .  $prdname, DIR_IMAGE. 'TEMP/' . $prdname . '.jpg'  , 75);
			imagedestroy($im);


			for($i=1;$i<=$imageCount;$i++){
				$newimagename_1 = 'image/TEMP/'. $prdname_AddlImage[$i];
				imagepng($im_AddlImage[$i] , $newimagename_1);
				$this->png2jpg(DIR_IMAGE. 'TEMP/' .  $prdname_AddlImage[$i], DIR_IMAGE. 'TEMP/' . $prdname_AddlImage[$i] . '.jpg'  , 75);				
				imagedestroy($im_AddlImage[$i]);
			}
			$product_cost = round($product_cost);
			$prdname_nopng=str_replace(".png", "", $prdname );
			copy(DIR_IMAGE. 'TEMP/' . $prdname . '.jpg' ,  DIR_IMAGE. 'TEMP/' . $prdname_nopng . "3.png.jpg" );
			$this->ImageFlip(DIR_IMAGE. 'TEMP/' . $prdname_nopng  ."3.png.jpg" , 2  );
			
			copy(DIR_IMAGE. 'TEMP/' . $prdname_nopng . "2.png.jpg" ,  DIR_IMAGE. 'TEMP/' . $prdname_nopng . "4.png.jpg" );			
			$this->rotateImage(DIR_IMAGE. 'TEMP/' . $prdname_nopng . "2.png.jpg", DIR_IMAGE. 'TEMP/' . $prdname_nopng . "4.png.jpg" , 90);
			
			copy(DIR_IMAGE. 'TEMP/' . $prdname_nopng . "1.png.jpg" ,  DIR_IMAGE. 'TEMP/' . $prdname_nopng . "5.png.jpg" );
			$this->ImageFlip(DIR_IMAGE. 'TEMP/' . $prdname_nopng . "5.png.jpg" , 1  );
			

			$this->session->data[$this->request->get['product_id'].'new_price']= $product_cost;
			$this->session->data[$this->request->get['product_id'].'new_product_image']= 'TEMP/' . $prdname ;			
			$this->session->data[$this->request->get['product_id'].'new_product_image_jpg']= 'TEMP/' . $prdname . '.jpg' ;			
		}
	}
	public function rotateImage($source, $target, $angle) {
		
			$rotate_source = imagecreatefromjpeg($source);			// Load
			$rotate = imagerotate($rotate_source, $angle, 0);														// Rotate
			imagejpeg($rotate,$target );								// Output
		
	}

	public function resize($filename, $width, $height) {
		if (!file_exists(DIR_IMAGE . $filename) || !is_file(DIR_IMAGE . $filename)) {
			return;
		} 
		 
		$info = pathinfo($filename);
		$extension = $info['extension'];
		
		$old_image = $filename;
		$new_image = 'cache/' . utf8_substr($filename, 0, strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
		
		if (!file_exists(DIR_IMAGE . $new_image) || (filemtime(DIR_IMAGE . $old_image) > filemtime(DIR_IMAGE . $new_image))) {
			$path = '';
			
			$directories = explode('/', dirname(str_replace('../', '', $new_image)));
			
			foreach ($directories as $directory) {
				$path = $path . '/' . $directory;
				
				if (!file_exists(DIR_IMAGE . $path)) {
					@mkdir(DIR_IMAGE . $path, 0777);
				}		
			}
			
			$image = new Image(DIR_IMAGE . $old_image);
			$image->resize($width, $height);
			$image->save(DIR_IMAGE . $new_image);
		}
	
		if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
			return   $new_image;
		} else {
			return   $new_image;
		}	
	}
	
	
	
	public function vflipImage($source,$target) {

		 $flimage = new Gmagick();
		 $flimage->readImage($source);			// read image file
  		 $flimage->flipImage();					// flip image vertically
  		 $flimage->writeImage($target); 		// write new image file
		 $image->destroy();
	}
	
	public function hflipImage($source,$target) {

		 $flimage = new Gmagick();
		 $flimage->readImage($source);			// read image file
  		 $flimage->flopImage();					// flip image vertically
  		 $flimage->writeImage($target); 		// write new image file
		 $flimage->destroy();
		 
	}
	
	
	public function ImageFlip( $source, $mode )
   {
	   
	   $this->log->write( 'Flipping : ' . $source );
		$imgsrc = ImageCreateFromJpeg(  $source );

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( (int) $mode )
    {

        case 1:
            $src_y                =    $height;
            $src_height           =    -$height;
        break;

        case 2:
            $src_x                =    $width;
            $src_width            =    -$width;
        break;

        case 3:
            $src_x                =    $width;
            $src_y                =    $height;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest = imagecreatetruecolor ( $width, $height );
 	 imagecopyresampled( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height )  ;
		imagejpeg( $imgdest, $source, 100 );
		
			   //$this->log->write( 'Flipping : ' . $imgdest );

    }

	
	public function imagechange() {

		$addImage=$this->request->post['myimg'];		
		$product_cost=$this->AddImage($addImage,$this->request->post['metal_number']);		
		$json = array();		
		
		$json['newimage'] = $this->session->data[$this->request->get['product_id'].'new_product_image_jpg'];
		
		$json['product_cost'] = substr($this->currency->format($product_cost),0,-3) ;
		$json['prdcost'] = $product_cost ;
		$this->session->data[$this->request->get['product_id'].'new_price']  = $product_cost ;
		$this->response->setOutput(json_encode($json));
		  
	}
	
	public function AddImage( $addimage,$modelnum ) {
		
		$this->load->model('catalog/product');
		$this->load->model('tool/image');
		$stamp ='';
		$im ='';

		if(substr($modelnum, 1)=='M'){
			$metal_selected=1;
			$selmetal=explode("-",$modelnum);
			$id=$selmetal[1];
			$selected_metal_id=$selmetal[2];				
			$value=$selected_metal_id;
		}else{
			$gemstone_selected=1;
			$selgemstone=explode("-",$modelnum);
			$id=$selgemstone[1];
			$selected_gemstone_id=$selgemstone[2];
			$value=$selected_gemstone_id;
		}		

		unset($product_details); 

		if(isset($this->session->data[$this->request->get['product_id'].'new_product_image'])) 
		//if(0)					// Use the Session Data if presents
		{		
			$product_details =  array();
			$product_details =  $this->session->data['product_details'];
			//$this->log->write('Size Of :'.sizeof($product_details));

			$product_mage = $this->session->data[$this->request->get['product_id'].'new_product_image'];
			$this->log->write('In Session Image : ' . $product_mage);	

			$new_image  = $this->resize( $product_mage, 400 , 400 );
						
			//$im = imagecreatefrompng('./image/'.str_replace('image/','',$product_mage));
			$this->log->write('In Session Image : ' . $new_image);	
			$im = imagecreatefrompng('./image/'.$new_image);
			
			$this->log->write('In Session Image : ' . $product_mage);	
		}
		
		// Product Details ready for usage
		unset($new_product_details); 
		$prdname=$this->request->get['product_id'];
		$product_cost=0;
		$this->log->write('--------------------------------------' ); 

		foreach ($product_details as $product_detail) {

			if($product_detail['type']==substr($modelnum,0, 1) && $product_detail['id']==$id)	// Process the selected metal
			{
				$cost=0;
				if(substr($modelnum,0, 1)=='M'){		// if Gemstone Selected;
					$metals = $this->model_catalog_product->getProductMetalAvalability($this->request->get['product_id']);
					foreach ($metals as $metal) {
						if( $metal['product_metalavail_id'] == $value )
						{
							$cost = $this->model_catalog_product->getProductMetalCost($value);
							$this->log->write(' Select Metal Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $cost );
						}
					}
				}else{									// if Metal Selected;
					$gemstones = $this->model_catalog_product->getProductGemstonesAvalability($this->request->get['product_id']);
					foreach ($gemstones as $gemstone) {
						if( $gemstone['product_gemavail_id'] ==  $value  )
						{
							
							$this->log->write( 'Cost : ' . $value . ' ' . $modelnum );
							$cost = $this->model_catalog_product->getProductGemstoneCost($value);
							$this->log->write(' Select Gem Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $itemprice );
						}
					}
				}

				$prdname = $prdname . '_' . substr($modelnum,0,1) . $id . '-' . $value;
				$product_cost += $cost ;
				
				$new_product_details[] = array(
					'type' => $product_detail['type'],
					'id' => $product_detail['id'],
					'value' => $value,
					'price' => $cost
				);
				
			}else{
				if(0){
					$itemprice = $product_detail['price'];
				}else{
					if( $product_detail['type']  == 'M'){
						$itemprice = $this->model_catalog_product->getProductMetalCost($product_detail['value']);
						$this->log->write(' Metal Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $itemprice );

					}else{
						
						$this->log->write( 'Cost : ' . $product_detail['value'] );

						$itemprice = $this->model_catalog_product->getProductGemstoneCost($product_detail['value']);
						$this->log->write(' Gem Cost (' . $product_detail['type'] . ' - ' . $product_detail['id'] . ') : ' . $itemprice );
					}
				}
				$new_product_details[] = array(
					'type' => $product_detail['type'],
					'id' => $product_detail['id'],
					'value' =>  $product_detail['value'],
					'price' => $itemprice
				);
				$product_cost += $itemprice;
				$prdname = $prdname . '_' . $product_detail['type'] . $product_detail['id'] . '-' . $product_detail['value'];
			}
		}
		

		$prdname = $prdname . '.png' ;
		$prdname_jpg = $prdname . '.jpg' ;
		$this->log->write($prdname  . ' vs ' . $prdname_jpg);
		$product_details = $new_product_details;

		unset($this->session->data['product_details']);
		$this->session->data['product_details']=$new_product_details;
				
		$stamp = imagecreatefrompng($addimage);

		$marge_right = 0;
		$marge_bottom = 0;
		$sx = imagesx($stamp);
		$sy = imagesy($stamp);
		imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
		
		$this->log->write( 'Metal and Gem : '. $product_cost );

		$product_SettingCost=$this->model_catalog_product->getProductSettingCost($this->request->get['product_id']);
		$product_cost += $product_SettingCost;
		$this->log->write( 'Setting Cost Calculated : '. $product_SettingCost );

		$product_weightCost=$this->model_catalog_product->getProductWeightCost($this->request->get['product_id']);
		$product_cost += $product_weightCost;
		
		$this->log->write( 'WeightCost Calculated : '. $product_weightCost );
		$this->log->write( 'Product Cost : '. $product_cost );
			
		$product_cost = $this->config->get('additionalCosts')  + $product_cost ;
		$this->log->write( 'Additional Cost  : '. $this->config->get('additionalCosts') . ' ; Additional Cost Added : '. $product_cost );
			
		$product_cost=$this->model_catalog_product->getProductMarkupCost($this->request->get['product_id'],$product_cost );
		$this->log->write( '-------------------------------------------' );
		$this->log->write( 'Product Final Price  : '. $product_cost );
		$this->log->write( '-------------------------------------------' );
			
		$newimagename=$prdname;
		$newimagename_jpg=$prdname_jpg;
		
		$newimagename='image/TEMP/'.$newimagename;
		$newimagename_jpg='image/TEMP/'.$newimagename_jpg;
		$newimage = $newimagename;
		imagepng($im , $newimage);
		
		$this->png2jpg(DIR_IMAGE. 'TEMP/' .  $prdname, DIR_IMAGE. 'TEMP/' . $prdname_jpg , 75);
		

		imagedestroy($im);
		$this->session->data[$this->request->get['product_id'].'new_product_image']=$newimagename;
		$this->session->data[$this->request->get['product_id'].'new_product_image_jpg']=$newimagename_jpg;
		
		$product_cost = round($product_cost);
		return $product_cost;
		
	}		
	
	
	
	public	function png2jpg($originalFile, $outputFile, $quality) {
    	$image = imagecreatefrompng($originalFile);
    	imagejpeg($image, $outputFile, $quality);
    	imagedestroy($image);
	}
	
	
	public function captcha() {
		$this->load->library('captcha');
		
		$captcha = new Captcha();
		
		$this->session->data['captcha'] = $captcha->getCode();
		
		$captcha->showImage();
	}
	
	
	
	public function upload() {
		$this->language->load('product/product');
		
		$json = array();
		
		if (!empty($this->request->files['file']['name'])) {
			$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
			
			if ((strlen($filename) < 3) || (strlen($filename) > 128)) {
        		$json['error'] = $this->language->get('error_filename');
	  		}	  	
			
			$allowed = array();
			
			$filetypes = explode(',', $this->config->get('config_upload_allowed'));
			
			foreach ($filetypes as $filetype) {
				$allowed[] = trim($filetype);
			}
			
			if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
				$json['error'] = $this->language->get('error_filetype');
       		}	
						
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
			}
		} else {
			$json['error'] = $this->language->get('error_upload');
		}
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !isset($json['error'])) {
			if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
				$file = basename($filename) . '.' . md5(rand());
				
				// Hide the uploaded file name sop people can not link to it directly.
				$this->load->library('encryption');
				
				$encryption = new Encryption($this->config->get('config_encryption'));
				
				$json['file'] = $encryption->encrypt($file);
				
				move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);
			}
						
			$json['success'] = $this->language->get('text_upload');
		}	
		
		$this->response->setOutput(json_encode($json));		
	}
}
?>