<?php
/*
	Freeway eCommerce
	http://www.openfreeway.org
	Copyright (c) 2007 ZacWare
	Released under the GNU General Public License 
*/	
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();

		$template_content=tep_load_template_content('product_listing.tpl.php');	

		$template_details["VALUE_NO_PRODUCT"]=NO_PRODUCTS;

		$cPath = $current_category_id;
		
		

		// Get the category name and description
		$category_query = tep_db_query("select c.parent_id,c.date_id,cd.categories_name, cd.categories_heading_title, cd.categories_description,cd.concert_venue,cd.concert_date,cd.concert_time, c.categories_image from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = '" . $cPath . "' and cd.categories_id = '" . $cPath . "' and cd.language_id = '" . (int)$FSESSION->languages_id . "'");		
		$category = tep_db_fetch_array($category_query);
		
		
			// $serverDateNow = date(EVENTS_DATE_FORMAT,getServerDate(false));
				
					// if ($category["concert_date"]<$serverDateNow)
					// {
					// //$customer_time='Date now is ' . date('M d, Y');
					// $customer_time='Date now is ' . date('M d, Y').' <br>  Time now is ' .date("g:i:a");
					// }elseif($category["concert_date"]>$serverDateNow)
					// {
					// $customer_time='These ' . ITEMS . ' are done!';
					// }else
					// {	
					// $customer_time='Time now is ' .date("g:i:a");
					// }
					
		// $concert_query = tep_db_query("SELECT * FROM " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd  WHERE c.categories_id=cd.categories_id and c.categories_id= '" . $category["parent_id"] . "' and cd.language_id = '" . (int)$FSESSION->languages_id . "'");
		// while ($result = tep_db_fetch_array($concert_query)) 
		// {
			// $categories_name = $result['categories_name'];
			// $categories_heading = $result['categories_heading_title'];
			// $cvenue = $result['concert_venue'];
			
			// $cdate = strtotime($result['concert_date']);
			// $thedate= date('M d, Y', $cdate);
			// $ctime = $result['concert_time'];
			// $cdesc = $result['categories_description'];
			
		// }
		

		$template_details["VALUE_CATEGORY_NAME"]=$category["categories_name"];
		$template_details["VALUE_CATEGORY_TITLE"]=$category["categories_heading_title"];
		$template_details["VALUE_CATEGORY_DESC"]=$category["categories_description"];
		$template_details["VALUE_CATEGORY_INFO"]='(' . (int)$current_category_id . ')';
		$template_details["VALUE_CATEGORY_VENUE"]=$category["concert_venue"];
		$template_details["VALUE_CATEGORY_DATE"]=$category["concert_date"];
		$template_details["VALUE_CATEGORY_TIME"]=$category["concert_time"];
		$template_details["VALUE_CATEGORY_IMAGE"]=$category["categories_image"];
		$template_details["VALUE_TEXT_TYPE"]=TEXT_TYPE;
		$template_details["VALUE_TEXT_PRICE"]=TEXT_PRICE;
		$template_details["VALUE_TEXT_QUANTITY"]=TEXT_QUANTITY;
		
		// $template_details["VALUE_CATEGORY_NAME"]=$category["categories_name"];
		// $template_details["VALUE_CATEGORY_TITLE"]=$categories_heading;
		// $template_details["VALUE_CATEGORY_VENUE"]=$cvenue;
		// $template_details["VALUE_CATEGORY_DATE"]=$thedate;
		// $template_details["VALUE_TEXT_SERVERDATENOW"]=$serverDateNow;
		// $template_details["VALUE_TEXT_CUSTOMERTIME"]=$customer_time;
		
		if(ALT_GA_TEMPLATE=='yes')
		{
		$template_details["VALUE_TEXT_PLEASE"]=TEXT_PLEASE_ADD_TO_CART;
		}
		else
		{
		$template_details["VALUE_TEXT_PLEASE"]='';	
		}
		
		$template_details["VALUE_FORM_START"]= tep_draw_form('add_multi', 'shopping_cart.php?action=add_multi');
		
		$category_ga_query = tep_db_query("select categories_GA,categories_quantity_remaining from " . TABLE_CATEGORIES . " where categories_id = '" . $cPath. "' limit 1");
		if (tep_db_num_rows($category_ga_query)) 
		{ 
			$category_ga = tep_db_fetch_array($category_ga_query);
			if(HIDE_GA_ONLY_QTY=="no")
			{	  
				if($category_ga['categories_GA']==1 && HIDE_GA_QTY=='no')
				{//this is a GA category with master quantity
				$template_details["VALUE_GA_TOTAL"]='<div class="ga_total">' . TEXT_GA_REMAIN_LEFT . '<span style="color:#ff0000">' . $category_ga['categories_quantity_remaining'] . '</span>' . TEXT_GA_REMAIN_RIGHT . '</div>';
				}else
				{
				$template_details["VALUE_GA_TOTAL"]='';
				}
			}else
			{
			$template_details["VALUE_GA_TOTAL"]='';
			}
		}

		$check_restrict_customer="";
		$customer_group_id=0;
		$check_restrict_customer=" and ((p.restrict_to_customers='' OR ISNULL(p.restrict_to_customers)) AND (p.restrict_to_groups='' OR ISNULL(p.restrict_to_groups)))";
		if($FSESSION->is_registered('customer_id'))
		{
			$customer_group_id=get_customer_group_id();
			$check_restrict_customer=substr($check_restrict_customer,0,-1)." OR (p.restrict_to_customers like '%". tep_db_input($FSESSION->customer_id) ."%' OR p.restrict_to_groups like '%". tep_db_input($customer_group_id) ."%'))";
		}
	if(!defined('ALT_GA_TEMPLATE'))
	{
	define('ALT_GA_TEMPLATE', 'no');
	}		
		if(SHOW_GA_SOLDOUT=='yes')
		{
			$soldout=' and products_status<2 ';
		}else
		{
			$soldout=' and products_status>0 ';
		}
		$check_pda_query = tep_db_query("select * from " . TABLE_PRODUCTS . " where products_id = '" . $pid . "'");
        $check_pda = tep_db_fetch_array($check_pda_query);
		//$soldout='and products_status=1 ';
		//We get the actual server date and time
		$serverDate = date('Y-m-d H:i',getServerDate(false));
		//Let's add 45 minutes
		$newtimestamp = strtotime($serverDate . ' + '.ADD_MINUTES.' minutes');
		//Now we have a newdatetime+45
		$stamp= date('Y-m-d H:i', $newtimestamp);
		//If the products_date_available is more than ....we kill the product.
		if($check_pda['products_date_available']>0)
		{
		$expires=" and  p.products_date_available >'" . $stamp . "' ";
		}else
		{
		$expires='';	
		}
			
		$product_repeat=array();
		$icnt=0;
		$listing_query = tep_db_query("select 
		p.products_id,
		p.color_code,
		p.products_quantity, 
		p.products_price_break,
		pd.products_name,
		pd.products_description,
		p.products_quantity,
		p.products_model,
		p.section_id,
		p.parent_id,p.
		products_sku, 
		p.products_season,
		p.products_image_1,
		p.products_price, 
		p.products_weight, 
		p.products_sort_order, 
		date_format(p.products_date_added,'%Y-%m-%d') as products_date_added, 
		date_format(p.products_last_modified,'%Y-%m-%d') as products_last_modified, 
		date_format(p.products_date_available, '%Y-%m-%d %H:%i') as products_date_available, 
		p.products_status, 
		p.products_tax_class_id,
		p.manufacturers_id,
		p.restrict_to_groups,
		p.restrict_to_customers,
		p.product_type,
		p.master_quantity 
		from " . TABLE_PRODUCTS . " p join ".TABLE_PRODUCTS_TO_CATEGORIES . " p2c on p2c.products_id=p.products_id join ".TABLE_PRODUCTS_DESCRIPTION . " pd on pd.products_id=p.products_id where p.product_type !='P' and p.products_id >'0' " . $expires . " " . $soldout . " and p2c.categories_id = '" . $cPath . "' and pd.language_id = '" . (int)$FSESSION->languages_id . "' ". $check_restrict_customer." order by p.products_id asc");
			
		while ($listing = tep_db_fetch_array($listing_query)) 
		{

			$serverDateNow = date(EVENTS_DATE_FORMAT,getServerDate(false));
				
					if ($cdate>$serverDateNow)
					{
					//$customer_time='Date now is ' . date('M d, Y');
					$customer_time='Date now is ' . date('M d, Y').' <br>  Time now is ' .date("g:i:a");
					}elseif($cdate<$serverDateNow)
					{
					$customer_time='These ' . ITEMS . ' are done!';
					}else
					{	
					$customer_time='Time now is ' .date("g:i:a");
					}

					//echo '<h1>' . $customer_time . '</h1>';
					//echo $cdate;

			$pid = $listing['products_id'];
			$qty = $listing['products_quantity'];
			$color = $listing['color_code'];
			$status = $listing['products_status'];
			$type = $listing['product_type'];
			$pda = $listing['products_date_available'];
			$pname = $listing['products_name'];
			$pdesc = mb_strimwidth($listing['products_description'], 0, 250, "...");
			$img1 = "small/" . $listing['products_image_1'];
			$price = $currencies->format(tep_add_tax($listing['products_price'], tep_get_tax_rate($listing['products_tax_class_id'])));
		
					
			$salemaker_text = '';
			//multi buy check for salemaker
			$sDate=getServerDate(true);
			$sale_query = tep_db_query("select sale_id,sale_specials_condition, sale_deduction_value, sale_deduction_type,choice_text,choice_warning from " . TABLE_SALEMAKER_SALES . " where sale_discount_type='C'  and ((sale_categories_all='' and sale_products_selected='') or sale_categories_all like '%," . tep_db_input($current_category_id) . ",%' or sale_products_selected like '%," . tep_db_input($pid) .",%') and sale_status = '1' and (sale_date_start <='" . tep_db_input($sDate) . "' or sale_date_start = '0000-00-00') and (sale_date_end >= '" . tep_db_input($sDate) . "' or sale_date_end = '0000-00-00') and (sale_pricerange_from <= " . $listing['products_price'] . " or sale_pricerange_from = '0') and (sale_pricerange_to >= " . $listing['products_price'] . " or sale_pricerange_to = '0') order by sale_deduction_value");
			
			if(tep_db_num_rows($sale_query) > 0)
			{ 
			$salemaker_text = TEXT_DISCOUNT_ALERT3;
			}
			$template_details["VALUE_SALEMAKER"]=$salemaker_text;
			// if  ($g['products_date_available']>$serverDate){
			// echo "hello  world";
			// }else{
			// echo $serverDate;
			//break should stay enabled!
			 //echo '<br>';
			 //echo $stamp;
			 //echo $newtimestamp;
			// }
					
		$product_repeat[$icnt]=array('NAME'=>'','MANUFACTURER'=>'','PRICE'=>'','QUANTITY'=>'','WEIGHT'=>'','IMAGE'=>'','BUY_NOW'=>'','DESCRIPTION'=>'');
		for ($col=0, $n=sizeof($column_list); $col<$n; $col++) 
		{ 
			switch ($column_list[$col]) 
			{
				case 'PRODUCT_LIST_NAME':
				//print_r ($listing);
					if ($FREQUEST->getvalue('manufacturers_id')!='') 
					{
					$product_repeat[$icnt]['NAME']='<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $FREQUEST->getvalue('manufacturers_id','int') . '&products_id=' . $listing['products_id']) . '">' . $listing['products_name'] . '</a>';
					} else 
					{
					$product_repeat[$icnt]['NAME']='<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) . '">' . $listing['products_name'] . '</a>&nbsp;';
					}
					break;
				case 'PRODUCT_LIST_PRICE':
					if (tep_get_products_special_price($listing['products_id'])) 
					{
					$product_repeat[$icnt]['PRICE'] = '<s>' .  $currencies->display_price($listing['products_price'], tep_get_tax_rate($listing['products_tax_class_id']),'1',true) . '</s>&nbsp;&nbsp;<span>' . $currencies->display_price(tep_get_products_special_price($listing['products_id']), tep_get_tax_rate($listing['products_tax_class_id'])) . '</span>';
					} else {
					$product_repeat[$icnt]['PRICE'] = $currencies->display_price($listing['products_price'], tep_get_tax_rate($listing['products_tax_class_id']),'1',true);
					}
					break;
				case 'PRODUCT_LIST_QUANTITY':
					$product_repeat[$icnt]['QUANTITY'] = '<Br>' . $listing['products_quantity'];
					break;
				case 'PRODUCT_LIST_IMAGE':
					if ($FREQUEST->getvalue('manufacturers_id')!='') 
					{
				//	echo "width=" . $img_width . "height=" . $img_height;
					$product_repeat[$icnt]['IMAGE'] = '<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $FREQUEST->getvalue('manufacturers_id') . '&products_id=' . $listing['products_id']) . '">' . tep_product_small_image($listing['products_image_1'], $listing['products_title_1'],"title=" . $listing['products_name'],$timg_width,$timg_height) . '</a>';
					} else 
					{ 
					$product_repeat[$icnt]['IMAGE'] = '<a class="img-fluid" href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) . '">' . tep_product_small_image($listing['products_image_1'], $listing['products_title_1'], "title=" . $listing['products_name'],20,20) . '</a>';
					}
					break;
				case 'PRODUCT_LIST_BUY_NOW':
					if ($listing['products_status']<1)
					{
					$product_repeat[$icnt]['BUY_NOW'] = '<span>' . tep_template_image_button('', IMAGE_BUTTON_SOLD) . '</span>';
					}
					else
					{
					//Allow BUY NOW to go direct to shopping cart
					if(BUY_NOW_CART == 'yes')
					{
					$product_repeat[$icnt]['BUY_NOW'] ='<a href="' . tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action')) . 'action=buy_now&products_id=' . $listing['products_id']) . '">' . tep_template_image_button('', IMAGE_BUTTON_BUY_NOW) . '</a>';
					}
					else
					{
						if(ALT_GA_TEMPLATE=='yes')
						{
							
							$qty_box=tep_draw_input_field('qty['.$pid.']',0,'id="qty['.$pid.']'.'" 
									value="0" 
									style="margin:0;padding:0px; text-align: center;min-width:55px" size="3" onfocus="this.value=\'\';" onBlur="javascript:checkStock(\'\');" onKeyDown="javascript:return numericOnly(event);"');
							
							$product_repeat[$icnt]['BUY_NOW'] ='
							<table><tr><td>
							<a href="javascript:add_'.$pid.'(-1)">
							<span class="btn btn-primary"><i class="fa fa-minus"></i></span>
							</a>
							<script type="text/javascript">
								var currentValue_'.$pid.' = 0;
								var add_'.$pid.' = function(valueToAdd){
									currentValue_'.$pid.' += valueToAdd;
									if (currentValue_'.$pid.' < 1)
									{
									 currentValue_'.$pid.' =0;
									// return;
									}
									document.getElementById(\'qty['.$pid.']'.'\').value = currentValue_'.$pid.';
									};
							</script>
							</td><td>
							'.$qty_box.'
							</td><td>
							<a href="javascript:add_'.$pid.'(1)">
							<span class="btn btn-primary"><i class="fa fa-plus"></i></span>
							</a>
							</td></tr></table>
							';
							
							$template_details["VALUE_FORM_END"]="
							<span style=\"float:right;cursor:pointer\" onClick='document.forms[\"add_multi\"].submit()'><strong>" .tep_template_image_button('', IMAGE_BUTTON_IN_CART) . "</strong></span>&nbsp;
							";
						}
						else
						{
						$product_repeat[$icnt]['BUY_NOW'] ='<a href="' . tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action')) . 'action=buy_now&products_id=' . $listing['products_id']) . '">' . tep_template_image_button('', IMAGE_BUTTON_BUY_NOW) . '</a>';
						$template_details["VALUE_FORM_END"]="";
						}
						}
					}
					break;
				case 'PRODUCT_LIST_DESCRIPTION':
					$description=strip_tags($listing['products_description'],'<br>');
					$product_repeat[$icnt]['DESCRIPTION'] = $pdesc;
					break;
			}
		}
		$icnt++;
		}
		$template_details["REPEAT_PRODUCT_LIST"]=$product_repeat;
		unset($product_repeat);
		mysqli_free_result($listing_query);

		$template_details["SECTION_PRODUCT"]=1;
		$template_details["SECTION_NO_PRODUCT"]=0;
			
			

		//$template_details["VALUE_SYSTEM_TIME"]='Time now is ' .date("g:i:a");
		$replaced_content=$template_content;
		$template_name = "";

		$scnt=0;
		while(list($key,$value)=each($template_details))
		{
			switch(substr($key,0,strpos($key,'_')))
			{
				case "VALUE":
					$replaced_content=str_replace("{{" . $key . "}}",$value,$replaced_content);
					break;
				case "SECTION":
					if ($value!=1)
					{
						$start_pos=strpos($replaced_content,"{{" . $key . "_START}}");
						$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
						$temp_content=substr($replaced_content,0,$start_pos);
						$temp_content.=substr($replaced_content,$end_pos+strlen("{{" . $key ."_END}}"));
						$replaced_content=$temp_content;
						unset($temp_content);
					} else 
					{
						$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
					}
					break;
					//I think this is it
				case "REPEAT":
					$start_pos=strpos($replaced_content,"{{" . $key . "_START}}")+strlen("{{" . $key ."_START}}");
					$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
					$repeat_content=substr($replaced_content,$start_pos,$end_pos-$start_pos);
					$merged_total_content='' . "\n";
					$col=0;
					$row=0;
					for ($icnt=0,$n=count($value);$icnt<$n;$icnt++)
					{
						$merged_content='';
						if ($col==0 || $ttotal_cols==1)
						{
							$merged_content.='';
						}
							$merged_content.='' . $repeat_content;

						reset($value[$icnt]);
						while(list($itemkey,)=each($value[$icnt])){
							$merged_content=str_replace("{{" . $key . "_" . $itemkey . "}}",$value[$icnt][$itemkey],$merged_content);
						}
						$col++;
						if ($col==$ttotal_cols) 
						{
							$col=0;
							$row++;
						}
						if ($col==0 || $ttotal_cols==1) 
						$merged_content.='';
						$merged_total_content.="\n" . $merged_content;
					}
					
					$merged_total_content.="";
					$replaced_content=substr($replaced_content,0,$start_pos) . $merged_total_content . substr($replaced_content,$end_pos);
					unset($merged_total_content);
					$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
			}
			$scnt++;
		}
		echo $replaced_content;
		unset($replaced_content);
?>