<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, Openzc, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class openzcajax{
	
    function ajaxRun($data){
		global $product_class;
		$action=$data['action'];
		$_GET['action']=$action;
		$msgbox=true;
		switch($action){
			case "delCart":
			    if(array_key_exists($data['id'],$_SESSION['cart']->contents)){
				   $_SESSION['cart']->remove($data['id']);
				   $data['status']=true;
			    }
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCart";
					}else{
						$data['reload']="#msgOpenzc:msgCart";
					}
				}
			break;
			case "cartQty":
				global $predata_class;
				$options=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS);
				$stock=zen_get_products_stock($data['id']);
				if(!is_numeric($data['value'])){
					$new_qty=$_SESSION['cart']->get_quantity($data['id']);
				}else{
					$new_qty=$data['value'];
				}
				if($new_qty>=$stock){$new_qty=$stock;}
				if($new_qty==0){
					$_SESSION['cart']->remove($data['id']);
				}else{
					$attributes = $_SESSION['cart']->contents[$data['id']]['attributes'] ? $_SESSION['cart']->contents[$data['id']]['attributes'] : '';
					if(isset($_SESSION['cart']->contents[$data['id']]['attributes_values'])){
						foreach($_SESSION['cart']->contents[$data['id']]['attributes_values'] as $k => $v){
							if($options[$k]['products_options_type']==1){
								$attributes["txt_".$k]=$v;
								unset($attributes[$k]);
							}
						}
					}
					$_SESSION['cart']->add_cart($data['id'], $new_qty, $attributes, false);
				}
				$data['status']=true;
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCart";
					}else{
						$data['reload']="#msgOpenzc:msgCart";
					}
				}
			break;
			case "addOne":
				global $predata_class;
				$options=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS);
				
				$new_qty = $_SESSION['cart']->get_quantity($data['id'])+1;
				$attributes = $_SESSION['cart']->contents[$data['id']]['attributes'] ? $_SESSION['cart']->contents[$data['id']]['attributes'] : '';

				if(isset($_SESSION['cart']->contents[$data['id']]['attributes_values'])){
					foreach($_SESSION['cart']->contents[$data['id']]['attributes_values'] as $k => $v){
						if($options[$k]['products_options_type']==1){
							$attributes["txt_".$k]=$v;
							unset($attributes[$k]);
						}
					}
				}
				
				$_SESSION['cart']->add_cart($data['id'], $new_qty, $attributes, true);
				$data['status']=true;
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCart";
					}else{
						$data['reload']="#msgOpenzc:msgCart";
					}
				}
			break;
			case "cutOne":
				global $predata_class;
				$options=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS);
				$cart_qty=$_SESSION['cart']->get_quantity($data['id']);
				if($cart_qty==1){
					$_SESSION['cart']->remove($data['id']);
					$data['status']=true;
				}else{
					$attributes = $_SESSION['cart']->contents[$data['id']]['attributes'] ? $_SESSION['cart']->contents[$data['id']]['attributes'] : '';
					if(isset($_SESSION['cart']->contents[$data['id']]['attributes_values'])){
						foreach($_SESSION['cart']->contents[$data['id']]['attributes_values'] as $k => $v){
							if($options[$k]['products_options_type']==1){
								$attributes["txt_".$k]=$v;
								unset($attributes[$k]);
							}
						}
					}
				
					$_SESSION['cart']->add_cart($data['id'],$cart_qty-1, $attributes, false);
					$data['status']=true;
				}
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCart";
					}else{
						$data['reload']="#msgOpenzc:msgCart";
					}
				}
			break;
			case "editCart":
			break;
			case "addCart":
				if(!isset($data['products_id'])){
					$data['products_id']=$data["id"];
				}
			    $this->actionAddProduct($data);
			    $data['status']=true;
			    if((isset($data['submit']) && $data['submit']=="tocart") || !isset($data['submit'])){
					if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
					if($msgbox==true){
						if(isset($data['reload'])){
							$data['reload'].=",#msgOpenzc:msgCart";
						}else{
							$data['reload']="#msgOpenzc:msgCart";
						}
					}
			    }
			    if(isset($data['submit']) && $data['submit']=="tobuy"){
			    	$data['reload']="refresh";
			    	$data['url']=zen_href_link(FILENAME_CHECKOUT,'','SSL');
			    }

			break;
			case "clearCart":
				$data['status']=true;
				$_SESSION['cart']->reset(true);
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCart";
					}else{
						$data['reload']="#msgOpenzc:msgCart";
					}
				}
			break;
			case 'initslideprice':
				global $filter_class;
				$data=$this->getReferer($data);
				$filter=$filter_class->get_price_bar($_GET,false,false,true);
				$filter[0]['filter_item']="slide price";
				$filter[0]['range']=$filter[0]['min'].",".$filter[0]['max'];
				set_cookie("slideprice",json_encode($filter[0]));
				exit;
			break;
			case "slidePrice":
				global $currencies;
				$range=explode(",",$data['range']);
				$data['min']=$range[0];
				$data['max']=$range[1];
				if($data['min']>=$data['max']){
					$data['min']=$data['max']-1;
				}
				if(DEFAULT_CURRENCY!=$_SESSION['currency']){
					$data['min']=round($data['min']/($currencies->currencies[$_SESSION['currency']]['value']),2);
					$data['max']=round($data['max']/($currencies->currencies[$_SESSION['currency']]['value']),2);
				}
				if(isset($data['reload']) || isset($data['reloadGroup'])){
					$data['status']=true;
					$_GET['price']=$data['min'].",".$data['max'];
				}else{
					$data['reload']="null";
				}
				$page=parse_url($_SERVER['HTTP_REFERER']);
				$query=explode("&",$page['query']);
				foreach($query as $k => $v){
					$str=$v;
					$v=explode("=",$v);
					if($v[0]!="price"){
						if($k==0){$querys.="?".$str;}
						else{$querys.="&".$str;}
					}
				}
				$data['url']=$page['scheme']."://".$page['host'].$page['path'].$querys."&price=".$data['min'].",".$data['max'];
				$slideprice=json_decode($_COOKIE['slideprice'],true);
				$slideprice['slide_min']=$data['min'];
				$slideprice['slide_max']=$data['max'];
				set_cookie("slideprice",json_encode($slideprice));
			break;
			case "getHtml":
				unset($_GET['action']);
				
				$data['status']=true;
			break;
			case "getState":
				global $variable_class;
				$selected_country=$data['value'];
				$GLOBALS['states'] = $variable_class->get_state_list($selected_country);
				$GLOBALS['states_billing'] = $variable_class->get_state_list($selected_country);
				$data['status']=true;
			break;
			case "addWishlist":
				$data=$this->getReferer($data);
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					$_SESSION['wishlist']['list'].=",".$data['id'];
					$str=array_unique(array_filter(explode(",",$_SESSION['wishlist']['list'])));
					$_SESSION['wishlist']['list']=join(",",$str);
					$_SESSION['wishlist']['count']=count($str);
					$_SESSION['wishlist']['current']=$data['id'];
					if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
					if($msgbox==true){
						if(isset($data['reload'])){
							$data['reload'].=",#msgOpenzc:msgWishlist";
						}else{
							$data['reload']="#msgOpenzc:msgWishlist";
						}
					}
				}else{
					if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
					if($msgbox==true){
						if(isset($data['reload'])){
							$data['reload'].=",#msgOpenzc:msgLogin";
						}else{
							$data['reload']="#msgOpenzc:msgLogin";
						}
					}
				}
				$this->ajaxMessage("msgWishlist","wishlist","success","You have successfully added collection!");
			break;
			case "clearWishlist":
				$data=$this->getReferer($data);
				$data['status']=true;
				$_SESSION['wishlist']['list']="";
				$_SESSION['wishlist']['count']=0;
				$_SESSION['wishlist']['action']=$action;

				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgWishlist";
					}else{
						$data['reload']="#msgOpenzc:msgWishlist";
					}
				}
				$this->ajaxMessage("msgWishlist","wishlist","success","You have successfully cleared collection of products!");
			break;
			case "delWishlist":
				$data=$this->getReferer($data);
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					$list=explode(",",$_SESSION['wishlist']['list']);
					foreach($list as $k => $v){if($v==$data['id']){unset($list[$k]);}}
					$_SESSION['wishlist']['list']=join(",",$list);
					$_SESSION['wishlist']['count']=count($list);
					$_SESSION['wishlist']['current']=$data['id'];
					$_SESSION['wishlist']['action']=$action;
					if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
					if($msgbox==true){
						if(isset($data['reload'])){
							$data['reload'].=",#msgOpenzc:msgWishlist";
						}else{
							$data['reload']="#msgOpenzc:msgWishlist";
						}
					}
				}else{
					$data['reload']="#msgOpenzc:msgLogin";
				}
				$this->ajaxMessage("msgWishlist","wishlist","success","You have successfully deleted collection of products!");
			break;
			case "addCompare":
			    $data=$this->getReferer($data);
				$data['status']=true;
				$_SESSION['compare']['list'].=",".$data['id'];
				$str=array_unique(array_filter(explode(",",$_SESSION['compare']['list'])));
				$_SESSION['compare']['list']=join(",",$str);
				$_SESSION['compare']['count']=count($str);
				$_SESSION['compare']['current']=$data['id'];
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCompare";
					}else{
						$data['reload']="#msgOpenzc:msgCompare";
					}
				}
				$this->ajaxMessage("msgCompare","compare","success","You have successfully added contrast goods!");
			break;
			case "delCompare":
			    $data=$this->getReferer($data);
				$data['status']=true;
				$list=explode(",",$_SESSION['compare']['list']);
				foreach($list as $k => $v){if($v==$data['id']){unset($list[$k]);}}
				$_SESSION['compare']['list']=join(",",$list);
				$_SESSION['compare']['count']=count($list);
				$_SESSION['compare']['current']=$data['id'];
				$_SESSION['compare']['action']=$action;
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCompare";
					}else{
						$data['reload']="#msgOpenzc:msgCompare";
					}
				}
				$this->ajaxMessage("msgCompare","compare","success","Your contrast commodity has been deleted successfully!");
			break;
			case "clearCompare":
				$data=$this->getReferer($data);
				$data['status']=true;
				$_SESSION['compare']['list']="";
				$_SESSION['compare']['count']=0;
				$_SESSION['compare']['action']=$action;
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCompare";
					}else{
						$data['reload']="#msgOpenzc:msgCompare";
					}
				}
				$this->ajaxMessage("msgCompare","compare","success","Your product comparison list is empty!");
			break;
			case "writeReviews":
				$data['status']=true;
				if(isset($_SESSION['customer_id'])){
					$this->writeReviews($data);
					if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
					if($msgbox==true){
						if(isset($data['reload'])){
							$data['reload'].=",#msgOpenzc:msgReviews";
						}else{
							$data['reload']="#msgOpenzc:msgReviews";
						}
					}
				}else{
					$data['reload']="#msgOpenzc:msgLogin";
				}
			break;
			case "getPreview":
				unset($_SESSION['products_preview_id']);
				$data['status']=true;
				$_GET['main_page']=FILENAME_PRODUCT_INFO;
				$_GET['products_id']=$data['id'];
				$_SESSION['products_preview_id']=$data['id'];

			break;
			case "getSKU":
				global $skuPriceClass;
				$data['status']=true;
				$data=$this->getSKU($data);
				$data['reload']=".".$skuPriceClass."-".$data["products_id"].":".$data['sku_price'];
			break;
			case "listFlow":
				$data['status']=true;
				$pageCount=$data['pagecount'];
				if(!isset($data['page'])){
					$data['page']=1;
				}
				$data['page']=$data['page']+1;
				$_GET['page']=$data['page'];
				if(($pageCount-$data['page'])<1){$data['page']="null";}
			break;
			case "autoReload":
				$data['status']=true;
				$file=TPLCACHE_TPL."autoAjax_".md5(TEMPLATE_TPL).".inc";
				$autoAjax=json_decode(file_get_contents($file),true);
				if(isset($data['reload'])){$reload=array_filter(explode(",",$data['reload']));$data['reload']="";}
				foreach($reload as $k => $v){$key=substr(md5($v),0,5);$autoAjax[$key]=$v;}
				foreach($autoAjax as $k => $v){
					$data["reload"].=",".$v;
				}
			break;
			case "setShipping":
				//print_r(get_included_files());exit;
				if(isset($_POST['id']) && $_POST['id']){
					list($module, $method) = explode('_', $_POST['id']);
					foreach($_SESSION['quotes'] as $k => $v){
						if($v['id']==$module){
							foreach($v['methods'] as $a => $b){
								if($b['id']==$method){
									$_SESSION['shipping']=array('id' => $_POST['id'],'title' =>$v['module']." (".$b['title'].")","cost"=>$b['cost']);
								}
							}
						}
					}
					$_SESSION['navigation']->set_snapshot(array('mode' => 'SSL', 'page' => FILENAME_CHECKOUT,"get"=>array("action"=>"payment")));
				}
				$data['status']=true;
			break;
			case "setPayment":
				$data['status']=true;
			break;
			case "getCoupon":
				global $db;
				require(DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/order_total/ot_coupon.php');
				require(DIR_WS_MODULES . 'order_total/ot_coupon.php');
				$GLOBALS['ot_coupon']=new ot_coupon();
				require(DIR_WS_CLASSES . 'order.php');
				$GLOBALS['order'] = new order;
				if (!empty($_SESSION['cc_id'])) {
				  $discount_coupon_query = "SELECT coupon_code FROM " . TABLE_COUPONS . " WHERE coupon_id = :couponID";
				  $discount_coupon_query = $db->bindVars($discount_coupon_query, ':couponID', $_SESSION['cc_id'], 'integer');
				  $GLOBALS['discount_coupon'] = $db->Execute($discount_coupon_query);
				}
				$this->getCoupon();
				/*
				$_POST['dc_redeem_code']=$_POST['redeem_code'];
				$order_total_modules->collect_posts();
				print_r($messageStack);
				*/
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgCoupon";
					}else{
						$data['reload']="#msgOpenzc:msgCoupon";
					}
				}
				$data['status']=true;
			break;
			case "getSearch":
				$data['status']=true;
				$_GET['main_page']=FILENAME_ADVANCED_SEARCH_RESULT;
				$_GET['keyword']=$data['value'];
			break;
			case "getContact":
				$this->getContact($data);
				$data['status']=true;
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgContact";
					}else{
						$data['reload']="#msgOpenzc:msgContact";
					}
				}
			break;
			case "getNewsletter":
				$this->getNewsletter($data);
				$data['status']=true;
				set_cookie('newsletter_popup',"false");
				if(isset($data['msgbox']) && $data['msgbox']=="false"){$msgbox=false;}
				if($msgbox==true){
					if(isset($data['reload'])){
						$data['reload'].=",#msgOpenzc:msgNewsletter";
					}else{
						$data['reload']="#msgOpenzc:msgNewsletter";
					}
				}
				
			break;
			case "getEstimate":
				$data['status']=true;
			break;
			
		}
		if(isset($data['reloadjs'])){
			$data['config']['customReloadJS']['yes']=$data['reloadjs'];
		}
		/*
		if($_SESSION['cart_errors']){
			//$result['errors']=$_SESSION['cart_errors'];
		}
		*/
		$result=$this->getParameter($data);
		if(isset($data['system'])){$result['system']=true;}
		if(isset($data['autoReload'])){$result['autoReload']=true;}else{$result['autoReload']=false;}
		header('Content-Type:application/json; charset=utf-8');
		echo json_encode($result);
	}
	function getParameter($data){
		mixinit();
		$GLOBALS['ajaxResult']=$data;
		$reloadID=openzc_field_to_key(array_filter(explode(",",$data['config']["customReloadAjax"])));
		$reloadGroup="";
		if(isset($data['config']["ajaxRloadgroup"]) && isset($data['reloadGroup'])){
			if(isset($data['config']["ajaxRloadgroup"][$data['reloadGroup']])){
				$reloadGroup=$data['config']["ajaxRloadgroup"][$data['reloadGroup']];
			}
		}
	
		if(!isset($data['reload'])){$data["reload"]="";}
		$result=$data;
		foreach($data as $k => $v){
			if(($k=="reload") && $data['status']==true){
				if(strstr($v,"refresh")){$v="";}else{
					$v.=",".$reloadGroup;
				}
				if($v){
					$result[$k]=$this->openzcRload($v,$reloadID,$data['action']);
					$result[$k]['count']=count($result[$k]);
				}else{
					$result[$k]="null";
				}
				if($data['action']=="listFlow"){
					$result[$k]['flow']=true;
				}
			}
		}
		
		if(isset($data["position"])){
			$data['position']=str_replace("%3D","=",$data['position']);

			$tmpfile=TEMPLATE_TPL.base64_decode($data['position']);
			
			$tmpfileOnlyName = preg_replace("/(.*)\//", "", $tmpfile);
		
			$jquery=TPLCACHE_TPL.preg_replace("/\.(php|tpl)$/", "_".substr(md5($tmpfile),0,24).'_jquery.inc', $tmpfileOnlyName);
		
			include($jquery);
			
			if(isset($data["config"]["customReloadJS"])){
				$reloadJS=$data["config"]["customReloadJS"];
				if(isset($data['autoReload']) || $reloadJS['yes']=="all"){
					$reloadJS['no'].=",openzc.js";
				}
				foreach($tplJquery as $k => $v){
					$yes=$no="";
					if(!isset($reloadJS['yes'])){unset($tplJquery[$k]);}
					if(isset($reloadJS['yes']) && $reloadJS['yes']!="all"){
						$rjs=explode(",",$reloadJS['yes']);
						foreach($rjs as $a => $b){
							if(strstr($v,$b)){$yes=true;}
						}
						if($yes!=true)unset($tplJquery[$k]);
					}
					if(isset($reloadJS["no"]) && $reloadJS["no"]!="all" ){
						$rjs=array_filter(explode(",",$reloadJS['no']));
						foreach($rjs as $a => $b){
							if(strstr($v,$b)){$no=true;}
						}
						if($no==true)unset($tplJquery[$k]);
					}
				}
			}else{
				$tplJquery=array();
			}
			$result['jquery']=$tplJquery;
		}
		return $result;
	}
	
	function openzcRload($data,$reloadID='',$action=''){
		global $OpenzcTpl;
		
		$DivID=array_unique(array_filter(explode(",",$data)));
		$ajaxDiv=file_get_contents(TPLCACHE_TPL."ajaxDiv_".md5(TEMPLATE_TPL_RESET).".inc");
		$ajaxDiv=json_decode($ajaxDiv,true);

		foreach($DivID as $k => $v){
			ob_start();
			if(strstr($v,":")){
				$v=array_filter(explode(":",$v));
				$name=$v[1];
				$div=$v[0];
				$divname=str_replace("#","",$div);
				$divname=str_replace(".","",$divname);
			}else{
				$name=$v;
				$v=str_replace("_","-",$v);
				if(isset($ajaxDiv[substr(md5($v),0,5)])){
					$div=explode(":",$ajaxDiv[substr(md5($v),0,5)])[0];
					$divname=$v."-".substr(md5($v),0,5);
				}else{
					$div="#".$v."-".substr(md5($v),0,5);
					$divname=$v."-".substr(md5($v),0,5);
				}
				
			}
			if($action=="getSKU"){
				$content[$divname]["div"]=$div;
				$content[$divname]["html"]=str_replace("#",",",$name);
			}else{
				if($name=="msgWishlist" || $name=="msgCompare" || $name=="msgLogin" || $name=="msgReviews" || $name=="msgCart" || $name=="msgCoupon" || $name=="msgContact" || $name=="msgNewsletter"){
					$tpl=str_replace(TEMPLATE_TPL,"",TPL_MODULES)."msgbox/".$name.".tpl";
				}else{
					$tpl=str_replace(TEMPLATE_TPL,"",TPL_AJAX_BOX).$name.".tpl";
				}
			
				$OpenzcTpl->LoadTemplate($tpl);
				ignore_user_abort(true);
				$OpenzcTpl->Display();
				
				$content[$divname]["div"]=$div;
				$content[$divname]["html"]=ob_get_contents();
				
				ob_end_clean();
			}
			
			if(array_key_exists($name,$reloadID)){
				$content[$divname]['custom_status']=true;
				$content[$divname]['custom_action']=$name;
				if(isset($_POST['id'])){
					$content[$divname]['id']=$_POST['id'];
				}
				
			}else{
				$content[$divname]['custom_status']=false;
			}
		}
		unset($_SESSION['msgBox']);
		return $content;
	}
	
	private function getCoupon(){
		global $db, $currencies, $order,$discount_coupon,$ot_coupon;
		$_POST['dc_redeem_code'] = isset($_POST['dc_redeem_code']) ? trim($_POST['dc_redeem_code']) : '';
		
		// remove discount coupon by request
		if (isset($_POST['dc_redeem_code']) && strtoupper($_POST['dc_redeem_code']) == 'REMOVE') {
		  unset($_POST['dc_redeem_code']);
		  unset($_SESSION['cc_id']);
		  $GLOBALS['zco_notifier']->notify('NOTIFY_OT_COUPON_COUPON_REMOVED');
		  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_REMOVE_REDEEM_COUPON);
		}
		if ((isset($_POST['dc_redeem_code']) && $_POST['dc_redeem_code'] != '') || (isset($discount_coupon->fields['coupon_code']) && $discount_coupon->fields['coupon_code'] != '')) {
		  // set current Discount Coupon based on current or existing
		  if (isset($_POST['dc_redeem_code']) && $discount_coupon->fields['coupon_code'] == '') {
			$dc_check = $_POST['dc_redeem_code'];
		  } else {
			$dc_check = $discount_coupon->fields['coupon_code'];
		  }
		  $sql = "select coupon_id, coupon_amount, coupon_type, coupon_minimum_order, uses_per_coupon, uses_per_user,
              restrict_to_products, restrict_to_categories, coupon_zone_restriction, coupon_calc_base, coupon_order_limit
              from " . TABLE_COUPONS . "
              where coupon_code= :couponCodeEntered
              and coupon_active='Y'
              and coupon_type !='G'";
		  $sql = $db->bindVars($sql, ':couponCodeEntered', $dc_check, 'string');
		  $coupon_result=$db->Execute($sql);
		  if ($coupon_result->fields['coupon_type'] != 'G') {
			  if ($coupon_result->RecordCount() < 1 ) {
				  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_REDEEM_COUPON . ' ' . $dc_check);
				  $ot_coupon->clear_posts();
				  
				  return false;
			  }
			  $GLOBALS['zco_notifier']->notify('NOTIFY_OT_COUPON_COUPON_INFO', array('coupon_result' => $coupon_result->fields, 'code' => $dc_check));
			  $error_issues = 0;
			  $dc_link_count = 0;
			  $dc_link = ' <a href="javascript:couponpopupWindow(\'' . zen_href_link(FILENAME_POPUP_COUPON_HELP, 'cID=' . $coupon_result->fields['coupon_id']) . '\')">' . $dc_check . '</a>';
			  $orderTotalDetails = $ot_coupon->get_order_total($coupon_result->fields['coupon_id']);
			  if ($coupon_result->fields['coupon_calc_base'] == 0) {
				  $coupon_total_minimum = $orderTotalDetails['orderTotal']; // restricted products
				  $coupon_total = $orderTotalDetails['orderTotal']; // restricted products
			  }
			  if ($coupon_result->fields['coupon_calc_base'] == 1) {
				  $coupon_total_minimum = $orderTotalDetails['orderTotal']; // restricted products
				  $coupon_total = $orderTotalDetails['totalFull']; // all products
			  }
			  if (strval($coupon_total) > 0 && strval($coupon_total_minimum) < $coupon_result->fields['coupon_minimum_order']){
				  
				  $this->ajaxMessage("msgCoupon","coupon","caution",sprintf(TEXT_INVALID_REDEEM_COUPON_MINIMUM, $currencies->format($coupon_result->fields['coupon_minimum_order'])) . ($dc_link_count == 0 ? $dc_link : ''));
				  $error_issues ++;
				  $dc_link_count ++;
			  }
			  $products = $_SESSION['cart']->get_products();
        	  $foundvalid = true;
			  if ($foundvalid == true) {
				  $foundvalid = false;
				  for ($i=0; $i<sizeof($products); $i++) {
					if (is_product_valid($products[$i]['id'], $coupon_result->fields['coupon_id'])) {
					  $foundvalid = true;
					  continue;
					}
				  }
				}
			  if ($foundvalid == true) {
				  // check if products on special or sale are valid
				  $foundvalid = false;
				  for ($i=0, $n=sizeof($products); $i<$n; $i++) {
					if (is_coupon_valid_for_sales($products[$i]['id'], $coupon_result->fields['coupon_id'])) {
					  $foundvalid = true;
					  continue;
					}
				  }
			  }
			  if (!$foundvalid) {$ot_coupon->clear_posts();}
			  if (!$foundvalid) {
				  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_COUPON_PRODUCT . ' ' . ($dc_link_count ==0 ? $dc_link : ''));
				  $error_issues ++;
				  $dc_link_count ++;
			  }
			  if ($coupon_result->fields['coupon_order_limit'] > 0) {
				  $sql = "SELECT orders_id FROM " . TABLE_ORDERS . " WHERE customers_id = '" . $_SESSION['customer_id'] . "'";
				  $chk_customer_orders = $db->Execute($sql);
				  if ($chk_customer_orders->RecordCount() > $coupon_result->fields['coupon_order_limit']) {
					  $this->ajaxMessage("msgCoupon","coupon","caution",sprintf(TEXT_INVALID_COUPON_ORDER_LIMIT, $coupon_result->fields['coupon_order_limit']) . ' ' . ($dc_link_count ==0 ? $dc_link : ''));
					$error_issues ++;
					$dc_link_count ++;
				  }
			  }
			  $date_query=$db->Execute("select coupon_start_date from " . TABLE_COUPONS . " where coupon_start_date <= now() and coupon_code='" . zen_db_prepare_input($dc_check) . "'");
			  if ($date_query->RecordCount() < 1 ) {
				  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_STARTDATE_COUPON . ' ' . ($dc_link_count ==0 ? $dc_link : ''));
				  $error_issues ++;
				  $dc_link_count ++;
			  }
			  $date_query=$db->Execute("select coupon_expire_date from " . TABLE_COUPONS . "
                                  where coupon_expire_date >= now() and
                                  coupon_code='" . zen_db_prepare_input($dc_check) . "'");
			  if ($date_query->RecordCount() < 1 ) {
				  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_FINISHDATE_COUPON . ' ' . ($dc_link_count ==0 ? $dc_link : ''));
				  $error_issues ++;
				  $dc_link_count ++;
		      }
			  $coupon_count = $db->Execute("select coupon_id from " . TABLE_COUPON_REDEEM_TRACK . "
                                      where coupon_id = '" . (int)$coupon_result->fields['coupon_id']."'");
			  $coupon_count_customer = $db->Execute("select coupon_id from " . TABLE_COUPON_REDEEM_TRACK . "
                                               where coupon_id = '" . $coupon_result->fields['coupon_id']."' and
                                               customer_id = '" . (int)$_SESSION['customer_id'] . "'");
			  if ($coupon_count->RecordCount() >= $coupon_result->fields['uses_per_coupon'] && $coupon_result->fields['uses_per_coupon'] > 0) {
				  
				  $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_USES_COUPON . $coupon_result->fields['uses_per_coupon'] . TIMES . ' ' . ($dc_link_count ==0 ? $dc_link : '') );
				  $error_issues ++;
				  $dc_link_count ++;
			  }
			  if ($coupon_count_customer->RecordCount() >= $coupon_result->fields['uses_per_user'] && $coupon_result->fields['uses_per_user'] > 0) {
				  
				  $this->ajaxMessage("msgCoupon","coupon","caution",sprintf(TEXT_INVALID_USES_USER_COUPON, $dc_check) . $coupon_result->fields['uses_per_user'] . ($coupon_result->fields['uses_per_user'] == 1 ? TIME : TIMES) . ' ' . ($dc_link_count ==0 ? $dc_link : '') );
				  $error_issues ++;
				  $dc_link_count ++;
			  }
			  $_SESSION['cc_id'] = $coupon_result->fields['coupon_id'];
			  if ($_SESSION['cc_id'] > 0) {
				  $sql = "select coupon_id, coupon_amount, coupon_type, coupon_minimum_order, uses_per_coupon, uses_per_user,
						  restrict_to_products, restrict_to_categories, coupon_zone_restriction, coupon_code
						  from " . TABLE_COUPONS . "
						  where coupon_id= :couponIDEntered
						  and coupon_active='Y'";
				  $sql = $db->bindVars($sql, ':couponIDEntered', $_SESSION['cc_id'], 'string');

				  $coupon_result=$db->Execute($sql);

				  $foundvalid = true;

				  $check_flag = false;
				  // base restrictions zone restrictions for Delivery or Billing address
				  switch($coupon_result->fields['coupon_type']) {
					case 'S': // shipping
					  // use delivery address
					  $check_zone_country_id = $order->delivery['country']['id'];
					  break;
					case 'F': // amount
					  // use billing address
					  $check_zone_country_id = $order->billing['country']['id'];
					  break;
					case 'O': // amount off and free shipping
					  // use delivery address
					  $check_zone_country_id = $order->delivery['country']['id'];
					  break;
					case 'P': // percentage
					  // use billing address
					  $check_zone_country_id = $order->billing['country']['id'];
					  break;
					case 'E': // percentage and Free Shipping
					  // use delivery address
					  $check_zone_country_id = $order->delivery['country']['id'];
					  break;
					default:
					  // use billing address
					  $check_zone_country_id = $order->billing['country']['id'];
					  break;
				  }

				  $sql = "select zone_id, zone_country_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . $coupon_result->fields['coupon_zone_restriction'] . "' and zone_country_id = '" . (int)$check_zone_country_id . "' order by zone_id";
				  $check = $db->Execute($sql);

				  // base restrictions zone restrictions for Delivery or Billing address
				  switch($coupon_result->fields['coupon_type']) {
					case 'S': // shipping
					  // use delivery address
					  $check_zone_id = $order->delivery['zone_id'];
					  break;
					case 'F': // amount
					  // use billing address
					  $check_zone_id = $order->billing['zone_id'];
					  break;
					case 'O': // amount off and free shipping
					  // use delivery address
					  $check_zone_id = $order->delivery['zone_id'];
					  break;
					case 'P': // percentage
					  // use billing address
					  $check_zone_id = $order->billing['zone_id'];
					  break;
					case 'E': // percentage and free shipping
					  // use delivery address
					  $check_zone_id = $order->delivery['zone_id'];
					  break;
					default:
					  // use billing address
					  $check_zone_id = $order->billing['zone_id'];
					  break;
				  }

				  if ($coupon_result->fields['coupon_zone_restriction'] > 0) {
					while (!$check->EOF) {
					  if ($check->fields['zone_id'] < 1) {
						$check_flag = true;
						break;
					  } elseif ($check->fields['zone_id'] == $check_zone_id) {
						$check_flag = true;
						break;
					  }
					  $check->MoveNext();
					}
					$foundvalid = $check_flag;
				  }
				  // remove if fails address validation
				  if (!$foundvalid) {
					$this->ajaxMessage("msgCoupon","coupon","caution",TEXT_REMOVE_REDEEM_COUPON_ZONE . ' ' . ($dc_link_count ==0 ? $dc_link : ''));
					$dc_link_count ++;
				  }
				  // display all error messages
				  if ($error_issues > 0 || !$foundvalid) {
					$ot_coupon->clear_posts();
					return false;
				  }

				  // remove if fails address validation
				  if ($foundvalid) {
					$this->ajaxMessage("msgCoupon","coupon","success",TEXT_VALID_COUPON);
				  }
				}
			  } else {
			    $this->ajaxMessage("msgCoupon","coupon","caution",TEXT_INVALID_REDEEM_COUPON . ' ' . $dc_check);
				$ot_coupon->clear_posts();
			  	return false;
			  }
		  }
		}
	
	
	private function actionAddProduct($data=[]) {
		global $messageStack;
		if ($_SESSION['cart']->display_debug_messages){
			$this->ajaxMessage("msgCart","cart","caution",'A: FUNCTION ' . __FUNCTION__);
		}
		$the_list = '';
		if (isset($data['products_id']) && is_numeric($data['products_id'])) {
			// verify attributes and quantity first
			if ($_SESSION['cart']->display_debug_messages){
				$this->ajaxMessage("msgCart","cart","caution",'A2: FUNCTION ' . __FUNCTION__);
			}
			$adjust_max= 'false';
			if (isset($data['id'])) {
				foreach ($data['id'] as $key => $value) {
					$check = zen_get_attributes_valid($data['products_id'], $key, $value);
					if ($check == false) {
						$the_list .= TEXT_ERROR_OPTION_FOR . '<span class="alertBlack">' . zen_options_name($key) . '</span>' . TEXT_INVALID_SELECTION . '<span class="alertBlack">' . ($value == (int)PRODUCTS_OPTIONS_VALUES_TEXT_ID ? TEXT_INVALID_USER_INPUT : zen_values_name($value)) . '</span>' . '<br />';
					}
				}
			}
			if (!is_numeric($data['cart_quantity']) || $data['cart_quantity'] <= 0) {
				// adjust quantity when not a value
				// If use an extra_cart_actions file to prevent processing by this function,
				// then be sure to set $_POST['shopping_cart_zero_or_less'] to a value other than true
				// to display success on add to cart and not display the below message.
				if (!isset($data['shopping_cart_zero_or_less'])) {
					$chk_link = '<a href="' . zen_href_link(zen_get_info_page($data['products_id']), 'cPath=' . (zen_get_generated_category_path_rev(zen_get_products_category_id($data['products_id']))) . '&products_id=' . $data['products_id']) . '">' . zen_get_products_name($data['products_id']) . '</a>';
					$this->ajaxMessage("msgCart","cart","caution",ERROR_CORRECTIONS_HEADING . ERROR_PRODUCT_QUANTITY_UNITS_SHOPPING_CART . $chk_link . ' ' . PRODUCTS_ORDER_QTY_TEXT . zen_output_string_protected($data['cart_quantity']));
					$data['shopping_cart_zero_or_less'] = true;
				}
				$data['cart_quantity'] = 0;
			}
			// verify qty to add
			$add_max = zen_get_products_quantity_order_max($data['products_id']);
			$cart_qty = $_SESSION['cart']->in_cart_mixed($data['products_id']);
			if ($_SESSION['cart']->display_debug_messages){
				$this->ajaxMessage("msgCart","cart","caution",'B: FUNCTION ' . __FUNCTION__ . ' Products_id: ' . $data['products_id'] . ' cart_qty: ' . $cart_qty . ' $data[cart_quantity]: ' . $data['cart_quantity'] . ' <br>');
			}
			$new_qty = $data['cart_quantity'];
			$new_qty = $_SESSION['cart']->adjust_quantity($new_qty, $data['products_id'], 'shopping_cart');

			// adjust new quantity to be no more than current in stock
			$chk_current_qty = zen_get_products_stock($data['products_id']);
			$_SESSION['cart']->flag_duplicate_msgs_set = FALSE;
			if (STOCK_ALLOW_CHECKOUT == 'false' && ($cart_qty + $new_qty > $chk_current_qty)) {
				$new_qty = $chk_current_qty;
				$this->ajaxMessage("msgCart","cart","caution",($_SESSION['cart']->display_debug_messages ? 'C: FUNCTION ' . __FUNCTION__ . ': ' : '') . WARNING_PRODUCT_QUANTITY_ADJUSTED . zen_get_products_name($_POST['products_id']));
				$_SESSION['cart']->flag_duplicate_msgs_set = TRUE;
			}

			if ($add_max == 1 && $cart_qty == 1) {
					// do not add
					$new_qty = 0;
					$adjust_max= 'true';
			} else {
					// adjust new quantity to be no more than current in stock
				if (STOCK_ALLOW_CHECKOUT == 'false' && ($new_qty + $cart_qty > $chk_current_qty)) {
						$adjust_new_qty = 'true';
						$alter_qty = $chk_current_qty - $cart_qty;
						$new_qty = ($alter_qty > 0 ? $alter_qty : 0);
					if (!$_SESSION['cart']->flag_duplicate_msgs_set) {
						
						$this->ajaxMessage("msgCart","cart","caution",($_SESSION['cart']->display_debug_messages ? 'D: FUNCTION ' . __FUNCTION__ . ': ' : '') . WARNING_PRODUCT_QUANTITY_ADJUSTED . zen_get_products_name($data['products_id']));
					}
				}

				// adjust quantity if needed
				if (($new_qty + $cart_qty > $add_max) && $add_max != 0) {
					$adjust_max= 'true';
					$new_qty = $add_max - $cart_qty;
				}
			}
			if (zen_get_products_quantity_order_max($data['products_id']) == 1 && $_SESSION['cart']->in_cart_mixed($data['products_id']) == 1) {
				// do not add
			} else {
				// process normally
				// bof: set error message
				if ($the_list != '') {
					$this->ajaxMessage("msgCart","cart","caution",ERROR_CORRECTIONS_HEADING . $the_list);
				} else {
						// process normally
						// iii 030813 added: File uploading: save uploaded files with unique file names
					$real_ids = isset($data['id']) ? $data['id'] : array();
					if (isset($_GET['number_of_uploads']) && $_GET['number_of_uploads'] > 0) {
						/*** Need the upload class for attribute type that allows user uploads.**/
						include(DIR_WS_CLASSES . 'upload.php');
						for ($i = 1, $n = $_GET['number_of_uploads']; $i <= $n; $i++) {
							if (isset($data[UPLOAD_PREFIX . $i]) && isset($_FILES['id']['tmp_name'][TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]]) && zen_not_null($_FILES['id']['tmp_name'][TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]]) && (!isset($data[UPLOAD_PREFIX . $i]) || !isset($_FILES['id']['tmp_name'][TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]]) || ($_FILES['id']['tmp_name'][TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]] != 'none'))) {
								$products_options_file = new upload('id');
								$products_options_file->set_destination(DIR_FS_UPLOADS);
								$products_options_file->set_output_messages('session');
								if ($products_options_file->parse(TEXT_PREFIX . $data[UPLOAD_PREFIX . $i])) {
									$products_image_extension = substr($products_options_file->filename, strrpos($products_options_file->filename, '.'));
									if (zen_is_logged_in()) {
										$db->Execute("INSERT INTO " . TABLE_FILES_UPLOADED . " (sesskey, customers_id, files_uploaded_name) VALUES ('" . zen_session_id() . "', " . (int)$_SESSION['customer_id'] . ", '" . zen_db_input($products_options_file->filename) . "')");
									} else {
										$db->Execute("INSERT INTO " . TABLE_FILES_UPLOADED . " (sesskey, files_uploaded_name) VALUES ('" . zen_session_id() . "', '" . zen_db_input($products_options_file->filename) . "')");
									}
									$insert_id = $db->Insert_ID();
									$real_ids[TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]] = $insert_id . ". " . $products_options_file->filename;
									$products_options_file->set_filename("$insert_id" . $products_image_extension);
									if (!($products_options_file->save())) {
										break;
									}
								} else {
									break;
								}
							} else { // No file uploaded -- use previous value
								$real_ids[TEXT_PREFIX . $data[UPLOAD_PREFIX . $i]] = isset($data[TEXT_PREFIX . UPLOAD_PREFIX . $i]) ? $data[TEXT_PREFIX . UPLOAD_PREFIX . $i] : '';
								if (!zen_get_attributes_valid($data['products_id'], TEXT_PREFIX . $data[UPLOAD_PREFIX . $i], !empty($data[TEXT_PREFIX . UPLOAD_PREFIX . $i]) ? $data[TEXT_PREFIX . UPLOAD_PREFIX . $i] : '')) {
										$the_list .= TEXT_ERROR_OPTION_FOR . '<span class="alertBlack">' . zen_options_name($data[UPLOAD_PREFIX . $i]) . '</span>' . TEXT_INVALID_SELECTION . '<span class="alertBlack">' . ($data[TEXT_PREFIX . UPLOAD_PREFIX . $i] == (int)PRODUCTS_OPTIONS_VALUES_TEXT_ID ? TEXT_INVALID_USER_INPUT : zen_values_name($value)) . '</span>' . '<br />';
									$new_qty = 0; // Don't increase the quantity of product in the cart.
								}
							}
						}
						if ($the_list != '') {
							$this->ajaxMessage("msgCart","cart","caution",ERROR_CORRECTIONS_HEADING . $the_list);
						}
						// remove helper param from URI of the upcoming redirect
						$parameters[] = 'number_of_uploads';
						unset($_GET['number_of_uploads']);
					}
					// do the actual add to cart
					$_SESSION['cart']->add_cart($data['products_id'], $_SESSION['cart']->get_quantity(zen_get_uprid($data['products_id'], $real_ids))+($new_qty), $real_ids);
					// iii 030813 end of changes.
				} // eof: set error message
			} // eof: quantity maximum = 1

			if ($adjust_max == 'true') {
				$this->ajaxMessage("msgCart","cart","caution",ERROR_MAXIMUM_QTY . zen_get_products_name($data['products_id']));
				if ($_SESSION['cart']->display_debug_messages){
					$this->ajaxMessage("msgCart","cart","caution",'E: FUNCTION ' . __FUNCTION__ . '<br>' . ERROR_MAXIMUM_QTY . zen_get_products_name($data['products_id']));
				}
			}
		}
		
		if (empty($the_list)) { // no errors
			foreach($data['id'] as $k => $v){
				$sql= "SELECT pa.products_id FROM " . TABLE_PRODUCTS_ATTRIBUTES . " pa WHERE pa.products_id = " . (int)$data['products_id'] . " AND pa.options_values_id = '".(int)$v."'";
				$chk_attributes_exist = openzcQuery($sql);
				if ($chk_attributes_exist->EOF) {
					$this->ajaxMessage("msgCart","cart","caution",ERROR_PRODUCT_STATUS_SHOPPING_CART_ATTRIBUTES);
				}
			}
		} else {
			// errors found with attributes - perhaps display an additional message here, using an observer class to add to the messageStack
			$_SESSION['cart']->notify('NOTIFIER_CART_OPTIONAL_ATTRIBUTE_ERROR_MESSAGE_HOOK', $data, $the_list);
		}
		foreach($messageStack->messages as $k => $v){if($v['class']=="cart")$caution++;}
		// display message if all is good and not on shopping_cart page
		if ($_GET['main_page'] != FILENAME_SHOPPING_CART && $caution== 0) {
			$this->ajaxMessage("msgCart","cart","success",($_SESSION['cart']->display_debug_messages ? 'FUNCTION ' . __FUNCTION__ . ': ' : '') . SUCCESS_ADDED_TO_CART_PRODUCT);
			
		}else{
			$this->ajaxMessage("msgCart","cart","error","Add to Shopping Cart failed!");
		}
		
	}
	function actionBuyNow($data) {
		if ($_SESSION['cart']->display_debug_messages){
			$this->ajaxMessage("msgCart","cart",'caution','FUNCTION ' . __FUNCTION__ . ' $data[products_id]: ' . $data['products_id']);
		}

		$_SESSION['cart']->flag_duplicate_msgs_set = FALSE;
		if (isset($data['products_id'])) {
			if (zen_requires_attribute_selection($data['products_id'])) {
				$data['gotourl']=str_replace("&amp;","&",zen_href_link(zen_get_info_page($data['products_id']), 'products_id=' . $data['products_id']));
				$this->ajaxMessage("msgCart","cart",'caution',ERROR_PRODUCT_STATUS_SHOPPING_CART_ATTRIBUTES);
			}else {
				$add_max = zen_get_products_quantity_order_max($data['products_id']);
				$cart_qty = $_SESSION['cart']->in_cart_mixed($data['products_id']);
				$new_qty = zen_get_buy_now_qty($data['products_id']);
				if (!is_numeric($new_qty) || $new_qty < 0) {
					// adjust quantity when not a value
					$chk_link = '<a href="' . zen_href_link(zen_get_info_page($data['products_id']), 'cPath=' . (zen_get_generated_category_path_rev(zen_get_products_category_id($data['products_id']))) . '&products_id=' . $data['products_id']) . '">' . zen_get_products_name($data['products_id']) . '</a>';
					$this->ajaxMessage("msgCart","cart",'caution',ERROR_CORRECTIONS_HEADING . ERROR_PRODUCT_QUANTITY_UNITS_SHOPPING_CART . $chk_link . ' ' . PRODUCTS_ORDER_QTY_TEXT . zen_output_string_protected($new_qty));
					$new_qty = 0;
				}
				if (($add_max == 1 and $cart_qty == 1)) {
					// do not add
					$new_qty = 0;
				} else {
					// adjust quantity if needed
					if (($new_qty + $cart_qty > $add_max) and $add_max != 0) {
						$new_qty = $add_max - $cart_qty;
					}
				}
				if ((zen_get_products_quantity_order_max($data['products_id']) == 1 and $_SESSION['cart']->in_cart_mixed($data['products_id']) == 1)) {
					// do not add
				} else {
					// check for min/max and add that value or 1
					$_SESSION['cart']->add_cart($data['products_id'], $_SESSION['cart']->get_quantity($data['products_id'])+$new_qty);
					$this->ajaxMessage("msgCart","cart","success",($_SESSION['cart']->display_debug_messages ? 'FUNCTION ' . __FUNCTION__ . ': ' : '') . SUCCESS_ADDED_TO_CART_PRODUCTS);
					$data['gotourl']=stripslashes(zen_href_link(FILENAME_SHOPPING_CART));
				}
			}
			//print_r($messageStack);
		}
		return $data;
		
    }
	
	private function writeReviews($data=[]){
		global $db;
		if($this->postCheck("writeReviews",$data)){return false;}
		
		$customer_query = "SELECT customers_firstname, customers_lastname, customers_email_address
                   FROM " . TABLE_CUSTOMERS . " WHERE customers_id = :customersID";
        $customer_query = $db->bindVars($customer_query, ':customersID', $_SESSION['customer_id'], 'integer');
        $customer = $db->Execute($customer_query);
        
		$rating = zen_db_prepare_input($data['rating']);
		$review_text = zen_db_prepare_input($data['review_text']);
		$error = false;
		if (strlen($review_text) < REVIEW_TEXT_MIN_LENGTH) {
	    	$error = true;
			$this->ajaxMessage("msgReviews","reviews","error",JS_REVIEW_TEXT);
		}
		if (($rating < 1) || ($rating > 5)) {
		    $error = true;
			$this->ajaxMessage("msgReviews","reviews","error",JS_REVIEW_RATING);
		}
		if ($error == false) {
		    if (REVIEWS_APPROVAL == '1') {
		      $review_status = '0';
		    } else {
		      $review_status = '1';
		    }
		    $sql = "INSERT INTO " . TABLE_REVIEWS . " (products_id, customers_id, customers_name, reviews_rating, date_added, status)
		            VALUES (:productsID, :customersID, :customersName, :rating, now(), " . $review_status . ")";
		    $sql = $db->bindVars($sql, ':productsID', $_GET['products_id'], 'integer');
		    $sql = $db->bindVars($sql, ':customersID', $_SESSION['customer_id'], 'integer');
		    $sql = $db->bindVars($sql, ':customersName', $customer->fields['customers_firstname'] . ' ' . $customer->fields['customers_lastname'], 'string');
		    $sql = $db->bindVars($sql, ':rating', $rating, 'string');
		
		    $db->Execute($sql);
		
		    $insert_id = $db->Insert_ID();
		
		    $sql = "INSERT INTO " . TABLE_REVIEWS_DESCRIPTION . " (reviews_id, languages_id, reviews_text)
		            VALUES (:insertID, :languagesID, :reviewText)";
		
		    $sql = $db->bindVars($sql, ':insertID', $insert_id, 'integer');
		    $sql = $db->bindVars($sql, ':languagesID', $_SESSION['languages_id'], 'integer');
		    $sql = $db->bindVars($sql, ':reviewText', $review_text, 'string');
		
		    $db->Execute($sql);
			$this->ajaxMessage("msgReviews","reviews","success",'Write a review successfully!');
		}
	
	}
	//*获取产品属性SKU信息*//
	private function getSKU($data){
		global $attributes_class,$currencies,$product_class;
		$options=explode(":",$data['options']);
		$pid=$options[0];
		$opid=$options[1];
		$value=$data['value'];
		$specials_products = openzcQuery("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id in('" .$pid. "') and status='1'");
		$specials_products = openzc_table_to_list($specials_products,"products_id");
		$sql="select pa.*,p.products_tax_class_id,p.products_price,p.products_priced_by_attribute,p.product_is_free,p.product_is_call,p.products_model,p.master_categories_id,po.products_options_sort_order from ".TABLE_PRODUCTS_ATTRIBUTES." pa left join ".TABLE_PRODUCTS." p on pa.products_id=p.products_id ,".TABLE_PRODUCTS_OPTIONS." po where po.products_options_id=pa.options_id and p.products_id in('".$pid."') and po.language_id='".(int)$_SESSION['languages_id']."' order by po.products_options_sort_order asc";
			
		$attributes=openzcQuery($sql);
		$attributes=openzc_table_to_list($attributes);
		foreach($attributes as $k => $v){
			$products_attributes[$v['products_id']][$v["options_values_id"]]=$v;
		}
		$values_final_price=$attributes_class->get_attributes_price_final($products_attributes[$pid][$value],$products_attributes[$pid],$specials_products[$pid]);
		$price=$product_class->get_display_price($pid);
		$price=$product_class->get_price_number($price);
		
		$_SESSION['SKU'][$pid][$opid]['price']=$product_class->get_price_number($values_final_price);
		$_SESSION['SKU'][$pid][$opid]['prefix']=$products_attributes[$pid][$value]['price_prefix'];
		$_SESSION['SKU'][$pid]['price']=round($price/($currencies->currencies[$_SESSION['currency']]['value']),2);
		$data['sku_price']=$_SESSION['SKU'][$pid]['price'];
		foreach($_SESSION['SKU'][$pid] as $k => $v){
			if($k!="price"){
				$v['price']=round($v['price']/($currencies->currencies[$_SESSION['currency']]['value']),2);
				if($v['prefix']=="+"){
					$data['sku_price']=$data['sku_price']+$v['price'];
				}
				if($v['prefix']=="-"){
					$data['sku_price']=$data['sku_price']-$v['price'];
				}
			}
		}
		$data['products_id']=$pid;
		$data['sku_price']=str_replace(",","#",$currencies->display_price($data['sku_price'],''));
		return $data;
	}
	
	//Ajax数据提交安全检查，防止恶意行为
	function postCheck($action,$data){
		switch($action){
			case "writeReviews":
				$sql="select * from ".TABLE_REVIEWS." where products_id='".$_GET['products_id']."' and customers_id='".$_SESSION['customer_id']."' and TO_DAYS(date_added) = TO_DAYS(NOW())";
				$rs=openzcQuery($sql);
				if($rs->resource->num_rows >2){
					$this->ajaxMessage("msgReviews","reviews","caution",'Sorry,Cannot review the same product multiple times in one day！');
					return true;
				}
				$sql="select * from ".TABLE_REVIEWS." where customers_id='".$_SESSION['customer_id']."' and TO_DAYS(date_added) = TO_DAYS(NOW())";
				$rs=openzcQuery($sql);
				if($rs->resource->num_rows >5){
					$this->ajaxMessage("msgReviews","reviews","caution",'Sorry,Reviews are too frequent in one day！');
					return true;
				}
				return false;
			break;
		}
	}
	function getNewsletter($data=[]){
		global $db;
		if(isset($data['EMAIL'])){$email=$data['EMAIL'];}else{$email=$data['email'];}
		$error = false;
		$enquiry = '';
		if(!$email){$error = true;}
		$zc_validate_email = zen_validate_email($email);
		
		if($zc_validate_email && $error == false){
			$date_now=date("Y-m-d H:i:s");
			if(isset($_SESSION['customer_id']) && $_SESSION['customer_id']){
				$sql = "select customers_email_address from ".TABLE_CUSTOMERS." where customers_id='".$_SESSION['customer_id']."'";
				$check_email = $db->Execute($sql);
				if($data['email']==$check_email->fields['customers_email_address']){
					$sql = "update ".TABLE_CUSTOMERS." set customers_newsletter='1' where customers_id='".$_SESSION['customer_id']."'";
					$db->Execute($sql);
				}else{
					$sql = "insert into ".TABLE_NEWSLETTERS_EMAIL." (newsletters_email,date_added,last_modified) values('".$email."','".$date_now."','".$date_now."')
    ON DUPLICATE KEY UPDATE newsletters_email = '".$email."',last_modified = '".$date_now."',last_modified_ip='".$_SESSION['customers_ip_address']."'";
					$db->Execute($sql);
				}
			}else{
				$sql = "insert into ".TABLE_NEWSLETTERS_EMAIL." (newsletters_email,date_added,last_modified) values('".$email."','".$date_now."','".$date_now."')
    ON DUPLICATE KEY UPDATE newsletters_email = '".$email."',last_modified = '".$date_now."',last_modified_ip='".$_SESSION['customers_ip_address']."'";
				$db->Execute($sql);
			}

			$sql="select configuration_value from ".TABLE_CONFIGURATION." where configuration_key='DEFAULT_NEWSLETTERS_ID'";
			$default_newsletter_id=$db->Execute($sql);
			$default_newsletter_id=$default_newsletter_id->fields['configuration_value'];
			if($default_newsletter_id){
				$sql="select * from ".TABLE_NEWSLETTERS." where newsletters_id='".$default_newsletter_id."' and locked='0'";
				$newsletter_contents=$db->Execute($sql);
				$text="";
				$html_msg=[];
				$title=$newsletter_contents->fields['title'];
				if(ADMIN_EXTRA_EMAIL_FORMAT=="HTML"){
					$html_msg['EMAIL_FIRST_NAME']=$email;
					$html_msg['EMAIL_LAST_NAME']="";
					$html_msg['EMAIL_MESSAGE_HTML']=$newsletter_contents->fields['content_html'];
					$html_msg['UNSUBSCRIBE_LINK']="";
					$html_msg['EMAIL_FOOTER_COPYRIGHT']="";
					$html_msg['EMAIL_WELCOME']="";
					$html_msg['EMAIL_GREETING']="";
					$html_msg['EMAIL_CONTACT_OWNER']="";
					$html_msg['EMAIL_CLOSURE']="";
				}else{
					$text=$newsletter_contents->fields['content'];
				}
				$GLOBALS['current_page_base']='newsletters';
				zen_mail("", $email, $title, $text, STORE_NAME, EMAIL_FROM, $html_msg, 'newsletters');
				$this->ajaxMessage("msgNewsletter","newsletter","success","Success: You have successfully subscribed newsletter!");
			}else{
				$this->ajaxMessage("msgNewsletter","newsletter","caution","Warning: Subscription email template is not set!");
			}
		}else{
			$this->ajaxMessage("msgNewsletter","newsletter","error","Warning: Please enter your email address!");
		}
	}
	function getContact($data){
		global $db;
		$error = false;
		$enquiry = '';
		$antiSpamFieldName = isset($_SESSION['antispam_fieldname']) ? $_SESSION['antispam_fieldname'] : 'should_be_empty';
		$name = zen_db_prepare_input($data['contactname']);
		$email_address = zen_db_prepare_input($data['email']);
		$enquiry = zen_db_prepare_input(strip_tags($data['enquiry']));
		$telephone = zen_db_prepare_input($data['telephone']);
		$antiSpam = !empty($data[$antiSpamFieldName]) ? 'spam' : '';
		if (!empty($data['contactname']) && preg_match('~https?://?~', $data['contactname'])){$antiSpam = 'spam';}
		$zc_validate_email = zen_validate_email($email_address);
		if ($zc_validate_email && !empty($enquiry) && !empty($name) && $error == FALSE) {
			if ($antiSpam != '') {
            	$zco_notifier->notify('NOTIFY_SPAM_DETECTED_USING_CONTACT_US', $data);
        	}else if($antiSpam == '') {
				// auto complete when logged in
				if (zen_is_logged_in() && !zen_in_guest_checkout()) {
					$sql = "SELECT customers_id, customers_firstname, customers_lastname, customers_password, customers_email_address, customers_default_address_id, customers_telephone 
						  FROM " . TABLE_CUSTOMERS . "
						  WHERE customers_id = :customersID";
	
					$sql = $db->bindVars($sql, ':customersID', $_SESSION['customer_id'], 'integer');
					$check_customer = $db->Execute($sql);
					$customer_email = $check_customer->fields['customers_email_address'];
					$customer_name  = $check_customer->fields['customers_firstname'] . ' ' . $check_customer->fields['customers_lastname'];
					$customer_telephone = $check_customer->fields['customers_telephone']; 
				} else {
					$customer_email = NOT_LOGGED_IN_TEXT;
					$customer_name = NOT_LOGGED_IN_TEXT;
					$customer_telephone = NOT_LOGGED_IN_TEXT;
				}
				// declare variable
				$send_to_array = [];
	
				// use contact us dropdown if defined and if a destination is provided
				if (CONTACT_US_LIST != '' && isset($data['send_to'])){
					$send_to_array = explode(",", CONTACT_US_LIST);
					if (isset($send_to_array[$data['send_to']])) {
						preg_match('/\<[^>]+\>/', $send_to_array[$data['send_to']], $send_email_array);
					}
				}
				$send_to_email = trim(EMAIL_FROM); // default to EMAIL_FROM
            	$send_to_name  = trim(STORE_NAME);  // default to STORE_NAME
				// Assign email destination from array
				if (!empty($send_email_array)) {
					$send_to_email = preg_replace ("/>/", "", $send_email_array[0]);
					$send_to_email = trim(preg_replace("/</", "", $send_to_email));
					$send_to_name  = trim(preg_replace('/\<[^*]*/', '', $send_to_array[$data['send_to']]));
				}
				// Prepare extra-info details
            	$extra_info = email_collect_extra_info($name, $email_address, $customer_name, $customer_email, $customer_telephone);
				// Prepare Text-only portion of message
				$text_message = OFFICE_FROM . "\t" . $name . "\n" . OFFICE_EMAIL . "\t" . $email_address . "\n";
				if (!empty($telephone)){$text_message .= OFFICE_LOGIN_PHONE . "\t" . $telephone . "\n";}
				$text_message .= "\n" .
				'------------------------------------------------------' . "\n\n" .
				strip_tags($data['enquiry']) .  "\n\n" .
				'------------------------------------------------------' . "\n\n" .
				$extra_info['TEXT'];
				// Prepare HTML-portion of message
				$html_msg['EMAIL_MESSAGE_HTML'] = strip_tags($data['enquiry']);
				$html_msg['CONTACT_US_OFFICE_FROM'] = OFFICE_FROM . ' ' . $name . '<br />' . OFFICE_EMAIL . '(' . $email_address . ')';
				$html_msg['EXTRA_INFO'] = $extra_info['HTML'];
				// Send message
            	zen_mail($send_to_name, $send_to_email, EMAIL_SUBJECT, $text_message, $name, $email_address, $html_msg, 'contact_us');
			}
			$this->ajaxMessage("msgContact","contact","success","The content is submitted successfully, we will contact you in time, thank you!");
		}else {
			$error = true;
			if (empty($name)) {
				$this->ajaxMessage("msgContact","contact","error",ENTRY_EMAIL_NAME_CHECK_ERROR);
			}
			if ($zc_validate_email == false) {
				$this->ajaxMessage("msgContact","contact","error",ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
			}
			if (empty($enquiry)) {
				$this->ajaxMessage("msgContact","contact","error",ENTRY_EMAIL_CONTENT_CHECK_ERROR);
			}
		}
	}
	private function ajaxMessage($item='',$action='',$type='',$text=''){
		global $messageStack;
		$_SESSION['msgBox'][$item]['action']=$action;
		$_SESSION['msgBox'][$item]['type']=$type;
		$_SESSION['msgBox'][$item]['text']=$text;
		$messageStack->add_session($action,$text,$type);
	}
	private function getReferer($data){
		$referer=$_SERVER['HTTP_REFERER'];
		if($referer){
			$result=parse_url($referer);
			$query=explode("&",$result["query"]);
			foreach($query as $k => $v){
				$v=explode("=",$v);
				$_GET[$v[0]]=$v[1];
				$data[$v[0]]=$v[1];
			}
		}
		return $data;
	}
	
}
?>