<?php
class ModelModuleGiftTeaser extends Model {
  
	public function getCurrentGifts() {
		return $this->db->query("SELECT *, gt.description AS description 
								 FROM `". DB_PREFIX . "gift_teaser` gt
								 JOIN " . DB_PREFIX . "product p ON gt.item_id=p.product_id
								 JOIN " . DB_PREFIX . "product_description pd ON p.product_id=pd.product_id
								 WHERE start_date<" . time(). " 
								 AND end_date>" . time() ." 
								 AND store_id=" . $this->config->get('store_id') . " 
								 AND language_id=" . $this->config->get('config_language_id') . 
							 	 " ORDER BY gt.sort_order ASC")->rows;	
	}

	public function updateGiftsInCart($key = null) {
		$setting = $this->getSetting('giftTeaser', $this->config->get('store_id'));
		if(isset($setting['giftTeaser']['Enabled']) && $setting['giftTeaser']['Enabled'] == 'yes') {
			$eligibleGifts = $this->getEligibleGifts(50, 50);
			$key = explode(':', $key); 
			if(isset($key[1])) {
				$option = (unserialize(base64_decode($key[1])));
				if(isset($option['giftTeaser']) && $option['giftTeaser'] == 'giftTeaser') {
					$this->session->data['excludedGifts'][] = $key[0];  
				}
			}	
			$giftCountBeforeUpdate = count($this->model_module_giftTeaser->getGiftsFromCart());
			$this->removeGiftsFromCart();
			if(!empty($this->session->data['excludedGifts'])){
				foreach ($eligibleGifts as $key => $gift) { 
					if(in_array($gift['item_id'], $this->session->data['excludedGifts'])){
						unset($eligibleGifts[$key]);
					}
				} 
			}
			$this->addGiftsToCart($eligibleGifts);	
	
			if($giftCountBeforeUpdate < count($this->model_module_giftTeaser->getGiftsFromCart())){
				$this->session->data['gift_added_to_cart'] = TRUE;
			}	
		}
	}
	
	public function addGiftsToCart($gifts) {
		foreach ($gifts as $key => $gift) {
			$this->cart->add($gift['item_id'], 1, array('giftTeaser' => 'giftTeaser'));		
			$this->session->data['cartGifts'][] = $gift['item_id']; 	
		}
	}
	
	public function removeGiftsFromCart(){
		$giftsInCart = $this->getGiftsFromCart(); 			
		if(!empty($giftsInCart)) {
			foreach ($giftsInCart as $key => $gift) {
				$this->cart->remove($gift);
			}
		}
	}
	
	public function getGiftsFromCart() { 
		$gifts = array();
		foreach ($this->session->data['cart'] as $key => $k) {
			$explode = explode(':', $key); 
			$option = unserialize(base64_decode($explode[1]));
			if(!empty($option) && in_array('giftTeaser', $option)) {
				$gifts[] = $key;
			}
		}
		return $gifts;
	}
	
	public function getEligibleGifts($width = 50, $height = 50){
		$eligibleGifts = array(); 
		$cart = array_map(create_function('$a', 'return $a[\'product_id\'];'), $this->cart->getProducts());
		foreach ($this->getCurrentGifts() as $gift) {
			$properties =  unserialize($gift['condition_properties']);
			switch ($gift['condition_type']) {
				case '1': $properties['total'] < $this->cart->getTotal() - $this->session->data['giftTeaserTotal'] ? $eligibleGifts[] = $gift : false; break;
				case '2': isset($properties['certain']) && array_intersect($properties['certain'], $cart) === $properties['certain'] ? $eligibleGifts[] = $gift : false; break;
				case '3': isset($properties['some']) && count(array_intersect($properties['some'], $cart)) > 0 ? $eligibleGifts[] = $gift : false; break; 
				case '4': isset($properties['categories']) && count(array_intersect($this->getProductsFromCategories($properties['categories']), $cart)) > 0 ? $eligibleGifts[] = $gift : false; break;; 
				default: $description = ''; break;
			}
		}
		$this->resizeGiftImages($eligibleGifts, $width, $height);
		$this->session->data['eligibleGifts'] = $eligibleGifts;
		return $eligibleGifts;
	}
	
	public function resizeGiftImages(&$gifts = array(), $width = 50, $height = 50) {
		$this->load->model('tool/image');
		foreach ($gifts as $key => $gift) {
			$gifts[$key]['image'] = $this->model_tool_image->resize($gift['image'], $width, $height);  
		}
	}
	
	private function getProductsFromCategories($categories = array()) {
		if(!empty($categories)) {
		 	$products = $this->db->query("SELECT product_id FROM " . DB_PREFIX . "product_to_category WHERE category_id IN (" . implode(',', $categories) . ")")->rows;
			return array_map(create_function('$a', 'return $a[\'product_id\'];'), $products);
		}
	}
	
  	public function getSetting ($group, $store_id) {
    	$data = array(); 
    	$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");
    	foreach ($query->rows as $result) {
      		if (!$result['serialized']) {
        		$data[$result['key']] = $result['value'];
      		} else {
        		$data[$result['key']] = unserialize($result['value']);
      		}
    	} 
    	return $data;
  	}
	
}
?>