<?php
class ModelExtensionTotalSalescombo extends Model {
	public function getTotal($total) {
		$this->load->language('extension/total/salescombo');
	    $totaldiscount = array();
	    $this->session->data['salescombo_netdiscount']  = 0;
		foreach ($this->cart->getProducts() as $product) {
		    $key = $product['cart_id'];
			if(isset($this->session->data['cartbindercombooffers'][$key])) {
				$discount = 0;
				if(isset($totaldiscount[$this->session->data['cartbindercombooffers'][$key]['variation']][$this->session->data['cartbindercombooffers'][$key]['id']])) {
					$discount = round($totaldiscount[$this->session->data['cartbindercombooffers'][$key]['variation']][$this->session->data['cartbindercombooffers'][$key]['id']]['discountdone'],2);
				}
	        	$totaldiscount[$this->session->data['cartbindercombooffers'][$key]['variation']][$this->session->data['cartbindercombooffers'][$key]['id']] = array(
				'discountdone'	=> $discount + $this->session->data['cartbindercombooffers'][$key]['discountdone'],
	    		'name' => $this->session->data['cartbindercombooffers'][$key]['name']
	    		);
				$this->session->data['salescombo_netdiscount'] += $this->session->data['cartbindercombooffers'][$key]['discountdone'];

				$this->session->data['salescombo_netdiscount'] = round($this->session->data['salescombo_netdiscount'],2);

		    }
		}

		foreach ($totaldiscount as $variation => $disounts) {
			foreach ($disounts as $key => $value) {
				$value['discountdone'] = round($value['discountdone'],2);
				$charge = $this->currency->format($value['discountdone'], $this->session->data['currency']);
				$total['totals'][] = array(
				'code'       => 'salescombo',
				'title'      => sprintf($this->language->get('text_salescombo'),$value['name'],$charge),
				'value'      => -$value['discountdone'],
				'sort_order' => $this->config->get('total_salescombo_sort_order')
				);
				$total['total'] -= $value['discountdone'];
			}
		}
	}

	public function getAvailableOffers($product_id) {
		$availableoffers['notab'] = "";
		$availableoffers['tab'] = "";
		return $availableoffers;
	}

	public function checkCg($cids = array()) {
  		$cggrup = json_decode($cids,true);
        if(!empty($cggrup)) {
        	$cgid = $this->customer->getGroupId();
         	if(!in_array($cgid, $cggrup)) {
            	return 1;
         	}
        }
        return 0;
    }

	public function optionnames($optionids) {
		$optionarray = explode(",", $optionids);

		$name = $out = "";
		foreach ($optionarray as $key => $value) {
			$optionname =  $this->getOptionName($value);
			$name .= $out.$optionname;
			$out = "<br>";
		}
		return $name;

	}

	public function getOptionName($product_option_value_id) {
		if($product_option_value_id) {
			$product_option_value_query = $this->db->query("SELECT ovd.name as name FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (pov.option_value_id = ovd.option_value_id)  WHERE pov.product_option_value_id = '" . (int)$product_option_value_id . "' AND ovd.language_id = '".$this->config->get('config_language_id')."' ");
			if($product_option_value_query->num_rows) {
				return $product_option_value_query->row['name'];
			}
		}
		return "";
	}

	public function generateOffer($value = array()) {
		  $primaryarray = explode(",",$value['primarypids']);
		  // $customarray = explode(",",$value['custompids']);
	      $this->load->model("catalog/product");
	      $this->load->model("catalog/category");
	      $this->load->model("extension/module/salescombopge");
	      $this->load->model('tool/image');
	      $data['offers'][$value['id']]['id'] = $value['variation']."_".$value['id'];
	      $data['offers'][$value['id']]['name'] = $value['name'];
	      $data['offers'][$value['id']]['bundle'] = isset($value['bundle'])?$value['bundle']:0;

	      if($value['type']) {
	        $discount = $this->currency->format($value['discount'], $this->session->data['currency']);
	        $data['offers'][$value['id']]['offervalue'] = sprintf($this->language->get("fixedoff"),$discount);
	      } else {
	        $data['offers'][$value['id']]['offervalue'] = sprintf($this->language->get("percentageoff"),$value['discount']);
	      }
	      if(isset($value['extras']) && $value['extras']) {
	      	$data['offers'][$value['id']]['offervalue'] = 0;
	      }
	      $data['offers'][$value['id']]['offerpage'] = "";
	      if($value['sales_offer_id']) {
	        $salescombopge_info = $this->model_extension_module_salescombopge->getPage($value['sales_offer_id']);
	        if ($salescombopge_info) {
	          $url = $this->url->link('extension/module/salescombopge', 'page_id=' .  $value['sales_offer_id'], "SSL");
	          $data['offers'][$value['id']]['offerpage'] = sprintf($this->language->get('readmore_offerpage'), $url, $salescombopge_info['title']);
	        }
	      }

	      $data['offers'][$value['id']]['addproducts'] = array();
	      foreach ($primaryarray as $key => $product_id) {
	        $product_info = $this->model_catalog_product->getProduct($product_id);
	        if(empty($product_info)) {
	        	return array();
	        }
	        $product_name = $product_info['name'];
	        if ($product_info['image']) {
	          $thumb = $this->model_tool_image->resize($product_info['image'], 75, 75);
	        } else {
	          $thumb = $this->model_tool_image->resize('placeholder.png', 75, 75);
	        }
	        if($value['variation'] == 6) {
	        	$optionnames = $this->optionnames($value['optionids']);
	        } else {
	        	$optionnames = "";
	        }
					
	        $data['offers'][$value['id']]['addproducts'][] = array(
	          'name' => $product_name,
	          'product_id' => $product_id,
	          'href' => $this->url->link('product/product', 'product_id=' . $product_id, TRUE),
	          'thumb' => $thumb,
	          'customqty' => $value['customquant'],
	          'priqty' => $value['primaryquant'],
	          'secqty' => $value['secondaryquant'],
	          'optionnames' => $optionnames,
	        );

					// custom
					// $data['offers'][$value['id']]['caddproducts'][] = array(
	        //   'name' => $product_name,
	        //   'product_id' => $product_id,
	        //   'href' => $this->url->link('product/product', 'product_id=' . $product_id, TRUE),
	        //   'thumb' => $thumb,
	        //   'customqty' => $value['customquant'],
	        //   'priqty' => $value['primaryquant'],
	        //   'secqty' => $value['secondaryquant'],
	        //   'optionnames' => $optionnames,
	        // );
					// End of custom
	      }

	      if($value['variation'] == 3 || $value['variation'] == 6) {
	      	$data['offers'][$value['id']]['getproducts'] = $data['offers'][$value['id']]['addproducts'];
	      } else if ($value['variation'] == 5) {
	      	$secondaryarray = explode(",",$value['secondarycids']);
		    $data['offers'][$value['id']]['getcategories'] = array();
		    foreach ($secondaryarray as $key => $category_id) {
		        $category_info = $this->model_catalog_category->getCategory($category_id);
		        if(empty($category_info)) {
		        	return array();
		        }
		        $category_name = $category_info['name'];
		        if ($category_info['image']) {
		          $thumb = $this->model_tool_image->resize($category_info['image'], 75, 75);
		        } else {
		          $thumb = $this->model_tool_image->resize('placeholder.png', 75, 75);
		        }
		        $data['offers'][$value['id']]['getcategories'][] = array(
		          'name' => $category_name,
		          'href' => $this->url->link('product/category', 'path=' . $category_id, TRUE),
		          'thumb' => $thumb,
		          'secqty' => $value['secondaryquant'],
		        );
		    }
	      } else if($value['variation'] == 1) {
	      	$secondaryarray = explode(",",$value['secondarypids']);
	        $data['offers'][$value['id']]['getproducts'] = array();
	        foreach ($secondaryarray as $key => $product_id) {
		        $product_info = $this->model_catalog_product->getProduct($product_id);
		        if(empty($product_info)) {
		        	return array();
		        }
		        $product_name = $product_info['name'];
		        if ($product_info['image']) {
		          $thumb = $this->model_tool_image->resize($product_info['image'], 75, 75);
		        } else {
		          $thumb = $this->model_tool_image->resize('placeholder.png', 75, 75);
		        }
		        $data['offers'][$value['id']]['getproducts'][] = array(
		          'name' => $product_name,
		          'product_id' => $product_id,
		          'href' => $this->url->link('product/product', 'product_id=' . $product_id, TRUE),
		          'thumb' => $thumb,
		          'secqty' => $value['secondaryquant'],
							// 'test' => $value['variation'],
		        );
	        }

					// custom code
					$customarray = explode(",",$value['custompids']);
	        $data['offers'][$value['id']]['getproducts'] = array();
	        foreach ($customarray as $key => $product_id) {
		        $product_info = $this->model_catalog_product->getProduct($product_id);
		        if(empty($product_info)) {
		        	return array();
		        }
		        $product_name = $product_info['name'];
		        if ($product_info['image']) {
		          $thumb = $this->model_tool_image->resize($product_info['image'], 75, 75);
		        } else {
		          $thumb = $this->model_tool_image->resize('placeholder.png', 75, 75);
		        }
		        $data['offers'][$value['id']]['getproducts'][] = array(
		          'name' => $product_name,
		          'product_id' => $product_id,
		          'href' => $this->url->link('product/product', 'product_id=' . $product_id, TRUE),
		          'thumb' => $thumb,
		          // 'secqty' => $value['secondaryquant'],
		          'customqty' => $value['customquant'],

		        );
	        }
					// End of custom code

	      }
	      return $data['offers'];
	}

	public function addOffersDetails($order_id) {
		$this->deleteOldOffers($order_id);
		foreach ($this->cart->getProducts() as $product) {
			$key = $product['cart_id'];
			if(isset($this->session->data['cartbindercombooffers'][$key])) {

				$offerdetails = $this->session->data['cartbindercombooffers'][$key];
				$type = ($this->session->data['cartbindercombooffers'][$key]['type'])?"Fixed":"Percentage";
			      if($this->session->data['cartbindercombooffers'][$key]['variation'] == 1) {
			        $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo1 SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' ,secondarypids = '".$offerdetails['secondarypids']."',discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 2) {
			        $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo2 SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarycids = '".$offerdetails['primarycids']."' ,secondarypids = '".$offerdetails['secondarypids']."',secondarycids = '".$offerdetails['secondarycids']."' ,discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 3) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo1a SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' ,discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			     } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 4) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo2a SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarycids = '".$offerdetails['primarycids']."' ,discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      }  else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 5) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo1b SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' , secondarycids = '".$offerdetails['secondarycids']."' , discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 6) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo1c SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' , optionids = '".$offerdetails['optionids']."' , discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 7) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo_custom SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' , secondarypids = '".$offerdetails['secondarypids']."' , discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      } else if($this->session->data['cartbindercombooffers'][$key]['variation'] == 8) {
			         $this->db->query("INSERT INTO " . DB_PREFIX . "cartbindercombo_custom2 SET order_id = '" . (int)$order_id . "',offer_id = '" . (int)$offerdetails['id'] . "', customer_id = '" . (int)$this->customer->getId() . "', type = '" . $type . "',name = '" . $offerdetails['name'] . "', primarypids = '".$offerdetails['primarypids']."' , secondarypids = '".$offerdetails['secondarypids']."' , discount = '".$offerdetails['discount']."',total = '" . (float)$offerdetails['discountdone'] . "'");
			      }
	      	}
	  	}
	}

	public function deleteOldOffers($order_id) {

	}

	public function total() {
		$message['success'] = $message['warning'] = array();
		$this->load->language('extension/module/salescombopage');
		$this->load->model('extension/module/salescombopge');
		$this->session->data['cartbindercombooffers_pages'] = array_unique($this->session->data['cartbindercombooffers_pages']);

		foreach ($this->session->data['cartbindercombooffers_pages'] as $key => $value) {
			$url = $this->url->link('extension/module/salescombopge', 'page_id=' .  $value);
			$salescombopge_info = $this->model_extension_module_salescombopge->getPage($value);
			if ($salescombopge_info) {
				if($this->customer->getId()) {
					$name = $this->customer->getFirstName();
					if($salescombopge_info['bottom']) {
						$message['warning'][] = 	sprintf($this->language->get('eligibleforgifttotalcustomerpopup'),$name,$salescombopge_info['title'],$value);
					} else {
						$message['warning'][] = 	sprintf($this->language->get('eligibleforgifttotalcustomer'),$name,$salescombopge_info['title'],$url);
					}
		 		} else {
		 			if($salescombopge_info['bottom']) {
						$message['warning'][] = 	sprintf($this->language->get('eligibleforgifttotalpopup'),$salescombopge_info['title'],$value);
					} else {
						$message['warning'][] = 	sprintf($this->language->get('eligibleforgifttotal'),$salescombopge_info['title'],$url);
					}
				}
			}
		}
		$this->session->data['cartbindercombooffers_offerapplied'] = array_unique($this->session->data['cartbindercombooffers_offerapplied']);
		foreach ($this->session->data['cartbindercombooffers_offerapplied'] as $key => $value) {
			$url = $this->url->link('extension/module/salescombopge', 'page_id=' .  $value);
			$salescombopge_info = $this->model_extension_module_salescombopge->getPage($value);
			if ($salescombopge_info) {
				if($this->customer->getId()) {
					$name = $this->customer->getFirstName();
					if($salescombopge_info['bottom']) {
						$message['success'][] = 	sprintf($this->language->get('appliedgifttotalcustomerpopup'),$name,$salescombopge_info['title'],$value);
					} else {
						$message['success'][] = 	sprintf($this->language->get('appliedgifttotalcustomer'),$name,$salescombopge_info['title'],$url);
					}
		 		} else {
		 			if($salescombopge_info['bottom']) {
						$message['success'][] = 	sprintf($this->language->get('appliedgifttotalpopup'),$salescombopge_info['title'],$value);
					} else {
						$message['success'][] = 	sprintf($this->language->get('appliedgifttotal'),$salescombopge_info['title'],$url);
					}
				}
			}
		}
		return $message;
	}
}
