<?php
/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
// calculate events category path
  if (file_exists(DIR_WS_LANGUAGES . $language . '/' . FILENAME_EVENTS_MESSAGES_MAIL)) {
    include(DIR_WS_LANGUAGES . $language . "/" . FILENAME_EVENTS_MESSAGES_MAIL);
  }
 //=================================
  if (isset($HTTP_GET_VARS['event_action'])) {
	$element_type=isset($HTTP_GET_VARS['element_type'])?tep_db_prepare_input($HTTP_GET_VARS['element_type']):'P';  
    $goto =  FILENAME_SHOPPING_CART;
    $parameters = array('event_action', 'ecPath', 'products_id','products_qty');
  }  
  switch ($HTTP_GET_VARS['event_action']) {
      // customer wants to update the product quantity in their shopping cart
      case 'update_cart' : 	 
	  						for ($i=0, $n=sizeof($HTTP_POST_VARS['products_id']); $i<$n; $i++) {
								if($HTTP_GET_VARS['type']=='E' && is_array($HTTP_POST_VARS['cart_delete'])) {
									$products_id=$HTTP_POST_VARS['products_id'][$i];
									$cart->remove($products_id,$HTTP_POST_VARS['cart_delete'],$HTTP_GET_VARS['type']);
                                } else if (in_array($HTTP_POST_VARS['products_id'][$i], (is_array($HTTP_POST_VARS['cart_delete']) ? $HTTP_POST_VARS['cart_delete'] : array()))) {
								  $products_id=$HTTP_POST_VARS['products_id'][$i];
								  //if ($HTTP_POST_VARS['products_type'][$i]=="E") $products_id='E' . $products_id;
								  //if ($HTTP_POST_VARS['products_type'][$i]=="S") $products_id='S' . $products_id;
                                  $cart->remove($products_id);
                                } else {
									$products_id=$HTTP_POST_VARS['products_id'][$i];
									//if ($HTTP_POST_VARS['products_type'][$i]=="P" || $HTTP_POST_VARS['products_type'][$i]=="V")
									//$products_id=tep_get_prid($HTTP_POST_VARS['products_id'][$i]);
										  if (PHP_VERSION < 4) {
											// if PHP3, make correction for lack of multidimensional array.
											reset($HTTP_POST_VARS);
											while (list($key, $value) = each($HTTP_POST_VARS)) {
											  if (is_array($value)) {
												while (list($key2, $value2) = each($value)) {
												  if (ereg ("(.*)\]\[(.*)", $key2, $var)) {
													$id2[$var[1]][$var[2]] = $value2;
												  }
												}
											  }
											}
											$attributes = ($id2[$products_id]) ? $id2[$products_id] : '';
										  } else {
										    $attributes = ($HTTP_POST_VARS['id'][$products_id]) ? $HTTP_POST_VARS['id'][$products_id] : '';
										  
										  } 
										$cart->add_cart($products_id, $HTTP_POST_VARS['cart_quantity'][$i], $attributes, false,'',0,$HTTP_POST_VARS['txt_tax'][$i],$HTTP_POST_VARS['txt_price'][$i],$HTTP_POST_VARS['price_breaks'][$i],(int)$HTTP_POST_VARS['discount_ids'][$i]);
								  }
                              }
                              //tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
                              break;
      // performed by the 'buy now' button in product listings and review page
      case 'buy_product' : 
	  		$customers_list=array();
			$errors=array();
  			$no_attendees=(isset($HTTP_POST_VARS['no_attendees'])?(int)$HTTP_POST_VARS['no_attendees']:1);
			$store_membership_option=isset($HTTP_POST_VARS['store_membership_option'])?tep_db_prepare_input($HTTP_POST_VARS['store_membership_option']):"";	

		//	echo $no_attendees;
			if($no_attendees>1)
			{
				$check_array=tep_db_prepare_input($HTTP_POST_VARS['attendee']);
				  for($icnt=0;$icnt<$no_attendees;$icnt++){
					$first_name=tep_db_prepare_input($HTTP_POST_VARS["first_name"][$icnt]);
					$last_name=tep_db_prepare_input($HTTP_POST_VARS["last_name"][$icnt]);
					$email_address=tep_db_prepare_input($HTTP_POST_VARS["email_address"][$icnt]);
					$street_address=tep_db_prepare_input($HTTP_POST_VARS["street_address"][$icnt]);
					$city=tep_db_prepare_input($HTTP_POST_VARS["city"][$icnt]);
					$postcode=tep_db_prepare_input($HTTP_POST_VARS["postcode"][$icnt]);
					$state=tep_db_prepare_input($HTTP_POST_VARS["customer_state"][$icnt]);
					$country=tep_db_prepare_input($HTTP_POST_VARS["country"][$icnt]);
					$check_existing=$check_array[$icnt];
					//get existing customer
					if (strlen($first_name) < ENTRY_FIRST_NAME_MIN_LENGTH) {	
						$error = true;
						$errors[$icnt][]=FIRST_NAME_ERROR;
					}
					if (strlen($last_name) < ENTRY_LAST_NAME_MIN_LENGTH) {
						$error = true;
						$errors[$icnt][]=LAST_NAME_ERROR;
					}
					if (strlen($email_address) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) {
						$error = true;
						$errors[$icnt][]=EMAIL_ADDRESS_ERROR;
						//echo "Error is =" . $errors[$icnt] . " by Raga "; 
					} elseif (tep_validate_email($email_address) == false) {
						$error = true;
						$errors[$icnt][]=ADDRESS_CHECK_ERROR;
						//echo "Errors are = " . $errors[$icnt] . "by Ram"; 
					} else {//if($check_existing!=1 && $mode!='edit') {
						if($icnt>0){	
						$check_email_query = tep_db_query("select count(*) as total from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($email_address) . "'");
						$check_email = tep_db_fetch_array($check_email_query);
						if ($check_email['total'] > 0 && !$check_existing) {
							$error = true;
							$errors[$icnt][]=ADDRESS_ERROR_EXISTS;
						}
					  }	
					}
					if (strlen($street_address) < ENTRY_STREET_ADDRESS_MIN_LENGTH) {
						$error = true;
						$errors[$icnt][]=STREET_ADDRESS_ERROR;
					}
					
					if (strlen($postcode) < ENTRY_POSTCODE_MIN_LENGTH) {
						$error = true;
						$errors[$icnt][]=POSTCODE_ERROR;
					}
					
					if (strlen($city) < ENTRY_CITY_MIN_LENGTH) {
						$error = true;
						$errors[$icnt][]=CITY_ERROR;
					}
					if (is_numeric($country) == false) {
						$error = true;
						$errors[$icnt][]=COUNTRY_ERROR;
					}
					$zone_id = 0;
					$check_query = tep_db_query("select count(*) as total from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country . "'");
					$check = tep_db_fetch_array($check_query);
					$entry_state_has_zones = ($check['total'] > 0);
					if ($entry_state_has_zones == true) {
						$zone_query = tep_db_query("select distinct zone_id from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country . "' and (zone_name like '" . tep_db_input($state) . "%' or zone_code like '%" . tep_db_input($state) . "%')");
						if (tep_db_num_rows($zone_query) == 1) {
							$zone = tep_db_fetch_array($zone_query);
							$zone_id = $zone['zone_id'];
						} else {
							$error = true;
							$errors[$icnt][]=STATE_ERROR_SELECT;
							$state_errors[$icnt][]=1;
						}
					} else {
						if (strlen($state) < ENTRY_STATE_MIN_LENGTH) {
							$error = true;
							$errors[$icnt][]=STATE_ERROR;
						}
					}
					$customers_list[]=array("first_name"=>$first_name,
										"last_name"=>$last_name,
										"email_address"=>$email_address,
										"street_address"=>$street_address,
										"city"=>$city,
										"postcode"=>$postcode,
										"state"=>$state,
										"country"=>$country,
										"attendee" =>(int)$check_existing);
				  }
		}//print_r($customers_list);
		//if (!$error){
			if($no_attendees>1)
				$cart->set_attendees($customers_list);
			// get products added by checking products_id[];
			$old_orders_id=(isset($HTTP_POST_VARS['old_orders_id'])?(int)$HTTP_POST_VARS['old_orders_id']:0);

			$question_type=(isset($HTTP_POST_VARS['event_question_type'])?tep_db_prepare_input($HTTP_POST_VARS['event_question_type']):'');
			$question_value=(isset($HTTP_POST_VARS['event_question_value_data'])?tep_db_prepare_input($HTTP_POST_VARS['event_question_value_data']):'');
			//group booking
			$session_array=&$HTTP_POST_VARS['select_dates'];
			
			
			//group booking
			$products=$HTTP_POST_VARS['sessions_id'];
			$sessions=array();
			for ($icnt=0;$icnt<sizeof($products);$icnt++){
				if (isset($session_array[$products[$icnt]])){
					$session=&$session_array[$products[$icnt]];
				//if (isset($HTTP_POST_VARS["session_select_" . $HTTP_POST_VARS['sessions_id'][$icnt]])){
					if ($session['type']=="R") $session["group"]="";
					$sessions[$HTTP_POST_VARS['sessions_id'][$icnt]]=array(	"type"=>$session['type'],
												"date"=>$session['date'],
												"fees"=>0,
												"group"=>$session['group']);
				}
			}
			$cart->add_cart_event($HTTP_POST_VARS['events_name'],$sessions,$old_orders_id,$question_type,$question_value,$no_attendees);
			if($store_membership_option=='Y'){
		 	$subs_query=tep_db_query("select s.subscription_id as id from " .TABLE_SUBSCRIPTIONS ." s," . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sc where s.subscription_id=sc.subscription_id and  s.subscription_type='M'");
			$subs_result=tep_db_fetch_array($subs_query);
			$order_query=tep_db_query("select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . tep_db_input($customer_id) . "' and  op.products_id='" . $subs_result['id']. "' and op.products_type='S'");
			$order_result=tep_db_fetch_array($order_query);
			 $item_exists=false;
			 $check_subs=false;
			if(tep_db_num_rows($order_query)<=0) {
				$check_subs=true;
			}	else  {
				
				if(tep_session_is_registered('order_id') && $order_id==$order_result['orders_id']) {
					$check_subs=true;
				}
			}
			//store membership
			if($order_result['orders_id']>0){
				while (list($products_id, ) = each($cart->contents)) {
					if($cart->contents[$products_id]['element_type']=='S' && $products_id=$subs_result['id'])
						$item_exists=true;
				}
				
				if(!$item_exists) {
					$subs_start_date=tep_convert_date_raw(date(EVENTS_DATE_FORMAT));
					$cart->add_cart_subscription($subs_result['id'], 1, '','','','',$subs_start_date);
				}			
			}else{
			if($check_subs) {
			while (list($products_id, ) = each($cart->contents)) {
					if($cart->contents[$products_id]['element_type']=='S' && $products_id=$subs_result['id'])
						$item_exists=true;
				}
				
				if(!$item_exists) {
					$subs_start_date=tep_convert_date_raw(date(EVENTS_DATE_FORMAT));
					$cart->add_cart_subscription($subs_result['id'], 1, '','','','',$subs_start_date);
				}	
			 }
			}
			}	
            break;
  }

  // check for subscription action
  if (isset($HTTP_GET_VARS['subs_action'])) {
	  $goto =  FILENAME_SHOPPING_CART;
      $parameters = array('subs_action', 'sucPath', 'subscription_id');
  }

  switch ($HTTP_GET_VARS['subs_action']) {
      case 'add_subscription' : 
		 if (isset($HTTP_POST_VARS['subscriptions_id']) && is_numeric($HTTP_POST_VARS['subscriptions_id'])) {
			$products_id=(int)$HTTP_POST_VARS['subscriptions_id'];
	  		$subscription_start_date = isset($HTTP_POST_VARS['your_start_date'])?tep_convert_date_raw($HTTP_POST_VARS['your_start_date']):'0000-00-00';
			$cart->add_cart_subscription($products_id, 1, '','','','',$subscription_start_date);
			// check for forced products;
			$xsell_ids=(isset($HTTP_POST_VARS["xsell_forced_id"])?tep_db_prepare_input($HTTP_POST_VARS["xsell_forced_id"]):array());
			if (count($xsell_ids)>0){
				for ($lcnt=0;$lcnt<count($xsell_ids);$lcnt++){
					$cart->add_cart_subscription($xsell_ids[$lcnt], 1,'', true,array(),0,$subscription_start_date);
				}
			}
		 }
		 // tep_redirect(tep_href_link($goto, tep_get_all_get_params($parameters)));
		  break;
   }
 //================================
  if (isset($HTTP_GET_VARS['ecPath'])){
     $ecPath=$HTTP_GET_VARS['ecPath'];
  }
  else{
     $ecPath= '';
  }
  if (tep_not_null($ecPath))
  {
    $ecPath_array=tep_parse_events_category_path($ecPath);
	$ecPath = implode('_', $ecPath_array);
    $current_events_category_id = $ecPath_array[(sizeof($ecPath_array)-1)];	
  } else {
     $current_events_category_id=0;
  }
 if (isset($HTTP_GET_VARS['sucPath'])){
     $sucPath=$HTTP_GET_VARS['sucPath'];
  }
  else{
     $sucPath= '';
  }
  if (tep_not_null($sucPath))
  {
    $sucPath_array=tep_parse_events_category_path($sucPath);
	$sucPath = implode('_', $sucPath_array);
    $current_subscription_category_id = $sucPath_array[(sizeof($sucPath_array)-1)];	
  } else {
     $current_subscription_category_id=0;
  }
  
  //services
  if (isset($HTTP_GET_VARS['secPath'])){
     $secPath=$HTTP_GET_VARS['secPath'];
  }
  else{
     $secPath= '';
  }
  if (tep_not_null($secPath))
  {
    $secPath_array=tep_parse_events_category_path($secPath);
	$secPath = implode('_', $secPath_array);
   
	$current_service_category_id= $secPath_array[(sizeof($secPath_array)-1)];	
  } else {
    
	 $current_service_category_id=0;
  }
  
  //contractors
   if (isset($HTTP_GET_VARS['cocPath'])){
     $cocPath=$HTTP_GET_VARS['cocPath'];
  }
  else{
     $cocPath= '';
  }
  if (tep_not_null($cocPath))
  {
    $cocPath_array=tep_parse_events_category_path($cocPath);
	$cocPath = implode('_', $cocPath_array);
   
	$current_contract_category_id= $cocPath_array[(sizeof($cocPath_array)-1)];	
  } else {
    
	 $current_contract_category_id=0;
  }
  
require(DIR_WS_CLASSES . "edit_order_cart.php");

if (tep_session_is_registered('edit_order')){
  $page=basename($PHP_SELF);
  $pages=array(FILENAME_EDIT_ORDERS,FILENAME_ADDPRODUCTS,FILENAME_ADDSUBSCRIPTIONS,FILENAME_ADD_EVENTS,FILENAME_EDIT_ORDERS_CONFIRM,FILENAME_EDIT_ORDERS_PROCESS,FILENAME_CHECKOUT_PAYMENT,FILENAME_CHECKOUT_PROCESS,FILENAME_EDIT_EVENTS,FILENAME_CHECKOUT_PAYPALIPN,FILENAME_PAYPAL_NOTIFY,FILENAME_CHECKOUT_COMMBANK_RESULT,FILENAME_ADD_SERVICES,FILENAME_CHECKOUT_VIRTUALPAY_RESULT,FILENAME_CHECKOUT_ATTENDEES);
  //if ($page==FILENAME_EDIT_ORDERS || $page==FILENAME_ADD_EVENTS || $page==FILENAME_EDIT_ORDERS_CONFIRM || $page==FILENAME_EDIT_ORDERS_PROCESS || $page==FILENAME_CHECKOUT_PAYMENT || $page==FILENAME_CHECKOUT_PROCESS || $page==FILENAME_EDIT_EVENTS);
  if (!in_array($page,$pages)){
      $edit_cart=new editOrderCart($HTTP_SESSION_VARS['edit_order']);
      $edit_cart->reset((int)$HTTP_SESSION_VARS['edit_order']);
      tep_session_unregister('edit_order');
  }

}
 $page=basename($PHP_SELF);

 if ($page!=FILENAME_FORBIDEN && $page!='save_flag.php'){
	 if (!tep_session_is_registered('lastAccessPage')){
		tep_session_register('lastAccessPage');	
	 }
	 $lastAccessPage=$page;
 }

 if  (MENU_DHTML != true)
    define('BOX_WIDTH', 125);

 if ($login_groups_type==TEXT_CALLSTAFF_ENTRY)
     $SESS_LIFE=4500;
	 
// Hide from backend menu Products,Events,Subscriptions, Services
$menu_query=tep_db_query("select configuration_value from ".TABLE_CONFIGURATION ." where configuration_key='SHOP_SELL_ITEMS'")	 ;
$menu_result=tep_db_fetch_array($menu_query);
$prd=true;
for($i=0;$i<strlen($menu_result['configuration_value']);$i++){
	$menu_value=substr($menu_result['configuration_value'],$i,1);
	switch ($menu_value){
		case 'P':
			define('HIDE_FROM_BACKEND_MENU_PRODUCTS','false');
			break;
		case 'E':
			define('HIDE_FROM_BACKEND_MENU_EVENTS','false');
			break;
		case 'S':
			define('HIDE_FROM_BACKEND_MENU_SUBSCRIPTIONS','false');
			break;
		case 'V':
			define('HIDE_FROM_BACKEND_MENU_SERVICES','false');
			break;		
	}
}
//echo'sdfsdfds'.$prd;
//define('HIDE_FROM_BACKEND_MENU_PRODUCTS',$prd);
/*define('HIDE_FROM_BACKEND_MENU_EVENTS','true');
define('HIDE_FROM_BACKEND_MENU_SUBSCRIPTIONS','true');
define('HIDE_FROM_BACKEND_MENU_SERVICES','true');*/
//echo HIDE_FROM_BACKEND_MENU_PRODUCTS;
require(DIR_WS_LANGUAGES . $language . "/reports_english.php");
require(DIR_WS_CLASSES . 'sms.php');

$sms=new sms(SMS_GATEWAY);

	// set the flag
	if (isset($HTTP_GET_VARS["action"]) && $HTTP_GET_VARS["action"]=="sflag"){
		if($HTTP_GET_VARS["value"]==1){
			$update_value="1," . date('Y-m-d',tep_dateadd(mktime(),'day',5));
		}else{
			$update_value="2";
		}
		if (defined('CURRENT_VERSION')){
			tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value= '" . $update_value . "' where configuration_key='CURRENT_VERSION'");
		} else {
			tep_db_query("INSERT INTO configuration(configuration_title,configuration_key,configuration_group_id,configuration_value) VALUES('version','CURRENT_VERSION','6','" . $update_value . "')");
		}
		tep_redirect(tep_href_link($lastAccessPage));
	}
	
	
  // menu related details
  if(basename($PHP_SELF)==FILENAME_LOGIN || basename($PHP_SELF)==FILENAME_DEFAULT)
		unset($HTTP_SESSION_VARS['mPath']);

  $menu_path=(isset($HTTP_GET_VARS["mPath"])?tep_db_prepare_input($HTTP_GET_VARS["mPath"]):'');
  if ($menu_path=='') $menu_path=(isset($HTTP_SESSION_VARS["mPath"])?$HTTP_SESSION_VARS["mPath"]:'');

  if ($menu_path=='') $menu_path=get_current_menu_path();
  
  
  if ($menu_path!=''){
	  $HTTP_SESSION_VARS["mPath"]=$menu_path;
	$menu_splt=split("_",$menu_path);
	for ($icnt=1,$n=count($menu_splt);$icnt<=$n;$icnt++){
		$GLOBALS["l" . $icnt]=$menu_splt[$icnt-1];
	}
  }

  // designing the menu structure
  $menu_arr=array();
  $breadcrumb=new breadcrumb();
  load_menu(0);
  
  $CONFIG_ACCESS_KEY='';
  //print_r($menu_arr);
  //prepare the navigation list
  for ($icnt=1;$icnt<=5;$icnt++){
	if (!isset($GLOBALS["l" . $icnt])) break;
	$menu_id=$GLOBALS["l" . $icnt];
	
	//echo "menu_id=" . $menu_id . "<br>";
	
	if (isset($menu_arr[$icnt][$menu_id])){
		$breadcrumb->add($menu_arr[$icnt][$menu_id]['text'],tep_href_link($menu_arr[$icnt][$menu_id]['file'],"mPath=" . $menu_arr[$icnt][$menu_id]['path'].'&'.$menu_arr[$icnt][$menu_id]['params'] ));
		$CONFIG_ACCESS_KEY=$CONFIG_ACCESS_KEY . $menu_arr[$icnt][$menu_id]['text'] ." ";
		//echo $CONFIG_ACCESS_KEY;
	}
  }
  $CONFIG_ACCESS_KEY=substr($CONFIG_ACCESS_KEY,0,-1);
?>
