<?php
class ControllerExtensionModulepmcbd extends Controller {
	private $modpath = '';
	private $modtpl = 'default/template/module/pmcbd.tpl';
	private $modname = 'pmcbd';
	private $modssl = '';
	private $modstatus = false;
	private $modlangid = '';
	private $modstoreid = '';
	private $modcustgrpid = '';
 	
	public function __construct($registry) {
		parent::__construct($registry);
		
		$this->modpath = (substr(VERSION,0,3)=='2.3') ? 'extension/module/pmcbd' : 'module/pmcbd';
 		if(substr(VERSION,0,3)=='2.3') {
			$this->modtpl = 'extension/module/pmcbd';
		} else if(substr(VERSION,0,3)=='2.2') {
			$this->modtpl = 'module/pmcbd';
		}
 		$this->modssl = (substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') ? true : 'SSL';
		$this->modstatus = $this->config->get($this->modname.'_status');
		$this->modlangid = (int)$this->config->get('config_language_id');
		$this->modstoreid = (int)$this->config->get('config_store_id');
		$this->modcustgrpid = (int)$this->config->get('config_customer_group_id');
 	}
	
	public function index() {
		if (isset($this->request->get['product_id'])) {
			$product_id = (int)$this->request->get['product_id'];
		} else {
			$product_id = 0;
		}
		if($product_id && $this->modstatus) {
			$data = $this->load->language($this->modpath);
			//$data['addcombourl'] = $this->url->link($this->modpath.'/addtocartcombo', '' ,$this->modssl);
 			$data['addcombourl'] = 'index.php?route=' . $this->modpath.'/addtocartcombo';
			
			$setting = $this->getpmcbd($product_id);
			if($setting && $setting['status']) {
 				$combo_setting = json_decode($setting['combo_setting'], true);				
  				$data['randstr'] = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
  				$data['limit'] = isset($setting['limitset']) ? $setting['limitset'] : 3;
				$data['pmcbd_id'] = isset($setting['pmcbd_id']) ? $setting['pmcbd_id'] : 0;
				$data['target_product_id'] = isset($setting['target_product_id']) ? $setting['target_product_id'] : 0;
 				if($combo_setting) {
					$data['pmcbddata'] = array();
 					foreach ($combo_setting as $row => $pmcbdstng) { 
						if(isset($pmcbdstng['store']) && in_array($this->modstoreid, $pmcbdstng['store'])) {
							if(isset($pmcbdstng['customer_group']) &&  in_array($this->modcustgrpid, $pmcbdstng['customer_group'])) {
								if(isset($pmcbdstng['product']) && $pmcbdstng['product']) { 
									$data['pmcbddata'][] = $this->getproductinfo($pmcbdstng);
								}
							}
						}
 					}  
 					//echo "<pre>";print_r($data['pmcbddata']);exit;
						 
					if ($data['pmcbddata']) {
						if(file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/extension/module/pmcbd.tpl')){
						    return $this->load->view( DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/extension/module/pmcbd', $data);
						}else{ 
						    return $this->load->view(DIR_TEMPLATE . 'default/template/extension/module/pmcbd', $data);
						}
					}		
				} 			
			}
		}
 	} 
	public function getpmcbd($product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "pmcbd WHERE target_product_id = '" . (int)$product_id . "' limit 1");
 		return $query->row;
	}
	
	protected function setvalue($postfield) {
		return $this->config->get($postfield);
	}
	public function getproductinfo($pmcbdstng) {
 		$this->load->language($this->modpath);
		$this->load->model('catalog/product'); 		
 		$this->load->model('tool/image');
 
 		$product_data = array();
		$pmcbdstng_data = array();
		$product_id_array = array();
 		
		if($pmcbdstng['product'] && is_array($pmcbdstng['product'])) {
 			$pmcbdttlprc = 0;
  			foreach ($pmcbdstng['product'] as $product_id) {
				$product_id_array[] = $product_id;
 				$product_info = $this->model_catalog_product->getProduct($product_id);
			
				if ($product_info) {
					$image = $this->model_tool_image->resize('placeholder.png', 200,200);
					if ($product_info['image']) {
						$image = $this->model_tool_image->resize($product_info['image'], 200,200);
					}
		
					$price = false;
 					if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
						if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 
							$price = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
						} else {
							$price = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
						}
						$price_tx = $this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax'));
 					} 
		
					$special = false;
 					if ((float)$product_info['special']) {
						if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 	
							$special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
						} else {
							$special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
						}
						$special_tx = $this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax'));
 					} 
					
					$pmcbdttlprc += $special ? $special_tx : $price_tx;
					 	
 					$tax = false;
					if ($this->config->get('config_tax')) {
						if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 	
							$tax = $this->currency->format((float)$product_info['special'] ? $product_info['special'] : $product_info['price'], $this->session->data['currency']);
						} else {
							$tax = $this->currency->format((float)$product_info['special'] ? $product_info['special'] : $product_info['price']);
						}
					}  
		
					$rating = false;
					if ($this->config->get('config_review_status')) {
						$rating = $product_info['rating'];
					} 
					
 					$product_data[] = array(
						'product_id'  => $product_info['product_id'],
						'thumb'       => $image,
						'name'        => $product_info['name'],
						'description' => utf8_substr(strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
						'price'       => $price,
						'special'     => $special,
  						'tax'         => $tax,
						'config_tax'         => $this->config->get('config_tax'),
						'rating'      => $rating,
						'href'        => $this->url->link('product/product', 'product_id=' . $product_info['product_id'])
					);
				}
			}

			if($product_data) {
				$pmcbdstng_data['tabtitle'] = $pmcbdstng['tabtitle'][$this->modlangid];
				$pmcbdstng_data['product'] = $product_data;
				$pmcbdstng_data['disctype'] = $pmcbdstng['disctype'];
				$pmcbdstng_data['discount'] = $pmcbdstng['discount'];
				$pmcbdstng_data['product_id_str'] = implode(",",$product_id_array);
				$pmcbdstng_data['pmcbdttlprc'] = $this->currency->format($pmcbdttlprc, $this->session->data['currency']);
 				if($pmcbdstng['disctype'] == 'F') {
					if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 		
						$pmcbdstng_data['pmcbd'] = '-'.$this->currency->format($pmcbdstng['discount'], $this->session->data['currency']);
						$pmcbdstng_data['pmcbdprc'] = $this->currency->format($pmcbdttlprc - $pmcbdstng['discount'], $this->session->data['currency']);
						$pmcbdstng_data['pmcbdsave'] = $this->currency->format($pmcbdstng['discount'], $this->session->data['currency']);
					} else {
						$pmcbdstng_data['pmcbd'] = '-'.$this->currency->format($pmcbdstng['discount']);
						$pmcbdstng_data['pmcbdprc'] = $this->currency->format($pmcbdttlprc - $pmcbdstng['discount']);
						$pmcbdstng_data['pmcbdsave'] = $this->currency->format($pmcbdstng['discount']);
					}
				} else {
					if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 		
						$pmcbdstng_data['pmcbd'] = -$pmcbdstng['discount'].'%';
						$pmcbdstng_data['pmcbdprc'] = $this->currency->format($pmcbdttlprc - round(($pmcbdttlprc * $pmcbdstng['discount'])/100,2), $this->session->data['currency']);
						$pmcbdstng_data['pmcbdsave'] = $this->currency->format(round(($pmcbdttlprc * $pmcbdstng['discount'])/100,2), $this->session->data['currency']);
					} else { 
						$pmcbdstng_data['pmcbd'] = -$pmcbdstng['discount'].'%';
						$pmcbdstng_data['pmcbdprc'] = $this->currency->format($pmcbdttlprc - round(($pmcbdttlprc * $pmcbdstng['discount'])/100,2));
						$pmcbdstng_data['pmcbdsave'] = $this->currency->format(round(($pmcbdttlprc * $pmcbdstng['discount'])/100,2));
					}
				}	
				return $pmcbdstng_data;
			} 
		}
 	}
	
	public function addtocartcombo() {
		$data = $this->load->language($this->modpath);
		$json = array();
		if(isset($this->request->post['product_id_str'])) {
			$this->session->data['pmcbd'][] = array('pmcbd_id' => $this->request->post['pmcbd_id'], 'target_product_id' => $this->request->post['target_product_id'], 'pmcbd_id_key' => $this->request->post['pmcbd_id_key']);
			
			$product_id_array = explode(",",$this->request->post['product_id_str']);
			if($product_id_array) {
				foreach($product_id_array as $product_id) {
					$this->cart->add($product_id);	
				}
				
				
				if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 
					// Totals
					$this->load->model('extension/extension');
	
					$totals = array();
					$taxes = $this->cart->getTaxes();
					$total = 0;
			
					// Because __call can not keep var references so we put them into an array. 			
					$total_data = array(
						'totals' => &$totals,
						'taxes'  => &$taxes,
						'total'  => &$total
					);
	
					// Display prices
					if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
						$sort_order = array();
	
						$results = $this->model_extension_extension->getExtensions('total');
	
						foreach ($results as $key => $value) {
							$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
						}
	
						array_multisort($sort_order, SORT_ASC, $results);
	
						foreach ($results as $result) {
							if ($this->config->get($result['code'] . '_status')) {
								if(substr(VERSION,0,3)=='2.3') { 
									$this->load->model('extension/total/' . $result['code']);
								} else {
									$this->load->model('total/' . $result['code']);
								}
	
								// We have to put the totals in an array so that they pass by reference.
								if(substr(VERSION,0,3)=='2.3') { 
									$this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
								} else {
									$this->{'model_total_' . $result['code']}->getTotal($total_data);
								}
							}
						}
	
						$sort_order = array();
	
						foreach ($totals as $key => $value) {
							$sort_order[$key] = $value['sort_order'];
						}
	
						array_multisort($sort_order, SORT_ASC, $totals);
					}
				} else {
					
					// Totals
					$this->load->model('extension/extension');
	
					$total_data = array();
					$total = 0;
					$taxes = $this->cart->getTaxes();
	
					// Display prices
					if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
						$sort_order = array();
	
						$results = $this->model_extension_extension->getExtensions('total');
	
						foreach ($results as $key => $value) {
							$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
						}
	
						array_multisort($sort_order, SORT_ASC, $results);
	
						foreach ($results as $result) {
							if ($this->config->get($result['code'] . '_status')) {
								$this->load->model('total/' . $result['code']);
	
								$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
							}
						}
	
						$sort_order = array();
	
						foreach ($total_data as $key => $value) {
							$sort_order[$key] = $value['sort_order'];
						}
	
						array_multisort($sort_order, SORT_ASC, $total_data);
					}
					
				}
				
				$json['success'] = $data['text_sucaddcom'];
				
				if(substr(VERSION,0,3)=='2.3' || substr(VERSION,0,3)=='2.2') { 
					$json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));	
				} else {
					$json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
				}
 				
  				//$json['redirect'] = str_replace('&amp;', '&', $this->url->link('checkout/cart'));
			} 
		}
		$json['error'] = $data['text_failaddcom'];
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	} 
}