<?php

	define("MAX_ORDERS_PER_PRINT", 48 );
	define("ORDERS_PER_COLUMN",    12 );
	define("CALL_TIMESTAMP",       date('Y-m-d-H-i-s'));
	define("CALL_DATE_TIME",       date('g:iA \o\n l \t\h\e jS \o\f F Y  (Y-m-d H:i:s)'));
	define("ACCOUNT_NAME",         "General Merchandise International Limited - UK" );
	define("REFRESH_TOKEN",        "k80-gm2WIi47rINc75-wZVryYE5OL9wi1DZLw5nOtiU"    );
	define("APPLICATION_ID",       "vcci9vtyaf6yck38w9pg6ktymat66vx5"               );
	define("SHARED_SECRET",        "HggjlAcyUk24ZjsebHTBUQ"                         );
	define("ACCESS_TOKEN",         ca_api_get_access_token()           );
	define("PROFILE_ID",           ca_api_get_profile_id(ACCOUNT_NAME) );
	$G_GMI_DCS      = array('GMI-NTHRFLD-01','GMI-ARWCAB');
	$G_SUPPLIER_DCS = array('GROVES','SMPLCT','BUTTER','NOVA','WHTCRF','DRWONO','TRHOPR','ARWCAB');
	define("DATABASE_NAME"  , "sewing_so");
	define("MYSQL_USERNAME" , "sewing_so");
	define("MYSQL_PASSWORD" , "Gr33n3y3Y#rk!p##");
	$mysqli = new mysqli('localhost', MYSQL_USERNAME, MYSQL_PASSWORD, DATABASE_NAME);
	if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }
	
	$distribution_centres = array(
		-3=>"AMAZON",  
		 1=>"GROVES",  
		 3=>"STOCK",  
		 4=>"SIMPLICITY",  
		 5=>"BUTTERICK",  
		 6=>"NOVA", 
		12=>"BIRCH (AU)", 
		13=>"JACKSONS (AU)", 
		14=>"ARROW (US)", 
		15=>"STOCK", 
		17=>"SSS (AU)"
	);
?>
<?php
	function pre_print_r($val)
	{
		?><pre class="no_print"><?php print_r($val); ?></pre><?php
	}	
?>
<?php
	function channeladvisor_REST_API($endpoint, $fields=false)
	{
		$headers = [ 'Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode(APPLICATION_ID.':'.SHARED_SECRET) ];
		$ch = curl_init();
		curl_setopt ( $ch, CURLOPT_URL,            trim($endpoint)            );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true                       );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false                      );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false                      );
		curl_setopt ( $ch, CURLOPT_POST,           count($fields)             );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS,     http_build_query($fields)  );
		curl_setopt ( $ch, CURLOPT_TIMEOUT,        5                          );
		curl_setopt ( $ch, CURLOPT_HTTPHEADER,     $headers                   );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE                       );
		curl_setopt ( $ch, CURLOPT_HTTPGET,        false                      );
		curl_setopt ( $ch, CURLOPT_HEADER,         false                      ); // to see the header info displayed, change this to 1
		curl_setopt ( $ch, CURLINFO_HEADER_OUT,    true                       );
		curl_setopt ( $ch, CURLOPT_VERBOSE,        true                       );
		curl_setopt ( $ch, CURLOPT_STDERR,         $verbose = fopen('php://temp', 'rw+') );
		$result=curl_exec($ch); $error=curl_error($ch); curl_close($ch); // Parse the result and send it back to the calling function
		if ($error) { var_dump($error); return false; }
		return $result;
	}	

    function ca_api_get_access_token()
    {
        $endpoint = "https://api.channeladvisor.com/oauth2/token";
        $fields   = [ 'grant_type'    => 'refresh_token', 'refresh_token' => REFRESH_TOKEN ];
        $access_token = channeladvisor_REST_API($endpoint, $fields);
        if($access_token===false) return false;
        return json_decode($access_token,true)["access_token"];
    }

	function ca_api_GET($url)
	{
		$options = array('http' => array('method'  => 'GET','header'  => "Authorization: bearer ".ACCESS_TOKEN."\r\n"));
		return json_decode( file_get_contents( $url, false, stream_context_create( $options ) ) );	
	}

	function ca_api_get_profile_id($account_name)
	{
		$result = ca_api_GET("https://api.channeladvisor.com/v1/Profiles");
		foreach($result->value AS $profile) if($profile->AccountName==$account_name) return $profile->ID;
		return null;
	}

	function ca_api_get_profile_distribution_centres($profile_id)
	{
		$next_link="https://api.channeladvisor.com/v1/DistributionCenters?ProfileID()=".$profile_id;
		while($next_link!=null && $next_link!="") {
			$result = ca_api_GET($next_link);
			$dc_list = (is_array($dc_list) ? array_merge($dc_list,$result->value) : $result->value);
			$next_link = get_object_vars($result)['@odata.nextLink'];
		}
		return($dc_list);
	}

	function getDistributionCentresFromChannelAdvisor()
	{
	Global $G_GMI_DCS, $G_SUPPLIER_DCS;
	
		$result['GMI'     ] = array();
		$result['SUPPLIER'] = array();
        $result['IGNORE'  ] = array();
		$result['REVERSE' ] = array();
		
		$dcs = ca_api_get_profile_distribution_centres(PROFILE_ID);
		foreach($dcs AS $dc)
		{
			if      ( in_array($dc->Code , $G_GMI_DCS      , true) ) $result['GMI'     ][$dc->ID] = $dc->Code;
			else if ( in_array($dc->Code , $G_SUPPLIER_DCS , true) ) $result['SUPPLIER'][$dc->ID] = $dc->Code;
			else                                                     $result['IGNORE'  ][$dc->ID] = $dc->Code;
			$result['REVERSE' ][$dc->Code] = $dc->ID;
		}
		return $result;
	}

	function get_product_ids_for_skus($skus)
	{
		$result=array();
		$ix=0; $filter = "Sku%20eq%20'DUMMYSKU'";
		foreach($skus AS $sku)
		{
			$filter.="%20or%20Sku%20eq%20'".$sku."'";
			if((++$ix)==10)
			{
				$sub_result = ca_api_GET("https://api.channeladvisor.com/v1/Products?\$filter=".$filter."&\$select=Sku,ID");
				foreach($sub_result->value AS $sku_id) $result[$sku_id->Sku] = $sku_id->ID;
				$ix=0; $filter = "Sku%20eq%20'DUMMYSKU'";
			}
		}
		$sub_result = ca_api_GET("https://api.channeladvisor.com/v1/Products?\$filter=".$filter."&\$select=Sku,ID");
		foreach($sub_result->value AS $sku_id) $result[$sku_id->Sku] = $sku_id->ID;
		return $result;
	}

	function ca_api_get_product_dcquantities_by_skus($skus)
	{
		$result=array();
		$sku_ids = get_product_ids_for_skus($skus);

		foreach($sku_ids AS $sku => $id)
		{
			$sub_result = ca_api_GET("https://api.channeladvisor.com/v1/Products(".$id.")/DCQuantities");
			foreach($sub_result->value AS $sku_dc_qty)
			{
				$result[$sku]['ca_product_id'] = $id;
				$result[$sku][$sku_dc_qty->DistributionCenterID] = $sku_dc_qty->AvailableQuantity;
			}
		}
		return $result;
	}

	function getStockLevelsForMagentoSalesFromChannelAdvisor($magento_sales)
	{
		Global $G_DISTRIBUTION_CENTRES;

		foreach($magento_sales AS $magento_sale) $skus[]=$magento_sale->sku;
		$skus=array_unique($skus);
		$sku_dc_qtys = ca_api_get_product_dcquantities_by_skus($skus);
		foreach($sku_dc_qtys AS $sku => $dc_qtys)
		{
			$ca_stock_info[$sku]['ca_product_id']=$dc_qtys['ca_product_id'];
			$ca_stock_info[$sku]['GMI'     ]['total']=0;
			$ca_stock_info[$sku]['SUPPLIER']['total']=0;
			foreach($dc_qtys AS $dc => $qty)
			{
				if($dc=='ca_product_id') continue;
				if( array_key_exists ( $dc , $G_DISTRIBUTION_CENTRES['GMI'] ) && $qty!=0 )
				{
					$ca_stock_info[$sku]['GMI'][$G_DISTRIBUTION_CENTRES['GMI'][$dc]]=$qty;
					$ca_stock_info[$sku]['GMI']['total']+=$qty;
				}
				else if( array_key_exists ( $dc , $G_DISTRIBUTION_CENTRES['SUPPLIER'] ) && $qty!=0 )
				{
					$ca_stock_info[$sku]['SUPPLIER'][$G_DISTRIBUTION_CENTRES['SUPPLIER'][$dc]]=$qty;
					$ca_stock_info[$sku]['SUPPLIER']['total']+=$qty;
				}
			}
		}
		return $ca_stock_info;
	}
?>
<?php
	require("fpdf181/fpdf.php");

	function WEB_currency_format($value) { return "£".number_format((float)$value, 2, '.', ''); }

	function WEB_address_text_format($order_Title,$order_FirstName,$order_LastName,$order_Suffix,$order_AddressLine1,$order_AddressLine2,$order_City,$order_CompanyJobTitle,$order_CountryName,$order_PostalCode,$order_StateOrProvinceName)
	{
		$name         = ""; $join = ""; if($order_Title              ) { $name     .=($join.$order_Title               ); $join=" ";   } if($order_FirstName          ) { $name     .=($join.$order_FirstName);            $join=" "; } if($order_LastName           ) { $name.=($join.$order_LastName ); $join=" "; } if($order_Suffix             ) { $name.=($join.$order_Suffix   ); $join=" "; }
		$company      = ""; $join = ""; if($order_CompanyJobTitle    ) { $company  .=($join.$order_CompanyJobTitle     ); $join=" ";   } if($order_CompanyName        ) { $company  .=($join.$order_CompanyName    );      $join=" "; }
		$AddressLine1  = explode("\n",$order_AddressLine1 ); if(is_array($AddressLine1) ) { $order_AddressLine1=$AddressLine1[0];   $order_AddressLine2=$AddressLine1[1];   }
		$address = ""; $join = ""; $blank_rows=9;
		if($name                     ) { $blank_rows--; $address.=($join.$name                     ); $join=chr(0x0A); }
		if($company                  ) { $blank_rows--; $address.=($join.$company                  ); $join=chr(0x0A); }
		if($order_AddressLine1       ) { $blank_rows--; $address.=($join.$order_AddressLine1       ); $join=chr(0x0A); }
		if($order_AddressLine2       ) { $blank_rows--; $address.=($join.$order_AddressLine2       ); $join=chr(0x0A); }
		if($order_City               ) { $blank_rows--; $address.=($join.$order_City               ); $join=chr(0x0A); }
		if($order_StateOrProvinceName) { $blank_rows--; $address.=($join.$order_StateOrProvinceName); $join=chr(0x0A); }
		if($order_PostalCode         ) { $blank_rows--; $address.=($join.$order_PostalCode         ); $join=chr(0x0A); }
		if($order_CountryName        ) { $blank_rows--; $address.=($join.$order_CountryName        ); $join=chr(0x0A); }
		while($blank_rows<9 && $blank_rows>0) { $address.=chr(0x0A); $blank_rows--; }
		return $address;
	}

	function WEB_telephone_text_format($order_DaytimePhone,$order_EveningPhone)
	{
		$telephone = ""; $join  = "";
		if($order_DaytimePhone ) { $telephone .= ($join .'Day: '.$order_DaytimePhone ); $join =" / "; }
		if($order_EveningPhone ) { $telephone .= ($join .'Eve: '.$order_EveningPhone ); $join =" ";   }
		return $telephone;
	}

	function CA_currency_format($SiteName, $value)
	{
		switch($SiteName)
		{
			case "Amazon UK" :
			case "eBay Fixed Price UK" :
				$currency_symbol = "£";
				break;

			case "eBay Fixed Price DE" : 
			case "Amazon Seller Central - DE" : 
			case "eBay Prix Fixe FR" : 
			case "Amazon Seller Central - FR" : 
			case "eBay Tiendas ES" : 
			case "Amazon Seller Central - ES" : 
			case "Amazon Seller Central - IT" : 
			case "Amazon Seller Central - NL" : 
				$currency_symbol = "€";
				break;
			
			default :
				$currency_symbol = "$";
				break;
		}
		return $currency_symbol.number_format((float)$value, 2, '.', '');
	}

	class InvoicePDF extends FPDF
	{
		// Page header
		function Header()
		{
			if (!$this->skipHeader){
				$LogoImage  = 'https://sewing-online.com/media/main_logo.png';
				$HeaderText = 'General Merchandise International'.chr(0x0A).'VAT Registration Number : GB 983852765'.chr(0x0A).'Sewing Online'.chr(0x0A).'9 Mallard Rd, Victoria Business Park'.chr(0x0A).'Netherfield, Nottingham, NG4 2PE'.chr(0x0A).'Tel: +44 (0)115 987 4422'.chr(0x0A).'Fax: +44(0)115 987 4001'.chr(0x0A).'Email: sales@sewing-online.com';
				$this->Image     (        $LogoImage,  10,10,80);  $this->Cell(95,10,'',0); $this->SetFont('Helvetica','',8); $this->SetTextColor(0,0,0); $this->MultiCell (95,3.5, $HeaderText, 0,'R'   );  $this->ln(10);
			}
		}

		function CA_PrepareOrder($order, $mysqli)
		{
			$thisOrder = array();
			switch($order->SiteName)
			{
				case 'Amazon UK'                  : $site_country_code="UK"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - US' : $site_country_code="US"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - AU' : $site_country_code="AU"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - CA' : $site_country_code="CA"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - DE' : $site_country_code="DE"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - ES' : $site_country_code="ES"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - FR' : $site_country_code="FR"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - IT' : $site_country_code="IT"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - NL' : $site_country_code="NL"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Amazon Seller Central - MX' : $site_country_code="MX"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'Catch AU'                   : $site_country_code="AU"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'TradeMe'                    : $site_country_code="NZ"; $SiteOrderID =         $order->SiteOrderID;          break;
				case 'eBay Fixed Price UK'        : $site_country_code="UK"; $SiteOrderID = "E-"  . $order->SecondarySiteOrderID; break;
				case 'eBay Fixed Price US'        : $site_country_code="US"; $SiteOrderID = "US-" . $order->SecondarySiteOrderID; break;
				case 'eBay Fixed Price AU'        : $site_country_code="AU"; $SiteOrderID = "AU-" . $order->SecondarySiteOrderID; break;
				case 'eBay Fixed Price DE'        : $site_country_code="DE"; $SiteOrderID = "DE-" . $order->SecondarySiteOrderID; break;
				case 'eBay Prix Fixe FR'          : $site_country_code="FR"; $SiteOrderID = "FR-" . $order->SecondarySiteOrderID; break;
				case 'eBay Tiendas ES'            : $site_country_code="ES"; $SiteOrderID = "ES-" . $order->SecondarySiteOrderID; break;
			}
			$ID             = $order->ID;
			$PaymentDateUtc = $order->PaymentDateUtc;
			$billing_name = ""; $billing_join = "";
			if($order->BillingTitle              ) { $billing_name.=($billing_join.$order->BillingTitle    ); $billing_join=" "; }
			if($order->BillingFirstName          ) { $billing_name.=($billing_join.$order->BillingFirstName); $billing_join=" "; }
			if($order->BillingLastName           ) { $billing_name.=($billing_join.$order->BillingLastName ); $billing_join=" "; }
			if($order->BillingSuffix             ) { $billing_name.=($billing_join.$order->BillingSuffix   ); $billing_join=" "; }
			$billing_company = ""; $billing_join = "";
			if($order->BillingCompanyJobTitle    ) { $billing_company.=($billing_join.$order->BillingCompanyJobTitle); $billing_join=" "; }
			if($order->BillingCompanyName        ) { $billing_company.=($billing_join.$order->BillingCompanyName    ); $billing_join=" "; }
			$billing_telephone = ""; $billing_join = "";
			if($order->BillingDaytimePhone       ) { $billing_telephone.=($billing_join.'Day: '.$order->BillingDaytimePhone); $billing_join=" / "; }
			if($order->BillingEveningPhone       ) { $billing_telephone.=($billing_join.'Eve: '.$order->BillingEveningPhone); $billing_join=" "; }
			$billing_address = ""; $billing_join = ""; $billing_blank_rows=9;
			if($billing_name                     ) { $billing_blank_rows--; $billing_address.=($billing_join.$billing_name                   ); $billing_join=chr(0x0A); }
			if($billing_company                  ) { $billing_blank_rows--; $billing_address.=($billing_join.$billing_company                ); $billing_join=chr(0x0A); }
			if($order->BillingAddressLine1       ) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingAddressLine1       ); $billing_join=chr(0x0A); }
			if($order->BillingAddressLine2       ) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingAddressLine2       ); $billing_join=chr(0x0A); }
			if($order->BillingCity               ) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingCity               ); $billing_join=chr(0x0A); }
			if($order->BillingStateOrProvinceName) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingStateOrProvinceName); $billing_join=chr(0x0A); }
			if($order->BillingPostalCode         ) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingPostalCode         ); $billing_join=chr(0x0A); }
			if($order->BillingCountryName        ) { $billing_blank_rows--; $billing_address.=($billing_join.$order->BillingCountryName        ); $billing_join=chr(0x0A); }
			while($billing_blank_rows<9 && $billing_blank_rows>0)
			{
				$billing_address.=chr(0x0A);
				$billing_blank_rows--;
			}
			$shipping_name = ""; $shipping_join = "";
			if($order->ShippingTitle              ) { $shipping_name.=($shipping_join.$order->ShippingTitle    ); $shipping_join=" "; }
			if($order->ShippingFirstName          ) { $shipping_name.=($shipping_join.$order->ShippingFirstName); $shipping_join=" "; }
			if($order->ShippingLastName           ) { $shipping_name.=($shipping_join.$order->ShippingLastName ); $shipping_join=" "; }
			if($order->ShippingSuffix             ) { $shipping_name.=($shipping_join.$order->ShippingSuffix   ); $shipping_join=" "; }
			$shipping_company = ""; $shipping_join = "";
			if($order->ShippingCompanyJobTitle    ) { $shipping_company.=($shipping_join.$order->ShippingCompanyJobTitle); $shipping_join=" "; }
			if($order->ShippingCompanyName        ) { $shipping_company.=($shipping_join.$order->ShippingCompanyName    ); $shipping_join=" "; }
			$shipping_telephone = ""; $shiping_join = "";
			if($order->ShippingDaytimePhone       ) { $shipping_telephone.=($shipping_join.'Day: '.$order->ShippingDaytimePhone); $shipping_join=" / "; }
			if($order->ShippingEveningPhone       ) { $shipping_telephone.=($shipping_join.'Eve: '.$order->ShippingEveningPhone); $shipping_join=" "; }
			$shipping_address = ""; $shipping_join = ""; $shipping_blank_rows=9;
			if($shipping_name                     ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$shipping_name                     ); $shipping_join=chr(0x0A); }
			if($shipping_company                  ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$shipping_company                  ); $shipping_join=chr(0x0A); }
			if($order->ShippingAddressLine1       ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingAddressLine1       ); $shipping_join=chr(0x0A); }
			if($order->ShippingAddressLine2       ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingAddressLine2       ); $shipping_join=chr(0x0A); }
			if($order->ShippingCity               ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingCity               ); $shipping_join=chr(0x0A); }
			if($order->ShippingStateOrProvinceName) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingStateOrProvinceName); $shipping_join=chr(0x0A); }
			if($order->ShippingPostalCode         ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingPostalCode         ); $shipping_join=chr(0x0A); }
			if($order->ShippingCountryName        ) { $shipping_blank_rows--; $shipping_address.=($shipping_join.$order->ShippingCountryName        ); $shipping_join=chr(0x0A); }
			while($shipping_blank_rows>0)
			{
				$shipping_address.=chr(0x0A);
				$shipping_blank_rows--;
			}
			$thisOrder['Invoice']['InvoiceInfoText']='Invoice # '.$ID.chr(0x0A).'Order # '.$SiteOrderID.chr(0x0A).'Order Date: '.date("d M Y H:i:s",strtotime($PaymentDateUtc." UTC")).'';
			switch($order->OrderTags)
			{
				case 'AmazonBusiness'             					: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/amazon-business.jpg';       				break;
				case 'AmazonMerchantPrime'        					: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/amazon-merchant-prime.jpg'; 				break;
				case 'eBayClickAndCollect'        					: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/click-and-collect.jpg';     				break;
				case 'eBayClickAndCollect,eBayWithdrawZeroSales'	: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/click-and-collect.jpg';     				break;
				case 'eBayPlusDelivery'           					: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/ebay-plus-delivery.jpg';    				break;
				case 'AmazonMerchantPrime,AmazonBusiness'			: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/amazon-merchant-prime_amazon-business.jpg';	break;
				case 'eBayClickAndCollect,eBayPlusDelivery'			: $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/order-tags/click-and-collect_ebay-plus-delivery.jpg';	break;
				default                                             : $thisOrder['Invoice']['MarketTagsImage']='https://sewing-online.com/ca-rest-api/images/flags/blank.jpg';                                      break;
			}
			switch($order->SiteName)
			{
				case 'Amazon UK'                  : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/gb.jpg';    break;
				case 'Amazon Seller Central - US' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/us.jpg';    break;
				case 'Amazon Seller Central - AU' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/au.jpg';    break;
				case 'Amazon Seller Central - CA' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/ca.jpg';    break;
				case 'Amazon Seller Central - DE' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/de.jpg';    break;
				case 'Amazon Seller Central - ES' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/es.jpg';    break;
				case 'Amazon Seller Central - FR' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/fr.jpg';    break;
				case 'Amazon Seller Central - IT' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/it.jpg';    break;
				case 'Amazon Seller Central - NL' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/nl.jpg';    break;
				case 'Amazon Seller Central - MX' : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/amazon.jpg';  $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/mx.jpg';    break;
				case 'Catch AU'                   : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/catch.jpg';   $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/au.jpg';    break;
				case 'eBay Fixed Price UK'        : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/ebay.jpg';    $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/gb.jpg';    break;
				case 'eBay Fixed Price US'        : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/ebay.jpg';    $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/us.jpg';    break;
				case 'eBay Fixed Price AU'        : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/ebay.jpg';    $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/au.jpg';    break;
				case 'eBay Fixed Price DE'        : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/ebay.jpg';    $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/de.jpg';    break;
				case 'eBay Prix Fixe FR'          : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/ebay.jpg';    $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/fr.jpg';    break;
				case 'TradeMe'                    : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/markets/trademe.jpg'; $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/nz.jpg';    break;
				default                           : $thisOrder['Invoice']['MarketNameImage']='https://sewing-online.com/ca-rest-api/images/flags/blank.jpg';     $thisOrder['Invoice']['MarketCountryImage']='https://sewing-online.com/ca-rest-api/images/flags/blank.jpg'; break;
			}
			$thisOrder['Invoice']['BillingAddressText'      ] = $billing_address?$billing_address:$shipping_address;
			$thisOrder['Invoice']['ShippingAddressText'     ] = $shipping_address;
			$thisOrder['Invoice']['ShippingCountryFlagImage'] = 'https://sewing-online.com/ca-rest-api/images/flags/'.(($order->ShippingCountryFlag!="gb.jpg")?($order->ShippingCountryFlag):('blank.jpg'));
			$thisOrder['Invoice']['BillingTelephoneText'    ] = $billing_telephone;
			$thisOrder['Invoice']['ShippingTelephoneText'   ] = $shipping_telephone;
			$ship_class_join="";
			$ship_class="";
			$order_fulfillments=$mysqli->query("SELECT * FROM __ca_order_fulfillments WHERE OrderID=".$order->ID);
			while($order_fulfillment=$order_fulfillments->fetch_object())
			{
				$ship_class .= ($ship_class_join.$order_fulfillment->ShippingClass);
				$ship_class_join=" / ";
			}
			$thisOrder['Invoice']['PaymentMethodText'] = $order->PaymentMethod. ' ('.(($order->BuyerUserId!=$order->BuyerEmailAddress)?$order->BuyerUserId:'').')'.chr(0x0A).'Payer Email: '.$order->BuyerEmailAddress;
			$thisOrder['Invoice']['ShippingTypeText']  = $ship_class;
			$item_total = 0;
			$num_items--;
			$order_item_count=0;
			$order_items=$mysqli->query("SELECT * FROM `__ca_order_items` WHERE OrderID=".$order->ID." ORDER BY `Sku` ASC");
			$num_items = $order_items->num_rows;
			while($order_item=$order_items->fetch_object())
			{
				$ca_products=$mysqli->query("SELECT * FROM __ca_products WHERE InventoryNumber=\"".$order_item->Sku."\"");
				$ca_product=$ca_products->fetch_object();
				$order_item_fulfillments=$mysqli->query("SELECT * FROM__ca_order_item_fulfillmentitems AS OIFI LEFT JOIN __ca_order_fulfillments AS OF  ON OIFI.FulfillmentID=OF.ID WHERE OIFI.OrderID=".$order->ID." AND OIFI.OrderItemID=".$order_item->ID." ORDER BY OF.ShippingClass ASC");
				switch($order->SiteName)
				{
					case 'Amazon Seller Central - US': 
						$line_value = ($order_item->Quantity * ($order_item->UnitPrice)) + $order_item->TaxPrice;
						break;
					default:
						$line_value = ($order_item->Quantity * ($order_item->UnitPrice));
						break;
				}
				$item_total += $line_value;
				$num_items--;
				switch($site_country_code)
				{
					case 'UK': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeUK.":£".$ca_product->ShippingCostUK."]"; break;
					case 'DE': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeDE.":£".$ca_product->ShippingCostDE."]"; break;
					case 'FR': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeFR.":£".$ca_product->ShippingCostFR."]"; break;
					case 'ES': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeES.":£".$ca_product->ShippingCostES."]"; break;
					case 'IT': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeIT.":£".$ca_product->ShippingCostIT."]"; break;
					case 'US': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeUS.":£".$ca_product->ShippingCostUS."]"; break;
					case 'CA': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeCA.":£".$ca_product->ShippingCostCA."]"; break;
					case 'MX': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeMX.":£".$ca_product->ShippingCostMX."]"; break;
					case 'AU': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeAU.":£".$ca_product->ShippingCostAU."]"; break;
					case 'NZ': $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'] = $order_item->Title.' ['.$ca_product->ShippingTypeNZ.":£".$ca_product->ShippingCostNZ."]"; break;
				}
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['Sku'                  ] = $order_item->Sku;
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['UnitPrice'            ] = CA_currency_format($order->SiteName, ($order_item->UnitPrice));
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['Quantity'             ] = $order_item->Quantity;
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['TaxPrice'             ] = CA_currency_format($order->SiteName, $order_item->TaxPrice);
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'            ] = CA_currency_format($order->SiteName, $line_value);
				$order_item_count++;
			}
			$thisOrder['Invoice']['OrderItemTotalText'] = CA_currency_format($order->SiteName, $item_total               );
			$thisOrder['Invoice']['TotalShippingPrice'] = CA_currency_format($order->SiteName, $order->TotalShippingPrice);
			switch($order->SiteName)
			{
				case 'Amazon Seller Central - US': 
				case 'Amazon UK': 
				case 'eBay Fixed Price UK':
				case 'Shop.com Marketplace':
					$thisOrder['Invoice']['TotalExTaxPrice'] = CA_currency_format($order->SiteName, $order->TotalPrice-$order->TotalTaxPrice);
					$thisOrder['Invoice']['TotalTaxPrice'  ] = CA_currency_format($order->SiteName, $order->TotalTaxPrice);
					$thisOrder['Invoice']['TotalPrice'     ] = CA_currency_format($order->SiteName, $order->TotalPrice);
					break;

				default: 
					$thisOrder['Invoice']['TotalExTaxPrice'] = CA_currency_format($order->SiteName, $order->TotalPrice-$order->TotalTaxPrice-$order->TotalTaxPrice);
					$thisOrder['Invoice']['TotalTaxPrice'  ] = CA_currency_format($order->SiteName, $order->TotalTaxPrice);
					$thisOrder['Invoice']['TotalPrice'     ] = CA_currency_format($order->SiteName, $order->TotalPrice-$order->TotalTaxPrice);
					break;
			}
			////////////////////////////////////////////////////////////////////////////////
			// PACKING SLIP
			////////////////////////////////////////////////////////////////////////////////
			$thisOrder['PackingSlip']['ShippingAddressText'] = ''.chr(0x0A).$shipping_address.chr(0x0A);
			$thisOrder['PackingSlip']['InfoText']            = ''.chr(0x0A).$order->SiteName.chr(0x0A).chr(0x0A).'Order Date'.chr(0x0A).$order->PaymentDateUtc.chr(0x0A).chr(0x0A).'Order ID'.chr(0x0A).$SiteOrderID.chr(0x0A).chr(0x0A).chr(0x0A).chr(0x0A).'';
			$item_total = 0;
			$num_items--;
			
			$order_items=$mysqli->query("SELECT * FROM `__ca_order_items` WHERE OrderID=".$order->ID." ORDER BY `Sku` ASC");
			$num_items = $order_items->num_rows;

			$OrderItemId=0;
			while($order_item=$order_items->fetch_object())
			{
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Sku'     ] = $order_item->Sku;
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Quantity'] = $order_item->Quantity;
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Title'   ] = $order_item->Title;
				$OrderItemId++;
			}
			return $thisOrder;
		}


		function CA_AddOrderToPDF($thisOrder)
		{
			$this->AddPage(); $this->SetFillColor(255,255,255); $this->SetTextColor(0,0,0); $this->SetFont('Times','',11);
			$this->MultiCell(190,7,$thisOrder['Invoice']['InvoiceInfoText'],1,'L',true);
			$this->Image($thisOrder['Invoice']['MarketTagsImage'],125,55,30);
			$this->Image($thisOrder['Invoice']['MarketNameImage'], 97,1,45);  
			$this->Image($thisOrder['Invoice']['MarketNameImage'], 157,49,20);  
			$this->Image($thisOrder['Invoice']['MarketCountryImage'],177,49,20);  $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont   ('Times','B',12); $this->Cell(95,10,'Sold to:',1,0,'L',true); $this->Cell(95,10,'Ship to:',1,1,'L',true); $this->SetFont   ('Times','',11);
			$this->MultiCell(95,6.5,$thisOrder['Invoice']['BillingAddressText'],1,'L',false);  $this->SetXY(105,79);
			$this->MultiCell(95,6.5,$thisOrder['Invoice']['ShippingAddressText'],1,'L',false);
			$this->Image($thisOrder['Invoice']['ShippingCountryFlagImage'],177,110,20);    $this->Cell(95,8,'Billing Telephone:',1,0,'L',true); $this->Cell(95,8,'Shipping Telephone:',1,1,'L',true); $this->SetFillColor(255,255,255);
			$this->Cell(95,8,$thisOrder['Invoice']['BillingTelephoneText'],1,0,'L',true);
			$this->Cell(95,8,$thisOrder['Invoice']['ShippingTelephoneText'],1,1,'L',true); $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Times','B',12); $this->Cell(125,10,'Payment Method: ',1,0,'L',true); $this->Cell(65,10,'Shipping Method:',1,1,'R',true); $this->SetFont('Times','',11);
			$this->MultiCell(125,6.5,$thisOrder['Invoice']['PaymentMethodText'],1,'L',false);  $this->SetXY(135,157); $this->SetFont   ('Times',(($thisOrder['Invoice']['ShippingTypeText']!="Standard")?'B':''),15);
			$this->Cell(65,13,$thisOrder['Invoice']['ShippingTypeText'],1,1,'R',false);        $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Times','B',10); $this->Cell(85, 10, 'Product Title',    1, 0, 'L', true); $this->Cell(51, 10, 'Inventory Number', 1, 0, 'L', true); $this->Cell(14, 10, 'Price',            1, 0, 'R', true); $this->Cell(10, 10, 'Qty',              1, 0, 'R', true); $this->Cell(14, 10, 'Tax',              1, 0, 'R', true); $this->Cell(16, 10, 'Subtotal',         1, 1, 'R', true);
			$order_item_count=0;
			while(isset($thisOrder['Invoice']['ProductLine'][$order_item_count]))
			{
				$x=$this->GetX(); $y=$this->GetY(); $this->SetTextColor(0,0,0); $this->SetFillColor(250,250,255); $this->SetFont   ('Times','',10);
				$this->MultiCell(85,5,  $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'], 1,'L',true);  $this->SetXY($x+85,$y); $this->SetFont   ('Times','',9);
				$this->Cell     (51,15, $thisOrder['Invoice']['ProductLine'][$order_item_count]['Sku'                  ], 1,0,'L',true);
				$this->Cell     (14,15, $thisOrder['Invoice']['ProductLine'][$order_item_count]['UnitPrice'            ], 1,0,'R',true);
				$this->Cell     (10,15, $thisOrder['Invoice']['ProductLine'][$order_item_count]['Quantity'             ], 1,0,'R',true);
				$this->Cell     (14,15, $thisOrder['Invoice']['ProductLine'][$order_item_count]['TaxPrice'             ], 1,0,'R',true);
				$this->Cell     (16,15, $thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'            ], 1,1,'R',true);
				if($order_item_count==2 || $order_item_count==10 || $order_item_count==21) { $this->SetXY($x,$y+20); $this->SetTextColor(0,0,0); $this->SetFillColor(255,255,255); $this->SetFont   ('Times','',16); $this->Cell(190,15,"continued...", 0,0,'R',true); $this->AddPage(); }
				else { $this->SetXY($x,$y+15); }
				$order_item_count++;
			}
																											$this->SetFont   ('Times','',10); $this->SetFillColor(230,230,240); $this->Cell(174,6,'Sub-total: ',1,0,'R',true);	
			$this->Cell(16,6,$thisOrder['Invoice']['OrderItemTotalText'], 1,1,'R',true); $this->SetFillColor(230,230,220); $this->Cell(174,6,'Shipping & Handling: ',     1,0,'R',true);	
			$this->Cell(16,6,$thisOrder['Invoice']['TotalShippingPrice'], 1,1,'R',true);
			                                                                                   $this->SetFillColor(230,230,240); $this->Cell(174,6,'Grand Total (Excl. Tax): ',       1,0,'R',true);	
			$this->Cell(16,6, $thisOrder['Invoice']['TotalExTaxPrice'], 1,1,'R',true);  $this->SetFillColor(230,230,220);                                                             $this->Cell(174,6,  'Tax: ',                     1,0,'R',true);
			$this->Cell(16,6, $thisOrder['Invoice']['TotalTaxPrice'  ], 1,1,'R',true);  $this->SetTextColor(255,255,255); $this->SetFont('Times','B',12); $this->SetFillColor(0,0,0); $this->Cell(174,10, 'Grand Total (Incl. Tax): ', 1,0,'R',true);
			$this->Cell(16,10,$thisOrder['Invoice']['TotalPrice'     ], 1,1,'R',true);  $this->SetFillColor(250,250,250);                                                             $this->Cell(190,8,  ' ', 1,1,'R',true); $this->Cell(190,8,  ' ', 1,1,'R',true); $this->Cell(190,8,  ' ', 1,1,'R',true); $this->Cell(190,8,  ' ', 1,1,'R',true);
			////////////////////////////////////////////////////////////////////////////////
			// PACKING SLIP
			////////////////////////////////////////////////////////////////////////////////
																									 $this->AddPage(); $this->SetXY(10,49); $this->SetTextColor(0,0,0); $this->SetFillColor(255,255,255);  $this->SetXY(10,50); $this->SetFont   ('Courier','B',13); 
			$this->MultiCell(110,7,$thisOrder['PackingSlip']['ShippingAddressText'],'TR','L',true);  if($thisOrder['Invoice']['MarketNameImage']=='https://sewing-online.com/ca-rest-api/images/markets/trademe.jpg' && time()>=1575115201) { $this->SetXY(10,114); $this->SetFont   ('Courier','B',9);  $this->MultiCell(110,6,'Trade Me Limited    GST number 072-491-386    GST PAID','TRL','C',true); $this->SetXY(70,90); } else { $this->SetXY(70,95); }
																									 $this->SetFont('Courier','',8);  $this->MultiCell(45,4,'SENDER:'.chr(0x0A).'GMI, Unit 9 Mallard Road'.chr(0x0A).'Victoria Business Park'.chr(0x0A).'Netherfield, Nottingham'.chr(0x0A).'NG4 2PE, United Kingdom',1,'L',true); $this->SetXY(120,50); $this->SetFont('Courier','B',11); 
			$this->MultiCell(80,6,$thisOrder['PackingSlip']['InfoText'],'T','R',false);              $this->ln(4.5); $this->SetFillColor(255,255,255); $this->SetTextColor(0,0,0); $this->SetFont('Courier','B',24); $this->Cell(0,15,'PACKING SLIP', 'T',1,'C',false); $this->ln(1); $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Courier','B',10); $this->Cell(80,10,'Inventory Number',1,0,'L',true); $this->Cell(10,10,'Qty',1,0,'C',true); $this->Cell(100,10,'Product Title',1,1,'L',true);
			$OrderItemId=0;
			while(isset($thisOrder['PackingSlip']['OrderItem'][$OrderItemId]))
			{
                                                                                                                          $this->SetFillColor(250,250,255); $this->SetTextColor(0,0,0); $this->SetFont('Courier','', 10); 
				$this->Cell     (80,10,$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Sku'     ],1,0,'L',true);
				$this->Cell     (10,10,$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Quantity'],1,0,'C',true);
				$this->MultiCell(100,5,$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Title'   ],1,1,'L',true);
				$OrderItemId++;
			}
		}


		function AddPicklistToPDF($picklist,$table_title,$action_title)
		{
			ksort($picklist);
			$this->skipHeader=true;
			$this->AddPage('L'); $this->SetFillColor(255,255,255); $this->SetTextColor(0,0,0); $this->SetFont('Arial','B',12);
			$this->Cell(275,8,$table_title.date('l d/m/Y A (H:i)'),1,0,'L',true);
			$this->ln(8);
			$this->SetFont('Arial','B',10);
			$this->Cell( 41,8,"Site Name",1,0,'L',true);
			$this->Cell( 36,8,"Site Order ID",1,0,'L',true);
			$this->Cell( 55,8,"Sku",1,0,'L',true);
			$this->Cell( 15,8,$action_title,1,0,'C',true);
			$this->Cell( 20,8,"FROM",1,0,'C',true);
			$this->Cell(108,8,"Title",1,0,'L',true);
			while($row=array_shift($picklist))
			{
				$this->ln(8);
				$this->SetFont('Arial','',9);
				$this->Cell( 41,8,$row['SiteName'] 			,1,0,'L',true);
				$this->Cell( 36,8,$row['SiteOrderID']		,1,0,'L',true);
				$this->Cell( 55,8,$row['Sku']				,1,0,'L',true);
				$this->Cell( 15,8,$row['Quantity']			,1,0,'C',true);
				$this->Cell( 20,8,$row['DistributionCentre'],1,0,'C',true);
				$this->SetFont('Arial','',7);
				$this->Cell(108,8,$row['Title']				,1,0,'L',true);
			}
			$this->skipHeader=false;
		}
		

		function WEB_PrepareOrder($order, $mysqli)
		{
			$thisOrder = array();
			$thisOrder['Invoice']['InvoiceInfoText']          = 'Invoice # '.$order->ID.chr(0x0A).'Order # '.$order->SiteOrderID.chr(0x0A).'Order Date: '.date("d M Y H:i:s",strtotime($order->PaymentDateUtc." UTC"));
			$thisOrder['Invoice']['MarketNameImage']          = 'https://sewing-online.com/ca-rest-api/images/markets/magento2.jpg';
			$thisOrder['Invoice']['MarketCountryImage']       = 'https://sewing-online.com/ca-rest-api/images/flags/gb.jpg';
			$thisOrder['Invoice']['BillingAddressText']       = WEB_address_text_format($order->BillingTitle,$order->BillingFirstName,$order->BillingLastName,$order->BillingSuffix,$order->BillingAddressLine1,$order->BillingAddressLine2,$order->BillingCity,$order->BillingCompanyJobTitle,$order->BillingCountryName,$order->BillingPostalCode,$order->BillingStateOrProvinceName);
			$thisOrder['Invoice']['ShippingAddressText']      = WEB_address_text_format($order->ShippingTitle,$order->ShippingFirstName,$order->ShippingLastName,$order->ShippingSuffix,$order->ShippingAddressLine1,$order->ShippingAddressLine2,$order->ShippingCity,$order->ShippingCompanyJobTitle,$order->ShippingCountryName,$order->ShippingPostalCode,$order->ShippingStateOrProvinceName);
			$thisOrder['Invoice']['BillingAddressText']       = $thisOrder['Invoice']['BillingAddressText']?$thisOrder['Invoice']['BillingAddressText']:$thisOrder['Invoice']['ShippingAddressText'];
			$thisOrder['Invoice']['ShippingCountryFlagImage'] = 'https://sewing-online.com/ca-rest-api/images/flags/'.(($order->ShippingCountryFlag!="gb.jpg") ? ($order->ShippingCountryFlag) : ('blank.jpg'));
			$thisOrder['Invoice']['BillingTelephoneText']     = WEB_telephone_text_format($order->BillingDaytimePhone,$order->BillingEveningPhone);
			$thisOrder['Invoice']['ShippingTelephoneText']    = WEB_telephone_text_format($order->ShippingDaytimePhone,$order->ShippingEveningPhone);
			$thisOrder['Invoice']['PaymentMethodText']        = $order->PaymentMethod;
			$thisOrder['Invoice']['ShippingTypeText']         = "Standard";
			$OrderItemTotalText=0; $order_item_count=0;
			$order_items=$mysqli->query("SELECT product_type, sku AS Sku, item_id AS ID, base_price AS UnitPrice, qty_ordered AS Quantity, name AS Title, (base_price/6) AS TaxPrice FROM sales_order_item WHERE base_price>0 AND order_id=".$order->ID." ORDER BY `Sku` ASC");
			while($order_item=$order_items->fetch_object())
			{
				if($order_item->product_type=="configurable")
				{
					$simple_items=$mysqli->query("SELECT name AS Title FROM sales_order_item WHERE order_id=".$order->ID." AND parent_item_id=".$order_item->ID." ORDER BY `Sku` ASC");
					$simple_item=$simple_items->fetch_object();
					if($simple_item->Title!="") $order_item->Title=$simple_item->Title;
				}
				$order_item->Quantity = (int)$order_item->Quantity;
				$ca_products=$mysqli->query("SELECT * FROM __ca_products WHERE InventoryNumber=\"".$order_item->Sku."\"");
				$ca_product=$ca_products->fetch_object();
				switch($order->ShippingCountryNameCode)
				{
					case 'GB':   
					case 'UK': $ShippingType=$ca_product->ShippingTypeUK; $ShippingCost=$ca_product->ShippingCostUK; break;
					case 'DE': $ShippingType=$ca_product->ShippingTypeDE; $ShippingCost=$ca_product->ShippingCostDE; break;
					case 'FR': $ShippingType=$ca_product->ShippingTypeFR; $ShippingCost=$ca_product->ShippingCostFR; break;
					case 'ES': $ShippingType=$ca_product->ShippingTypeES; $ShippingCost=$ca_product->ShippingCostES; break;
					case 'IT': $ShippingType=$ca_product->ShippingTypeIT; $ShippingCost=$ca_product->ShippingCostIT; break;
					case 'US': $ShippingType=$ca_product->ShippingTypeUS; $ShippingCost=$ca_product->ShippingCostUS; break;
					case 'CA': $ShippingType=$ca_product->ShippingTypeCA; $ShippingCost=$ca_product->ShippingCostCA; break;
					case 'MX': $ShippingType=$ca_product->ShippingTypeMX; $ShippingCost=$ca_product->ShippingCostMX; break;
					case 'AU': $ShippingType=$ca_product->ShippingTypeAU; $ShippingCost=$ca_product->ShippingCostAU; break;
					case 'NZ': $ShippingType=$ca_product->ShippingTypeNZ; $ShippingCost=$ca_product->ShippingCostNZ; break;
				}
				switch($order->ShippingCountryNameCode)
				{
					case 'GB': case 'UK': case 'DE': case 'FR': case 'ES': case 'IT': case 'US': case 'CA': case 'MX': case 'AU': case 'NZ':
						$ProductShippingInfoText = ' ['.(($ShippingType && $ShippingCost)?"":"!!CHECK!! ").$ShippingType.":£".$ShippingCost."]";
						break;
					default:
						$__ca_country_codes=$mysqli->query("SELECT approx_ship_country FROM __ca_country_codes WHERE country_code='".$order->ShippingCountryNameCode."'");
						$__ca_country_code=$__ca_country_codes->fetch_object();
						switch($__ca_country_code->approx_ship_country) {
							case 'UK': case 'DE': case 'FR': case 'ES': case 'IT': case 'US': case 'CA': case 'MX': case 'AU': case 'NZ':
								$ProductShippingInfoText = ' [!!CHECK!! '.$ShippingType.":£".$ShippingCost."]";
								break;
						}
						break;
				}
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'            ]  = ($order_item->Quantity * ($order_item->UnitPrice));
				$thisOrder['Invoice']['OrderItemTotalText'] += $thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'];
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText']  = $order_item->Title.$ProductShippingInfoText;
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['Sku'                  ]  = $order_item->Sku;
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['UnitPrice'            ]  = WEB_currency_format($order_item->UnitPrice);
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['Quantity'             ]  = $order_item->Quantity;
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['TaxPrice'             ]  = WEB_currency_format($order_item->TaxPrice);
				$thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'            ]  = WEB_currency_format($thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText']);

				$order_item_count++;
			}
			$thisOrder['Invoice']['OrderItemTotalText'] = WEB_currency_format($thisOrder['Invoice']['OrderItemTotalText']);
			$thisOrder['Invoice']['TotalShippingPrice'] = WEB_currency_format($order->TotalShippingPrice);
			$thisOrder['Invoice']['CouponText'        ] = ($order->Discount<0)?('Discount ('.$order->Coupon.'): '):('');
			$thisOrder['Invoice']['Discount'          ] = ($order->Discount<0)?("-".WEB_currency_format(-$order->Discount)):('');
			$thisOrder['Invoice']['TotalExTaxPrice'   ] = WEB_currency_format($order->TotalPrice-$order->TotalTaxPrice);
			$thisOrder['Invoice']['TotalTaxPrice'     ] = WEB_currency_format($order->TotalTaxPrice);
			$thisOrder['Invoice']['TotalPrice'        ] = WEB_currency_format($order->TotalPrice);
			////////////////////////////////////////////////////////////////////////////////
			// PACKING SLIP
			////////////////////////////////////////////////////////////////////////////////
			$thisOrder['PackingSlip']['InfoText'] = chr(0x0A).'Web UK'.chr(0x0A).chr(0x0A).'Order Date'.chr(0x0A).$order->PaymentDateUtc.chr(0x0A).chr(0x0A).'Order ID'.chr(0x0A).$order->SiteOrderID.chr(0x0A).chr(0x0A).chr(0x0A).chr(0x0A);
			$thisOrder['PackingSlip']['ShippingAddressText'] = chr(0x0A).$thisOrder['Invoice']['ShippingAddressText'].chr(0x0A);
			$order_items=$mysqli->query("SELECT product_type, sku AS Sku, item_id AS ID, base_price AS UnitPrice, qty_ordered AS Quantity, name AS Title, (base_price/6) AS TaxPrice FROM sales_order_item WHERE base_price>0 AND order_id=".$order->ID." ORDER BY `Sku` ASC");
			$OrderItemId=0;
			while($order_item=$order_items->fetch_object())
			{
				if($order_item->product_type=="configurable")
				{
					$simple_items=$mysqli->query("SELECT name AS Title FROM sales_order_item WHERE order_id=".$order->ID." AND parent_item_id=".$order_item->ID." ORDER BY `Sku` ASC");
					$simple_item=$simple_items->fetch_object();
					if($simple_item->Title!="") $order_item->Title=$simple_item->Title;
				}

				$order_item->Quantity = (int)$order_item->Quantity;
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Sku'     ] = $order_item->Sku;
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Quantity'] = $order_item->Quantity;
				$thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Title'   ] = $order_item->Title;
				$OrderItemId++;
			}
			return $thisOrder;
		}


		function WEB_AddOrderToPDF($thisOrder)
		{
			                                                                                              $this->AddPage(); $this->SetFillColor(255,255,255); $this->SetTextColor(0,0,0); $this->SetFont('Times','',11);
			$this->MultiCell(190,7,   $thisOrder['Invoice']['InvoiceInfoText'],          1,  'L',true );        
			$this->Image    (         $thisOrder['Invoice']['MarketNameImage'],          97,1,45      );        
			$this->Image    (         $thisOrder['Invoice']['MarketNameImage'],          157,49,20    );        
			$this->Image    (         $thisOrder['Invoice']['MarketCountryImage'],       177,49,20    );  $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Times','B',12); $this->Cell(95,10,'Sold to:',1,0,'L',true); $this->Cell(95,10,'Ship to:',1,1,'L',true); $this->SetFont('Times','',11);
			$this->MultiCell(95,6.5,  $thisOrder['Invoice']['BillingAddressText'],       1,  'L',false);  $this->SetXY(105,79);
			$this->MultiCell(95,6.5,  $thisOrder['Invoice']['ShippingAddressText'],      1,  'L',false);  
			$this->Image    (         $thisOrder['Invoice']['ShippingCountryFlagImage'], 177,110,20   );  $this->Cell(95,8,'Billing Telephone:',1,0,'L',true); $this->Cell(95,8,'Shipping Telephone:',1,1,'L',true); $this->SetFillColor(255,255,255);
			$this->Cell     (95,8,    $thisOrder['Invoice']['BillingTelephoneText'],     1,0,'L',true );  
			$this->Cell     (95,8,    $thisOrder['Invoice']['ShippingTelephoneText'],    1,1,'L',true );  $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Times','B',12); $this->Cell(125,10,'Payment Method: ',1,0,'L',true); $this->Cell(65,10,'Shipping Method:',1,1,'R',true); $this->SetFont('Times','',11);
			$this->MultiCell(125,6.5, $thisOrder['Invoice']['PaymentMethodText'],        1,  'L',false);  $this->SetXY(135,157); $this->SetFont('Times','',15);
			$this->Cell     (65,13,   $thisOrder['Invoice']['ShippingTypeText'],         1,1,'R',false);  $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Times','B',10); $this->Cell(85,10,'Product Title',1,0,'L',true); $this->Cell(51,10,'Inventory Number',1,0,'L',true); $this->Cell(14,10,'Price',1,0,'R',true); $this->Cell(10,10,'Qty',1,0,'R',true); $this->Cell(14,10,'Tax',1,0,'R',true); $this->Cell(16,10,'Subtotal',1,1,'R',true);
			$order_item_count=0;
			while(isset($thisOrder['Invoice']['ProductLine'][$order_item_count]))
			{
				$x=$this->GetX(); $y=$this->GetY(); 
				                                                                                                                             $this->SetTextColor(0,0,0); $this->SetFillColor(250,250,255); $this->SetFont   ('Times','',10);
				$this->MultiCell(85,5,  $thisOrder['Invoice']['ProductLine'][$order_item_count]['TitleShippingInfoText'], 1,    'L', true);  $this->SetXY($x+85,$y); $this->SetFont   ('Times','',9);
				$this->Cell     (51,20, $order_item_count.") ".$thisOrder['Invoice']['ProductLine'][$order_item_count]['Sku'                  ], 1, 0, 'L', true);
				$this->Cell     (14,20, $thisOrder['Invoice']['ProductLine'][$order_item_count]['UnitPrice'            ], 1, 0, 'R', true);
				$this->Cell     (10,20, $thisOrder['Invoice']['ProductLine'][$order_item_count]['Quantity'             ], 1, 0, 'R', true);
				$this->Cell     (14,20, $thisOrder['Invoice']['ProductLine'][$order_item_count]['TaxPrice'             ], 1, 0, 'R', true);
				$this->Cell     (16,20, $thisOrder['Invoice']['ProductLine'][$order_item_count]['ValueText'            ], 1, 1, 'R', true);  if($order_item_count==2 || $order_item_count==10 || $order_item_count==21) { $this->SetXY($x,$y+25); $this->SetTextColor(0,0,0); $this->SetFillColor(255,255,255); $this->SetFont   ('Times','',16); $this->Cell(190,20,"continued...", 0,0,'R',true); $this->AddPage(); } else { $this->SetXY($x,$y+20); }
				$order_item_count++;
			}
		                                                                                       $this->SetFont   ('Times','',10); $this->SetFillColor(230,230,240); $this->Cell(174,6,'Sub-total: ',1,0,'R',true);
			$this->Cell(16,6,    $thisOrder['Invoice']['OrderItemTotalText'], 1,1,'R',true);   $this->SetFillColor(230,230,220); $this->Cell(174,6,'Shipping & Handling: ',           1,0,'R',true);	
			$this->Cell(16,6,    $thisOrder['Invoice']['TotalShippingPrice'], 1,1,'R',true);   $this->SetFillColor(230,230,240);
			if($thisOrder['Invoice']['CouponText']<>'' || $thisOrder['Invoice']['Discount']<>'')
			{
				$this->Cell(174,6,   $thisOrder['Invoice']['CouponText'],         1,0,'R',true);	
				$this->Cell(16,6,    $thisOrder['Invoice']['Discount'],           1,1,'R',true);   
			}
			                                                                                   $this->SetFillColor(230,230,240); $this->Cell(174,6,'Grand Total (Excl. Tax): ',       1,0,'R',true);	
			$this->Cell(16,6,    $thisOrder['Invoice']['TotalExTaxPrice'],    1,1,'R',true);   $this->SetFillColor(230,230,220); $this->Cell(174,6,'Tax: ',                           1,0,'R',true);	
			$this->Cell(16,6,    $thisOrder['Invoice']['TotalTaxPrice'],      1,1,'R',true);   $this->SetTextColor(255,255,255); $this->SetFont   ('Times','B',12); $this->SetFillColor(  0,  0,  0); $this->Cell(174,10,'Grand Total (Incl. Tax): ',      1,0,'R',true);	
			$this->Cell(16,10,   $thisOrder['Invoice']['TotalPrice'],         1,1,'R',true);   

			////////////////////////////////////////////////////////////////////////////////
			// PACKING SLIP
			////////////////////////////////////////////////////////////////////////////////
			                                                                                             $this->AddPage(); $this->SetXY(10,49); $this->SetTextColor(0,0,0); $this->SetFillColor(255,255,255); $this->SetXY(10,50); $this->SetFont   ('Courier','B',13); 
			$this->MultiCell(110,7,  $thisOrder['PackingSlip']['ShippingAddressText'], 'TR','L',true );  $this->SetXY(70,95); $this->SetFont   ('Courier','',8); $this->MultiCell(45,4,'SENDER:'.chr(0x0A).'GMI, Unit 9 Mallard Road'.chr(0x0A).'Victoria Business Park'.chr(0x0A).'Netherfield, Nottingham'.chr(0x0A).'NG4 2PE, United Kingdom',1,'L',true); $this->SetXY(120,50); $this->SetFont('Courier','B',11); 
			$this->MultiCell(80,6,   $thisOrder['PackingSlip']['InfoText'],            'T', 'R',false);  $this->ln(4.5); $this->SetFillColor(255,255,255); $this->SetTextColor(0,0,0); $this->SetFont('Courier','B',24); $this->Cell(0,15,'PACKING SLIP', 'T',1,'C',false); $this->ln(1); $this->SetFillColor(220,220,230); $this->SetTextColor(0,0,0); $this->SetFont('Courier','B',10); $this->Cell(80,10,'Inventory Number',1,0,'L',true); $this->Cell(10,10,'Qty',1,0,'C',true); $this->Cell(100,10,'Product Title',1,1,'L',true);

			$OrderItemId=0;
			while(isset($thisOrder['PackingSlip']['OrderItem'][$OrderItemId]))
			{
                                                                                                                          $this->SetFillColor(250,250,255); $this->SetTextColor(0,0,0); $this->SetFont('Courier','', 10); 
				$this->Cell(80,15,      $thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Sku'     ], 1,0,'L',true);
				$this->Cell(10,15,      $thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Quantity'], 1,0,'C',true);
				$this->MultiCell(100,5, $thisOrder['PackingSlip']['OrderItem'][$OrderItemId]['Title'   ], 1,1,'L',true);  $this->ln(5);
				$OrderItemId++;
			}
		}


		// Page footer
		function Footer() { 
			$this->SetY(-15); $this->SetTextColor(200,200,200); $this->SetFont('Helvetica','I',8); $this->Cell(0,10,$this->PageNo(),0,0,'C'); 
		}
		
		function MultiCell ($w, $h, $txt, $border=0, $align='J', $fill=false                     ) { parent::MultiCell($w, $h,         $this->normalize($txt), $border,      $align, $fill       ); }
		function Cell      ($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='') { parent::Cell     ($w, $h,         $this->normalize($txt), $border, $ln, $align, $fill, $link); }
		function Write     ($h, $txt, $link=''                                                   ) { parent::Write    (    $h,         $this->normalize($txt),                              $link); }
		function Text      ($x, $y, $txt                                                         ) { parent::Text     (        $x, $y, $this->normalize($txt)                                    ); }
		protected function normalize($word)
		{
			$word = str_replace(Array("€",		"@",   "`",   "¢",   "£",   "¥",   "|",   "«",   "¬",   "¯",   "º",   "±",   "ª",   "µ",   "»",   "¼",   "½",   "¿",   "À",   "Á",   "Â",   "Ã",   "Ä",   "Å",   "Æ",   "Ç",   "È",   "É",   "Ê",   "Ë",   "Ì",   "Í",   "Î",   "Ï",   "Ð",   "Ñ",   "Ò",   "Ó",   "Ô",   "Õ",   "Ö",   "Ø",   "Ù",   "Ú",   "Û",   "Ü",   "Ý",   "Þ",   "ß",   "à",   "á",   "â",   "ã",   "ä",   "å",   "æ",   "ç",   "è",   "é",   "ê",   "ë",   "ì",   "í",   "î",   "ï",   "ð",   "ñ",   "ò",   "ó",   "ô",   "õ",   "ö",   "÷",   "ø",   "ù",   "ú",   "û",   "ü",   "ý",   "þ",   "ÿ"),
								Array(chr(128),	"%40", "%60", "%A2", "%A3", "%A5", "%A6", "%AB", "%AC", "%AD", "%B0", "%B1", "%B2", "%B5", "%BB", "%BC", "%BD", "%BF", "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7", "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF"),
								$word);
			return urldecode($word);
		}	

	}
?>
<?php
	############################################################################
	# BUILD AN ARRAY OF THE NEXT BATCH OF WEBSITE ORDERS TO BE PRINTED
	############################################################################
	$magento_sales=array();
	$WEB_picklist=array('PICK'=>array(),'ORDER'=>array(),'FAILED'=>array());
	$_GET['WEB_orderIDs']="-99999"; 
	if(date('a')!='pm') // No Website orders in the afternoon!
	{
		$magento_sale_ids = $mysqli->query("SELECT DISTINCT entity_id FROM sales_order AS SO LEFT JOIN sales_order_item AS SOI ON SOI.order_id=SO.entity_id LEFT JOIN __andy_printed_orders AS APO ON SO.entity_id=APO.ix WHERE APO.ix IS NULL        AND SOI.price > 0        AND  SO.base_total_paid IS NOT NULL  ORDER BY SO.entity_id ASC LIMIT 0,50");
		while($magento_sale_id=$magento_sale_ids->fetch_object()) $_GET['WEB_orderIDs'] .= (",".$magento_sale_id->entity_id);
		$magento_sales_result = $mysqli->query("SELECT SO.entity_id, SO.updated_at, SOI.sku, 'WEB SALE' AS adj_type, -(SOI.qty_ordered) AS qty_ordered, SO.increment_id, SOI.name FROM sales_order AS SO LEFT JOIN sales_order_item AS SOI ON SOI.order_id=SO.entity_id WHERE SO.entity_id IN (".$_GET['WEB_orderIDs'].") AND  SOI.price > 0 ORDER BY SO.entity_id ASC");
		while($magento_sale=$magento_sales_result->fetch_object()) $magento_sales[] = $magento_sale;
		if(count($magento_sales)>0)
		{
			$G_DISTRIBUTION_CENTRES = getDistributionCentresFromChannelAdvisor();
			$ca_stock_info = getStockLevelsForMagentoSalesFromChannelAdvisor($magento_sales);

			foreach($magento_sales AS $key => $magento_sale)
			{
				$qty = -$magento_sales[$key]->qty_ordered;
				if      ($ca_stock_info[$magento_sale->sku]['GMI']['total']      >= $qty) { $magento_sales[$key]->action = "PICK";   $ca_stock_info[$magento_sale->sku]['GMI']['total' ] -= $qty; $ca_stock_info[$magento_sale->sku]['GMI']['picked'] += $qty; }
				else if ($ca_stock_info[$magento_sale->sku]['SUPPLIER']['total'] >= $qty) { $magento_sales[$key]->action = "ORDER";  $ca_stock_info[$magento_sale->sku]['SUPPLIER']['total'  ] -= $qty; $ca_stock_info[$magento_sale->sku]['SUPPLIER']['ordered'] += $qty; }
				else                                                                      { $magento_sales[$key]->action = "FAILED"; $ca_stock_info[$magento_sale->sku]['GMI']['failed'] += $qty; }
				$magento_sales[$key]->stock_info = $ca_stock_info[$magento_sale->sku];
			}
			foreach($magento_sales AS $magento_sale)
			{
				$ca_dc_name_to_use="";
				foreach($magento_sale->stock_info['GMI'] AS $ca_dc_name => $ca_dc_qty)
				{
					if($ca_dc_name=="total" || $ca_dc_name=="picked" || $ca_dc_name=="ordered") continue;
					$ca_dc_name_to_use=$ca_dc_name;
					break;
				}
				$_POST_sku[]        = $magento_sale->sku;
				$_POST_ca_prod_id[] = $magento_sale->stock_info['ca_product_id'];
				$_POST_qty[]        = -$magento_sale->qty_ordered;
				$_POST_ca_dc_id[]   = $G_DISTRIBUTION_CENTRES['REVERSE'][$ca_dc_name_to_use];
				switch($magento_sale->action)
				{
					case "PICK"   : $distribution_center = "STOCK"; break;
					case "ORDER"  : $distribution_center = explode("_",$magento_sale->sku); $distribution_center = $distribution_center['0']; break;
					default       : $distribution_center = "OOS?"; break;
				}
				$title = $magento_sale->name;
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['SiteName'          ] = "WEBSITE";
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['SiteOrderID'       ] = $magento_sale->increment_id;
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['Sku'               ] = $magento_sale->sku;
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['Quantity'          ] = (-$magento_sale->qty_ordered);
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['DistributionCentre'] = $distribution_center;
				$WEB_picklist[$magento_sale->action][$distribution_center."::".$magento_sale->sku."::".$magento_sale->entity_id]['Title'             ] = $magento_sale->name;
			}
		}
	}
	############################################################################
	# pre_print_r($_POST_sku       );
	# pre_print_r($_POST_ca_prod_id);
	# pre_print_r($_POST_qty       );
	# pre_print_r($_POST_ca_dc_id  );
	# exit();
	# pre_print_r("WEB_picklist");
	# pre_print_r($WEB_picklist);
	# pre_print_r("WEB_orderIDs");
	# pre_print_r($_GET['WEB_orderIDs']);
	# exit();
	############################################################################


	############################################################################
	# BUILD AN ARRAY OF THE NEXT BATCH OF CHANNEL ADVISOR ORDERS TO BE PRINTED
	############################################################################
	$CA_picklist=array('PICK'=>array(),'ORDER'=>array(),'FAILED'=>array());
	$_GET['CA_orderIDs']="-99999"; 
	$ca_sale_ids = $mysqli->query("SELECT CAO.ID FROM __ca_orders AS CAO WHERE CAO.DistributionCenterTypeRollup = 'SellerManaged' AND CAO.FlagDescription LIKE '' ORDER BY CAO.PaymentDateUtc DESC LIMIT 0,20000");
	while($ca_sale_id=$ca_sale_ids->fetch_object()) $_GET['CA_orderIDs'] .= (",".$ca_sale_id->ID);
	$order_sql  = "SELECT CAO.*, CACC1.country_name AS ShippingCountryName, CACC1.flag AS ShippingCountryFlag, CACC2.country_name AS BillingCountryName, CACC2.flag AS BillingCountryFlag FROM __ca_orders AS CAO LEFT JOIN __ca_country_codes AS CACC1 ON CAO.ShippingCountry = CACC1.country_code LEFT JOIN __ca_country_codes AS CACC2 ON CAO.BillingCountry  = CACC2.country_code ";
	$order_sql .= "WHERE CAO.ID IN (".$_GET['CA_orderIDs'].") ";
	$order_sql .= "ORDER BY CAO.ShippingCountry, CAO.SiteName, CAO.PaymentDateUtc ASC ";

	$_GET['CA_orderIDs']="-99999"; 
	$orders=$mysqli->query($order_sql);
	while($order=$orders->fetch_object())
	{
		if(date('a')=='pm') // Only Expedited orders in the afternoon!
		{
			$skip=FALSE;
			$order_items=$mysqli->query("SELECT * FROM `__ca_order_items` WHERE OrderID=".$order->ID." ORDER BY `Sku` ASC");
			$num_items = $order_items->num_rows;
			$order_item=$order_items->fetch_object();
			$order_item_fulfillment_sql = "SELECT * FROM __ca_order_item_fulfillmentitems AS OIFI LEFT JOIN __ca_order_fulfillments AS OF ON OIFI.FulfillmentID=OF.ID WHERE OIFI.OrderID=".$order->ID." AND OIFI.OrderItemID=".$order_item->ID." ORDER BY OF.ShippingClass ASC";
			$order_item_fulfillments=$mysqli->query($order_item_fulfillment_sql);
			$num_order_item_fulfillments = $order_item_fulfillments->num_rows;
			while($order_item_fulfillment=$order_item_fulfillments->fetch_object())
			{
				if( strstr($order_item_fulfillment->ShippingClass, "Overnight")===FALSE AND 
					strstr($order_item_fulfillment->ShippingClass, "Expedited")===FALSE AND
					strstr($order_item_fulfillment->ShippingClass, "NextDay"  )===FALSE AND
					strstr($order_item_fulfillment->ShippingClass, "SecondDay")===FALSE )
				{
					$skip=TRUE; break;	 
				}  
			}
			if($skip==TRUE) continue;
		}
		
		$_GET['CA_orderIDs'] .= (",".$order->ID);
		
		$order_items=$mysqli->query("SELECT * FROM `__ca_order_items` WHERE OrderID=".$order->ID." ORDER BY `Sku` ASC");
		while($order_item=$order_items->fetch_object())
		{
			$order_item_fulfillments=$mysqli->query("
				SELECT  *
				FROM       __ca_order_item_fulfillmentitems AS OIFI
				LEFT JOIN  __ca_order_fulfillments     AS OF  ON OIFI.FulfillmentID=OF.ID
				WHERE OIFI.OrderID=".$order->ID." AND OIFI.OrderItemID=".$order_item->ID."
				ORDER BY OF.ShippingClass ASC");
			while($order_item_fulfillment=$order_item_fulfillments->fetch_object())
			{
				$SiteOrderID    = (strpos($order->SiteName,"eBay")===0 ? $order->SecondarySiteOrderID : $order->SiteOrderID);
				
				switch($distribution_centres[$order_item_fulfillment->DistributionCenterID])
				{
					case 'STOCK' : $dc="PICK"; break;
					default      : $dc="ORDER"; break;
				}
				$products=$mysqli->query("SELECT AuctionTitle FROM __ca_products WHERE InventoryNumber=\"".$order_item->Sku."\""); $product=$products->fetch_object();
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['SiteName'          ] =  $order->SiteName.((strstr($order_item_fulfillment->ShippingClass, "Prime")!==FALSE)?" <Prime>":"");
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['SiteOrderID'       ] =  $SiteOrderID;
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['Sku'               ] =  $order_item->Sku;
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['Quantity'          ] += $order_item_fulfillment->Quantity;
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['DistributionCentre'] =  $distribution_centres[$order_item_fulfillment->DistributionCenterID];
				$CA_picklist[$dc][$distribution_centres[$order_item_fulfillment->DistributionCenterID]."::".$order_item->Sku.'::'.$order->ID]['Title'             ] =  $product->AuctionTitle;
			}
		}
	}
	############################################################################
	# pre_print_r("CA_picklist");
	# pre_print_r($CA_picklist);
	# pre_print_r("CA_orderIDs");
	# pre_print_r($_GET['CA_orderIDs']);
	# exit();
	############################################################################


	############################################################################
	# START A NEW PDF DOCUMENT
	############################################################################
	$pdf = new InvoicePDF();
	$pdf->AliasNbPages();
	############################################################################


	############################################################################
	# SHOW PICKLISTS...
	############################################################################
	if(date('l')!='Monday' || date('a')!='am') // !!!!!NEEDS TO ALSO DETECT BANK HOLIDAY WEEKENDS!!!!!
	{
		########################################################################
		# SHOW PICKLISTS FOR ALL ORDERS...
		########################################################################
		$merged_picklists['PICK'    ] = array_merge($CA_picklist['PICK'   ],$WEB_picklist['PICK'  ]);
		$merged_picklists['ORDER'   ] = array_merge($CA_picklist['ORDER'  ],$WEB_picklist['ORDER' ]);
		$merged_picklists['FAILED'  ] = array_merge($CA_picklist['FAILED'  ],$WEB_picklist['FAILED' ]);

		if(count($merged_picklists['PICK'  ])) $pdf->AddPicklistToPDF($merged_picklists['PICK'  ],"ALL ORDERS FROM STOCK. "    , "PICK" );
		if(count($merged_picklists['ORDER' ])) $pdf->AddPicklistToPDF($merged_picklists['ORDER' ],"ALL ORDERS FROM SUPPLIER. " , "ORDER");
		if(count($merged_picklists['FAILED'])) $pdf->AddPicklistToPDF($merged_picklists['FAILED'],"ALL ORDERS OUT OF STOCK! "  , "OOS!" );
		########################################################################
		# pre_print_r("merged_picklists");
		# pre_print_r($merged_picklists);
		# exit();
		########################################################################
	}
	else
	{
		########################################################################
		# SHOW PICKLISTS FOR CHANNEL ADVISOR ORDERS...
		########################################################################
		if(count($CA_picklist['PICK'  ])) $pdf->AddPicklistToPDF($CA_picklist['PICK'  ],"CHANNEL ADVISOR FROM STOCK. "    , "PICK" );
		if(count($CA_picklist['ORDER' ])) $pdf->AddPicklistToPDF($CA_picklist['ORDER' ],"CHANNEL ADVISOR FROM SUPPLIER. " , "ORDER");
		if(count($CA_picklist['FAILED'])) $pdf->AddPicklistToPDF($CA_picklist['FAILED'],"CHANNEL ADVISOR OUT OF STOCK! "  , "OOS!" );
		########################################################################

		########################################################################
		# SHOW PICKLISTS FOR WEBSITE ORDERS...
		########################################################################
		if(count($WEB_picklist['PICK'  ])) $pdf->AddPicklistToPDF($WEB_picklist['PICK'  ],"SEWING ONLINE FROM STOCK. "    , "PICK" );
		if(count($WEB_picklist['ORDER' ])) $pdf->AddPicklistToPDF($WEB_picklist['ORDER' ],"SEWING ONLINE FROM SUPPLIER. " , "ORDER");
		if(count($WEB_picklist['FAILED'])) $pdf->AddPicklistToPDF($WEB_picklist['FAILED'],"SEWING ONLINE OUT OF STOCK! "  , "OOS!" );
		########################################################################
	}
	############################################################################


	############################################################################
	# SHOW INVOICES AND PACKING SLIPS FOR CHANNEL ADVISOR ORDERS
	############################################################################
	$order_sql  = "SELECT CAO.*, CACC1.country_name AS ShippingCountryName, CACC1.flag AS ShippingCountryFlag, CACC2.country_name AS BillingCountryName, CACC2.flag AS BillingCountryFlag FROM __ca_orders AS CAO LEFT JOIN __ca_country_codes AS CACC1 ON CAO.ShippingCountry = CACC1.country_code LEFT JOIN __ca_country_codes AS CACC2 ON CAO.BillingCountry  = CACC2.country_code WHERE CAO.ID IN (".$_GET['CA_orderIDs'].") ORDER BY CAO.ShippingCountry, CAO.SiteName, CAO.PaymentDateUtc ASC ";
	$orders=$mysqli->query($order_sql);
	$num_orders = $orders->num_rows;
	$orderArray=array();
	while($order=$orders->fetch_object()) $orderArray[] = $pdf->CA_PrepareOrder($order,$mysqli);
	while($order=array_shift($orderArray)) $pdf->CA_AddOrderToPDF($order);
	############################################################################


	############################################################################
	# SHOW INVOICES AND PACKING SLIPS FOR WEBSITE ORDERS
	############################################################################
	$order_sql  = "SELECT SO.entity_id AS ID, SO.created_at AS PaymentDateUtc, SOP.method AS PaymentMethod, NULL AS SecondarySiteOrderID, SO.increment_id AS SiteOrderID, SO.base_grand_total AS TotalPrice, SO.coupon_code AS Coupon, SO.base_discount_amount AS Discount, SO.base_shipping_amount AS TotalShippingPrice, ((SO.base_grand_total + SO.base_shipping_amount + SO.base_discount_amount)/6) AS TotalTaxPrice, SO.customer_email AS BuyerEmailAddress, SO.customer_email AS BuyerUserId, SOAb.street      AS BillingAddressLine1, NULL             AS BillingAddressLine2, SOAb.city        AS BillingCity, NULL             AS BillingCompanyJobTitle, SOAb.company     AS BillingCompanyName, SOAb.telephone   AS BillingDaytimePhone, NULL             AS BillingEveningPhone, SOAb.firstname   AS BillingFirstName, SOAb.lastname    AS BillingLastName, SOAb.postcode    AS BillingPostalCode, SOAb.region      AS BillingStateOrProvinceName, SOAb.suffix      AS BillingSuffix, SOAb.prefix      AS BillingTitle, SOAs.street      AS ShippingAddressLine1, NULL             AS ShippingAddressLine2, SOAs.city        AS ShippingCity, NULL             AS ShippingCompanyJobTitle, SOAs.company     AS ShippingCompanyName, SOAs.telephone   AS ShippingDaytimePhone, NULL             AS ShippingEveningPhone, SOAs.firstname   AS ShippingFirstName, SOAs.lastname    AS ShippingLastName, SOAs.postcode    AS ShippingPostalCode, SOAs.region      AS ShippingStateOrProvinceName, SOAs.suffix      AS ShippingSuffix, SOAs.prefix      AS ShippingTitle, CACC1.country_name AS ShippingCountryName,  CACC1.flag AS ShippingCountryFlag,  CACC2.country_name AS BillingCountryName,  CACC2.flag AS BillingCountryFlag, SOAs.country_id AS ShippingCountryNameCode FROM  sales_order AS SO  LEFT JOIN sales_order_payment AS SOP ON SO.entity_id=SOP.parent_id LEFT JOIN sales_order_address AS SOAb ON SO.billing_address_id=SOAb.entity_id LEFT JOIN sales_order_address AS SOAs ON SO.shipping_address_id=SOAs.entity_id LEFT JOIN __ca_country_codes AS CACC1 ON SOAs.country_id = CACC1.country_code LEFT JOIN __ca_country_codes AS CACC2 ON SOAb.country_id = CACC2.country_code  WHERE SO.entity_id IN (".$_GET['WEB_orderIDs'].")  ORDER BY SOAs.country_id, SO.created_at DESC";
	$orders=$mysqli->query($order_sql);
	$num_orders = $orders->num_rows;
	$orderArray=array();
	while($order=$orders->fetch_object()) $orderArray[] = $pdf->WEB_PrepareOrder($order,$mysqli);
	while($order=array_shift($orderArray)) $pdf->WEB_AddOrderToPDF($order);
	############################################################################


	############################################################################
	# SEND THE PDF TO BROWSER
	############################################################################
	$pdf->Output();
	############################################################################
?>
<?php
	if(!isset($_GET['NOPRINT']))
	{
		############################################################################
		# DEAL WITH THE CHANNEL ADVISOR ORDERS CONFIRMED AS PRINTED!!!
		############################################################################
		if(isset($_GET['CA_orderIDs']) && is_array($_GET['CA_orderIDs']) && count($_GET['CA_orderIDs']))
		{
			$update_flag_sql="UPDATE __ca_orders SET FlagID='6', FlagDescription='".$FlagDescription."', updated_at_ca=false WHERE ID IN (".$_GET['CA_orderIDs'].") ";
			$mysqli->query($update_flag_sql);
		}
		############################################################################
		# Crontab then calls ca-flagasprinted.php every 5 minutes to update flags at
		# Channel Advisor, 25 at a time...
		############################################################################

		############################################################################
		# DEAL WITH THE WEBSITE ORDERS CONFIRMED AS PRINTED!!!
		############################################################################
		if(isset($_GET['WEB_orderIDs']) && is_array($_GET['WEB_orderIDs']) && count($_GET['WEB_orderIDs']))
		{
			$printed_ca_order_ids = explode($_GET['WEB_orderIDs'],",");
			foreach($printed_ca_order_ids AS $order_ix) if($order_ix>0) $mysqli->query("INSERT INTO __andy_printed_orders SET ix=".$order_ix);
			if(count($_POST_ca_prod_id)>0)
			{
				foreach($_POST_ca_prod_id AS $post_index => $ca_prod_id)
				{
					$url = "https://api.channeladvisor.com/v1/Products(".$ca_prod_id.")/UpdateQuantity";	
					$data = array('Value' => array('UpdateType' => 'Relative', 'Updates'    => array( 0 => array('DistributionCenterID' => $_POST_ca_dc_id[$post_index],'Quantity'             => -($_POST_qty[$post_index])))));
					$options = array('http' => array('method'  => 'POST', 'content' => json_encode( $data ), 'header'  => "Authorization: bearer ".ACCESS_TOKEN."\r\n" . "Content-Type: application/json\r\n" . "Accept: application/json\r\n"));
					$response = json_decode( file_get_contents( $url, false, stream_context_create( $options ) ) );
				}
			}
		}
		############################################################################
	}
?>