<?php 
class ControllerCheckoutCart extends Controller {
	private $error = array();
	
	public function index() {
		$this->language->load('checkout/cart');
        
		if (!isset($this->session->data['vouchers'])) {
			$this->session->data['vouchers'] = array();
		}
		
		// Update

				if( ! empty( $this->session->data['mod_groups'] ) ) {
					$this->load->model('module/mod_gifts_gift');

					ModGiftsHelperCart::newInstance( $this, $this->data )->initSetOptions();
				}
				
				if( isset( $this->session->data['mod_error'] ) ) {
					$this->error['warning'] = $this->session->data['mod_error'];

					unset( $this->session->data['mod_error'] );
				}
			
		if (!empty($this->request->post['quantity'])) {
			foreach ($this->request->post['quantity'] as $key => $value) {
				$this->cart->update($key, $value);
			}
			
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']); 
			unset($this->session->data['reward']);
			

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));  			
		}
       	
		// Remove
		if (isset($this->request->get['remove'])) {
			$this->cart->remove($this->request->get['remove']);

				if( ! empty( $this->session->data['mod_groups'] ) ) {
					$this->load->model('module/mod_gifts_gift');
					$modGroups = array();

					if( $this->cart->hasProducts() ) {
						foreach( $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() ) as $item ) {
							$modGroups[$item['group_id']] = $item;
						}
					}
					
					foreach( $this->session->data['mod_groups'] as $item ) {
						if( ! isset( $modGroups[$item['group_id']] ) ) {
							unset( $this->session->data['mod_groups'][$item['group_id']] );
						}
					}
				}
			
			
			unset($this->session->data['vouchers'][$this->request->get['remove']]);
			
			$this->session->data['success'] = $this->language->get('text_remove');
		
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']); 
			unset($this->session->data['reward']);  
								

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));
		}
			
		// Coupon    
		if (isset($this->request->post['coupon']) && $this->validateCoupon()) { 
			$this->session->data['coupon'] = $this->request->post['coupon'];
				
			$this->session->data['success'] = $this->language->get('text_coupon');
			

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));
		}
		
		// Voucher
		if (isset($this->request->post['voucher']) && $this->validateVoucher()) { 
			$this->session->data['voucher'] = $this->request->post['voucher'];
				
			$this->session->data['success'] = $this->language->get('text_voucher');
				

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));
		}

		// Reward
		if (isset($this->request->post['reward']) && $this->validateReward()) { 
			$this->session->data['reward'] = abs($this->request->post['reward']);
				
			$this->session->data['success'] = $this->language->get('text_reward');
				

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));
		}
		
		// Shipping
		if (isset($this->request->post['shipping_method']) && $this->validateShipping()) {
			$shipping = explode('.', $this->request->post['shipping_method']);
			
			$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
			
			$this->session->data['success'] = $this->language->get('text_shipping');
			

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();

				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );
						
				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}
					
					if( ! empty( $this->request->post['add_gift_to_cart'] ) ) {
						$this->session->data['success'] = $this->language->get( 'update_cart' );
					}

					$this->language->load('checkout/cart');
				}
			
			$this->redirect($this->url->link('checkout/cart'));
		}
		
		
			$ast_sval = array("", $this->config->get('config_title'), $this->language->get('heading_title'), $this->config->get('ast_custom'));
			$ast_sorder = explode(",",$this->config->get('ast_sorder'));
			$ast_ssep = explode(",",$this->config->get('ast_ssep'));
			$newTitle = $ast_sval[$ast_sorder[0]];
			for($i=1;$i<3;$i++) {
				$newTitle .= ($ast_ssep[$i-1].$ast_sval[$ast_sorder[$i]]);
			}
			$this->document->setTitle($newTitle);
		$this->document->addScript('catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
		$this->document->addStyle('catalog/view/javascript/jquery/colorbox/colorbox.css');
			
      	$this->data['breadcrumbs'] = array();

      	$this->data['breadcrumbs'][] = array(
        	'href'      => $this->url->link('common/home'),
        	'text'      => $this->language->get('text_home'),
        	'separator' => false
      	); 

      	$this->data['breadcrumbs'][] = array(
        	'href'      => $this->url->link('checkout/cart'),
        	'text'      => $this->language->get('heading_title'),
        	'separator' => $this->language->get('text_separator')
      	);
			
    	if ($this->cart->hasProducts() || !empty($this->session->data['vouchers'])) {
			$points = $this->customer->getRewardPoints();
			
			$points_total = 0;
			
			foreach ($this->cart->getProducts() as $product) {
				if ($product['points']) {
					$points_total += $product['points'];
				}
			}		
				
      		$this->data['heading_title'] = $this->language->get('heading_title');
			
			$this->data['text_next'] = $this->language->get('text_next');
			$this->data['text_next_choice'] = $this->language->get('text_next_choice');
     		$this->data['text_use_coupon'] = $this->language->get('text_use_coupon');
			$this->data['text_use_voucher'] = $this->language->get('text_use_voucher');
			$this->data['text_use_reward'] = sprintf($this->language->get('text_use_reward'), $points);
			$this->data['text_shipping_estimate'] = $this->language->get('text_shipping_estimate');
			$this->data['text_shipping_detail'] = $this->language->get('text_shipping_detail');
			$this->data['text_shipping_method'] = $this->language->get('text_shipping_method');
			$this->data['text_select'] = $this->language->get('text_select');
			$this->data['text_none'] = $this->language->get('text_none');
			$this->data['text_until_cancelled'] = $this->language->get('text_until_cancelled');
			$this->data['text_freq_day'] = $this->language->get('text_freq_day');
			$this->data['text_freq_week'] = $this->language->get('text_freq_week');
			$this->data['text_freq_month'] = $this->language->get('text_freq_month');
			$this->data['text_freq_bi_month'] = $this->language->get('text_freq_bi_month');
			$this->data['text_freq_year'] = $this->language->get('text_freq_year');


			$this->data['text_auction_won'] = $this->language->get('text_auction_won');
			$this->data['text_auction_removal'] = sprintf($this->language->get('text_auction_removal'), $this->config->get('config_auction_payment_period') ? (string)$this->config->get('config_auction_payment_period') : '21');
			
			$this->data['column_image'] = $this->language->get('column_image');
      		$this->data['column_name'] = $this->language->get('column_name');
      		$this->data['column_model'] = $this->language->get('column_model');
      		$this->data['column_quantity'] = $this->language->get('column_quantity');
			$this->data['column_price'] = $this->language->get('column_price');
      		$this->data['column_total'] = $this->language->get('column_total');
			
			$this->data['entry_coupon'] = $this->language->get('entry_coupon');
			$this->data['entry_voucher'] = $this->language->get('entry_voucher');
			$this->data['entry_reward'] = sprintf($this->language->get('entry_reward'), $points_total);
			$this->data['entry_country'] = $this->language->get('entry_country');
			$this->data['entry_zone'] = $this->language->get('entry_zone');
			$this->data['entry_postcode'] = $this->language->get('entry_postcode');
						
			$this->data['button_update'] = $this->language->get('button_update');
			$this->data['button_remove'] = $this->language->get('button_remove');
			$this->data['button_coupon'] = $this->language->get('button_coupon');
			$this->data['button_voucher'] = $this->language->get('button_voucher');
			$this->data['button_reward'] = $this->language->get('button_reward');
			$this->data['button_quote'] = $this->language->get('button_quote');
			$this->data['button_shipping'] = $this->language->get('button_shipping');			
      		$this->data['button_shopping'] = $this->language->get('button_shopping');
      		$this->data['button_checkout'] = $this->language->get('button_checkout');

      		$this->data['text_trial'] = $this->language->get('text_trial');
      		$this->data['text_recurring'] = $this->language->get('text_recurring');
      		$this->data['text_length'] = $this->language->get('text_length');
      		$this->data['text_recurring_item'] = $this->language->get('text_recurring_item');
      		$this->data['text_payment_profile'] = $this->language->get('text_payment_profile');

			if (isset($this->error['warning'])) {
				$this->data['error_warning'] = $this->error['warning'];
			} elseif (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
      			$this->data['error_warning'] = $this->language->get('error_stock');		
			} else {
				$this->data['error_warning'] = '';
			}
			
			if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
				$this->data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
			} else {
				$this->data['attention'] = '';
			}
						
			if (isset($this->session->data['success'])) {
				$this->data['success'] = $this->session->data['success'];
			
				unset($this->session->data['success']);
			} else {
				$this->data['success'] = '';
			}
			
			$this->data['action'] = $this->url->link('checkout/cart');   
						
			if ($this->config->get('config_cart_weight')) {
				$this->data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
			} else {
				$this->data['weight'] = '';
			}
						 
			$this->load->model('tool/image');



	//Q: Coupon Free Product
	if (isset($this->session->data['coupon'])) {
		$coupon_product_info = $this->db->query("SELECT * FROM " . DB_PREFIX . "coupon_product cp LEFT JOIN " . DB_PREFIX . "coupon c ON (c.coupon_id = cp.coupon_id) WHERE c.code = '" . $this->session->data['coupon'] . "'");
		if ($coupon_product_info->num_rows) { // Check that if there are coupon products with this coupon that they exist first
			foreach ($coupon_product_info->rows as $coupon_product) {
				foreach ($this->cart->getProducts() as $cart_product) {
					if ($coupon_product['product_id'] == $cart_product['product_id']) {
						$free_product_info = $this->db->query("SELECT * FROM " . DB_PREFIX . "coupon_free_product cfp LEFT JOIN " . DB_PREFIX . "coupon c ON (c.coupon_id = cfp.coupon_id) WHERE c.code = '" . $this->session->data['coupon'] . "'");
						if ($free_product_info->num_rows) {
							foreach ($free_product_info->rows as $free_product) {
								$found = false;
								foreach ($this->cart->getProducts() as $cart_product2) {
									if ($free_product['product_id'] == $cart_product2['product_id']) {
										$found = true;
									}
								}
								if (!$found) {
									$this->cart->add($free_product['product_id'], 1, array(), 0);
									$this->session->data['coupon_free'] = 1;
								}
							}
						}
					}
				}
			}
		} else { // Else if there are no coupon_products, then just apply it
			$free_product_info = $this->db->query("SELECT * FROM " . DB_PREFIX . "coupon_free_product cfp LEFT JOIN " . DB_PREFIX . "coupon c ON (c.coupon_id = cfp.coupon_id) WHERE c.code = '" . $this->session->data['coupon'] . "'");
			if ($free_product_info->num_rows) {
				foreach ($free_product_info->rows as $free_product) {
					$found = false;
					foreach ($this->cart->getProducts() as $cart_product2) {
						if ($free_product['product_id'] == $cart_product2['product_id']) {
							$found = true;
						}
					}
					if (!$found) {
						$this->cart->add($free_product['product_id'], 1, array(), 0);
						$this->session->data['coupon_free'] = 1;
					}
				}
			}
		}
	}//

			
            $this->data['products'] = array();

            $products = $this->cart->getProducts();

				if( ! empty( $this->session->data['mod_groups'] ) ) {
					$this->load->model('module/mod_gifts_gift');

					if( ! $this->cart->hasProducts() ) {
						$this->session->data['mod_groups'] = array();
					} else {
						ModGiftsHelperCart::newInstance( $this, $this->data )->initCartOptions( $products );

						$this->data['mod_groups_info'] = $this->model_module_mod_gifts_gift->getGroupsMaxProducts();
					}
				}
			

            foreach ($products as $product) {
                $product_total = 0;

                foreach ($products as $product_2) {
                    if ($product_2['product_id'] == $product['product_id']) {
                        $product_total += $product_2['quantity'];
                    }
                }

                if ($product['minimum'] > $product_total) {
                    $this->data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
                }

                if ($product['image']) {
                    $image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
                } else {
                    $image = '';
                }

                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['option_value'];
                    } else {
                        $filename = $this->encryption->decrypt($option['option_value']);

                        $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
                    }

                    $option_data[] = array(
                        'name'  => $option['name'],
                        'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                    );
                }

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $total = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']);
                } else {
                    $total = false;
                }
                
                $profile_description = '';
                

				if( empty( $product['recurring'] ) ) {
					$product['recurring'] = '';
				}
				
				if( empty( $product['profile_name'] ) ) {
					$product['profile_name'] = '';
				}
			
                if ($product['recurring']) {
                    $frequencies = array(
                        'day' => $this->language->get('text_day'),
                        'week' => $this->language->get('text_week'),
                        'semi_month' => $this->language->get('text_semi_month'),
                        'month' => $this->language->get('text_month'),
                        'year' => $this->language->get('text_year'),
                    );

                    if ($product['recurring_trial']) {
                        $recurring_price = $this->currency->format($this->tax->calculate($product['recurring_trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')));
                        $profile_description = sprintf($this->language->get('text_trial_description'), $recurring_price, $product['recurring_trial_cycle'], $frequencies[$product['recurring_trial_frequency']], $product['recurring_trial_duration']) . ' ';
                    }

                    $recurring_price = $this->currency->format($this->tax->calculate($product['recurring_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')));

                    if ($product['recurring_duration']) {
                        $profile_description .= sprintf($this->language->get('text_payment_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                    } else {
                        $profile_description .= sprintf($this->language->get('text_payment_until_canceled_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                    }
                }


				//Q: Coupon Free Product
				if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $cfp_total = $this->currency->format($this->tax->calculate($product['cfp_total'], $product['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $cfp_total = false;
                }//
			

			if ($product['auction_id']) {
				$href_auction = '&auction_id=' . $product['auction_id'];
			} else {
				$href_auction = '';
			}
			
                $this->data['products'][] = array(

				'product_id' => $product['product_id'],
			
'cfp_total'               => isset($cfp_total) ? $cfp_total : false, //Q: coupon free product
                    'key'                 => $product['key'],
                    'thumb'               => $image,
                    'name'                => $product['name'],
                    'model'               => $product['model'],

			'auction_id' => $product['auction_id'],
			
                    'option'              => $option_data,
                    'quantity'            => $product['quantity'],
                    'stock'               => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                    'reward'              => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                    'price'               => $price,
                    'total'               => $total,
                    'href'                
			=> $this->url->link('product/product', 'product_id=' . $product['product_id'] . $href_auction),
			

				'href' => ! isset( $product['status'] ) || ! empty( $product['status'] ) ? $this->url->link('product/product', 'product_id=' . $product['product_id']) : $this->url->link('checkout/cart' ),
				'product_id' => $product['product_id'],
				'mod_is_gift' => ! empty( $product['mod_is_gift'] ),
				'mod_is_select' => isset( $product['mod_group_id'] ) && ! empty( $this->session->data['mod_gifts'][$product['mod_group_id']] ) && in_array( $product['product_id'], $this->session->data['mod_gifts'][$product['mod_group_id']] ),
				'mod_group_id' => isset( $product['mod_group_id'] ) ? $product['mod_group_id'] : NULL,
			
                    'remove'              => $this->url->link('checkout/cart', 'remove=' . $product['key']),
                    'recurring'           => $product['recurring'],
                    'profile_name'        => $product['profile_name'],
                    'profile_description' => $profile_description,
                );
            }


            $this->data['products_recurring'] = array();
            
			// Gift Voucher
			$this->data['vouchers'] = array();
			
			if (!empty($this->session->data['vouchers'])) {
				foreach ($this->session->data['vouchers'] as $key => $voucher) {
					$this->data['vouchers'][] = array(
						'key'         => $key,
						'description' => $voucher['description'],
						'amount'      => $this->currency->format($voucher['amount']),
						'remove'      => $this->url->link('checkout/cart', 'remove=' . $key)   
					);
				}
			}

			if (isset($this->request->post['next'])) {
				$this->data['next'] = $this->request->post['next'];
			} else {
				$this->data['next'] = '';
			}
						 
			$this->data['coupon_status'] = $this->config->get('coupon_status');
			
			if (isset($this->request->post['coupon'])) {
				$this->data['coupon'] = $this->request->post['coupon'];			
			} elseif (isset($this->session->data['coupon'])) {
				$this->data['coupon'] = $this->session->data['coupon'];
			} else {
				$this->data['coupon'] = '';
			}
			
			$this->data['voucher_status'] = $this->config->get('voucher_status');
			
			if (isset($this->request->post['voucher'])) {
				$this->data['voucher'] = $this->request->post['voucher'];				
			} elseif (isset($this->session->data['voucher'])) {
				$this->data['voucher'] = $this->session->data['voucher'];
			} else {
				$this->data['voucher'] = '';
			}
			
			$this->data['reward_status'] = ($points && $points_total && $this->config->get('reward_status'));
			
			if (isset($this->request->post['reward'])) {
				$this->data['reward'] = $this->request->post['reward'];				
			} elseif (isset($this->session->data['reward'])) {
				$this->data['reward'] = $this->session->data['reward'];
			} else {
				$this->data['reward'] = '';
			}

			$this->data['shipping_status'] = $this->config->get('shipping_status') && $this->config->get('shipping_estimator') && $this->cart->hasShipping();	
								
			if (isset($this->request->post['country_id'])) {
				$this->data['country_id'] = $this->request->post['country_id'];				
			} elseif (isset($this->session->data['shipping_country_id'])) {
				$this->data['country_id'] = $this->session->data['shipping_country_id'];			  	
			} else {
				$this->data['country_id'] = $this->config->get('config_country_id');
			}
				
			$this->load->model('localisation/country');
			
			$this->data['countries'] = $this->model_localisation_country->getCountries();
						
			if (isset($this->request->post['zone_id'])) {
				$this->data['zone_id'] = $this->request->post['zone_id'];				
			} elseif (isset($this->session->data['shipping_zone_id'])) {
				$this->data['zone_id'] = $this->session->data['shipping_zone_id'];			
			} else {
				$this->data['zone_id'] = '';
			}
			
			if (isset($this->request->post['postcode'])) {
				$this->data['postcode'] = $this->request->post['postcode'];				
			} elseif (isset($this->session->data['shipping_postcode'])) {
				$this->data['postcode'] = $this->session->data['shipping_postcode'];					
			} else {
				$this->data['postcode'] = '';
			}
			
			if (isset($this->request->post['shipping_method'])) {
				$this->data['shipping_method'] = $this->request->post['shipping_method'];				
			} elseif (isset($this->session->data['shipping_method'])) {
				$this->data['shipping_method'] = $this->session->data['shipping_method']['code']; 
			} else {
				$this->data['shipping_method'] = '';
			}
						
			// Totals
			$this->load->model('setting/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_setting_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);			
				}
			}
			
			$this->data['totals'] = $total_data;
						
			$this->data['continue'] = $this->url->link('common/home');
						
			$this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');

            $this->load->model('setting/extension');
            
            $this->data['checkout_buttons'] = array();

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/cart.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/checkout/cart.tpl';
			} else {
				$this->template = 'default/template/checkout/cart.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_bottom',
				'common/content_top',
				'common/footer',
				'common/header'	
			);
						
				
				if( isset( $this->request->post['get_gifts'] ) ) {
					$this->children = array();
					$this->data['column_left'] = $this->data['column_right'] = $this->data['content_bottom'] = $this->data['content_top'] = $this->data['footer'] = $this->data['header'] = '';
				}
				
				$this->data['mod_gifts_settings'] = $this->config->get('mod_gifts_settings');
				
				$this->language->load('module/mod_gifts');
				
				$this->data['button_update'] = $this->language->get( 'button_update' );
				$this->data['button_upload'] = $this->language->get( 'button_upload' );
				$this->data['text_select_gift'] = $this->language->get( 'text_select_gift' );
				$this->data['text_gifts'] = $this->language->get( 'text_gifts' );
				$this->data['text_choose'] = $this->language->get( 'text_choose' );
				$this->data['text_choose_gift'] = $this->language->get( 'text_choose_gift' );
				$this->data['text_choose_gifts'] = $this->language->get( 'text_choose_gifts' );
				$this->data['text_gift'] = $this->language->get( 'text_gift' );
			
			$this->response->setOutput($this->render());					
    	} else {
      		$this->data['heading_title'] = $this->language->get('heading_title');

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

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

			unset($this->session->data['success']);

			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'	
			);
					
				
				if( isset( $this->request->post['get_gifts'] ) ) {
					$this->children = array();
					$this->data['column_left'] = $this->data['column_right'] = $this->data['content_bottom'] = $this->data['content_top'] = $this->data['footer'] = $this->data['header'] = '';
				}
				
				$this->data['mod_gifts_settings'] = $this->config->get('mod_gifts_settings');
				
				$this->language->load('module/mod_gifts');
				
				$this->data['button_update'] = $this->language->get( 'button_update' );
				$this->data['button_upload'] = $this->language->get( 'button_upload' );
				$this->data['text_select_gift'] = $this->language->get( 'text_select_gift' );
				$this->data['text_gifts'] = $this->language->get( 'text_gifts' );
				$this->data['text_choose'] = $this->language->get( 'text_choose' );
				$this->data['text_choose_gift'] = $this->language->get( 'text_choose_gift' );
				$this->data['text_choose_gifts'] = $this->language->get( 'text_choose_gifts' );
				$this->data['text_gift'] = $this->language->get( 'text_gift' );
			
			$this->response->setOutput($this->render());			
    	}
  	}
	
	protected function validateCoupon() {
		$this->load->model('checkout/coupon');
				
		$coupon_info = $this->model_checkout_coupon->getCoupon($this->request->post['coupon']);			
		
		if (!$coupon_info) {			
			$this->error['warning'] = $this->language->get('error_coupon');
		}
		
		if (!$this->error) {
			return true;
		} else {
			return false;
		}		
	}
	
	protected function validateVoucher() {
		$this->load->model('checkout/voucher');
				
		$voucher_info = $this->model_checkout_voucher->getVoucher($this->request->post['voucher']);			
		
		if (!$voucher_info) {			
			$this->error['warning'] = $this->language->get('error_voucher');
		}
		
		if (!$this->error) {
			return true;
		} else {
			return false;
		}		
	}
	
	protected function validateReward() {
		$points = $this->customer->getRewardPoints();
		
		$points_total = 0;
		
		foreach ($this->cart->getProducts() as $product) {
			if ($product['points']) {
				$points_total += $product['points'];
			}
		}	
				
		if (empty($this->request->post['reward'])) {
			$this->error['warning'] = $this->language->get('error_reward');
		}
	
		if ($this->request->post['reward'] > $points) {
			$this->error['warning'] = sprintf($this->language->get('error_points'), $this->request->post['reward']);
		}
		
		if ($this->request->post['reward'] > $points_total) {
			$this->error['warning'] = sprintf($this->language->get('error_maximum'), $points_total);
		}
		
		if (!$this->error) {
			return true;
		} else {
			return false;
		}		
	}
	
	protected function validateShipping() {
		if (!empty($this->request->post['shipping_method'])) {
			$shipping = explode('.', $this->request->post['shipping_method']);
					
			if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {			
				$this->error['warning'] = $this->language->get('error_shipping');
			}
		} else {
			$this->error['warning'] = $this->language->get('error_shipping');
		}
		
		if (!$this->error) {
			return true;
		} else {
			return false;
		}		
	}
								
	public function add() {
		$this->language->load('checkout/cart');
		
		$json = array();
		
		if (isset($this->request->post['product_id'])) {
			$product_id = $this->request->post['product_id'];
		} else {
			$product_id = 0;
		}
		
		$this->load->model('catalog/product');
						
		$product_info = $this->model_catalog_product->getProduct($product_id);
		
		if ($product_info) {			
			if (isset($this->request->post['quantity'])) {
				$quantity = $this->request->post['quantity'];
			} else {
				$quantity = 1;
			}
														
			if (isset($this->request->post['option'])) {
				$option = array_filter($this->request->post['option']);
			} else {
				$option = array();	
			}
            
            if (isset($this->request->post['profile_id'])) {
                $profile_id = $this->request->post['profile_id'];
            } else {
                $profile_id = 0;
            }
			

			if ($this->config->get('config_auction_status_id') && is_array($this->config->get('config_auction_status_id'))) {
				$auction_status_ids = $this->config->get('config_auction_status_id');
			} else {
				$auction_status_ids = array('starting' => 1, 'relisting' => 2, 'inprogress' => 3, 'extended' => 4, 'won' => 5, 'expired' => 6, 'sold' => 7, 'voided' => 8);
			}
			if (!is_null($this->config->get('config_auction_normal_sales'))) {
				$normal_sales = (int)$this->config->get('config_auction_normal_sales');
			} else {
				$normal_sales = 0;
			}
			$this->load->model('catalog/auction');
			$total_auctions = (int)$this->model_catalog_auction->getTotalLiveAuctionsByProductId($product_id, $auction_status_ids);
			if (!$normal_sales && $total_auctions) {
				$json['total_auctions'] = $total_auctions;
			}
			
			$product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
			
			foreach ($product_options as $product_option) {
				if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
					$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
				}
			}
            
            $profiles = $this->model_catalog_product->getProfiles($product_info['product_id']);
            
            if ($profiles) {
                $profile_ids = array();
                
                foreach ($profiles as $profile) {
                    $profile_ids[] = $profile['profile_id'];
                }
                
                if (!in_array($profile_id, $profile_ids)) {
                    $json['error']['profile'] = $this->language->get('error_profile_required');
                }
            }
			
			if (!$json) {
				$this->cart->add($this->request->post['product_id'], $quantity, $option, $profile_id);

				$json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();
				
				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );

				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}

					$this->language->load('checkout/cart');
				}
			

        $this->load->model('module/giftTeaser');
		$giftTeaser = $this->model_module_giftTeaser->getSetting('giftTeaser', $this->config->get('store_id'));
		if (empty($giftTeaser['giftTeaser']['Enabled']) || $giftTeaser['giftTeaser']['Enabled'] == 'no') { } else {
			$this->load->language('module/giftTeaser');
			$prods = $this->cart->getProducts(); 
			$addition = '';
			foreach ($prods as $prod) {
				if ($prod['gift_teaser']==true && !isset($this->session->data['gift_teaser_success'])) {
					$addition = $this->language->get('gift_added_to_cart');
					$this->session->data['gift_teaser_success'] = true;
				}
			}
			if(isset($json['success'])) {
				$json['success'] .= $addition;
			}	
		 }
      
				
				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
				unset($this->session->data['payment_method']);
				unset($this->session->data['payment_methods']);
				
				// Totals
				$this->load->model('setting/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_setting_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['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));
			} else {
				$json['redirect'] = str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
			}
		}
		
		$this->response->setOutput(json_encode($json));		
	}
	
	public function quote() {
		$this->language->load('checkout/cart');
		
		$json = array();	
		
		if (!$this->cart->hasProducts()) {
			$json['error']['warning'] = $this->language->get('error_product');				
		}				

		if (!$this->cart->hasShipping()) {
			$json['error']['warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));				
		}				
		
		if ($this->request->post['country_id'] == '') {
			$json['error']['country'] = $this->language->get('error_country');
		}
		
		if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
			$json['error']['zone'] = $this->language->get('error_zone');
		}
			
		$this->load->model('localisation/country');
		
		$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
		
		if ($country_info && $country_info['postcode_required'] && (utf8_strlen($this->request->post['postcode']) < 2) || (utf8_strlen($this->request->post['postcode']) > 10)) {
			$json['error']['postcode'] = $this->language->get('error_postcode');
		}
						
		if (!$json) {		
			$this->tax->setShippingAddress($this->request->post['country_id'], $this->request->post['zone_id']);
		
			// Default Shipping Address
			$this->session->data['shipping_country_id'] = $this->request->post['country_id'];
			$this->session->data['shipping_zone_id'] = $this->request->post['zone_id'];
			$this->session->data['shipping_postcode'] = $this->request->post['postcode'];
		
			if ($country_info) {
				$country = $country_info['name'];
				$iso_code_2 = $country_info['iso_code_2'];
				$iso_code_3 = $country_info['iso_code_3'];
				$address_format = $country_info['address_format'];
			} else {
				$country = '';
				$iso_code_2 = '';
				$iso_code_3 = '';	
				$address_format = '';
			}
			
			$this->load->model('localisation/zone');
		
			$zone_info = $this->model_localisation_zone->getZone($this->request->post['zone_id']);
			
			if ($zone_info) {
				$zone = $zone_info['name'];
				$zone_code = $zone_info['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}	
		 
			$address_data = array(
				'firstname'      => '',
				'lastname'       => '',
				'company'        => '',
				'address_1'      => '',
				'address_2'      => '',
				'postcode'       => $this->request->post['postcode'],
				'city'           => '',
				'zone_id'        => $this->request->post['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $this->request->post['country_id'],
				'country'        => $country,	
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'address_format' => $address_format
			);
		
			$quote_data = array();
			
			$this->load->model('setting/extension');
			
			$results = $this->model_setting_extension->getExtensions('shipping');
			
			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('shipping/' . $result['code']);
					
					$quote = $this->{'model_shipping_' . $result['code']}->getQuote($address_data); 
		
					if ($quote) {
						$quote_data[$result['code']] = array( 
							'title'      => $quote['title'],
							'quote'      => $quote['quote'], 
							'sort_order' => $quote['sort_order'],
							'error'      => $quote['error']
						);
					}
				}
			}
	
			$sort_order = array();
		  
			foreach ($quote_data as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}
	
			array_multisort($sort_order, SORT_ASC, $quote_data);
			
			$this->session->data['shipping_methods'] = $quote_data;
			
			if ($this->session->data['shipping_methods']) {
				$json['shipping_method'] = $this->session->data['shipping_methods']; 
			} else {
				$json['error']['warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
			}				
		}	
		
		$this->response->setOutput(json_encode($json));						
	}
	

        public function giftTeaserOptions() {
        $this->language->load('module/giftTeaser');
        $this->load->model('catalog/product');
        $this->load->model('tool/image');
        
        $this->document->addStyle('catalog/view/theme/default/stylesheet/giftTeaser.css');
        
        $product_info= $this->model_catalog_product->getProduct($this->request->get['product_id']);
        $product_options = $this->model_catalog_product->getProductOptions($this->request->get['product_id']);
        
        if ($product_info['image']) {
            $image = $this->model_tool_image->resize($product_info['image'], 80, 80);
            } 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($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
            } else {
                $price = false;
            }
                    
            if ((float)$product_info['special']) {
                $special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $TotalPrice+=$this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax'));                  
            } else {
                $TotalPrice+=$this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax'));
                $special = false;
            }*/
            
            if ($this->config->get('config_review_status')) {
                $rating = (int)$product_info['rating'];
            } else {
                $rating = false;
            }
            
            $product_options = $this->model_catalog_product->getProductOptions($product_info['product_id']);
            $this->data['options'] = array();
        
            foreach ($product_options 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)) {
                            if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                                $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                            } else {
                                $price = false;
                            }
        
                            $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'                   => $price,
                                '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']
                    );                      
                }
            }
        
        $this->data['gift'] = array(
            'product_id' => $product_info['product_id'],
            'thumb'      => $image,
            'name'       => $product_info['name'],
            /*'price'        => $price,
            'special'    => $special,*/
            'rating'     => $rating,
            'reviews'    => sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']),
            'href'       => $this->url->link('product/product', 'product_id=' . $product_info['product_id']),
            'options' => $this->data['options']
        );
        
        $this->data['text_select'] = $this->language->get('text_select');
        $this->data['text_option'] = $this->language->get('text_option');
        $this->data['text_option_heading'] =  $this->language->get('gift_added_to_cart');
        $this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['button_cart'] = $this->language->get('button_cart');
        $this->data['Continue'] = $this->language->get('Continue');
 
        //$this->data['currenttemplate'] =  $this->config->get('config_template');
        if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
            $this->data['data']['giftTeaser'] = str_replace('http', 'https', $this->config->get('giftTeaser'));
        } else {
            $this->data['data']['giftTeaser'] = $this->config->get('giftTeaser');
        }
        
        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/giftTeaser/giftteaser_options.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/module/giftTeaser/giftteaser_options.tpl';
        } else {
            $this->template = 'default/template/module/giftTeaser/giftteaser_options.tpl';
        }
        
				
				if( isset( $this->request->post['get_gifts'] ) ) {
					$this->children = array();
					$this->data['column_left'] = $this->data['column_right'] = $this->data['content_bottom'] = $this->data['content_top'] = $this->data['footer'] = $this->data['header'] = '';
				}
				
				$this->data['mod_gifts_settings'] = $this->config->get('mod_gifts_settings');
				
				$this->language->load('module/mod_gifts');
				
				$this->data['button_update'] = $this->language->get( 'button_update' );
				$this->data['button_upload'] = $this->language->get( 'button_upload' );
				$this->data['text_select_gift'] = $this->language->get( 'text_select_gift' );
				$this->data['text_gifts'] = $this->language->get( 'text_gifts' );
				$this->data['text_choose'] = $this->language->get( 'text_choose' );
				$this->data['text_choose_gift'] = $this->language->get( 'text_choose_gift' );
				$this->data['text_choose_gifts'] = $this->language->get( 'text_choose_gifts' );
				$this->data['text_gift'] = $this->language->get( 'text_gift' );
			
        $this->response->setOutput($this->render());
    }
    
    public function checkGifts() { 
        $this->load->model('module/giftTeaser');
        $giftTeaser = $this->model_module_giftTeaser->getSetting('giftTeaser', $this->config->get('store_id'));
    
        if (empty($giftTeaser['giftTeaser']['Enabled']) || $giftTeaser['giftTeaser']['Enabled'] == 'no') { } else {
            $this->load->language('module/giftTeaser');
            
            $prods = $this->cart->getProducts();
        
            foreach ($prods as $key => $val) {
                if (!empty($val['gift_teaser'])) {
                  if(!empty($val['option'])) { 
                      if (isset($this->session->data['cart'][$key])) {
                        unset($this->session->data['cart'][$key]);
                        $this->data = array();
                      }
                  }
                }
              }
            
            $addition = '';
            $gifts = $this->cart->getAllGifts();
            $cart_products = array_map(create_function('$a', 'return $a["product_id"];'), $this->cart->getProducts());
 
          if (empty($cart_products)) return;
 
          $eligible_gifts = array();
 		  $products = $this->cart->getProducts();

				if( ! empty( $this->session->data['mod_groups'] ) ) {
					$this->load->model('module/mod_gifts_gift');

					if( ! $this->cart->hasProducts() ) {
						$this->session->data['mod_groups'] = array();
					} else {
						ModGiftsHelperCart::newInstance( $this, $this->data )->initCartOptions( $products );

						$this->data['mod_groups_info'] = $this->model_module_mod_gifts_gift->getGroupsMaxProducts();
					}
				}
			
 
          foreach ($gifts as $gift) {
            $properties = unserialize($gift['condition_properties']);
            $to_add = null;
            $to_add_quantity = (int)$gift['minimum'];
 
            switch ($gift['condition_type']) {
              case '1' : {
                if ((int)$properties['total'] < $this->cart->getTotal() && (int)$properties['total_max'] > $this->cart->getTotal()) {
                  $to_add = $gift['product_id'];
                }
 
              } break;
 
             case '2' : {
                $eligible_products = array_intersect($properties['certain'], $cart_products);
                $add_gift= array();
                if(isset($eligible_products)) {
                    foreach($eligible_products as $eligible_product) {
                        unset($quantity);
                        $quantity=array();
                        foreach($products as $key => $value) {
                             $exp_key = explode(':', $key);
                             if($exp_key[0] == $eligible_product){
                                 $quantity[] = $value['quantity'];
                            }
                        }
                        if(count($quantity) > 1 ) {
                            $quantity = array_sum($quantity);
                        } else {
                            $quantity = $quantity[0];
                        }
                        
                        if($quantity >= $properties['certain_product_quantity'] ) {
                            $add_gift[] = 'true';
                        } else {
                            $add_gift[] = 'false';
                        }
                    } 
                }
                if (in_array("false", $add_gift)) {
                    $quantity_reached = false;
                } else {
                    $quantity_reached = true;
                }
 
                if (
                  isset($properties['certain']) &&
                  array_values(array_intersect($properties['certain'], $cart_products)) === array_values($properties['certain']) &&
                  $quantity_reached
                ) {
                  $to_add = $gift['product_id'];
                
                }
 
              } break;
 
              case '3' : {
                $eligible_products = array_intersect($properties['some'], $cart_products);
                $add_gift= array();
                foreach($eligible_products as $eligible_product) {
                    unset($quantity);
                    $quantity=array();
                    foreach($products as $key => $value) {
                             $exp_key = explode(':', $key);
                             if($exp_key[0] == $eligible_product){
                                 $quantity[] = $value['quantity'];
                            }
                        }
                        if(count($quantity) > 1 ) {
                            $quantity = array_sum($quantity);
                        } else {
                            $quantity = $quantity[0];
                        }
                        
                        if($quantity >= $properties['some_product_quantity'] ) {
                        $add_gift[] = 'true';
                    } else {
                        $add_gift[] = 'false';
                    }
                } 
                if (in_array("true", $add_gift)) {
                    $quantity_reached = true;
                } else {
                    $quantity_reached = false;
                }
                if (
                  isset($properties['some']) &&
                  count(array_intersect($properties['some'], $cart_products)) &&
                  $quantity_reached 
                ) { 
                  $to_add = $gift['product_id'];
                }
 
              } break; 
 
              case '4' : {
                if (
                  isset($properties['categories']) &&
                  $this->cart->categoriesHaveProducts($properties['categories'], $cart_products)
                ) {
                  $to_add = $gift['product_id'];
                }
 
              } break;
 
            }
 
            if (
              !empty($this->session->data['gift_teaser_exclude']) && 
              in_array($to_add, $this->session->data['gift_teaser_exclude'])
            ) {
              continue;
            }
 
            if (!empty($to_add)) {
              for ($i = 0; $i < $to_add_quantity; $i++) {
                $eligible_gifts[] = $to_add;
              }
            }
          }
 
          $option_key = 'gift_teaser';
          $json['gifts_with_options'] = false;
          foreach ($eligible_gifts as $eligible_gift) {
                $product_options = $this->db->query("SELECT po.product_id, po.option_value_id as option_index, ovp.name FROM `". DB_PREFIX . "product_option_value` po LEFT JOIN `" . DB_PREFIX . "option_value_description` ovp ON (po.option_value_id = ovp.option_value_id) WHERE po.product_id=".(int)$eligible_gift)->rows;
                if(!empty($product_options)) {
                    
                    //$key = (int)$eligible_gift . ':';
                    $key = base64_encode(serialize($option_key));  
                    $containts_gift = array();
                    foreach($this->session->data['cart'] as $k => $v){
                        if (strpos($k,$key) !== false) {
                            $contains_gift[]='true';
                        } else {
                            $contains_gift[]='false';
                        }
                    }
                    
                    if (!in_array('true', $contains_gift)) {
                        $json['gifts_with_options'] = $eligible_gift;
                    } else {
                        $json['gifts_with_options'] = false;
                    }
                } else {
                    $json['gifts_with_options'] = false;
 
                }
          }
 
            $this->response->setOutput(json_encode($json));   
        }
    }
     
    public function GiftAdd() { 
        $this->language->load('checkout/cart');
 
        $json = array();
 
        if (isset($this->request->post['product_id'])) {
            $product_id = $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }
 
        $this->load->model('catalog/product');
 
        $product_info = $this->model_catalog_product->getProduct($product_id);
 
        if ($product_info) {            
            if (isset($this->request->post['quantity'])) {
                $quantity = $this->request->post['quantity'];
            } else {
                $quantity = 1;
            }
 
            if (isset($this->request->post['option'])) {
                $option = array_filter($this->request->post['option']);
            } else {
                $option = array();  
            }
 
            if (isset($this->request->post['profile_id'])) {
                $profile_id = $this->request->post['profile_id'];
            } else {
                $profile_id = 0;
            }
 

			if ($this->config->get('config_auction_status_id') && is_array($this->config->get('config_auction_status_id'))) {
				$auction_status_ids = $this->config->get('config_auction_status_id');
			} else {
				$auction_status_ids = array('starting' => 1, 'relisting' => 2, 'inprogress' => 3, 'extended' => 4, 'won' => 5, 'expired' => 6, 'sold' => 7, 'voided' => 8);
			}
			if (!is_null($this->config->get('config_auction_normal_sales'))) {
				$normal_sales = (int)$this->config->get('config_auction_normal_sales');
			} else {
				$normal_sales = 0;
			}
			$this->load->model('catalog/auction');
			$total_auctions = (int)$this->model_catalog_auction->getTotalLiveAuctionsByProductId($product_id, $auction_status_ids);
			if (!$normal_sales && $total_auctions) {
				$json['total_auctions'] = $total_auctions;
			}
			
            $product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
 
            foreach ($product_options as $product_option) {
                if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                    $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
                }
            }
 
            $profiles = $this->model_catalog_product->getProfiles($product_info['product_id']);
 
            if ($profiles) {
                $profile_ids = array();
 
                foreach ($profiles as $profile) {
                    $profile_ids[] = $profile['profile_id'];
                }
 
                if (!in_array($profile_id, $profile_ids)) {
                    $json['error']['profile'] = $this->language->get('error_profile_required');
                }
                
            }
            if (!$json) { 
                    
                    //$option_key = 'gift_teaser';
 
                    //$key = (int)$this->request->post['product_id'] . ':';
                    //$key .= base64_encode(serialize($option_key)) . ':';
 
                $this->cart->add($this->request->post['product_id'], $quantity, $option, $profile_id, $gift = true);
 
                $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));

				$this->load->model('module/mod_gifts_gift');
				$this->session->data['mod_groups'] = array();
				
				$modGroups = $this->model_module_mod_gifts_gift->getGroupsByCart( ModGiftsHelperCart::newInstance( $this, $this->data )->getCartTotal() );

				if( $modGroups ) {
					$this->language->load('module/mod_gifts');

					$modItems = array();

					foreach( $modGroups as $item ) {
						if( ! isset( $this->session->data['mod_groups'][$item['group_id']] ) ) {
							if( $item['notification'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['notification'] );
							elseif( $item['name'] )
								$modItems[] = str_replace( array( '{currency}', '{amount}' ), array( $this->currency->getCode(), round( $item['amount'] * $this->currency->getValue(), 2 ) ), $item['name'] );

							$this->session->data['mod_groups'][$item['group_id']] = $item;
						}
					}

					if( isset( $json['success'] ) && $modItems ) {
						$json['success'] .= '<br /><br />';
						$json['success'] .= implode( '<br /><br />', $modItems );
					}

					$this->language->load('checkout/cart');
				}
			
 
        $this->load->model('module/giftTeaser');
        $giftTeaser = $this->model_module_giftTeaser->getSetting('giftTeaser', $this->config->get('store_id'));
        if (empty($giftTeaser['giftTeaser']['Enabled']) || $giftTeaser['giftTeaser']['Enabled'] == 'no') { } else {
            $this->load->language('module/giftTeaser');
            $prods = $this->cart->getProducts(); 
            $addition = '';
            
            foreach ($prods as $prod) {
                if ($prod['gift_teaser']==true && !isset($this->session->data['gift_teaser_success'])) {
                    $addition = $this->language->get('gift_added_to_cart');
                    $this->session->data['gift_teaser_success'] = true;
                }
            }
            if(isset($json['success'])) {
                $json['success'] .= $addition;
            }   
         }
      
 
                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);
 
            /*  // Totals
                $this->load->model('setting/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_setting_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['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)); */
            } else {
                $json['redirect'] = str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
            }
        }
 
        $this->response->setOutput(json_encode($json));       
    }
      
	public function country() {
		$json = array();
		
		$this->load->model('localisation/country');

    	$country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);
		
		if ($country_info) {
			$this->load->model('localisation/zone');

			$json = array(
				'country_id'        => $country_info['country_id'],
				'name'              => $country_info['name'],
				'iso_code_2'        => $country_info['iso_code_2'],
				'iso_code_3'        => $country_info['iso_code_3'],
				'address_format'    => $country_info['address_format'],
				'postcode_required' => $country_info['postcode_required'],
				'zone'              => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
				'status'            => $country_info['status']		
			);
		}
		
		$this->response->setOutput(json_encode($json));
	}
}
?>
