<?php


// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	

  require('includes/application_top.php');
  require('includes/classes/http_client.php');
  require(DIR_WS_CLASSES . 'order.php');
  require(DIR_WS_CLASSES . 'shipping.php');
  require(DIR_WS_CLASSES . 'order_total.php');
  require(DIR_WS_CLASSES . 'payment.php');
  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CHECKOUT_SINGLE);

$currencies=new currencies();
  //ajax start
  $command=$REQUEST->getvalue('command');
	$format_id=0;
  if($command!='')
  {
	  switch($command)
	  {
	  case 'show_state':
 		 $country=$REQUEST->getvalue('country_id');
		  $zone_ids="";
		  $zone_name="";
		  $zones_query = tep_db_query("select zone_id,zone_name from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' order by zone_name");
		  while ($zones_values = tep_db_fetch_array($zones_query)) {
			 $zone_ids.=$zones_values['zone_id'].",";
			 $zone_name.=$zones_values['zone_name'].",";
		  }
	  	 echo 'show_state^'.substr($zone_ids,0,-2)."^".substr($zone_name,0,-2)."^".$zone;     
	 	break;
		case 'billing_address_submit':
			$messageStack->reset();
			tep_billing_address_submit('P');
			if($messageStack->size('checkout_address')>0) //error occurs
				echo 'command{}billing_address_error||' . $messageStack->output('checkout_address');
			elseif($shipping) //shipping included
			{
				echo 'command{}show_shipping_address||';
				echo '{}billing_address_display||' . tep_address_format($format_id, $billto_array, true, ' ', '<br>');
			}
			else //skip to payment method
			{
				echo 'command{}show_payment_method||';
				echo '{}billing_address_display||' . tep_address_format($format_id, $billto_array, true, ' ', '<br>');
			}
			break;
		case 'shipping_address_submit':
			$messageStack->reset();
			tep_billing_address_submit('S');
			if($messageStack->size('checkout_shipping_address')>0) //error occurs
				echo 'command{}shipping_address_error||' . $messageStack->output('checkout_shipping_address');
			else
			{
				echo 'command{}show_shipping_method';
				echo '{}shipping_address_display||' . tep_address_format($format_id, $sendto_array, true, ' ', '<br>');
			}
			break;
		case 'shipping_method_submit':
			$messageStack->reset();
			$order = new order;
			 $total_weight = $cart->show_weight();
			$shipping_modules = new shipping;
			$quotes_available = $shipping_modules->quote();
			tep_session_register('free_shipping');
			$free_shipping=$REQUEST->postvalue('free_shipping');
			if ((tep_count_shipping_modules() > 0) || ($free_shipping == true) ) {
				 if ( ($REQUEST->postvalue('shipping')) && (strpos($REQUEST->postvalue('shipping'), '_')) ) {
					$shipping_id = $REQUEST->postvalue('shipping');
					list($module, $method) = explode('_', $shipping_id);
					if ( is_object($$module) || ($shipping_id == 'free_free') ) {
					  if ($shipping_id == 'free_free') {
						$quote[0]['methods'][0]['title'] = FREE_SHIPPING_TITLE;
						$quote[0]['methods'][0]['cost'] = '0';
					  } else {
						$quote = $shipping_modules->quote($method, $module);
					  }
					  if (isset($quote['error'])) {
						$messageStack->add('shipping_method_error',$quote['error']);
						//tep_session_unregister('shipping');
					  } else {
						if ( (isset($quote[0]['methods'][0]['title'])) && (isset($quote[0]['methods'][0]['cost'])) ) {
						    $shipping = array('id' => $shipping_id,
											'title' => (($free_shipping == true) ?  $quote[0]['methods'][0]['title'] : $quote[0]['module'] . ' (' . $quote[0]['methods'][0]['title'] . ')'),
											'cost' => $quote[0]['methods'][0]['cost']);
							 tep_session_register('shipping');	
						}
					  }
					} 
				  }
				} else {
				  $shipping = false;
				} 
			if(!is_array($shipping) && !($free_shipping == true))
				 $messageStack->add('shipping_method_error',TEXT_CHOOSE_SHIPPING_METHOD);
			if($messageStack->size('shipping_method_error')>0)
				echo 'command{}shipping_method_error||' . $messageStack->output('shipping_method_error');
			else
			{
				echo 'command{}show_payment_method';
				echo '{}shipping_method_display||' . $shipping['title'];
			}
			break;
		case 'payment_method_submit':
			$GLOBALS["EXECUTE_PAYMENT"]=1;
			 echo 'command{}';
		 	 include('templates/content/checkout_single_confirm.tpl.php');
			break;
		case 'get_counpon_details':
 			$HTTP_POST_VARS['coupon']=tep_db_prepare_input($REQUEST->getvalue('coupon'));
 			$HTTP_POST_VARS['gv_redeem_code']=tep_db_prepare_input($REQUEST->getvalue('gv_redeem_code'));
			$HTTP_POST_VARS['cot_gv']=tep_db_prepare_input($REQUEST->getvalue('cot_gv'));
			if ($HTTP_POST_VARS['cot_gv']) $_SESSION['cot_gv'] = tep_db_prepare_input($HTTP_POST_VARS['cot_gv']);
			if ($credit_covers) $payment=''; //ICW added for CREDIT CLASS
			$payment_modules = new payment($payment);
		  //ICW ADDED FOR CREDIT CLASS SYSTEM
		   $order = new order;
		  //$payment_modules->update_status();
		  //ICW ADDED FOR CREDIT CLASS SYSTEM
		   $order_total_modules = new order_total;
		  //ICW ADDED FOR CREDIT CLASS SYSTEM
		  $order_total_modules->collect_posts_forajax();
		  //ICW ADDED FOR CREDIT CLASS SYSTEM
			$order_total_modules->process();
			//print_r($GLOBALS);
			echo 'command{}coupon_details||';
			if(sizeof($GLOBALS['ot_coupon'])){
				$coupon=$GLOBALS['ot_coupon'];
				$error="";
				$error=$HTTP_SESSION_VARS['coupon_error'];
				if($coupon->code=='ot_coupon' && $error=="" && $coupon->output[0]['text']){
					echo '<table border="0" width="90%" cellspacing="3" cellpadding="3" class="formArea" align="center">' .
							'<tr><td></td>' .
							'   <td class="eventTitle">'.TEXT_REDEEM_CODE . (($HTTP_SESSION_VARS['email_redeem_code'])?$HTTP_SESSION_VARS['email_redeem_code']: $coupon->coupon_code).'</td>' .
							'   <td class="eventTitle">'.TEXT_VALUE. $coupon->output[0]['text'].'</td>' .
							'</tr>' . 
							'<tr><td></td>' .
							'   <td class="eventTitle">'.TEXT_VALID_UTIL. $coupon->expire_date.'</td>' .
							'   <td class="eventTitle">'.(($coupon->uses_per_user!=0)?TEXT_USES_REMAINING .$coupon->uses_per_user:'').'</td>' .
							'<td rowspan="2" valign="middle" align="right">'.tep_template_image_button('button_dont_redeem.gif','','style="cursor:pointer;cursor:hand" onclick="javascript:submitFunction(1);"').'</td>'.
							'</tr>' .   					
							'</table>';
				} else {
					echo '<table border="0" width="90%" align="center" cellspacing="0" cellpadding="0"><tr align="center"><td align="left" class="smalltext"><span class="errortext">'.$error.'</span></td></tr></table>';
				}
			} 
		break;
	  }
	  exit;
  }
 //ajax end

  if (!tep_session_is_registered('customer_id')) {
    $navigation->set_snapshot();
    tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
  }
  if(tep_check_is_blocked_customer()){
	tep_redirect(tep_href_link(FILENAME_ACCOUNT,'isblocked=yes'));
  }
  if(tep_check_is_suspended_customer()){
	tep_redirect(tep_href_link(FILENAME_ACCOUNT,'suspended=yes'));
  } 
// if there is nothing in the customers cart, redirect them to the shopping cart page
  if ($cart->count_contents() < 1) {
    tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
  }
  $valid_to_checkout= true;
  $cart->get_products(true);
  if ($valid_to_checkout) { // Added lines 50-58 by sobi
  	$cart_subs_result=$cart->check_stored_subscription_purchased();
	
    if($cart_subs_result>2){
		if($cart_subs_result==4) {
			$subs_query=tep_db_query("select sc.subscription_categories_id as cat_id,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'  and s.subscription_status='1'");
			if(tep_db_num_rows($subs_query)>0)
			{
				$row=tep_db_fetch_array($subs_query);
				tep_redirect(tep_href_link(FILENAME_SUBSCRIPTION_INFO, 'sucPath=' . $row['cat_id']. '&subscription_id=' .$row['id']));
			}
		} else if($cart_subs_result==3){
		   	$get_member_subs_query=tep_db_query("select subscription_id from " . TABLE_SUBSCRIPTIONS . " where subscription_type='M'  and subscription_status='1' ");
					if(tep_db_num_rows($get_member_subs_query)>0){
					   $member_subscription=tep_db_fetch_array($get_member_subs_query);
					   $subscription_id = $member_subscription['subscription_id'];
					    if($cart->in_cart('S'.$subscription_id)) $cart->remove("S".$subscription_id);
						} 
       tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
	   exit;
		}
   }
    if($cart->check_forced_items_purchased()){
	   $messageStack->add_session('shopping_cart', 'Please purchase all forced order items ...','error');
       tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
	   exit;
   }
  }
  // Stock Check
  if ( (STOCK_CHECK == 'true') && (STOCK_ALLOW_CHECKOUT != 'true') ) {
    $products = $cart->get_products();
    for ($i=0, $n=sizeof($products); $i<$n; $i++) {
     if ($products[$i]['elementType']=='P'){
      if (tep_check_stock($products[$i]['id'], $products[$i]['quantity'])) {
        tep_redirect(tep_href_link(FILENAME_SHOPPING_CART));
        break;
      }
     }
    }
  }
  //===========
  if (!tep_session_is_registered('shipping')) tep_session_register('shipping');
  $shipping=true;
  if (!tep_session_is_registered('sendto')) {
    tep_session_register('sendto');
    $sendto = $customer_default_address_id;
  } else {
// verify the selected shipping address
    $check_address_query = tep_db_query("select count(*) as total from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$customer_id . "' and address_book_id = '" . (int)$sendto . "'");
    $check_address = tep_db_fetch_array($check_address_query);
    if ($check_address['total'] != '1') {
      $sendto = $customer_default_address_id;
      if (tep_session_is_registered('shipping')) tep_session_unregister('shipping');
    }
  }
 if (!tep_session_is_registered('billto')) {
    tep_session_register('billto');
    $billto = $customer_default_address_id;
  } else {
// verify the selected billing address
    $check_address_query = tep_db_query("select count(*) as total from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$customer_id . "' and address_book_id = '" . (int)$billto . "'");
    $check_address = tep_db_fetch_array($check_address_query);

    if ($check_address['total'] != '1') {
      $billto = $customer_default_address_id;
      if (tep_session_is_registered('payment')) tep_session_unregister('payment');
    }
  }
	
  if (!tep_session_is_registered('cartID')) tep_session_register('cartID');
  $cartID = $cart->cartID;
  if (NO_CHECKOUT_ZERO_PRICE=="1" && $cart->is_free_checkout()){
	tep_redirect(tep_href_link(FILENAME_CHECKOUT_PROCESS_FREE, '', 'SSL'));
  }
  $order = new order;
  if (($order->content_type == 'virtual') || ($order->content_type == 'virtual_weight') ) {
  	 $shipping = false;
   	 $sendto = false;
 }
 tep_session_register('billto_array');
 if($shipping)
 {
  tep_session_register('sendto_array');
  tep_check_country_differ();
  $total_weight = $cart->show_weight();
  $total_count = $cart->count_contents();
  // ------load all enabled shipping modules===================
  $shipping_modules = new shipping;
  $quotes_available = $shipping_modules->quote();
  if(sizeof($quotes_available)<=0){
  	tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
  }
  if ( defined('MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING') && (MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING == 'true') ) {
    $pass = false;
    switch (MODULE_ORDER_TOTAL_SHIPPING_DESTINATION) {
      case 'national':
        if ($order->delivery['country_id'] == STORE_COUNTRY) {
          $pass = true;
        }
        break;
      case 'international':
        if ($order->delivery['country_id'] != STORE_COUNTRY) {
          $pass = true;
        }
        break;
      case 'both':
        $pass = true;
        break;
    }
    $free_shipping = false;
    if ( ($pass == true) && ($order->info['total'] >= MODULE_ORDER_TOTAL_SHIPPING_FREE_SHIPPING_OVER) ) {
      $free_shipping = true;
      include(DIR_WS_LANGUAGES . $language . '/modules/order_total/ot_shipping.php');
    }
  } else {
    $free_shipping = false;
  }
  //$free_shipping = true;
   //include(DIR_WS_LANGUAGES . $language . '/modules/order_total/ot_shipping.php');
  $quotes = $shipping_modules->quote();
   if ( !tep_session_is_registered('shipping') || ( tep_session_is_registered('shipping') && ($shipping == false) && (tep_count_shipping_modules() > 1) ) ) $shipping = $shipping_modules->cheapest();
 }
//=================================shipping end==================================
//=============payment start=========================
  $order_timestamp=time();
 $referenceID= substr(strtolower($order->customer['firstname']),0,3) . substr(strtolower($order->customer['lastname']),0,3) . $order_timestamp ;
 if (!tep_session_is_registered('referenceID')) tep_session_register('referenceID');	
  $payment_modules = new payment;
//==========payment end==============================
  $breadcrumb->add(NAVBAR_TITLE_1, tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
  $breadcrumb->add(NAVBAR_TITLE_2, tep_href_link(FILENAME_CHECKOUT_SINGLE, '', 'SSL'));

  $content = CONTENT_CHECKOUT_SINGLE;
  $javascript = CONTENT_CHECKOUT_SINGLE . '.js.php';

  require(DIR_WS_TEMPLATES . TEMPLATE_NAME . '/' . TEMPLATENAME_MAIN_PAGE);
  require(DIR_WS_INCLUDES . 'application_bottom.php');
  
  function tep_billing_address_submit($mode)
  {
  	global $REQUEST,$messageStack,$billto,$sendto,$billto_array,$sendto_array,$format_id,$customer_id;
	if($mode=='P')  //payment
	{
  	    $billto=tep_db_prepare_input($REQUEST->postvalue('address'),'int');
		$delivery_query = tep_db_query("select  c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3 from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$billto . "'");
		$format_id=$REQUEST->postvalue('format' . $billto);
		$stack_class='checkout_address';
		$session_array='billto_array';
	}
	else
	{
  	    $sendto=tep_db_prepare_input($REQUEST->postvalue('address'),'int');
		$delivery_query = tep_db_query("select  c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3 from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$sendto . "'");
		$format_id=$REQUEST->postvalue('format' . $sendto);
		$stack_class='checkout_shipping_address';
		$session_array='sendto_array';
	}
      if (ACCOUNT_GENDER == 'true') $gender = tep_db_prepare_input($REQUEST->postvalue('gender'));
      if (ACCOUNT_COMPANY == 'true') $company = tep_db_prepare_input($REQUEST->postvalue('company'));
      $firstname = tep_db_prepare_input($REQUEST->postvalue('firstname'));
      $lastname = tep_db_prepare_input($REQUEST->postvalue('lastname'));
      $street_address = tep_db_prepare_input($REQUEST->postvalue('street_address'));
      if (ACCOUNT_SUBURB == 'true') $suburb = tep_db_prepare_input($REQUEST->postvalue('suburb'));
      $postcode = tep_db_prepare_input($REQUEST->postvalue('postcode'));
      $city = tep_db_prepare_input($REQUEST->postvalue('city'));
      $country = tep_db_prepare_input($REQUEST->postvalue('country'));
      if (ACCOUNT_STATE == 'true') {
        if ($REQUEST->postvalue('zone_id')) {
          $zone_id = tep_db_prepare_input($REQUEST->postvalue('zone_id'));
        } else {
          $zone_id = false;
        }
        $state = tep_db_prepare_input($REQUEST->postvalue('state'));
		//textbox value
		$state1= tep_db_prepare_input($REQUEST->postvalue('state1'));
      }
      if (ACCOUNT_GENDER == 'true') {
        if ( ($gender != 'm') && ($gender != 'f') ) {
          $error = true;
          $messageStack->add($stack_class, ENTRY_GENDER_ERROR);
        }
      }
      if (strlen($firstname) < ENTRY_FIRST_NAME_MIN_LENGTH) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_FIRST_NAME_ERROR);
      }
      if (strlen($lastname) < ENTRY_LAST_NAME_MIN_LENGTH) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_LAST_NAME_ERROR);
      }
      if (strlen($street_address) < ENTRY_STREET_ADDRESS_MIN_LENGTH) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_STREET_ADDRESS_ERROR);
      }
      if (strlen($postcode) < ENTRY_POSTCODE_MIN_LENGTH) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_POST_CODE_ERROR);
      }
      if (strlen($city) < ENTRY_CITY_MIN_LENGTH) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_CITY_ERROR);
      }
      if (ACCOUNT_STATE == 'true') {
        $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;
            $messageStack->add($stack_class, ENTRY_STATE_ERROR_SELECT);
          }
        } else {
          if (strlen($state1) < ENTRY_STATE_MIN_LENGTH) {
            $error = true;
            $messageStack->add($stack_class, ENTRY_STATE_ERROR);
          }
        }
      }
      if ( (is_numeric($country) == false) || ($country < 1) ) {
        $error = true;
        $messageStack->add($stack_class, ENTRY_COUNTRY_ERROR);
      }
	  if ($error == false) {
	  	$delivery_result=tep_db_fetch_array($delivery_query);
        $sessions_array = array('customers_id' => $customer_id,
								'format_id'=>$format_id,
                                'firstname' => $firstname,
                                'lastname' => $lastname,
                                'street_address' => $street_address,
                                'postcode' => $postcode,
                                'city' => $city,
								'country' => array('id' => $delivery_result['countries_id'], 'title' => $delivery_result['countries_name'], 'iso_code_2' => $delivery_result['countries_iso_code_2'], 'iso_code_3' => $delivery_result['countries_iso_code_3']),
                                'country_id' => $country);

        if (ACCOUNT_GENDER == 'true') $sessions_array['gender'] = $gender;
        if (ACCOUNT_COMPANY == 'true') $sessions_array['company'] = $company;
        if (ACCOUNT_SUBURB == 'true') $sessions_array['suburb'] = $suburb;
        if (ACCOUNT_STATE == 'true') {
          if ($zone_id > 0) {
            $sessions_array['zone_id'] = $zone_id;
            $sessions_array['state'] = $state;
          } else {
            $sessions_array['zone_id'] = '0';
            $sessions_array['state'] = $state;
          }
        }
	  $$session_array=$sessions_array;
	 }
  }
?>
