<?php
/**
 * Checkout Shipping Page
 *
 * @package page
 * @copyright Copyright 2003-2019 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: DrByte 2019 Jan 04 Modified in v1.5.6a $
 */
 
  $checkout_errors=array();
  
  // This should be first line of the script:
  $zco_notifier->notify('NOTIFY_HEADER_START_CHECKOUT_SHIPPING');

  require_once(DIR_WS_CLASSES . 'http_client.php');
  if($_SESSION['checkout_process_style']=="default"){
	  zen_redirect(zen_href_link(FILENAME_CHECKOUT_INFORMATION));
  }
  require(DIR_WS_MODULES . zen_get_module_directory('require_languages.php'));
  // if there is nothing in the customers cart, redirect them to the shopping cart page
  if ($_SESSION['cart']->count_contents() <= 0) {
    zen_redirect(zen_href_link(FILENAME_SHOPPING_CART));
  }
  if(!isset($_SESSION['comments'])){$_SESSION['comments']="";}
  if(!isset($_SESSION['customer_id']) || !isset($_SESSION['sendto'])){
  	$billing_column_sql="SHOW COLUMNS from ".TABLE_ADDRESS_BOOK;
	$billing_address_column=openzcQuery($billing_column_sql);
	$billing_address_column=openzc_table_to_list($billing_address_column,"Field");
	foreach($billing_address_column as $k => $v){
		$k=str_replace("entry_","",$k);
		$billing_address[$k]="";
	}
  }else{
  	$billing_address_sql="select * from ".TABLE_ADDRESS_BOOK." where address_book_id='".$_SESSION['sendto']."'";
	
	$billing_address_data=openzcQuery($billing_address_sql);
	$billing_address_data=openzc_table_to_list($billing_address_data);
	foreach($billing_address_data[0] as $k => $v){
		$k=str_replace("entry_","",$k);
		$billing_address[$k]=$v;
	}
  }
  if (isPost() && isset($_POST['action']) && ($_POST['action'] == 'process')) {
	  if (isset($_POST['comments'])) $_SESSION['comments'] = zen_db_prepare_input($_POST['comments']);
	  if (!isset($_SESSION['customer_id'])) {
			require(DIR_WS_MODULES . zen_get_module_directory('checkout_create_account.php'));
			$information_errors=$checkout_errors['information'];
	  }
	  
	  if (isset($_POST['comments'])) $_SESSION['comments'] = zen_db_prepare_input($_POST['comments']);
	  $_SESSION['sendto'] = $_SESSION['customer_default_address_id'];
	  $_SESSION['billto'] = $_SESSION['customer_default_address_id'];
	  
	  if(isset($_SESSION['customer_id'])){
		  if (isset($_POST['payment'])) {$_SESSION['payment'] = $_POST['payment'];}
		  $error=false;
		  //verify billing address details
		 
		  if(isset($_POST['billing_address_different']) && $_POST['billing_address_different']=="true"){
			$billing_address=$_POST['billing_address'];
			$_SESSION['billto']="";
				if (ACCOUNT_GENDER == 'true') {
					if ( ($billing_address['gender'] != 'm') && ($billing_address['gender'] != 'f') ) {
					  $error = true;
					  $messageStack->add('checkout_information', ENTRY_GENDER_ERROR);
					  $checkout_errors['billing_address']['gender']=ENTRY_GENDER_ERROR;
					}
				}
				if (strlen($billing_address['firstname']) < ENTRY_FIRST_NAME_MIN_LENGTH) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_FIRST_NAME_ERROR);
					$checkout_errors['billing_address']['firstname']=ENTRY_FIRST_NAME_ERROR;
				}
			
				if (strlen($billing_address['lastname']) < ENTRY_LAST_NAME_MIN_LENGTH) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_LAST_NAME_ERROR);
					$checkout_errors['billing_address']['lastname']=ENTRY_LAST_NAME_ERROR;
				}
				
				if (strlen($billing_address['street_address']) < ENTRY_STREET_ADDRESS_MIN_LENGTH) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_STREET_ADDRESS_ERROR);
					$checkout_errors['billing_address']['street_address']=ENTRY_STREET_ADDRESS_ERROR;
				}
				
				if (strlen($billing_address['city']) < ENTRY_CITY_MIN_LENGTH) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_CITY_ERROR);
					$checkout_errors['billing_address']['city']=ENTRY_CITY_ERROR;
				}
				
				if (strlen($billing_address['postcode']) < ENTRY_POSTCODE_MIN_LENGTH) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_POST_CODE_ERROR);
					$checkout_errors['billing_address']['postcode']=ENTRY_POST_CODE_ERROR;
				}
				
				if ( (is_numeric($billing_address['country_id']) == false) ) {
					$error = true;
					$messageStack->add('checkout_information', ENTRY_COUNTRY_ERROR);
					$checkout_errors['billing_address']['country']=ENTRY_COUNTRY_ERROR;
				}
				
				if (ACCOUNT_STATE == 'true') {
					$billing_address['state'] = zen_db_prepare_input($billing_address['state']);
					if (isset($billing_address['zone_id'])) {
					  $billing_address['zone_id'] = zen_db_prepare_input($billing_address['zone_id']);
					} else {
					  $billing_address['zone_id'] = false;
					}
				 }
			   $billto_errors=$checkout_errors['billing_address'];
			   //billing address insert start
				if(sizeof($billing_address)>0 && $error==false){
					$sql_data_array = array(array('fieldName'=>'customers_id', 'value'=>$_SESSION['customer_id'], 'type'=>'integer'),
										array('fieldName'=>'entry_firstname', 'value'=>$billing_address['firstname'], 'type'=>'stringIgnoreNull'),
										array('fieldName'=>'entry_lastname', 'value'=>$billing_address['lastname'], 'type'=>'stringIgnoreNull'),
										array('fieldName'=>'entry_street_address', 'value'=>$billing_address['street_address'], 'type'=>'stringIgnoreNull'),
										array('fieldName'=>'entry_postcode', 'value'=>$billing_address['postcode'], 'type'=>'stringIgnoreNull'),
										array('fieldName'=>'entry_city', 'value'=>$billing_address['city'], 'type'=>'stringIgnoreNull'),
										array('fieldName'=>'entry_country_id', 'value'=>$billing_address['country'], 'type'=>'integer'),
					);
			
					if (ACCOUNT_GENDER == 'true') $sql_data_array[] = array('fieldName'=>'entry_gender', 'value'=>$billing_address['gender'], 'type'=>'stringIgnoreNull');
					if (ACCOUNT_COMPANY == 'true') $sql_data_array[] = array('fieldName'=>'entry_company', 'value'=>$billing_address['company'], 'type'=>'stringIgnoreNull');
					if (ACCOUNT_SUBURB == 'true') $sql_data_array[] = array('fieldName'=>'entry_suburb', 'value'=>$billing_address['suburb'], 'type'=>'stringIgnoreNull');
			
					if (ACCOUNT_STATE == 'true') {
					  if ($billing_address['zone_id'] > 0) {
						$sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>$billing_address['zone_id'], 'type'=>'integer');
						$sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>'', 'type'=>'stringIgnoreNull');
					  } else {
						$sql_data_array[] = array('fieldName'=>'entry_zone_id', 'value'=>0, 'type'=>'integer');
						$sql_data_array[] = array('fieldName'=>'entry_state', 'value'=>$billing_address['state'], 'type'=>'stringIgnoreNull');
					  }
					}
			
					$db->perform(TABLE_ADDRESS_BOOK, $sql_data_array);
			
					$billing_address_id = $db->Insert_ID();
					$_SESSION['billto'] = $billing_address_id;
				}
			   //billing address insert end
		  }
		  
		  /////////////////////////////////////
		  require(DIR_WS_CLASSES . 'shipping.php');
  		  $shipping_modules = new shipping;
		  $quote=array();
		  if ( zen_count_shipping_modules() > 0) {
			  if ( (isset($_POST['shipping'])) && (strpos($_POST['shipping'], '_')) ) {
				
				list($module, $method) = explode('_', $_POST['shipping']);
				if ( is_object($$module) || ($_POST['shipping'] == 'free_free') ) {
				  if ($_POST['shipping'] == 'free_free') {
					$quote[0]['methods'][0]['title'] = FREE_SHIPPING_TITLE;
					$quote[0]['methods'][0]['cost'] = '0';
					$quote[0]['methods'][0]['icon'] = '';
				  } else {
					$quote = $shipping_modules->quote($method, $module);
				  }
				  if (isset($quote[0]['error'])) {
					unset($_SESSION['shipping']);
				  } else {
					if ( (isset($quote[0]['methods'][0]['title'])) && (isset($quote[0]['methods'][0]['cost'])) ) {
					  $_SESSION['shipping'] = array('id' => $_POST['shipping'],
										'title' => (($free_shipping == true) ?  $quote[0]['methods'][0]['title'] : $quote[0]['module'] . ' (' . $quote[0]['methods'][0]['title'] . ')'),
										'cost' => $quote[0]['methods'][0]['cost']);
					}
				  }
				} else {
				  unset($_SESSION['shipping']);
				}
			  }
			} else {
			  unset($_SESSION['shipping']);
			}
		////////////////////////////////////////
			
		  //unset($shipping_modules);
		  if (!$_SESSION['shipping']) {
			  $messageStack->add_session('checkout', 'Please select one shipping methods', 'error');
			
		  }
		  if (!$_SESSION['payment']) {
			  $messageStack->add_session('checkout', 'Please select one payment methods', 'error');
			  
		  }
		  
		  if(isset($_POST['shipping']) && isset($_POST['payment']) && $error!=true){
			  require(DIR_WS_CLASSES . 'payment.php');
			  $payment_modules = new payment($_SESSION['payment']);
			  $payment_modules->update_status();
			  
			  require(DIR_WS_CLASSES . 'order.php');
			  $order = new order; //放在shipping和payment类后；收集配送和付款信息
			  
			  require(DIR_WS_CLASSES . 'order_total.php');
			  $order_total_modules = new order_total;
			  $order_total_modules->collect_posts();
			  $order_total_modules->pre_confirmation_check();
			  
			  $zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_BEFORE_ORDER_TOTALS_PROCESS');
			  $order_totals = $order_total_modules->process();//处理订单信息
			  $zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_ORDER_TOTALS_PROCESS');
			  if ( ($_SESSION['payment'] == '' || !is_object(${$_SESSION['payment']}) ) && $credit_covers === FALSE) {
				$messageStack->add_session('checkout_payment', ERROR_NO_PAYMENT_MODULE_SELECTED, 'error');
			  }
			  
			  if(is_array($payment_modules->modules)){
				$payment_modules->pre_confirmation_check();
			  }
			  $confirmation = $payment_modules->confirmation();
			  
			  if (isset($$_SESSION['payment']->form_action_url)) {
			   echo '<html xmlns="http://www.w3.org/1999/xhtml"><head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<title>Payment Redirecting</title>
			<style type="text/css">
			body {text-align:center;}
			#wrapper{width:411px; margin:130px auto 0; background:none repeat scroll 0 0 #FFFFFF; border:1px solid #B5B5B5;	text-align:center;	-moz-border-radius:5px 5px 5px 5px;font:13px Helvetica,Arial,sans-serif; color:#454545}
			#wrapper h1{color:#5F5F5F;font-size:22px;font-weight:normal;margin:22px 0 26px;padding:0;}
			#wrapper p{cmargin:0 0 12px;padding:0;}
			#wrapper img{margin-bottom:35px;}
			.forbid{text-align:center; font-size:16px; padding-top:10px;}
			</style>
			</head>
			<body onload="return document.checkout_confirmation.submit();">
			<div style="text-align:center;width:100%"><div id="wrapper">
			<h1>Please wait while you\'re redirected</h1>
			<p>Redirecting...</p>
			<img src="includes/images/redirection-loader.gif" alt="loading...">
			</div></div>
			'. zen_draw_form('checkout_confirmation', $$_SESSION['payment']->form_action_url, 'post')
			. $$_SESSION['payment']->process_button()
			.'<center><input name="submit" type="image" style="margin:0 auto" src="includes/images/ie1hJo.png" ></center>
			</form>
			</body></html>';
			//$_SESSION['cart']->reset(true);
			  exit;
			}
			
			$payment_modules->before_process();
			$zco_notifier->notify('NOTIFY_CHECKOUT_PROCESS_AFTER_PAYMENT_MODULES_BEFOREPROCESS');
			
			require(DIR_WS_MODULES . zen_get_module_directory('checkout_process_quick.php'));
			
			$_SESSION['cart']->reset(true);
			unset($_SESSION['sendto']);
			unset($_SESSION['shipping']);
			$order_total_modules->clear_posts();
			$payment_modules->after_process();
			zen_redirect(zen_href_link(FILENAME_CHECKOUT_SUCCESS));
		  
		  }
		  
	  }
	  
	  
	  
  }