<?php
class catalog {
  public $filter_sql = array();
  public $join_sql = array();
  public $field_sql = array();
  public $common_js = array();
  public $header_code = array();
  public $footer_js = array();
  public $hooks_js = array();
  public $header_js_file = array();
  public $footer_js_file = array();
  public $header_css_file = array();
  public $footer_css_file = array();
  public $block_code = array();
  public $common_document_ready_js = array();
  public $code_mod = 'core';
  public $code_file = 'index.php';
  public $code_page = 'index';
  public $filter_product_sql = '';
  public $category_tree = array();
  public $category_tree_all = array();
  public $permalinks = array();

  public function __construct() {
	global $language, $languages_id;
	self::force_ssl();
  }  //end of __construct
//--------------------------------
//Force SSL
//--------------------------------
  public static function force_ssl()
  {
	$redirect_url = '';
	if(strtolower(HTTP_COOKIE_DOMAIN) != strtolower($_SERVER['HTTP_HOST']))
		$redirect_url = HTTP_SERVER.$_SERVER['REQUEST_URI'];

	if((ENABLE_SSL == 'true') && (!isset($_SERVER['HTTPS']) || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https')))
		$redirect_url = HTTPS_SERVER.$_SERVER['REQUEST_URI'];
		
	if($redirect_url != '') {
		header("HTTP/1.1 301 Moved Permanently");
		header('Location: '. $redirect_url);
		exit(0);
	}
  }

  public static function b2b_filter_sql($fieldname) {
	$filter_product_sql = '';
	if(function_exists('b2b_filter_sql')) {
		$filter_product_sql = b2b_filter_sql($fieldname);
	}
	return 	$filter_product_sql;
  }

  public function set_filter_sql($queryKey, $filterQuery) {
  	if($queryKey != '') {
	  	$this->filter_sql[$queryKey][] = $filterQuery;
	  }
  }

  public function get_filter_sql($queryKey) {
	$appendSql = '';
  	if($queryKey != '' && is_array($this->filter_sql[$queryKey])) {
		foreach($this->filter_sql[$queryKey] as $sql) {
			$appendSql .= ' '.$sql;
		}
	}
	return $appendSql;
  }

  public function set_join_sql($queryKey, $joinQuery) {
  	if($queryKey != '') {
	  	$this->join_sql[$queryKey][] = $joinQuery;
	  }
  }

  public function get_join_sql($queryKey) {
	$appendSql = '';
  	if($queryKey != '' && is_array($this->filter_sql[$queryKey])) {
		foreach($this->join_sql[$queryKey] as $sql) {
			$appendSql .= ' '.$sql;
		}
	}
	return $appendSql;
  }

  public function set_field_sql($queryKey, $fields) {
  	if($queryKey != '') {
	  	$this->field_sql[$queryKey][] = $fields;
	  }
  }

  public function get_field_sql($queryKey) {
	$appendSql = '';
  	if($queryKey != '' && is_array($this->filter_sql[$queryKey])) {
		foreach($this->field_sql[$queryKey] as $sql) {
			$appendSql .= ' '.$sql;
		}
	}
	return $appendSql;
  }

  public function set_js_document_ready($jscode) {
  	$this->common_document_ready_js[] = $jscode;
  }

  public function get_js_document_ready() {
  	return $this->common_document_ready_js;
  }

  public function set_js($jscode) {
  	$this->common_js[] = $jscode;
  }

  public function get_js() {
  	return $this->common_js;
  }

  public function set_header_code($jscode) {
  	$this->header_code[] = $jscode;
  }

  public function get_header_code() {
  	return $this->header_code;
  }

  public function print_header_code() {
  	$str_header_code = "\n";
  	foreach($this->header_code as $code) {
  		$str_header_code .= $code."\n";
  	}
  	return $str_header_code;
  }

  public function set_footer_js($jscode) {
  	$this->footer_js[] = $jscode;
  }

  public function get_footer_js() {
  	return $this->footer_js;
  }

  public function print_footer_js() {
  	$str_footer_js = "\n";
  	foreach($this->footer_js as $jscode) {
  		$str_footer_js .= $jscode."\n";
  	}
  	return $str_footer_js;
  }

  public function set_hooks_js($jscode, $hooks_code='common') {
  	$this->hooks_js[$hooks_code][] = $jscode;
  }

  public function get_hooks_js($hooks_code='common') {
  	return $this->hooks_js[$hooks_code];
  }

  public function print_hooks_js($hooks_code='common', $withscripttag=0) {
  	$str_hooks_js = "\n";
  	if(isset($this->hooks_js[$hooks_code])) {
		foreach($this->hooks_js[$hooks_code] as $jscode) {
			$str_hooks_js .= $jscode."\n";
		}
		if($withscripttag) {
			$str_hooks_js = '<script language="javascript">'. $str_hooks_js .'</script>';
		}
	}
  	return $str_hooks_js;
  }

  public function add_footer_block($blockcode) {
  	$this->block_code[] = $blockcode;
  }

  public function get_footer_block() {
  	return $this->block_code;
  }

  public function print_footer_block() {
  	$str_footer_block = "\n";
  	foreach($this->block_code as $block_code) {
  		$str_footer_block .= $block_code."\n";
  	}
  	return $str_footer_block;
  }

  public function set_header_js_file($jsFilename) {
  	$this->header_js_file[] = $jsFilename;
  }

  public function set_footer_js_file($jsFilename) {
  	$this->footer_js_file[] = $jsFilename;
  }

  public function printHeaderJSFile() {
  	$str_header_js_file = "\n";
  	foreach($this->header_js_file as $jsfile) {
  		$str_header_js_file .= '<script type="text/javascript" id="headerjs-'. str_replace('.', '-', strtolower(basename($jsfile))) .'" src="'. $jsfile .'"></script>'."\n";
  	}
  	return $str_header_js_file;
  }

  public function printFooterJSFile() {
  	$str_footer_js_file = "\n";
  	foreach($this->footer_js_file as $jsfile) {
  		$str_footer_js_file .= '<script type="text/javascript" id="footerjs-'. str_replace('.', '-', strtolower(basename($jsfile))) .'" src="'. $jsfile .'"></script>'."\n";
  	}
  	return $str_footer_js_file;
  }

  public function set_header_css_file($cssFilename, $params='') {
  	$this->header_css_file[] = array($cssFilename, $params);
  }

  public function set_footer_css_file($cssFilename, $params='') {
  	$this->footer_css_file[] = array($cssFilename, $params);
  }

  public function printHeaderCSSFile() {
  	$str_header_css_file = "\n";
  	foreach($this->header_css_file as $cssfile) {
  		$arrURL = parse_url($cssfile[0]);
  		$params = (trim($cssfile[1]) != '')? ' '.trim($cssfile[1]) : '';
  		$str_header_css_file .= '<link id="headercss-'. str_replace('.', '-', strtolower(basename($arrURL['path']))) .'" href="'. $cssfile[0] .'" rel="stylesheet"'. $params .' />'."\n";
  	}
  	return $str_header_css_file;
  }

  public function printFooterCSSFile() {
  	$str_footer_css_file = "\n";
  	foreach($this->footer_css_file as $cssfile) {
  		$arrURL = parse_url($cssfile[0]);
  		$params = (trim($cssfile[1]) != '')? ' '.trim($cssfile[1]) : '';
  		$str_footer_css_file .= '<link id="footercss-'. str_replace('.', '-', strtolower(basename($arrURL['path']))) .'" href="'. $cssfile[0] .'" rel="stylesheet"'. $params .' />'."\n";
  	}
  	return $str_footer_css_file;
  }

  public function load_listing_module() {

	global $pf, $languages_id, $listing_sql, $listing, $column_list, $obj_catalog;

	$listing_method = FILENAME_PRODUCT_LISTING_COL;
	if ( file_exists(TEMPLATE_FS_CUSTOM_MODULES . $listing_method)) {
		require(TEMPLATE_FS_CUSTOM_MODULES . $listing_method);
	} else {
		require(DIR_WS_MODULES . $listing_method);
	}

  }
  public function lc_checklogin() {
  	if(isset($_SESSION['noaccount']))
  		return false;
  	elseif($_SESSION['customer_id'])
  		return true;
  	else
  		return false;
  }

  public function lc_get_branding_info() {
	global $languages_id;
	$site_branding_query = tep_db_query("SELECT * FROM " . TABLE_BRANDING_DESCRIPTION . " WHERE language_id = " . $languages_id);
	$site_brand_info = tep_db_fetch_array($site_branding_query);
	return $site_brand_info;
  }

  public function lc_mobile_detect() {
	$detect = new Mobile_Detect;
	return $detect;
  }

  public function lc_isMobile() {
	$detect = new Mobile_Detect;
	if($detect->isMobile())
		return true;
	else 	
		return false;
  }
  
  public function get_append_query () {

  }
  public function sanitize_get_var () {
	$query_string = htmlspecialchars_decode($_SERVER['QUERY_STRING']);
	parse_str($query_string, $output);

	foreach($_GET as $akey=>$aval) {
		unset($_GET[$akey]);
	}
	foreach($output as $gkey=>$gval) {
		$_GET[$gkey] = $gval;
	}
  }

  public function showhide_addtocart_action()	{
  	if(defined('SYSTEM_ADDON') && SYSTEM_ADDON == 'b2b') {
	  $hide_add_to_cart = hide_add_to_cart();
	  if ($hide_add_to_cart == 'true') {
		tep_redirect(tep_href_link('index.php', 'hide_add_to_cart_error=1'));
	  }
	}
  }

  public function show_addtocart_button()	{
  	$show_button = 0;
  	if(defined('SYSTEM_ADDON') && SYSTEM_ADDON == 'b2b') {
		$hide_add_to_cart = hide_add_to_cart();
		if ($hide_add_to_cart == 'false' && group_hide_show_prices() == 'true') {
		  	$show_button = 1;
		}
  	}
  	else
		$show_button = 1;

  	return $show_button;
  }
  public static function getButton($product_id)	{
	global $pf, $languages_id, $obj_catalog;
	$lc_text = '';
	if(method_exists(DEFAULT_TEMPLATE, 'grid_action_button')) {
  		$class_name = DEFAULT_TEMPLATE;
  		$lc_text = $class_name::grid_action_button($product_id);
	} elseif (method_exists('lc_pro', 'grid_action_button')) {
  		$lc_text = lc_pro::grid_action_button($product_id);
  	}
  	else {
		if ($obj_catalog->show_addtocart_button()) {
			if (tep_has_product_attributes($product_id) || tep_has_product_subproducts($product_id) ) {
				$lc_text = '<div class="col-sm-12 col-lg-12 col-12 no-margin-left product-listing-module-buy-now buy-btn-div buy-btn-div-gridlist"><a href="' . tep_href_link(basename($_SERVER['PHP_SELF']), tep_get_all_get_params(array('action','cPath','products_id')) . 'products_id=' . $product_id . '&amp;cPath=' . tep_get_product_path($product_id)) . '" class="product-listing-module-buy-now-button-ce btn btn-success btn-block"><i class="fa fa-eye btn-fa-cart" aria-hidden="true" style="font-size: 16px;margin-right: 2px"></i> '. IMAGE_BUTTON_IN_CART_ATTRIBUTE_CE .'</a></div>';
			} else {
				$lc_text = '<div class="col-sm-12 col-lg-12 col-12 no-margin-left product-listing-module-buy-now buy-btn-div buy-btn-div-gridlist"><a href="' . tep_href_link(basename($_SERVER['PHP_SELF']), tep_get_all_get_params(array('action','cPath','products_id')) . 'action=buy_now&amp;products_id=' . $product_id . '&amp;cPath=' . tep_get_product_path($product_id)) . '" class="product-listing-module-buy-now-button-ce btn btn-success btn-block"><i class="fa fa-shopping-cart btn-fa-cart" aria-hidden="true" style="font-size: 16px;margin-right: 2px"></i> '. IMAGE_BUTTON_IN_CART_CE .'</a></div>';
			}
		}
	}
  	return $lc_text;
  }
  public function prod_grid_listing($listing, $column_list)	{
	if(method_exists(DEFAULT_TEMPLATE, 'prod_grid_listing')) {
  		$class_name = DEFAULT_TEMPLATE;
  		$product_contents = $class_name::prod_grid_listing($listing, $column_list);
	} elseif (method_exists('lc_pro', 'prod_grid_listing')) {
  		$product_contents = lc_pro::prod_grid_listing($listing, $column_list);
  	}
  	else {
		$product_contents = self::default_prod_grid_listing($listing, $column_list);
  	}
	return $product_contents;
  }
  public static function default_prod_grid_listing($listing, $column_list)	{
		global $pf, $languages_id, $obj_catalog;
		$product_contents = array();
		for ($col=0, $n=sizeof($column_list); $col<$n; $col++)
		{
			$lc_align = '';
			$lc_text = '';
			$lc_bottom = '';
			$lc_name ='';
			$lc_mfg ='';
			switch ($column_list[$col])
			{
			  case 'PRODUCT_LIST_MODEL':
				$lc_align = '';
				if(trim($listing['products_model']) != ''){
					$lc_text = '<div class="bottom-cover-div col-lg-12 col-xl-12 col-sm-12 col-12 no-padding"><div class="col-sm-12 col-lg-12 no-padding  model-row model_name" style="height:30px;"><b class="model-label hide-on-mobile">Model: </b>' . $listing['products_model'] . '</div>';
				}else{
					$lc_text = '<div class="bottom-cover-div col-lg-12 col-xl-12 col-sm-12 col-12 no-padding"><div class="col-lg-12" style="height:30px;"></div>';

				}
				if(PRODUCT_LIST_BUY_NOW < 1 && PRODUCT_LIST_PRICE < 1){
				//$lc_text .= '</div>';
				}
				break;
			  case 'PRODUCT_LIST_NAME':
				$lc_align = '';
				/** custom **/
					$lc_desc = '';
					$lc_mfg= '';
					if($listing['products_blurb'] != ''){
						$lc_desc = '<p class="products_desc" id="products_desc">'.substr(strip_tags($listing['products_blurb']),'0','150').'</p>';
					}
					if(trim($listing['manufacturers_id']) > 0 && $listing['manufacturers_name'] != ''){
						$lc_mfg = '<div class="product-listing-module-manufacturer product-listing-module-manufacturer-box col-lg-12 col-xl-12 col-12 col-sm-12"><a href="' . tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . $listing['manufacturers_id'] . $params) . '">' . $listing['manufacturers_name'] . '</a></div>';
					}else{
					   //$lc_mfg = '<div class="product-listing-module-manufacturer product-listing-module-manufacturer-box col-lg-12 col-xl-12 col-12 col-sm-12" style="height:25px;"></div>';
					}
					$lc_custom_btn = '';
					$valid_to_checkout= true;
					if (STOCK_CHECK == 'true') {
						$stock_check = tep_check_stock((int)$listing['products_id'], 1);
						if (tep_not_null($stock_check) && (STOCK_ALLOW_CHECKOUT == 'false')) {
						  $valid_to_checkout = false;
						}
					}

				if (isset($_GET['manufacturers_id'])) {
				  $lc_text = '<div class="col-sm-12 col-lg-12 col-12 product-listing-module-name"><div class="no-padding-left no-padding-right name-box"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . (int)$_GET['manufacturers_id'] . '&amp;products_id=' . $listing['products_id'] . $params) . '">' . $listing['products_name'] . '</a></div>'. $lc_desc . $lc_mfg .'</div>';
				} else {
				  $lc_text = '<div class="col-sm-12 col-lg-12 col-12 product-listing-module-name"><div class="no-padding-left no-padding-right name-box"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&amp;' : '') . 'products_id=' . $listing['products_id'] . $params) . '">' . $listing['products_name'] . '</a></div>'. $lc_desc . $lc_mfg .'</div>';
				}

				break;
			  /* case 'PRODUCT_LIST_MANUFACTURER':
				$lc_align = '';
				if(trim($listing['manufacturers_id']) > 0 && $listing['manufacturers_name'] != ''){
					$lc_mfg = '<div class="product-listing-module-manufacturer product-listing-module-manufacturer-box col-lg-12 col-xl-12 col-12 col-sm-12"><b>Mfg.: </b><a href="' . tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . $listing['manufacturers_id'] . $params) . '">' . $listing['manufacturers_name'] . '</a></div>';
				}else{
					$lc_text = '';
				}
				break; */
			  case 'PRODUCT_LIST_PRICE':
				 $newdiv = '';
				if(PRODUCT_LIST_MODEL < 1){
				  $newdiv = '<div class="bottom-cover-div col-lg-12 col-xl-12 col-sm-12 col-12 no-padding">';
				}
				$pf->loadProduct($listing['products_id'],$languages_id);
				$lc_text =$newdiv.'<div class="col-sm-12 col-lg-12 col-xl-12 col-12 price_mainpage price_mainpage_gridlist"><p class="lead small-margin-bottom">'. $pf->getPriceStringShort('r') .'</p></div>';
				if(PRODUCT_LIST_BUY_NOW < 1){
				$lc_text .= '</div>';
				}
				break;
			  case 'PRODUCT_LIST_QUANTITY':
				$lc_align = 'right';
				if(trim($listing['products_quantity']) != '')
					$lc_text = '<div class="col-sm-12 col-lg-6 col-12 col-xl-6 qty-row qty-row-gl"><b>Qty:</b> ' . $listing['products_quantity'] . '</div>';
				break;
			  case 'PRODUCT_LIST_WEIGHT':
				$lc_align = 'right';
				if(trim($listing['products_weight']) != '')
					$lc_text = '<div class="col-sm-12 col-lg-6 col-12 col-xl-6 no-padding weight-row weight-row-gl"><b>Weight:</b> ' . $listing['products_weight'] . '</div>';
				break;
			  case 'PRODUCT_LIST_IMAGE':
				$lc_align = 'center';
				$imageprop = 'object-fit: contain;';
				if(trim(SMALL_IMAGE_WIDTH) != '')
					$imageprop .= ' width:'. SMALL_IMAGE_WIDTH .'px;';
				if(trim(SMALL_IMAGE_HEIGHT) != '')
					$imageprop .= ' height:'. SMALL_IMAGE_HEIGHT .'px;';
				$imageprop = 'class="img-responsive img-thumbnail" style="'. $imageprop .'"';
				$pf->loadProduct($listing['products_id'],$languages_id);
				$show_saleicon = '';
				if($pf->hasSpecialPrice == 1){
				$show_saleicon = '<div class="stickers"><div class="sale">Sale</div></div>';
				}
				if (isset($_GET['manufacturers_id'])) {
				  $lc_text =  '<div class="col-sm-12 col-lg-12 col-xl-12 col-12 thumb-img" style="margin-bottom:5px;"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . (int)$_GET['manufacturers_id'] . '&amp;products_id=' . $listing['products_id'] . $params) . '">' . tep_image(DIR_WS_PRODUCTS . $listing['products_image'], $listing['products_name'], '', '', $imageprop) . '</a></div>'.$show_saleicon;
				} else {
				  $lc_text = '<div class="col-sm-12 col-lg-12 col-xl-12 col-12 thumb-img" style="margin-bottom:5px;"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&amp;' : '') . 'products_id=' . $listing['products_id'] . $params) . '">' . tep_image(DIR_WS_PRODUCTS . $listing['products_image'], $listing['products_name'], '', '', $imageprop) . '</a></div>'.$show_saleicon;
				}
				break;
			  case 'PRODUCT_LIST_DATE_EXPECTED':
				  $duedate= date('m/d/Y', strtotime($listing['products_date_available']));
				  $lc_text = '<div class="col-sm-12 col-lg-12 no-margin-left buy-btn-div date-exp"><div class="alert-success" style="color:#ff0000;">' . TABLE_HEADING_DATE_EXPECTED . '&nbsp;' .$duedate .'</div></div>';
				  $lc_text .= '</div>'.'<div class="LC-quick-view-div col-lg-12 col-xl-12 col-sm-12 col-12"><a onclick="javascript:quick_view('.$listing['products_id'].')"  href="javascript:" title="Quick View">'.QUICK_VIEW_LINK.'</a> <a href="javascript:" class="" title="Add to Compare" onclick="javascript:compareProduct('.$listing['products_id'].')" data-original-title="Compare products"><i class="fa fa-exchange"></i></a></div>';
				break;
			  case 'PRODUCT_LIST_BUY_NOW':
				  $valid_to_checkout= true;
				  if (STOCK_CHECK == 'true') {
					$stock_check = tep_check_stock((int)$listing['products_id'], 1);
					if (tep_not_null($stock_check) && (STOCK_ALLOW_CHECKOUT == 'false')) {
					  $valid_to_checkout = false;
					}
				  }

				  if ($valid_to_checkout == true) {

					$lc_text = self::getButton($listing['products_id']);
					/*
					if ($obj_catalog->show_addtocart_button()) {
					  //$lc_text = '<div class="col-sm-12 col-lg-12 col-12 no-margin-left product-listing-module-buy-now buy-btn-div buy-btn-div-gridlist"><a href="' . tep_href_link(basename($_SERVER['PHP_SELF']), tep_get_all_get_params(array('action','cPath','products_id')) . 'action=buy_now&amp;products_id=' . $listing['products_id'] . '&amp;cPath=' . tep_get_product_path($listing['products_id']) . $params) . '"><button class="product-listing-module-buy-now-button btn btn-success btn-block">Add To Cart</button></a></div>';
					  if (tep_has_product_attributes($listing['products_id']) || tep_has_product_subproducts($listing['products_id']) ) {
					     $lc_text = '<div class="col-sm-12 col-lg-12 col-12 no-margin-left product-listing-module-buy-now buy-btn-div buy-btn-div-gridlist pl-1 pr-1">
					     			  <a class="product-listing-module-compare-button btn btn-success  pull-right"  href="javascript:" class="" title="Add to Compare" onclick="javascript:compareProduct('.$listing['products_id'].')" data-original-title="Compare products"><span>Compare </span> <i class="fa fa-exchange"></i></a>
					     			  <a class="product-listing-module-quickview-button btn btn-success  pull-right" onclick="javascript:quick_view('.$listing['products_id'].')"  href="javascript:" title="Quick View"><span>Quick View</span> '.QUICK_VIEW_LINK.'</a>
					     			  <a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&amp;' : '') . 'products_id=' . $listing['products_id'] . $params) . '" class="product-listing-module-buy-now-button btn btn-success btn-block"><i class="fa fa-eye btn-fa-cart" aria-hidden="true" style="font-size: 16px;margin-right: 2px"></i> <span>'. IMAGE_BUTTON_IN_CART_ATTRIBUTE .'</span></a>
					     			 </div>';
					  }else{
					     $lc_text = '<div class="col-sm-12 col-lg-12 col-12 no-margin-left product-listing-module-buy-now buy-btn-div buy-btn-div-gridlist pl-1 pr-1">
					     			  <a class="product-listing-module-compare-button btn btn-success  pull-right"  href="javascript:" class="" title="Add to Compare" onclick="javascript:compareProduct('.$listing['products_id'].')" data-original-title="Compare products"><span>Compare </span> <i class="fa fa-exchange"></i></a>
					     			  <a class="product-listing-module-quickview-button btn btn-success  pull-right" onclick="javascript:quick_view('.$listing['products_id'].')"  href="javascript:" title="Quick View"><span>Quick View</span> '.QUICK_VIEW_LINK.'</a>
					     			  <button class="product-listing-module-buy-now-button btn btn-success btn-block pull-right" onclick="javascript:ajaxAddtoCartInv('.$listing['products_id'].')"><i class="fa fa-shopping-cart btn-fa-cart" aria-hidden="true" style="font-size: 16px;margin-right: 2px"></i> <span>'. IMAGE_BUTTON_IN_CART .'</span></button>
					     			</div>';
					  }
				    }*/
				  }
				  $lc_text .= '</div>';
				  break;
			}
			//echo $lc_bottom;

			//$lc_text = $lc_text.'<div class="bottom-cover-div col-lg-12 col-xl-12 col-sm-12 col-12">'.$lc_bottom.'</div>';
			$product_contents[] = $lc_text;
		}
		return $product_contents;
	}
  public function getState()	{
		$country_id = (int) $_GET['country_id'];
		$isbilladdress = (isset($_GET['isbilladdress']) && $_GET['isbilladdress'] == 1) ? 1 : 0;
		if($isbilladdress){
			$inputname = 'bill_state';
		}else{
			$inputname = 'state';
		}

		$str_return_data = $this->getZonePullDown($inputname, $country_id);

		$arr_data = array('data' => $str_return_data);
		return $arr_data;
    }
  public function getCounty()	{
		$str_return_data = '';
	    $zone_code = tep_db_prepare_input($_GET['zone_code']);
		$zone_query1 = tep_db_query("SELECT c.county_name, c.zone_code, c.county_id FROM counties c inner join zones z on c.zone_code = z.zone_code  WHERE z.zone_name = '" .$zone_code . "' ORDER BY c.countries_id");

		if(tep_db_num_rows($zone_query1) > 0){
			$str_return_data .= '<div class="form-group full-width"><label class="sr-only"></label><select name="customers_county" class="form-control">';
			$str_return_data .= '<option value="">Select County</option>';
			while($row =tep_db_fetch_array($zone_query1)){
				$str_return_data .= '<option value="'.$row['county_id'].'">'.$row['county_name'].'</option>';
			}
			$str_return_data .= '</select></div>';
		}

		$arr_data = array('data' => $str_return_data);
		return $arr_data;
    }
  public function getZoneIdByName($country_id, $zone_name)	{

	$country_id = (int)$country_id;
	$zone_query = tep_db_query("select distinct zone_id from " . TABLE_ZONES . " where zone_country_id = '" . $country_id . "' and (zone_name = '" . tep_db_input($zone_name) . "' OR zone_code = '" . tep_db_input($zone_name) . "')");
	$zone = tep_db_fetch_array($zone_query);
	return (isset($zone['zone_id'])?$zone['zone_id']:0);

  }
  public function getZonePullDown($controlName='state', $country_id=223, $selectedZone='', $selectedState='')	{

	$zone_pull_down = '';
	if (defined('ACCOUNT_STATE') && ACCOUNT_STATE == 'true')
	{
		$zone_pull_down = '<label>'.STATE.'</label>';
		$entry_state_has_zones = true;
		$zones_query = tep_db_query("select zone_name, zone_id, zone_code from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_status = 1 order by zone_name");
		if (tep_db_num_rows($zones_query) > 0)
		{
			$zones_array = array();
			$selected_zone = '';
			$selected_zone_code = '';
			$zones_array[] = array('id' => '', 'text' => 'Select State');
			while ($zones_values = tep_db_fetch_array($zones_query))
			{
				$zones_array[] = array('id' => $zones_values['zone_name'], 'text' => $zones_values['zone_name']);
				if (strtolower($selectedZone) == strtolower($zones_values['zone_code']) || strtolower($selectedZone) == strtolower($zones_values['zone_name']) || $selectedZone == $zones_values['zone_id']) {
					$selected_zone = $zones_values['zone_name'];
					$selected_zone_code = $zones_values['zone_code'];
				}
			}
			if(defined('ENABLE_COUNTY') && ENABLE_COUNTY == 'true')
				$zone_pull_down .= tep_draw_pull_down_menu($controlName, $zones_array, $selected_zone, 'id="'. $controlName .'" class="form-control" onchange="javascript:county_check(this.value)"');
			else
				$zone_pull_down .= tep_draw_pull_down_menu($controlName, $zones_array, $selected_zone, 'id="'. $controlName .'" class="form-control"');

		} else {
			$zone_pull_down .= tep_draw_input_field($controlName, $selectedState, 'id="'. $controlName .'" class="form-control"' );
		}
	}
	return $zone_pull_down;
  }


  public function getCustomerExistByEmail($email='')	{
      $get_customer_info = tep_db_query("select customers_id, customers_email_address, purchased_without_account from " . TABLE_CUSTOMERS . " where lower(customers_email_address) = '" . tep_db_prepare_input($email) . "'");
      if(tep_db_num_rows($get_customer_info) > 0)
        return true;
      else
        return false;
  }

  public function getCountryById($country_id=0)	{
	$info = array();
	if((int) $country_id > 0) {
		$query = "select * from ". TABLE_COUNTRIES ." where countries_id = '". (int)$country_id ."' ORDER BY countries_name";
		$info = tep_db_get_result($query);
		$count = count($info);
	} else {
		$query = "select * from ". TABLE_COUNTRIES ." ORDER BY county_name";
		$info = tep_db_get_result($query);
		$count = count($info);
	}
	return array('count'=>$count, 'data'=>$info);
  }
  public function checkValidCountry($country_id)	{
		$data = $this->getCountryById($country_id);
		if($data['count'] > 0)
			return 1;
		else
			return 0;
	}

  public function getAttributePrice()	{
	global $languages_id, $currencies;
		$query = "select p.products_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price,
					IF(s.status, s.specials_new_products_price, p.products_price) as final_price
					FROM " . TABLE_PRODUCTS . " p LEFT JOIN " . TABLE_SPECIALS . " s on(s.products_id = p.products_id and s.status = 1),
					 " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . (int)$_POST['products_id'] . "'
					 and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'";
		$product_info_query = tep_db_query($query);
		$product_info = tep_db_fetch_array($product_info_query);

		$orig_price = $product_info['products_price'];
		$ret_price = $product_info['final_price'];
		foreach($_POST['id'] as $option => $value) {
			if ( ! is_array($value) ) {
				if($option > 0 && $value > 0){
					$options_values_id = $value;
					$attributes = tep_db_query("select op.options_id, ot.products_options_name, o.options_type, ov.products_options_values_name, op.options_values_price, op.price_prefix
												from " . TABLE_PRODUCTS_ATTRIBUTES . " op,
													 " . TABLE_PRODUCTS_OPTIONS_VALUES . " ov,
													 " . TABLE_PRODUCTS_OPTIONS . " o,
													 " . TABLE_PRODUCTS_OPTIONS_TEXT . " ot
												where op.products_id = " . $product_info['products_id'] . "
												  and op.options_values_id = " . $options_values_id . "
												  and op.options_id = " . $option . "
												  and ov.products_options_values_id = op.options_values_id
												  and ov.language_id = " . (int)$languages_id . "
												  and o.products_options_id = op.options_id
												  and ot.products_options_text_id = o.products_options_id
												  and ot.language_id = " . (int)$languages_id . "
											   ");
					$attributes_values = tep_db_fetch_array($attributes);

					//options_values_price
					if($attributes_values['price_prefix'] == '-')
					{
						$ret_price = $ret_price - $attributes_values['options_values_price'];
						$orig_price = $orig_price - $attributes_values['options_values_price'];
					}
					else
					{
						$ret_price = $ret_price + $attributes_values['options_values_price'];
						$orig_price = $orig_price + $attributes_values['options_values_price'];
					}
				}
			}elseif( isset($value['s'] ) ) {
				foreach ($value['s'] as $v) {
					if($option > 0 && $v > 0){
						$options_values_id = $v;
						$attributes = tep_db_query("select op.options_id, ot.products_options_name, o.options_type, ov.products_options_values_name, op.options_values_price, op.price_prefix
													from " . TABLE_PRODUCTS_ATTRIBUTES . " op,
														 " . TABLE_PRODUCTS_OPTIONS_VALUES . " ov,
														 " . TABLE_PRODUCTS_OPTIONS . " o,
														 " . TABLE_PRODUCTS_OPTIONS_TEXT . " ot
													where op.products_id = " . $product_info['products_id'] . "
													  and op.options_values_id = " . $options_values_id . "
													  and op.options_id = " . $option . "
													  and ov.products_options_values_id = op.options_values_id
													  and ov.language_id = " . (int)$languages_id . "
													  and o.products_options_id = op.options_id
													  and ot.products_options_text_id = o.products_options_id
													  and ot.language_id = " . (int)$languages_id . "
												   ");
						$attributes_values = tep_db_fetch_array($attributes);

						//options_values_price
						if($attributes_values['price_prefix'] == '-')
						{
							$ret_price = $ret_price - $attributes_values['options_values_price'];
							$orig_price = $orig_price - $attributes_values['options_values_price'];
						}
						else
						{
							$ret_price = $ret_price + $attributes_values['options_values_price'];
							$orig_price = $orig_price + $attributes_values['options_values_price'];
						}
					}
				}
			}elseif( isset($value['c'] ) ) {
				foreach ($value['c'] as $v) {
					if($option > 0 && $v > 0){
						$options_values_id = $v;
						//echo $options_values_id.'------'.$option.'<br>';
						$attributes = tep_db_query("select op.options_id, ot.products_options_name, o.options_type, ov.products_options_values_name, op.options_values_price, op.price_prefix
													from " . TABLE_PRODUCTS_ATTRIBUTES . " op,
														 " . TABLE_PRODUCTS_OPTIONS_VALUES . " ov,
														 " . TABLE_PRODUCTS_OPTIONS . " o,
														 " . TABLE_PRODUCTS_OPTIONS_TEXT . " ot
													where op.products_id = " . $product_info['products_id'] . "
													  and op.options_values_id = " . $options_values_id . "
													  and op.options_id = " . $option . "
													  and ov.products_options_values_id = op.options_values_id
													  and ov.language_id = " . (int)$languages_id . "
													  and o.products_options_id = op.options_id
													  and ot.products_options_text_id = o.products_options_id
													  and ot.language_id = " . (int)$languages_id . "
												   ");
						$attributes_values = tep_db_fetch_array($attributes);

						//options_values_price
						if($attributes_values['price_prefix'] == '-')
						{
							$ret_price = $ret_price - $attributes_values['options_values_price'];
							$orig_price = $orig_price - $attributes_values['options_values_price'];
						}
						else
						{
							$ret_price = $ret_price + $attributes_values['options_values_price'];
							$orig_price = $orig_price + $attributes_values['options_values_price'];
							//echo $ret_price.'---------'.$attributes_values['options_values_price'].'<br>';
						}
					}
				}
			} elseif ( isset($value['t'] ) ) {
			  	$textvalue = $value['t'];
			  	if($textvalue == 'Yes'){
					//only valid for boolean type with value 1
					$attributes = tep_db_query("select op.options_id, ot.products_options_name, o.options_type, ov.products_options_values_name, op.options_values_price, op.price_prefix
												from " . TABLE_PRODUCTS_ATTRIBUTES . " op,
													 " . TABLE_PRODUCTS_OPTIONS_VALUES . " ov,
													 " . TABLE_PRODUCTS_OPTIONS . " o,
													 " . TABLE_PRODUCTS_OPTIONS_TEXT . " ot
												where op.products_id = " . $product_info['products_id'] . "
												  and op.options_id = " . $option . "
												  and o.products_options_id = op.options_id
												  and ot.products_options_text_id = o.products_options_id
												  and ot.language_id = " . (int)$languages_id . "
											   ");
					 if(tep_db_num_rows($attributes) > 0){
						$attributes_values = tep_db_fetch_array($attributes);
						if ($textvalue != ''){
							if($attributes_values['price_prefix'] == '-')
							{
								$ret_price = $ret_price - $attributes_values['options_values_price'];
								$orig_price = $orig_price - $attributes_values['options_values_price'];
							}
							else
							{
								$ret_price = $ret_price + $attributes_values['options_values_price'];
								$orig_price = $orig_price + $attributes_values['options_values_price'];
							}
						}
					}
				}
			 }
		}


		$str_return_data = $currencies->format($ret_price);
		$arr_data = array('data' => $str_return_data);
		return $arr_data;
    }

  public function stockCheck()	{
		global $order;
	// Stock Check
	  $any_out_of_stock = false;
	  if (STOCK_CHECK == 'true') {
		for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
		  if (tep_check_stock($order->products[$i]['id'], $order->products[$i]['qty'])) {
			$any_out_of_stock = true;
		  }
		}
		// Out of Stock
		if ( (STOCK_ALLOW_CHECKOUT != 'true') && ($any_out_of_stock == true) ) {
		  tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
		}
	  }
    }

  public function getCustomerIPInfo()	{
		return getCustomerIPInfo();
	}
  public function setCatalogData()	{
  		$category = $this->getCategoryTree();
		$this->category_tree = $category['tree'];
		$this->category_tree_all = $category['all'];
		$this->permalinks = $this->getPermalinks();
	}
  public function getPermalinks()	{

		$arr_permalink = array();
		$permalink_query = tep_db_query("SELECT categories_id, permalink_name FROM permalinks where categories_id > 0");
		while($permalink = tep_db_fetch_array($permalink_query)) {
			$arr_permalink['category'][$permalink['categories_id']] = $permalink;
		}

		$permalink_query = tep_db_query("SELECT pages_categories_id, permalink_name FROM permalinks where pages_categories_id > 0 ");
		while($permalink = tep_db_fetch_array($permalink_query)) {
			$arr_permalink['page_category'][$permalink['pages_categories_id']] = $permalink;
		}

		$permalink_query = tep_db_query("SELECT pages_id, permalink_name FROM permalinks where pages_id > 0 ");
		while($permalink = tep_db_fetch_array($permalink_query)) {
			$arr_permalink['page'][$permalink['pages_id']] = $permalink;
		}

		$permalink_query = tep_db_query("SELECT manufacturers_id, permalink_name FROM permalinks where manufacturers_id > 0 ");
		while($permalink = tep_db_fetch_array($permalink_query)) {
			$arr_permalink['manufacturer'][$permalink['manufacturers_id']] = $permalink;
		}
		return $arr_permalink;
  }
  public function getCategoryTree()	{
		global $languages_id;
		$catTree = array();
		$AllCategories = array();
		$AllCategoriesAndParent = array();
		$cPath_array = array();

		$sql = "select c.categories_id, cd.categories_name,  c.categories_image, c.parent_id, c.categories_banner_image from  " . TABLE_CATEGORIES . " c,  " . TABLE_CATEGORIES_DESCRIPTION . " cd
						where c.categories_id = cd.categories_id and c.categories_status=1 and cd.language_id='" . $languages_id ."'";
		$sql .= self::b2b_filter_sql('c.products_group_access');
		$sql .= " order by sort_order, cd.categories_name";
		$rs = tep_db_query($sql);
		while($rw = tep_db_fetch_array($rs)) {

			$AllCategories[$rw['categories_id']] = $rw;
			$AllCategoriesAndParent[$rw['parent_id']][$rw['categories_id']] = $rw;

		}

		$catgoryParents = $AllCategoriesAndParent;
		$catTree = $AllCategoriesAndParent[0];
		unset($AllCategoriesAndParent[0]);
		foreach($catTree as $cat_id=>$parentNode) {
			$cPath_array = array();
			$cPath_array[] = $parentNode['categories_id'];
			$cPath_new = 'cPath=' . $parentNode['categories_id'];
			$catTree[$cat_id]['cPath'] = $cPath_new;
			$catTree[$cat_id]['cPath_array'] = $cPath_array;
			if(isset($AllCategoriesAndParent[$parentNode['categories_id']])) {
				$nodeData = $AllCategoriesAndParent[$parentNode['categories_id']];
				$catTree[$parentNode['categories_id']]['sub'] = $nodeData;
				unset($AllCategoriesAndParent[$parentNode['categories_id']]);
				if(count($nodeData) > 0) {
					foreach($nodeData as $subNode){
						$cPath_id = $parentNode['categories_id']. '_' . $subNode['categories_id'];
						$cPath_new = 'cPath=' . $parentNode['categories_id']. '_' . $subNode['categories_id'];
						$catTree[$cat_id]['sub'][$subNode['categories_id']]['cPath'] = $cPath_new;
						$catTree[$cat_id]['sub'][$subNode['categories_id']]['cPath_array'] = explode('_', $cPath_id);
						if(isset($AllCategoriesAndParent[$subNode['categories_id']])) {
							$nodeData = $AllCategoriesAndParent[$subNode['categories_id']];
							$catTree[$parentNode['categories_id']]['sub'][$subNode['categories_id']]['sub'] = $nodeData;
							unset($AllCategoriesAndParent[$subNode['categories_id']]);

							foreach($nodeData as $subNode2){
								$cPath_id = $parentNode['categories_id']. '_' . $subNode['categories_id']. '_' . $subNode2['categories_id'];
								$cPath_new = 'cPath=' . $cPath_id;
								$catTree[$cat_id]['sub'][$subNode['categories_id']]['sub'][$subNode2['categories_id']]['cPath'] = $cPath_new;
								$catTree[$cat_id]['sub'][$subNode['categories_id']]['sub'][$subNode2['categories_id']]['cPath_array'] = explode('_', $cPath_id);
							}
						}
					}
				}
			}
		}
		return array('tree'=>$catTree, 'all'=>$AllCategories, 'categoryWithParents'=>$catgoryParents);
	}

    public function review_form(){
    	global $pf, $languages_id, $obj_catalog, $captcha;
    	$readonly = '';
	    $customer_query = tep_db_query("select customers_firstname, customers_lastname, customers_email_address from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$_SESSION['customer_id'] . "'");
	    $customer = tep_db_fetch_array($customer_query);
	    if(isset($_SESSION['customer_id']) && $_SESSION['customer_id'] > 0){
	    	$readonly = 'readonly';
	    }
    	$formhtml = '';
    	$formhtml .= tep_draw_form('review', '' , 'post','id="review_form"');
    	$formhtml .= '<div class="reviewforms">
    					  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12"> <span id="reviewerror"></span></div>
						  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">
								<label>Name: </label>
								<input type="hidden" name="products_id" value="'.$_POST['products_id'].'">
								<input type="text" '.$readonly.' name="firstname" value="'.$customer['customers_firstname'].' '.$customer['customers_lastname'].'" class="form-control"><span id="redq">*</span>
						  </div>
						  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">
								<label>Email Address: </label>
								<input type="text" '.$readonly.' name="emailaddress" value="'.$customer['customers_email_address'].'" class="form-control"><span id="redq">*</span>
						  </div>
						  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">
								<label>Comments: </label>
								<textarea name="comments" class="form-control"></textarea><span id="redq">*</span>
						  </div>
						  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">
						  		<label>Rate Me: </label>
								<div class="review-container">
									<div class="card-body text-center clearfix">
											<fieldset class="rating">
												<input type="radio" id="star5" name="rating" value="5" /><label class="full" for="star5" title="Awesome"></label>
												<input type="radio" id="star4" name="rating" value="4" /><label class="full" for="star4" title="Pretty good"></label>
												<input type="radio" id="star3" name="rating" value="3" /><label class="full" for="star3" title="Average"></label>
												<input type="radio" id="star2" name="rating" value="2" /><label class="full" for="star2" title="Bad"></label>
												<input type="radio" id="star1" name="rating" value="1" /><label class="full" for="star1" title=""></label>
												<input type="radio" class="reset-option" name="rating" value="reset" />
											</fieldset>
									</div>
								</div>
						  </div>';
			$formhtml .= '<div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">';
							if ($captcha->captcha_status('VVC_PRODUCT_REVIEWS_ON_OFF')){
								$captcha_instructions = trim($captcha->display_captcha_instructions());
								$formhtml .= '<label>'.$captcha->display_captcha_label().'</label>';
								$formhtml .= '<div class="form-group full-width margin-bottom">'.$captcha->render_captcha_image().$captcha->render_captcha_control('class="form-control"').'</div>';
								if($captcha_instructions != '')
									$formhtml .= '<div class="form-group full-width margin-bottom">'.$captcha_instructions.'</div>';
							}
			$formhtml .= '</div>';
		$formhtml .= '</div>
					  <div class="col-md-12 col-lg-12 col-sm-12 col-12 col-xl-12">
					  		<button type="button" name="addreview" onclick="return ajaxAddReview();" value="addreview" class="btn btn-primary btn-savecontinue">Add Review</button>
					  </div>
					 ';
		$formhtml .= '</form>';
        echo $formhtml;
    }
	public function ajax_add_review(){
    	global $pf, $languages_id, $obj_catalog, $captcha, $messageStack;
    	$errormsg = '';
    	$error = false;
    	$name = tep_db_input($_POST['firstname']);
    	$email = tep_db_input($_POST['emailaddress']);
    	$comments = tep_db_input(strip_tags($_POST['comments']));
    	$rating = tep_db_input($_POST['rating']);
    	$customers_id = (int)$_SESSION['customer_id'];
    	$products_id = (int)$_POST['products_id'];
    	if($comments == '' || $rating == '' || $name == '' || $email == ''){
    		$error = true;
    		$errormsg .= '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Please Fill up all Mandetory(*) Fields.<br>';
    	}
		if ($captcha->captcha_status('VVC_PRODUCT_REVIEWS_ON_OFF')){
				if(!$captcha->validate_captcha()) {
					$error = true;
					$errormsg .= '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> '.VISUAL_VERIFY_CODE_ENTRY_ERROR.'<br>';
				}
		}
    	if($error == false){
      		tep_db_query("insert into " . TABLE_REVIEWS . " (products_id, customers_id, customers_name, customers_email, reviews_rating, date_added) values ('" . (int)$products_id . "', '" . (int)$_SESSION['customer_id'] . "', '" . $name . "', '".$email."', '" . $rating . "', now())");
      		$insert_id = tep_db_insert_id();
      		tep_db_query("insert into " . TABLE_REVIEWS_DESCRIPTION . " (reviews_id, languages_id, reviews_text) values ('" . (int)$insert_id . "', '" . (int)$languages_id . "', '" . $comments . "')");
      		$messageStack->add_session('frontend_message', 'Your Review has been Sent to Us Successfully!! .','success');
      	}else{
      		echo $errormsg;
      	}
    }

}
?>
