<?php
	require("fpdf181/fpdf.php");

	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, '.', '');
	}
	?>
	<?php
	class CA_InvoicePDF extends FPDF
	{
		// Page header
		function Header()
		{
			$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 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 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==4 || $order_item_count==12) { $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++;
			}
		}

		// 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);
		}	

	}


	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(); }

	$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['orderIDs'].") ";
	$order_sql .= "ORDER BY CAO.ShippingCountry, CAO.SiteName, CAO.PaymentDateUtc ASC ";
	$orders=$mysqli->query($order_sql);
	$num_orders = $orders->num_rows;

	$pdf = new CA_InvoicePDF(); // Instanciation of inherited class
	$pdf->AliasNbPages();

	$orderArray=array();
	while($order=$orders->fetch_object()) $orderArray[] = $pdf->PrepareOrder($order,$mysqli);
	while($order=array_shift($orderArray)) $pdf->AddOrderToPDF($order);
	$pdf->Output();

?>
