<?php

$PageSecurity=1;

include('includes/DefineCartClass.php');

include('includes/session.inc');

$title=_('Synchronise Sales from Zencart');

include('includes/header.inc');
include('includes/GetPrice.inc');
include('includes/SQL_CommonFunctions.inc');
include('includes/GetSalesTransGLCodes.inc');



echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" >';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/group_add.png" title="' . _('Search') . '" alt="" />' . ' ' . $title.'</p>
	<br />';

if (isset($_POST['sync_sales'])) 
{ 
  //=====Get Zencart Details (Start)=====
  $sqlGetZencartDetails = "SELECT id, zencart_db, emp_stock_location FROM emp_zencart_integration WHERE id=1";
  $resultGetZencartDetails = DB_query($sqlGetZencartDetails,$db);
  $myrowGetZencartDetails = DB_fetch_array($resultGetZencartDetails);
	
	$zencartDB = $myrowGetZencartDetails['zencart_db'];
	$empLocation = $myrowGetZencartDetails['emp_stock_location'];
	//=====Get Zencart Details (End)=====
	
	//=====Add Sales (Start)=====
	$sqlGetZencartSales = "SELECT orders_id, customers_id, 
                                delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, 
                                delivery_postcode, delivery_state, delivery_country, delivery_telephone, delivery_email_address,
                                payment_method, date_purchased, currency, order_total, order_tax                                
                                  FROM ".$zencartDB.".orders";
	$resultGetZencartSales = DB_query($sqlGetZencartSales,$db);
  
  while($myrowGetZencartSales = DB_fetch_array($resultGetZencartSales))
  {
    $AddSalesToEMP = 1;
    $zencartSalesID = $myrowGetZencartSales['orders_id'];
    $zencartSalesCustomerID = $myrowGetZencartSales['customers_id'];
    $zencartSalesDeliveryName = $myrowGetZencartSales['delivery_name'];
    $zencartSalesDeliveryCompany = $myrowGetZencartSales['delivery_company'];
    $zencartSalesDeliveryStreet = $myrowGetZencartSales['delivery_street_address'];
    $zencartSalesDeliverySuburb = $myrowGetZencartSales['delivery_suburb'];
    $zencartSalesDeliveryCity = $myrowGetZencartSales['delivery_city'];
    $zencartSalesDeliveryPostcode = $myrowGetZencartSales['delivery_postcode'];
    $zencartSalesDeliveryState = $myrowGetZencartSales['delivery_state'];
    $zencartSalesDeliveryCountry = $myrowGetZencartSales['delivery_country'];
    $zencartSalesDeliveryTel = $myrowGetZencartSales['delivery_telephone'];
    $zencartSalesDeliveryEmail = $myrowGetZencartSales['delivery_email_address'];
    $zencartSalesPaymentMethod = $myrowGetZencartSales['payment_method'];
    $zencartSalesDatePurchased = Date('Y-m-d', strtotime($myrowGetZencartSales['date_purchased']));
    $zencartSalesCurrency = $myrowGetZencartSales['currency'];
    $zencartSalesTotal = $myrowGetZencartSales['order_total'];
    $zencartSalesTax = $myrowGetZencartSales['order_tax'];
    
    $sqlGetEMPExistingOrder = "SELECT count(*) AS OrderCount FROM salesorders WHERE customerref='".$zencartSalesID."'";
    $resultGetEMPExistingOrder = DB_query($sqlGetEMPExistingOrder,$db);
    
    if (DB_num_rows($resultGetEMPExistingOrder)!=0)
    {
        $AddSalesToEMP = 0;
        prnMsg(_('Zencart order') . ' ' . $zencartSalesID . ' ' . _(' exists in EMP database'), 'error');
        break;
    }
    
    $sqlGetEMPDebtorNo = "SELECT debtorno FROM custbranch WHERE custbranchcode='".$zencartSalesCustomerID."'";
    $resultGetEMPDebtorNo = DB_query($sqlGetEMPDebtorNo,$db);
    
    if (DB_num_rows($resultGetEMPDebtorNo)==0)
    {
        $AddSalesToEMP = 0;
        prnMsg(_('Zencart customer') . ' ' . $zencartSalesCustomerID . ' ' . _(' does not exist in EMP database'), 'error');
        break;
    }

    if($AddSalesToEMP == 1)
    {     
      $LocationName = 'ECOMM';
			$Location = 'ECOMM';
			$SalesLocation = 'ECOMM';
			$DispatchTaxProvince = '1';
			
			$AlreadyWarnedAboutCredit = false;

      if (empty($_GET['identifier'])) {
        $identifier=date('U');
      } else {
        $identifier=$_GET['identifier'];
      }

      if (isset($_SESSION['Items'.$identifier]) AND isset($_POST['CustRef']))
      {
        //update the Items object variable with the data posted from the form
        $_SESSION['Items'.$identifier]->CustRef = $_POST['CustRef'];
        $_SESSION['Items'.$identifier]->Comments = $_POST['Comments'];
        $_SESSION['Items'.$identifier]->DeliverTo = $_POST['DeliverTo'];
        $_SESSION['Items'.$identifier]->PhoneNo = $_POST['PhoneNo'];
        $_SESSION['Items'.$identifier]->Email = $_POST['Email'];
        //20130520 YS Chin: No more selection from entry page. User selected first time.
        //$_SESSION['Items'.$identifier]->SalesLocation = $_POST['SalesLocation'];
      }

      if (isset($_POST['QuickEntry'])){
        unset($_POST['PartSearch']);
      }

      if (isset($_POST['SelectingOrderItems'])){
        foreach ($_POST as $FormVariable => $Quantity) {
          if (mb_strpos($FormVariable,'OrderQty')!==false) {
            $NewItemArray[$_POST['StockID' . mb_substr($FormVariable,8)]] = filter_number_format($Quantity);
          }
        }
      }

      if (isset($_GET['NewItem'])){
        $NewItem = trim($_GET['NewItem']);
      }

      if (isset($_GET['NewOrder'])){
        /*New order entry - clear any existing order details from the Items object and initiate a newy*/
         if (isset($_SESSION['Items'.$identifier])){
          unset ($_SESSION['Items'.$identifier]->LineItems);
          $_SESSION['Items'.$identifier]->ItemsOrdered=0;
          unset ($_SESSION['Items'.$identifier]);
        }
      }
			
			$_SESSION['ExistingOrder'. $identifier] = 0;
      $_SESSION['Items'.$identifier] = new cart;
      $_SESSION['PrintedPackingSlip'] = 0; /*Of course 'cos the order ain't even started !!*/
    
    
      $_SESSION['Items'.$identifier]->LocationName = $LocationName;
      //20130520 YS Chin: Use location ID from SQL (selected) rather than User Stock Location
      $_SESSION['Items'.$identifier]->Location = $Location;
      $_SESSION['Items'.$identifier]->SalesLocation = $SalesLocation;
      $_SESSION['Items'.$identifier]->DispatchTaxProvince = $DispatchTaxProvince;
			
			//20150903  DONE UNTIL HERE ==============
			
			// Now check to ensure this account exists and set defaults 
			$sqlGetEMPCustomerDetails = "SELECT debtorsmaster.name,
                                  custbranch.branchcode,
                                  custbranch.debtorno,
                                  holdreasons.dissallowinvoices,
                                  debtorsmaster.salestype,
                                  salestypes.sales_type,
                                  debtorsmaster.currcode,
                                  debtorsmaster.customerpoline,
                                  paymentterms.terms,
                                  currencies.decimalplaces
                                FROM debtorsmaster INNER JOIN holdreasons
                                ON debtorsmaster.holdreason=holdreasons.reasoncode
                                INNER JOIN salestypes 
                                ON debtorsmaster.salestype=salestypes.typeabbrev
                                INNER JOIN paymentterms 
                                ON debtorsmaster.paymentterms=paymentterms.termsindicator 
                                INNER JOIN currencies 
                                ON debtorsmaster.currcode=currencies.currabrev
                                INNER JOIN custbranch 
                                ON debtorsmaster.debtorno=custbranch.debtorno
                                WHERE custbranch.custbranchcode = '" . $zencartSalesCustomerID . "'";
			
			$ErrMsgGetEMPCustomerDetails = _('The details of the Zencart customer selected') . ': ' .  $zencartSalesCustomerID . ' ' . _('cannot be retrieved because');
			$DbgMsgGetEMPCustomerDetails = _('The SQL used to retrieve the customer details and failed was') . ':';

			$resultGetEMPCustomerDetails = DB_query($sqlGetEMPCustomerDetails,$db,$ErrMsgGetEMPCustomerDetails,$DbgMsgGetEMPCustomerDetails);
			
			$myrowGetEMPCustomerDetails = DB_fetch_array($resultGetEMPCustomerDetails);
			
			if ($myrowGetEMPCustomerDetails['dissallowinvoices'] != 1){
			
				if ($myrowGetEMPCustomerDetails['dissallowinvoices']==2){
					prnMsg($myrowGetEMPCustomerDetails['name'] . ' ' . _('Although this account is defined as the Zencart sale account for the location.  The account is currently flagged as an account that needs to be watched. Please contact the credit control personnel to discuss'),'warn');
				}
	
				//$_SESSION['RequireCustomerSelection']=0;
				$_SESSION['Items'.$identifier]->DebtorNo = $myrowGetEMPCustomerDetails['debtorno'];
				$_SESSION['Items'.$identifier]->Branch = $myrowGetEMPCustomerDetails['branchcode'];
				$_SESSION['Items'.$identifier]->CustomerName = $myrowGetEMPCustomerDetails['name'];
				// the sales type is the price list to be used for this sale
				$_SESSION['Items'.$identifier]->DefaultSalesType = $myrowGetEMPCustomerDetails['salestype'];
				$_SESSION['Items'.$identifier]->SalesTypeName = $myrowGetEMPCustomerDetails['sales_type'];
				$_SESSION['Items'.$identifier]->DefaultCurrency = $myrowGetEMPCustomerDetails['currcode'];
				$_SESSION['Items'.$identifier]->DefaultPOLine = $myrowGetEMPCustomerDetails['customerpoline'];
				$_SESSION['Items'.$identifier]->PaymentTerms = $myrowGetEMPCustomerDetails['terms'];
				$_SESSION['Items'.$identifier]->CurrDecimalPlaces = $myrowGetEMPCustomerDetails['decimalplaces'];
				

        /* now get the branch defaults from the customer branches table CustBranch. */
	
				$sqlGetEMPCustomerBranchDetails = "SELECT custbranch.brname,
					       custbranch.braddress1,
					       custbranch.defaultshipvia,
					       custbranch.deliverblind,
					       custbranch.specialinstructions,
					       custbranch.estdeliverydays,
					       custbranch.salesman,
					       custbranch.taxgroupid,
					       custbranch.defaultshipvia
					FROM custbranch
					WHERE custbranch.branchcode='" . $BranchCode . "'
					AND custbranch.debtorno = '" . $DebtorNo . "'";
		    $ErrMsgGetEMPCustomerBranchDetails = _('The customer branch record of the customer selected') . ': ' . $BranchCode . ' ' . _('cannot be retrieved because');
				$DbgMsgGetEMPCustomerBranchDetails = _('SQL used to retrieve the branch details was') . ':';
				$resultGetEMPCustomerBranchDetails =DB_query($sqlGetEMPCustomerBranchDetails,$db,$ErrMsgGetEMPCustomerBranchDetails,$DbgMsgGetEMPCustomerBranchDetails);
	
				if (DB_num_rows($resultGetEMPCustomerBranchDetails)==0)
				{
					prnMsg(_('The branch details for branch code') . ': ' . $BranchCode . ' ' . _('against customer code') . ': ' . $DebtorNo . ' ' . _('could not be retrieved') . '. ' . _('Check the set up of the customer and branch'),'error');
					break;
				}

				$myrowGetEMPCustomerBranchDetails = DB_fetch_array($resultGetEMPCustomerBranchDetails);
	
        $_SESSION['Items'.$identifier]->DeliverTo = $zencartSalesDeliveryName.' '.$zencartSalesDeliveryCompany;
				$_SESSION['Items'.$identifier]->DelAdd1 = $zencartSalesDeliveryStreet.', '.$zencartSalesDeliverySuburb.', '.$zencartSalesDeliveryCity;
				$_SESSION['Items'.$identifier]->ShipVia = $myrowGetEMPCustomerBranchDetails['defaultshipvia'];
				$_SESSION['Items'.$identifier]->DeliverBlind = $myrowGetEMPCustomerBranchDetails['deliverblind'];
				$_SESSION['Items'.$identifier]->SpecialInstructions = $myrowGetEMPCustomerBranchDetails['specialinstructions'];
				$_SESSION['Items'.$identifier]->DeliveryDays = $myrowGetEMPCustomerBranchDetails['estdeliverydays'];
				$_SESSION['Items'.$identifier]->TaxGroup = $myrowGetEMPCustomerBranchDetails['taxgroupid'];
	
				if ($SpecialInstructions) {
					prnMsg($SpecialInstructions,'warn');
				}

        /*
				if ($_SESSION['CheckCreditLimits'] > 0 AND $AlreadyWarnedAboutCredit==false) {  //Check credit limits is 1 for warn and 2 for prohibit sales 
					$_SESSION['Items'.$identifier]->CreditAvailable = GetCreditAvailable($_SESSION['Items'.$identifier]->DebtorNo,$db);
	
					if ($_SESSION['CheckCreditLimits']==1 AND $_SESSION['Items'.$identifier]->CreditAvailable <=0){
						prnMsg(_('The') . ' ' . $myrow['brname'] . ' ' . _('account is currently at or over their credit limit'),'warn');
						$AlreadyWarnedAboutCredit = true;
					} elseif ($_SESSION['CheckCreditLimits']==2 AND $_SESSION['Items'.$identifier]->CreditAvailable <=0){
						prnMsg(_('No more orders can be placed by') . ' ' . $myrow[0] . ' ' . _(' their account is currently at or over their credit limit'),'warn');
						$AlreadyWarnedAboutCredit = true;
						break;
					}
				}
				*/
	
			} else {
				prnMsg($myrowGetEMPCustomerBranchDetails['brname'] . ' ' . _('Although the account is defined as the cash sale account for the location  the account is currently on hold. Please contact the credit control personnel to discuss'),'warn');
			}
	
	//20150908 until here
	
      //echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '?identifier='.$identifier . '" name="SelectParts" method="post">';
      echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	
      //Get The exchange rate used for GPPercent calculations on adding or amending items
      if ($_SESSION['Items'.$identifier]->DefaultCurrency != $_SESSION['CompanyRecord']['currencydefault']){
        $ExRateResult = DB_query("SELECT rate FROM currencies WHERE currabrev='" . $_SESSION['Items'.$identifier]->DefaultCurrency . "'",$db);
        if (DB_num_rows($ExRateResult)>0){
          $ExRateRow = DB_fetch_row($ExRateResult);
          $ExRate = $ExRateRow[0];
        } else {
          $ExRate =1;
        }
      } else {
        $ExRate = 1;
      }		
			
			
			$InputError = false; //always assume the best
			
			/*
      //but check for the worst
      if ($_SESSION['Items'.$identifier]->LineCounter == 0){
        prnMsg(_('There are no lines on this sale. Please enter lines to invoice first'),'error');
        $InputError = true;
      }
      if (abs(filter_number_format($_POST['AmountPaid']) -($_SESSION['Items'.$identifier]->total+filter_number_format($_POST['TaxTotal'])))>=0.01) {
        prnMsg(_('The amount entered as payment does not equal the amount of the invoice. Please ensure the customer has paid the correct amount and re-enter'),'error');
        $InputError = true;
      }
      */

      //20130404 YS Chin: Check if Sales Branch is selected
      if ($SalesLocation == "")
      {
        prnMsg(_('There is no Sales Branch defined'),'error');
        $InputError = true;
      }
      
      //=====Get the products for the sales (start)=====
      
      $sqlGetProductsForSales = "SELECT products_id, products_name, products_price, final_price, products_tax, products_quantity
                                  FROM ".$zencartDB.".orders_products WHERE orders_id = '".$zencartSalesID."'";
      $ErrMsgGetProductsForSales = _('The products of the selected Zencart order') . ': ' . $zencartSalesID . ' ' . _('cannot be retrieved because');
			$DbgMsgGetProductsForSales = _('SQL used to retrieve the products details was') . ':';
			$resultGetProductsForSales =DB_query($sqlGetProductsForSales,$db,$ErrMsgGetProductsForSales,$DbgMsgGetProductsForSales);
	
      if (DB_num_rows($resultGetProductsForSales)==0)
      {
        prnMsg(_('The product details for branch code') . ': ' . $BranchCode . ' ' . _('against customer code') . ': ' . $DebtorNo . ' ' . _('could not be retrieved') . '. ' . _('Check the set up of the customer and branch'),'error');
        break;
        
      } else {
        
        if ($_SESSION['ProhibitNegativeStock']==1)
        { 
          // checks for negative stock after processing invoice
          //sadly this check does not combine quantities occuring twice on and order and each line is considered individually :-(
          $NegativesFound = false;
          
          while($myrowGetProductsForSales=DB_fetch_array($resultGetProductsForSales)) 
          {
            $SQL = "SELECT stockmaster.description,
                      locstock.quantity,
                      stockmaster.mbflag
                FROM locstock
                INNER JOIN stockmaster
                ON stockmaster.stockid=locstock.stockid
                WHERE stockmaster.stockid='" . $myrowGetProductsForSales['products_name'] . "'
                AND locstock.loccode='" . $Location . "'";

            $ErrMsg = _('Could not retrieve the quantity left at the location once this order is invoiced (for the purposes of checking that stock will not go negative because)');
            $Result = DB_query($SQL,$db,$ErrMsg);
            $CheckNegRow = DB_fetch_array($Result);
            if ($CheckNegRow['mbflag']=='B' OR $CheckNegRow['mbflag']=='M'){
              if ($CheckNegRow['quantity'] < $myrowGetProductsForSales['products_quantity']){
                prnMsg( _('Invoicing the selected order would result in negative stock. The system parameters are set to prohibit negative stocks from occurring. This invoice cannot be created until the stock on hand is corrected.'),'error',$OrderLine->StockID . ' ' . $CheckNegRow['description'] . ' - ' . _('Negative Stock Prohibited'));
                $NegativesFound = true;
              }
            } else if ($CheckNegRow['mbflag']=='A') {

              //Now look for assembly components that would go negative 
              $SQL = "SELECT bom.component,
                       stockmaster.description,
                       locstock.quantity-(" . $myrowGetProductsForSales['products_quantity']  . "*bom.quantity) AS qtyleft
                  FROM bom
                  INNER JOIN locstock
                  ON bom.component=locstock.stockid
                  INNER JOIN stockmaster
                  ON stockmaster.stockid=bom.component
                  WHERE bom.parent='" . $myrowGetProductsForSales['products_name'] . "'
                  AND locstock.loccode='" . $Location . "'
                  AND effectiveafter <'" . Date('Y-m-d') . "'
                  AND effectiveto >='" . Date('Y-m-d') . "'";

              $ErrMsg = _('Could not retrieve the component quantity left at the location once the assembly item on this order is invoiced (for the purposes of checking that stock will not go negative because)');
              $Result = DB_query($SQL,$db,$ErrMsg);
              while ($NegRow = DB_fetch_array($Result)){
                if ($NegRow['qtyleft']<0){
                  prnMsg(_('Invoicing the selected order would result in negative stock for a component of an assembly item on the order. The system parameters are set to prohibit negative stocks from occurring. This invoice cannot be created until the stock on hand is corrected.'),'error',$NegRow['component'] . ' ' . $NegRow['description'] . ' - ' . _('Negative Stock Prohibited'));
                  $NegativesFound = true;
                } // end if negative would result
              } //loop around the components of an assembly item
            } //end if its an assembly item - check component stock

          } //end of loop around items on the order for negative check
  
        if ($NegativesFound)
        {
          prnMsg(_('The parameter to prohibit negative stock is set and invoicing this sale would result in negative stock. No futher processing can be performed. Alter the sale first changing quantities or deleting lines which do not have sufficient stock.'),'error');
          $InputError = true;
        }
      
      }//end of testing for negative stocks
      
      
      if ($InputError == false) 
      { 
        //all good so let's get on with the processing
        //Now Get the area where the sale is to from the branches table 

        $SQL = "SELECT 	area,
                defaultshipvia
            FROM custbranch
            WHERE custbranch.debtorno ='". $DebtorNo . "'
            AND custbranch.branchcode = '" . $BranchCode . "'";

        $ErrMsg = _('We were unable to load the area where the sale is to from the custbranch table');
        $Result = DB_query($SQL,$db, $ErrMsg);
        $myrow = DB_fetch_row($Result);
        $Area = $myrow[0];
        $DefaultShipVia = $myrow[1];
        DB_free_result($Result);

        //company record read in on login with info on GL Links and debtors GL account

        if ($_SESSION['CompanyRecord']==0){
          //The company data and preferences could not be retrieved for some reason 
          prnMsg( _('The company information and preferences could not be retrieved. See your system administrator'), 'error');
          include('includes/footer.inc');
          exit;
        }

        // *************************************************************************
        //   S T A R T   O F   I N V O I C E   S Q L   P R O C E S S I N G
        // *************************************************************************
          $result = DB_Txn_Begin($db);
        /*First add the order to the database - it only exists in the session currently! */
          $OrderNo = GetNextTransNo(30, $db);
          //20130404 YS Chin: Add Salesman and Sales Branch
          $HeaderSQL = "INSERT INTO salesorders (	orderno,
                              debtorno,
                              branchcode,
                              customerref,
                              comments,
                              orddate,
                              ordertype,
                              shipvia,
                              deliverto,
                              deladd1,
                              deladd2,
                              deladd3,
                              deladd4,
                              deladd5,
                              deladd6
                              contactphone,
                              contactemail,
                              fromstkloc,
                              deliverydate,
                              confirmeddate,
                              deliverblind,
                              ra_salesbranch,
                              ra_salesman)
                            VALUES (
                              '" . $OrderNo . "',
                              '" . $DebtorNo . "',
                              '" . $BranchCode . "',
                              '',
                              'Zencart Order ID ".$zencartSalesID." ',
                              '" . $zencartSalesDatePurchased . "',
                              '" . $DefaultSalesType . "',
                              '" . $ShipVia . "',
                              '" . $zencartSalesDeliveryName . "',
                              '" . $zencartSalesDeliveryCompany . "',
                              '" . $zencartSalesDeliveryStreet . ", " . $zencartSalesDeliverySuburb . "',
                              '" . $zencartSalesDeliveryPostcode . ", " . $zencartSalesDeliveryCity . "',
                              '" . $zencartSalesDeliveryState . "',
                              '" . $zencartSalesDeliveryCountry . "',
                              '',
                              '" . $zencartSalesDeliveryTel . "',
                              '" . $zencartSalesDeliveryEmail . "',
                              '" . $Location ."',
                              '" . $zencartSalesDatePurchased . "',
                              '" . $zencartSalesDatePurchased . "',
                              0,
                              '" . $SalesLocation ."',
                              'ECOMM'
                              )";

          $ErrMsg = _('The order cannot be added because');
          $InsertQryResult = DB_query($HeaderSQL,$db,$ErrMsg);

          $StartOf_LineItemsSQL = "INSERT INTO salesorderdetails (orderlineno,
                                      orderno,
                                      stkcode,
                                      unitprice,
                                      quantity,
                                      discountpercent,
                                      narrative,
                                      itemdue,
                                      actualdispatchdate,
                                      qtyinvoiced,
                                      completed)
                                    VALUES (";

          $DbgMsg = _('Trouble inserting a line of a sales order. The SQL that failed was');
          
          $sqlGetProductsForSales = "SELECT products_id, products_name, products_price, final_price, products_tax, products_quantity
                                      FROM ".$zencartDB.".orders_products WHERE orders_id = '".$zencartSalesID."'";
          $ErrMsgGetProductsForSales = _('The products of the selected Zencart order') . ': ' . $zencartSalesID . ' ' . _('cannot be retrieved because');
          $DbgMsgGetProductsForSales = _('SQL used to retrieve the products details was') . ':';
          $resultGetProductsForSales =DB_query($sqlGetProductsForSales,$db,$ErrMsgGetProductsForSales,$DbgMsgGetProductsForSales);
	
          if (DB_num_rows($resultGetProductsForSales)==0)
          {
            prnMsg(_('The product details for branch code') . ': ' . $BranchCode . ' ' . _('against customer code') . ': ' . $DebtorNo . ' ' . _('could not be retrieved') . '. ' . _('Check the set up of the customer and branch'),'error');
            break;
            
          } else {
          
            $LineNumber=0;
            
            while($myrowGetProductsForSales=DB_fetch_array($resultGetProductsForSales)) 
            {
                $StockID = $myrowGetProductsForSales['products_name'];
                $Price = $myrowGetProductsForSales['final_price'];
                $Quantity = $myrowGetProductsForSales['products_quantity'];
                $Tax = $myrowGetProductsForSales['products_tax'];
                
                $LineItemsSQL = $StartOf_LineItemsSQL .
                    "'".$LineNumber . "',
                    '" . $OrderNo . "',
                    '" . $StockID . "',
                    '" . $Price . "',
                    '" . $Quantity . "',
                    '0.00',
                    '',
                    '" . $zencartSalesDatePurchased . "',
                    '" . $zencartSalesDatePurchased . "',
                    '" . $Quantity . "',
                    1)";

                $ErrMsg = _('Unable to add the sales order line');
                $Ins_LineItemResult = DB_query($LineItemsSQL,$db,$ErrMsg,$DbgMsg,true);

                /*
                //Now check to see if the item is manufactured
                 //and AutoCreateWOs is on
                 //and it is a real order (not just a quotation)
                
                $SQL = "SELECT mbflag
                    FROM stockmaster
                    WHERE stockmaster.stockid='" . $StockID . "'";

                $ErrMsg = _('Could not retrieve the quantity left at the location once this order is invoiced (for the purposes of checking that stock will not go negative because)');
                $Result = DB_query($SQL,$db,$ErrMsg);
                $CheckMBFlag = DB_fetch_array($Result);
                $MBFlag = $CheckMBFlag['mbflag'];
            
                if ($MBflag=='M' AND $_SESSION['AutoCreateWOs']==1)
                { //oh yeah its all on!

                  //now get the data required to test to see if we need to make a new WO
                  $QOHResult = DB_query("SELECT SUM(quantity) FROM locstock WHERE stockid='" . $StockID . "'",$db);
                  $QOHRow = DB_fetch_row($QOHResult);
                  $QOH = $QOHRow[0];

                  $SQL = "SELECT SUM(salesorderdetails.quantity - salesorderdetails.qtyinvoiced) AS qtydemand
                            FROM salesorderdetails
                            WHERE salesorderdetails.stkcode = '" . $StockID . "'
                            AND salesorderdetails.completed = 0";
                  $DemandResult = DB_query($SQL,$db);
                  $DemandRow = DB_fetch_row($DemandResult);
                  $QuantityDemand = $DemandRow[0];

                  $SQL = "SELECT SUM((salesorderdetails.quantity-salesorderdetails.qtyinvoiced)*bom.quantity) AS dem
                          FROM salesorderdetails,
                            bom,
                            stockmaster
                          WHERE salesorderdetails.stkcode=bom.parent
                          AND salesorderdetails.quantity-salesorderdetails.qtyinvoiced > 0
                          AND bom.component='" . $StockID . "'
                          AND stockmaster.stockid=bom.parent
                          AND salesorderdetails.completed=0";
                  $AssemblyDemandResult = DB_query($SQL,$db);
                  $AssemblyDemandRow = DB_fetch_row($AssemblyDemandResult);
                  $QuantityAssemblyDemand = $AssemblyDemandRow[0];

                  $SQL = "SELECT SUM(purchorderdetails.quantityord - purchorderdetails.quantityrecd) as qtyonorder
                          FROM purchorderdetails INNER JOIN purchorders
                          ON purchorderdetails.orderno = purchorders.orderno
                          WHERE purchorderdetails.itemcode = '" . $StockID . "'
                          AND purchorderdetails.completed = 0
                          AND purchorders.status<>'Rejected'
                          AND purchorders.status<>'Pending'
                          AND purchorders.status<>'Completed'";
                  $PurchOrdersResult = DB_query($SQL,$db);
                  $PurchOrdersRow = DB_fetch_row($PurchOrdersResult);
                  $QuantityPurchOrders = $PurchOrdersRow[0];

                  $SQL = "SELECT SUM(woitems.qtyreqd - woitems.qtyrecd) as qtyonorder
                          FROM woitems INNER JOIN workorders
                          ON woitems.wo=workorders.wo
                          WHERE woitems.stockid = '" . $StockID . "'
                          AND woitems.qtyreqd > woitems.qtyrecd
                          AND workorders.closed = 0";
                  $WorkOrdersResult = DB_query($SQL,$db);
                  $WorkOrdersRow = DB_fetch_row($WorkOrdersResult);
                  $QuantityWorkOrders = $WorkOrdersRow[0];

                  //Now we have the data - do we need to make any more?
                  $ShortfallQuantity = $QOH-$QuantityDemand-$QuantityAssemblyDemand+$QuantityPurchOrders+$QuantityWorkOrders;

                  if ($ShortfallQuantity < 0) { //then we need to make a work order
                    //How many should the work order be for??
                    if ($ShortfallQuantity + $StockItem->EOQ < 0){
                      $WOQuantity = -$ShortfallQuantity;
                    } else {
                      $WOQuantity = $StockItem->EOQ;
                    }

                    $WONo = GetNextTransNo(40,$db);
                    $ErrMsg = _('Unable to insert a new work order for the sales order item');
                    $InsWOResult = DB_query("INSERT INTO workorders (wo,
                                     loccode,
                                     requiredby,
                                     startdate)
                             VALUES ('" . $WONo . "',
                                '" . $_SESSION['DefaultFactoryLocation'] . "',
                                '" . Date('Y-m-d') . "',
                                '" . Date('Y-m-d'). "')",
                                $db,$ErrMsg,$DbgMsg,true);
                    //Need to get the latest BOM to roll up cost
                    $CostResult = DB_query("SELECT SUM((materialcost+labourcost+overheadcost)*bom.quantity) AS cost
                                            FROM stockmaster INNER JOIN bom
                                            ON stockmaster.stockid=bom.component
                                            WHERE bom.parent='" . $StockItem->StockID . "'
                                            AND bom.loccode='" . $_SESSION['DefaultFactoryLocation'] . "'",
                                          $db);
                    $CostRow = DB_fetch_row($CostResult);
                    if (is_null($CostRow[0]) OR $CostRow[0]==0){
                      $Cost =0;
                      prnMsg(_('In automatically creating a work order for') . ' ' . $StockItem->StockID . ' ' . _('an item on this sales order, the cost of this item as accumulated from the sum of the component costs is nil. This could be because there is no bill of material set up ... you may wish to double check this'),'warn');
                    } else {
                      $Cost = $CostRow[0];
                    }

                    // insert parent item info
                    $sql = "INSERT INTO woitems (wo,
                                   stockid,
                                   qtyreqd,
                                   stdcost)
                             VALUES ('" . $WONo . "',
                                 '" . $StockItem->StockID . "',
                                 '" . $WOQuantity . "',
                                 '" . $Cost . "')";
                    $ErrMsg = _('The work order item could not be added');
                    $result = DB_query($sql,$db,$ErrMsg,$DbgMsg,true);

                    //Recursively insert real component requirements - see includes/SQL_CommonFunctions.in for function WoRealRequirements
                    WoRealRequirements($db, $WONo, $_SESSION['DefaultFactoryLocation'], $StockItem->StockID);

                    $FactoryManagerEmail = _('A new work order has been created for') .
                              ":\n" . $StockItem->StockID . ' - ' . $StockItem->ItemDescription . ' x ' . $WOQuantity . ' ' . $StockItem->Units .
                              "\n" . _('These are for') . ' ' . $_SESSION['Items'.$identifier]->CustomerName . ' ' . _('there order ref') . ': '  . $_SESSION['Items'.$identifier]->CustRef . ' ' ._('our order number') . ': ' . $OrderNo;

                    if ($StockItem->Serialised AND $StockItem->NextSerialNo>0){
                      //then we must create the serial numbers for the new WO also
                      $FactoryManagerEmail .= "\n" . _('The following serial numbers have been reserved for this work order') . ':';

                      for ($i=0;$i<$WOQuantity;$i++){

                        $result = DB_query("SELECT serialno FROM stockserialitems
                                    WHERE serialno='" . ($StockItem->NextSerialNo + $i) . "'
                                    AND stockid='" . $StockItem->StockID ."'",$db);
                        if (DB_num_rows($result)!=0){
                          $WOQuantity++;
                          prnMsg(($StockItem->NextSerialNo + $i) . ': ' . _('This automatically generated serial number already exists - it cannot be added to the work order'),'error');
                        } else {
                          $sql = "INSERT INTO woserialnos (wo,
                                            stockid,
                                            serialno)
                                      VALUES ('" . $WONo . "',
                                          '" . $StockItem->StockID . "',
                                          '" . ($StockItem->NextSerialNo + $i)	 . "')";
                          $ErrMsg = _('The serial number for the work order item could not be added');
                          $result = DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
                          $FactoryManagerEmail .= "\n" . ($StockItem->NextSerialNo + $i);
                        }
                      } //end loop around creation of woserialnos
                      $NewNextSerialNo = ($StockItem->NextSerialNo + $WOQuantity +1);
                      $ErrMsg = _('Could not update the new next serial number for the item');
                      $UpdateSQL="UPDATE stockmaster SET nextserialno='" . $NewNextSerialNo . "' WHERE stockid='" . $StockItem->StockID . "'";
                      $UpdateNextSerialNoResult = DB_query($UpdateSQL,$db,$ErrMsg,$DbgMsg,true);
                    } // end if the item is serialised and nextserialno is set

                    $EmailSubject = _('New Work Order Number') . ' ' . $WONo . ' ' . _('for') . ' ' . $StockItem->StockID . ' x ' . $WOQuantity;
                    //Send email to the Factory Manager
                    mail($_SESSION['FactoryManagerEmail'],$EmailSubject,$FactoryManagerEmail);
                  } //end if with this sales order there is a shortfall of stock - need to create the WO
                }//end if auto create WOs in on
                */
                
                $LineNumber++;
                
              } // end inserted line items into sales order details 

              prnMsg(_('Order Number') . ' ' . $OrderNo . ' ' . _('has been entered'),'success');

            }// End of insertion of new sales order 

            //Now Get the next invoice number - GetNextTransNo() function in SQL_CommonFunctions
            // GetPeriod() in includes/DateFunctions.inc 

            $InvoiceNo = GetNextTransNo(10, $db);
            $PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat'],strtotime($zencartSalesDatePurchased)), $db);

            $DefaultDispatchDate = $zencartSalesDatePurchased;

            /*Update order header for invoice charged on */
            $SQL = "UPDATE salesorders SET comments = CONCAT(comments,'" . ' ' . _('Invoice') . ': ' . "','" . $InvoiceNo . "') WHERE orderno= '" . $OrderNo."'";

            $ErrMsg = _('CRITICAL ERROR') . ' ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales order header could not be updated with the invoice number');
            $DbgMsg = _('The following SQL to update the sales order was used');
            $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);


            //20150901 stop here
            
            
            /*Now insert the DebtorTrans */

            $TotalAlloc = $zencartSalesTotal + $zencartSalesTax;
            
            $SQL = "INSERT INTO debtortrans (transno,
                            type,
                            debtorno,
                            branchcode,
                            trandate,
                            inputdate,
                            prd,
                            reference,
                            tpe,
                            order_,
                            ovamount,
                            ovgst,
                            rate,
                            invtext,
                            shipvia,
                            alloc,
                            settled )
              VALUES (
                '". $InvoiceNo . "',
                10,
                '" . $DebtorNo . "',
                '" . $BranchCode . "',
                '" . $DefaultDispatchDate . "',
                '" . date('Y-m-d H-i-s', strtotime($DefaultDispatchDate)) . "',
                '" . $PeriodNo . "',
                '',
                '" . $DefaultSalesType . "',
                '" . $OrderNo . "',
                '" . $zencartSalesTotal . "',
                '" . $zencartSalesTax . "',
                '" . $ExRate . "',
                '',
                '" . $ShipVia . "',
                '" . $TotalAlloc . "',
                '1')";
    
    
              $ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction record could not be inserted because');
              $DbgMsg = _('The following SQL to insert the debtor transaction record was used');
              $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

              $DebtorTransID = DB_Last_Insert_ID($db,'debtortrans','id');
              
              $TaxAuthID = 1; //Hardcode for Malaysian GST

              $SQL = "INSERT INTO debtortranstaxes (debtortransid,
                                  taxauthid,
                                  taxamount)
                            VALUES ('" . $DebtorTransID . "',
                              '" . $TaxAuthID . "',
                              '" . $zencartSalesTax/$ExRate . "')";

              $ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
              $DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
              $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
              

              //Loop around each item on the sale and process each in turn
              foreach ($_SESSION['Items'.$identifier]->LineItems as $OrderLine) {
                 /* Update location stock records if not a dummy stock item
                 need the MBFlag later too so save it to $MBFlag */
                $Result = DB_query("SELECT mbflag FROM stockmaster WHERE stockid = '" . $OrderLine->StockID . "'",$db);
                $myrow = DB_fetch_row($Result);
                $MBFlag = $myrow[0];
                if ($MBFlag=='B' OR $MBFlag=='M') {
                  $Assembly = False;

                  /* Need to get the current location quantity
                  will need it later for the stock movement */
                  $SQL="SELECT locstock.quantity
                          FROM locstock
                          WHERE locstock.stockid='" . $OrderLine->StockID . "'
                          AND loccode= '" . $_SESSION['Items'.$identifier]->Location . "'";
                  $ErrMsg = _('WARNING') . ': ' . _('Could not retrieve current location stock');
                  $Result = DB_query($SQL, $db, $ErrMsg);

                  if (DB_num_rows($Result)==1){
                    $LocQtyRow = DB_fetch_row($Result);
                    $QtyOnHandPrior = $LocQtyRow[0];
                  } else {
                    /* There must be some error this should never happen */
                    $QtyOnHandPrior = 0;
                  }

                  $SQL = "UPDATE locstock
                        SET quantity = locstock.quantity - " . $OrderLine->Quantity . "
                        WHERE locstock.stockid = '" . $OrderLine->StockID . "'
                        AND loccode = '" . $_SESSION['Items'.$identifier]->Location . "'";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated because');
                  $DbgMsg = _('The following SQL to update the location stock record was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                } else if ($MBFlag=='A'){ /* its an assembly */
                  /*Need to get the BOM for this part and make
                  stock moves for the components then update the Location stock balances */
                  $Assembly=True;
                  $StandardCost =0; /*To start with - accumulate the cost of the comoponents for use in journals later on */
                  $SQL = "SELECT bom.component,
                      bom.quantity,
                      stockmaster.materialcost+stockmaster.labourcost+stockmaster.overheadcost AS standard
                      FROM bom,
                        stockmaster
                      WHERE bom.component=stockmaster.stockid
                      AND bom.parent='" . $OrderLine->StockID . "'
                      AND bom.effectiveto > '" . Date('Y-m-d') . "'
                      AND bom.effectiveafter < '" . Date('Y-m-d') . "'";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Could not retrieve assembly components from the database for'). ' '. $OrderLine->StockID . _('because').' ';
                  $DbgMsg = _('The SQL that failed was');
                  $AssResult = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                  while ($AssParts = DB_fetch_array($AssResult,$db)){

                    $StandardCost += ($AssParts['standard'] * $AssParts['quantity']) ;
                    /* Need to get the current location quantity
                    will need it later for the stock movement */
                    $SQL="SELECT locstock.quantity
                            FROM locstock
                            WHERE locstock.stockid='" . $AssParts['component'] . "'
                            AND loccode= '" . $_SESSION['Items'.$identifier]->Location . "'";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Can not retrieve assembly components location stock quantities because ');
                    $DbgMsg = _('The SQL that failed was');
                    $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                    if (DB_num_rows($Result)==1){
                      $LocQtyRow = DB_fetch_row($Result);
                      $QtyOnHandPrior = $LocQtyRow[0];
                    } else {
                      /*There must be some error this should never happen */
                      $QtyOnHandPrior = 0;
                    }
                    if (empty($AssParts['standard'])) {
                      $AssParts['standard']=0;
                    }
                    $SQL = "INSERT INTO stockmoves (stockid,
                                    type,
                                    transno,
                                    loccode,
                                    trandate,
                                    debtorno,
                                    branchcode,
                                    prd,
                                    reference,
                                    qty,
                                    standardcost,
                                    show_on_inv_crds,
                                    newqoh
                      ) VALUES (
                                    '" . $AssParts['component'] . "',
                                     10,
                                    '" . $InvoiceNo . "',
                                    '" . $_SESSION['Items'.$identifier]->Location . "',
                                    '" . $DefaultDispatchDate . "',
                                    '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                                    '" . $_SESSION['Items'.$identifier]->Branch . "',
                                    '" . $PeriodNo . "',
                                    '" . _('Assembly') . ': ' . $OrderLine->StockID . ' ' . _('Order') . ': ' . $OrderNo . "',
                                    '" . -$AssParts['quantity'] * $OrderLine->Quantity . "',
                                    '" . $AssParts['standard'] . "',
                                    0,
                                    newqoh-" . ($AssParts['quantity'] * $OrderLine->Quantity) . " )";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records for the assembly components of'). ' '. $OrderLine->StockID . ' ' . _('could not be inserted because');
                    $DbgMsg = _('The following SQL to insert the assembly components stock movement records was used');
                    $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);


                    $SQL = "UPDATE locstock
                        SET quantity = locstock.quantity - " . $AssParts['quantity'] * $OrderLine->Quantity . "
                        WHERE locstock.stockid = '" . $AssParts['component'] . "'
                        AND loccode = '" . $_SESSION['Items'.$identifier]->Location . "'";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Location stock record could not be updated for an assembly component because');
                    $DbgMsg = _('The following SQL to update the locations stock record for the component was used');
                    $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                  } /* end of assembly explosion and updates */

                  /*Update the cart with the recalculated standard cost from the explosion of the assembly's components*/
                  $_SESSION['Items'.$identifier]->LineItems[$OrderLine->LineNumber]->StandardCost = $StandardCost;
                  $OrderLine->StandardCost = $StandardCost;
                } /* end of its an assembly */

                // Insert stock movements - with unit cost
                $LocalCurrencyPrice = ($OrderLine->Price / $ExRate);

                if (empty($OrderLine->StandardCost)) {
                  $OrderLine->StandardCost=0;
                }
                if ($MBFlag=='B' OR $MBFlag=='M'){
                  $SQL = "INSERT INTO stockmoves (stockid,
                                  type,
                                  transno,
                                  loccode,
                                  trandate,
                                  debtorno,
                                  branchcode,
                                  price,
                                  prd,
                                  reference,
                                  qty,
                                  discountpercent,
                                  standardcost,
                                  newqoh,
                                  narrative )
                      VALUES ('" . $OrderLine->StockID . "',
                          10,
                          '" . $InvoiceNo . "',
                          '" . $_SESSION['Items'.$identifier]->Location . "',
                          '" . $DefaultDispatchDate . "',
                          '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                          '" . $_SESSION['Items'.$identifier]->Branch . "',
                          '" . $LocalCurrencyPrice . "',
                          '" . $PeriodNo . "',
                          '" . $OrderNo . "',
                          '" . -$OrderLine->Quantity . "',
                          '" . $OrderLine->DiscountPercent . "',
                          '" . $OrderLine->StandardCost . "',
                          '" . ($QtyOnHandPrior - $OrderLine->Quantity) . "',
                          '" . $OrderLine->Narrative . "' )";
                } else {
                // its an assembly or dummy and assemblies/dummies always have nil stock (by definition they are made up at the time of dispatch  so new qty on hand will be nil
                  if (empty($OrderLine->StandardCost)) {
                    $OrderLine->StandardCost = 0;
                  }
                  $SQL = "INSERT INTO stockmoves (stockid,
                                  type,
                                  transno,
                                  loccode,
                                  trandate,
                                  debtorno,
                                  branchcode,
                                  price,
                                  prd,
                                  reference,
                                  qty,
                                  discountpercent,
                                  standardcost,
                                  narrative )
                      VALUES ('" . $OrderLine->StockID . "',
                              10,
                              '" . $InvoiceNo . "',
                              '" . $_SESSION['Items'.$identifier]->Location . "',
                              '" . $DefaultDispatchDate . "',
                              '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                              '" . $_SESSION['Items'.$identifier]->Branch . "',
                              '" . $LocalCurrencyPrice . "',
                              '" . $PeriodNo . "',
                              '" . $OrderNo . "',
                              '" . -$OrderLine->Quantity . "',
                              '" . $OrderLine->DiscountPercent . "',
                              '" . $OrderLine->StandardCost . "',
                              '" . $OrderLine->Narrative . "')";
                }

                $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Stock movement records could not be inserted because');
                $DbgMsg = _('The following SQL to insert the stock movement records was used');
                $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

              /*Get the ID of the StockMove... */
                $StkMoveNo = DB_Last_Insert_ID($db,'stockmoves','stkmoveno');

              /*Insert the taxes that applied to this line */
                foreach ($OrderLine->Taxes as $Tax) {

                  $SQL = "INSERT INTO stockmovestaxes (stkmoveno,
                            taxauthid,
                            taxrate,
                            taxcalculationorder,
                            taxontax)
                      VALUES ('" . $StkMoveNo . "',
                        '" . $Tax->TaxAuthID . "',
                        '" . $Tax->TaxRate . "',
                        '" . $Tax->TaxCalculationOrder . "',
                        '" . $Tax->TaxOnTax . "')";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('Taxes and rates applicable to this invoice line item could not be inserted because');
                  $DbgMsg = _('The following SQL to insert the stock movement tax detail records was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                } //end for each tax for the line

                /* Controlled stuff not currently handled by counter orders

                Insert the StockSerialMovements and update the StockSerialItems  for controlled items

                if ($OrderLine->Controlled ==1){
                  foreach($OrderLine->SerialItems as $Item){
                          //We need to add the StockSerialItem record and the StockSerialMoves as well

                    $SQL = "UPDATE stockserialitems
                        SET quantity= quantity - " . $Item->BundleQty . "
                        WHERE stockid='" . $OrderLine->StockID . "'
                        AND loccode='" . $_SESSION['Items'.$identifier]->Location . "'
                        AND serialno='" . $Item->BundleRef . "'";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock item record could not be updated because');
                    $DbgMsg = _('The following SQL to update the serial stock item record was used');
                    $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);

                    // now insert the serial stock movement

                    $SQL = "INSERT INTO stockserialmoves (stockmoveno,
                              stockid,
                              serialno,
                              moveqty)
                      VALUES (" . $StkMoveNo . ",
                        '" . $OrderLine->StockID . "',
                        '" . $Item->BundleRef . "',
                        " . -$Item->BundleQty . ")";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The serial stock movement record could not be inserted because');
                    $DbgMsg = _('The following SQL to insert the serial stock movement records was used');
                    $Result = DB_query($SQL, $db, $ErrMsg, $DbgMsg, true);
                  }// foreach controlled item in the serialitems array
                } //end if the orderline is a controlled item

                End of controlled stuff not currently handled by counter orders
                */


              /*Insert Sales Analysis records */

                $SQL="SELECT COUNT(*),
                    salesanalysis.stockid,
                    salesanalysis.stkcategory,
                    salesanalysis.cust,
                    salesanalysis.custbranch,
                    salesanalysis.area,
                    salesanalysis.periodno,
                    salesanalysis.typeabbrev,
                    salesanalysis.salesperson
                  FROM salesanalysis,
                    custbranch,
                    stockmaster
                  WHERE salesanalysis.stkcategory=stockmaster.categoryid
                  AND salesanalysis.stockid=stockmaster.stockid
                  AND salesanalysis.cust=custbranch.debtorno
                  AND salesanalysis.custbranch=custbranch.branchcode
                  AND salesanalysis.area=custbranch.area
                  AND salesanalysis.salesperson=custbranch.salesman
                  AND salesanalysis.typeabbrev ='" . $_SESSION['Items'.$identifier]->DefaultSalesType . "'
                  AND salesanalysis.periodno='" . $PeriodNo . "'
                  AND salesanalysis.cust " . LIKE . " '" . $_SESSION['Items'.$identifier]->DebtorNo . "'
                  AND salesanalysis.custbranch " . LIKE . " '" . $_SESSION['Items'.$identifier]->Branch . "'
                  AND salesanalysis.stockid " . LIKE . " '" . $OrderLine->StockID . "'
                  AND salesanalysis.budgetoractual=1
                  GROUP BY salesanalysis.stockid,
                    salesanalysis.stkcategory,
                    salesanalysis.cust,
                    salesanalysis.custbranch,
                    salesanalysis.area,
                    salesanalysis.periodno,
                    salesanalysis.typeabbrev,
                    salesanalysis.salesperson";

                $ErrMsg = _('The count of existing Sales analysis records could not run because');
                $DbgMsg = _('SQL to count the no of sales analysis records');
                $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                $myrow = DB_fetch_row($Result);

                if ($myrow[0]>0){  /*Update the existing record that already exists */

                  $SQL = "UPDATE salesanalysis
                        SET amt=amt+" . ($OrderLine->Price * $OrderLine->Quantity / $ExRate) . ",
                          cost=cost+" . ($OrderLine->StandardCost * $OrderLine->Quantity) . ",
                          qty=qty +" . $OrderLine->Quantity . ",
                          disc=disc+" . ($OrderLine->DiscountPercent * $OrderLine->Price * $OrderLine->Quantity / $ExRate) . "
                        WHERE salesanalysis.area='" . $myrow[5] . "'
                          AND salesanalysis.salesperson='" . $myrow[8] . "'
                          AND typeabbrev ='" . $_SESSION['Items'.$identifier]->DefaultSalesType . "'
                          AND periodno = '" . $PeriodNo . "'
                          AND cust " . LIKE . " '" . $_SESSION['Items'.$identifier]->DebtorNo . "'
                          AND custbranch " . LIKE . " '" . $_SESSION['Items'.$identifier]->Branch . "'
                          AND stockid " . LIKE . " '" . $OrderLine->StockID . "'
                          AND salesanalysis.stkcategory ='" . $myrow[2] . "'
                          AND budgetoractual=1";

                } else { /* insert a new sales analysis record */

                  $SQL = "INSERT INTO salesanalysis (	typeabbrev,
                                    periodno,
                                    amt,
                                    cost,
                                    cust,
                                    custbranch,
                                    qty,
                                    disc,
                                    stockid,
                                    area,
                                    budgetoractual,
                                    salesperson,
                                    stkcategory	)
                    SELECT '" . $_SESSION['Items'.$identifier]->DefaultSalesType . "',
                      '" . $PeriodNo . "',
                      '" . ($OrderLine->Price * $OrderLine->Quantity / $ExRate) . "',
                      '" . ($OrderLine->StandardCost * $OrderLine->Quantity) . "',
                      '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                      '" . $_SESSION['Items'.$identifier]->Branch . "',
                      '" . $OrderLine->Quantity . "',
                      '" . ($OrderLine->DiscountPercent * $OrderLine->Price * $OrderLine->Quantity / $ExRate) . "',
                      '" . $OrderLine->StockID . "',
                      custbranch.area,
                      1,
                      custbranch.salesman,
                      stockmaster.categoryid
                    FROM stockmaster,
                      custbranch
                    WHERE stockmaster.stockid = '" . $OrderLine->StockID . "'
                    AND custbranch.debtorno = '" . $_SESSION['Items'.$identifier]->DebtorNo . "'
                    AND custbranch.branchcode='" . $_SESSION['Items'.$identifier]->Branch . "'";
                }

                $ErrMsg = _('Sales analysis record could not be added or updated because');
                $DbgMsg = _('The following SQL to insert the sales analysis record was used');
                $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

              /* If GLLink_Stock then insert GLTrans to credit stock and debit cost of sales at standard cost*/

                if ($_SESSION['CompanyRecord']['gllink_stock']==1 AND $OrderLine->StandardCost !=0){

              /*first the cost of sales entry*/

                  $SQL = "INSERT INTO gltrans (	type,
                                  typeno,
                                  trandate,
                                  periodno,
                                  account,
                                  narrative,
                                  amount)
                              VALUES ( 10,
                                  '" . $InvoiceNo . "',
                                  '" . $DefaultDispatchDate . "',
                                  '" . $PeriodNo . "',
                                  '" . GetCOGSGLAccount($Area, $OrderLine->StockID, $_SESSION['Items'.$identifier]->DefaultSalesType, $db) . "',
                                  '" . $_SESSION['Items'.$identifier]->DebtorNo . " - " . $OrderLine->StockID . " x " . $OrderLine->Quantity . " @ " . $OrderLine->StandardCost . "',
                                  '" . $OrderLine->StandardCost * $OrderLine->Quantity . "')";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost of sales GL posting could not be inserted because');
                  $DbgMsg = _('The following SQL to insert the GLTrans record was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

              /*now the stock entry*/
                  $StockGLCode = GetStockGLCode($OrderLine->StockID,$db);

                  $SQL = "INSERT INTO gltrans (type,
                                typeno,
                                trandate,
                                periodno,
                                account,
                                narrative,
                                amount )
                              VALUES ( 10,
                                '" . $InvoiceNo . "',
                                '" . $DefaultDispatchDate . "',
                                '" . $PeriodNo . "',
                                '" . $StockGLCode['stockact'] . "',
                                '" . $_SESSION['Items'.$identifier]->DebtorNo . " - " . $OrderLine->StockID . " x " . $OrderLine->Quantity . " @ " . $OrderLine->StandardCost . "',
                                '" . (-$OrderLine->StandardCost * $OrderLine->Quantity) . "')";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock side of the cost of sales GL posting could not be inserted because');
                  $DbgMsg = _('The following SQL to insert the GLTrans record was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                } /* end of if GL and stock integrated and standard cost !=0 */

                if ($_SESSION['CompanyRecord']['gllink_debtors']==1 AND $OrderLine->Price !=0){

              //Post sales transaction to GL credit sales
                  $SalesGLAccounts = GetSalesGLAccount($Area, $OrderLine->StockID, $_SESSION['Items'.$identifier]->DefaultSalesType, $db);

                  $SQL = "INSERT INTO gltrans (type,
                                typeno,
                                trandate,
                                periodno,
                                account,
                                narrative,
                                amount )
                              VALUES ( 10,
                                '" . $InvoiceNo . "',
                                '" . $DefaultDispatchDate . "',
                                '" . $PeriodNo . "',
                                '" . $SalesGLAccounts['salesglcode'] . "',
                                '" . $_SESSION['Items'.$identifier]->DebtorNo . " - " . $OrderLine->StockID . " x " . $OrderLine->Quantity . " @ " . $OrderLine->Price . "',
                                '" . (-$OrderLine->Price * $OrderLine->Quantity/$ExRate) . "')";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales GL posting could not be inserted because');
                  $DbgMsg = '<br />' ._('The following SQL to insert the GLTrans record was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                  if ($OrderLine->DiscountPercent !=0){

                    $SQL = "INSERT INTO gltrans (type,
                                  typeno,
                                  trandate,
                                  periodno,
                                  account,
                                  narrative,
                                  amount )
                                  VALUES ( 10,
                                    '" . $InvoiceNo . "',
                                    '" . $DefaultDispatchDate . "',
                                    '" . $PeriodNo . "',
                                    '" . $SalesGLAccounts['discountglcode'] . "',
                                    '" . $_SESSION['Items'.$identifier]->DebtorNo . " - " . $OrderLine->StockID . " @ " . ($OrderLine->DiscountPercent * 100) . "%',
                                    '" . ($OrderLine->Price * $OrderLine->Quantity * $OrderLine->DiscountPercent/$ExRate) . "')";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The sales discount GL posting could not be inserted because');
                    $DbgMsg = _('The following SQL to insert the GLTrans record was used');
                    $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                  } /*end of if discount !=0 */
                } /*end of if sales integrated with debtors */
              } /*end of OrderLine loop */

              if ($_SESSION['CompanyRecord']['gllink_debtors']==1){

            /*Post debtors transaction to GL debit debtors, credit freight re-charged and credit sales */
                if (($_SESSION['Items'.$identifier]->total + filter_number_format($_POST['TaxTotal'])) !=0) {
                  $SQL = "INSERT INTO gltrans (	type,
                                  typeno,
                                  trandate,
                                  periodno,
                                  account,
                                  narrative,
                                  amount	)
                                VALUES ( 10,
                                  '" . $InvoiceNo . "',
                                  '" . $DefaultDispatchDate . "',
                                  '" . $PeriodNo . "',
                                  '" . $_SESSION['CompanyRecord']['debtorsact'] . "',
                                  '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                                  '" . (($_SESSION['Items'.$identifier]->total + filter_number_format($_POST['TaxTotal']))/$ExRate) . "')";

                  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The total debtor GL posting could not be inserted because');
                  $DbgMsg = _('The following SQL to insert the total debtors control GLTrans record was used');
                  $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                }


                foreach ( $_SESSION['Items'.$identifier]->TaxTotals as $TaxAuthID => $TaxAmount){
                  if ($TaxAmount !=0 ){
                    $SQL = "INSERT INTO gltrans (	type,
                                    typeno,
                                    trandate,
                                    periodno,
                                    account,
                                    narrative,
                                    amount	)
                                  VALUES ( 10,
                                    '" . $InvoiceNo . "',
                                    '" . $DefaultDispatchDate . "',
                                    '" . $PeriodNo . "',
                                    '" . $_SESSION['Items'.$identifier]->TaxGLCodes[$TaxAuthID] . "',
                                    '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                                    '" . (-$TaxAmount/$ExRate) . "')";

                    $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The tax GL posting could not be inserted because');
                    $DbgMsg = _('The following SQL to insert the GLTrans record was used');
                    $Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                  }
                }
              
                EnsureGLEntriesBalance(10,$InvoiceNo,$db);

                /*Also if GL is linked to debtors need to process the debit to bank and credit to debtors for the payment */
                /*Need to figure out the cross rate between customer currency and bank account currency */

                if ($_POST['AmountPaid']!=0){
                  $ReceiptNumber = GetNextTransNo(12,$db);
                  $SQL="INSERT INTO gltrans (type,
                                typeno,
                                trandate,
                                periodno,
                                account,
                                narrative,
                                amount)
                      VALUES (12,
                        '" . $ReceiptNumber . "',
                        '" . $DefaultDispatchDate . "',
                        '" . $PeriodNo . "',
                        '" . $_POST['BankAccount'] . "',
                        '" . $_SESSION['Items'.$identifier]->LocationName . ' ' . _('Counter Sale') . ' ' . $InvoiceNo . "',
                        '" . (filter_number_format($_POST['AmountPaid'])/$ExRate) . "')";
                  $DbgMsg = _('The SQL that failed to insert the GL transaction for the bank account debit was');
                  $ErrMsg = _('Cannot insert a GL transaction for the bank account debit');
                  $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                  /* Now Credit Debtors account with receipt */
                  $SQL="INSERT INTO gltrans ( type,
                      typeno,
                      trandate,
                      periodno,
                      account,
                      narrative,
                      amount)
                  VALUES (12,
                    '" . $ReceiptNumber . "',
                    '" . $DefaultDispatchDate . "',
                    '" . $PeriodNo . "',
                    '" . $_SESSION['CompanyRecord']['debtorsact'] . "',
                    '" . $_SESSION['Items'.$identifier]->LocationName . ' ' . _('Counter Sale') . ' ' . $InvoiceNo . "',
                    '" . -(filter_number_format($_POST['AmountPaid'])/$ExRate) . "')";
                  $DbgMsg = _('The SQL that failed to insert the GL transaction for the debtors account credit was');
                  $ErrMsg = _('Cannot insert a GL transaction for the debtors account credit');
                  $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
                }//amount paid we not zero
                
                EnsureGLEntriesBalance(12,$ReceiptNumber,$db);
                
              } /*end of if Sales and GL integrated */
              if ($_POST['AmountPaid']!=0){
                if (!isset($ReceiptNumber)){
                  $ReceiptNumber = GetNextTransNo(12,$db);
                }
                //Now need to add the receipt banktrans record
                //First get the account currency that it has been banked into
                $result = DB_query("SELECT rate FROM currencies
                          INNER JOIN bankaccounts 
                          ON currencies.currabrev=bankaccounts.currcode
                          WHERE bankaccounts.accountcode='" . $_POST['BankAccount'] . "'",$db);
                $myrow = DB_fetch_row($result);
                $BankAccountExRate = $myrow[0];

                /*
                 * Some interesting exchange rate conversion going on here
                 * Say :
                 * The business's functional currency is NZD
                 * Customer location counter sales are in AUD - 1 NZD = 0.80 AUD
                 * Banking money into a USD account - 1 NZD = 0.68 USD
                 *
                 * Customer sale is for $100 AUD
                 * GL entries  conver the AUD 100 to NZD  - 100 AUD / 0.80 = $125 NZD
                 * Banktrans entries convert the AUD 100 to USD using 100/0.8 * 0.68
                */

                //insert the banktrans record in the currency of the bank account

                $SQL="INSERT INTO banktrans (type,
                      transno,
                      bankact,
                      ref,
                      exrate,
                      functionalexrate,
                      transdate,
                      banktranstype,
                      amount,
                      currcode)
                    VALUES (12,
                      '" . $ReceiptNumber . "',
                      '" . $_POST['BankAccount'] . "',
                      '" . $_SESSION['Items'.$identifier]->LocationName . ' ' . _('Counter Sale') . ' ' . $InvoiceNo . "',
                      '" . $ExRate . "',
                      '" . $BankAccountExRate . "',
                      '" . $DefaultDispatchDate . "',
                      '" . $_POST['PaymentMethod'] . "',
                      '" . filter_number_format($_POST['AmountPaid']) * $BankAccountExRate . "',
                      '" . $_SESSION['Items'.$identifier]->DefaultCurrency . "')";

                $DbgMsg = _('The SQL that failed to insert the bank account transaction was');
                $ErrMsg = _('Cannot insert a bank transaction');
                $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                //insert a new debtortrans for the receipt

                $SQL = "INSERT INTO debtortrans (transno,
                        type,
                        debtorno,
                        trandate,
                        inputdate,
                        prd,
                        reference,
                        rate,
                        ovamount,
                        alloc,
                        invtext,
                        settled)
                    VALUES ('" . $ReceiptNumber . "',
                      12,
                      '" . $_SESSION['Items'.$identifier]->DebtorNo . "',
                      '" . $DefaultDispatchDate . "',
                      '" . date('Y-m-d H-i-s') . "',
                      '" . $PeriodNo . "',
                      '" . $InvoiceNo . "',
                      '" . $ExRate . "',
                      '" . -filter_number_format($_POST['AmountPaid']) . "',
                      '" . -filter_number_format($_POST['AmountPaid']) . "',
                      '" . $_SESSION['Items'.$identifier]->LocationName . ' ' . _('Counter Sale') ."',
                      '1')";

                $DbgMsg = _('The SQL that failed to insert the customer receipt transaction was');
                $ErrMsg = _('Cannot insert a receipt transaction against the customer because') ;
                $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                $ReceiptDebtorTransID = DB_Last_Insert_ID($db,'debtortrans','id');

                $SQL = "UPDATE debtorsmaster SET lastpaiddate = '" . $DefaultDispatchDate . "',
                                lastpaid='" . filter_number_format($_POST['AmountPaid']) . "'
                            WHERE debtorsmaster.debtorno='" . $_SESSION['Items'.$identifier]->DebtorNo . "'";

                $DbgMsg = _('The SQL that failed to update the date of the last payment received was');
                $ErrMsg = _('Cannot update the customer record for the date of the last payment received because');
                $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

                //and finally add the allocation record between receipt and invoice

                $SQL = "INSERT INTO custallocns (	amt,
                                  datealloc,
                                  transid_allocfrom,
                                  transid_allocto )
                            VALUES  ('" . filter_number_format($_POST['AmountPaid']) . "',
                                '" . $DefaultDispatchDate . "',
                                 '" . $ReceiptDebtorTransID . "',
                                 '" . $DebtorTransID . "')";
                $DbgMsg = _('The SQL that failed to insert the allocation of the receipt to the invoice was');
                $ErrMsg = _('Cannot insert the customer allocation of the receipt to the invoice because');
                $result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);
              } //end if $_POST['AmountPaid']!= 0

              DB_Txn_Commit($db);
            // *************************************************************************
            //   E N D   O F   I N V O I C E   S Q L   P R O C E S S I N G
            // *************************************************************************

              unset($_SESSION['Items'.$identifier]->LineItems);
              unset($_SESSION['Items'.$identifier]);

              echo prnMsg( _('Invoice number'). ' '. $InvoiceNo .' '. _('processed'), 'success');

              echo '<br /><div class="centre">';

              if ($_SESSION['InvoicePortraitFormat']==0){
                echo '<img src="'.$rootpath.'/css/'.$theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . '<a target="_blank" href="'.$rootpath.'/PrintCustTrans.php?FromTransNo='.$InvoiceNo.'&InvOrCredit=Invoice&PrintPDF=True">'. _('Print this invoice'). ' (' . _('Landscape') . ')</a><br /><br />';
              } else {
                echo '<img src="'.$rootpath.'/css/'.$theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . '<a target="_blank" href="'.$rootpath.'/PrintCustTransPortrait.php?FromTransNo='.$InvoiceNo.'&InvOrCredit=Invoice&PrintPDF=True">'. _('Print this invoice'). ' (' . _('Portrait') . ')</a><br /><br />';
              }
              echo '<br /><br /><a href="' .htmlspecialchars($_SERVER['PHP_SELF']) . '">' . _('Start a new Counter Sale') . '</a></div>';

            }
            
            
            
            //=====Get the products for the sales (end)=====
            
           
            
            
            
            
            
            
            
            
            
            
            //=====Get Latest Customer ID of EMP (Start)=====
            if ($_SESSION['AutoDebtorNo']== 1) {
                $LatestDebtorNo = GetNextTransNo(500, $db);
            }
            //=====Get Latest Customer ID of EMP (End)=====
            
            $sqlAddNewCustomer = "INSERT INTO debtorsmaster (debtorno,
                                                            name,
                                                            address1,
                                                            address2,
                                                            address3,
                                                            address4,
                                                            address5,
                                                            address6,
                                                            currcode,
                                                            clientsince,
                                                            holdreason,
                                                            paymentterms,
                                                            discount,
                                                            discountcode,
                                                            pymtdiscount,
                                                            creditlimit,
                                                            salestype,
                                                            invaddrbranch,
                                                            taxref,
                                                            customerpoline,
                                                            typeid)
                                                      VALUES ('" . $LatestDebtorNo ."',
                                                        '" . $zencartCustomerName ."',
                                                        '" . $zencartCustomerCompany ."',
                                                        '" . $zencartCustomerStreet ."',
                                                        '" . $zencartCustomerSuburb . "',
                                                        '" . $zencartCustomerPostcode . " " . $zencartCustomerCity . "',
                                                        '" . $zencartCustomerState . "',
                                                        '[Via E-Commerce]',
                                                        'MYR',
                                                        NOW(),
                                                        '1',
                                                        'NA',
                                                        '0',
                                                        '0',
                                                        '0',
                                                        '999999',
                                                        'NE',
                                                        '0',
                                                        '',
                                                        '0',
                                                        '1'
                                                        )";
            $ErrMsgAddNewCustomer = _('The customer') . ' ' . $zencartCustomerName . ' ' . _('could not be added to EMP database because');
            $DbgMsgAddNewCustomer = _('The SQL that failed was');
            $resultAddNewCustomer = DB_query($sqlAddNewCustomer, $db, $ErrMsgAddNewCustomer, $DbgMsgAddNewCustomer);
            
            
            $sqlAddCustomerBranch = "INSERT INTO custbranch (branchcode,
                                                            debtorno,
                                                            brname,
                                                            braddress1,
                                                            braddress2,
                                                            braddress3,
                                                            braddress4,
                                                            braddress5,
                                                            braddress6,
                                                            lat,
                                                            lng,
                                                            specialinstructions,
                                                            estdeliverydays,
                                                            fwddate,
                                                            salesman,
                                                            phoneno,
                                                            faxno,
                                                            contactname,
                                                            area,
                                                            email,
                                                            taxgroupid,
                                                            defaultlocation,
                                                            brpostaddr1,
                                                            brpostaddr2,
                                                            brpostaddr3,
                                                            brpostaddr4,
                                                            disabletrans,
                                                            defaultshipvia,
                                                            custbranchcode,
                                                            deliverblind)
                                                        VALUES ('" . $LatestDebtorNo . "',
                                                          '" . $LatestDebtorNo . "',
                                                          '" . $zencartCustomerName ."',
                                                          '" . $zencartCustomerCompany ."',
                                                          '" . $zencartCustomerStreet ."',
                                                          '" . $zencartCustomerSuburb . "',
                                                          '" . $zencartCustomerPostcode . " " . $zencartCustomerCity . "',
                                                          '" . $zencartCustomerState . "',
                                                          '[Via E-Commerce]',
                                                          '0.000000',
                                                          '0.000000',
                                                          '',
                                                          '0',
                                                          '0',
                                                          'ECOMM',
                                                          '" . $zencartCustomerTel . "',
                                                          '" . $zencartCustomerFax . "',
                                                          '" . $zencartCustomerName . "',
                                                          'ECOMM',
                                                          '" . $zencartCustomerEmail . "',
                                                          '1',
                                                          '" . $empLocation . "',
                                                          '',
                                                          '',
                                                          '',
                                                          '',
                                                          '0',
                                                          '1',
                                                          '" .$zencartCustomerID. "',
                                                          '1')";
            $ErrMsgAddCustomerBranch = _('The customer branch') . ' ' . $zencartCustomerName . ' ' . _('could not be added to EMP database because');
            $DbgMsgAddCustomerBranch = _('The SQL that failed was');
            $resultAddCustomerBranch = DB_query($sqlAddCustomerBranch, $db, $ErrMsgAddCustomerBranch, $DbgMsgAddCustomerBranch);

            prnMsg(_('Customer') . ' ' . $zencartCustomerName . ' ' . _(' has been successfully added to EMP database'), 'success');
              
          }else{
                
            $sqlUpdateCustomerBranch = "UPDATE custbranch SET brname = '" . $zencartCustomerName ."',
                                                            braddress1 = '" . $zencartCustomerCompany ."',
                                                            braddress2 = '" . $zencartCustomerStreet ."',
                                                            braddress3 =  '" . $zencartCustomerSuburb . "',
                                                            braddress4 = '" . $zencartCustomerPostcode . " " . $zencartCustomerCity . "',
                                                            braddress5 = '" . $zencartCustomerState . "'
                                                      WHERE custbranchcode = '" . $zencartCustomerID . "'";                
            $ErrMsgUpdateCustomerBranch = _('The customer branch') . ' ' . $zencartCustomerName . ' ' . _('could not be updated to EMP database because');
            $DbgMsgUpdateCustomerBranch = _('The SQL that failed was');
            $resultUpdateCustomerBranch = DB_query($sqlUpdateCustomerBranch, $db, $ErrMsgUpdateCustomerBranch, $DbgMsgUpdateCustomerBranch);

            $sqlGetEMPDebtorNo = "SELECT debtorno FROM custbranch WHERE custbranchcode = '" . $zencartCustomerID . "'";  
            $resultGetEMPDebtorNo = DB_query($sqlGetEMPDebtorNo,$db);
            $myrowGetEMPDebtorNo = DB_fetch_array($resultGetEMPDebtorNo);
            $empDebtorNo = $myrowGetEMPDebtorNo['debtorno'];

            $sqlUpdateCustomer = "UPDATE debtorsmaster SET name = '" . $zencartCustomerName ."',
                                                            address1 = '" . $zencartCustomerCompany ."',
                                                            address2 = '" . $zencartCustomerStreet ."',
                                                            address3 = '" . $zencartCustomerSuburb . "',
                                                            address4 = '" . $zencartCustomerPostcode . " " . $zencartCustomerCity . "',
                                                            address5 = '" . $zencartCustomerState . "'
                                                WHERE debtorno = '" . $empDebtorNo . "'";    
            $ErrMsgUpdateCustomer = _('The customer') . ' ' . $zencartCustomerName . ' ' . _('could not be updated to EMP database because');
            $DbgMsgUpdateCustomer = _('The SQL that failed was');
            $resultUpdateCustomer = DB_query($sqlUpdateCustomer, $db, $ErrMsgUpdateCustomer, $DbgMsgUpdateCustomer);
            
            prnMsg(_('Customer') . ' ' . $zencartCustomerName . ' ' . _(' has been successfully updated to EMP database'), 'success');
          }
      }
  //=====Add Sales (End)=====
}
      
echo '<tr><td>';
		echo '<div class="centre"><input type="submit" name="sync_sales" value="Synchronise Sales from Zencart"></div>';
echo '</td></tr>';	
echo '</table>';

	
	
include('includes/footer.inc'); ?>