<?php
/**
 * Exports Order / Shipping Information From Zen Cart in various chosen formats
 *
 * @package Export Shipping and Order Information
 * @copyright Copyright 2009, Eric Leuenberger http://www.zencartoptimization.com
 * @copyright Portions Copyright 2003-2006 Zen Cart Development Team
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: shipping_export.php, v 1.3.2 08.05.2010 11:41 Eric Leuenberger econcepts@zencartoptimization.com$
 * Thanks to dhcernese and Scott Wilson (That Software Guy) for contributing various portions that contained several bug-fixes.
 */
define('VERSION', '1.3.2');
$fromcron ='yes';
 require_once('includes/application_top.php');
 require_once(DIR_WS_CLASSES . 'currencies.php');
 $currencies = new currencies();
 require_once(DIR_WS_CLASSES . 'order.php');

// change destination here for path when using "save to file on server"
if (!defined('DIR_FS_EMAIL_EXPORT')) define('DIR_FS_EMAIL_EXPORT',DIR_FS_CATALOG.'images/uploads/orders/');

	$_POST['format'] =0;
	$_POST['auto_email_subject'] = 'LivingSupplements orders for processing.';
	$_POST['auto_email_supplier'] ='testdevaa@gmail.com';
	$_POST['download_csv'] ='Export to Excel Spreadsheet';
	$_POST['filelayout'] = 2;
	$_POST['product_details'] = 1;
	$_POST['shipmethod'] = 1;
	$_POST['order_total'] = 1;
	$_POST['date_purchased'] = 1;
	$_POST['order_comments'] = 1;
	$_POST['savetofile'] = 1;
	$_POST['include_header_row'] =1;
	$_POST['split_name'] =1;
	
	$newsendarrayLAST = array();
	$i =0;
/** Set Available Export Formats **/
  $available_export_formats[0]=array('id' => '0', 'text' => 'CSV');
  $available_export_formats[1]=array('id' => '1', 'text' => 'TXT');
//  $available_export_formats[2]=array('id' => '2', 'text' => 'HTML');
//  $available_export_formats[3]=array('id' => '3', 'text' => 'XML');
/**********************************/
/** Set Variables **/
  $save_to_file_checked=(isset($_POST['savetofile']) && zen_not_null($_POST['savetofile']) ? $_POST['savetofile'] : 0 );
  $post_format = (isset($_POST['format']) && zen_not_null($_POST['format']) ? $_POST['format'] : 0 );
  $format = $available_export_formats[$post_format]['text'];
/* Get file types */
  if ($format =='CSV') {
    $file_extension = '.csv';
	$FIELDSTART = '"';
    $FIELDEND = '"';
    $FIELDSEPARATOR = ',';
    $LINESTART = '';
    $LINEBREAK = "\n";
	$ATTRIBSEPARATOR = ' | '; //Be Careful with this option. Setting it to a 'comma' for example could throw off the remaining fields.
  }
  if ($format =='TXT') {
    $file_extension = '.txt';
	$FIELDSTART = '';
    $FIELDEND = '';
    $FIELDSEPARATOR = "\t"; // Tab separated
    //$FIELDSEPARATOR = ','; // Comma separated
    $LINESTART = '';
    $LINEBREAK = "\n";
	$ATTRIBSEPARATOR = ' | '; //Be Careful with this option. Setting it to a 'comma' for example could throw off the remaining fields.
  }
  //echo $file_extension;
  $file = (isset($_POST['filename']) ? $_POST['filename'] : "Orders".date('mdy-Hi'). $file_extension ."");
  //echo $file;
  //$file = (isset($_POST['filename']) ? $_POST['filename'] : "Orders". $file_extension ."");
  $to_email_address = (isset($_POST['auto_email_supplier']) ? $_POST['auto_email_supplier'] : "".EMAIL_EXPORT_ADDRESS."");
  $email_subject = (isset($_POST['auto_email_subject']) ? $_POST['auto_email_subject'] : "Order export from ".STORE_NAME."");
/*******************/

 if( isset($_POST['download_csv']) ) { // If form was submitted then do processing.
// begin streaming file contents
/*
    Header('Content-type: application/csv');
    Header("Content-disposition: attachment; filename=\"". $file ."");
*/
// if date_range is set then gather form vars for SQL processing
if ($_POST['start_date'] != '') {
	  $start_date = $_POST['start_date'] . ' 00:00';
}
if ($_POST['end_date'] != '') {
	  $end_date = $_POST['end_date'] . ' 23:59';
}
//**************************************************************

if ($_POST['filelayout'] == 2) { // 1 Product Per row RADIO

	$order_info = "SELECT o.orders_id, customers_email_address, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, shipping_method, customers_telephone, order_total, op.products_model, products_name, op.products_price, final_price, op.products_quantity, date_purchased, ot.value, orders_products_id, order_tax, o.orders_status, o.payment_method";
if ($_POST['iso_country2_code'] == 1) { $order_info = $order_info . ", cc.countries_iso_code_2"; };
if ($_POST['iso_country3_code'] == 1) { $order_info = $order_info . ", cc.countries_iso_code_3"; };
/*
if (ACCOUNT_STATE == 'true') {
	$order_info = $order_info . ", z.zone_code";
}
*/
	$order_info = $order_info . " FROM (". TABLE_ORDERS ." o LEFT JOIN ". TABLE_ORDERS_PRODUCTS ." op ON o.orders_id = op.orders_id), ". TABLE_ORDERS_TOTAL ." ot";
	if ($_POST['iso_country2_code'] == 1 || $_POST['iso_country3_code'] == 1) { $order_info = $order_info . ", " . TABLE_COUNTRIES . " cc"; };
/*
if (ACCOUNT_STATE == 'true') {
	$order_info = $order_info . ", " . TABLE_ZONES . " z";
}
*/
	if ($_POST['iso_country2_code'] == 1 || $_POST['iso_country3_code'] == 1) { $order_info = $order_info . " AND cc.countries_name = o.delivery_country "; };
	$order_info = $order_info . " WHERE o.orders_id = ot.orders_id ";
/*
if (ACCOUNT_STATE == 'true') { // If states are used on account form then find out which type.
	if (ACCOUNT_STATE_DRAW_INITIAL_DROPDOWN == 'true') { // If using state drop down then match against the abbreviation
		$order_info = $order_info . "AND z.zone_code = o.delivery_state ";
	} else { //Not using state drop down so match against full state name.
		$order_info = $order_info . "AND z.zone_name = o.delivery_state ";
	} // end if state drop down or not.
} // end if for determining if states are used on account form.
*/
	$order_info = $order_info . "AND ot.class = 'ot_shipping'";
	if ($_POST['dload_include'] != 1) {
	$order_info = $order_info . " AND downloaded_ship='no'";
	}
	if ($_POST['status_target'] == 2) {
		  $order_info = $order_info . " AND o.orders_status = '" . $_POST['order_status'] . "'";
	}
	if ($_POST['start_date'] != '' && $_POST['end_date'] != '') {
	$order_info = $order_info . " AND date_purchased BETWEEN '". $start_date ."' AND '". $end_date ."'";
	//$order_info = $order_info . " AND date_purchased >= '". $start_date ."' AND date_purchased <= '". $end_date ."'";
	}
	$datfrm = '2019-01-21 00:00:00';
	$order_info .= " AND date_purchased > '".$datfrm."' ";
	$order_info = $order_info . " ORDER BY orders_id ASC";
	//echo $order_info;

} else { // Default 1 Order Per row (filelayout1=1)

	$order_info = "SELECT o.orders_id, customers_email_address, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, shipping_method, customers_telephone, order_total, date_purchased, ot.value, comments, order_tax, o.orders_status, o.payment_method";
if ($_POST['iso_country2_code'] == 1) { $order_info = $order_info . ", cc.countries_iso_code_2"; };
if ($_POST['iso_country3_code'] == 1) { $order_info = $order_info . ", cc.countries_iso_code_3"; };
/*
if (ACCOUNT_STATE == 'true') {
	$order_info = $order_info . ", z.zone_code";
}
*/
	$order_info = $order_info . " FROM ". TABLE_ORDERS ." o, " . TABLE_ORDERS_STATUS_HISTORY . " os, " . TABLE_ORDERS_TOTAL . " ot";
	if ($_POST['iso_country2_code'] == 1 || $_POST['iso_country3_code'] == 1) { $order_info = $order_info . ", " . TABLE_COUNTRIES . " cc"; };
/*
if (ACCOUNT_STATE == 'true') {
	$order_info = $order_info . ", " . TABLE_ZONES . " z";
}
*/
	$order_info = $order_info . " WHERE o.orders_id = ot.orders_id 
	AND ot.class = 'ot_shipping' ";
	if ($_POST['iso_country2_code'] == 1 || $_POST['iso_country3_code'] == 1) { $order_info = $order_info . " AND cc.countries_name = o.delivery_country "; };
/*
if (ACCOUNT_STATE == 'true') { // If states are used on account form then find out which type.
	if (ACCOUNT_STATE_DRAW_INITIAL_DROPDOWN == 'true') { // If using state drop down then match against the abbreviation
		$order_info = $order_info . "AND z.zone_code = o.delivery_state ";
	} else { //Not using state drop down so match against full state name.
		$order_info = $order_info . "AND z.zone_name = o.delivery_state ";
	} // end if state drop down or not.
} // end if for determining if states are used on account form.
*/
	$order_info = $order_info . "AND o.orders_id = os.orders_id";
	if ($_POST['dload_include'] != 1) {
	$order_info = $order_info . " AND downloaded_ship='no'";
	}
	if ($_POST['status_target'] == 2) {
	$order_info = $order_info . " AND o.orders_status = '" . $_POST['order_status'] . "'";
	}
	if ($_POST['start_date'] != '' && $_POST['end_date'] != '') {
	$order_info = $order_info . " AND date_purchased BETWEEN '". $start_date ."' AND '". $end_date ."'";
	//$order_info = $order_info . " AND date_purchased >= '". $start_date ."' AND date_purchased <= '". $end_date ."'";
	}
	$order_info = $order_info . " GROUP BY orders_id ASC";
	//echo $order_info;
	
	$max_num_products = "SELECT COUNT( * ) AS max_num_of_products
	FROM (". TABLE_ORDERS ." o LEFT JOIN ". TABLE_ORDERS_PRODUCTS ." op ON o.orders_id = op.orders_id), ". TABLE_ORDERS_TOTAL ." ot
	WHERE o.orders_id = ot.orders_id
	AND ot.class = 'ot_shipping'";
	if ($_POST['dload_include'] != 1) {
	$max_num_products = $max_num_products . " AND downloaded_ship='no'";
	}
	if ($_POST['status_target'] == 2) {
	$max_num_products = $max_num_products . " AND o.orders_status = '" . $_POST['order_status'] . "'";
	}
	if ($_POST['start_date'] != '' && $_POST['end_date'] != '') {
	$max_num_products = $max_num_products . " AND date_purchased BETWEEN '". $start_date ."' AND '". $end_date ."'";
	//$max_num_products = $max_num_products . " AND date_purchased >= '". $start_date ."' AND date_purchased <= '". $end_date ."'";
	}
	
	$max_num_products = $max_num_products . " GROUP BY o.orders_id ASC
	ORDER BY max_num_of_products DESC
	LIMIT 1";
	  $max_num_products_result = $db->Execute($max_num_products);
	  $max_products = $max_num_products_result->fields['max_num_of_products'];

} // End File layout sql
	
	$order_info = $order_info."   LIMIT 0 , 100 ";
	//echo $order_info;

$order_details = $db->Execute($order_info);
//echo "RES".$order_details->RecordCount();
//exit;
if($order_details->RecordCount() > 0) { 
	
	/******************Begin Set Header Row Information*****************************/
	     $str_header = 	"Order ID,Customer Email";
	if ($_POST['split_name'] == 1) { //If name split is desired then split it.
		 $str_header = $str_header . ",First Name,Last Name";
	} else {
		 $str_header = $str_header . ",Delivery Name";
	}
		 $str_header = $str_header . ",Company,Delivery Street,Delivery Suburb,Delivery City,Delivery State,Delivery Post Code,Delivery Country,Ship Dest Type"; // swguy
			if ($_POST['shipmethod'] == 1) { $str_header = $str_header . ",Shipping Method"; };
			if ($_POST['shiptotal'] == 1) { $str_header = $str_header . ",Shipping Total"; };
			if ($_POST['customers_telephone'] == 1) { $str_header = $str_header . ",Customers Telephone"; };
			if ($_POST['order_total'] == 1) { $str_header = $str_header . ",Order Total"; };
			if ($_POST['date_purchased'] == 1) { $str_header = $str_header . ",Order Date"; };
			if ($_POST['order_comments'] == 1) { $str_header = $str_header . ",Order Notes"; };
			if ($_POST['order_tax'] == 1) { $str_header = $str_header . ",Order Tax"; };
			if ($_POST['order_subtotal'] == 1) { $str_header = $str_header . ",Order Subtotal"; };
			if ($_POST['order_discount'] == 1) { $str_header = $str_header . ",Order Discount"; };
			if ($_POST['payment_method'] == 1) { $str_header = $str_header . ",Payment Method"; };
			if ($_POST['orders_status_export'] == 1) { $str_header = $str_header . ",Order Status"; };
			if ($_POST['iso_country2_code'] == 1) { $str_header = $str_header . ",ISO Country Code 2"; };
			if ($_POST['iso_country3_code'] == 1) { $str_header = $str_header . ",ISO Country Code 3"; };
	//		if ($_POST['abbr_state_code'] == 1) { $str_header = $str_header . ",Abbr State Code"; };
	if ($_POST['product_details'] == 1) { // add to header row
		if ($_POST['filelayout'] == 2) { // 1 Product Per row RADIO
				$str_header = $str_header . ",Product Qty,Products Price,Product Name,Product Model,Product Attributes";
		} else { // File layout is 1 OPR
		/**************the following exports 1 OPR attribs****************/
		  $oID = zen_db_prepare_input($order_details->fields['orders_id']);
		  $oIDME = $order_details->fields['orders_id'];
		  $order = new order($oID);
			for ($i = 0, $n = $max_products; $i < $n; $i++) {
				$str_header = $str_header . ",Product " . $i . " Qty";
				$str_header = $str_header . ",Product " . $i . " Price";
				$str_header = $str_header . ",Product " . $i . " Name";
				$str_header = $str_header . ",Product " . $i . " Model";
				$str_header = $str_header . ",Product " . $i . " Attributes";
		    }
		/*****************************************************************/
		} // End if to determine which header to use
	} // end Row header if product details selected
		   $str_header = $str_header . "\n";
	/******************End Header Row Information*****************************/
	
	/* dhc */
		//echo $str_header;
	//	$str_header = $str_header . $order_info . "<br />\n" . $order_details->RecordCount() . "<br />\n";
		$str_full_export = "";
		$newsendarray = array();
	while( !$order_details->EOF ) {
	
       $str_export = $FIELDSTART . $order_details->fields['orders_id'] . $FIELDEND . $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['customers_email_address'] . $FIELDEND;
       $newsendarray['Order ID'] = utf8_encode($order_details->fields['orders_id']);
       $newsendarray['Customer Email'] = utf8_encode($order_details->fields['customers_email_address']);
		if ($_POST['split_name'] == 1) { 
			$fullname = $order_details->fields['delivery_name'];
			  list($first, $middle, $last) = split(' ', $fullname);
			  if ( !$last ) {
			    $last = $middle;
			    unset($middle);
			 }
			$str_export .= $FIELDSEPARATOR . $FIELDSTART . $first . $FIELDEND . $FIELDSEPARATOR . $FIELDSTART . $last . $FIELDEND;
			$newsendarray['First Name'] = utf8_encode($first);
			$newsendarray['Last Name'] = utf8_encode($last); 
		} else {
			$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_name'] . $FIELDEND; 
			$newsendarray['First Name'] = utf8_encode($order_details->fields['delivery_name']);
		};
		
// swguy
        if ($order_details->fields['delivery_company'] == '') {
           $dest_type = 'Residential'; 
        } else {
           $dest_type = 'Commercial'; 
        }
// end swguy
			$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_company'] . $FIELDEND . $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_street_address'] . $FIELDEND .
			$FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_suburb'] . $FIELDEND . $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_city'] . $FIELDEND .
			$FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_state'] . $FIELDEND . $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_postcode'] . $FIELDEND .
			$FIELDSEPARATOR . $FIELDSTART . $order_details->fields['delivery_country'] . $FIELDEND .
			$FIELDSEPARATOR . $FIELDSTART . $dest_type . $FIELDEND;
			
			$newsendarray['Company'] = utf8_encode($order_details->fields['delivery_company']);
			$newsendarray['Delivery Street'] = utf8_encode($order_details->fields['delivery_street_address']);
			$newsendarray['Delivery Suburb'] = utf8_encode($order_details->fields['delivery_suburb']);
			$newsendarray['Delivery City'] = utf8_encode($order_details->fields['delivery_country']);
			$newsendarray['Delivery State'] = utf8_encode($order_details->fields['delivery_state']);
			$newsendarray['Delivery Post Code'] = utf8_encode($order_details->fields['delivery_postcode']);
			$newsendarray['Delivery Country'] = utf8_encode($order_details->fields['delivery_country']);
			$newsendarray['Ship Dest Type'] = utf8_encode($dest_type);
			//echo json_encode($newsendarray);
// swguy last line changed		
		if ($_POST['shipmethod'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['shipping_method'] . $FIELDEND;
			$newsendarray['Shipping Method'] = utf8_encode($order_details->fields['shipping_method']);
		 };
		if ($_POST['shiptotal'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['value'] . $FIELDEND; };
		if ($_POST['customers_telephone'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['customers_telephone'] . $FIELDEND; };
		if ($_POST['order_total'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['order_total'] . $FIELDEND;
			$newsendarray['Order Total'] = utf8_encode($order_details->fields['order_total']); 
		};
		if ($_POST['date_purchased'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['date_purchased'] . $FIELDEND;
			$newsendarray['Order Date'] = utf8_encode($order_details->fields['date_purchased']);
		 };
		if ($_POST['order_comments'] == 1) { 
			 if ($_POST['filelayout'] == 2) { // 1 Product Per row RADIO
				$orders_comments_query="SELECT *  FROM " . TABLE_ORDERS_STATUS_HISTORY . " WHERE orders_id = " . $order_details->fields['orders_id'] . " GROUP BY orders_id ORDER BY orders_status_history_id ASC";
				$orders_comments = $db->Execute($orders_comments_query);
					$str_safequotes = str_replace('"',"'",$orders_comments->fields['comments']); // replace quotes with single quotes if present
					//$str_safequotes = $str_safequotes . str_replace(","," ",$str_safequotes); // replace commas with blank space if present
					// dhc 16-Nov-2007 array("\r\n","\r","\n")
					$str_export .= $FIELDSEPARATOR . $FIELDSTART . str_replace(array("\r\n","\r","\n"), " ", $str_safequotes) . $FIELDEND; // Remove any line breaks in first comment and print to export string
					$newsendarray['Order Notes'] = utf8_encode(str_replace(array("\r\n","\r","\n"), " ", $str_safequotes));
			 } else {
					$str_safequotes = str_replace('"',"'",$order_details->fields['comments']); // replace quotes with single quotes if present
					//$str_safequotes = $str_safequotes . str_replace(","," ",$str_safequotes); // replace commas with blank space if present
					// dhc 16-Nov-2007 array("\r\n","\r","\n")
					$str_export .= $FIELDSEPARATOR . $FIELDSTART . str_replace(array("\r\n","\r","\n"), " ", $str_safequotes) . $FIELDEND; // Remove any line breaks in first comment and print to export string
			 }
		}
			
/***********************************************************************************************************************************/
if ($_POST['order_tax'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['order_tax'] . $FIELDEND; };
		
if ($_POST['order_subtotal'] == 1) {
		
	$orders_subtotal_query = "SELECT o.orders_id, customers_email_address, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, shipping_method, customers_telephone, order_total, products_model, products_name, products_price, final_price, products_quantity, date_purchased, ot.value, orders_products_id, order_tax
	FROM (". TABLE_ORDERS ." o LEFT JOIN ". TABLE_ORDERS_PRODUCTS ." op ON o.orders_id = op.orders_id), ". TABLE_ORDERS_TOTAL ." ot
	WHERE o.orders_id = ot.orders_id
	AND ot.class = 'ot_subtotal'
	AND ot.orders_id = " . $order_details->fields['orders_id'] . "";
if ($_POST['dload_include'] != 1) {
$orders_subtotal_query = $orders_subtotal_query . " AND downloaded_ship='no'";
}
if ($_POST['status_target'] == 2) {
$orders_subtotal_query = $orders_subtotal_query . " AND o.orders_status = '" . $_POST['order_status'] . "'";
}
if ($_POST['start_date'] != '' && $_POST['end_date'] != '') {
$orders_subtotal_query = $orders_subtotal_query . " AND date_purchased BETWEEN '". $start_date ."' AND '". $end_date ."'";
//$orders_subtotal_query = $orders_subtotal_query . " AND date_purchased >= '". $start_date ."' AND date_purchased <= '". $end_date ."'";
}
	$orders_subtotal_query = $orders_subtotal_query . " ORDER BY orders_id ASC";

	$orders_subtotal = $db->Execute($orders_subtotal_query);

//$recordcount = mysql_query($orders_subtotal_query);
$num_rows = $orders_subtotal->RecordCount(); 
	//if( !isset($orders_subtotal->fields['o.orders_id']) ) {
	//if (mysql_num_rows($result) > 0) { // if records were found
	//$num_rows = mysql_num_rows($orders_subtotal_query);
	if ( $num_rows > 0) {
		 $str_export .= $FIELDSEPARATOR . $FIELDSTART . $orders_subtotal->fields['value'] . $FIELDEND; //add discount amt to export string
	} else { // add a BLANK field to the export file for "consistancy"
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $FIELDEND; // add blank space for filler
	} // end if
 
}
//echo $str_export;
		//exit;
if ($_POST['order_discount'] == 1) { // if order discount was selected, then run the query to pull the data for adding it to the export string.
// Run a query to pull the Order Discount total if present
	$orders_discount_query = "SELECT o.orders_id, ot.value
	FROM (". TABLE_ORDERS ." o LEFT JOIN ". TABLE_ORDERS_PRODUCTS ." op ON o.orders_id = op.orders_id), ". TABLE_ORDERS_TOTAL ." ot
	WHERE o.orders_id = ot.orders_id
	AND ot.class = 'ot_coupon'
	AND ot.orders_id = " . $order_details->fields['orders_id'] . "";
if ($_POST['dload_include'] != 1) {
$orders_discount_query = $orders_discount_query . " AND downloaded_ship='no'";
}
if ($_POST['status_target'] == 2) {
$orders_discount_query = $orders_discount_query . " AND o.orders_status = '" . $_POST['order_status'] . "'";
}
if ($_POST['start_date'] != '' && $_POST['end_date'] != '') {
$orders_discount_query = $orders_discount_query . " AND date_purchased BETWEEN '". $start_date ."' AND '". $end_date ."'";
//$orders_discount_query = $orders_discount_query . " AND date_purchased >= '". $start_date ."' AND date_purchased <= '". $end_date ."'";
}
	$orders_discount_query = $orders_discount_query . " ORDER BY orders_id ASC";
	
	$orders_discount = $db->Execute($orders_discount_query);

//$recordcount = mysql_query($orders_discount_query);
$num_rows = $orders_discount->RecordCount(); 
	if ($num_rows > 0) { // if records were found
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $orders_discount->fields['value'] . $FIELDEND; //add discount amt to export string
	} else { // add a BLANK field to the export file for "consistancy"
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $FIELDEND; // add blank space for filler
	} // end if
} // End if for determining if order discount was selected to export.

//*********Add Payment Method if selected***************/
if ($_POST['payment_method'] == 1) { $str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['payment_method'] . $FIELDEND; };
//******************************************************/

if ($_POST['orders_status_export'] == 1) { // if order status was selected, then run the query to pull the data for adding it to the export string.
// Run a query to pull the Order Status if present
	$orders_status_query = "SELECT orders_status_name 
	FROM (". TABLE_ORDERS_STATUS .")
	WHERE orders_status_id=" . $order_details->fields['orders_status'] . "";
	$orders_status = $db->Execute($orders_status_query);

//$recordcount = mysql_query($orders_status_query);
$num_rows = $orders_status->RecordCount(); 
	if ($num_rows > 0) { // if records were found
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $orders_status->fields['orders_status_name'] . $FIELDEND; //add discount amt to export string
	} else { // add a BLANK field to the export file for "consistancy"
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $FIELDEND; // add blank space for filler
	} // end if
} // End if for determining if order discount was selected to export.

//*************bof ISO Country Codes********************//
if ($_POST['iso_country2_code'] == 1) { // if iso country 2 was selected, then add it to the export string.
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['countries_iso_code_2'] . $FIELDEND; //add ISO country code to export string
}
if ($_POST['iso_country3_code'] == 1) { // if iso country 3 was selected, then add it to the export string.
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['countries_iso_code_3'] . $FIELDEND; //add ISO country code to export string
}
//*************eof ISO Country Codes********************//
//*************bof State Abbr Codes********************//
/*
if ($_POST['abbr_state_code'] == 1) { // if state abbr code was selected, then add it to the export string.
		$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['zone_code'] . $FIELDEND; //add State Abbrv. to export string
}
*/
//*************eof State Abbr Codes********************//
/***********************************************************************************************************************************/

if ($_POST['product_details'] == 1) { // Order details should be added to the export string.

if ($_POST['filelayout'] == 2) { // 1 PPR RADIO

$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['products_quantity'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['final_price'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['products_name'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order_details->fields['products_model'] . $FIELDEND . $FIELDSEPARATOR;

$newsendarray['Product Qty'] = utf8_encode($order_details->fields['products_quantity']);
$newsendarray['Products Price'] = utf8_encode($order_details->fields['final_price']);
$newsendarray['Product Name'] = utf8_encode($order_details->fields['products_name']);
$newsendarray['Product Model'] = utf8_encode($order_details->fields['products_model']);
//echo json_encode($newsendarray);
//exit;

$product_attributes_rows="SELECT Count(*) as num_rows
FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . "
WHERE orders_id = " . $order_details->fields['orders_id'] . "
AND orders_products_id = " . (int)$order_details->fields['orders_products_id'] . "";
//echo "WHILE IN".$product_attributes_rows;
//exit;
$attributes_query_rows = $db->Execute($product_attributes_rows);
$num_rows = $attributes_query_rows->fields['num_rows'];
	$productatt ="";
	
	If ( $num_rows > 0) {
	$product_attributes_query="SELECT *
	FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . "
	WHERE orders_id = " . $order_details->fields['orders_id'] . "
	AND orders_products_id = " . $order_details->fields['orders_products_id'] . "";
	$attributes_query_results = $db->Execute($product_attributes_query);
	$str_export .= $FIELDSTART;
		for ($i = 0, $n = $num_rows; $i < $n; $i++) {
			//dhc 
			$str_safequotes = str_replace('"',"'",$attributes_query_results->fields['products_options_values']);
			$str_export .= $attributes_query_results->fields['products_options'] . ': ' . str_replace(array("\r\n","\r","\n"), " ", $str_safequotes) . $ATTRIBSEPARATOR;
			$productatt =$attributes_query_results->fields['products_options'] . ': ' . str_replace(array("\r\n","\r","\n"), " ", $str_safequotes) . $ATTRIBSEPARATOR;
			$attributes_query_results->MoveNext();
		
		}
	$str_export .= $FIELDEND;
}
$newsendarray['Product Attributes'] = utf8_encode($productatt);

} else { // 1 OPR default

/**************the following exports 1 OPR w/ attributes) ****************/
  $oID = zen_db_prepare_input($order_details->fields['orders_id']);
  $oIDME = $order_details->fields['orders_id'];
  $order = new order($oID);
    for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order->products[$i]['qty'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order->products[$i]['final_price'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order->products[$i]['name'] . $FIELDEND;
$str_export .= $FIELDSEPARATOR . $FIELDSTART . $order->products[$i]['model'] . $FIELDEND . $FIELDSEPARATOR;
      if (isset($order->products[$i]['attributes']) && (($k = sizeof($order->products[$i]['attributes'])) > 0)) {
$str_export .= $FIELDSTART;
        for ($j = 0; $j < $k; $j++) {
//erl
//$str_export .= $order->products[$i]['attributes'][$j]['option'] . ': ' . nl2br($order->products[$i]['attributes'][$j]['value']) . $ATTRIBSEPARATOR;
			//dhc
			$str_safequotes = str_replace('"',"'",$order->products[$i]['attributes'][$j]['value']);
			$str_export .= $order->products[$i]['attributes'][$j]['option'] . ': ' . str_replace(array("\r\n","\r","\n"), " ", $str_safequotes) . $ATTRIBSEPARATOR;
        }
$str_export .= $FIELDEND;
      }
    }
/*************************************************************************/
} // End if for determining type of export

} // End if to determine if the order details should be added to the export string.

	

	   $str_export = $str_export . "\n";
	   $str_full_export .= $str_export;
	   //echo $str_export . "<br />\n"; //dhc
	//********************************************************************
$order_details->MoveNext();
		//echo json_encode($newsendarray);
		//print"<pre>";
		//print_r($newsendarray);
		//echo $i;
		$newsendarrayLAST[$i] = $newsendarray;
		$i++;
} // End Outer While statement to loop through all non downloaded orders.
//echo json_encode($order_details);
//exit;
//echo "HERE";
	//	
	//print"<pre>";

//$array = unserialize($newsendarrayLAST);
 $json = json_encode($newsendarrayLAST);
// echo  json_last_error();
 echo $json;
 //$jsonError = json_last_error();
 //var_dump($json);
exit;
/**************************************Process the export file**************************************************/
if ($save_to_file_checked == 1) { // saving to a file for email attachement, so write and ready else do regular output (prompt for download)
  // Do not set headers becuase we are going to email the file to the supplier.
        //open output file for writing
        $f=fopen(DIR_FS_EMAIL_EXPORT.$file,'w+');
        //fwrite($f,$str_export);
// swguy
	   if ($_POST['include_header_row'] == 1) { //Include the Header Row In The Export Else Leave out
		fwrite($f,$str_header);
	   }
// End swguy
        fwrite($f,$str_full_export);
        fclose($f);
        unset($f);
		//Email File to Supplier
    // send the email
    zen_mail('Supplier Name', $to_email_address, $email_subject, EMAIL_EXPORT_BODY, STORE_NAME, EMAIL_FROM, $html_msg,'default', DIR_FS_EMAIL_EXPORT.$file);
	
	/***************************End Update records in db if selected by user***************************/
 	} else { // This export should be in the format of a file download so set page headers.

	}
 }// end of record if count 
/*******************************************************************************************************/
}
?>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>