<?php

$CompanyName = 'Datacom';

function Synchro_SendData() {
	include("config.inc.php");
	
	//Set Time Execution Limit
	set_time_limit (0);

	//Local Connection
	$local_connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($config['dbName'],$local_connection) or die("Could not find local DB");
	
	//Destination/Remote Connection
	$dest_connection = GetRemoteConnection($local_connection);
	
	$sub_query = " Select Synchro_ID, Upper(Synchro_TableName), Synchro_TransID, Synchro_TransCode, Upper(Synchro_State), Upper(Synchro_BranchCode) ".
				 " From SynchroData ".
				 " Where Synchro_Flag In ('F','P') ".
				 " Order By Synchro_ID ";
										 
	//echo $sub_query;exit;
	$sub_result=mysql_query($sub_query,$local_connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){
	
		$vSynchroTableActive = 0;
		$vSynchroAllBranches = 0;
		$sub_query1 = " Select ifNull(SynchroTable_Active,0), ifNull(SynchroTable_AllBranches,0) ".
					  " From SynchroTables ".
					  " Where upper(SynchroTable_Name) = upper('".$sub_rows[1]."')";
		
		$sub_result1 = selectData($local_connection, $sub_query1);			
		$vSynchroTableActive = $sub_result1[0];
		$vSynchroAllBranches = $sub_result1[1];
			
		If ($vSynchroTableActive == 1) {
			$vResult = F_Synchro($sub_rows[0], $sub_rows[1], $sub_rows[2], $sub_rows[3], $sub_rows[4], $sub_rows[5], $vSynchroAllBranches, $local_connection, $dest_connection);
		}	
	}

}


function Synchro_ReceiveData() {
	include("config.inc.php");
	
	//Set Time Execution Limit
	set_time_limit (0);

	//Local Connection
	$local_connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($config['dbName'],$local_connection) or die("Could not find local DB");
	
	//Destination/Remote Connection
	$dest_connection = GetRemoteConnection($local_connection);
	
	$sub_query  = " Select Setup_Branch From Setup ";
	$sub_result = selectData($local_connection, $sub_query);
	$vBranchCode = $sub_result[0];
	
	$sub_query = " Select Synchro_ID, Upper(Synchro_TableName), Synchro_TransID, Synchro_TransCode, Upper(Synchro_State), Upper(Synchro_BranchCode) ".
				 " From SynchroData ".
				 " Where Synchro_Flag In ('F','P') ".
				 " And Upper(ifNull(Synchro_BranchCode,'".$vBranchCode."')) = Upper('".$vBranchCode."') ".
				 " Order By Synchro_ID ";
										 
	//echo $sub_query;exit;
	$sub_result=mysql_query($sub_query,$dest_connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){
	
		$vSynchroTableActive = 0;
		$vSynchroAllBranches = 0;
		$sub_query1 = " Select ifNull(SynchroTable_Receive,0), ifNull(SynchroTable_AllBranches,0) ".
					  " From SynchroTables ".
					  " Where upper(SynchroTable_Name) = upper('".$sub_rows[1]."')";
		
		$sub_result1 = selectData($local_connection, $sub_query1);
		$vSynchroTableActive = $sub_result1[0];
		//$vSynchroAllBranches = $sub_result1[1];
			
		If ($vSynchroTableActive == 1) {
			$vResult = F_Synchro($sub_rows[0], $sub_rows[1], $sub_rows[2], $sub_rows[3], $sub_rows[4], $sub_rows[5], $vSynchroAllBranches, $dest_connection, $local_connection);
		}	
	}

}

function F_Synchro($PSynchroID, $PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	$vResult = 'F';
	
	If ($PTableName == 'SORDER') {
		$vResult = F_SynchroSorder($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'DELIVERIES') {
		$vResult = F_SynchroDeliveries($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'SALES') {
		$vResult = F_SynchroSales($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PREQUEST') {
		$vResult = F_SynchroPRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PORDER') {
		$vResult = F_SynchroPorder($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PURCHASES') {
		$vResult = F_SynchroPurchases($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'GRNPURCHASES') {
		$vResult = F_SynchroGrnPurchases($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'ADJUSTMENTREQUEST') {
		$vResult = F_SynchroAdjustmentRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'ADJUSTMENT') {
		$vResult = F_SynchroAdjustment($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'ASSEMBLE') {
		$vResult = F_SynchroAssemble($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'TRANSFERREQUEST') {
		$vResult = F_SynchroTransferRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'TRANSFER') {
		$vResult = F_SynchroTransfer($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'RETAIL') {
		$vResult = F_SynchroRetail($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'JOURNAL') {
		$vResult = F_SynchroJournal($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PAYMENTRQST') {
		$vResult = F_SynchroPaymentRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'TRANS') {
		$vResult = F_SynchroTrans($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PURCHASESJV') {
		$vResult = F_SynchroPurchasesJv($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'SALESJV') {
		$vResult = F_SynchroSalesJv($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'PROJECT') {
		$vResult = F_SynchroProject($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'COSTCENT') {
		$vResult = F_SynchroCostCent($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'WAREHOUSE') {
		$vResult = F_SynchroWarehouse($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'AREA') {
		$vResult = F_SynchroArea($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'CATEGORY') {
		$vResult = F_SynchroCategory($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'LEDGERGRP') {
		$vResult = F_SynchroLedgerGrp($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'GROUPING') {
		$vResult = F_SynchroGrouping($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'SUBGROUP') {
		$vResult = F_SynchroSubGroup($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'ACCTYPE') {
		$vResult = F_SynchroAccType($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'CURRENCY') {
		$vResult = F_SynchroCurrency($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'CUSTOMER') {
		$vResult = F_SynchroCustomer($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'VENDOR') {
		$vResult = F_SynchroVendor($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'COUPON') {
		$vResult = F_SynchroCoupon($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	/*Else If ($PTableName == 'CHECKS') {
		$vResult = F_SynchroChecks($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'BILLS') {
		$vResult = F_SynchroBills($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}*/
	Else If ($PTableName == 'BANKS') {
		$vResult = F_SynchroBanks($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'CLIENTS') {
		$vResult = F_SynchroClients($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'SUPPLIERS') {
		$vResult = F_SynchroSuppliers($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'SALESMEN') {
		$vResult = F_SynchroSalesmen($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'LEDGER') {
		$vResult = F_SynchroLedger($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	Else If ($PTableName == 'ITEMS') {
		$vResult = F_SynchroItems($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn);
	}
	
	
	$sub_query = " Update SynchroData Set Synchro_Flag = '".$vResult."' ".
				 " Where Synchro_ID = '".$PSynchroID."'";
	$sub_result = mysql_query($sub_query, $PLocConn) or die(mysql_error());		
}

function F_SynchroSorder($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Sorder_ID	, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_RequestBy, Sorder_MaturityDate, ".
				 " Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryDate, Sorder_DeliveryPlace, Sorder_DeliveryContact, ".
				 " Salesman_Code, Currency_Code, Project_Code, Costcent_code, Sorder_Posted, Sorder_confirmed, Sorder_disapproved, ".
				 " Sorder_type, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, ".
				 " Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, Sorder_DiscountBase2, Sorder_DiscountPer, ".
				 " Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, Sorder_Paymentmode, ".
				 " Journal_Type, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, ".
				 " Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, ".
				 " Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, User_Account, ".
				 " Sorder_Status, Transfer_ID, Journal_ID, Sorder_CreditCur, Sorder_CreditAccount, Sorder_CreditAccountVat, ".
				 " Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, ".
				 " Sorder_ConfirmUser, sorder_produced, Sorder_vehicalno, Sorder_drivername, Sorder_vehicleweight, Sorder_Invoiced, ".
				 " Owner_Branch, Destination_Branch, Sorder_Syn_ID ".
				 " From Sorder ".
				 " Where Sorder_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vSorderSynID		 = GetSQLValueString($rows['Sorder_ID'],'int');
		$vTransferSynID		 = GetSQLValueString($rows['Transfer_ID'],'int');
		$vJournalSynID		 = GetSQLValueString($rows['Journal_ID'],'int');
		$vSorderReference	 = GetSQLValueString($rows['Sorder_Reference'],'double');
		$vSorderDate		 = GetSQLValueString($rows['Sorder_Date'],'date');
		$vMaturityDate       = GetSQLValueString($rows['Sorder_MaturityDate'],'date');
		$vSorderRemark	     = GetSQLValueString($rows['Sorder_Remark'],'text');
		$vSorderRequestBy    = GetSQLValueString($rows['Sorder_RequestBy'],'text');
		$vSorderRequestDate  = GetSQLValueString($rows['Sorder_RequestDate'],'date');
		$vClientCode		 = GetSQLValueString($rows['Client_code'],'text');
		$vClientContact      = GetSQLValueString($rows['Sorder_ClientContact'],'text');
		$vDeliveryDate       = GetSQLValueString($rows['Sorder_DeliveryDate'],'date');
		$vDeliveryPlace		 = GetSQLValueString($rows['Sorder_DeliveryPlace'],'text');
		$vDeliveryContact    = GetSQLValueString($rows['Sorder_DeliveryContact'],'text');
		$vSalesmanCode		 = GetSQLValueString($rows['Salesman_Code'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vSorderPosted		 = GetSQLValueString($rows['Sorder_Posted'],'int');
		$vSorderConfirmed    = GetSQLValueString($rows['Sorder_confirmed'],'int');
		$vSorderDisapproved  = GetSQLValueString($rows['Sorder_disapproved'],'int');
		$vSorderType		 = GetSQLValueString($rows['Sorder_type'],'text');
		$vSorderTaxable		   	 = GetSQLValueString($rows['Sorder_Taxable'],'double');
		$vSorderTaxableBase1	 = GetSQLValueString($rows['Sorder_TaxableBase1'],'double');
		$vSorderTaxableBase2	 = GetSQLValueString($rows['Sorder_TaxableBase2'],'double');
		$vSorderNoneTaxable	     = GetSQLValueString($rows['Sorder_NoneTaxable'],'double');
		$vSorderNoneTaxableBase1 = GetSQLValueString($rows['Sorder_NoneTaxableBase1'],'double');
		$vSorderNoneTaxableBase2 = GetSQLValueString($rows['Sorder_NoneTaxableBase2'],'double');
		$vSorderDiscountAmount   = GetSQLValueString($rows['Sorder_DiscountAmount'],'double');
		$vSorderDiscountBase1	 = GetSQLValueString($rows['Sorder_DiscountBase1'],'double');
		$vSorderDiscountBase2    = GetSQLValueString($rows['Sorder_DiscountBase2'],'double');
		$vSorderDiscountPer	   	 = GetSQLValueString($rows['Sorder_DiscountPer'],'double');
		$vSorderVAT			   	 = GetSQLValueString($rows['Sorder_VAT'],'double');
		$vSorderVATBase1		 = GetSQLValueString($rows['Sorder_VATBase1'],'double');
		$vSorderVATBase2		 = GetSQLValueString($rows['Sorder_VATBase2'],'double');
		$vTotalQuantity		     = GetSQLValueString($rows['Sorder_TotalQuantity'],'double');
		$vTotalQuantityUsed 	 = GetSQLValueString($rows['Sorder_TotalQuantityUsed'],'double');
		$vSorderMode			 = GetSQLValueString($rows['Sorder_Paymentmode'],'int');
		$vJournalType 			 = GetSQLValueString($rows['Journal_Type'],'text');
		$vSorderBelongsToGroup   = GetSQLValueString($rows['Sorder_BelongsToGrp'],'int');
		$vSorderTax1 		= GetSQLValueString($rows['Sorder_tax1'],'double');
		$vSorderTax2 		= GetSQLValueString($rows['Sorder_tax2'],'double');
		$vSorderTax3 		= GetSQLValueString($rows['Sorder_tax3'],'double');
		$vSorderTax4 		= GetSQLValueString($rows['Sorder_tax4'],'double');
		$vSorderTax5 		= GetSQLValueString($rows['Sorder_tax5'],'double');
		$vSorderTax1Base1   = GetSQLValueString($rows['Sorder_tax1base1'],'double');
		$vSorderTax2Base1   = GetSQLValueString($rows['Sorder_tax2base1'],'double');
		$vSorderTax3Base1   = GetSQLValueString($rows['Sorder_tax3base1'],'double');
		$vSorderTax4Base1   = GetSQLValueString($rows['Sorder_tax4base1'],'double');
		$vSorderTax5Base1   = GetSQLValueString($rows['Sorder_tax5base1'],'double');
		$vSorderTax1Base2   = GetSQLValueString($rows['Sorder_tax1base2'],'double');
		$vSorderTax2Base2   = GetSQLValueString($rows['Sorder_tax2base2'],'double');
		$vSorderTax3Base2   = GetSQLValueString($rows['Sorder_tax3base2'],'double');
		$vSorderTax4Base2   = GetSQLValueString($rows['Sorder_tax4base2'],'double');
		$vSorderTax5Base2   = GetSQLValueString($rows['Sorder_tax5base2'],'double');
		$vDetailCode		 = GetSQLValueString($rows['Detail_Code'],'text');
		$vSorderVatChkbx	 = GetSQLValueString($rows['Sorder_VatChckbx'],'int');
		$vSorderHide		 = GetSQLValueString($rows['Sorder_Hide'],'int');
		$vSorderStatus 		 = GetSQLValueString($rows['Sorder_Status'],'int');
		$vUserAccount 		 = GetSQLValueString($rows['User_Account'],'text');
		$vCreditCur 		 = GetSQLValueString($rows['Sorder_CreditCur'],'text');
		$vCreditAccount 	 = GetSQLValueString($rows['Sorder_CreditAccount'],'text');
		$vCreditAccountVat 	 = GetSQLValueString($rows['Sorder_CreditAccountVat'],'text');
		$vTransportAccount 	 = GetSQLValueString($rows['Sorder_TransportAccount'],'text');
		$vTransportAmount	 = GetSQLValueString($rows['Sorder_TransportAmount'],'double');
		$vTransportBase1	 = GetSQLValueString($rows['Sorder_TransportBase1'],'double');
		$vTransportBase2	 = GetSQLValueString($rows['Sorder_TransportBase2'],'double');
		$vTransportTTC  	 = GetSQLValueString($rows['Sorder_TransportTTC'],'double');
		$vConfirmUser 	 	 = GetSQLValueString($rows['Sorder_ConfirmUser'],'text');
		$vSorderProduced 	 = GetSQLValueString($rows['sorder_produced'],'int');
		$vSorderVehicalno 	 = GetSQLValueString($rows['Sorder_vehicalno'],'text');
		$vSorderDrivername 	 = GetSQLValueString($rows['Sorder_drivername'],'text');
		$vVehicleWeight 	 = GetSQLValueString($rows['Sorder_vehicleweight'],'text');
		$vSorderInvoiced 	 = GetSQLValueString($rows['Sorder_Invoiced'],'int');
		$vOwnerBranch 		 = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch  = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$vTransferID 	   = F_Get_SorderTransferID($PDestConn, $vTransferSynID);
		
		
		$sub_query  = " Select Count(*) From Sorder ".
		              " Where Sorder_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vSorderID = GetNextSequence($PDestConn,'Null','Null','ID','SORDER','','Null',$rows['Sorder_Date']);
			$vSorderID = GetNextSequence1($PDestConn,'Sorder_ID','');
			
			$sub_query = " Insert Into Sorder (Sorder_ID, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_RequestBy, Sorder_MaturityDate, ".
						 " Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryDate, Sorder_DeliveryPlace, Sorder_DeliveryContact, ".
						 " Salesman_Code, Currency_Code, Project_Code, Costcent_code, Sorder_Posted, Sorder_confirmed, Sorder_disapproved, ".
						 " Sorder_type, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, ".
						 " Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, Sorder_DiscountBase2, Sorder_DiscountPer, ".
						 " Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, Sorder_Paymentmode, ".
						 " Journal_Type, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, ".
						 " Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, ".
						 " Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, User_Account, ".
						 " Sorder_Status, Transfer_ID, Sorder_CreditCur, Sorder_CreditAccount, Sorder_CreditAccountVat, ".
						 " Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, ".
						 " Sorder_ConfirmUser, sorder_produced, Sorder_vehicalno, Sorder_drivername, Sorder_vehicleweight, Sorder_Invoiced, ".
						 " Owner_Branch, Destination_Branch, Sorder_Syn_ID ) ".
						 " Values ( ".$vSorderID.", ".$vSorderReference.", ".$vSorderDate.", ".$vSorderRequestDate.", ".$vSorderRequestBy.", ".$vMaturityDate.
						 ", ".$vSorderRemark.", ".$vClientCode.", ".$vClientContact.", ".$vDeliveryDate.", ".$vDeliveryPlace.", ".$vDeliveryContact.
						 ", ".$vSalesmanCode.", ".$vCurrencyCode.", ".$vProjectCode.", ".$vCostcentCode.", ".$vSorderPosted.", ".$vSorderConfirmed.", ".$vSorderDisapproved.
						 ", ".$vSorderType.", ".$vSorderTaxable.", ".$vSorderTaxableBase1.", ".$vSorderTaxableBase2.", ".$vSorderNoneTaxable.", ".$vSorderNoneTaxableBase1.
						 ", ".$vSorderNoneTaxableBase2.", ".$vSorderDiscountAmount.", ".$vSorderDiscountBase1.", ".$vSorderDiscountBase2.", ".$vSorderDiscountPer.
						 ", ".$vSorderVAT.", ".$vSorderVATBase1.", ".$vSorderVATBase2.", ".$vTotalQuantity.", ".$vTotalQuantityUsed.", ".$vSorderMode.
						 ", ".$vJournalType.", ".$vSorderTax1.", ".$vSorderTax1Base1.", ".$vSorderTax1Base2.", ".$vSorderTax2.", ".$vSorderTax2Base1.
						 ", ".$vSorderTax2Base2.", ".$vSorderTax3.", ".$vSorderTax3Base1.", ".$vSorderTax3Base2.", ".$vSorderTax4.", ".$vSorderTax4Base1.
						 ", ".$vSorderTax4Base2.", ".$vSorderTax5.", ".$vSorderTax5Base1.", ".$vSorderTax5Base2.", ".$vSorderVatChkbx.", ".$vSorderHide.
						 ", ".$vSorderBelongsToGroup.", ".$vDetailCode.", ".$vUserAccount.", ".$vSorderStatus.", ".$vTransferID.", ".$vCreditCur.
						 ", ".$vCreditAccount.", ".$vCreditAccountVat.", ".$vTransportAccount.", ".$vTransportAmount.", ".$vTransportBase1.", ".$vTransportBase2.
						 ", ".$vTransportTTC.", ".$vConfirmUser.", ".$vSorderProduced.", ".$vSorderVehicalno.", ".$vSorderDrivername.", ".$vVehicleWeight.
						 ", ".$vSorderInvoiced.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vSorderSynID." )";
						 
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Sorder_ID From Sorder ".
					  " Where Sorder_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vSorderID = $result[0];
			
			$sub_query = "  Update Sorder Set Sorder_Date = ".$vSorderDate.", Sorder_RequestDate = ".$vSorderRequestDate.", Sorder_RequestBy = ".$vSorderRequestBy.
						 ", Sorder_MaturityDate = ".$vMaturityDate.", Sorder_Remark = ".$vSorderRemark.", Client_code = ".$vClientCode.
						 ", Sorder_ClientContact = ".$vClientContact.",	Sorder_DeliveryDate = ".$vDeliveryDate.", Sorder_DeliveryPlace = ".$vDeliveryPlace.
						 ", Sorder_DeliveryContact = ".$vDeliveryContact.", Salesman_Code = ".$vSalesmanCode.",	Currency_Code = ".$vCurrencyCode.
						 ", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode.", Sorder_Posted = ".$vSorderPosted.
						 ", Sorder_confirmed = ".$vSorderConfirmed.", Sorder_disapproved = ".$vSorderDisapproved.", Sorder_type = ".$vSorderType.
						 ", Sorder_Taxable = ".$vSorderTaxable.", Sorder_TaxableBase1 = ".$vSorderTaxableBase1.", Sorder_TaxableBase2 = ".$vSorderTaxableBase2. 
						 ",	Sorder_NoneTaxable = ".$vSorderNoneTaxable.", Sorder_NoneTaxableBase1 = ".$vSorderNoneTaxableBase1. 
						 ", Sorder_NoneTaxableBase2 = ".$vSorderNoneTaxableBase2.", Sorder_DiscountAmount = ".$vSorderDiscountAmount. 
						 ",	Sorder_DiscountBase1 = ".$vSorderDiscountBase1.", Sorder_DiscountBase2 = ".$vSorderDiscountBase2. 
						 ",	Sorder_DiscountPer = ".$vSorderDiscountPer.", Sorder_VAT = ".$vSorderVAT.", Sorder_VATBase1 = ".$vSorderVATBase1. 
						 ",	Sorder_VATBase2 = ".$vSorderVATBase2.", Sorder_TotalQuantity = ".$vTotalQuantity.", Sorder_TotalQuantityUsed = ".$vTotalQuantityUsed. 
						 ",	Sorder_Paymentmode = ".$vSorderMode.", Journal_Type = ".$vJournalType.", Sorder_tax1 = ".$vSorderTax1.
						 ", Sorder_tax1base1 = ".$vSorderTax1Base1.", Sorder_tax1base2 = ".$vSorderTax1Base2.", Sorder_tax2 = ".$vSorderTax2.
						 ", Sorder_tax2base1 = ".$vSorderTax2Base1.", Sorder_tax2base2 = ".$vSorderTax2Base2.", Sorder_tax3 = ".$vSorderTax3.
						 ", Sorder_tax3base1 = ".$vSorderTax3Base1.", Sorder_tax3base2 = ".$vSorderTax3Base2.", Sorder_tax4 = ".$vSorderTax4.
						 ", Sorder_tax4base1 = ".$vSorderTax4Base1.", Sorder_tax4base2 = ".$vSorderTax4Base2.", Sorder_tax5 = ".$vSorderTax5.
						 ", Sorder_tax5base1 = ".$vSorderTax5Base1.", Sorder_tax5base2 = ".$vSorderTax5Base2.",	Sorder_VatChckbx = ".$vSorderVatChkbx.
						 ", Sorder_Hide = ".$vSorderHide.", Sorder_BelongsToGrp = ".$vSorderBelongsToGroup.", Detail_Code = ".$vDetailCode.
						 ", Sorder_Status = ".$vSorderStatus.", Transfer_ID = ".$vTransferID.", Sorder_CreditCur = ".$vCreditCur.
						 ", Sorder_CreditAccount = ".$vCreditAccount.", Sorder_CreditAccountVat = ".$vCreditAccountVat.", Sorder_TransportAccount = ".$vTransportAccount.
						 ", Sorder_TransportAmount = ".$vTransportAmount.", Sorder_TransportBase1 = ".$vTransportBase1.", Sorder_TransportBase2 = ".$vTransportBase2.
						 ", Sorder_TransportTTC = ".$vTransportTTC.", Sorder_ConfirmUser = ".$vConfirmUser.", sorder_produced = ".$vSorderProduced.
						 ", Sorder_vehicalno = ".$vSorderVehicalno.", Sorder_drivername = ".$vSorderDrivername.", Sorder_vehicleweight = ".$vVehicleWeight.
						 ", Sorder_Invoiced = ".$vSorderInvoiced.", Destination_Branch = ".$vDestinationBranch.
						 "  Where Sorder_Syn_ID = '".$PRecordID."'";
					 
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Sorder Set Sorder_Syn_ID = ".$vSorderID.
							 " Where Sorder_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In SorderDt
			If ($vRecordExists > 0) {
				$query = "Delete From SorderDt Where Sorder_ID = '".$vSorderID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From SorderDt
			$query = " Select SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, ".
			         " Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, SorderDt_Price, ".
					 " SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, ".
					 " SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, ".
					 " SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, ".
					 " Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, ".
					 " Sorderdt_promotion, Item_QtyPacked, User_Account, SorderDt_TransportAmount, SorderDt_TransportBase1, SorderDt_TransportBase2 ".
					 " From SorderDt ".
					 " Where Sorder_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vSorderDtID   = GetNextSequence($PDestConn,'Null','Null','ID','SORDERDT','','Null',$rows['Sorder_Date']);
				$vSorderDtID = GetNextSequence1($PDestConn,'SorderDt_ID','');
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SorderDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'SorderDt',$vMessage);
					
					break;
				}	*/
				
				$sub_query = " Insert Into SorderDt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, ".
							 " Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, SorderDt_Price, ".
							 " SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, ".
							 " SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, ".
							 " SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, ".
							 " Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, ".
							 " Sorderdt_promotion, Item_QtyPacked, User_Account, SorderDt_Syn_ID, Sorder_Syn_ID, SorderDt_TransportAmount, ".
							 " SorderDt_TransportBase1, SorderDt_TransportBase2 ) ".
					 		 " Values ( ".$vSorderDtID.", ".$vSorderID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Sorder_Date'],'date').
							 ", ".GetSQLValueString($rows['Client_Code'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCent_Code'],'text').
							 ", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['SorderDt_Quantity'],'double').", ".GetSQLValueString($rows['SorderDt_QuantityUsed'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_Price'],'double').", ".GetSQLValueString($rows['SorderDt_PriceBase1'],'double').
							 ", ".GetSQLValueString($rows['SroderDt_PriceBase2'],'double').", ".GetSQLValueString($rows['SorderDt_Discount'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_DiscountAmount'],'double').", ".GetSQLValueString($rows['SorderDt_DiscountBase1'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_DiscountBase2'],'double').", ".GetSQLValueString($rows['Item_Vat'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_PriceTTC'],'double').", ".GetSQLValueString($rows['SorderDt_Remark'],'text').
							 ", ".GetSQLValueString($rows['SorderDt_DirectStkDbt'],'text').", ".GetSQLValueString($rows['SorderDt_DirectStkCrd'],'text').
							 ", ".GetSQLValueString($rows['SorderDt_DirectStkCur'],'text').", ".GetSQLValueString($rows['SorderDt_ItemAccount'],'text').
							 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Sorderdt_posted'],'int').", ".GetSQLValueString($rows['Sorderdt_OldData'],'int').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_oqty'],'double').", ".GetSQLValueString($rows['SorderDt_cqty'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_cqtydate'],'date').", ".GetSQLValueString($rows['SorderDt_cqtyuser'],'text').
							 ", ".GetSQLValueString($rows['Sorderdt_promotion'],'int').", ".GetSQLValueString($rows['Item_QtyPacked'],'double').
							 ", ".GetSQLValueString($rows['User_Account'],'text').", ".GetSQLValueString($rows['SorderDt_id'],'int').
							 ", ".$vSorderSynID.", ".GetSQLValueString($rows['SorderDt_TransportAmount'],'double').", ".GetSQLValueString($rows['SorderDt_TransportBase1'],'double').
							 ", ".GetSQLValueString($rows['SorderDt_TransportBase2'],'double')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SorderDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'SorderDt',$vMessage);
					
					break;
				}
			}
			
			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Sorder Set Journal_ID = '".$vJournalID."' ".
							  " Where Sorder_ID = '".$vSorderID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Sorder',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Sorder_ID, Owner_Branch ".
					 " From Sorder Where Sorder_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vSorderID    = $sub_result[1];
		$vOwnerBranch = $sub_result[2];
			
		$query = "Delete From SorderDt Where Sorder_ID = '".$vSorderID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$query = "Delete From Sorder Where Sorder_ID = '".$vSorderID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($vJournalID != -1) {
				$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}	
			
			if ($result) {
				$vResult  = 'T';
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Sorder',$vMessage);
			}	
				
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SorderDt',$vMessage);
		}
		
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vSorderID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroDeliveries($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, ".
				 " Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, Project_Code, ".
				 " Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, ".
				 " Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, Delivery_DiscountBase1, ".
				 " Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, ".
				 " Delivery_TotalBase2, Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, ".
				 " Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, Delivery_Tax3Base1, ".
				 " Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, ".
				 " Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, ".
				 " Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, ".
				 " Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, ".
				 " Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
				 " Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef, Delivery_VatChkbx, Delivery_DirectReturn, User_Account, Owner_Branch, ".
				 " Destination_Branch, Delivery_Syn_ID, delivery_activevat, Delivery_TransportTTC, Delivery_BonusAccount, Delivery_BonusAmount, ".
				 " Delivery_BonusBase1, Delivery_BonusBase2, Delivery_BonusTTC, Delivery_ManualNo, Delivery_vehicleLoadweight, Delivery_vehicleweight, ".
				 " DELIVERY_LOADHHT, CashRegister_Name, Delivery_CashInBase1, Delivery_CashInBase2, Delivery_CashOutBase1, Delivery_CashOutBase2, Delivery_TipsBase1 ".
				 " From Deliveries ".
				 " Where Delivery_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vDeliverySynID		 = GetSQLValueString($rows['Delivery_ID'],'int');
		$vJournalSynID		 = GetSQLValueString($rows['Journal_Id'],'int');
		$vDeliveryReference	 = GetSQLValueString($rows['Delivery_Reference'],'double');
		$vDeliveryReturnRef  = GetSQLValueString($rows['Delivery_ReturnRef'],'double');
		$vSorderReference    = GetSQLValueString($rows['Sorder_reference'],'double');
		$vSorderReferences   = GetSQLValueString($rows['Delivery_SorderReferences'],'double');
		$vDeliveryDate		 = GetSQLValueString($rows['Delivery_Date'],'date');
		$vJournalDtValueDate = GetSQLValueString($rows['JournalDt_ValueDate'],'date');
		$vDeliveryRemark	 = GetSQLValueString($rows['Delivery_Remark'],'text');
		$vClientCode		 = GetSQLValueString($rows['Client_code'],'text');
		$vDeliveryShippedTo  = GetSQLValueString($rows['Delivery_ShippedTo'],'text');
		$vDeliveryMarks		 = GetSQLValueString($rows['Delivery_Marks'],'text');
		$vDeliveryShippedVia = GetSQLValueString($rows['Delivery_ShippedVia'],'text');
		$vSalesmanCode		 = GetSQLValueString($rows['Salesman_Code'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vDeliveryPosted	 = GetSQLValueString($rows['Delivery_Posted'],'int');
		$vDeliveryEdit		 = GetSQLValueString($rows['Delivery_Edit'],'int');
		$vDeliveryTaxable		   = GetSQLValueString($rows['Delivery_Taxable'],'double');
		$vDeliveryTaxableBase1	   = GetSQLValueString($rows['Delivery_TaxableBase1'],'double');
		$vDeliveryTaxableBase2	   = GetSQLValueString($rows['Delivery_TaxableBase2'],'double');
		$vDeliveryNoneTaxable	   = GetSQLValueString($rows['Delivery_NoneTaxable'],'double');
		$vDeliveryNoneTaxableBase1 = GetSQLValueString($rows['Delivery_NoneTaxableBase1'],'double');
		$vDeliveryNoneTaxableBase2 = GetSQLValueString($rows['Delivery_NoneTaxableBase2'],'double');
		$vDeliveryDiscountAmount   = GetSQLValueString($rows['Delivery_DiscountAmount'],'double');
		$vDeliveryDiscountBase1	   = GetSQLValueString($rows['Delivery_DiscountBase1'],'double');
		$vDeliveryDiscountBase2    = GetSQLValueString($rows['Delivery_DiscountBase2'],'double');
		$vDeliveryDiscountPer	   = GetSQLValueString($rows['Delivery_DiscountPer'],'double');
		$vDeliveryVAT			   = GetSQLValueString($rows['Delivery_VAT'],'double');
		$vDeliveryVATBase1		   = GetSQLValueString($rows['Delivery_VATBase1'],'double');
		$vDeliveryVATBase2		   = GetSQLValueString($rows['Delivery_VATBase2'],'double');
		$vDeliveryTotal			   = GetSQLValueString($rows['Delivery_Total'],'double');
		$vDeliveryTotalBase1	   = GetSQLValueString($rows['Delivery_TotalBase1'],'double');
		$vDeliveryTotalBase2	   = GetSQLValueString($rows['Delivery_TotalBase2'],'double');
		$vDeliveryConfirmed		   = GetSQLValueString($rows['Delivery_Confirmed'],'int');
		$vDeliveryMode			   = GetSQLValueString($rows['Delivery_Mode'],'int');
		$vJournalType 			   = GetSQLValueString($rows['Journal_Type'],'text');
		$vDeliveryBelongsToGroup   = GetSQLValueString($rows['Delivery_BelongsToGroup'],'int');
		$vDeliveryTax1 		= GetSQLValueString($rows['Delivery_Tax1'],'double');
		$vDeliveryTax2 		= GetSQLValueString($rows['Delivery_Tax2'],'double');
		$vDeliveryTax3 		= GetSQLValueString($rows['Delivery_Tax3'],'double');
		$vDeliveryTax4 		= GetSQLValueString($rows['Delivery_Tax4'],'double');
		$vDeliveryTax5 		= GetSQLValueString($rows['Delivery_Tax5'],'double');
		$vDeliveryTax1Base1 = GetSQLValueString($rows['Delivery_Tax1Base1'],'double');
		$vDeliveryTax2Base1 = GetSQLValueString($rows['Delivery_Tax2Base1'],'double');
		$vDeliveryTax3Base1 = GetSQLValueString($rows['Delivery_Tax3Base1'],'double');
		$vDeliveryTax4Base1 = GetSQLValueString($rows['Delivery_Tax4Base1'],'double');
		$vDeliveryTax5Base1 = GetSQLValueString($rows['Delivery_Tax5Base1'],'double');
		$vDeliveryTax1Base2 = GetSQLValueString($rows['Delivery_Tax1Base2'],'double');
		$vDeliveryTax2Base2 = GetSQLValueString($rows['Delivery_Tax2Base2'],'double');
		$vDeliveryTax3Base2 = GetSQLValueString($rows['Delivery_Tax3Base2'],'double');
		$vDeliveryTax4Base2 = GetSQLValueString($rows['Delivery_Tax4Base2'],'double');
		$vDeliveryTax5Base2 = GetSQLValueString($rows['Delivery_Tax5Base2'],'double');
		$vDeliveryAcctax1 	= GetSQLValueString($rows['Delivery_Acctax1'],'text');
		$vDeliveryAcctax2 	= GetSQLValueString($rows['Delivery_Acctax2'],'text');
		$vDeliveryAcctax3 	= GetSQLValueString($rows['Delivery_Acctax3'],'text');
		$vDeliveryAcctax4 	= GetSQLValueString($rows['Delivery_Acctax4'],'text');
		$vDeliveryAcctax5 	= GetSQLValueString($rows['Delivery_Acctax5'],'text');
		$vDeliveryCreditCur = GetSQLValueString($rows['Delivery_CreditCur'],'text');
		$vDeliveryCreditAccount		   = GetSQLValueString($rows['Delivery_CreditAccount'],'text');
		$vDeliveryTipsAccount		   = GetSQLValueString($rows['Delivery_TipsAccount'],'text');
		$vDeliveryVatAccount		   = GetSQLValueString($rows['Delivery_VatAccount'],'text');
		$vDeliveryCreditAccountVat	   = GetSQLValueString($rows['Delivery_CreditAccountVat'],'text');
		$vDeliveryPromotionAcc		   = GetSQLValueString($rows['Delivery_PromotionAcc'],'text');
		$vDeliveryTransportAccount 	   = GetSQLValueString($rows['Delivery_TransportAccount'],'text');
		$vDeliveryCREDITACCcur		   = GetSQLValueString($rows['Delivery_CREDITACCcur'],'text');
		$vDeliveryCREDITACC			   = GetSQLValueString($rows['Delivery_CREDITACC'],'text');
		$vDeliveryTotalTax			   = GetSQLValueString($rows['Delivery_TotalTax'],'double');
		$vDeliveryTotalTaxBase1		   = GetSQLValueString($rows['Delivery_TotalTaxBase1'],'double');
		$vDeliveryTotalTaxBase2 	   = GetSQLValueString($rows['Delivery_TotalTaxBase2'],'double');
		$vDeliveryTransportAmount	   = GetSQLValueString($rows['Delivery_TransportAmount'],'double');
		$vDeliveryTransportAmountBase1 = GetSQLValueString($rows['Delivery_TransportAmountBase1'],'double');
		$vDeliveryTransportAmountBase2 = GetSQLValueString($rows['Delivery_TransportAmountBase2'],'double');
		$vDeliveryTaxableTTC 		   = GetSQLValueString($rows['Delivery_TaxableTTC'],'double');
		$vDeliveryDiscountTTC		   = GetSQLValueString($rows['Delivery_DiscountTTC'],'double');
		$vDetailCode				   = GetSQLValueString($rows['Detail_Code'],'text');
		$vDeliveryVatChkbx			   = GetSQLValueString($rows['Delivery_VatChkbx'],'int');
		$vDeliveryDirectReturn 		   = GetSQLValueString($rows['Delivery_DirectReturn'],'int');
		$vDeliveryActiveVat 		   = GetSQLValueString($rows['delivery_activevat'],'int');
		$vDeliveryTransportTTC		   = GetSQLValueString($rows['Delivery_TransportTTC'],'double');
		$vDeliveryBonusAccount 		   = GetSQLValueString($rows['Delivery_BonusAccount'],'text');
		$vDeliveryBonusAmount		   = GetSQLValueString($rows['Delivery_BonusAmount'],'double');
		$vDeliveryBonusBase1		   = GetSQLValueString($rows['Delivery_BonusBase1'],'double');
		$vDeliveryBonusBase2		   = GetSQLValueString($rows['Delivery_BonusBase2'],'double');
		$vDeliveryBonusTTC			   = GetSQLValueString($rows['Delivery_BonusTTC'],'double');
		$vDeliveryManualNo 			   = GetSQLValueString($rows['Delivery_ManualNo'],'text');
		$vVehicleLoadWeight			   = GetSQLValueString($rows['Delivery_vehicleLoadweight'],'double');
		$vVehicleWeight 			   = GetSQLValueString($rows['Delivery_vehicleweight'],'double');
		$vDeliveryLoadHHT 			   = GetSQLValueString($rows['DELIVERY_LOADHHT'],'int');
		$vCashRegisterName 			   = GetSQLValueString($rows['CashRegister_Name'],'text');
		$vDeliveryCashInBase1	   	   = GetSQLValueString($rows['Delivery_CashInBase1'],'double');
		$vDeliveryCashInBase2	   	   = GetSQLValueString($rows['Delivery_CashInBase2'],'double');
		$vDeliveryCashOutBase1	   	   = GetSQLValueString($rows['Delivery_CashOutBase1'],'double');
		$vDeliveryCashOutBase2	  	   = GetSQLValueString($rows['Delivery_CashOutBase2'],'double');
		$vDeliveryTipsBase1			   = GetSQLValueString($rows['Delivery_TipsBase1'],'double');
		$vUserAccount 				   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 				   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch            = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
				 
		/*$vCheckClientID	   = F_Check_ClientID($PDestConn, $vClientID);
		$vCheckSalesmanID  = F_Check_SalesmanID($PDestConn, $vSalesmanID);
		$vCheckCurrencyID  = F_Check_CurrencyID($PDestConn, $vCurrencyID);
		$vCheckProjectID   = F_Check_ProjectID($PDestConn, $vProjectID);
		$vCheckCostCentID  = F_Check_CostCentID($PDestConn, $vCostCentID);
		
		if ($vCheckClientID == 0 || $vCheckSalesmanID == 0 || $vCheckCurrencyID == 0 || 
		    $vCheckProjectID == 0 || $vCheckCostCentID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Client|Salesman|Currency|Project|CostCent not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Deliveries',$vMessage);
			
			Return $vResult;
		}*/
		
		$sub_query  = " Select Count(*) From Deliveries ".
		              " Where Delivery_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vDeliveryID = GetNextSequence($PDestConn,'Null','Null','ID','DELIVERIES','','Null',$rows['Delivery_Date']);
			$vDeliveryID = GetNextSequence1($PDestConn,'Delivery_ID','');
			
			$sub_query = " Insert Into Deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, ".
						 " Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, Project_Code, ".
						 " Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, ".
						 " Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, Delivery_DiscountBase1, ".
						 " Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, ".
						 " Delivery_TotalBase2, Delivery_Confirmed, Delivery_Mode, Journal_Type, Delivery_BelongsToGroup, Delivery_Tax1, ".
						 " Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, Delivery_Tax3Base1, ".
						 " Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, ".
						 " Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, ".
						 " Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, ".
						 " Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, ".
						 " Delivery_TransportAmount, Delivery_TransportAmountBase1, Delivery_TransportAmountBase2, Delivery_TaxableTTC, Delivery_DiscountTTC, ".
						 " Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef, Delivery_VatChkbx, Delivery_DirectReturn, User_Account, Owner_Branch, ".
						 " Destination_Branch, Delivery_Syn_ID, delivery_activevat, Delivery_TransportTTC, Delivery_BonusAccount, Delivery_BonusAmount, ".
						 " Delivery_BonusBase1, Delivery_BonusBase2, Delivery_BonusTTC, Delivery_ManualNo, Delivery_vehicleLoadweight, Delivery_vehicleweight, ".
						 " DELIVERY_LOADHHT, CashRegister_Name, Delivery_CashInBase1, Delivery_CashInBase2, Delivery_CashOutBase1, Delivery_CashOutBase2, Delivery_TipsBase1 ) ".
						 " Values ( ".$vDeliveryID.", ".$vDeliveryReference.", ".$vSorderReference.", ".$vDeliveryDate.", ".$vJournalDtValueDate.", ".$vDeliveryRemark.
						 ", ".$vClientCode.", ".$vDeliveryShippedTo.", ".$vDeliveryMarks.", ".$vDeliveryShippedVia.", ".$vSalesmanCode.", ".$vCurrencyCode.", ".$vProjectCode.
						 ", ".$vCostcentCode.", ".$vDeliveryPosted.", ".$vDeliveryEdit.", ".$vDeliveryTaxable.", ".$vDeliveryTaxableBase1.", ".$vDeliveryTaxableBase2.
						 ", ".$vDeliveryNoneTaxable.", ".$vDeliveryNoneTaxableBase1.", ".$vDeliveryNoneTaxableBase2.", ".$vDeliveryDiscountAmount.", ".$vDeliveryDiscountBase1.
						 ", ".$vDeliveryDiscountBase2.", ".$vDeliveryDiscountPer.", ".$vDeliveryVAT.", ".$vDeliveryVATBase1.", ".$vDeliveryVATBase2.", ".$vDeliveryTotal.
						 ", ".$vDeliveryTotalBase1.", ".$vDeliveryTotalBase2.", ".$vDeliveryConfirmed.", ".$vDeliveryMode.", ".$vJournalType.
						 ", ".$vDeliveryBelongsToGroup.", ".$vDeliveryTax1.", ".$vDeliveryTax2.", ".$vDeliveryTax3.", ".$vDeliveryTax4.", ".$vDeliveryTax5.
						 ", ".$vDeliveryTax1Base1.", ".$vDeliveryTax2Base1.", ".$vDeliveryTax3Base1.", ".$vDeliveryTax4Base1.", ".$vDeliveryTax5Base1.
						 ", ".$vDeliveryTax1Base2.", ".$vDeliveryTax2Base2.", ".$vDeliveryTax3Base2.", ".$vDeliveryTax4Base2.", ".$vDeliveryTax5Base2.
						 ", ".$vDeliveryAcctax1.", ".$vDeliveryAcctax2.", ".$vDeliveryAcctax3.", ".$vDeliveryAcctax4.", ".$vDeliveryAcctax5.
						 ", ".$vDeliveryCreditCur.", ".$vDeliveryCreditAccount.", ".$vDeliveryTipsAccount.", ".$vDeliveryVatAccount.", ".$vDeliveryCreditAccountVat.
						 ", ".$vDeliveryPromotionAcc.", ".$vDeliveryTransportAccount.", ".$vDeliveryCREDITACCcur.", ".$vDeliveryCREDITACC.
						 ", ".$vDeliveryTotalTax.", ".$vDeliveryTotalTaxBase1.", ".$vDeliveryTotalTaxBase2.", ".$vDeliveryTransportAmount.
						 ", ".$vDeliveryTransportAmountBase1.", ".$vDeliveryTransportAmountBase2.", ".$vDeliveryTaxableTTC.", ".$vDeliveryDiscountTTC.
						 ", ".$vSorderReferences.", ".$vDetailCode.", ".$vDeliveryReturnRef.", ".$vDeliveryVatChkbx.", ".$vDeliveryDirectReturn.
						 ", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vDeliverySynID.", ".$vDeliveryActiveVat.", ".$vDeliveryTransportTTC.
						 ", ".$vDeliveryBonusAccount.", ".$vDeliveryBonusAmount.", ".$vDeliveryBonusBase1.", ".$vDeliveryBonusBase2.", ".$vDeliveryBonusTTC.
						 ", ".$vDeliveryManualNo.", ".$vVehicleLoadWeight.", ".$vVehicleWeight.", ".$vDeliveryLoadHHT.", ".$vCashRegisterName.
						 ", ".$vDeliveryCashInBase1.", ".$vDeliveryCashInBase2.", ".$vDeliveryCashOutBase1.", ".$vDeliveryCashOutBase2.", ".$vDeliveryTipsBase1." )";
		}	
			
	
		//Case Record Exists - Update
		else {
			$query  = " Select Delivery_ID From Deliveries ".
					  " Where Delivery_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vDeliveryID = $result[0];
			
			$sub_query = "  Update Deliveries Set Delivery_Date = ".$vDeliveryDate.", JournalDt_ValueDate = ".$vJournalDtValueDate. 
						 ",	Delivery_Remark = ".$vDeliveryRemark.", Client_code = ".$vClientCode.", Delivery_ShippedTo = ".$vDeliveryShippedTo. 
						 ",	Delivery_Marks = ".$vDeliveryMarks.", Delivery_ShippedVia = ".$vDeliveryShippedVia.", Salesman_Code = ".$vSalesmanCode. 
						 ",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode. 
						 ",	Delivery_Posted = ".$vDeliveryPosted.", Delivery_Edit = ".$vDeliveryEdit.", Delivery_Taxable = ".$vDeliveryTaxable. 
						 ",	Delivery_TaxableBase1 = ".$vDeliveryTaxableBase1.", Delivery_TaxableBase2 = ".$vDeliveryTaxableBase2. 
						 ",	Delivery_NoneTaxable = ".$vDeliveryNoneTaxable.", Delivery_NoneTaxableBase1 = ".$vDeliveryNoneTaxableBase1. 
						 ", Delivery_NoneTaxableBase2 = ".$vDeliveryNoneTaxableBase2.", Delivery_DiscountAmount = ".$vDeliveryDiscountAmount. 
						 ",	Delivery_DiscountBase1 = ".$vDeliveryDiscountBase1.", Delivery_DiscountBase2 = ".$vDeliveryDiscountBase2. 
						 ",	Delivery_DiscountPer = ".$vDeliveryDiscountPer.", Delivery_VAT = ".$vDeliveryVAT.", Delivery_VATBase1 = ".$vDeliveryVATBase1. 
						 ",	Delivery_VATBase2 = ".$vDeliveryVATBase2.", Delivery_Total = ".$vDeliveryTotal.", Delivery_TotalBase1 = ".$vDeliveryTotalBase1. 
						 ",	Delivery_TotalBase2 = ".$vDeliveryTotalBase2.", Delivery_Confirmed = ".$vDeliveryConfirmed.", Delivery_Mode = ".$vDeliveryMode. 
						 ",	Journal_Type = ".$vJournalType.", Delivery_Tax1 = ".$vDeliveryTax1.", Delivery_Tax1Base1 = ".$vDeliveryTax1Base1. 
						 ",	Delivery_Tax1Base2 = ".$vDeliveryTax1Base2.", Delivery_Tax2 = ".$vDeliveryTax2.", Delivery_Tax2Base1 = ".$vDeliveryTax2Base1. 
						 ",	Delivery_Tax2Base2 = ".$vDeliveryTax2Base2.", Delivery_Tax3 = ".$vDeliveryTax3.", Delivery_Tax3Base1 = ".$vDeliveryTax3Base1. 
						 ",	Delivery_Tax3Base2 = ".$vDeliveryTax3Base2.", Delivery_Tax4 = ".$vDeliveryTax3.", Delivery_Tax4Base1 = ".$vDeliveryTax4Base1. 
						 ",	Delivery_Tax4Base2 = ".$vDeliveryTax4Base2.", Delivery_Tax5 = ".$vDeliveryTax5.", Delivery_Tax5Base1 = ".$vDeliveryTax5Base1. 
						 ", Delivery_Tax5Base2 = ".$vDeliveryTax5Base2.", Delivery_Acctax1 = ".$vDeliveryAcctax1.", Delivery_Acctax2 = ".$vDeliveryAcctax2. 
						 ",	Delivery_Acctax3 = ".$vDeliveryAcctax3.", Delivery_Acctax4 = ".$vDeliveryAcctax4.", Delivery_Acctax5 = ".$vDeliveryAcctax5. 
						 ",	Delivery_TotalTax = ".$vDeliveryTotalTax.", Delivery_TotalTaxBase1 = ".$vDeliveryTotalTaxBase1.", Delivery_TotalTaxBase2 = ".$vDeliveryTotalTaxBase2.
						 ",	Delivery_TransportAmount = ".$vDeliveryTransportAmount.", Delivery_TransportAmountBase1 = ".$vDeliveryTransportAmountBase1. 
						 ",	Delivery_TransportAmountBase2 = ".$vDeliveryTransportAmountBase2.
						 ",	Delivery_TaxableTTC = ".$vDeliveryTaxableTTC.", Delivery_DiscountTTC = ".$vDeliveryDiscountTTC.
						 ",	Delivery_SorderReferences = ".$vSorderReferences.", Detail_Code = ".$vDetailCode.", Delivery_VatChkbx = ".$vDeliveryVatChkbx.
						 ",	Delivery_DirectReturn = ".$vDeliveryDirectReturn.", Destination_Branch = ".$vDestinationBranch.
						 ",	delivery_activevat = ".$vDeliveryActiveVat.", Delivery_TransportTTC = ".$vDeliveryTransportTTC.", Delivery_BonusAccount = ".$vDeliveryBonusAccount.
						 ",	Delivery_BonusAmount = ".$vDeliveryBonusAmount.", Delivery_BonusBase1 = ".$vDeliveryBonusBase1.", Delivery_BonusBase2 = ".$vDeliveryBonusBase2.
						 ", Delivery_BonusTTC = ".$vDeliveryBonusTTC.", Delivery_ManualNo = ".$vDeliveryManualNo.", Delivery_vehicleLoadweight = ".$vVehicleLoadWeight.
						 ", Delivery_vehicleweight = ".$vVehicleWeight.", DELIVERY_LOADHHT = ".$vDeliveryLoadHHT.", CashRegister_Name = ".$vCashRegisterName.
						 ", Delivery_CashInBase1 = ".$vDeliveryCashInBase1.", Delivery_CashInBase2 = ".$vDeliveryCashInBase2.", Delivery_CashOutBase1 = ".$vDeliveryCashOutBase1.
						 ", Delivery_CashOutBase2 = ".$vDeliveryCashOutBase2.", Delivery_TipsBase1 = ".$vDeliveryTipsBase1.
						 "  Where Delivery_Syn_ID = '".$PRecordID."'";
		}
		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Deliveries Set Delivery_Syn_ID = ".$vDeliveryID.
							 " Where Delivery_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In DeliveryDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				$query = " Select RelatedSerial_Id ".
						 " From PurchasesSerialNo ".
						 " Where PurchaseDt_ID In ( Select DeliveryDt_ID From DeliveryDt Where Delivery_ID = '".$vDeliveryID."' ) ".
					     " And Journal_Type = $vJournalType ".
						 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
				//echo $query; exit;		 
				$result=mysql_query($query,$PDestConn);
				while($rows=mysql_fetch_assoc($result)){		 
					$vRelatedSerialID = $rows['RelatedSerial_Id'];
					
					$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
					if($vJournalType == 'DR')
						$sub_query = $sub_query.", flagunique = 0 ";
									
					$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
					$sub_result=mysql_query($sub_query,$PDestConn);
				}
				
				$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select DeliveryDt_ID From DeliveryDt Where Delivery_ID = '".$vDeliveryID."' ) And Journal_Type = $vJournalType ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From DeliveryDt Where Delivery_ID = '".$vDeliveryID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From DeliveryDt
			$query = " Select DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, ".
					 " Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, ".
					 " DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
					 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, ".
					 " Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_ItemAccount, Deliverydt_discountacc, ".
					 " DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, ".
					 " Deliverydt_OldData, Deliverydt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, Deliverydt_costbase1, Deliverydt_costbase2, ".
					 " DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, DeliveryDt_TransportAmountBase2, Item_QtyPacked, Related_Ref, User_Account, ".
					 " DeliveryDt_ExpireDate, Item_Barcode, Delivery_discountTTC, Delivery_taxableTTC, deliverydt_offer, DeliveryDt_BonusAmount, ".
					 " DeliveryDt_BonusBase1, DeliveryDt_BonusBase2, deliverydt_usedqty, DeliveryDt_ClosingQuantity, DeliveryDt_BatchNo ".
					 " From DeliveryDt ".
					 " Where Delivery_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vDeliveryDtID = GetNextSequence1($PDestConn,'DeliveryDt_ID','');
				$vRelatedDtID  = F_Get_DeliveryDtRelatedID($PDestConn, $rows['RelatedDt_Id']);
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['DeliveryDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'DeliveryDt',$vMessage);
					
					break;
				}*/
				
				
				$sub_query = " Insert Into DeliveryDt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Client_Code, Journal_Type, Project_Code, CostCent_Code, ".
							 " Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, ".
							 " DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
							 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, DeliveryDt_Remark, ".
							 " Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_ItemAccount, Deliverydt_discountacc, ".
							 " DeliveryDt_PromoAcc, Deliverydt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, ".
							 " Deliverydt_OldData, Deliverydt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, Deliverydt_costbase1, Deliverydt_costbase2, ".
							 " DeliveryDt_TransportAmount, DeliveryDt_TransportAmountBase1, DeliveryDt_TransportAmountBase2, Item_QtyPacked, Related_Ref, User_Account, ".
							 " DeliveryDt_Syn_ID, Delivery_Syn_ID, DeliveryDt_ExpireDate, Item_Barcode, Delivery_discountTTC, Delivery_taxableTTC, deliverydt_offer, ".
							 " DeliveryDt_BonusAmount, DeliveryDt_BonusBase1, DeliveryDt_BonusBase2, deliverydt_usedqty, DeliveryDt_ClosingQuantity, DeliveryDt_BatchNo ) ".
							 " Values ( ".$vDeliveryDtID.", ".$vDeliveryID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Delivery_Date'],'date').
							 ", ".GetSQLValueString($rows['Client_Code'],'text').", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').
							 ", ".GetSQLValueString($rows['CostCent_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').
							 ", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['DeliveryDt_Quantity'],'double').", ".GetSQLValueString($rows['DeliveryDt_Price'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_PriceBase1'],'double').", ".GetSQLValueString($rows['DeliveryDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_DiscountPer'],'double').", ".GetSQLValueString($rows['DeliveryDt_DiscountAmount'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_DiscountBase1'],'double').", ".GetSQLValueString($rows['DeliveryDt_DiscountBase2'],'double').
							 ", ".GetSQLValueString($rows['Item_Vat'],'double').", ".GetSQLValueString($rows['DeliveryDt_PriceTTC'],'double').
							 ", ".GetSQLValueString($rows['Deliverydt_priceTTCBase1'],'double').", ".GetSQLValueString($rows['Deliverydt_priceTTCBase2'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_Price'],'double').", ".GetSQLValueString($rows['SaleDt_PriceBase1'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_PriceBase2'],'double').", ".GetSQLValueString($rows['DeliveryDt_Remark'],'text').
							 ", ".GetSQLValueString($rows['Deliverydt_DirectStkDbt'],'text').", ".GetSQLValueString($rows['Deliverydt_DirectStkCrd'],'text').
							 ", ".GetSQLValueString($rows['Deliverydt_DirectStkCur'],'text').", ".GetSQLValueString($rows['Deliverydt_ItemAccount'],'text').
							 ", ".GetSQLValueString($rows['Deliverydt_discountacc'],'text').", ".GetSQLValueString($rows['DeliveryDt_PromoAcc'],'text').
							 ", ".GetSQLValueString($rows['Deliverydt_BelongsToGroup'],'int').", ".GetSQLValueString($rows['Item_Tax'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Deliverydt_posted'],'int').", ".GetSQLValueString($rows['Deliverydt_OldData'],'int').
							 ", ".GetSQLValueString($rows['Deliverydt_promotion'],'int').", ".$vRelatedDtID.", ".GetSQLValueString($rows['Item_UnitCoef'],'double').
							 ", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".GetSQLValueString($rows['Deliverydt_costbase1'],'double').
							 ", ".GetSQLValueString($rows['Deliverydt_costbase2'],'double').", ".GetSQLValueString($rows['DeliveryDt_TransportAmount'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_TransportAmountBase1'],'double').", ".GetSQLValueString($rows['DeliveryDt_TransportAmountBase2'],'double').
							 ", ".GetSQLValueString($rows['Item_QtyPacked'],'double').", ".GetSQLValueString($rows['Related_Ref'],'double').
							 ", ".GetSQLValueString($rows['User_Account'],'text').", ".GetSQLValueString($rows['DeliveryDt_id'],'int').", ".$vDeliverySynID.
							 ", ".GetSQLValueString($rows['DeliveryDt_ExpireDate'],'date').", ".GetSQLValueString($rows['Item_Barcode'],'text').
							 ", ".GetSQLValueString($rows['Delivery_discountTTC'],'double').", ".GetSQLValueString($rows['Delivery_taxableTTC'],'double').
							 ", ".GetSQLValueString($rows['deliverydt_offer'],'int').", ".GetSQLValueString($rows['DeliveryDt_BonusAmount'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_BonusBase1'],'double').", ".GetSQLValueString($rows['DeliveryDt_BonusBase2'],'double').
							 ", ".GetSQLValueString($rows['deliverydt_usedqty'],'double').", ".GetSQLValueString($rows['DeliveryDt_ClosingQuantity'],'double').
							 ", ".GetSQLValueString($rows['DeliveryDt_BatchNo'],'text')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
					
					//InCase Insert DeliveryDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, SerialNo_Used, ".
					          " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where DeliveryDt_ID = '".$rows['DeliveryDt_id']."' ".
							  " And Journal_Type = '".$rows['Journal_Type']."'";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
									  " Serial_Syn_ID, Item_ExpireDate, Item_BatchNo) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vDeliveryDtID.", ".$vDeliveryDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int').
									  ", ".GetSQLValueString($rows1['Item_ExpireDate'],'date').", ".GetSQLValueString($rows1['Item_BatchNo'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1 ";
								if($rows1['Journal_Type'] == 'DR')
									$sub_query2 = $sub_query2.", flagunique = Serial_ID ";
									
								$sub_query2 = $sub_query2." Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A SerialNo Then Exit Loop Of DeliveryDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['DeliveryDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'DeliveryDt',$vMessage);
					
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Deliveries Set Journal_ID = '".$vJournalID."' ".
							  " Where Delivery_ID = '".$vDeliveryID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Deliveries',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, Delivery_ID, Owner_Branch ".
					 " From Deliveries Where Delivery_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vJournalType = $sub_result[1];
		$vDeliveryID  = $sub_result[2];
		$vOwnerBranch = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Select RelatedSerial_Id ".
				 " From PurchasesSerialNo ".
				 " Where PurchaseDt_ID In ( Select DeliveryDt_ID From DeliveryDt Where Delivery_ID = '".$vDeliveryID."' ) ".
			     " And Journal_Type = '".$vJournalType."' ".
				 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
		//echo $query; exit;		 
		$result=mysql_query($query,$PDestConn);
		while($rows=mysql_fetch_assoc($result)){		 
			$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
			$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
			if($vJournalType == 'DR')
				$sub_query = $sub_query.", flagunique = 0 ";
									
			$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
			$sub_result=mysql_query($sub_query,$PDestConn);
		}
				
		$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select DeliveryDt_ID From DeliveryDt Where Delivery_ID = '".$vDeliveryID."' ) And Journal_Type = '".$vJournalType."'";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query = "Delete From DeliveryDt Where Delivery_ID = '".$vDeliveryID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Deliveries Where Delivery_ID = '".$vDeliveryID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'DeliveryDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vDeliveryID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroSales($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Sale_ID, Sale_Reference, Sorder_reference, Sale_Date, JournalDt_ValueDate, Sale_Remark, Client_code, ".
				 " Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, Salesman_Code, Currency_Code, Project_Code, Costcenter_code, ".
				 " Sale_Posted, Sale_Edit, Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, ".
				 " Sale_NoneTaxableBase2, Sale_DiscountAmount, Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, ".
				 " Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, Sale_Mode, Journal_Type, Journal_Id, ".
				 " Sales_BelongsToGroup, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
				 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, ".
				 " Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, Sale_TotalTax, Sale_TotalTaxBase1, ".
				 " Sale_TotalTaxBase2, Sale_CreditCur, Sale_CreditAccount, Sale_TipsAccount, Sale_Vataccount, Sale_creditaccountvat, ".
				 " Sale_CreditCLA, Sale_CreditDCT, Sale_CreditAW, Sale_CreditTRP, Sale_PromotionAcc, Sale_chkvat, sale_activevat, ".
				 " Sale_TaxableTTC, Sale_DiscountTTC, Sale_RelatedId, Sale_SorderReferences, Sale_DeliveryReferences, Sale_TransportAccount, ".
				 " Sale_TransportAmount, Sale_TransportBase1, Sale_TransportBase2, Sale_TransportTTC, Sale_BonusAccount, Sale_BonusAmount, ".
				 " Sale_BonusBase1, Sale_BonusBase2, Sale_BonusTTC, User_Account, Owner_Branch, Destination_Branch, Sale_Syn_ID, ".
				 " CashRegister_Name, Sale_ManualNo, Sale_vehicleLoadweight, Sale_vehicleweight, Sale_vehicleRealweight, Sale_PrintReceipt, ".
				 " Sale_CashInBase1, Sale_CashInBase2, Sale_CashOutBase1, Sale_CashOutBase2, Sale_TipsBase1 ".
				 " From Sales ".
				 " Where Sale_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vSaleSynID		 	   = GetSQLValueString($rows['Sale_ID'],'int');
		$vJournalSynID		   = GetSQLValueString($rows['Journal_Id'],'int');
		$vSaleReference	 	   = GetSQLValueString($rows['Sale_Reference'],'double');
		$vSorderReference      = GetSQLValueString($rows['Sorder_reference'],'double');
		$vSorderReferences     = GetSQLValueString($rows['Sale_SorderReferences'],'double');
		$vDeliveryReferences   = GetSQLValueString($rows['Sale_DeliveryReferences'],'double');
		$vSaleDate			   = GetSQLValueString($rows['Sale_Date'],'date');
		$vJournalDtValueDate   = GetSQLValueString($rows['JournalDt_ValueDate'],'date');
		$vSaleRemark	 	   = GetSQLValueString($rows['Sale_Remark'],'text');
		$vClientCode		   = GetSQLValueString($rows['Client_code'],'text');
		$vSaleShippedTo  	   = GetSQLValueString($rows['Sale_ShippedTo'],'text');
		$vSaleMarks			   = GetSQLValueString($rows['Sale_Marks'],'text');
		$vSaleShippedVia	   = GetSQLValueString($rows['Sale_ShippedVia'],'text');
		$vSalesmanCode		   = GetSQLValueString($rows['Salesman_Code'],'text');
		$vCurrencyCode		   = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		   = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		   = GetSQLValueString($rows['Costcenter_code'],'text');
		$vSalePosted		   = GetSQLValueString($rows['Sale_Posted'],'int');
		$vSaleEdit			   = GetSQLValueString($rows['Sale_Edit'],'int');
		$vSaleTaxable		   = GetSQLValueString($rows['Sale_Taxable'],'double');
		$vSaleTaxableBase1	   = GetSQLValueString($rows['Sale_TaxableBase1'],'double');
		$vSaleTaxableBase2	   = GetSQLValueString($rows['Sale_TaxableBase2'],'double');
		$vSaleNoneTaxable	   = GetSQLValueString($rows['Sale_NoneTaxable'],'double');
		$vSaleNoneTaxableBase1 = GetSQLValueString($rows['Sale_NoneTaxableBase1'],'double');
		$vSaleNoneTaxableBase2 = GetSQLValueString($rows['Sale_NoneTaxableBase2'],'double');
		$vSaleDiscountAmount   = GetSQLValueString($rows['Sale_DiscountAmount'],'double');
		$vSaleDiscountBase1	   = GetSQLValueString($rows['Sale_DiscountBase1'],'double');
		$vSaleDiscountBase2    = GetSQLValueString($rows['Sale_DiscountBase2'],'double');
		$vSaleDiscountPer	   = GetSQLValueString($rows['Sale_DiscountPer'],'double');
		$vSaleVAT			   = GetSQLValueString($rows['Sale_VAT'],'double');
		$vSaleVATBase1		   = GetSQLValueString($rows['Sale_VATBase1'],'double');
		$vSaleVATBase2		   = GetSQLValueString($rows['Sale_VATBase2'],'double');
		$vSaleTotal			   = GetSQLValueString($rows['Sale_Total'],'double');
		$vSaleTotalBase1	   = GetSQLValueString($rows['Sale_TotalBase1'],'double');
		$vSaleTotalBase2	   = GetSQLValueString($rows['Sale_TotalBase2'],'double');
		$vSaleMode			   = GetSQLValueString($rows['Sale_Mode'],'int');
		$vJournalType 		   = GetSQLValueString($rows['Journal_Type'],'text');
		$vSaleBelongsToGroup   = GetSQLValueString($rows['Sales_BelongsToGroup'],'int');
		$vSaleTax1 		= GetSQLValueString($rows['Sale_Tax1'],'double');
		$vSaleTax2 		= GetSQLValueString($rows['Sale_Tax2'],'double');
		$vSaleTax3 		= GetSQLValueString($rows['Sale_Tax3'],'double');
		$vSaleTax4 		= GetSQLValueString($rows['Sale_Tax4'],'double');
		$vSaleTax5 		= GetSQLValueString($rows['Sale_Tax5'],'double');
		$vSaleTax1Base1 = GetSQLValueString($rows['Sale_Tax1Base1'],'double');
		$vSaleTax2Base1 = GetSQLValueString($rows['Sale_Tax2Base1'],'double');
		$vSaleTax3Base1 = GetSQLValueString($rows['Sale_Tax3Base1'],'double');
		$vSaleTax4Base1 = GetSQLValueString($rows['Sale_Tax4Base1'],'double');
		$vSaleTax5Base1 = GetSQLValueString($rows['Sale_Tax5Base1'],'double');
		$vSaleTax1Base2 = GetSQLValueString($rows['Sale_Tax1Base2'],'double');
		$vSaleTax2Base2 = GetSQLValueString($rows['Sale_Tax2Base2'],'double');
		$vSaleTax3Base2 = GetSQLValueString($rows['Sale_Tax3Base2'],'double');
		$vSaleTax4Base2 = GetSQLValueString($rows['Sale_Tax4Base2'],'double');
		$vSaleTax5Base2 = GetSQLValueString($rows['Sale_Tax5Base2'],'double');
		$vSaleAcctax1 	= GetSQLValueString($rows['Sale_Acctax1'],'text');
		$vSaleAcctax2 	= GetSQLValueString($rows['Sale_Acctax2'],'text');
		$vSaleAcctax3 	= GetSQLValueString($rows['Sale_Acctax3'],'text');
		$vSaleAcctax4 	= GetSQLValueString($rows['Sale_Acctax4'],'text');
		$vSaleAcctax5 	= GetSQLValueString($rows['Sale_Acctax5'],'text');
		$vSaleTotalTax  = GetSQLValueString($rows['Sale_TotalTax'],'double');
		$vSaleTotalTaxBase1		   = GetSQLValueString($rows['Sale_TotalTaxBase1'],'double');
		$vSaleTotalTaxBase2		   = GetSQLValueString($rows['Sale_TotalTaxBase2'],'double');
		$vSaleCreditCur 		   = GetSQLValueString($rows['Sale_CreditCur'],'text');
		$vSaleCreditAccount		   = GetSQLValueString($rows['Sale_CreditAccount'],'text');
		$vSaleTipsAccount		   = GetSQLValueString($rows['Sale_TipsAccount'],'text');
		$vSaleVatAccount		   = GetSQLValueString($rows['Sale_Vataccount'],'text');
		$vSaleCreditAccountVat	   = GetSQLValueString($rows['Sale_creditaccountvat'],'text');
		$vSalePromotionAcc		   = GetSQLValueString($rows['Sale_PromotionAcc'],'text');
		$vSaleCreditCLA		  	   = GetSQLValueString($rows['Sale_CreditCLA'],'text');
		$vSaleCreditDCT		       = GetSQLValueString($rows['Sale_CreditDCT'],'text');
		$vSaleCreditAW		   	   = GetSQLValueString($rows['Sale_CreditAW'],'text');
		$vSaleCreditTRP		       = GetSQLValueString($rows['Sale_CreditTRP'],'text');
		$vSaleTransportAccount 	   = GetSQLValueString($rows['Sale_TransportAccount'],'text');
		$vSaleTransportAmount	   = GetSQLValueString($rows['Sale_TransportAmount'],'double');
		$vSaleTransportAmountBase1 = GetSQLValueString($rows['Sale_TransportBase1'],'double');
		$vSaleTransportAmountBase2 = GetSQLValueString($rows['Sale_TransportBase2'],'double');
		$vSaleBonusAccount 		   = GetSQLValueString($rows['Sale_BonusAccount'],'text');
		$vSaleBonusAmount	  	   = GetSQLValueString($rows['Sale_BonusAmount'],'double');
		$vSaleBonusAmountBase1	   = GetSQLValueString($rows['Sale_BonusBase1'],'double');
		$vSaleBonusAmountBase2	   = GetSQLValueString($rows['Sale_BonusBase2'],'double');
		$vSaleTransportTTC 		   = GetSQLValueString($rows['Sale_TransportTTC'],'double');
		$vSaleBonusTTC 		   	   = GetSQLValueString($rows['Sale_BonusTTC'],'double');
		$vSaleTaxableTTC 		   = GetSQLValueString($rows['Sale_TaxableTTC'],'double');
		$vSaleDiscountTTC		   = GetSQLValueString($rows['Sale_DiscountTTC'],'double');
		$vSaleVatChkbx			   = GetSQLValueString($rows['Sale_chkvat'],'int');
		$vSaleActiveVat 		   = GetSQLValueString($rows['sale_activevat'],'int');
		$vSaleRelatedId 		   = GetSQLValueString($rows['Sale_RelatedId'],'double');
		$vCashRegisterName 		   = GetSQLValueString($rows['CashRegister_Name'],'text');
		$vSaleManualNo 			   = GetSQLValueString($rows['Sale_ManualNo'],'text');
		$vVehicleLoadWeight		   = GetSQLValueString($rows['Sale_vehicleLoadweight'],'double');
		$vVehicleWeight 		   = GetSQLValueString($rows['Sale_vehicleweight'],'double');
		$vVehicleRealWeight 	   = GetSQLValueString($rows['Sale_vehicleRealweight'],'double');
		$vSalePrintReceipt 		   = GetSQLValueString($rows['Sale_PrintReceipt'],'int');
		$vSaleCashInBase1 		   = GetSQLValueString($rows['Sale_CashInBase1'],'double');
		$vSaleCashInBase2 		   = GetSQLValueString($rows['Sale_CashInBase2'],'double');
		$vSaleCashOutBase1 		   = GetSQLValueString($rows['Sale_CashOutBase1'],'double');
		$vSaleCashOutBase2 		   = GetSQLValueString($rows['Sale_CashOutBase2'],'double');
		$vSaleTipsBase1 		   = GetSQLValueString($rows['Sale_TipsBase1'],'double');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		 
		/*$vCheckClientID	   = F_Check_ClientID($PDestConn, $vClientID);
		$vCheckSalesmanID  = F_Check_SalesmanID($PDestConn, $vSalesmanID);
		$vCheckCurrencyID  = F_Check_CurrencyID($PDestConn, $vCurrencyID);
		$vCheckProjectID   = F_Check_ProjectID($PDestConn, $vProjectID);
		$vCheckCostCentID  = F_Check_CostCentID($PDestConn, $vCostCentID);
		
		if ($vCheckClientID == 0 || $vCheckSalesmanID == 0 || $vCheckCurrencyID == 0 || 
		    $vCheckProjectID == 0 || $vCheckCostCentID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Client|Salesman|Currency|Project|CostCent not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Sales',$vMessage);
			
			Return $vResult;
		}*/
		
		$sub_query  = " Select Count(*) From Sales ".
		              " Where Sale_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vSaleID = GetNextSequence1($PDestConn,'Sales_ID','');
			
			$sub_query = " Insert Into Sales (Sale_ID, Sale_Reference, Sorder_reference, Sale_Date, JournalDt_ValueDate, Sale_Remark, ".
						 " Client_code, Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, Salesman_Code, Currency_Code, Project_Code, Costcenter_code, ".
						 " Sale_Posted, Sale_Edit, Sale_Taxable, Sale_TaxableBase1, Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, ".
						 " Sale_NoneTaxableBase2, Sale_DiscountAmount, Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, ".
						 " Sale_VATBase1, Sale_VATBase2, Sale_Total, Sale_TotalBase1, Sale_TotalBase2, Sale_Mode, Journal_Type, ".
						 " Sales_BelongsToGroup, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
						 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, ".
						 " Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, Sale_TotalTax, Sale_TotalTaxBase1, ".
						 " Sale_TotalTaxBase2, Sale_CreditCur, Sale_CreditAccount, Sale_TipsAccount, Sale_Vataccount, Sale_creditaccountvat, ".
						 " Sale_CreditCLA, Sale_CreditDCT, Sale_CreditAW, Sale_CreditTRP, Sale_PromotionAcc, Sale_chkvat, sale_activevat, ".
						 " Sale_TaxableTTC, Sale_DiscountTTC, Sale_RelatedId, Sale_SorderReferences, Sale_DeliveryReferences, Sale_TransportAccount, ".
						 " Sale_TransportAmount, Sale_TransportBase1, Sale_TransportBase2, Sale_TransportTTC, Sale_BonusAccount, Sale_BonusAmount, ".
						 " Sale_BonusBase1, Sale_BonusBase2, Sale_BonusTTC, User_Account, Owner_Branch, Destination_Branch, Sale_Syn_ID, ".
						 " CashRegister_Name, Sale_ManualNo, Sale_vehicleLoadweight, Sale_vehicleweight, Sale_vehicleRealweight, Sale_PrintReceipt, ".
						 " Sale_CashInBase1, Sale_CashInBase2, Sale_CashOutBase1, Sale_CashOutBase2, Sale_TipsBase1 ) ".
						 " Values ( ".$vSaleID.", ".$vSaleReference.", ".$vSorderReference.", ".$vSaleDate.", ".$vJournalDtValueDate.", ".$vSaleRemark.
						 ", ".$vClientCode.", ".$vSaleShippedTo.", ".$vSaleMarks.", ".$vSaleShippedVia.", ".$vSalesmanCode.", ".$vCurrencyCode.", ".$vProjectCode.
						 ", ".$vCostcentCode.", ".$vSalePosted.", ".$vSaleEdit.", ".$vSaleTaxable.", ".$vSaleTaxableBase1.", ".$vSaleTaxableBase2.
						 ", ".$vSaleNoneTaxable.", ".$vSaleNoneTaxableBase1.", ".$vSaleNoneTaxableBase2.", ".$vSaleDiscountAmount.", ".$vSaleDiscountBase1.
						 ", ".$vSaleDiscountBase2.", ".$vSaleDiscountPer.", ".$vSaleVAT.", ".$vSaleVATBase1.", ".$vSaleVATBase2.", ".$vSaleTotal.
						 ", ".$vSaleTotalBase1.", ".$vSaleTotalBase2.", ".$vSaleMode.", ".$vJournalType.", ".$vSaleBelongsToGroup.
						 ", ".$vSaleTax1.", ".$vSaleTax2.", ".$vSaleTax3.", ".$vSaleTax4.", ".$vSaleTax5.
						 ", ".$vSaleTax1Base1.", ".$vSaleTax2Base1.", ".$vSaleTax3Base1.", ".$vSaleTax4Base1.", ".$vSaleTax5Base1.
						 ", ".$vSaleTax1Base2.", ".$vSaleTax2Base2.", ".$vSaleTax3Base2.", ".$vSaleTax4Base2.", ".$vSaleTax5Base2.
						 ", ".$vSaleAcctax1.", ".$vSaleAcctax2.", ".$vSaleAcctax3.", ".$vSaleAcctax4.", ".$vSaleAcctax5.
						 ", ".$vSaleTotalTax.", ".$vSaleTotalTaxBase1.", ".$vSaleTotalTaxBase2.", ".$vSaleCreditCur.", ".$vSaleCreditAccount.
						 ", ".$vSaleTipsAccount.", ".$vSaleVatAccount.", ".$vSaleCreditAccountVat.", ".$vSaleCreditCLA.", ".$vSaleCreditDCT.
						 ", ".$vSaleCreditAW.", ".$vSaleCreditTRP.", ".$vSalePromotionAcc.", ".$vSaleVatChkbx.", ".$vSaleActiveVat.
						 ", ".$vSaleTaxableTTC.", ".$vSaleDiscountTTC.", ".$vSaleRelatedId.", ".$vSorderReferences.", ".$vDeliveryReferences.
						 ", ".$vSaleTransportAccount.", ".$vSaleTransportAmount.", ".$vSaleTransportAmountBase1.", ".$vSaleTransportAmountBase2.
						 ", ".$vSaleTransportTTC.", ".$vSaleBonusAccount.", ".$vSaleBonusAmount.", ".$vSaleBonusAmountBase1.", ".$vSaleBonusAmountBase2.
						 ", ".$vSaleBonusTTC.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vSaleSynID.", ".$vCashRegisterName.
						 ", ".$vSaleManualNo.", ".$vVehicleLoadWeight.", ".$vVehicleWeight.", ".$vVehicleRealWeight.", ".$vSalePrintReceipt.
						 ", ".$vSaleCashInBase1.", ".$vSaleCashInBase2.", ".$vSaleCashOutBase1.", ".$vSaleCashOutBase2.", ".$vSaleTipsBase1." )";
		}	
		
		//Case Record Exists - Update
		else {
			$query  = " Select Sale_ID From Sales ".
					  " Where Sale_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vSaleID = $result[0];
			
			$sub_query = "  Update Sales Set Sale_Date = ".$vSaleDate.", JournalDt_ValueDate = ".$vJournalDtValueDate. 
						 ",	Sale_Remark = ".$vSaleRemark.", Client_code = ".$vClientCode.", Sale_ShippedTo = ".$vSaleShippedTo. 
						 ",	Sale_Marks = ".$vSaleMarks.", Sale_ShippedVia = ".$vSaleShippedVia.", Salesman_Code = ".$vSalesmanCode. 
						 ",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcenter_code = ".$vCostcentCode. 
						 ",	Sale_Posted = ".$vSalePosted.", Sale_Edit = ".$vSaleEdit.", Sale_Taxable = ".$vSaleTaxable. 
						 ",	Sale_TaxableBase1 = ".$vSaleTaxableBase1.", Sale_TaxableBase2 = ".$vSaleTaxableBase2. 
						 ",	Sale_NoneTaxable = ".$vSaleNoneTaxable.", Sale_NoneTaxableBase1 = ".$vSaleNoneTaxableBase1. 
						 ", Sale_NoneTaxableBase2 = ".$vSaleNoneTaxableBase2.", Sale_DiscountAmount = ".$vSaleDiscountAmount. 
						 ",	Sale_DiscountBase1 = ".$vSaleDiscountBase1.", Sale_DiscountBase2 = ".$vSaleDiscountBase2. 
						 ",	Sale_DiscountPer = ".$vSaleDiscountPer.", Sale_VAT = ".$vSaleVAT.", Sale_VATBase1 = ".$vSaleVATBase1. 
						 ",	Sale_VATBase2 = ".$vSaleVATBase2.", Sale_Total = ".$vSaleTotal.", Sale_TotalBase1 = ".$vSaleTotalBase1. 
						 ",	Sale_TotalBase2 = ".$vSaleTotalBase2.", Sale_Mode = ".$vSaleMode. 
						 ",	Journal_Type = ".$vJournalType.", Sale_Tax1 = ".$vSaleTax1.", Sale_Tax1Base1 = ".$vSaleTax1Base1. 
						 ",	Sale_Tax1Base2 = ".$vSaleTax1Base2.", Sale_Tax2 = ".$vSaleTax2.", Sale_Tax2Base1 = ".$vSaleTax2Base1. 
						 ",	Sale_Tax2Base2 = ".$vSaleTax2Base2.", Sale_Tax3 = ".$vSaleTax3.", Sale_Tax3Base1 = ".$vSaleTax3Base1. 
						 ",	Sale_Tax3Base2 = ".$vSaleTax3Base2.", Sale_Tax4 = ".$vSaleTax3.", Sale_Tax4Base1 = ".$vSaleTax4Base1. 
						 ",	Sale_Tax4Base2 = ".$vSaleTax4Base2.", Sale_Tax5 = ".$vSaleTax5.", Sale_Tax5Base1 = ".$vSaleTax5Base1. 
						 ", Sale_Tax5Base2 = ".$vSaleTax5Base2.", Sale_Acctax1 = ".$vSaleAcctax1.", Sale_Acctax2 = ".$vSaleAcctax2. 
						 ",	Sale_Acctax3 = ".$vSaleAcctax3.", Sale_Acctax4 = ".$vSaleAcctax4.", Sale_Acctax5 = ".$vSaleAcctax5. 
						 ",	Sale_TotalTax = ".$vSaleTotalTax.", Sale_TotalTaxBase1 = ".$vSaleTotalTaxBase1.", Sale_TotalTaxBase2 = ".$vSaleTotalTaxBase2.
						 ",	Sale_TransportAmount = ".$vSaleTransportAmount.", Sale_TransportAmountBase1 = ".$vSaleTransportAmountBase1. 
						 ",	Sale_TransportAmountBase2 = ".$vSaleTransportAmountBase2.",	Sale_TransportTTC = ".$vSaleTransportTTC.
						 ",	Sale_BonusAmount = ".$vSaleBonusAmount.", Sale_BonusBase1 = ".$vSaleBonusAmountBase1. 
						 ",	Sale_BonusBase2 = ".$vSaleBonusAmountBase2.",	Sale_BonusTTC = ".$vSaleBonusTTC.
						 ",	Sale_TaxableTTC = ".$vSaleTaxableTTC.", Sale_DiscountTTC = ".$vSaleDiscountTTC.", Sale_RelatedId = ".$vSaleRelatedId.
						 ",	Sale_SorderReferences = ".$vSorderReferences.", Sale_DeliveryReferences = ".$vDeliveryReferences.
						 ", Sale_chkvat = ".$vSaleVatChkbx.", sale_activevat = ".$vSaleActiveVat.", Destination_Branch = ".$vDestinationBranch.
						 ",	CashRegister_Name = ".$vCashRegisterName.", Sale_ManualNo = ".$vSaleManualNo.", Sale_vehicleLoadweight = ".$vVehicleLoadWeight.
						 ",	Sale_vehicleweight = ".$vVehicleWeight.", Sale_vehicleRealweight = ".$vVehicleRealWeight.", Sale_PrintReceipt = ".$vSalePrintReceipt.
						 ",	Sale_CashInBase1 = ".$vSaleCashInBase1.", Sale_CashInBase2 = ".$vSaleCashInBase2.", Sale_CashOutBase1 = ".$vSaleCashOutBase1.
						 ",	Sale_CashOutBase2 = ".$vSaleCashOutBase2.", Sale_TipsBase1 = ".$vSaleTipsBase1.
						 "  Where Sale_Syn_ID = '".$PRecordID."'";
		}
		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Sales Set Sale_Syn_ID = ".$vSaleID.
							 " Where Sale_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In SalesDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				$query = " Select RelatedSerial_Id ".
						 " From PurchasesSerialNo ".
						 " Where PurchaseDt_ID In ( Select SaleDt_ID From SalesDt Where Sale_ID = '".$vSaleID."' ) ".
					     " And Journal_Type = $vJournalType ".
						 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
				//echo $query; exit;		 
				$result=mysql_query($query,$PDestConn);
				while($rows=mysql_fetch_assoc($result)){		 
					$vRelatedSerialID = $rows['RelatedSerial_Id'];
					
					$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
					if($vJournalType == 'DR')
						$sub_query = $sub_query.", flagunique = 0 ";
									
					$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
					$sub_result=mysql_query($sub_query,$PDestConn);
				}
				
				$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select SaleDt_ID From SalesDt Where Sale_ID = '".$vSaleID."' ) And Journal_Type = $vJournalType ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From SalesDt Where Sale_ID = '".$vSaleID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From SalesDt
			$query = " Select SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, ".
					 " Warehouse_Code, Item_code, Item_CodePacked, SaleDt_Quantity, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, ".
					 " SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, Item_Vat, SaleDt_PriceTTC, ".
					 " Saledt_priceTTCBase1, Saledt_priceTTCBase2, SalesDt_Remark, Saledt_DirectStkDbt, Saledt_DirectStkCrd, Saledt_DirectStkCur, ".
					 " Saledt_ItemAccount, SaleDt_DiscountAcc, Saledt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
					 " Saledt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, SaleDt_TransportAmount, SaleDt_TransportBase1, SaleDt_TransportBase2, ".
					 " SaleDt_BonusAmount, SaleDt_BonusBase1, SaleDt_BonusBase2, SaleDt_Syn_ID, Sale_Syn_ID, SaleDt_ExpireDate, Item_Barcode, salesdt_offer, ".
					 " SaleDt_BatchNo ".
					 " From SalesDt ".
					 " Where Sale_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vSaleDtID = GetNextSequence1($PDestConn,'SaleDt_ID','');
				$vRelatedDtID  = F_Get_SalesDtRelatedID($PDestConn, $rows['RelatedDt_Id']);
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SaleDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'SalesDt',$vMessage);
					
					break;
				}*/
				
				$sub_query = " Insert Into SalesDt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, ".
							 " Warehouse_Code, Item_code, Item_CodePacked, SaleDt_Quantity, SaleDt_Price, SaleDt_PriceBase1, SaleDt_PriceBase2, ".
							 " SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, Item_Vat, SaleDt_PriceTTC, ".
							 " Saledt_priceTTCBase1, Saledt_priceTTCBase2, SalesDt_Remark, Saledt_DirectStkDbt, Saledt_DirectStkCrd, Saledt_DirectStkCur, ".
							 " Saledt_ItemAccount, SaleDt_DiscountAcc, Saledt_BelongsToGroup, Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
							 " Saledt_promotion, RelatedDt_Id, Item_UnitCoef, Item_Unit2Qty, SaleDt_TransportAmount, SaleDt_TransportBase1, SaleDt_TransportBase2, ".
							 " SaleDt_BonusAmount, SaleDt_BonusBase1, SaleDt_BonusBase2, SaleDt_FtsiCLAAMT, SaleDt_FtsiDCTAMT, SaleDt_FtsiAWAMT, SaleDt_FtsiTRPAMT, ".
							 " Saledt_FTsiSOF, SaleDt_Syn_ID, Sale_Syn_ID, SaleDt_ExpireDate, Item_Barcode, salesdt_offer, SaleDt_BatchNo ) ".
							 " Values ( ".$vSaleDtID.", ".$vSaleID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Sale_Date'],'date').
							 ", ".GetSQLValueString($rows['Client_Code'],'text').", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').
							 ", ".GetSQLValueString($rows['CostCenter_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').
							 ", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['SaleDt_Quantity'],'double').", ".GetSQLValueString($rows['SaleDt_Price'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_PriceBase1'],'double').", ".GetSQLValueString($rows['SaleDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_DiscountPer'],'double').", ".GetSQLValueString($rows['SaleDt_DiscountAmount'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_DiscountBase1'],'double').", ".GetSQLValueString($rows['SaleDt_DiscountBase2'],'double').
							 ", ".GetSQLValueString($rows['Item_Vat'],'double').", ".GetSQLValueString($rows['SaleDt_PriceTTC'],'double').
							 ", ".GetSQLValueString($rows['Saledt_priceTTCBase1'],'double').", ".GetSQLValueString($rows['Saledt_priceTTCBase2'],'double').
							 ", ".GetSQLValueString($rows['SalesDt_Remark'],'text').", ".GetSQLValueString($rows['Saledt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['Saledt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['Saledt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['Saledt_ItemAccount'],'text').", ".GetSQLValueString($rows['SaleDt_DiscountAcc'],'text').
							 ", ".GetSQLValueString($rows['Saledt_BelongsToGroup'],'int').", ".GetSQLValueString($rows['Item_Tax'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Saledt_promotion'],'int').", ".$vRelatedDtID.", ".GetSQLValueString($rows['Item_UnitCoef'],'double').
							 ", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".GetSQLValueString($rows['SaleDt_TransportAmount'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_TransportBase1'],'double').", ".GetSQLValueString($rows['SaleDt_TransportBase2'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_BonusAmount'],'double').", ".GetSQLValueString($rows['SaleDt_BonusBase1'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_BonusBase2'],'double').", ".GetSQLValueString($rows['SaleDt_FtsiCLAAMT'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_FtsiDCTAMT'],'double').", ".GetSQLValueString($rows['SaleDt_FtsiAWAMT'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_FtsiTRPAMT'],'double').", ".GetSQLValueString($rows['Saledt_FTsiSOF'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_id'],'int').", ".GetSQLValueString($rows['SaleDt_ExpireDate'],'date').
							 ", ".GetSQLValueString($rows['Item_Barcode'],'text').", ".GetSQLValueString($rows['salesdt_offer'],'int').
							 ", ".GetSQLValueString($rows['SaleDt_BatchNo'],'text')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
					
					//InCase Insert SalesDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, SaleDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, SerialNo_Used, ".
					          " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where SaleDt_ID = '".$rows['SaleDt_id']."' ".
							  " And Journal_Type = '".$rows['Journal_Type']."'";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, SaleDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
									  " Serial_Syn_ID, Item_ExpireDate, Item_BatchNo) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vSaleDtID.", ".$vSaleDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int').
									  ", ".GetSQLValueString($rows1['Item_ExpireDate'],'text').", ".GetSQLValueString($rows1['Item_BatchNo'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1 ";
								if($rows1['Journal_Type'] == 'DR')
									$sub_query2 = $sub_query2.", flagunique = Serial_ID ";
									
								$sub_query2 = $sub_query2." Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A SerialNo Then Exit Loop Of SalesDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SaleDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'SalesDt',$vMessage);
					
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Sales Set Journal_ID = '".$vJournalID."' ".
							  " Where Sale_ID = '".$vSaleID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Sales',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, Sale_ID, Owner_Branch ".
					 " From Sales Where Sale_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vJournalType = $sub_result[1];
		$vSaleID 	  = $sub_result[2];
		$vOwnerBranch = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Select RelatedSerial_Id ".
				 " From PurchasesSerialNo ".
				 " Where PurchaseDt_ID In ( Select SaleDt_ID From SalesDt Where Sale_ID = '".$vSaleID."' ) ".
			     " And Journal_Type = '".$vJournalType."' ".
				 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
		//echo $query; exit;		 
		$result=mysql_query($query,$PDestConn);
		while($rows=mysql_fetch_assoc($result)){		 
			$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
			$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
			if($vJournalType == 'DR')
				$sub_query = $sub_query.", flagunique = 0 ";
									
			$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
			$sub_result=mysql_query($sub_query,$PDestConn);
		}
				
		$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select SaleDt_ID From SalesDt Where Sale_ID = '".$vSaleID."' ) And Journal_Type = '".$vJournalType."'";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query = "Delete From SalesDt Where Sale_ID = '".$vSaleID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Sales Where Sale_ID = '".$vSaleID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vSaleID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'SalesDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vSaleID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}


function F_SynchroPRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select PRqst_ID, PRqst_Reference, PRqst_Date, PRqst_RequestDate, PRqst_RequestBy, Currency_Code, Project_Code, ".
				 " Costcent_code, Supplier_code, PRqst_SupplierContract, PRqst_Remark, PRqst_Posted, Expiry_date, PRqst_Import, ".
				 " PRqst_Status, Status_Remark, PRqst_DeliveryDate, PRqst_DeliveryPlace, PRqst_DeliveryContact, PRqst_Taxable, ".
				 " PRqst_TaxableBase1, PRqst_TaxableBase2, PRqst_NoneTaxable, PRqst_NoneTaxableBase1, PRqst_NoneTaxableBase2, ".
				 " PRqst_DiscountAmount, PRqst_DiscountBase1, PRqst_DiscountBase2, PRqst_DiscountPer, PRqst_Total, PRqst_TotalBase1, ".
				 " PRqst_TotalBase2, PRqst_Vat, PRqst_VatBase1, PRqst_VatBase2, Prqst_VatChkBox, PRqst_Tax1, PRqst_Tax1Base1, ".
				 " PRqst_Tax1Base2, PRqst_Tax2, PRqst_Tax2Base1, PRqst_Tax2Base2, PRqst_Tax3, PRqst_Tax3Base1, PRqst_Tax3Base2, ".
				 " PRqst_Tax4, PRqst_Tax4Base1, PRqst_Tax4Base2, PRqst_Tax5, PRqst_Tax5Base1, PRqst_Tax5Base2, PRqst_Type, ".
				 " PRqst_Confirmed, PRqst_BelongsToGroup, PRqst_warranty, PRqst_document, PRqst_TotalQuantity, PRqst_TotalQuantityUsed, ".
				 " PRqst_Application, PRqst_Approved, PRqst_ApprovedBy, rejectedreason, User_Name, Owner_Branch, Destination_Branch, PRqst_Syn_ID ".
				 " From PRequest ".
				 " Where PRqst_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vPRqstSynID		 = GetSQLValueString($rows['PRqst_ID'],'int');
		$vPRqstReference	 = GetSQLValueString($rows['PRqst_Reference'],'double');
		$vPRqstDate		 	 = GetSQLValueString($rows['PRqst_Date'],'date');
		$vPRqstRemark	     = GetSQLValueString($rows['PRqst_Remark'],'text');
		$vPRqstRequestBy     = GetSQLValueString($rows['PRqst_RequestBy'],'text');
		$vPRqstRequestDate   = GetSQLValueString($rows['PRqst_RequestDate'],'date');
		$vSupplierCode		 = GetSQLValueString($rows['Supplier_code'],'text');
		$vSupplierContact    = GetSQLValueString($rows['PRqst_SupplierContract'],'text');
		$vDeliveryDate       = GetSQLValueString($rows['PRqst_DeliveryDate'],'date');
		$vDeliveryPlace		 = GetSQLValueString($rows['PRqst_DeliveryPlace'],'text');
		$vDeliveryContact    = GetSQLValueString($rows['PRqst_DeliveryContact'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vPRqstPosted		 = GetSQLValueString($rows['PRqst_Posted'],'int');
		$vPRqstImport	     = GetSQLValueString($rows['PRqst_Import'],'int');
		$vExpiryDate         = GetSQLValueString($rows['Expiry_date'],'date');
		$vPRqstStatus		 = GetSQLValueString($rows['PRqst_Status'],'text');
		$vStatusRemark		 = GetSQLValueString($rows['Status_Remark'],'text');
		$vPRqstTaxable		 = GetSQLValueString($rows['PRqst_Taxable'],'double');
		$vPRqstTaxableBase1	 = GetSQLValueString($rows['PRqst_TaxableBase1'],'double');
		$vPRqstTaxableBase2	 = GetSQLValueString($rows['PRqst_TaxableBase2'],'double');
		$vPRqstNoneTaxable	    = GetSQLValueString($rows['PRqst_NoneTaxable'],'double');
		$vPRqstNoneTaxableBase1 = GetSQLValueString($rows['PRqst_NoneTaxableBase1'],'double');
		$vPRqstNoneTaxableBase2 = GetSQLValueString($rows['PRqst_NoneTaxableBase2'],'double');
		$vPRqstDiscountAmount   = GetSQLValueString($rows['PRqst_DiscountAmount'],'double');
		$vPRqstDiscountBase1	= GetSQLValueString($rows['PRqst_DiscountBase1'],'double');
		$vPRqstDiscountBase2    = GetSQLValueString($rows['PRqst_DiscountBase2'],'double');
		$vPRqstDiscountPer	   	= GetSQLValueString($rows['PRqst_DiscountPer'],'double');
		$vPRqstTotalAmount      = GetSQLValueString($rows['PRqst_Total'],'double');
		$vPRqstTotalBase1	 	= GetSQLValueString($rows['PRqst_TotalBase1'],'double');
		$vPRqstTotalBase2    	= GetSQLValueString($rows['PRqst_TotalBase2'],'double');
		$vPRqstVAT			   	= GetSQLValueString($rows['PRqst_Vat'],'double');
		$vPRqstVATBase1		 	= GetSQLValueString($rows['PRqst_VatBase1'],'double');
		$vPRqstVATBase2		 	= GetSQLValueString($rows['PRqst_VatBase2'],'double');
		$vTotalQuantity		    = GetSQLValueString($rows['PRqst_TotalQuantity'],'double');
		$vTotalQuantityUsed 	= GetSQLValueString($rows['PRqst_TotalQuantityUsed'],'double');
		$vPRqstTax1 			= GetSQLValueString($rows['PRqst_Tax1'],'double');
		$vPRqstTax2 			= GetSQLValueString($rows['PRqst_Tax2'],'double');
		$vPRqstTax3 			= GetSQLValueString($rows['PRqst_Tax3'],'double');
		$vPRqstTax4 			= GetSQLValueString($rows['PRqst_Tax4'],'double');
		$vPRqstTax5 			= GetSQLValueString($rows['PRqst_Tax5'],'double');
		$vPRqstTax1Base1  		= GetSQLValueString($rows['PRqst_Tax1Base1'],'double');
		$vPRqstTax2Base1   		= GetSQLValueString($rows['PRqst_Tax2Base1'],'double');
		$vPRqstTax3Base1   		= GetSQLValueString($rows['PRqst_Tax3Base1'],'double');
		$vPRqstTax4Base1   		= GetSQLValueString($rows['PRqst_Tax4Base1'],'double');
		$vPRqstTax5Base1   		= GetSQLValueString($rows['PRqst_Tax5Base1'],'double');
		$vPRqstTax1Base2   		= GetSQLValueString($rows['PRqst_Tax1Base2'],'double');
		$vPRqstTax2Base2   		= GetSQLValueString($rows['PRqst_Tax2Base2'],'double');
		$vPRqstTax3Base2   		= GetSQLValueString($rows['PRqst_Tax3Base2'],'double');
		$vPRqstTax4Base2   		= GetSQLValueString($rows['PRqst_Tax4Base2'],'double');
		$vPRqstTax5Base2   		= GetSQLValueString($rows['PRqst_Tax5Base2'],'double');
		$vPRqstType			 	= GetSQLValueString($rows['PRqst_Type'],'text');
		$vPRqstVatChkbx	 	 	= GetSQLValueString($rows['Prqst_VatChkBox'],'int');
		$vPRqstBelongsToGroup   = GetSQLValueString($rows['PRqst_BelongsToGroup'],'int');
		$vPRqstConfirmed		= GetSQLValueString($rows['PRqst_Confirmed'],'int');
		$vPRqstWarranty 		= GetSQLValueString($rows['PRqst_warranty'],'text');
		$vPRqstDocument 		= GetSQLValueString($rows['PRqst_document'],'text');
		$vPRqstApplication 		= GetSQLValueString($rows['PRqst_Application'],'text');
		$vPRqstApproved 		= GetSQLValueString($rows['PRqst_Approved'],'text');
		$vPRqstApprovedBy 		= GetSQLValueString($rows['PRqst_ApprovedBy'],'int');
		$vRejectedReason 		= GetSQLValueString($rows['rejectedreason'],'text');
		$vUserAccount 			= GetSQLValueString($rows['User_Name'],'text');
		$vOwnerBranch 			= GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch  	= GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		$sub_query  = " Select Count(*) From PRequest ".
		              " Where PRqst_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vPRqstID = GetNextSequence($PDestConn,'Null','Null','ID','PORDER','','Null',$rows['Porder_Date']);
			$vPRqstID = GetNextSequence1($PDestConn,'PRequest_ID','');
			
			$sub_query = " Insert Into PRequest (PRqst_ID, PRqst_Reference, PRqst_Date, PRqst_RequestDate, PRqst_RequestBy, Currency_Code, Project_Code, ".
						 " Costcent_code, Supplier_code, PRqst_SupplierContract, PRqst_Remark, PRqst_Posted, Expiry_date, PRqst_Import, ".
						 " PRqst_Status, Status_Remark, PRqst_DeliveryDate, PRqst_DeliveryPlace, PRqst_DeliveryContact, PRqst_Taxable, ".
						 " PRqst_TaxableBase1, PRqst_TaxableBase2, PRqst_NoneTaxable, PRqst_NoneTaxableBase1, PRqst_NoneTaxableBase2, ".
						 " PRqst_DiscountAmount, PRqst_DiscountBase1, PRqst_DiscountBase2, PRqst_DiscountPer, PRqst_Total, PRqst_TotalBase1, ".
						 " PRqst_TotalBase2, PRqst_Vat, PRqst_VatBase1, PRqst_VatBase2, Prqst_VatChkBox, PRqst_Tax1, PRqst_Tax1Base1, ".
						 " PRqst_Tax1Base2, PRqst_Tax2, PRqst_Tax2Base1, PRqst_Tax2Base2, PRqst_Tax3, PRqst_Tax3Base1, PRqst_Tax3Base2, ".
						 " PRqst_Tax4, PRqst_Tax4Base1, PRqst_Tax4Base2, PRqst_Tax5, PRqst_Tax5Base1, PRqst_Tax5Base2, PRqst_Type, ".
						 " PRqst_Confirmed, PRqst_BelongsToGroup, PRqst_warranty, PRqst_document, PRqst_TotalQuantity, PRqst_TotalQuantityUsed, ".
						 " PRqst_Application, PRqst_Approved, PRqst_ApprovedBy, rejectedreason, User_Name, Owner_Branch, Destination_Branch, PRqst_Syn_ID ) ".
						 " Values ( ".$vPRqstID.", ".$vPRqstReference.", ".$vPRqstDate.", ".$vPRqstRequestDate.", ".$vPRqstRequestBy.", ".$vCurrencyCode.
						 ", ".$vProjectCode.", ".$vCostcentCode.", ".$vSupplierCode.", ".$vSupplierContact.", ".$vPRqstRemark.", ".$vPRqstPosted.
						 ", ".$vExpiryDate.", ".$vPRqstImport.", ".$vPRqstStatus.", ".$vStatusRemark.", ".$vDeliveryDate.", ".$vDeliveryPlace.
						 ", ".$vDeliveryContact.", ".$vPRqstTaxable.", ".$vPRqstTaxableBase1.", ".$vPRqstTaxableBase2.", ".$vPRqstNoneTaxable.
						 ", ".$vPRqstNoneTaxableBase1.", ".$vPRqstNoneTaxableBase2.", ".$vPRqstDiscountAmount.", ".$vPRqstDiscountBase1.
						 ", ".$vPRqstDiscountBase2.", ".$vPRqstDiscountPer.", ".$vPRqstTotalAmount.", ".$vPRqstTotalBase1.", ".$vPRqstTotalBase2.
						 ", ".$vPRqstVAT.", ".$vPRqstVATBase1.", ".$vPRqstVATBase2.", ".$vPRqstVatChkbx.", ".$vPRqstTax1.", ".$vPRqstTax1Base1.
						 ", ".$vPRqstTax1Base2.", ".$vPRqstTax2.", ".$vPRqstTax2Base1.", ".$vPRqstTax2Base2.", ".$vPRqstTax3.", ".$vPRqstTax3Base1.
						 ", ".$vPRqstTax3Base2.", ".$vPRqstTax4.", ".$vPRqstTax4Base1.", ".$vPRqstTax4Base2.", ".$vPRqstTax5.", ".$vPRqstTax5Base1.
						 ", ".$vPRqstTax5Base2.", ".$vPRqstType.", ".$vPRqstConfirmed.", ".$vPRqstBelongsToGroup.", ".$vPRqstWarranty.", ".$vPRqstDocument.
						 ", ".$vTotalQuantity.", ".$vTotalQuantityUsed.", ".$vPRqstApplication.", ".$vPRqstApproved.", ".$vPRqstApprovedBy.", ".$vRejectedReason.
						 ", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vPRqstSynID." )";
						 
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select PRqst_ID From PRequest ".
					  " Where PRqst_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPRqstID = $result[0];
			
			$sub_query = "  Update PRequest Set PRqst_Date = ".$vPRqstDate.", PRqst_RequestDate = ".$vPRqstRequestDate.", PRqst_RequestBy = ".$vPRqstRequestBy.
						 ", Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode.", Supplier_code = ".$vSupplierCode.
						 ", PRqst_SupplierContract = ".$vSupplierContact.", PRqst_Remark = ".$vPRqstRemark.", PRqst_Posted = ".$vPRqstPosted.
						 ", Expiry_date = ".$vExpiryDate.", PRqst_Import = ".$vPRqstImport.", PRqst_Status = ".$vPRqstStatus.", Status_Remark = ".$vStatusRemark.
						 ",	PRqst_DeliveryDate = ".$vDeliveryDate.", PRqst_DeliveryPlace = ".$vDeliveryPlace.", PRqst_DeliveryContact = ".$vDeliveryContact.
						 ", PRqst_Taxable = ".$vPRqstTaxable.", PRqst_TaxableBase1 = ".$vPRqstTaxableBase1.", PRqst_TaxableBase2 = ".$vPRqstTaxableBase2. 
						 ",	PRqst_NoneTaxable = ".$vPRqstNoneTaxable.", PRqst_NoneTaxableBase1 = ".$vPRqstNoneTaxableBase1. 
						 ", PRqst_NoneTaxableBase2 = ".$vPRqstNoneTaxableBase2.", PRqst_DiscountAmount = ".$vPRqstDiscountAmount. 
						 ",	PRqst_DiscountBase1 = ".$vPRqstDiscountBase1.", PRqst_DiscountBase2 = ".$vPRqstDiscountBase2. 
						 ",	PRqst_DiscountPer = ".$vPRqstDiscountPer.", PRqst_Total = ".$vPRqstTotalAmount.", PRqst_TotalBase1 = ".$vPRqstTotalBase1.
						 ",	PRqst_TotalBase2 = ".$vPRqstTotalBase2.", PRqst_Vat = ".$vPRqstVAT.", PRqst_VatBase1 = ".$vPRqstVATBase1. 
						 ",	PRqst_VatBase2 = ".$vPRqstVATBase2.", PRqst_VATChckbx = ".$vPRqstVatChkbx.", PRqst_Tax1 = ".$vPRqstTax1.
						 ", PRqst_Tax1Base1 = ".$vPRqstTax1Base1.", PRqst_Tax1Base2 = ".$vPRqstTax1Base2.", PRqst_Tax2 = ".$vPRqstTax2.
						 ", PRqst_Tax2Base1 = ".$vPRqstTax2Base1.", PRqst_Tax2Base2 = ".$vPRqstTax2Base2.", PRqst_Tax3 = ".$vPRqstTax3.
						 ", PRqst_Tax3Base1 = ".$vPRqstTax3Base1.", PRqst_Tax3Base2 = ".$vPRqstTax3Base2.", PRqst_Tax4 = ".$vPRqstTax4.
						 ", PRqst_Tax4Base1 = ".$vPRqstTax4Base1.", PRqst_Tax4Base2 = ".$vPRqstTax4Base2.", PRqst_Tax5 = ".$vPRqstTax5.
						 ", PRqst_Tax5Base1 = ".$vPRqstTax5Base1.", PRqst_Tax5Base2 = ".$vPRqstTax5Base2.",	PRqst_Type = ".$vPRqstType.
						 ", PRqst_Confirmed = ".$vPRqstConfirmed.", PRqst_BelongsToGroup = ".$vPRqstBelongsToGroup.", PRqst_warranty = ".$vPRqstWarranty.
						 ", PRqst_document = ".$vPRqstDocument.", PRqst_TotalQuantity = ".$vTotalQuantity.", PRqst_TotalQuantityUsed = ".$vTotalQuantityUsed. 
						 ", PRqst_Application = ".$vPRqstApplication.", PRqst_Approved = ".$vPRqstApproved.", PRqst_ApprovedBy = ".$vPRqstApprovedBy. 
						 ", rejectedreason = ".$vRejectedReason.", User_Name = ".$vUserAccount.", Destination_Branch = ".$vDestinationBranch.
						 "  Where PRqst_Syn_ID = '".$PRecordID."'";
		}
						 
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			//InCase Update, Delete All Related Details In PRqstDt
			If ($vRecordExists > 0) {
				$query = "Delete From PRequestDt Where PRqst_ID = '".$vPRqstID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From PRequestDt
			$query = " Select PRqstDt_ID, PRqst_ID, PRqst_Date, Currency_Code, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_QtyPacked, PRqstDt_Quantity, PRqstDt_QuantityUsed, PRqstDt_Price, PRqstDt_PriceBase1, ".
					 " PRqstDt_PriceBase2, PRqstDt_PriceTTC, PRqstDt_PriceTTCBase1, PRqstDt_PriceTTCBase2, PRqstDt_Discount, PRqstDt_DiscountAmount, ".
					 " PRqstDt_DiscountBase1, PRqstDt_DiscountBase2, Item_VAT, PRqstDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, ".
					 " Item_Tax5, Item_UnitCoef, Item_Unit2Qty, PRqstDt_OQuantity, PRqstDt_CQuantity, item_description, PRqstDt_status,  ".
					 " PRqstDt_approvedlevel, rejectedreason, User_Name, approvedby ".
					 " From PRequestDt ".
					 " Where PRqst_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vPRqstDtID   = GetNextSequence($PDestConn,'Null','Null','ID','PORDERDT','','Null',$rows['Porder_Date']);
				$vPRqstDtID = GetNextSequence1($PDestConn,'PRequestDt_Id','');
				
				$sub_query = " Insert Into PRequestDt (PRqstDt_ID, PRqst_ID, PRqst_Date, Currency_Code, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_QtyPacked, PRqstDt_Quantity, PRqstDt_QuantityUsed, PRqstDt_Price, PRqstDt_PriceBase1, ".
							 " PRqstDt_PriceBase2, PRqstDt_PriceTTC, PRqstDt_PriceTTCBase1, PRqstDt_PriceTTCBase2, PRqstDt_Discount, PRqstDt_DiscountAmount, ".
							 " PRqstDt_DiscountBase1, PRqstDt_DiscountBase2, Item_VAT, PRqstDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, ".
							 " Item_Tax5, Item_UnitCoef, Item_Unit2Qty, PRqstDt_OQuantity, PRqstDt_CQuantity, item_description, PRqstDt_status, ".
							 " PRqstDt_approvedlevel, rejectedreason, User_Name, approvedby, PRqstDt_Syn_ID, PRqst_Syn_ID ) ".
					 		 " Values ( ".$vPRqstDtID.", ".$vPRqstID.", ".GetSQLValueString($rows['PRqst_Date'],'date').", ".GetSQLValueString($rows['Currency_Code'],'text').
							 ", ".GetSQLValueString($rows['Supplier_Code'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCent_Code'],'text').
							 ", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['Item_QtyPacked'],'double').", ".GetSQLValueString($rows['PRqstDt_Quantity'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_QuantityUsed'],'double').", ".GetSQLValueString($rows['PRqstDt_Price'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_PriceBase1'],'double').", ".GetSQLValueString($rows['PRqstDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_PriceTTC'],'double').", ".GetSQLValueString($rows['PRqstDt_PriceTTCBase1'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_PriceTTCBase2'],'double').", ".GetSQLValueString($rows['PRqstDt_Discount'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_DiscountAmount'],'double').", ".GetSQLValueString($rows['PRqstDt_DiscountBase1'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_DiscountBase2'],'double').", ".GetSQLValueString($rows['Item_VAT'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_Remark'],'text').", ".GetSQLValueString($rows['Item_Tax1'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').
							 ", ".GetSQLValueString($rows['PRqstDt_OQuantity'],'double').", ".GetSQLValueString($rows['PRqstDt_CQuantity'],'double').
							 ", ".GetSQLValueString($rows['item_description'],'text').", ".GetSQLValueString($rows['PRqstDt_status'],'text').
							 ", ".GetSQLValueString($rows['PRqstDt_approvedlevel'],'int').", ".GetSQLValueString($rows['rejectedreason'],'text').
							 ", ".GetSQLValueString($rows['User_Name'],'text').", ".GetSQLValueString($rows['approvedby'],'text').
							 ", ".GetSQLValueString($rows['PRqstDt_ID'],'int').", ".$vPRqstSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PRqstDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PRequestDt',$vMessage);
					
					break;
				}
			}
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PRequest',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select PRqst_ID, Owner_Branch ".
					 " From PRequest Where PRqst_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vPRqstID	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
			
		$query = "Delete From PRequestDt Where PRqst_ID = '".$vPRqstID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$query = "Delete From PRequest Where PRqst_ID = '".$vPRqstID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'PRequest',$vMessage);
			}
				
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PRequestDt',$vMessage);
		}
		
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPRqstID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroPorder($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, ".
				 " Costcent_code, Supplier_code, Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, ".
				 " Porder_Status, Status_Remark, Porder_DeliveryDate, Porder_DeliveryPlace, Porder_DeliveryContact, Porder_Taxable, ".
				 " Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, ".
				 " Porder_DiscountAmount, Porder_DiscountBase1, Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, ".
				 " Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, Porder_Tax1, Porder_Tax1Base1, ".
				 " Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2, ".
				 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, ".
				 " Porder_Confirmed, Porder_BelongsToGroup, Porder_warranty, Porder_document, Porder_TotalQuantity, Porder_TotalQuantityUsed, ".
				 " PRqst_Id, porder_approvedstatus, porder_approvedlevel, rejectedreason, approvedby, User_Name, Owner_Branch, Destination_Branch, Porder_Syn_ID ".
				 " From Porder ".
				 " Where Porder_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vPorderSynID		 = GetSQLValueString($rows['Porder_ID'],'int');
		$vPRqstSynID		 = GetSQLValueString($rows['PRqst_Id'],'int');
		$vPorderReference	 = GetSQLValueString($rows['Porder_Reference'],'double');
		$vPorderDate		 = GetSQLValueString($rows['Porder_Date'],'date');
		$vPorderRemark	     = GetSQLValueString($rows['Porder_Remark'],'text');
		$vPorderRequestBy    = GetSQLValueString($rows['Porder_RequestBy'],'text');
		$vPorderRequestDate  = GetSQLValueString($rows['Porder_RequestDate'],'date');
		$vSupplierCode		 = GetSQLValueString($rows['Supplier_code'],'text');
		$vSupplierContact    = GetSQLValueString($rows['Porder_SupplierContact'],'text');
		$vDeliveryDate       = GetSQLValueString($rows['Porder_DeliveryDate'],'date');
		$vDeliveryPlace		 = GetSQLValueString($rows['Porder_DeliveryPlace'],'text');
		$vDeliveryContact    = GetSQLValueString($rows['Porder_DeliveryContact'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vPorderPosted		 = GetSQLValueString($rows['Porder_Posted'],'int');
		$vPorderImport	     = GetSQLValueString($rows['Porder_Import'],'int');
		$vExpiryDate         = GetSQLValueString($rows['Expiry_date'],'date');
		$vPorderStatus		 = GetSQLValueString($rows['Porder_Status'],'text');
		$vStatusRemark		 = GetSQLValueString($rows['Status_Remark'],'text');
		$vPorderTaxable		   	 = GetSQLValueString($rows['Porder_Taxable'],'double');
		$vPorderTaxableBase1	 = GetSQLValueString($rows['Porder_TaxableBase1'],'double');
		$vPorderTaxableBase2	 = GetSQLValueString($rows['Porder_TaxableBase2'],'double');
		$vPorderNoneTaxable	     = GetSQLValueString($rows['Porder_NoneTaxable'],'double');
		$vPorderNoneTaxableBase1 = GetSQLValueString($rows['Porder_NoneTaxableBase1'],'double');
		$vPorderNoneTaxableBase2 = GetSQLValueString($rows['Porder_NoneTaxableBase2'],'double');
		$vPorderDiscountAmount   = GetSQLValueString($rows['Porder_DiscountAmount'],'double');
		$vPorderDiscountBase1	 = GetSQLValueString($rows['Porder_DiscountBase1'],'double');
		$vPorderDiscountBase2    = GetSQLValueString($rows['Porder_DiscountBase2'],'double');
		$vPorderDiscountPer	   	 = GetSQLValueString($rows['Porder_DiscountPer'],'double');
		$vPorderTotalAmount      = GetSQLValueString($rows['Porder_Total'],'double');
		$vPorderTotalBase1	 	 = GetSQLValueString($rows['Porder_TotalBase1'],'double');
		$vPorderTotalBase2    	 = GetSQLValueString($rows['Porder_TotalBase2'],'double');
		$vPorderVAT			   	 = GetSQLValueString($rows['Porder_Vat'],'double');
		$vPorderVATBase1		 = GetSQLValueString($rows['Porder_VatBase1'],'double');
		$vPorderVATBase2		 = GetSQLValueString($rows['Porder_VatBase2'],'double');
		$vTotalQuantity		     = GetSQLValueString($rows['Porder_TotalQuantity'],'double');
		$vTotalQuantityUsed 	 = GetSQLValueString($rows['Porder_TotalQuantityUsed'],'double');
		$vPorderTax1 		= GetSQLValueString($rows['Porder_Tax1'],'double');
		$vPorderTax2 		= GetSQLValueString($rows['Porder_Tax2'],'double');
		$vPorderTax3 		= GetSQLValueString($rows['Porder_Tax3'],'double');
		$vPorderTax4 		= GetSQLValueString($rows['Porder_Tax4'],'double');
		$vPorderTax5 		= GetSQLValueString($rows['Porder_Tax5'],'double');
		$vPorderTax1Base1   = GetSQLValueString($rows['Porder_Tax1Base1'],'double');
		$vPorderTax2Base1   = GetSQLValueString($rows['Porder_Tax2Base1'],'double');
		$vPorderTax3Base1   = GetSQLValueString($rows['Porder_Tax3Base1'],'double');
		$vPorderTax4Base1   = GetSQLValueString($rows['Porder_Tax4Base1'],'double');
		$vPorderTax5Base1   = GetSQLValueString($rows['Porder_Tax5Base1'],'double');
		$vPorderTax1Base2   = GetSQLValueString($rows['Porder_Tax1Base2'],'double');
		$vPorderTax2Base2   = GetSQLValueString($rows['Porder_Tax2Base2'],'double');
		$vPorderTax3Base2   = GetSQLValueString($rows['Porder_Tax3Base2'],'double');
		$vPorderTax4Base2   = GetSQLValueString($rows['Porder_Tax4Base2'],'double');
		$vPorderTax5Base2   = GetSQLValueString($rows['Porder_Tax5Base2'],'double');
		$vPorderType			 = GetSQLValueString($rows['Porder_Type'],'text');
		$vPorderVatChkbx	 	 = GetSQLValueString($rows['Porder_VATChckbx'],'int');
		$vPorderBelongsToGroup   = GetSQLValueString($rows['Porder_BelongsToGroup'],'int');
		$vPorderConfirmed		 = GetSQLValueString($rows['Porder_Confirmed'],'int');
		$vPorderWarranty 		 = GetSQLValueString($rows['Porder_warranty'],'text');
		$vPorderDocument 		 = GetSQLValueString($rows['Porder_document'],'text');
		$vApprovedStatus 		 = GetSQLValueString($rows['porder_approvedstatus'],'text');
		$vApprovedLevel 		 = GetSQLValueString($rows['porder_approvedlevel'],'int');
		$vRejectedReason 		 = GetSQLValueString($rows['rejectedreason'],'text');
		$vApprovedBy 			 = GetSQLValueString($rows['approvedby'],'text');
		$vUserAccount 			 = GetSQLValueString($rows['User_Name'],'text');
		$vOwnerBranch 			 = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch  	 = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$vPRqstID	 	   = F_Get_PurchaseReqID($PDestConn, $vPRqstSynID);
		
		$sub_query  = " Select Count(*) From Porder ".
		              " Where Porder_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vPorderID = GetNextSequence($PDestConn,'Null','Null','ID','PORDER','','Null',$rows['Porder_Date']);
			$vPorderID = GetNextSequence1($PDestConn,'Porder_ID','');
			
			$sub_query = " Insert Into Porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, ".
						 " Project_Code, Costcent_code, Supplier_code, Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, ".
						 " Porder_Status, Status_Remark, Porder_DeliveryDate, Porder_DeliveryPlace, Porder_DeliveryContact, Porder_Taxable, ".
						 " Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, ".
						 " Porder_DiscountAmount, Porder_DiscountBase1, Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, ".
						 " Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, Porder_Tax1, Porder_Tax1Base1, ".
						 " Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2, ".
						 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, ".
						 " Porder_Confirmed, Porder_BelongsToGroup, Porder_warranty, Porder_document, Porder_TotalQuantity, Porder_TotalQuantityUsed, ".
						 " PRqst_Id, porder_approvedstatus, porder_approvedlevel, rejectedreason, approvedby, User_Name, Owner_Branch, Destination_Branch, Porder_Syn_ID ) ".
						 " Values ( ".$vPorderID.", ".$vPorderReference.", ".$vPorderDate.", ".$vPorderRequestDate.", ".$vPorderRequestBy.", ".$vCurrencyCode.
						 ", ".$vProjectCode.", ".$vCostcentCode.", ".$vSupplierCode.", ".$vSupplierContact.", ".$vPorderRemark.", ".$vPorderPosted.
						 ", ".$vExpiryDate.", ".$vPorderImport.", ".$vPorderStatus.", ".$vStatusRemark.", ".$vDeliveryDate.", ".$vDeliveryPlace.
						 ", ".$vDeliveryContact.", ".$vPorderTaxable.", ".$vPorderTaxableBase1.", ".$vPorderTaxableBase2.", ".$vPorderNoneTaxable.
						 ", ".$vPorderNoneTaxableBase1.", ".$vPorderNoneTaxableBase2.", ".$vPorderDiscountAmount.", ".$vPorderDiscountBase1.
						 ", ".$vPorderDiscountBase2.", ".$vPorderDiscountPer.", ".$vPorderTotalAmount.", ".$vPorderTotalBase1.", ".$vPorderTotalBase2.
						 ", ".$vPorderVAT.", ".$vPorderVATBase1.", ".$vPorderVATBase2.", ".$vPorderVatChkbx.", ".$vPorderTax1.", ".$vPorderTax1Base1.
						 ", ".$vPorderTax1Base2.", ".$vPorderTax2.", ".$vPorderTax2Base1.", ".$vPorderTax2Base2.", ".$vPorderTax3.", ".$vPorderTax3Base1.
						 ", ".$vPorderTax3Base2.", ".$vPorderTax4.", ".$vPorderTax4Base1.", ".$vPorderTax4Base2.", ".$vPorderTax5.", ".$vPorderTax5Base1.
						 ", ".$vPorderTax5Base2.", ".$vPorderType.", ".$vPorderConfirmed.", ".$vPorderBelongsToGroup.", ".$vPorderWarranty.", ".$vPorderDocument.
						 ", ".$vTotalQuantity.", ".$vTotalQuantityUsed.", ".$vPRqstID.", ".$vApprovedStatus.", ".$vApprovedLevel.", ".$vRejectedReason.
						 ", ".$vApprovedBy.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vPorderSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Porder_ID From Porder ".
					  " Where Porder_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPorderID = $result[0];
			
			$sub_query = "  Update Porder Set Porder_Date = ".$vPorderDate.", Porder_RequestDate = ".$vPorderRequestDate.", Porder_RequestBy = ".$vPorderRequestBy.
						 ", Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode.", Supplier_code = ".$vSupplierCode.
						 ", Porder_SupplierContact = ".$vSupplierContact.", Porder_Remark = ".$vPorderRemark.", Porder_Posted = ".$vPorderPosted.
						 ", Expiry_date = ".$vExpiryDate.", Porder_Import = ".$vPorderImport.", Porder_Status = ".$vPorderStatus.", Status_Remark = ".$vStatusRemark.
						 ",	Porder_DeliveryDate = ".$vDeliveryDate.", Porder_DeliveryPlace = ".$vDeliveryPlace.", Porder_DeliveryContact = ".$vDeliveryContact.
						 ", Porder_Taxable = ".$vPorderTaxable.", Porder_TaxableBase1 = ".$vPorderTaxableBase1.", Porder_TaxableBase2 = ".$vPorderTaxableBase2. 
						 ",	Porder_NoneTaxable = ".$vPorderNoneTaxable.", Porder_NoneTaxableBase1 = ".$vPorderNoneTaxableBase1. 
						 ", Porder_NoneTaxableBase2 = ".$vPorderNoneTaxableBase2.", Porder_DiscountAmount = ".$vPorderDiscountAmount. 
						 ",	Porder_DiscountBase1 = ".$vPorderDiscountBase1.", Porder_DiscountBase2 = ".$vPorderDiscountBase2. 
						 ",	Porder_DiscountPer = ".$vPorderDiscountPer.", Porder_Total = ".$vPorderTotalAmount.", Porder_TotalBase1 = ".$vPorderTotalBase1.
						 ",	Porder_TotalBase2 = ".$vPorderTotalBase2.", Porder_Vat = ".$vPorderVAT.", Porder_VatBase1 = ".$vPorderVATBase1. 
						 ",	Porder_VatBase2 = ".$vPorderVATBase2.", Porder_VATChckbx = ".$vPorderVatChkbx.", Porder_Tax1 = ".$vPorderTax1.
						 ", Porder_Tax1Base1 = ".$vPorderTax1Base1.", Porder_Tax1Base2 = ".$vPorderTax1Base2.", Porder_Tax2 = ".$vPorderTax2.
						 ", Porder_Tax2Base1 = ".$vPorderTax2Base1.", Porder_Tax2Base2 = ".$vPorderTax2Base2.", Porder_Tax3 = ".$vPorderTax3.
						 ", Porder_Tax3Base1 = ".$vPorderTax3Base1.", Porder_Tax3Base2 = ".$vPorderTax3Base2.", Porder_Tax4 = ".$vPorderTax4.
						 ", Porder_Tax4Base1 = ".$vPorderTax4Base1.", Porder_Tax4Base2 = ".$vPorderTax4Base2.", Porder_Tax5 = ".$vPorderTax5.
						 ", Porder_Tax5Base1 = ".$vPorderTax5Base1.", Porder_Tax5Base2 = ".$vPorderTax5Base2.",	Porder_Type = ".$vPorderType.
						 ", Porder_Confirmed = ".$vPorderConfirmed.", Porder_BelongsToGroup = ".$vPorderBelongsToGroup.", Porder_warranty = ".$vPorderWarranty.
						 ", Porder_document = ".$vPorderDocument.", Porder_TotalQuantity = ".$vTotalQuantity.", Porder_TotalQuantityUsed = ".$vTotalQuantityUsed. 
						 ", porder_approvedstatus = ".$vApprovedStatus.", porder_approvedlevel = ".$vApprovedLevel.", rejectedreason = ".$vRejectedReason. 
						 ", approvedby = ".$vApprovedBy.", User_Name = ".$vUserAccount.", Destination_Branch = ".$vDestinationBranch.
						 "  Where Porder_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Porder Set Porder_Syn_ID = ".$vPorderID.
							 " Where Porder_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In PorderDt
			If ($vRecordExists > 0) {
				$query = "Delete From PorderDt Where Porder_ID = '".$vPorderID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From PorderDt
			$query = " Select PorderDt_ID, Porder_ID, Porder_Date, Currency_Code, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, ".
					 " PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, PorderDt_Discount, PorderDt_DiscountAmount, ".
					 " PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, ".
					 " Item_Tax5, Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, RelatedDt_ID, rejectedreason ".
					 " From PorderDt ".
					 " Where Porder_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vPorderDtID   = GetNextSequence($PDestConn,'Null','Null','ID','PORDERDT','','Null',$rows['Porder_Date']);
				$vPorderDtID = GetNextSequence1($PDestConn,'PorderDt_ID','');
				$vRelatedDtID  = F_Get_PorderDtRelatedID($PDestConn, $rows['RelatedDt_ID']);
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PorderDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PorderDt',$vMessage);
					
					break;
				}*/			
				
				$sub_query = " Insert Into PorderDt (PorderDt_ID, Porder_ID, Porder_Date, Currency_Code, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_QtyPacked, PorderDt_Quantity, PorderDt_QuantityUsed, PorderDt_Price, PorderDt_PriceBase1, ".
							 " ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, PorderDt_Discount, PorderDt_DiscountAmount, ".
							 " PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, ".
							 " Item_Tax5, Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, rejectedreason, RelatedDt_ID, PorderDt_Syn_ID, Porder_Syn_ID ) ".
					 		 " Values ( ".$vPorderDtID.", ".$vPorderID.", ".GetSQLValueString($rows['Porder_Date'],'date').", ".GetSQLValueString($rows['Currency_Code'],'text').
							 ", ".GetSQLValueString($rows['Supplier_Code'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCent_Code'],'text').
							 ", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['Item_QtyPacked'],'double').", ".GetSQLValueString($rows['PorderDt_Quantity'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_QuantityUsed'],'double').", ".GetSQLValueString($rows['PorderDt_Price'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_PriceBase1'],'double').", ".GetSQLValueString($rows['ProderDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_PriceTTC'],'double').", ".GetSQLValueString($rows['PorderDt_PriceTTCBase1'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_PriceTTCBase2'],'double').", ".GetSQLValueString($rows['PorderDt_Discount'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_DiscountAmount'],'double').", ".GetSQLValueString($rows['PorderDt_Discountbase1'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_Discountbase2'],'double').", ".GetSQLValueString($rows['Item_VAT'],'double').
							 ", ".GetSQLValueString($rows['PorderDt_Remark'],'text').", ".GetSQLValueString($rows['Item_Tax1'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Porderdt_OldData'],'int').", ".GetSQLValueString($rows['Item_UnitCoef'],'double').
							 ", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".GetSQLValueString($rows['rejectedreason'],'text').
							 ", ".$vRelatedDtID.", ".GetSQLValueString($rows['PorderDt_ID'],'int').", ".$vPorderSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PorderDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PorderDt',$vMessage);
					
					break;
				}
			}
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Porder',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Porder_ID, Owner_Branch ".
					 " From Porder Where Porder_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vPorderID    = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
			
		$query = "Delete From PorderDt Where Porder_ID = '".$vPorderID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$query = "Delete From Porder Where Porder_ID = '".$vPorderID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Porder',$vMessage);
			}
				
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PorderDt',$vMessage);
		}
		
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPorderID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroPurchases($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Purchase_ID, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, ".
				 " Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, ".
				 " Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, ".
				 " Purchase_DiscountBase2, Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, ".
				 " Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, Journal_Type, ".
				 " Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, ".
				 " Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, ".
				 " Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, ".
				 " Purchase_VatChkbx, Purchase_TotalQuantity, Purchase_Edit, Prorder_Id, Purchase_LoadHHT, User_Account, Owner_Branch, Destination_Branch, Purchase_Syn_ID  ".
				 " From Purchases ".
				 " Where Purchase_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vPurchaseSynID		 = GetSQLValueString($rows['Purchase_ID'],'int');
		$vJournalSynID		 = GetSQLValueString($rows['Journal_Id'],'int');
		$vPorderSynID		 = GetSQLValueString($rows['Prorder_Id'],'int');
		$vPurchaseReference	 = GetSQLValueString($rows['Purchase_Reference'],'double');
		$vPorderReference    = GetSQLValueString($rows['Porder_Ref'],'double');
		$vPorderReferences   = GetSQLValueString($rows['Purchase_PorderReferences'],'double');
		$vPurchaseDate		 = GetSQLValueString($rows['Purchase_Date'],'date');
		$vJournalDtValueDate = GetSQLValueString($rows['Journaldt_valuedate'],'date');
		$vPurchaseRemark	 = GetSQLValueString($rows['Purchase_Remark'],'text');
		$vPurchaseInvoiceNo	 = GetSQLValueString($rows['Purchase_InvoiceNo'],'text');
		$vSupplierCode		 = GetSQLValueString($rows['Supplier_code'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vPurchasePosted	 = GetSQLValueString($rows['Purchase_Posted'],'int');
		$vPurchaseEdit		 = GetSQLValueString($rows['Purchase_Edit'],'int');
		$vPurchaseTaxable		   = GetSQLValueString($rows['Purchase_Taxable'],'double');
		$vPurchaseTaxableBase1	   = GetSQLValueString($rows['Purchase_TaxableBase1'],'double');
		$vPurchaseTaxableBase2	   = GetSQLValueString($rows['Purchase_TaxableBase2'],'double');
		$vPurchaseNoneTaxable	   = GetSQLValueString($rows['Purchase_NoneTaxable'],'double');
		$vPurchaseNoneTaxableBase1 = GetSQLValueString($rows['Purchase_NoneTaxableBase1'],'double');
		$vPurchaseNoneTaxableBase2 = GetSQLValueString($rows['Purchase_NoneTaxableBase2'],'double');
		$vPurchaseDiscountAmount   = GetSQLValueString($rows['Purchase_DiscountAmount'],'double');
		$vPurchaseDiscountBase1	   = GetSQLValueString($rows['Purchase_DiscountBase1'],'double');
		$vPurchaseDiscountBase2    = GetSQLValueString($rows['Purchase_DiscountBase2'],'double');
		$vPurchaseDiscountPer	   = GetSQLValueString($rows['Purchase_DiscountPer'],'double');
		$vPurchaseVAT			   = GetSQLValueString($rows['Purchase_VAT'],'double');
		$vPurchaseVATBase1		   = GetSQLValueString($rows['Purchase_VATBase1'],'double');
		$vPurchaseVATBase2		   = GetSQLValueString($rows['Purchase_VATBase2'],'double');
		$vPurchaseTotal			   = GetSQLValueString($rows['Purchase_Total'],'double');
		$vPurchaseTotalBase1	   = GetSQLValueString($rows['Purchase_TotalBase1'],'double');
		$vPurchaseTotalBase2	   = GetSQLValueString($rows['Purchase_TotalBase2'],'double');
		$vPurchaseCharges		   = GetSQLValueString($rows['Purchase_Charges'],'double');
		$vPurchaseChargesBase1	   = GetSQLValueString($rows['Purchase_ChargesBase1'],'double');
		$vPurchaseChargesBase2	   = GetSQLValueString($rows['Purchase_ChargesBase2'],'double');
		$vPurchaseMode			   = GetSQLValueString($rows['Purchase_Mode'],'int');
		$vJournalType 			   = GetSQLValueString($rows['Journal_Type'],'text');
		$vPurchaseBelongsToGroup   = GetSQLValueString($rows['Purchase_BelongsToGroup'],'int');
		$vPurchaseTax1 		= GetSQLValueString($rows['Purchase_tax1'],'double');
		$vPurchaseTax2 		= GetSQLValueString($rows['Purchase_tax2'],'double');
		$vPurchaseTax3 		= GetSQLValueString($rows['Purchase_tax3'],'double');
		$vPurchaseTax4 		= GetSQLValueString($rows['Purchase_tax4'],'double');
		$vPurchaseTax5 		= GetSQLValueString($rows['Purchase_tax5'],'double');
		$vPurchaseTax1Base1 = GetSQLValueString($rows['Purchase_tax1base1'],'double');
		$vPurchaseTax2Base1 = GetSQLValueString($rows['Purchase_tax2base1'],'double');
		$vPurchaseTax3Base1 = GetSQLValueString($rows['Purchase_tax3base1'],'double');
		$vPurchaseTax4Base1 = GetSQLValueString($rows['Purchase_tax4base1'],'double');
		$vPurchaseTax5Base1 = GetSQLValueString($rows['Purchase_tax5base1'],'double');
		$vPurchaseTax1Base2 = GetSQLValueString($rows['Purchase_tax1base2'],'double');
		$vPurchaseTax2Base2 = GetSQLValueString($rows['Purchase_tax2base2'],'double');
		$vPurchaseTax3Base2 = GetSQLValueString($rows['Purchase_tax3base2'],'double');
		$vPurchaseTax4Base2 = GetSQLValueString($rows['Purchase_tax4base2'],'double');
		$vPurchaseTax5Base2 = GetSQLValueString($rows['Purchase_tax5base2'],'double');
		$vPurchaseAcctax1 	= GetSQLValueString($rows['Purchase_Acctax1'],'text');
		$vPurchaseAcctax2 	= GetSQLValueString($rows['Purchase_Acctax2'],'text');
		$vPurchaseAcctax3 	= GetSQLValueString($rows['Purchase_Acctax3'],'text');
		$vPurchaseAcctax4 	= GetSQLValueString($rows['Purchase_Acctax4'],'text');
		$vPurchaseAcctax5 	= GetSQLValueString($rows['Purchase_Acctax5'],'text');
		$vPurchaseDebitCur 		   = GetSQLValueString($rows['Purchase_DebitCur'],'text');
		$vPurchaseDebitAccount	   = GetSQLValueString($rows['Purchase_DebitAccount'],'text');
		$vPurchaseVatChkbx		   = GetSQLValueString($rows['Purchase_VatChkbx'],'int');
		$vPurchaseImport 		   = GetSQLValueString($rows['Purchase_Import'],'int');
		$vPurchaseGrn 		   	   = GetSQLValueString($rows['Purchase_Grn'],'int');
		$vPurchaseType 			   = GetSQLValueString($rows['Purchase_Type'],'text');
		$vTotalQuantity		       = GetSQLValueString($rows['Purchase_TotalQuantity'],'double');
		$vPurchaseLoadHHT 		   = GetSQLValueString($rows['Purchase_LoadHHT'],'int');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$vPorderId	= F_Get_PorderID($PDestConn, $vPorderSynID);
		
		
		$sub_query  = " Select Count(*) From Purchases ".
		              " Where Purchase_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vPurchaseID = GetNextSequence($PDestConn,'Null','Null','ID','PURCHASES','','Null',$rows['Purchase_Date']);
			$vPurchaseID = GetNextSequence1($PDestConn,'Purchase_ID','');
			
			$sub_query = " Insert Into Purchases (Purchase_ID, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, ".
						 " Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, ".
						 " Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, ".
						 " Purchase_DiscountBase2, Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, ".
						 " Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, Journal_Type, ".
						 " Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, ".
						 " Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, ".
						 " Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
						 " Purchase_DebitAccount, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, ".
						 " Purchase_VatChkbx, Purchase_TotalQuantity, Purchase_Edit, Prorder_Id, Purchase_LoadHHT, User_Account, Owner_Branch, Destination_Branch, Purchase_Syn_ID  ) ".
						 " Values ( ".$vPurchaseID.", ".$vPurchaseReference.", ".$vPurchaseDate.", ".$vPurchaseRemark.", ".$vSupplierCode.", ".$vCurrencyCode.
						 ", ".$vProjectCode.", ".$vCostcentCode.", ".$vPurchaseInvoiceNo.", ".$vJournalDtValueDate.", ".$vPurchasePosted.", ".$vPurchaseTaxable.
						 ", ".$vPurchaseTaxableBase1.", ".$vPurchaseTaxableBase2.", ".$vPurchaseNoneTaxable.", ".$vPurchaseNoneTaxableBase1.", ".$vPurchaseNoneTaxableBase2.
						 ", ".$vPurchaseDiscountAmount.", ".$vPurchaseDiscountBase1.", ".$vPurchaseDiscountBase2.", ".$vPurchaseDiscountPer.", ".$vPurchaseTotal.
						 ", ".$vPurchaseTotalBase1.", ".$vPurchaseTotalBase2.", ".$vPurchaseVAT.", ".$vPurchaseVATBase1.", ".$vPurchaseVATBase2.", ".$vPurchaseCharges.
						 ", ".$vPurchaseChargesBase1.", ".$vPurchaseChargesBase2.", ".$vPurchaseMode.", ".$vJournalType.", ".$vPurchaseTax1.", ".$vPurchaseTax1Base1.
						 ", ".$vPurchaseTax1Base2.", ".$vPurchaseTax2.", ".$vPurchaseTax2Base1.", ".$vPurchaseTax2Base2.", ".$vPurchaseTax3.", ".$vPurchaseTax3Base1.
						 ", ".$vPurchaseTax3Base2.", ".$vPurchaseTax4.", ".$vPurchaseTax4Base1.", ".$vPurchaseTax4Base2.", ".$vPurchaseTax5.", ".$vPurchaseTax5Base1.
						 ", ".$vPurchaseTax5Base2.", ".$vPurchaseAcctax1.", ".$vPurchaseAcctax2.", ".$vPurchaseAcctax3.", ".$vPurchaseAcctax4.", ".$vPurchaseAcctax5. 
						 ", ".$vPurchaseDebitCur.", ".$vPurchaseDebitAccount.", ".$vPurchaseBelongsToGroup.", ".$vPurchaseImport.", ".$vPurchaseType.", ".$vPurchaseGrn.
						 ", ".$vPorderReference.", ".$vPorderReferences.", ".$vPurchaseVatChkbx.", ".$vTotalQuantity.", ".$vPurchaseEdit.", ".$vPorderId.", ".$vPurchaseLoadHHT.
						 ", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vPurchaseSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Purchase_ID From Purchases ".
					  " Where Purchase_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPurchaseID = $result[0];
			
			$sub_query = "  Update Purchases Set Purchase_Date = ".$vPurchaseDate.", JournalDt_ValueDate = ".$vJournalDtValueDate. 
						 ",	Purchase_Remark = ".$vPurchaseRemark.", Supplier_code = ".$vSupplierCode.", Currency_Code = ".$vCurrencyCode.
						 ", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode.", Purchase_InvoiceNo = ".$vPurchaseInvoiceNo.  
						 ",	Purchase_Posted = ".$vPurchasePosted.", Purchase_Edit = ".$vPurchaseEdit.", Purchase_Taxable = ".$vPurchaseTaxable. 
						 ",	Purchase_TaxableBase1 = ".$vPurchaseTaxableBase1.", Purchase_TaxableBase2 = ".$vPurchaseTaxableBase2. 
						 ",	Purchase_NoneTaxable = ".$vPurchaseNoneTaxable.", Purchase_NoneTaxableBase1 = ".$vPurchaseNoneTaxableBase1. 
						 ", Purchase_NoneTaxableBase2 = ".$vPurchaseNoneTaxableBase2.", Purchase_DiscountAmount = ".$vPurchaseDiscountAmount. 
						 ",	Purchase_DiscountBase1 = ".$vPurchaseDiscountBase1.", Purchase_DiscountBase2 = ".$vPurchaseDiscountBase2. 
						 ",	Purchase_DiscountPer = ".$vPurchaseDiscountPer.", Purchase_Total = ".$vPurchaseTotal.
						 ", Purchase_TotalBase1 = ".$vPurchaseTotalBase1. ", Purchase_TotalBase2 = ".$vPurchaseTotalBase2.", Purchase_VAT = ".$vPurchaseVAT.
						 ", Purchase_VATBase1 = ".$vPurchaseVATBase1.",	Purchase_VATBase2 = ".$vPurchaseVATBase2.",	Purchase_Charges = ".$vPurchaseCharges.
						 ",	Purchase_ChargesBase1 = ".$vPurchaseChargesBase1.",	Purchase_ChargesBase2 = ".$vPurchaseChargesBase2.
						 ", Purchase_Mode = ".$vPurchaseMode.",	Journal_Type = ".$vJournalType.", Purchase_Tax1 = ".$vPurchaseTax1.
						 ", Purchase_Tax1Base1 = ".$vPurchaseTax1Base1.", Purchase_Tax1Base2 = ".$vPurchaseTax1Base2.
						 ", Purchase_Tax2 = ".$vPurchaseTax2.", Purchase_Tax2Base1 = ".$vPurchaseTax2Base1.", Purchase_Tax2Base2 = ".$vPurchaseTax2Base2.
						 ", Purchase_Tax3 = ".$vPurchaseTax3.", Purchase_Tax3Base1 = ".$vPurchaseTax3Base1.", Purchase_Tax3Base2 = ".$vPurchaseTax3Base2.
						 ", Purchase_Tax4 = ".$vPurchaseTax3.", Purchase_Tax4Base1 = ".$vPurchaseTax4Base1.", Purchase_Tax4Base2 = ".$vPurchaseTax4Base2.
						 ", Purchase_Tax5 = ".$vPurchaseTax5.", Purchase_Tax5Base1 = ".$vPurchaseTax5Base1.", Purchase_Tax5Base2 = ".$vPurchaseTax5Base2.
						 ", Purchase_Acctax1 = ".$vPurchaseAcctax1.", Purchase_Acctax2 = ".$vPurchaseAcctax2.",	Purchase_Acctax3 = ".$vPurchaseAcctax3.
						 ", Purchase_Acctax4 = ".$vPurchaseAcctax4.", Purchase_Acctax5 = ".$vPurchaseAcctax5.",	Purchase_DebitCur = ".$vPurchaseDebitCur.
						 ", Purchase_DebitAccount = ".$vPurchaseDebitAccount.", Purchase_BelongsToGroup = ".$vPurchaseBelongsToGroup.
						 ",	Purchase_Import = ".$vPurchaseImport.", Purchase_Type = ".$vPurchaseType.",	Purchase_Grn = ".$vPurchaseGrn.
						 ",	Porder_Ref = ".$vPorderReference.",	Purchase_PorderReferences = ".$vPorderReferences.", Purchase_VatChkbx = ".$vPurchaseVatChkbx.
						 ", Purchase_TotalQuantity = ".$vTotalQuantity.", Purchase_LoadHHT = ".$vPurchaseLoadHHT.", Destination_Branch = ".$vDestinationBranch.
						 "  Where Purchase_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Purchases Set Purchase_Syn_ID = ".$vPurchaseID.
							 " Where Purchase_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In PurchasesDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				if($vJournalType == 'PR') {
					$query = " Select RelatedSerial_Id ".
							 " From PurchasesSerialNo ".
							 " Where PurchaseDt_ID In ( Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) ".
							 " And Journal_Type = $vJournalType ".
							 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
					//echo $query; exit;		 
					$result=mysql_query($query,$PDestConn);
					while($rows=mysql_fetch_assoc($result)){		 
						$vRelatedSerialID = $rows['RelatedSerial_Id'];
						
						$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
									 " Where Serial_ID = ".$vRelatedSerialID;	
						$sub_result=mysql_query($sub_query,$PDestConn);
					}
				}
				
				$query = "Delete From PurchaseCharges Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select PurchaseDt_ID From PurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) And Journal_Type = $vJournalType ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From PurchasesDt Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			//Insert Related Charges From PurchaseCharges
			$query = " Select Auto, Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, ".
					 " Charges_AmountBase2, Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charge_Type, Charges_isSubjToCharge ".
					 " From PurchaseCharges ".
					 " Where Purchase_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				
				$sub_query = " Insert Into PurchaseCharges (Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, ".
							 " Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, Charges_isVat, Charges_GenerateDebit, Charge_Type, ".
							 " Charges_isSubjToCharge, Charges_Syn_ID, Purchase_Syn_ID ) ".
							 " Values ( ".$vPurchaseID.", ".GetSQLValueString($rows['Ledger_NumberDebit'],'text').", ".GetSQLValueString($rows['Ledger_NumberCredit'],'text').
							 ", ".GetSQLValueString($rows['Currency_code'],'text').", ".GetSQLValueString($rows['Charges_Amount'],'double').
							 ", ".GetSQLValueString($rows['Charges_AmountBase1'],'double').", ".GetSQLValueString($rows['Charges_AmountBase2'],'double').
							 ", ".GetSQLValueString($rows['Charges_distoption'],'double').", ".GetSQLValueString($rows['Charges_isVat'],'int').
							 ", ".GetSQLValueString($rows['Charges_GenerateDebit'],'int').", ".GetSQLValueString($rows['Charge_Type'],'text').
							 ", ".GetSQLValueString($rows['Charges_isSubjToCharge'],'int').", ".GetSQLValueString($rows['Auto'],'int').", ".$vPurchaseSynID." )";
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['Auto']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PurchaseCharges',$vMessage);
					
					break;
				}		
			}
				
			if ($vResult == 'T') {		
				//Insert Related Details From PurchasesDt
				$query = " Select PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, ".
						 " Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, ".
						 " PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, ".
						 " PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, ".
						 " PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, ".
						 " PurchaseDt_Charges, PurchaseDt_ChargesBase1,	PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, ".
						 " PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, ".
						 " Purchasedt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_UnitCoef, Item_Unit2Qty, RelatedDt_Id, ".
						 " Item_QtyPacked, PurchaseDt_OldData, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, prorderdt_id ".
						 " From PurchasesDt ".
						 " Where Purchase_ID = '".$PRecordID."'";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
					//$vPurchaseDtID = GetNextSequence($PDestConn,'Null','Null','ID','PURCHASESDT','','Null',$rows['Purchase_Date']);
					$vPurchaseDtID = GetNextSequence1($PDestConn,'PurchaseDt_id','');
					$vRelatedDtID  = F_Get_PurchasesDtRelatedID($PDestConn, $rows['RelatedDt_Id']);
					
					
					$sub_query = " Insert Into PurchasesDt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, ".
								 " CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
								 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, ".
								 " Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, ".
								 " PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, ".
								 " PurchaseDt_Charges, PurchaseDt_ChargesBase1,	PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, ".
								 " PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, ".
								 " Purchasedt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_UnitCoef, Item_Unit2Qty, RelatedDt_Id, ".
								 " Item_QtyPacked, PurchaseDt_OldData, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, prorderdt_id, PurchaseDt_Syn_ID, Purchase_Syn_ID ) ".
								 " Values ( ".$vPurchaseDtID.", ".$vPurchaseID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Purchase_Date'],'date').
								 ", ".GetSQLValueString($rows['Supplier_Code'],'text').", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').
								 ", ".GetSQLValueString($rows['CostCent_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').
								 ", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['PurchaseDt_Quantity'],'double').", ".GetSQLValueString($rows['PurchaseDt_Price'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_PriceBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_PriceBase2'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_DiscountPer'],'double').", ".GetSQLValueString($rows['PurchaseDt_DiscountAmount'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_DiscountBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_DiscountBase2'],'double').
								 ", ".GetSQLValueString($rows['Item_VAT'],'double').", ".GetSQLValueString($rows['PurchaseDt_Volume'],'double').
								 ", ".GetSQLValueString($rows['Purchasedt_Remark'],'text').", ".GetSQLValueString($rows['Purchase_invoiceNo'],'text').
								 ", ".GetSQLValueString($rows['PurchaseDt_ChargePer'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesAmnt'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_ChargesAmntB1'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesAmntB2'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_PriceTTC'],'double').", ".GetSQLValueString($rows['PurchaseDt_PriceTTCbase1'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_PriceTTCbase2'],'double').", ".GetSQLValueString($rows['PurchaseDt_Charges'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_ChargesBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesBase2'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_VatCharge'],'double').", ".GetSQLValueString($rows['PurchaseDt_VatChargeBase1'],'double').
								 ", ".GetSQLValueString($rows['PurchaseDt_VatChargeBase2'],'double').", ".GetSQLValueString($rows['Purchasedt_DirectStkDbt'],'text').
								 ", ".GetSQLValueString($rows['Purchasedt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['Purchasedt_DirectStkCur'],'text').
								 ", ".GetSQLValueString($rows['PurchaseDt_VATAccount'],'text').", ".GetSQLValueString($rows['Purchasedt_ItemAccount'],'text').
								 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
								 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
								 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".$vRelatedDtID.
								 ", ".GetSQLValueString($rows['Item_QtyPacked'],'double').", ".GetSQLValueString($rows['PurchaseDt_OldData'],'int').
								 ", ".GetSQLValueString($rows['PurchaseDt_ExpireDate'],'date').", ".GetSQLValueString($rows['PurchaseDt_BatchNo'],'text').
								 ", ".$vRelatedDtID.", ".GetSQLValueString($rows['PurchaseDt_id'],'int').", ".$vPurchaseSynID." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';
						
						//InCase Insert PurchasesDt Done, Then Inserts Related Serials
						$query1 = " Select Serial_ID, Journal_Type, PurchaseDt_id, Item_Code, SerialNo_Code, SerialNo_Used, ".
								  " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
								  " From PurchasesSerialNo ".
								  " Where PurchaseDt_ID = '".$rows['PurchaseDt_id']."' ".
								  " And Journal_Type = '".$rows['Journal_Type']."'";
						//echo $query1; exit;		 
						$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
						while($rows1=mysql_fetch_assoc($result1)){
							//$vSerialID 		  = GetNextSequence($PDestConn,'Null','Null','ID','PURCHASESSERIALNO','','Null',$rows['Purchase_Date']);
							$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
							$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
							
							$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, PurchaseDt_id, Item_Code, SerialNo_Code, ".
										  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
										  " Item_ExpireDate, Item_BatchNo, Serial_Syn_ID) ".
										  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vPurchaseDtID.
										  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
										  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
										  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
										  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Item_ExpireDate'],'date').
										  ", ".GetSQLValueString($rows1['Item_BatchNo'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int')." )";
							//echo $sub_query1; exit;	 
							$sub_result1=mysql_query($sub_query1,$PDestConn);
							if ($sub_result1) {
								if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null' && $rows1['Journal_Type'] == 'DR') {
									$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1, flagunique = Serial_ID ".
												  " Where Serial_ID = ".$vRelatedSerialID;	
									$sub_result2=mysql_query($sub_query2,$PDestConn);
								}	
							}
							else {
								$vResult  = 'P';
								$vMessage = mysql_error();
								$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
								$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
								
								break;
							}
						
						}
						
						//If Problem In Inserting A SerialNo Then Exit Loop Of PurchasesDt
						if ($vResult == 'P') break;
					
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert ID= ".$rows['PurchaseDt_id']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'PurchasesDt',$vMessage);
						
						break;
					}
				}

				if ($vResult == 'T') {
					// Synchro Related JV	
					$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
						
					$sub_query1 = " Update Purchases Set Journal_ID = '".$vJournalID."' ".
								  " Where Purchase_ID = '".$vPurchaseID."'";
					$sub_result1=mysql_query($sub_query1,$PDestConn);
				}	
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Purchases',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, Purchase_ID, Owner_Branch ".
					 " From Purchases Where Purchase_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vJournalType = $sub_result[1];
		$vPurchaseID  = $sub_result[2];
		$vOwnerBranch = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		if($vJournalType == 'PR') {
			$query = " Select RelatedSerial_Id ".
					 " From PurchasesSerialNo ".
					 " Where PurchaseDt_ID In ( Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) ".
					 " And Journal_Type = '".$vJournalType."' ".
					 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
			//echo $query; exit;		 
			$result=mysql_query($query,$PDestConn);
			while($rows=mysql_fetch_assoc($result)){		 
				$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
				$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
							 " Where Serial_ID = ".$vRelatedSerialID;	
				$sub_result=mysql_query($sub_query,$PDestConn);
			}
		}
		
		$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select PurchaseDt_ID From PurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) And Journal_Type = '".$vJournalType."'";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query  = "Delete From PurchasesDt Where Purchase_ID = '".$vPurchaseID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query  = "Delete From PurchaseCharges Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
			
				$query  = "Delete From Purchases Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'PurchasesDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPurchaseID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroGrnPurchases($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Purchase_ID, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, ".
				 " Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, ".
				 " Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, ".
				 " Purchase_DiscountBase2, Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, ".
				 " Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, Journal_Type, ".
				 " Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, ".
				 " Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, ".
				 " Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, ".
				 " Purchase_VatChkbx, Purchase_TotalQuantity, Purchase_Edit, SrvNo, WaybillNo, Purchase_PackingListRef, Purchase_FormMNo, Purchase_ReturnRef, ".
				 " User_Account, Owner_Branch, Destination_Branch, Purchase_Syn_ID ".
				 " From GrnPurchases ".
				 " Where Purchase_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vPurchaseSynID		 = GetSQLValueString($rows['Purchase_ID'],'int');
		$vJournalSynID		 = GetSQLValueString($rows['Journal_Id'],'int');
		$vSupplierID		 = GetSQLValueString($rows['Supplier_Id'],'int');
		$vProjectID			 = GetSQLValueString($rows['Project_Id'],'int');
		$vCostCentID		 = GetSQLValueString($rows['CostCent_Id'],'int');
		$vCurrencyID		 = GetSQLValueString($rows['Currency_Id'],'int');
		$vPurchaseReference	 = GetSQLValueString($rows['Purchase_Reference'],'double');
		$vPurchaseReturnRef	 = GetSQLValueString($rows['Purchase_ReturnRef'],'double');
		$vPorderReference    = GetSQLValueString($rows['Porder_Ref'],'double');
		$vPorderReferences   = GetSQLValueString($rows['Purchase_PorderReferences'],'double');
		$vPurchaseDate		 = GetSQLValueString($rows['Purchase_Date'],'date');
		$vJournalDtValueDate = GetSQLValueString($rows['Journaldt_valuedate'],'date');
		$vPurchaseRemark	 = GetSQLValueString($rows['Purchase_Remark'],'text');
		$vPurchaseInvoiceNo	 = GetSQLValueString($rows['Purchase_InvoiceNo'],'text');
		$vSupplierCode		 = GetSQLValueString($rows['Supplier_code'],'text');
		$vCurrencyCode		 = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_code'],'text');
		$vPurchasePosted	 = GetSQLValueString($rows['Purchase_Posted'],'int');
		$vPurchaseEdit		 = GetSQLValueString($rows['Purchase_Edit'],'int');
		$vPurchaseTaxable		   = GetSQLValueString($rows['Purchase_Taxable'],'double');
		$vPurchaseTaxableBase1	   = GetSQLValueString($rows['Purchase_TaxableBase1'],'double');
		$vPurchaseTaxableBase2	   = GetSQLValueString($rows['Purchase_TaxableBase2'],'double');
		$vPurchaseNoneTaxable	   = GetSQLValueString($rows['Purchase_NoneTaxable'],'double');
		$vPurchaseNoneTaxableBase1 = GetSQLValueString($rows['Purchase_NoneTaxableBase1'],'double');
		$vPurchaseNoneTaxableBase2 = GetSQLValueString($rows['Purchase_NoneTaxableBase2'],'double');
		$vPurchaseDiscountAmount   = GetSQLValueString($rows['Purchase_DiscountAmount'],'double');
		$vPurchaseDiscountBase1	   = GetSQLValueString($rows['Purchase_DiscountBase1'],'double');
		$vPurchaseDiscountBase2    = GetSQLValueString($rows['Purchase_DiscountBase2'],'double');
		$vPurchaseDiscountPer	   = GetSQLValueString($rows['Purchase_DiscountPer'],'double');
		$vPurchaseVAT			   = GetSQLValueString($rows['Purchase_VAT'],'double');
		$vPurchaseVATBase1		   = GetSQLValueString($rows['Purchase_VATBase1'],'double');
		$vPurchaseVATBase2		   = GetSQLValueString($rows['Purchase_VATBase2'],'double');
		$vPurchaseTotal			   = GetSQLValueString($rows['Purchase_Total'],'double');
		$vPurchaseTotalBase1	   = GetSQLValueString($rows['Purchase_TotalBase1'],'double');
		$vPurchaseTotalBase2	   = GetSQLValueString($rows['Purchase_TotalBase2'],'double');
		$vPurchaseCharges		   = GetSQLValueString($rows['Purchase_Charges'],'double');
		$vPurchaseChargesBase1	   = GetSQLValueString($rows['Purchase_ChargesBase1'],'double');
		$vPurchaseChargesBase2	   = GetSQLValueString($rows['Purchase_ChargesBase2'],'double');
		$vPurchaseMode			   = GetSQLValueString($rows['Purchase_Mode'],'int');
		$vJournalType 			   = GetSQLValueString($rows['Journal_Type'],'text');
		$vPurchaseBelongsToGroup   = GetSQLValueString($rows['Purchase_BelongsToGroup'],'int');
		$vPurchaseTax1 		= GetSQLValueString($rows['Purchase_tax1'],'double');
		$vPurchaseTax2 		= GetSQLValueString($rows['Purchase_tax2'],'double');
		$vPurchaseTax3 		= GetSQLValueString($rows['Purchase_tax3'],'double');
		$vPurchaseTax4 		= GetSQLValueString($rows['Purchase_tax4'],'double');
		$vPurchaseTax5 		= GetSQLValueString($rows['Purchase_tax5'],'double');
		$vPurchaseTax1Base1 = GetSQLValueString($rows['Purchase_tax1base1'],'double');
		$vPurchaseTax2Base1 = GetSQLValueString($rows['Purchase_tax2base1'],'double');
		$vPurchaseTax3Base1 = GetSQLValueString($rows['Purchase_tax3base1'],'double');
		$vPurchaseTax4Base1 = GetSQLValueString($rows['Purchase_tax4base1'],'double');
		$vPurchaseTax5Base1 = GetSQLValueString($rows['Purchase_tax5base1'],'double');
		$vPurchaseTax1Base2 = GetSQLValueString($rows['Purchase_tax1base2'],'double');
		$vPurchaseTax2Base2 = GetSQLValueString($rows['Purchase_tax2base2'],'double');
		$vPurchaseTax3Base2 = GetSQLValueString($rows['Purchase_tax3base2'],'double');
		$vPurchaseTax4Base2 = GetSQLValueString($rows['Purchase_tax4base2'],'double');
		$vPurchaseTax5Base2 = GetSQLValueString($rows['Purchase_tax5base2'],'double');
		$vPurchaseAcctax1 	= GetSQLValueString($rows['Purchase_Acctax1'],'text');
		$vPurchaseAcctax2 	= GetSQLValueString($rows['Purchase_Acctax2'],'text');
		$vPurchaseAcctax3 	= GetSQLValueString($rows['Purchase_Acctax3'],'text');
		$vPurchaseAcctax4 	= GetSQLValueString($rows['Purchase_Acctax4'],'text');
		$vPurchaseAcctax5 	= GetSQLValueString($rows['Purchase_Acctax5'],'text');
		$vPurchaseDebitCur 		   = GetSQLValueString($rows['Purchase_DebitCur'],'text');
		$vPurchaseDebitAccount	   = GetSQLValueString($rows['Purchase_DebitAccount'],'text');
		$vPurchaseVatChkbx		   = GetSQLValueString($rows['Purchase_VatChkbx'],'int');
		$vPurchaseImport 		   = GetSQLValueString($rows['Purchase_Import'],'int');
		$vPurchaseGrn 		   	   = GetSQLValueString($rows['Purchase_Grn'],'int');
		$vPurchaseType 			   = GetSQLValueString($rows['Purchase_Type'],'text');
		$vTotalQuantity		       = GetSQLValueString($rows['Purchase_TotalQuantity'],'double');
		$vPurchasePackingListRef   = GetSQLValueString($rows['Purchase_PackingListRef'],'text');
		$vPurchaseFormMNo 		   = GetSQLValueString($rows['Purchase_FormMNo'],'text');
		$vPurchaseSrvNo 		   = GetSQLValueString($rows['SrvNo'],'text');
		$vPurchaseWaybillNo		   = GetSQLValueString($rows['WaybillNo'],'text');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		$sub_query  = " Select Count(*) From GrnPurchases ".
		              " Where Purchase_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vPurchaseID = GetNextSequence($PDestConn,'Null','Null','ID','GRNPURCHASES','','Null',$rows['Purchase_Date']);
			$vPurchaseID = GetNextSequence1($PDestConn,'Grn_Id','');
			
			$sub_query = " Insert Into GrnPurchases (Purchase_ID, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, ".
						 " Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, ".
						 " Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, ".
						 " Purchase_DiscountBase2, Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, ".
						 " Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, Journal_Type, ".
						 " Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, ".
						 " Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, ".
						 " Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
						 " Purchase_DebitAccount, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, ".
						 " Purchase_VatChkbx, Purchase_TotalQuantity, Purchase_Edit, SrvNo, WaybillNo, Purchase_PackingListRef, Purchase_FormMNo, Purchase_ReturnRef, ".
						 " User_Account, Owner_Branch, Destination_Branch, Purchase_Syn_ID) ".
						 " Values ( ".$vPurchaseID.", ".$vPurchaseReference.", ".$vPurchaseDate.", ".$vPurchaseRemark.", ".$vSupplierCode.", ".$vCurrencyCode.
						 ", ".$vProjectCode.", ".$vCostcentCode.", ".$vPurchaseInvoiceNo.", ".$vJournalDtValueDate.", ".$vPurchasePosted.", ".$vPurchaseTaxable.
						 ", ".$vPurchaseTaxableBase1.", ".$vPurchaseTaxableBase2.", ".$vPurchaseNoneTaxable.", ".$vPurchaseNoneTaxableBase1.", ".$vPurchaseNoneTaxableBase2.
						 ", ".$vPurchaseDiscountAmount.", ".$vPurchaseDiscountBase1.", ".$vPurchaseDiscountBase2.", ".$vPurchaseDiscountPer.", ".$vPurchaseTotal.
						 ", ".$vPurchaseTotalBase1.", ".$vPurchaseTotalBase2.", ".$vPurchaseVAT.", ".$vPurchaseVATBase1.", ".$vPurchaseVATBase2.", ".$vPurchaseCharges.
						 ", ".$vPurchaseChargesBase1.", ".$vPurchaseChargesBase2.", ".$vPurchaseMode.", ".$vJournalType.", ".$vPurchaseTax1.", ".$vPurchaseTax1Base1.
						 ", ".$vPurchaseTax1Base2.", ".$vPurchaseTax2.", ".$vPurchaseTax2Base1.", ".$vPurchaseTax2Base2.", ".$vPurchaseTax3.", ".$vPurchaseTax3Base1.
						 ", ".$vPurchaseTax3Base2.", ".$vPurchaseTax4.", ".$vPurchaseTax4Base1.", ".$vPurchaseTax4Base2.", ".$vPurchaseTax5.", ".$vPurchaseTax5Base1.
						 ", ".$vPurchaseTax5Base2.", ".$vPurchaseAcctax1.", ".$vPurchaseAcctax2.", ".$vPurchaseAcctax3.", ".$vPurchaseAcctax4.", ".$vPurchaseAcctax5. 
						 ", ".$vPurchaseDebitCur.", ".$vPurchaseDebitAccount.", ".$vPurchaseBelongsToGroup.", ".$vPurchaseImport.", ".$vPurchaseType.", ".$vPurchaseGrn.
						 ", ".$vPorderReference.", ".$vPorderReferences.", ".$vPurchaseVatChkbx.", ".$vTotalQuantity.", ".$vPurchaseEdit.", ".$vPurchaseSrvNo.", ".$vPurchaseWaybillNo.
						 ", ".$vPurchasePackingListRef.", ".$vPurchaseFormMNo.", ".$vPurchaseReturnRef.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.
						 ", ".$vPurchaseSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Purchase_ID From GrnPurchases ".
					  " Where Purchase_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPurchaseID = $result[0];
			
			$sub_query = "  Update GrnPurchases Set Purchase_Date = ".$vPurchaseDate.", JournalDt_ValueDate = ".$vJournalDtValueDate. 
						 ",	Purchase_Remark = ".$vPurchaseRemark.", Supplier_code = ".$vSupplierCode.", Currency_Code = ".$vCurrencyCode.
						 ", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode.", Purchase_InvoiceNo = ".$vPurchaseInvoiceNo.  
						 ",	Purchase_Posted = ".$vPurchasePosted.", Purchase_Edit = ".$vPurchaseEdit.", Purchase_Taxable = ".$vPurchaseTaxable. 
						 ",	Purchase_TaxableBase1 = ".$vPurchaseTaxableBase1.", Purchase_TaxableBase2 = ".$vPurchaseTaxableBase2. 
						 ",	Purchase_NoneTaxable = ".$vPurchaseNoneTaxable.", Purchase_NoneTaxableBase1 = ".$vPurchaseNoneTaxableBase1. 
						 ", Purchase_NoneTaxableBase2 = ".$vPurchaseNoneTaxableBase2.", Purchase_DiscountAmount = ".$vPurchaseDiscountAmount. 
						 ",	Purchase_DiscountBase1 = ".$vPurchaseDiscountBase1.", Purchase_DiscountBase2 = ".$vPurchaseDiscountBase2. 
						 ",	Purchase_DiscountPer = ".$vPurchaseDiscountPer.", Purchase_Total = ".$vPurchaseTotal.
						 ", Purchase_TotalBase1 = ".$vPurchaseTotalBase1. ", Purchase_TotalBase2 = ".$vPurchaseTotalBase2.", Purchase_VAT = ".$vPurchaseVAT.
						 ", Purchase_VATBase1 = ".$vPurchaseVATBase1.",	Purchase_VATBase2 = ".$vPurchaseVATBase2.",	Purchase_Charges = ".$vPurchaseCharges.
						 ",	Purchase_ChargesBase1 = ".$vPurchaseChargesBase1.",	Purchase_ChargesBase2 = ".$vPurchaseChargesBase2.
						 ", Purchase_Mode = ".$vPurchaseMode.",	Journal_Type = ".$vJournalType.", Purchase_Tax1 = ".$vPurchaseTax1.
						 ", Purchase_Tax1Base1 = ".$vPurchaseTax1Base1.", Purchase_Tax1Base2 = ".$vPurchaseTax1Base2.
						 ", Purchase_Tax2 = ".$vPurchaseTax2.", Purchase_Tax2Base1 = ".$vPurchaseTax2Base1.", Purchase_Tax2Base2 = ".$vPurchaseTax2Base2.
						 ", Purchase_Tax3 = ".$vPurchaseTax3.", Purchase_Tax3Base1 = ".$vPurchaseTax3Base1.", Purchase_Tax3Base2 = ".$vPurchaseTax3Base2.
						 ", Purchase_Tax4 = ".$vPurchaseTax3.", Purchase_Tax4Base1 = ".$vPurchaseTax4Base1.", Purchase_Tax4Base2 = ".$vPurchaseTax4Base2.
						 ", Purchase_Tax5 = ".$vPurchaseTax5.", Purchase_Tax5Base1 = ".$vPurchaseTax5Base1.", Purchase_Tax5Base2 = ".$vPurchaseTax5Base2.
						 ", Purchase_Acctax1 = ".$vPurchaseAcctax1.", Purchase_Acctax2 = ".$vPurchaseAcctax2.",	Purchase_Acctax3 = ".$vPurchaseAcctax3.
						 ", Purchase_Acctax4 = ".$vPurchaseAcctax4.", Purchase_Acctax5 = ".$vPurchaseAcctax5.",	Purchase_DebitCur = ".$vPurchaseDebitCur.
						 ", Purchase_DebitAccount = ".$vPurchaseDebitAccount.", Purchase_BelongsToGroup = ".$vPurchaseBelongsToGroup.
						 ",	Purchase_Import = ".$vPurchaseImport.", Purchase_Type = ".$vPurchaseType.",	Purchase_Grn = ".$vPurchaseGrn.
						 ",	Porder_Ref = ".$vPorderReference.",	Purchase_PorderReferences = ".$vPorderReferences.", Purchase_VatChkbx = ".$vPurchaseVatChkbx.
						 ", Purchase_TotalQuantity = ".$vTotalQuantity.", SrvNo = ".$vPurchaseSrvNo.", WaybillNo = ".$vPurchaseWaybillNo.
						 ", Purchase_PackingListRef = ".$vPurchasePackingListRef.", Purchase_FormMNo = ".$vPurchaseFormMNo.", Purchase_ReturnRef = ".$vPurchaseReturnRef.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where Purchase_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update GrnPurchases Set Purchase_Syn_ID = ".$vPurchaseID.
							 " Where Purchase_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In GrnPurchasesDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				if($vJournalType == 'PR') {
					$query = " Select RelatedSerial_Id ".
							 " From PurchasesSerialNo ".
							 " Where GrnDt_ID In ( Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) ".
							 " And Journal_Type = $vJournalType ".
							 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
					//echo $query; exit;		 
					$result=mysql_query($query,$PDestConn);
					while($rows=mysql_fetch_assoc($result)){		 
						$vRelatedSerialID = $rows['RelatedSerial_Id'];
						
						$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
									 " Where Serial_ID = ".$vRelatedSerialID;	
						$sub_result=mysql_query($sub_query,$PDestConn);
					}
				}	
				
				$query = "Delete From PurchasesSerialNo Where GrnDt_ID In (Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) And Journal_Type = $vJournalType ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
							
			//Insert Related Details From GrnPurchasesDt 
			$query = " Select PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, ".
					 " Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, PurchaseDt_PriceBase2, ".
					 " PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, ".
					 " PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, ".
					 " PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, ".
					 " PurchaseDt_Charges, PurchaseDt_ChargesBase1,	PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, ".
					 " PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, ".
					 " Purchasedt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_UnitCoef, Item_Unit2Qty, RelatedDt_Id, ".
					 " Item_QtyPacked, PurchaseDt_OldData, Item_CodeFinished, Item_CodeSemiFinished, Related_Ref, PurchaseDt_ExpireDate, PurchaseDt_BatchNo ".
					 " From GrnPurchasesDt ".
					 " Where Purchase_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vPurchaseDtID = GetNextSequence($PDestConn,'Null','Null','ID','GRNPURCHASESDT','','Null',$rows['Purchase_Date']);
				$vPurchaseDtID = GetNextSequence1($PDestConn,'GrnDt_Id','');
				$vRelatedDtID  = F_Get_GrnDtRelatedID($PDestConn, $rows['RelatedDt_Id']);
				
				
				$sub_query = " Insert Into GrnPurchasesDt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, ".
							 " CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
							 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, ".
							 " Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, ".
							 " PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, ".
							 " PurchaseDt_Charges, PurchaseDt_ChargesBase1,	PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, ".
							 " PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, ".
							 " Purchasedt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_UnitCoef, Item_Unit2Qty, RelatedDt_Id, ".
							 " Item_QtyPacked, PurchaseDt_OldData, Item_CodeFinished, Item_CodeSemiFinished, Related_Ref, PurchaseDt_Syn_ID, Purchase_Syn_ID, ".
							 " PurchaseDt_ExpireDate, PurchaseDt_BatchNo ) ".
							 " Values ( ".$vPurchaseDtID.", ".$vPurchaseID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Purchase_Date'],'date').
							 ", ".GetSQLValueString($rows['Supplier_Code'],'text').", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').
							 ", ".GetSQLValueString($rows['CostCent_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').
							 ", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['PurchaseDt_Quantity'],'double').", ".GetSQLValueString($rows['PurchaseDt_Price'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_PriceBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_DiscountPer'],'double').", ".GetSQLValueString($rows['PurchaseDt_DiscountAmount'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_DiscountBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_DiscountBase2'],'double').
							 ", ".GetSQLValueString($rows['Item_VAT'],'double').", ".GetSQLValueString($rows['PurchaseDt_Volume'],'double').
							 ", ".GetSQLValueString($rows['Purchasedt_Remark'],'text').", ".GetSQLValueString($rows['Purchase_invoiceNo'],'text').
							 ", ".GetSQLValueString($rows['PurchaseDt_ChargePer'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesAmnt'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_ChargesAmntB1'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesAmntB2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_PriceTTC'],'double').", ".GetSQLValueString($rows['PurchaseDt_PriceTTCbase1'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_PriceTTCbase2'],'double').", ".GetSQLValueString($rows['PurchaseDt_Charges'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_ChargesBase1'],'double').", ".GetSQLValueString($rows['PurchaseDt_ChargesBase2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_VatCharge'],'double').", ".GetSQLValueString($rows['PurchaseDt_VatChargeBase1'],'double').
							 ", ".GetSQLValueString($rows['PurchaseDt_VatChargeBase2'],'double').", ".GetSQLValueString($rows['Purchasedt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['Purchasedt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['Purchasedt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['PurchaseDt_VATAccount'],'text').", ".GetSQLValueString($rows['Purchasedt_ItemAccount'],'text').
							 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".$vRelatedDtID.
							 ", ".GetSQLValueString($rows['Item_QtyPacked'],'double').", ".GetSQLValueString($rows['PurchaseDt_OldData'],'int').
							 ", ".GetSQLValueString($rows['Item_CodeFinished'],'text').", ".GetSQLValueString($rows['Item_CodeSemiFinished'],'text').
							 ", ".GetSQLValueString($rows['Related_Ref'],'double').", ".GetSQLValueString($rows['PurchaseDt_id'],'int').
							 ", ".$vPurchaseSynID.", ".GetSQLValueString($rows['PurchaseDt_ExpireDate'],'date').", ".GetSQLValueString($rows['PurchaseDt_BatchNo'],'text')." )";
								 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
						
					//InCase Insert GrnPurchasesDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, PurchaseDt_id, GrnDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, ".
							  " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where PurchaseDt_ID = '".$rows['PurchaseDt_id']."' ".
							  " And Journal_Type = '".$rows['Journal_Type']."'";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						//$vSerialID 		  = GetNextSequence($PDestConn,'Null','Null','ID','PURCHASESSERIALNO','','Null',$rows['Purchase_Date']);
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, PurchaseDt_id, GrnDt_ID, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
									  " Serial_Syn_ID, Item_ExpireDate, Item_BatchNo) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vPurchaseDtID.", ".$vPurchaseDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int').
									  ", ".GetSQLValueString($rows1['Item_ExpireDate'],'date').", ".GetSQLValueString($rows1['Item_BatchNo'],'int')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null' && $rows1['Journal_Type'] == 'DR') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1, flagunique = Serial_ID ".
											  " Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
						
					//If Problem In Inserting A SerialNo Then Exit Loop Of GrnPurchasesDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PurchaseDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'GrnPurchasesDt',$vMessage);
						
					break;
				}
			}

		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'GrnPurchases',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, Purchase_ID, Owner_Branch ".
					 " From GrnPurchases Where Purchase_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vJournalType = $sub_result[1];
		$vPurchaseID  = $sub_result[2];
		$vOwnerBranch = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		
		if($vJournalType == 'PR') {
			$query = " Select RelatedSerial_Id ".
					 " From PurchasesSerialNo ".
					 " Where GrnDt_ID In ( Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) ".
					 " And Journal_Type = '".$vJournalType."' ".
					 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
			//echo $query; exit;		 
			$result=mysql_query($query,$PDestConn);
			while($rows=mysql_fetch_assoc($result)){		 
				$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
				$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
							 " Where Serial_ID = ".$vRelatedSerialID;	
				$sub_result=mysql_query($sub_query,$PDestConn);
			}
		}	
		
		$query = "Delete From PurchasesSerialNo Where GrnDt_ID In (Select PurchaseDt_ID From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."' ) And Journal_Type = '".$vJournalType."'";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query  = "Delete From GrnPurchasesDt Where Purchase_ID = '".$vPurchaseID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query  = "Delete From GrnPurchases Where Purchase_ID = '".$vPurchaseID."'";
				$result = mysql_query($query, $PDestConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'GrnPurchasesDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPurchaseID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}


function F_SynchroAdjustmentRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select AdjustmentRequest_ID, AdjustmentRequest_Reference, AdjustmentRequest_Date, AdjustmentRequest_Remak, Currency_Code, Project_Code, Costcent_code, ".
                 " AdjustmentRequest_RequestBy, AdjustmentRequest_Type, AdjustmentRequest_EntryType, AdjustmentRequest_isInvoice, InvDebitAccount, InvCreditAccount, ".
				 " AdjustmentRequest_Amount, AdjustmentRequest_AmountBase1, AdjustmentRequest_AmountBase2, AdjustmentRequest_BelongsToGroup, AdjustmentRequest_Posted, ".
				 " Entry_Type, rejectedreason, User_Account, Owner_Branch, Destination_Branch, AdjustmentRequest_Syn_ID ".
				 " From AdjustmentRequest ".
				 " Where Adjustment_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vAdjustmentSynID		   = GetSQLValueString($rows['AdjustmentRequest_ID'],'int');
		$vAdjustmentReference	   = GetSQLValueString($rows['AdjustmentRequest_Reference'],'double');
		$vAdjustmentDate		   = GetSQLValueString($rows['AdjustmentRequest_Date'],'date');
		$vAdjustmentRemark	       = GetSQLValueString($rows['AdjustmentRequest_Remak'],'text');
		$vCurrencyCode		       = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		       = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		       = GetSQLValueString($rows['Costcent_code'],'text');
		$vAdjustmentRequestBy	   = GetSQLValueString($rows['AdjustmentRequest_RequestBy'],'text');
		$vAdjustmentType		   = GetSQLValueString($rows['AdjustmentRequest_Type'],'text');
		$vAdjustmentEntryType	   = GetSQLValueString($rows['AdjustmentRequest_EntryType'],'text');
		$vAdjustmentisInvoice	   = GetSQLValueString($rows['AdjustmentRequest_isInvoice'],'int');
		$vInvDebitAccount		   = GetSQLValueString($rows['InvDebitAccount'],'text');
		$vInvCreditAccount		   = GetSQLValueString($rows['InvCreditAccount'],'text');
		$vAdjustmentPosted	 	   = GetSQLValueString($rows['AdjustmentRequest_Posted'],'int');
		$vAdjustmentAmount		   = GetSQLValueString($rows['AdjustmentRequest_Amount'],'double');
		$vAdjustmentAmountBase1	   = GetSQLValueString($rows['AdjustmentRequest_AmountBase1'],'double');
		$vAdjustmentAmountBase2	   = GetSQLValueString($rows['AdjustmentRequest_AmountBase2'],'double');
		$vAdjustmentBelongsToGroup = GetSQLValueString($rows['AdjustmentRequest_BelongsToGroup'],'int');
		$vEntryType				   = GetSQLValueString($rows['Entry_Type'],'text');
		$vRejectedReason		   = GetSQLValueString($rows['rejectedreason'],'text');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		
		$sub_query  = " Select Count(*) From AdjustmentRequest ".
		              " Where AdjustmentRequest_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vAdjustmentID = GetNextSequence($PDestConn,'Null','Null','ID','ADJUSTMENT','','Null',$rows['Adjustment_Date']);
			$vAdjustmentID = GetNextSequence1($PDestConn,'AdjustmentRequest_ID','');
			
			$sub_query = " Insert Into AdjustmentRequest (AdjustmentRequest_ID, AdjustmentRequest_Reference, AdjustmentRequest_Date, AdjustmentRequest_Remak, Currency_Code, Project_Code, ".
						 " Costcent_code, AdjustmentRequest_RequestBy, AdjustmentRequest_Type, AdjustmentRequest_EntryType, AdjustmentRequest_isInvoice, InvDebitAccount, InvCreditAccount, ".
						 " AdjustmentRequest_Amount, AdjustmentRequest_AmountBase1, AdjustmentRequest_AmountBase2, AdjustmentRequest_BelongsToGroup, AdjustmentRequest_Posted, ".
						 " Entry_Type, rejectedreason, User_Account, Owner_Branch, Destination_Branch, AdjustmentRequest_Syn_ID ) ".
						 " Values ( ".$vAdjustmentID.", ".$vAdjustmentReference.", ".$vAdjustmentDate.", ".$vAdjustmentRemark.", ".$vCurrencyCode.", ".$vProjectCode.
						 ", ".$vCostcentCode.", ".$vAdjustmentRequestBy.", ".$vAdjustmentType.", ".$vAdjustmentEntryType.", ".$vAdjustmentisInvoice.", ".$vInvDebitAccount.
						 ", ".$vInvCreditAccount.", ".$vAdjustmentAmount.", ".$vAdjustmentAmountBase1.", ".$vAdjustmentAmountBase2.", ".$vAdjustmentBelongsToGroup.
						 ", ".$vAdjustmentPosted.", ".$vEntryType.", ".$vRejectedReason.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vAdjustmentSynID." )";
		}	
		
		//Case Record Exists - Update
		else {
			$query  = " Select AdjustmentRequest_ID From AdjustmentRequest ".
					  " Where AdjustmentRequest_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vAdjustmentID = $result[0];
			
			$sub_query = "  Update AdjustmentRequest Set AdjustmentRequest_Date = ".$vAdjustmentDate.", AdjustmentRequest_Remak = ".$vAdjustmentRemark. 
						 ",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode. 
						 ",	AdjustmentRequest_RequestBy = ".$vAdjustmentRequestBy.", AdjustmentRequest_Type = ".$vAdjustmentType.
						 ",	AdjustmentRequest_EntryType = ".$vAdjustmentEntryType.", AdjustmentRequest_isInvoice = ".$vAdjustmentisInvoice. 
						 ",	InvDebitAccount = ".$vInvDebitAccount.", InvCreditAccount = ".$vInvCreditAccount. 
						 ", AdjustmentRequest_Amount = ".$vAdjustmentAmount.", AdjustmentRequest_AmountBase1 = ".$vAdjustmentAmountBase1. 
						 ",	AdjustmentRequest_AmountBase2 = ".$vAdjustmentAmountBase2.", AdjustmentRequest_BelongsToGroup = ".$vAdjustmentBelongsToGroup. 
						 ",	AdjustmentRequest_Posted = ".$vAdjustmentPosted.", Entry_Type = ".$vEntryType.", rejectedreason = ".$vRejectedReason.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where AdjustmentRequest_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
					
			//InCase Update, Delete All Related Details In AdjustmentRequestDt
			If ($vRecordExists > 0) {
				$query = "Delete From AdjustmentRequestDt Where AdjustmentRequest_ID = '".$vAdjustmentID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From AdjustmentRequestDt
			$query = " Select AdjustmentRequestDt_ID, AdjustmentRequest_ID, Currency_Code, AdjustmentRequest_Date, Project_Code, CostCent_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentRequestDt_Quantity, AdjustmentRequestDt_Price, AdjustmentRequestDt_PriceBase1, ".
					 " AdjustmentRequestDt_PriceBase2, AdjustmentRequestDt_ExistingQty, AdjustmentRequestDt_PhysicalQty, Journal_Type, AdjustmentRequestDt_DirectStkDbt, ".
					 " AdjustmentRequestDt_DirectStkCrd, AdjustmentRequestDt_DirectStkCur, AdjustmentRequestDt_Posted, Item_UnitCoef, Item_Unit2Qty, AdjustmentRequestDt_ExpireDate, ".
					 " AdjustmentRequestDt_BatchNo, AdjustmentRequestDt_status, adjustmentrequestdt_approvedlevel, rejectedreason ".
					 " From AdjustmentRequestDt ".
					 " Where AdjustmentRequest_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vAdjustmentDtID = GetNextSequence($PDestConn,'Null','Null','ID','ADJUSTMENTDT','','Null',$rows['Adjustment_Date']);
				$vAdjustmentDtID = GetNextSequence1($PDestConn,'AdjustmentRequestDt_ID','');

				
				$sub_query = " Insert Into AdjustmentRequestDt (AdjustmentRequestDt_ID, AdjustmentRequest_ID, Currency_Code, AdjustmentRequest_Date, Project_Code, CostCent_Code, ".
							 " Warehouse_Code, Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentRequestDt_Quantity, AdjustmentRequestDt_Price, AdjustmentRequestDt_PriceBase1, ".
							 " AdjustmentRequestDt_PriceBase2, AdjustmentRequestDt_ExistingQty, AdjustmentRequestDt_PhysicalQty, Journal_Type, AdjustmentRequestDt_DirectStkDbt, ".
							 " AdjustmentRequestDt_DirectStkCrd, AdjustmentRequestDt_DirectStkCur, AdjustmentRequestDt_Posted, Item_UnitCoef, Item_Unit2Qty, AdjustmentRequestDt_ExpireDate, ".
							 " AdjustmentRequestDt_BatchNo, AdjustmentRequestDt_status, adjustmentrequestdt_approvedlevel, rejectedreason, AdjustmentRequestDt_Syn_ID, AdjustmentRequest_Syn_ID ) ".
							 " Values ( ".$vAdjustmentDtID.", ".$vAdjustmentID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['AdjustmentRequest_Date'],'date').
							 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCent_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').
							 ", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['Item_qtyPacked'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_Quantity'],'double').", ".GetSQLValueString($rows['AdjustmentRequestDt_Price'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_PriceBase1'],'double').", ".GetSQLValueString($rows['AdjustmentRequestDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_ExistingQty'],'double').", ".GetSQLValueString($rows['AdjustmentRequestDt_PhysicalQty'],'double').
							 ", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['AdjustmentRequestDt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['AdjustmentRequestDt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_Posted'],'int').", ".GetSQLValueString($rows['Item_UnitCoef'],'double').
							 ", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".GetSQLValueString($rows['AdjustmentRequestDt_ExpireDate'],'date').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_BatchNo'],'text').", ".GetSQLValueString($rows['AdjustmentRequestDt_status'],'text').
							 ", ".GetSQLValueString($rows['adjustmentrequestdt_approvedlevel'],'text').", ".GetSQLValueString($rows['rejectedreason'],'text').
							 ", ".GetSQLValueString($rows['AdjustmentRequestDt_ID'],'int').", ".$vAdjustmentSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['AdjustmentRequestDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'AdjustmentRequestDt',$vMessage);
					
					break;
				}
			}

		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'AdjustmentRequest',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select AdjustmentRequest_ID, Owner_Branch ".
					 " From AdjustmentRequest Where AdjustmentRequest_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vAdjustmentID = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		

		$query = "Delete From AdjustmentRequestDt Where AdjustmentRequest_ID = '".$vAdjustmentID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$vResult  = 'T';
			
			$query = "Delete From AdjustmentRequest Where AdjustmentRequest_ID = '".$vAdjustmentID."'";
			$result = mysql_query($query, $PDestConn);
				
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'AdjustmentRequest',$vMessage);
		}
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vAdjustmentID,'',$vOwnerBranch);
	}	
		
	
	
	Return $vResult;
}


function F_SynchroAdjustment($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Adjustment_ID, Adjustment_Reference, Adjustment_Date, Adjustment_Remak, Currency_Code, Project_Code, Costcent_code, ".
                 " Adjustment_RequestBy, Adjustment_Type, Adjustment_EntryType, Adjustment_isInvoice, InvDebitAccount, InvCreditAccount, ".
				 " Adjustment_Amount, Adjustment_AmountBase1, Adjustment_AmountBase2, Journal_Id, Adjustment_BelongsToGroup, Adjustment_Posted, ".
				 " AdjustmentRequest_Id, Entry_Type, User_Account, Owner_Branch, Destination_Branch, Adjustment_Syn_ID ".
				 " From Adjustment ".
				 " Where Adjustment_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vAdjustmentSynID		   = GetSQLValueString($rows['Adjustment_ID'],'int');
		$vJournalSynID			   = GetSQLValueString($rows['Journal_Id'],'int');
		$vAdjustRequestSynID	   = GetSQLValueString($rows['AdjustmentRequest_Id'],'int');
		$vAdjustmentReference	   = GetSQLValueString($rows['Adjustment_Reference'],'double');
		$vAdjustmentDate		   = GetSQLValueString($rows['Adjustment_Date'],'date');
		$vAdjustmentRemark	       = GetSQLValueString($rows['Adjustment_Remak'],'text');
		$vCurrencyCode		       = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		       = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		       = GetSQLValueString($rows['Costcent_code'],'text');
		$vAdjustmentRequestBy	   = GetSQLValueString($rows['Adjustment_RequestBy'],'text');
		$vAdjustmentType		   = GetSQLValueString($rows['Adjustment_Type'],'text');
		$vAdjustmentEntryType	   = GetSQLValueString($rows['Adjustment_EntryType'],'text');
		$vAdjustmentisInvoice	   = GetSQLValueString($rows['Adjustment_isInvoice'],'int');
		$vInvDebitAccount		   = GetSQLValueString($rows['InvDebitAccount'],'text');
		$vInvCreditAccount		   = GetSQLValueString($rows['InvCreditAccount'],'text');
		$vAdjustmentPosted	 	   = GetSQLValueString($rows['Adjustment_Posted'],'int');
		$vAdjustmentAmount		   = GetSQLValueString($rows['Adjustment_Amount'],'double');
		$vAdjustmentAmountBase1	   = GetSQLValueString($rows['Adjustment_AmountBase1'],'double');
		$vAdjustmentAmountBase2	   = GetSQLValueString($rows['Adjustment_AmountBase2'],'double');
		$vAdjustmentBelongsToGroup = GetSQLValueString($rows['Adjustment_BelongsToGroup'],'int');
		$vEntryType				   = GetSQLValueString($rows['Entry_Type'],'text');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		$vAdjustRequestId	 	   = F_Get_AdjustRequestID($PDestConn, $vAdjustRequestSynID);
		
		$sub_query  = " Select Count(*) From Adjustment ".
		              " Where Adjustment_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vAdjustmentID = GetNextSequence($PDestConn,'Null','Null','ID','ADJUSTMENT','','Null',$rows['Adjustment_Date']);
			$vAdjustmentID = GetNextSequence1($PDestConn,'Adjustment_ID','');
			
			$sub_query = " Insert Into Adjustment (Adjustment_ID, Adjustment_Reference, Adjustment_Date, Adjustment_Remak, Currency_Code, Project_Code, ".
						 " Costcent_code, Adjustment_RequestBy, Adjustment_Type, Adjustment_EntryType, Adjustment_isInvoice, InvDebitAccount, InvCreditAccount, ".
						 " Adjustment_Amount, Adjustment_AmountBase1, Adjustment_AmountBase2, Adjustment_BelongsToGroup, Adjustment_Posted, ".
						 " AdjustmentRequest_Id, Entry_Type, User_Account, Owner_Branch, Destination_Branch, Adjustment_Syn_ID ) ".
						 " Values ( ".$vAdjustmentID.", ".$vAdjustmentReference.", ".$vAdjustmentDate.", ".$vAdjustmentRemark.", ".$vCurrencyCode.", ".$vProjectCode.
						 ", ".$vCostcentCode.", ".$vAdjustmentRequestBy.", ".$vAdjustmentType.", ".$vAdjustmentEntryType.", ".$vAdjustmentisInvoice.", ".$vInvDebitAccount.
						 ", ".$vInvCreditAccount.", ".$vAdjustmentAmount.", ".$vAdjustmentAmountBase1.", ".$vAdjustmentAmountBase2.", ".$vAdjustmentBelongsToGroup.
						 ", ".$vAdjustmentPosted.", ".$vAdjustRequestId.", ".$vEntryType.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vAdjustmentSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Adjustment_ID From Adjustment ".
					  " Where Adjustment_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vAdjustmentID = $result[0];
			
			$sub_query = "  Update Adjustment Set Adjustment_Date = ".$vAdjustmentDate.", Adjustment_Remak = ".$vAdjustmentRemark. 
						 ",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.", Costcent_code = ".$vCostcentCode. 
						 ",	Adjustment_RequestBy = ".$vAdjustmentRequestBy.", Adjustment_Type = ".$vAdjustmentType.
						 ",	Adjustment_EntryType = ".$vAdjustmentEntryType.", Adjustment_isInvoice = ".$vAdjustmentisInvoice. 
						 ",	InvDebitAccount = ".$vInvDebitAccount.", InvCreditAccount = ".$vInvCreditAccount. 
						 ", Adjustment_Amount = ".$vAdjustmentAmount.", Adjustment_AmountBase1 = ".$vAdjustmentAmountBase1. 
						 ",	Adjustment_AmountBase2 = ".$vAdjustmentAmountBase2.", Adjustment_BelongsToGroup = ".$vAdjustmentBelongsToGroup. 
						 ",	Adjustment_Posted = ".$vAdjustmentPosted.", Entry_Type = ".$vEntryType.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where Adjustment_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Adjustment Set Adjustment_Syn_ID = ".$vAdjustmentID.
							 " Where Adjustment_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In AdjustmentDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				$query = " Select RelatedSerial_Id ".
						 " From PurchasesSerialNo ".
						 " Where PurchaseDt_ID In ( Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."' ) ".
					     " And Journal_Type = 'AR' ".
						 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
				//echo $query; exit;		 
				$result=mysql_query($query,$PDestConn);
				while($rows=mysql_fetch_assoc($result)){		 
					$vRelatedSerialID = $rows['RelatedSerial_Id'];
					
					$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
								 " Where Serial_ID = ".$vRelatedSerialID;	
					$sub_result=mysql_query($sub_query,$PDestConn);
				}
				
				$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."' ) And Journal_Type IN ('AI','AR') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From AdjustmentDt
			$query = " Select AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date, Project_Code, CostCent_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, ".
					 " AdjustmentDt_PriceBase2, AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Journal_Type, AdjustmentDt_DirectStkDbt, ".
					 " AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, AdjustmentDt_Posted, Item_UnitCoef, Item_Unit2Qty, AdjustmentDt_ExpireDate, ".
					 " AdjustmentDt_BatchNo, AdjustmentRequestDt_Id ".
					 " From AdjustmentDt ".
					 " Where Adjustment_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vAdjustmentDtID = GetNextSequence($PDestConn,'Null','Null','ID','ADJUSTMENTDT','','Null',$rows['Adjustment_Date']);
				$vAdjustmentDtID = GetNextSequence1($PDestConn,'AdjustmentDt_ID','');
				
				$vAdjustRequestDtId  = F_Get_AdjustRequestDtID($PDestConn, $rows['AdjustmentRequestDt_Id']);
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['AdjustmentDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'AdjustmentDt',$vMessage);
					
					break;
				}*/
				
				$sub_query = " Insert Into AdjustmentDt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date, Project_Code, CostCent_Code, ".
							 " Warehouse_Code, Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, ".
							 " AdjustmentDt_PriceBase2, AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Journal_Type, AdjustmentDt_DirectStkDbt, ".
							 " AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, AdjustmentDt_Posted, Item_UnitCoef, Item_Unit2Qty, AdjustmentDt_ExpireDate, ".
							 " AdjustmentDt_BatchNo, AdjustmentRequestDt_Id, AdjustmentDt_Syn_ID, Adjustment_Syn_ID ) ".
							 " Values ( ".$vAdjustmentDtID.", ".$vAdjustmentID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Adjustment_Date'],'date').
							 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCent_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').
							 ", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['Item_qtyPacked'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentDt_Quantity'],'double').", ".GetSQLValueString($rows['AdjustmentDt_Price'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentDt_PriceBase1'],'double').", ".GetSQLValueString($rows['AdjustmentDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['AdjustmentDt_ExistingQty'],'double').", ".GetSQLValueString($rows['AdjustmentDt_PhysicalQty'],'double').
							 ", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['AdjustmentDt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['AdjustmentDt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['AdjustmentDt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['AdjustmentDt_Posted'],'int').", ".GetSQLValueString($rows['Item_UnitCoef'],'double').
							 ", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').", ".GetSQLValueString($rows['AdjustmentDt_ExpireDate'],'date').
							 ", ".GetSQLValueString($rows['AdjustmentDt_BatchNo'],'text').", ".$vAdjustRequestDtId.
							 ", ".GetSQLValueString($rows['AdjustmentDt_ID'],'int').", ".$vAdjustmentSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
					
					//InCase Insert AdjustmentDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, AdjustmentDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, ".
					          " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where AdjustmentDt_ID = '".$rows['AdjustmentDt_ID']."' ".
							  " And Journal_Type = '".$rows['Journal_Type']."'";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						//$vSerialID = GetNextSequence($PDestConn,'Null','Null','ID','PURCHASESSERIALNO','','Null',$rows['Adjustment_Date']);
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, AdjustmentDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, ".
									  " Item_BatchNo, Serial_Syn_ID) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vAdjustmentDtID.", ".$vAdjustmentDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Item_ExpireDate'],'date').
									  ", ".GetSQLValueString($rows1['Item_BatchNo'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1 ";
								if($rows1['Journal_Type'] == 'AR')
									$sub_query2 = $sub_query2.", flagunique = Serial_ID ";
									
								$sub_query2 = $sub_query2." Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A SerialNo Then Exit Loop Of AdjustmentDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['AdjustmentDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'AdjustmentDt',$vMessage);
					
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Adjustment Set Journal_ID = '".$vJournalID."' ".
							  " Where Adjustment_ID = '".$vAdjustmentID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Adjustment',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Adjustment_ID, Owner_Branch ".
					 " From Adjustment Where Adjustment_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID    = $sub_result[0];
		$vAdjustmentID = $sub_result[1];
		$vOwnerBranch  = $sub_result[2];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Select RelatedSerial_Id ".
				 " From PurchasesSerialNo ".
				 " Where PurchaseDt_ID In ( Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."' ) ".
			     " And Journal_Type = 'AR' ".
				 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
		//echo $query; exit;		 
		$result=mysql_query($query,$PDestConn);
		while($rows=mysql_fetch_assoc($result)){		 
			$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
			$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0, flagunique = 0 ".
						 " Where Serial_ID = ".$vRelatedSerialID;	
			$sub_result=mysql_query($sub_query,$PDestConn);
		}
				
		$query = "Delete From PurchasesSerialNo Where PurchaseDt_ID In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."' ) And Journal_Type IN ('AI','AR') ";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query = "Delete From AdjustmentDt Where Adjustment_ID = '".$vAdjustmentID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Adjustment Where Adjustment_ID = '".$vAdjustmentID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'AdjustmentDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vAdjustmentID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroAssemble($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Production_ID, Production_Reference, Production_Date, Production_ExpireDate, Production_Remark, Currency_Code, ".
				 " Project_Code, Costcenter_code, Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_IdealQty, ".
				 " Production_Waste, Production_Total, Production_TotalBase1, Production_TotalBase2, Production_IdealTotal, Journal_Id, ".
				 " Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, ".
				 " Production_DirectStkDbt, Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, ".
				 " Production_WasteDiff, Item_UnitCoef, Item_Unit2Qty, SerialNo_Code, PreProduction_Id, Production_BatchNo, User_Account, ".
				 " Owner_Branch, Destination_Branch, Production_Syn_ID ".
				 " From Production ".
				 " Where Production_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vProductionSynID		   = GetSQLValueString($rows['Production_ID'],'int');
		$vJournalSynID			   = GetSQLValueString($rows['Journal_Id'],'int');
		$vProductionReference	   = GetSQLValueString($rows['Production_Reference'],'double');
		$vProductionDate		   = GetSQLValueString($rows['Production_Date'],'date');
		$vProductionExpireDate	   = GetSQLValueString($rows['Production_ExpireDate'],'date');
		$vProductionRemark	       = GetSQLValueString($rows['Production_Remark'],'text');
		$vCurrencyCode		       = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		       = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		       = GetSQLValueString($rows['Costcenter_code'],'text');
		$vProductionType		   = GetSQLValueString($rows['Production_Type'],'text');
		$vPrdItemCode	 		   = GetSQLValueString($rows['Item_code'],'text');
		$vPrdWarehouseCode	  	   = GetSQLValueString($rows['Warehouse_Code'],'text');
		$vProductionQuantity	   = GetSQLValueString($rows['Production_Quantity'],'double');
		$vProductionIdealQty   	   = GetSQLValueString($rows['Production_IdealQty'],'double');
		$vProductionWaste		   = GetSQLValueString($rows['Production_Waste'],'double');
		$vProductionTotal		   = GetSQLValueString($rows['Production_Total'],'double');
		$vProductionTotalBase1	   = GetSQLValueString($rows['Production_TotalBase1'],'double');
		$vProductionTotalBase2	   = GetSQLValueString($rows['Production_TotalBase2'],'double');
		$vProductionIdealTotal	   = GetSQLValueString($rows['Production_IdealTotal'],'double');
		$vProductionBelongsToGroup = GetSQLValueString($rows['Production_BelongsToGroup'],'int');
		$vProductionPosted		   = GetSQLValueString($rows['Production_Posted'],'int');
		$vProductionEdit		   = GetSQLValueString($rows['Production_Edit'],'int');
		$vProductionReversed	   = GetSQLValueString($rows['Production_Reversed'],'int');
		$vProductionItemAccount    = GetSQLValueString($rows['Production_ItemAccount'],'text');
		$vProductionDirectStkDbt   = GetSQLValueString($rows['Production_DirectStkDbt'],'text');
		$vProductionDirectStkCrd   = GetSQLValueString($rows['Production_DirectStkCrd'],'text');
		$vProductionDirectStkCur   = GetSQLValueString($rows['Production_DirectStkCur'],'text');
		$vProductionWasteDebit 	   = GetSQLValueString($rows['Production_WasteDebit'],'text');
		$vProductionWasteCredit    = GetSQLValueString($rows['Production_WasteCredit'],'text');
		$vProductionWasteDiff 	   = GetSQLValueString($rows['Production_WasteDiff'],'text');
		$vItemUnitCoef			   = GetSQLValueString($rows['Item_UnitCoef'],'double');
		$vItemUnit2Qty			   = GetSQLValueString($rows['Item_Unit2Qty'],'double');
		$vSerialNoCode 			   = GetSQLValueString($rows['SerialNo_Code'],'text');
		$vPreProductionSynId 	   = GetSQLValueString($rows['PreProduction_Id'],'double');
		$vProductionBatchNo 	   = GetSQLValueString($rows['Production_BatchNo'],'text');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$vPreProductionId	 	   = F_Get_PreProductionID($PDestConn, $vPreProductionSynId);
		
		/*$vCheckItemID	   = F_Check_ClientID($PDestConn, $vItemID);
		$vCheckWarehouseID = F_Check_SalesmanID($PDestConn, $vWarehouseID);
		$vCheckCurrencyID  = F_Check_CurrencyID($PDestConn, $vCurrencyID);
		$vCheckProjectID   = F_Check_ProjectID($PDestConn, $vProjectID);
		$vCheckCostCentID  = F_Check_CostCentID($PDestConn, $vCostCentID);
		
		if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 || $vCheckCurrencyID == 0 || 
		    $vCheckProjectID == 0 || $vCheckCostCentID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Warehouse|Item|Currency|Project|CostCent not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Production',$vMessage);
			
			Return $vResult;
		}*/
		
		$sub_query  = " Select Count(*) From Production ".
		              " Where Production_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vProductionID = GetNextSequence($PDestConn,'Null','Null','ID','ASSEMBLE','','Null',$rows['Production_Date']);
			$vProductionID = GetNextSequence1($PDestConn,'Production_ID','');
			
			$sub_query = " Insert Into Production (Production_ID, Production_Reference, Production_Date, Production_ExpireDate, Production_Remark, Currency_Code, ".
						 " Project_Code, Costcenter_code, Production_Type, Item_code, Warehouse_Code, Production_Quantity, Production_IdealQty, ".
						 " Production_Waste, Production_Total, Production_TotalBase1, Production_TotalBase2, Production_IdealTotal, ".
						 " Production_BelongsToGroup, Production_Posted, Production_Edit, Production_Reversed, Production_ItemAccount, ".
						 " Production_DirectStkDbt, Production_DirectStkCrd, Production_DirectStkCur, Production_WasteDebit, Production_WasteCredit, ".
						 " Production_WasteDiff, Item_UnitCoef, Item_Unit2Qty, SerialNo_Code, PreProduction_Id, Production_BatchNo, User_Account, ".
						 " Owner_Branch, Destination_Branch, Production_Syn_ID ) ".
						 " Values ( ".$vProductionID.", ".$vProductionReference.", ".$vProductionDate.", ".$vProductionExpireDate.", ".$vProductionRemark.", ".$vCurrencyCode.
						 ", ".$vProjectCode.", ".$vCostcentCode.", ".$vProductionType.", ".$vPrdItemCode.", ".$vPrdWarehouseCode.", ".$vProductionQuantity.
						 ", ".$vProductionIdealQty.", ".$vProductionWaste.", ".$vProductionTotal.", ".$vProductionTotalBase1.", ".$vProductionTotalBase2.
						 ", ".$vProductionIdealTotal.", ".$vProductionBelongsToGroup.", ".$vProductionPosted.", ".$vProductionEdit.", ".$vProductionReversed.
						 ", ".$vProductionItemAccount.", ".$vProductionDirectStkDbt.", ".$vProductionDirectStkCrd.", ".$vProductionDirectStkCur.
						 ", ".$vProductionWasteDebit.", ".$vProductionWasteCredit.", ".$vProductionWasteDiff.", ".$vItemUnitCoef.", ".$vItemUnit2Qty.
						 ", ".$vSerialNoCode.", ".$vPreProductionId.", ".$vProductionBatchNo.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.
						 ", ".$vProductionSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Production_ID From Production ".
					  " Where Production_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vProductionID = $result[0];
			
			$sub_query = "  Update Production Set Production_Date = ".$vProductionDate.", Production_ExpireDate = ".$vProductionExpireDate. 
						 ",	Production_Remark = ".$vProductionRemark.",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.
						 ", Costcenter_code = ".$vCostcentCode.", Production_Type = ".$vProductionType.", Item_code = ".$vPrdItemCode.
						 ",	Warehouse_Code = ".$vPrdWarehouseCode.", Production_Quantity = ".$vProductionQuantity. 
						 ",	Production_IdealQty = ".$vProductionIdealQty.", Production_Waste = ".$vProductionWaste. 
						 ", Production_Total = ".$vProductionTotal.", Production_TotalBase1 = ".$vProductionTotalBase1. 
						 ",	Production_TotalBase2 = ".$vProductionTotalBase2.", Production_IdealTotal = ".$vProductionIdealTotal. 
						 ",	Production_BelongsToGroup = ".$vProductionBelongsToGroup.", Production_Posted = ".$vProductionPosted.
						 ",	Production_Edit = ".$vProductionEdit.", Production_Reversed = ".$vProductionReversed.
						 ",	Production_ItemAccount = ".$vProductionItemAccount.", Production_DirectStkDbt = ".$vProductionDirectStkDbt.
						 ",	Production_DirectStkCrd = ".$vProductionDirectStkCrd.", Production_DirectStkCur = ".$vProductionDirectStkCur.
						 ",	Production_WasteDebit = ".$vProductionWasteDebit.", Production_WasteCredit = ".$vProductionWasteCredit.
						 ",	Production_WasteDiff = ".$vProductionWasteDiff.", Item_UnitCoef = ".$vItemUnitCoef.", Item_Unit2Qty = ".$vItemUnit2Qty.
						 ", SerialNo_Code = ".$vSerialNoCode.", Production_BatchNo = ".$vProductionBatchNo.",	Destination_Branch = ".$vDestinationBranch.
						 "  Where Production_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Production Set Production_Syn_ID = ".$vProductionID.
							 " Where Production_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In ProductionDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				
				$query = "Delete From ProductionDt Where Production_ID = '".$vProductionID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From ProductionDt
			$query = " Select ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
					 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ".
					 " ProductionDt_CostBase1, ProductionDt_CostBase2, ProductionDt_ExpireDate, ProductionDt_Remark, ProductionDt_ItemAccount, ".
					 " ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ".
					 " Item_UnitCoef, Item_Unit2Qty, SerialNo_Code, ProductionDt_BatchNo ".
					 " From ProductionDt ".
					 " Where Production_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vProductionDtID = GetNextSequence($PDestConn,'Null','Null','ID','ASSEMBLEDT','','Null',$rows['Production_Date']);
				$vProductionDtID = GetNextSequence1($PDestConn,'ProductionDt_ID','');
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['ProductionDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'ProductionDt',$vMessage);
					
					break;
				}*/
				
				$sub_query = " Insert Into ProductionDt (ProductionDt_ID, Production_ID, Currency_Code, Production_Date, Project_Code, CostCenter_Code, Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, ProductionDt_Quantity, ProductionDt_IdealQty, ProductionDt_Waste, ProductionDt_Cost, ".
							 " ProductionDt_CostBase1, ProductionDt_CostBase2, ProductionDt_ExpireDate, ProductionDt_Remark, ProductionDt_ItemAccount, ".
							 " ProductionDt_DirectStkDbt, ProductionDt_DirectStkCrd, ProductionDt_DirectStkCur, ProductionDt_WasteDebit, ProductionDt_WasteCredit, ".
							 " Item_UnitCoef, Item_Unit2Qty, SerialNo_Code, ProductionDt_BatchNo, ProductionDt_Syn_ID, Production_Syn_ID ) ".
							 " Values ( ".$vProductionDtID.", ".$vProductionID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Production_Date'],'date').
							 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['CostCenter_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').
							 ", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').", ".GetSQLValueString($rows['Item_qtyPacked'],'double').
							 ", ".GetSQLValueString($rows['ProductionDt_Quantity'],'double').", ".GetSQLValueString($rows['ProductionDt_IdealQty'],'double').
							 ", ".GetSQLValueString($rows['ProductionDt_Waste'],'double').", ".GetSQLValueString($rows['ProductionDt_Cost'],'double').
							 ", ".GetSQLValueString($rows['ProductionDt_CostBase1'],'double').", ".GetSQLValueString($rows['ProductionDt_CostBase2'],'double').
							 ", ".GetSQLValueString($rows['ProductionDt_ExpireDate'],'date').", ".GetSQLValueString($rows['ProductionDt_Remark'],'text').
							 ", ".GetSQLValueString($rows['ProductionDt_ItemAccount'],'text').", ".GetSQLValueString($rows['ProductionDt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['ProductionDt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['ProductionDt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['ProductionDt_WasteDebit'],'text').", ".GetSQLValueString($rows['ProductionDt_WasteCredit'],'text').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').
							 ", ".GetSQLValueString($rows['SerialNo_Code'],'text').", ".GetSQLValueString($rows['ProductionDt_BatchNo'],'text').
							 ", ".GetSQLValueString($rows['ProductionDt_ID'],'int').", ".$vProductionSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['ProductionDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'ProductionDt',$vMessage);
					
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Production Set Journal_ID = '".$vJournalID."' ".
							  " Where Production_ID = '".$vProductionID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Production',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Production_ID, Owner_Branch ".
					 " From Production Where Production_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID    = $sub_result[0];
		$vProductionID = $sub_result[1];
		$vOwnerBranch  = $sub_result[2];
		if(empty($vJournalID)) $vJournalID = -1;
						
		$query = "Delete From ProductionDt Where Production_ID = '".$vProductionID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$vResult  = 'T';
			
			$query = "Delete From Production Where Production_ID = '".$vProductionID."'";
			$result = mysql_query($query, $PDestConn);
				
			if ($vJournalID != -1) {
				$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}	
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'ProductionDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vProductionID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}


function F_SynchroTransferRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select TransferRequest_Id, TransferRequest_Reference, TransferRequest_Date, TransferRequest_Remark, TransferRequest_Posted, TransferRequest_Edit, ".
				 " Project_code1, Project_code2, Costcenter_Code, TransferRequest_BelongsToGroup, Adjustment_id, Driver_Name, Vehicle_No, f_Date, ".
				 " Requestedby, Company_Name, TransferRequest_WarehouseFrom, TransferRequest_WarehouseTo, ToCostcenter_Code, Document_RefNo, TransferRequest_Type, ".
				 " rejectedreason, Sorder_Reference, User_Account, Owner_Branch, Destination_Branch, TransferRequest_Syn_ID ".
				 " From TransferRequest ".
				 " Where TransferRequest_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vTransferSynID		   	   = GetSQLValueString($rows['TransferRequest_Id'],'int');
		$vTransferReference	  	   = GetSQLValueString($rows['TransferRequest_Reference'],'double');
		$vTransferDate		   	   = GetSQLValueString($rows['TransferRequest_Date'],'date');
		$vTransferRemark	       = GetSQLValueString($rows['TransferRequest_Remark'],'text');
		$vProject1Code		       = GetSQLValueString($rows['Project_code1'],'text');
		$vProject2Code		       = GetSQLValueString($rows['Project_code2'],'text');
		$vCostcent1Code		       = GetSQLValueString($rows['Costcenter_Code'],'text');
		$vCostcent2Code		       = GetSQLValueString($rows['ToCostcenter_Code'],'text');
		$vDriverName			   = GetSQLValueString($rows['Driver_Name'],'text');
		$vVehicleNo				   = GetSQLValueString($rows['Vehicle_No'],'text');
		$vFDate					   = GetSQLValueString($rows['f_Date'],'text');
		$vRequestedby			   = GetSQLValueString($rows['Requestedby'],'text');
		$vCompanyName			   = GetSQLValueString($rows['Company_Name'],'text');
		$vWarehouseFrom			   = GetSQLValueString($rows['TransferRequest_WarehouseFrom'],'text');
		$vWarehouseTo			   = GetSQLValueString($rows['TransferRequest_WarehouseTo'],'text');
		$vTransferPosted	 	   = GetSQLValueString($rows['TransferRequest_Posted'],'int');
		$vTransferEdit	 		   = GetSQLValueString($rows['TransferRequest_Edit'],'int');
		$vDocumentRefNo			   = GetSQLValueString($rows['Document_RefNo'],'text');
		$vTransferType			   = GetSQLValueString($rows['TransferRequest_Type'],'text');
		$vTransferBelongsToGroup   = GetSQLValueString($rows['TransferRequest_BelongsToGroup'],'int');
		$vRejectedReason 		   = GetSQLValueString($rows['rejectedreason'],'text');
		$vSorderReference 		   = GetSQLValueString($rows['Sorder_Reference'],'double');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');

		
		$sub_query  = " Select Count(*) From TransferRequest ".
		              " Where TransferRequest_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vTransferID = GetNextSequence($PDestConn,'Null','Null','ID','TRANSFER','','Null',$rows['Transfer_Date']);
			$vTransferID = GetNextSequence1($PDestConn,'TransferRequest_ID','');
			
			$sub_query = " Insert Into TransferRequest (TransferRequest_ID, TransferRequest_Reference, TransferRequest_Date, TransferRequest_Remark, TransferRequest_Posted, TransferRequest_Edit, ".
						 " Project_code1, Project_code2, Costcenter_Code, TransferRequest_BelongsToGroup, Driver_Name, Vehicle_No, f_Date, ".
						 " Requestedby, Company_Name, TransferRequest_WarehouseFrom, TransferRequest_WarehouseTo, ToCostcenter_Code, Document_RefNo, TransferRequest_Type, ".
						 " rejectedreason, Sorder_Reference, User_Account, Owner_Branch, Destination_Branch, TransferRequest_Syn_ID ) ".
						 " Values ( ".$vTransferID.", ".$vTransferReference.", ".$vTransferDate.", ".$vTransferRemark.", ".$vTransferPosted.", ".$vTransferEdit.
						 ", ".$vProject1Code.", ".$vProject2Code.", ".$vCostcent1Code.", ".$vTransferBelongsToGroup.", ".$vDriverName.", ".$vVehicleNo.", ".$vFDate.
						 ", ".$vRequestedby.", ".$vCompanyName.", ".$vWarehouseFrom.", ".$vWarehouseTo.", ".$vCostcent2Code.", ".$vDocumentRefNo.", ".$vTransferType.
						 ", ".$vRejectedReason.", ".$vSorderReference.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vTransferSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select TransferRequest_ID From TransferRequest ".
					  " Where TransferRequest_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vTransferID = $result[0];
			
			$sub_query = "  Update TransferRequest Set TransferRequest_Date = ".$vTransferDate.", TransferRequest_Remark = ".$vTransferRemark. 
						 ",	TransferRequest_Posted = ".$vTransferPosted.", TransferRequest_Edit = ".$vTransferEdit.
						 ", Project_code1 = ".$vProject1Code.",	Project_code2 = ".$vProject2Code.", Costcenter_Code = ".$vCostcent1Code.
						 ",	TransferRequest_BelongsToGroup = ".$vTransferBelongsToGroup.", Driver_Name = ".$vDriverName. 
						 ",	Vehicle_No = ".$vVehicleNo.", f_Date = ".$vFDate. 
						 ", Requestedby = ".$vRequestedby.", Company_Name = ".$vCompanyName. 
						 ",	TransferRequest_WarehouseFrom = ".$vWarehouseFrom.", TransferRequest_WarehouseTo = ".$vWarehouseTo. 
						 ",	ToCostcenter_Code = ".$vCostcent2Code.", Document_RefNo = ".$vDocumentRefNo.
						 ",	TransferRequest_Type = ".$vTransferType.", rejectedreason = ".$vRejectedReason.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where TransferRequest_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			
			//InCase Update, Delete All Related Details In TransferRequestDt
			If ($vRecordExists > 0) {
				$query = "Delete From TransferRequestDt Where TransferRequest_ID = '".$vTransferID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From TransferDt
			$query = " Select TransferRequestDt_ID, TransferRequest_ID, TransferRequest_Date, Item_Barcode, Item_code, TransferRequestDt_WarehouseFrom, TransferRequestDt_WarehouseTo, ".
					 " TransferRequestDt_Quantity, TransferRequestDt_ExpireDate, TransferRequestDt_Price, TransferRequestDt_PriceBase1, TransferRequestDt_PriceBase2, TransferRequest_Posted, ".
					 " Project_Code1, Project_Code2, Costcent_Code, TransferRequestDt_Remark, TransferRequestdt_posted, PreProduction_Serial, Item_CodePacked, ".
					 " Item_qtyPacked, TransferRequestDt_DirectStkDbt, TransferRequestDt_DirectStkCrd, TransferRequestDt_DirectStkCur, TransferRequestDt_PricePerUnit, TransferRequestDt_QtyUnit, ".
					 " Cur_code, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, ToCostcent_Code, Item_codefinished, Item_codesemifinished, ".
					 " TransferrequestDt_status, TransferrequestDt_approvedlevel, rejectedreason ".
					 " From TransferRequestDt ".
					 " Where TransferRequest_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vTransferDtID = GetNextSequence($PDestConn,'Null','Null','ID','TRANSFERDT','','Null',$rows['Transfer_Date']);
				$vTransferDtID    = GetNextSequence1($PDestConn,'TransferRequestdt_Id','');
				
				$sub_query = " Insert Into TransferRequestDt (TransferRequestDt_ID, TransferRequest_ID, TransferRequest_Date, Item_Barcode, Item_code, TransferRequestDt_WarehouseFrom, TransferRequestDt_WarehouseTo, ".
							 " TransferRequestDt_ExpireDate, TransferRequestDt_Quantity, TransferRequestDt_Price, TransferRequestDt_PriceBase1, TransferRequestDt_PriceBase2, TransferRequest_Posted, ".
							 " Project_Code1, Project_Code2, Costcent_Code, TransferRequestDt_Remark, TransferRequestdt_posted, PreProduction_Serial, Item_CodePacked, ".
							 " Item_qtyPacked, TransferRequestDt_DirectStkDbt, TransferRequestDt_DirectStkCrd, TransferRequestDt_DirectStkCur, TransferRequestDt_PricePerUnit, TransferRequestDt_QtyUnit, ".
							 " Cur_code, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id, ToCostcent_Code, Item_codefinished, Item_codesemifinished, ".
							 " TransferrequestDt_status, TransferrequestDt_approvedlevel, rejectedreason, TransferRequestDt_Syn_ID, TransferRequest_Syn_ID ) ".
							 " Values ( ".$vTransferDtID.", ".$vTransferID.", ".GetSQLValueString($rows['TransferRequest_Date'],'date').", ".GetSQLValueString($rows['Item_Barcode'],'text').
							 ", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['TransferRequestDt_WarehouseFrom'],'text').
							 ", ".GetSQLValueString($rows['TransferRequestDt_WarehouseTo'],'text').", ".GetSQLValueString($rows['TransferRequestDt_ExpireDate'],'date').
							 ", ".GetSQLValueString($rows['TransferRequestDt_Quantity'],'double').", ".GetSQLValueString($rows['TransferRequestDt_Price'],'double').
							 ", ".GetSQLValueString($rows['TransferRequestDt_PriceBase1'],'double').", ".GetSQLValueString($rows['TransferRequestDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['TransferRequest_Posted'],'int').", ".GetSQLValueString($rows['Project_Code1'],'text').
							 ", ".GetSQLValueString($rows['Project_Code2'],'text').", ".GetSQLValueString($rows['Costcent_Code'],'text').
							 ", ".GetSQLValueString($rows['TransferRequestDt_Remark'],'text').", ".GetSQLValueString($rows['TransferRequestdt_posted'],'int').
							 ", ".GetSQLValueString($rows['PreProduction_Serial'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['Item_qtyPacked'],'double').", ".GetSQLValueString($rows['TransferRequestDt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['TransferRequestDt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['TransferRequestDt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['TransferRequestDt_PricePerUnit'],'double').", ".GetSQLValueString($rows['TransferRequestDt_QtyUnit'],'double').
							 ", ".GetSQLValueString($rows['Cur_code'],'text').", ".GetSQLValueString($rows['Item_ManufacturedCode'],'text').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').
							 ", ".GetSQLValueString($rows['relateddt_id'],'double').", ".GetSQLValueString($rows['ToCostcent_Code'],'text').
							 ", ".GetSQLValueString($rows['Item_codefinished'],'text').", ".GetSQLValueString($rows['Item_codesemifinished'],'text').
							 ", ".GetSQLValueString($rows['TransferrequestDt_status'],'text').", ".GetSQLValueString($rows['TransferrequestDt_approvedlevel'],'int').
							 ", ".GetSQLValueString($rows['rejectedreason'],'text').
							 ", ".GetSQLValueString($rows['TransferRequestDt_ID'],'int').", ".$vTransferSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['TransferRequestDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'TransferRequestDt',$vMessage);
					
					break;
				}
			}
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'TransferRequest',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select TransferRequest_ID, Owner_Branch ".
					 " From TransferRequest Where TransferRequest_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vTransferID   = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		
		$query = "Delete From TransferRequestDt Where TransferRequest_ID = '".$vTransferID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$vResult  = 'T';
			
			$query = "Delete From Transfer Where TransferRequest_ID = '".$vTransferID."'";
			$result = mysql_query($query, $PDestConn);
				
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'TransferRequestDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vTransferID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}


function F_SynchroTransfer($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, Project_code1, ".
				 " Project_code2, Costcenter_Code, Journal_Id, Transfer_BelongsToGroup, Adjustment_id, Driver_Name, Vehicle_No, f_Date, ".
				 " Requestedby, Company_Name, Transfer_WarehouseFrom, Transfer_WarehouseTo, ToCostcenter_Code, Document_RefNo, Transfer_Type, ".
				 " Transfer_LOADHHT, TransferRequest_Id, Sorder_Reference, User_Account, Owner_Branch, Destination_Branch, Transfer_Syn_ID ".
				 " From Transfer ".
				 " Where Transfer_ID = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vTransferSynID		   	   = GetSQLValueString($rows['Transfer_Id'],'int');
		$vJournalSynID			   = GetSQLValueString($rows['Journal_Id'],'int');
		$vTransferReference	  	   = GetSQLValueString($rows['Transfer_Reference'],'double');
		$vTransferDate		   	   = GetSQLValueString($rows['Transfer_Date'],'date');
		$vTransferRemark	       = GetSQLValueString($rows['Transfer_Remark'],'text');
		$vProject1Code		       = GetSQLValueString($rows['Project_code1'],'text');
		$vProject2Code		       = GetSQLValueString($rows['Project_code2'],'text');
		$vCostcent1Code		       = GetSQLValueString($rows['Costcenter_Code'],'text');
		$vCostcent2Code		       = GetSQLValueString($rows['ToCostcenter_Code'],'text');
		$vDriverName			   = GetSQLValueString($rows['Driver_Name'],'text');
		$vVehicleNo				   = GetSQLValueString($rows['Vehicle_No'],'text');
		$vFDate					   = GetSQLValueString($rows['f_Date'],'text');
		$vRequestedby			   = GetSQLValueString($rows['Requestedby'],'text');
		$vCompanyName			   = GetSQLValueString($rows['Company_Name'],'text');
		$vWarehouseFrom			   = GetSQLValueString($rows['Transfer_WarehouseFrom'],'text');
		$vWarehouseTo			   = GetSQLValueString($rows['Transfer_WarehouseTo'],'text');
		$vTransferPosted	 	   = GetSQLValueString($rows['Transfer_Posted'],'int');
		$vTransferEdit	 		   = GetSQLValueString($rows['Transfer_Edit'],'int');
		$vDocumentRefNo			   = GetSQLValueString($rows['Document_RefNo'],'text');
		$vTransferType			   = GetSQLValueString($rows['Transfer_Type'],'text');
		$vTransferBelongsToGroup   = GetSQLValueString($rows['Transfer_BelongsToGroup'],'int');
		$vTransferLOADHHT		   = GetSQLValueString($rows['Transfer_LOADHHT'],'int');
		$vTransferReqSynID  	   = GetSQLValueString($rows['TransferRequest_Id'],'int');
		$vSorderReference 		   = GetSQLValueString($rows['Sorder_Reference'],'double');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');

		$vTransferReqID		 	   = F_Get_TransferReqID($PDestConn, $vTransferReqSynID);
		
		$sub_query  = " Select Count(*) From Transfer ".
		              " Where Transfer_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			//$vTransferID = GetNextSequence($PDestConn,'Null','Null','ID','TRANSFER','','Null',$rows['Transfer_Date']);
			$vTransferID = GetNextSequence1($PDestConn,'Transfer_ID','');
			
			$sub_query = " Insert Into Transfer (Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, ".
						 " Project_code1, Project_code2, Costcenter_Code, Transfer_BelongsToGroup, Driver_Name, Vehicle_No, f_Date, ".
						 " Requestedby, Company_Name, Transfer_WarehouseFrom, Transfer_WarehouseTo, ToCostcenter_Code, Document_RefNo, Transfer_Type, ".
						 " Transfer_LOADHHT, TransferRequest_Id, Sorder_Reference, User_Account, Owner_Branch, Destination_Branch, Transfer_Syn_ID ) ".
						 " Values ( ".$vTransferID.", ".$vTransferReference.", ".$vTransferDate.", ".$vTransferRemark.", ".$vTransferPosted.", ".$vTransferEdit.
						 ", ".$vProject1Code.", ".$vProject2Code.", ".$vCostcent1Code.", ".$vTransferBelongsToGroup.", ".$vDriverName.", ".$vVehicleNo.", ".$vFDate.
						 ", ".$vRequestedby.", ".$vCompanyName.", ".$vWarehouseFrom.", ".$vWarehouseTo.", ".$vCostcent2Code.", ".$vDocumentRefNo.", ".$vTransferType.
						 ", ".$vTransferLOADHHT.", ".$vTransferReqID.", ".$vSorderReference.", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vTransferSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Transfer_ID From Transfer ".
					  " Where Transfer_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vTransferID = $result[0];
			
			$sub_query = "  Update Transfer Set Transfer_Date = ".$vTransferDate.", Transfer_Remark = ".$vTransferRemark. 
						 ",	Transfer_Posted = ".$vTransferPosted.", Transfer_Edit = ".$vTransferEdit.
						 ", Project_code1 = ".$vProject1Code.",	Project_code2 = ".$vProject2Code.", Costcenter_Code = ".$vCostcent1Code.
						 ",	Transfer_BelongsToGroup = ".$vTransferBelongsToGroup.", Driver_Name = ".$vDriverName. 
						 ",	Vehicle_No = ".$vVehicleNo.", f_Date = ".$vFDate. 
						 ", Requestedby = ".$vRequestedby.", Company_Name = ".$vCompanyName. 
						 ",	Transfer_WarehouseFrom = ".$vWarehouseFrom.", Transfer_WarehouseTo = ".$vWarehouseTo. 
						 ",	ToCostcenter_Code = ".$vCostcent2Code.", Document_RefNo = ".$vDocumentRefNo.
						 ",	Transfer_Type = ".$vTransferType.", Transfer_LOADHHT = ".$vTransferLOADHHT.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where Transfer_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			
			//InCase Update, Delete All Related Details In TransferDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				$query = " Select RelatedSerial_Id ".
						 " From PurchasesSerialNo ".
						 " Where TransferDt_ID In ( Select TransferDt_ID From TransferDt Where Transfer_ID = '".$vTransferID."' ) ".
					     " And Journal_Type = 'TR' ".
						 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
				//echo $query; exit;		 
				$result=mysql_query($query,$PDestConn);
				while($rows=mysql_fetch_assoc($result)){		 
					$vRelatedSerialID = $rows['RelatedSerial_Id'];
					
					$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ".
								 " Where Serial_ID = ".$vRelatedSerialID;	
					$sub_result=mysql_query($sub_query,$PDestConn);
				}
				
				$query = "Delete From PurchasesSerialNo Where TransferDt_ID In (Select TransferDt_ID From TransferDt Where Transfer_ID = '".$vTransferID."' ) And Journal_Type = 'TR' ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From TransferDt Where Transfer_ID = '".$vTransferID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			//Insert Related Details From TransferDt
			$query = " Select TransferDt_ID, Transfer_ID, Transfer_Date, Item_Barcode, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, ".
					 " TransferDt_Quantity, TransferDt_ExpireDate, TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, ".
					 " Project_Code1, Project_Code2, Costcent_Code, Transferdt_remark, Transferdt_posted, PreProduction_Serial, Item_CodePacked, ".
					 " Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur, TransferDt_PricePerUnit, TransferDt_QtyUnit, ".
					 " Cur_code, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id, ToCostcent_Code, Item_codefinished, Item_codesemifinished, ".
					 " TransferRequest_Reference, TransferRequestdt_Id ".
					 " From TransferDt ".
					 " Where Transfer_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vTransferDtID = GetNextSequence($PDestConn,'Null','Null','ID','TRANSFERDT','','Null',$rows['Transfer_Date']);
				$vTransferDtID    = GetNextSequence1($PDestConn,'TransferDt_ID','');
				$vTransferReqDtID = F_Get_TransferReqDtID($PDestConn, $rows['TransferRequestdt_Id']);
				
				$sub_query = " Insert Into TransferDt (TransferDt_ID, Transfer_ID, Transfer_Date, Item_Barcode, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, ".
							 " TransferDt_ExpireDate, TransferDt_Quantity, TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, ".
							 " Project_Code1, Project_Code2, Costcent_Code, Transferdt_remark, Transferdt_posted, PreProduction_Serial, Item_CodePacked, ".
							 " Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur, TransferDt_PricePerUnit, TransferDt_QtyUnit, ".
							 " Cur_code, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id, ToCostcent_Code, Item_codefinished, Item_codesemifinished, ".
							 " TransferRequest_Reference, TransferRequestdt_Id, TransferDt_Syn_ID, Transfer_Syn_ID ) ".
							 " Values ( ".$vTransferDtID.", ".$vTransferID.", ".GetSQLValueString($rows['Transfer_Date'],'date').", ".GetSQLValueString($rows['Item_Barcode'],'text').
							 ", ".GetSQLValueString($rows['Item_code'],'text').", ".GetSQLValueString($rows['TransferDt_WarehouseFrom'],'text').
							 ", ".GetSQLValueString($rows['TransferDt_WarehouseTo'],'text').", ".GetSQLValueString($rows['TransferDt_ExpireDate'],'date').
							 ", ".GetSQLValueString($rows['TransferDt_Quantity'],'double').", ".GetSQLValueString($rows['TransferDt_Price'],'double').
							 ", ".GetSQLValueString($rows['TransferDt_PriceBase1'],'double').", ".GetSQLValueString($rows['TransferDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['Transfer_Posted'],'int').", ".GetSQLValueString($rows['Project_Code1'],'text').
							 ", ".GetSQLValueString($rows['Project_Code2'],'text').", ".GetSQLValueString($rows['Costcent_Code'],'text').
							 ", ".GetSQLValueString($rows['Transferdt_remark'],'text').", ".GetSQLValueString($rows['Transferdt_posted'],'int').
							 ", ".GetSQLValueString($rows['PreProduction_Serial'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['Item_qtyPacked'],'double').", ".GetSQLValueString($rows['TransferDt_DirectStkDbt'],'text').
							 ", ".GetSQLValueString($rows['TransferDt_DirectStkCrd'],'text').", ".GetSQLValueString($rows['TransferDt_DirectStkCur'],'text').
							 ", ".GetSQLValueString($rows['TransferDt_PricePerUnit'],'double').", ".GetSQLValueString($rows['TransferDt_QtyUnit'],'double').
							 ", ".GetSQLValueString($rows['Cur_code'],'text').", ".GetSQLValueString($rows['Item_ManufacturedCode'],'text').
							 ", ".GetSQLValueString($rows['Item_UnitCoef'],'double').", ".GetSQLValueString($rows['Item_Unit2Qty'],'double').
							 ", ".GetSQLValueString($rows['relateddt_id'],'double').", ".GetSQLValueString($rows['ToCostcent_Code'],'text').
							 ", ".GetSQLValueString($rows['Item_codefinished'],'text').", ".GetSQLValueString($rows['Item_codesemifinished'],'text').
							 ", ".GetSQLValueString($rows['TransferRequest_Reference'],'double').", ".$vTransferReqDtID.
							 ", ".GetSQLValueString($rows['TransferDt_ID'],'int').", ".$vTransferSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
					
					//InCase Insert TransferDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, TransferDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, ".
					          " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where TransferDt_ID = '".$rows['TransferDt_ID']."' ".
							  " And Journal_Type = 'TR'";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, TransferDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
									  " Serial_Syn_ID, Item_ExpireDate, Item_BatchNo) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vTransferDtID.", ".$vTransferDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int').
									  ", ".GetSQLValueString($rows1['Item_ExpireDate'],'date').", ".GetSQLValueString($rows1['Item_BatchNo'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1, flagunique = Serial_ID ".
											  " Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A SerialNo Then Exit Loop Of TransferDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['TransferDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'TransferDt',$vMessage);
					
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Transfer Set Journal_ID = '".$vJournalID."' ".
							  " Where Transfer_ID = '".$vTransferID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Transfer',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Transfer_ID, Owner_Branch ".
					 " From Transfer Where Transfer_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID    = $sub_result[0];
		$vTransferID   = $sub_result[1];
		$vOwnerBranch  = $sub_result[2];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Select RelatedSerial_Id ".
				 " From PurchasesSerialNo ".
				 " Where TransferDt_ID In ( Select TransferDt_ID From TransferDt Where Transfer_ID = '".$vTransferID."' ) ".
			     " And Journal_Type = 'TR' ".
				 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
		//echo $query; exit;		 
		$result=mysql_query($query,$PDestConn);
		while($rows=mysql_fetch_assoc($result)){		 
			$vRelatedSerialID = $rows['RelatedSerial_Id'];
				
			$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ".
						 " Where Serial_ID = ".$vRelatedSerialID;	
			$sub_result=mysql_query($sub_query,$PDestConn);
		}
				
		$query = "Delete From PurchasesSerialNo Where TransferDt_ID In (Select TransferDt_ID From TransferDt Where Transfer_ID = '".$vTransferID."' ) And Journal_Type = 'TR' ";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query = "Delete From TransferDt Where Transfer_ID = '".$vTransferID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Transfer Where Transfer_ID = '".$vTransferID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'TransferDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vTransferID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroRetail($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Sale_ID, Sale_Reference, Sale_Date, Sale_Remark, Client_code, Salesman_Code, Currency_Code, Project_Code, ".
				 " Costcenter_code, CashRegister_Name, Sale_TotalQuantity, Sale_TotalQuantityRet, Sale_Taxable, Sale_TaxableBase1, ".
				 " Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, Sale_DiscountAmount, ".
				 " Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, ".
				 " Sale_TotalBase1, Sale_TotalBase2, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_Posted, Sale_Mode, ".
				 " Journal_Type, Journal_Id, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
				 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, ".
				 " Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, ".
				 " Sale_CashCur, Sale_CashAccount, Sale_Cash, Sale_CashBase1, Sale_CashBase2, Sale_CheckDate, Sale_CheckNo, Sale_Bank, ".
				 " Sale_BankBranch, Sales_CashInBase1, Sales_CashOutBase1, Sales_CashInBase2, Sales_CashOutBase2, Sales_TipsBase1, ".
				 " Coupon_amount, Coupon_amountbase1, Coupon_amountbase2, Coupon_id, Sale_information, Sale_ClientCur, Sale_CreditAccountVat, ".
				 " Sales_CreditAmount, Sales_CreditAmountBase1, Sales_CreditAmountBase2, Sales_creditacc, Sales_creditacccur, Login_CardNo, ".
				 " Sale_SupervisorCode, Customer_Code, User_Account, Owner_Branch, Destination_Branch, Sale_Syn_ID ".
				 " From Retail ".
				 " Where Sale_ID = '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error($PLocConn));
		$rows=mysql_fetch_assoc($result);
		
		$vSaleSynID		 	   = GetSQLValueString($rows['Sale_ID'],'int');
		$vJournalSynID		   = GetSQLValueString($rows['Journal_Id'],'int');
		$vCouponID			   = GetSQLValueString($rows['Coupon_id'],'int');
		$vSaleReference	 	   = GetSQLValueString($rows['Sale_Reference'],'double');
		$vSaleDate			   = GetSQLValueString($rows['Sale_Date'],'date');
		$vSaleRemark	 	   = GetSQLValueString($rows['Sale_Remark'],'text');
		$vClientCode		   = GetSQLValueString($rows['Client_code'],'text');
		$vSalesmanCode		   = GetSQLValueString($rows['Salesman_Code'],'text');
		$vCustomerCode		   = GetSQLValueString($rows['Customer_Code'],'text');
		$vCurrencyCode		   = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		   = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		   = GetSQLValueString($rows['Costcenter_code'],'text');
		$vSalePosted		   = GetSQLValueString($rows['Sale_Posted'],'int');
		$vSaleMode			   = GetSQLValueString($rows['Sale_Mode'],'int');
		$vSaleTaxable		   = GetSQLValueString($rows['Sale_Taxable'],'double');
		$vSaleTaxableBase1	   = GetSQLValueString($rows['Sale_TaxableBase1'],'double');
		$vSaleTaxableBase2	   = GetSQLValueString($rows['Sale_TaxableBase2'],'double');
		$vSaleNoneTaxable	   = GetSQLValueString($rows['Sale_NoneTaxable'],'double');
		$vSaleNoneTaxableBase1 = GetSQLValueString($rows['Sale_NoneTaxableBase1'],'double');
		$vSaleNoneTaxableBase2 = GetSQLValueString($rows['Sale_NoneTaxableBase2'],'double');
		$vSaleDiscountAmount   = GetSQLValueString($rows['Sale_DiscountAmount'],'double');
		$vSaleDiscountBase1	   = GetSQLValueString($rows['Sale_DiscountBase1'],'double');
		$vSaleDiscountBase2    = GetSQLValueString($rows['Sale_DiscountBase2'],'double');
		$vSaleDiscountPer	   = GetSQLValueString($rows['Sale_DiscountPer'],'double');
		$vSaleVAT			   = GetSQLValueString($rows['Sale_VAT'],'double');
		$vSaleVATBase1		   = GetSQLValueString($rows['Sale_VATBase1'],'double');
		$vSaleVATBase2		   = GetSQLValueString($rows['Sale_VATBase2'],'double');
		$vSaleTotal			   = GetSQLValueString($rows['Sale_Total'],'double');
		$vSaleTotalBase1	   = GetSQLValueString($rows['Sale_TotalBase1'],'double');
		$vSaleTotalBase2	   = GetSQLValueString($rows['Sale_TotalBase2'],'double');
		$vSaleNetTotal		   = GetSQLValueString($rows['Sale_NetTotal'],'double');
		$vSaleNetTotalBase1	   = GetSQLValueString($rows['Sale_NetTotalBase1'],'double');
		$vSaleNetTotalBase2	   = GetSQLValueString($rows['Sale_NetTotalBase2'],'double');
		$vJournalType 		   = GetSQLValueString($rows['Journal_Type'],'text');
		$vSaleTax1 		= GetSQLValueString($rows['Sale_Tax1'],'double');
		$vSaleTax2 		= GetSQLValueString($rows['Sale_Tax2'],'double');
		$vSaleTax3 		= GetSQLValueString($rows['Sale_Tax3'],'double');
		$vSaleTax4 		= GetSQLValueString($rows['Sale_Tax4'],'double');
		$vSaleTax5 		= GetSQLValueString($rows['Sale_Tax5'],'double');
		$vSaleTax1Base1 = GetSQLValueString($rows['Sale_Tax1Base1'],'double');
		$vSaleTax2Base1 = GetSQLValueString($rows['Sale_Tax2Base1'],'double');
		$vSaleTax3Base1 = GetSQLValueString($rows['Sale_Tax3Base1'],'double');
		$vSaleTax4Base1 = GetSQLValueString($rows['Sale_Tax4Base1'],'double');
		$vSaleTax5Base1 = GetSQLValueString($rows['Sale_Tax5Base1'],'double');
		$vSaleTax1Base2 = GetSQLValueString($rows['Sale_Tax1Base2'],'double');
		$vSaleTax2Base2 = GetSQLValueString($rows['Sale_Tax2Base2'],'double');
		$vSaleTax3Base2 = GetSQLValueString($rows['Sale_Tax3Base2'],'double');
		$vSaleTax4Base2 = GetSQLValueString($rows['Sale_Tax4Base2'],'double');
		$vSaleTax5Base2 = GetSQLValueString($rows['Sale_Tax5Base2'],'double');
		$vSaleAcctax1 	= GetSQLValueString($rows['Sale_Acctax1'],'text');
		$vSaleAcctax2 	= GetSQLValueString($rows['Sale_Acctax2'],'text');
		$vSaleAcctax3 	= GetSQLValueString($rows['Sale_Acctax3'],'text');
		$vSaleAcctax4 	= GetSQLValueString($rows['Sale_Acctax4'],'text');
		$vSaleAcctax5 	= GetSQLValueString($rows['Sale_Acctax5'],'text');
		$vSaleCreditCur 		   = GetSQLValueString($rows['Sale_CreditCur'],'text');
		$vSaleCreditAccount		   = GetSQLValueString($rows['Sale_CreditAccount'],'text');
		$vSaleCashCur			   = GetSQLValueString($rows['Sale_CashCur'],'text');
		$vSaleCashAccount		   = GetSQLValueString($rows['Sale_CashAccount'],'text');
		$vSaleCash	 	           = GetSQLValueString($rows['Sale_Cash'],'double');
		$vSaleCashBase1			   = GetSQLValueString($rows['Sale_CashBase1'],'double');
		$vSaleCashBase2		  	   = GetSQLValueString($rows['Sale_CashBase2'],'double');
		$vSaleCheckDate		       = GetSQLValueString($rows['Sale_CheckDate'],'date');
		$vSaleCheckNo		   	   = GetSQLValueString($rows['Sale_CheckNo'],'text');
		$vSaleBank		   		   = GetSQLValueString($rows['Sale_Bank'],'text');
		$vSaleBankBranch 		   = GetSQLValueString($rows['Sale_BankBranch'],'text');
		$vSalesCashInBase1	 	   = GetSQLValueString($rows['Sales_CashInBase1'],'double');
		$vSalesCashOutBase1		   = GetSQLValueString($rows['Sales_CashOutBase1'],'double');
		$vSalesCashInBase2 		   = GetSQLValueString($rows['Sales_CashInBase2'],'double');
		$vSalesCashOutBase2	  	   = GetSQLValueString($rows['Sales_CashOutBase2'],'double');
		$vSalesTipsBase1		   = GetSQLValueString($rows['Sales_TipsBase1'],'double');
		$vCouponAmount	 		   = GetSQLValueString($rows['Coupon_amount'],'double');
		$vCouponAmountBase1 	   = GetSQLValueString($rows['Coupon_amountbase1'],'double');
		$vCouponAmountBase2 	   = GetSQLValueString($rows['Coupon_amountbase2'],'double');
		$vSaleInformation 		   = GetSQLValueString($rows['Sale_information'],'text');
		$vSaleClientCur 		   = GetSQLValueString($rows['Sale_ClientCur'],'text');
		$vSaleCreditAccountVat 	   = GetSQLValueString($rows['Sale_CreditAccountVat'],'text');
		$vSalesCreditAmount 	   = GetSQLValueString($rows['Sales_CreditAmount'],'double');
		$vSalesCreditAmountBase1   = GetSQLValueString($rows['Sales_CreditAmountBase1'],'double');
		$vSalesCreditAmountBase2   = GetSQLValueString($rows['Sales_CreditAmountBase2'],'double');
		$vSalesCreditAcc 		   = GetSQLValueString($rows['Sales_creditacc'],'text');
		$vSalesCreditacccur 	   = GetSQLValueString($rows['Sales_creditacccur'],'text');
		$vSaleTotalQuantity 	   = GetSQLValueString($rows['Sale_TotalQuantity'],'double');
		$vSaleTotalQuantityRet 	   = GetSQLValueString($rows['Sale_TotalQuantityRet'],'double');
		$vCashRegisterName 		   = GetSQLValueString($rows['CashRegister_Name'],'text');
		$vLoginCardNo 		 	   = GetSQLValueString($rows['Login_CardNo'],'text');
		$vSaleSupervisorCode 	   = GetSQLValueString($rows['Sale_SupervisorCode'],'text');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		/*$vCheckClientID	   = F_Check_ClientID($PDestConn, $vClientID);
		$vCheckSalesmanID  = F_Check_SalesmanID($PDestConn, $vSalesmanID);
		$vCheckCurrencyID  = F_Check_CurrencyID($PDestConn, $vCurrencyID);
		$vCheckProjectID   = F_Check_ProjectID($PDestConn, $vProjectID);
		$vCheckCostCentID  = F_Check_CostCentID($PDestConn, $vCostCentID);
		$vCheckCustomerID  = F_Check_CustomerID($PDestConn, $vCustomerID);
		$vCheckCouponID    = F_Check_CouponID($PDestConn, $vCouponID);
		
		if ($vCheckClientID == 0 || $vCheckSalesmanID == 0 || $vCheckCurrencyID == 0 || $vCheckProjectID == 0 || 
		    $vCheckCostCentID == 0 || $vCheckCustomerID == 0 || $vCheckCouponID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Client|Salesman|Currency|Project|CostCent|Customer|Coupon not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Retail',$vMessage);
			
			Return $vResult;
		}*/
		
		
		$sub_query  = " Select Count(*) From Retail ".
		              " Where Sale_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vSaleID = GetNextSequence1($PDestConn,'Retail_ID','');
			//echo $vSaleID; exit;
			$sub_query = " Insert Into Retail (Sale_ID, Sale_Reference, Sale_Date, Sale_Remark, Client_code, Salesman_Code, Currency_Code, Project_Code, ".
						 " Costcenter_code, CashRegister_Name, Sale_TotalQuantity, Sale_TotalQuantityRet, Sale_Taxable, Sale_TaxableBase1, ".
						 " Sale_TaxableBase2, Sale_NoneTaxable, Sale_NoneTaxableBase1, Sale_NoneTaxableBase2, Sale_DiscountAmount, ".
						 " Sale_DiscountBase1, Sale_DiscountBase2, Sale_DiscountPer, Sale_VAT, Sale_VATBase1, Sale_VATBase2, Sale_Total, ".
						 " Sale_TotalBase1, Sale_TotalBase2, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_Posted, Sale_Mode, ".
						 " Journal_Type, Sale_Tax1, Sale_Tax2, Sale_Tax3, Sale_Tax4, Sale_Tax5, Sale_Tax1Base1, Sale_Tax2Base1, ".
						 " Sale_Tax3Base1, Sale_Tax4Base1, Sale_Tax5Base1, Sale_Tax1Base2, Sale_Tax2Base2, Sale_Tax3Base2, Sale_Tax4Base2, ".
						 " Sale_Tax5Base2, Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, Sale_CreditCur, Sale_CreditAccount, ".
						 " Sale_CashCur, Sale_CashAccount, Sale_Cash, Sale_CashBase1, Sale_CashBase2, Sale_CheckDate, Sale_CheckNo, Sale_Bank, ".
						 " Sale_BankBranch, Sales_CashInBase1, Sales_CashOutBase1, Sales_CashInBase2, Sales_CashOutBase2, Sales_TipsBase1, ".
						 " Coupon_amount, Coupon_amountbase1, Coupon_amountbase2, Coupon_id, Sale_information, Sale_ClientCur, Sale_CreditAccountVat, ".
						 " Sales_CreditAmount, Sales_CreditAmountBase1, Sales_CreditAmountBase2, Sales_creditacc, Sales_creditacccur, Login_CardNo, ".
						 " Sale_SupervisorCode, Customer_Code, User_Account, Owner_Branch, Destination_Branch, Sale_Syn_ID ) ".
						 " Values ( ".$vSaleID.", ".$vSaleReference.", ".$vSaleDate.", ".$vSaleRemark.", ".$vClientCode.", ".$vSalesmanCode.
						 ", ".$vCurrencyCode.", ".$vProjectCode.", ".$vCostcentCode.", ".$vCashRegisterName.", ".$vSaleTotalQuantity.
						 ", ".$vSaleTotalQuantityRet.", ".$vSaleTaxable.", ".$vSaleTaxableBase1.", ".$vSaleTaxableBase2.", ".$vSaleNoneTaxable.
						 ", ".$vSaleNoneTaxableBase1.", ".$vSaleNoneTaxableBase2.", ".$vSaleDiscountAmount.", ".$vSaleDiscountBase1.
						 ", ".$vSaleDiscountBase2.", ".$vSaleDiscountPer.", ".$vSaleVAT.", ".$vSaleVATBase1.", ".$vSaleVATBase2.", ".$vSaleTotal.
						 ", ".$vSaleTotalBase1.", ".$vSaleTotalBase2.", ".$vSaleNetTotal.", ".$vSaleNetTotalBase1.", ".$vSaleNetTotalBase2.
						 ", ".$vSalePosted.", ".$vSaleMode.", ".$vJournalType.", ".$vSaleTax1.", ".$vSaleTax2.", ".$vSaleTax3.", ".$vSaleTax4.
						 ", ".$vSaleTax5.", ".$vSaleTax1Base1.", ".$vSaleTax2Base1.", ".$vSaleTax3Base1.", ".$vSaleTax4Base1.", ".$vSaleTax5Base1.
						 ", ".$vSaleTax1Base2.", ".$vSaleTax2Base2.", ".$vSaleTax3Base2.", ".$vSaleTax4Base2.", ".$vSaleTax5Base2.
						 ", ".$vSaleAcctax1.", ".$vSaleAcctax2.", ".$vSaleAcctax3.", ".$vSaleAcctax4.", ".$vSaleAcctax5.
						 ", ".$vSaleCreditCur.", ".$vSaleCreditAccount.", ".$vSaleCashCur.", ".$vSaleCashAccount.", ".$vSaleCash.", ".$vSaleCashBase1.
						 ", ".$vSaleCashBase2.", ".$vSaleCheckDate.", ".$vSaleCheckNo.", ".$vSaleBank.", ".$vSaleBankBranch.", ".$vSalesCashInBase1.
						 ", ".$vSalesCashOutBase1.", ".$vSalesCashInBase2.", ".$vSalesCashOutBase2.", ".$vSalesTipsBase1.", ".$vCouponAmount.
						 ", ".$vCouponAmountBase1.", ".$vCouponAmountBase2.", ".$vCouponID.", ".$vSaleInformation.", ".$vSaleClientCur.
						 ", ".$vSaleCreditAccountVat.", ".$vSalesCreditAmount.", ".$vSalesCreditAmountBase1.", ".$vSalesCreditAmountBase2.
						 ", ".$vSalesCreditAcc.", ".$vSalesCreditacccur.", ".$vLoginCardNo.", ".$vSaleSupervisorCode.", ".$vCustomerCode.
						 ", ".$vUserAccount.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vSaleSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select Sale_ID From Retail ".
					  " Where Sale_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vSaleID = $result[0];
			
			$sub_query = "  Update Retail Set Sale_Date = ".$vSaleDate.", Sale_Remark = ".$vSaleRemark.", Client_code = ".$vClientCode.
						 ", Salesman_Code = ".$vSalesmanCode.",	Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.
						 ", Costcenter_code = ".$vCostcentCode.", CashRegister_Name = ".$vCashRegisterName.", Sale_TotalQuantity = ".$vSaleTotalQuantity.
						 ",	Sale_TotalQuantityRet = ".$vSaleTotalQuantityRet.", Sale_Taxable = ".$vSaleTaxable. 
						 ",	Sale_TaxableBase1 = ".$vSaleTaxableBase1.", Sale_TaxableBase2 = ".$vSaleTaxableBase2. 
						 ",	Sale_NoneTaxable = ".$vSaleNoneTaxable.", Sale_NoneTaxableBase1 = ".$vSaleNoneTaxableBase1. 
						 ", Sale_NoneTaxableBase2 = ".$vSaleNoneTaxableBase2.", Sale_DiscountAmount = ".$vSaleDiscountAmount. 
						 ",	Sale_DiscountBase1 = ".$vSaleDiscountBase1.", Sale_DiscountBase2 = ".$vSaleDiscountBase2. 
						 ",	Sale_DiscountPer = ".$vSaleDiscountPer.", Sale_VAT = ".$vSaleVAT.", Sale_VATBase1 = ".$vSaleVATBase1. 
						 ",	Sale_VATBase2 = ".$vSaleVATBase2.", Sale_Total = ".$vSaleTotal.", Sale_TotalBase1 = ".$vSaleTotalBase1. 
						 ",	Sale_TotalBase2 = ".$vSaleTotalBase2.",	Sale_NetTotal = ".$vSaleNetTotal.",	Sale_NetTotalBase1 = ".$vSaleNetTotalBase1.
						 ",	Sale_NetTotalBase2 = ".$vSaleNetTotalBase2.", Sale_Posted = ".$vSalePosted. ", Sale_Mode = ".$vSaleMode. 
						 ",	Journal_Type = ".$vJournalType.", Sale_Tax1 = ".$vSaleTax1.", Sale_Tax1Base1 = ".$vSaleTax1Base1. 
						 ",	Sale_Tax1Base2 = ".$vSaleTax1Base2.", Sale_Tax2 = ".$vSaleTax2.", Sale_Tax2Base1 = ".$vSaleTax2Base1. 
						 ",	Sale_Tax2Base2 = ".$vSaleTax2Base2.", Sale_Tax3 = ".$vSaleTax3.", Sale_Tax3Base1 = ".$vSaleTax3Base1. 
						 ",	Sale_Tax3Base2 = ".$vSaleTax3Base2.", Sale_Tax4 = ".$vSaleTax3.", Sale_Tax4Base1 = ".$vSaleTax4Base1. 
						 ",	Sale_Tax4Base2 = ".$vSaleTax4Base2.", Sale_Tax5 = ".$vSaleTax5.", Sale_Tax5Base1 = ".$vSaleTax5Base1. 
						 ", Sale_Tax5Base2 = ".$vSaleTax5Base2.", Sale_Acctax1 = ".$vSaleAcctax1.", Sale_Acctax2 = ".$vSaleAcctax2. 
						 ",	Sale_Acctax3 = ".$vSaleAcctax3.", Sale_Acctax4 = ".$vSaleAcctax4.", Sale_Acctax5 = ".$vSaleAcctax5. 
						 ",	Sale_CreditCur = ".$vSaleCreditCur.", Sale_CreditAccount = ".$vSaleCreditAccount.", Sale_CashCur = ".$vSaleCashCur.
						 ",	Sale_CashAccount = ".$vSaleCashAccount.", Sale_Cash = ".$vSaleCash.", Sale_CashBase1 = ".$vSaleCashBase1.
						 ", Sale_CashBase2 = ".$vSaleCashBase2.", Sale_CheckDate = ".$vSaleCheckDate.", Sale_CheckNo = ".$vSaleCheckNo. 
						 ",	Sale_Bank = ".$vSaleBank.",	Sale_BankBranch = ".$vSaleBankBranch.",	Sales_CashInBase1 = ".$vSalesCashInBase1.
						 ", Sales_CashOutBase1 = ".$vSalesCashOutBase1.", Sales_CashInBase2 = ".$vSalesCashInBase2.
						 ",	Sales_CashOutBase2 = ".$vSalesCashOutBase2.", Sales_TipsBase1 = ".$vSalesTipsBase1.
						 ", Coupon_amount = ".$vCouponAmount.", Coupon_amountbase1 = ".$vCouponAmountBase1.
						 ", Coupon_amountbase2 = ".$vCouponAmountBase2.", Coupon_id = ".$vCouponID.
						 ", Sale_information = ".$vSaleInformation.", Sale_ClientCur = ".$vSaleClientCur.
						 ", Sale_CreditAccountVat = ".$vSaleCreditAccountVat.", Sales_CreditAmount = ".$vSalesCreditAmount.
						 ", Sales_CreditAmountBase1 = ".$vSalesCreditAmountBase1.", Sales_CreditAmountBase2 = ".$vSalesCreditAmountBase2.
						 ", Sales_creditacc = ".$vSalesCreditAcc.", Sales_creditacccur = ".$vSalesCreditacccur.
						 ", Login_CardNo = ".$vLoginCardNo.", Sale_SupervisorCode = ".$vSaleSupervisorCode.
						 ", Customer_Code = ".$vCustomerCode.", Destination_Branch = ".$vDestinationBranch.
						 "  Where Sale_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			//Update Coupon Amount
			$vResult = F_SynchroCoupon('COUPON', $vCouponID, 'U', $PBranchCode, 1, $PLocConn, $PDestConn);
			
			If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Retail Set Sale_Syn_ID = ".$vSaleID.
							 " Where Sale_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}
			
			//InCase Update, Delete All Related Details In RetailDt, PurchasesSerialNo
			If ($vRecordExists > 0) {
				$query = " Select RelatedSerial_Id, Journal_Type ".
						 " From PurchasesSerialNo ".
						 " Where RetailDt_ID In ( Select SaleDt_ID From RetailDt Where Sale_ID = '".$vSaleID."' ) ".
					     " And Journal_Type In ('DI','DR') ".
						 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
				//echo $query; exit;		 
				$result=mysql_query($query,$PDestConn);
				while($rows=mysql_fetch_assoc($result)){		 
					$vRelatedSerialID = $rows['RelatedSerial_Id'];
					$vSerJournalType  = $rows['Journal_Type'];
					
					$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
					if($vSerJournalType == 'DR')
						$sub_query = $sub_query.", flagunique = 0 ";
									
					$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
					$sub_result=mysql_query($sub_query,$PDestConn);
				}
				
				$query = "Delete From PurchasesSerialNo Where RetailDt_ID In (Select SaleDt_ID From RetailDt Where Sale_ID = '".$vSaleID."' ) And Journal_Type In ('DI','DR') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From RetailDt Where Sale_ID = '".$vSaleID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
	
    		//Insert Related Details From RetailDt
			$query = " Select SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, ".
					 " Warehouse_Code, Item_code, Item_Barcode, Item_CodePacked, SaleDt_Quantity, SaleDt_QuantityReturn, SaleDt_Price, ".
					 " SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, ".
					 " Item_Vat, SaleDt_PriceVat, SaleDt_PriceTTC, Saledt_priceTTCBase1, Saledt_priceTTCBase2, Saledt_DirectStkDbt, ".
					 " Saledt_DirectStkCrd, Saledt_DirectStkCur, Saledt_ItemAccount, SaleDt_DiscountAcc, SaleDt_PromoAcc, Item_Tax1, Item_Tax2, ".
					 " Item_Tax3, Item_Tax4, Item_Tax5, SaleDt_ExpireDate, RelatedDt_Id, SaleDt_Posted, Vendor_Code, Slip_number, Price_offer, ".
					 " SerialNo_Code, Customer_code, SaleDt_Syn_ID, Sale_Syn_ID, SaleDt_ActualPrice ".
					 " From RetailDt ".
					 " Where Sale_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error($PLocConn));
			while($rows=mysql_fetch_assoc($result)){
				$vSaleDtID = GetNextSequence1($PDestConn,'RetailDt_ID','');
				
				/*$vWarehouseID  = GetSQLValueString($rows['Warehouse_Id'],'int');
				$vItemID       = GetSQLValueString($rows['Item_Id'],'int');
				$vVendorID     = GetSQLValueString($rows['Vendor_Id'],'int');
				$vCheckWarehouseID  = F_Check_WarehouseID($PDestConn, $vWarehouseID);
				$vCheckItemID       = F_Check_ItemID($PDestConn, $vItemID);
				$vCheckVendorID     = F_Check_VendorID($PDestConn, $vVendorID);
				
				if ($vCheckWarehouseID == 0 || $vCheckItemID == 0 || $vCheckVendorID == 0 ) {
					$vResult  = 'P';
					$vMessage = 'Warehouse|Item|Vendor not found.';
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SaleDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'RetailDt',$vMessage);
					
					break;
				}*/
				
				$sub_query = " Insert Into RetailDt (SaleDt_id, Sale_id, Currency_Code, Sale_Date, Client_Code, Journal_Type, Project_Code, CostCenter_Code, ".
							 " Warehouse_Code, Item_code, Item_Barcode, Item_CodePacked, SaleDt_Quantity, SaleDt_QuantityReturn, SaleDt_Price, ".
							 " SaleDt_PriceBase1, SaleDt_PriceBase2, SaleDt_DiscountPer, SaleDt_DiscountAmount, SaleDt_DiscountBase1, SaleDt_DiscountBase2, ".
							 " Item_Vat, SaleDt_PriceVat, SaleDt_PriceTTC, Saledt_priceTTCBase1, Saledt_priceTTCBase2, Saledt_DirectStkDbt, ".
							 " Saledt_DirectStkCrd, Saledt_DirectStkCur, Saledt_ItemAccount, SaleDt_DiscountAcc, SaleDt_PromoAcc, Item_Tax1, Item_Tax2, ".
							 " Item_Tax3, Item_Tax4, Item_Tax5, SaleDt_ExpireDate, RelatedDt_Id, SaleDt_Posted, Vendor_Code, Slip_number, Price_offer, ".
							 " SerialNo_Code, Customer_code, SaleDt_Syn_ID, Sale_Syn_ID, SaleDt_ActualPrice ) ".
							 " Values ( ".$vSaleDtID.", ".$vSaleID.", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Sale_Date'],'date').
							 ", ".GetSQLValueString($rows['Client_Code'],'text').", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['Project_Code'],'text').
							 ", ".GetSQLValueString($rows['CostCenter_Code'],'text').", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['Item_code'],'text').
							 ", ".GetSQLValueString($rows['Item_Barcode'],'text').", ".GetSQLValueString($rows['Item_CodePacked'],'text').
							 ", ".GetSQLValueString($rows['SaleDt_Quantity'],'double').", ".GetSQLValueString($rows['SaleDt_QuantityReturn'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_Price'],'double').", ".GetSQLValueString($rows['SaleDt_PriceBase1'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_PriceBase2'],'double').", ".GetSQLValueString($rows['SaleDt_DiscountPer'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_DiscountAmount'],'double').", ".GetSQLValueString($rows['SaleDt_DiscountBase1'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_DiscountBase2'],'double').", ".GetSQLValueString($rows['Item_Vat'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_PriceVat'],'double').", ".GetSQLValueString($rows['SaleDt_PriceTTC'],'double').
							 ", ".GetSQLValueString($rows['Saledt_priceTTCBase1'],'double').", ".GetSQLValueString($rows['Saledt_priceTTCBase2'],'double').
							 ", ".GetSQLValueString($rows['Saledt_DirectStkDbt'],'text').", ".GetSQLValueString($rows['Saledt_DirectStkCrd'],'text').
							 ", ".GetSQLValueString($rows['Saledt_DirectStkCur'],'text').", ".GetSQLValueString($rows['Saledt_ItemAccount'],'text').
							 ", ".GetSQLValueString($rows['SaleDt_DiscountAcc'],'text').", ".GetSQLValueString($rows['SaleDt_PromoAcc'],'text').
							 ", ".GetSQLValueString($rows['Item_Tax1'],'double').", ".GetSQLValueString($rows['Item_Tax2'],'double').", ".GetSQLValueString($rows['Item_Tax3'],'double').
							 ", ".GetSQLValueString($rows['Item_Tax4'],'double').", ".GetSQLValueString($rows['Item_Tax5'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_ExpireDate'],'date').", ".GetSQLValueString($rows['RelatedDt_Id'],'double').
							 ", ".GetSQLValueString($rows['SaleDt_Posted'],'int').", ".GetSQLValueString($rows['Vendor_Code'],'text').
							 ", ".GetSQLValueString($rows['Slip_number'],'text').", ".GetSQLValueString($rows['Price_offer'],'int').
							 ", ".GetSQLValueString($rows['SerialNo_Code'],'text').", ".GetSQLValueString($rows['Customer_code'],'text').
							 ", ".GetSQLValueString($rows['SaleDt_id'],'int').", ".$vSaleSynID.", ".GetSQLValueString($rows['SaleDt_ActualPrice'],'double')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
					
					//InCase Insert RetailDt Done, Then Inserts Related Serials
					$query1 = " Select Serial_ID, Journal_Type, RetailDt_ID, DeliveryDt_ID, SaleDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, SerialNo_Used, ".
					          " RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, Item_ExpireDate, Item_BatchNo ".
							  " From PurchasesSerialNo ".
							  " Where RetailDt_ID = '".$rows['SaleDt_id']."' ".
							  " And Journal_Type In ('DI','DR') ";
					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error($PLocConn));
					while($rows1=mysql_fetch_assoc($result1)){
						$vSerialID = GetNextSequence1($PDestConn,'Serial_ID','');
						$vRelatedSerialID = F_Get_SerialRelatedID($PDestConn, $rows1['RelatedSerial_Id']);
						
						$sub_query1 = " Insert Into PurchasesSerialNo (Serial_ID, Journal_Type, RetailDt_ID, PurchaseDt_id, Item_Code, SerialNo_Code, ".
									  " SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, flagunique, Warehouse_code, ".
									  " Serial_Syn_ID, Item_ExpireDate, Item_BatchNo) ".
									  " Values ( ".$vSerialID.", ".GetSQLValueString($rows1['Journal_Type'],'text').", ".$vSaleDtID.", ".$vSaleDtID.
									  ", ".GetSQLValueString($rows1['Item_Code'],'text').", ".GetSQLValueString($rows1['SerialNo_Code'],'text').
									  ", ".GetSQLValueString($rows1['SerialNo_Used'],'int').", ".$vRelatedSerialID.", ".GetSQLValueString($rows1['SerialNo_Quantity'],'double').
									  ", ".GetSQLValueString($rows1['SerialNo_QuantitySold'],'double').", ".GetSQLValueString($rows1['flagunique'],'double').
									  ", ".GetSQLValueString($rows1['Warehouse_code'],'text').", ".GetSQLValueString($rows1['Serial_ID'],'int').
									  ", ".GetSQLValueString($rows1['Item_ExpireDate'],'text').", ".GetSQLValueString($rows1['Item_BatchNo'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							if ($vRelatedSerialID != '' && $vRelatedSerialID != 'Null') {
								$sub_query2 = " Update PurchasesSerialNo Set SerialNo_Used = 1 ";
								if($rows1['Journal_Type'] == 'DR')
									$sub_query2 = $sub_query2.", flagunique = Serial_ID ";
									
								$sub_query2 = $sub_query2." Where Serial_ID = ".$vRelatedSerialID;	
								$sub_result2=mysql_query($sub_query2,$PDestConn);
							}	
						}
						else {
							$vResult  = 'P';
							$vMessage = mysql_error($PDestConn);
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Serial_ID']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A SerialNo Then Exit Loop Of RetailDt
					if ($vResult == 'P') break;
				
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error($PDestConn);
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SaleDt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'RetailDt',$vMessage);
					
					break;
				}
			}
			
			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Retail Set Journal_ID = '".$vJournalID."' ".
							  " Where Sale_ID = '".$vSaleID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}

		} else {
			$vResult  = 'P';
			$vMessage = mysql_error($PDestConn);
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Retail',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, Sale_ID, Owner_Branch ".
					 " From Retail Where Sale_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vJournalType = $sub_result[1];
		$vSaleID 	  = $sub_result[2];
		$vOwnerBranch = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Select RelatedSerial_Id, Journal_Type ".
				 " From PurchasesSerialNo ".
				 " Where RetailDt_ID In ( Select SaleDt_ID From RetailDt Where Sale_ID = '".$vSaleID."' ) ".
			     " And Journal_Type In ('DI','DR') ".
				 " And RelatedSerial_Id Is Not Null And RelatedSerial_Id != '' ";
		//echo $query; exit;		 
		$result=mysql_query($query,$PDestConn);
		while($rows=mysql_fetch_assoc($result)){		 
			$vRelatedSerialID = $rows['RelatedSerial_Id'];
			$vSerJournalType  = $rows['Journal_Type'];
				
			$sub_query = " Update PurchasesSerialNo Set SerialNo_Used = 0 ";
			if($vSerJournalType == 'DR')
				$sub_query = $sub_query.", flagunique = 0 ";
									
			$sub_query = $sub_query." Where Serial_ID = ".$vRelatedSerialID;	
			$sub_result=mysql_query($sub_query,$PDestConn);
		}
				
		$query = "Delete From PurchasesSerialNo Where RetailDt_ID In (Select SaleDt_ID From RetailDt Where Sale_ID = '".$vSaleID."' ) And Journal_Type In ('DI','DR') ";
		$result = mysql_query($query, $PDestConn);
		
		if ($result) {
			$query = "Delete From RetailDt Where Sale_ID = '".$vSaleID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Retail Where Sale_ID = '".$vSaleID."'";
				$result = mysql_query($query, $PDestConn);
				
				if ($vJournalID != -1) {
					$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
					$result = mysql_query($query, $PDestConn);
				}	
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error($PDestConn);
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'RetailDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error($PDestConn);
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesSerialNo',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vSaleID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroRelatedJv($PRecordID, $PState, $PLocConn, $PDestConn) {

	If (($PState == 'I' || $PState == 'U') && $PRecordID != '' && $PRecordID != 'Null') {
		$query = " Select journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
				 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
				 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
				 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup ".
				 " From Journal ".
				 " Where Journal_ID	= '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vJournalSynID		 = GetSQLValueString($rows['journal_id'],'int');
		$vJournalReference	 = GetSQLValueString($rows['journal_refgovernment'],'double');
		$vJournalFolio	 	 = GetSQLValueString($rows['journal_folio'],'double');
		$vJournalType        = GetSQLValueString($rows['journal_type'],'text');
		$vJournalTypeRef	 = GetSQLValueString($rows['Journal_typeref'],'text');
		$vJournalDate		 = GetSQLValueString($rows['Journal_Date'],'date');
		$vJournalSysDate     = GetSQLValueString($rows['Journal_SysDate'],'date');
		$vJournalTime		 = GetSQLValueString($rows['Journal_Time'],'date');
		$vAmnt1db		 	 = GetSQLValueString($rows['Amnt1_db'],'double');
		$vAmnt1cd		 	 = GetSQLValueString($rows['Amnt1_cd'],'double');
		$vAmnt2db		 	 = GetSQLValueString($rows['Amnt2_db'],'double');
		$vAmnt2cd		 	 = GetSQLValueString($rows['Amnt2_cd'],'double');
		$vJournalFlag		 = GetSQLValueString($rows['journal_flag'],'text');
		$vJournaldtincr		 = GetSQLValueString($rows['Journal_dtincr'],'double');
		$vJournalEdit 		 = GetSQLValueString($rows['Journal_Edit'],'int');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_Code'],'text');
		$vJournalRemark		 = GetSQLValueString($rows['Journal_Remark'],'text');
		$vJournalPosted		 = GetSQLValueString($rows['Journal_posted'],'int');
		$vUserAccount		 = GetSQLValueString($rows['User_account'],'text');
		$vUserName			 = GetSQLValueString($rows['User_Name'],'text');
		$vJournalConfirmed	 = GetSQLValueString($rows['Journal_Confirmed'],'int');
		$vConfirmedUser		 = GetSQLValueString($rows['Journal_ConfirmedUser'],'text');
		$vJournalManualNo	 = GetSQLValueString($rows['Manual_no'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['journal_belongstogroup'],'int');
		
		$sub_query  = " Select Count(*) From Journal ".
		              " Where Journal_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vJournalID = GetNextSequence1($PDestConn,'Journal_ID','');
			
			$sub_query = " Insert Into Journal (journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
						 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
						 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
						 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup, ".
						 " Journal_Syn_ID) ".
						 " Values ( ".$vJournalID.", ".$vJournalReference.", ".$vJournalFolio.", ".$vJournalType.", ".$vJournalTypeRef.
						 ", ".$vJournalDate.", ".$vJournalSysDate.", ".$vJournalTime.", ".$vAmnt1db.", ".$vAmnt1cd.", ".$vAmnt2db.", ".$vAmnt2cd.
						 ", ".$vJournalFlag.", ".$vJournaldtincr.", ".$vJournalEdit.", ".$vProjectCode.", ".$vCostcentCode.", ".$vJournalRemark.
						 ", ".$vJournalPosted.", ".$vUserAccount.", ".$vUserName.", ".$vJournalConfirmed.", ".$vConfirmedUser.
						 ", ".$vJournalManualNo.", ".$vBelongsToGroup.", ".$vJournalSynID." ) ";
		}	
		else {
			$query  = " Select Journal_ID From Journal ".
					  " Where Journal_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vJournalID = $result[0];
		
			$sub_query = "  Update Journal Set journal_refgovernment = ".$vJournalReference.", journal_folio = ".$vJournalFolio. 
						 ",	journal_type = ".$vJournalType.", Journal_typeref = ".$vJournalTypeRef.", Journal_Date = ".$vJournalDate. 
						 ",	Journal_SysDate = ".$vJournalSysDate.", Journal_Time = ".$vJournalTime.", Amnt1_db = ".$vAmnt1db. 
						 ",	Amnt1_cd = ".$vAmnt1cd.", Amnt2_db = ".$vAmnt2db.", Amnt2_cd = ".$vAmnt2cd. 
						 ",	journal_flag = ".$vJournalFlag.", Journal_dtincr = ".$vJournaldtincr.", Journal_Edit = ".$vJournalEdit. 
						 ",	Project_Code = ".$vProjectCode.", Costcent_Code = ".$vCostcentCode.", Journal_Remark = ".$vJournalRemark.
						 ", Journal_posted = ".$vJournalPosted.", User_account = ".$vUserAccount.", User_Name = ".$vUserName. 
						 ", Journal_Confirmed = ".$vJournalConfirmed.", Journal_ConfirmedUser = ".$vConfirmedUser. 
						 ", Manual_no = ".$vJournalManualNo.", journal_belongstogroup = ".$vBelongsToGroup.
						 "  Where Journal_Syn_ID = '".$PRecordID."'";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
		
			If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Journal Set Journal_Syn_ID = ".$vJournalID.
							 " Where Journal_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}
			
			//InCase Update, Delete All Related Details In JournalDt, CstJour
			If ($vRecordExists > 0) {
				$query = "Delete From JournalDt Where Journal_ID = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			
			$dtincr = 0;
			
			//Insert Related Details From JournalDt
			$query = " Select journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
					 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
					 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
					 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code ".
					 " From JournalDt ".
					 " Where Journal_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vJournalDtID = GetNextSequence1($PDestConn,'JournalDt_ID','');
				
				$dtincr += 1;
				$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
				$vJournalDtID = $vJournalID.''.$dtincr_pad;
				
				$sub_query = " Insert Into JournalDt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
							 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
							 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
							 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code ) ".
							 " Values ( ".$vJournalDtID.", ".$vJournalID.", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['Document'],'text').
							 ", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Journaldt_DBCD'],'text').
							 ", ".GetSQLValueString($rows['Journaldt_dbcdAra'],'text').", ".GetSQLValueString($rows['Journaldt_Desc'],'text').
							 ", ".GetSQLValueString($rows['journaldt_desc1'],'text').", ".GetSQLValueString($rows['Journal_date'],'date').
							 ", ".GetSQLValueString($rows['Journaldt_valuedate'],'date').", ".GetSQLValueString($rows['Journal_BelongsToGroup'],'int').
							 ", ".GetSQLValueString($rows['manual_no'],'text').", ".GetSQLValueString($rows['Journaldt_Amount'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_Amount1'],'double').", ".GetSQLValueString($rows['Journaldt_Amount2'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_posted'],'int').", ".GetSQLValueString($rows['Journaldt_reconciled'],'int').
							 ", ".GetSQLValueString($rows['Journaldt_reconciledref'],'text').", ".GetSQLValueString($rows['Reconciliation_date'],'date').
							 ", ".GetSQLValueString($rows['Reconciliation_Sysdate'],'date').", ".GetSQLValueString($rows['Journal_JVRef'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_JVMode'],'text').", ".GetSQLValueString($rows['Detail_Code'],'text')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {	
					$vResult = 'T';
					
					//InCase Insert JournalDt Done, Then Inserts Related CstJour
					$query1 = " Select Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
                              " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ".
					          " From CstJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						
						$sub_query1 = " Insert Into CstJour (Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
									  " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Costcent_code'],'text').", ".GetSQLValueString($rows1['project_code'],'text').
									  ", ".GetSQLValueString($rows1['Cstjour_amount'],'double').", ".GetSQLValueString($rows1['Cstjour_amount1'],'double').
									  ", ".GetSQLValueString($rows1['Cstjour_amount2'],'double').", ".GetSQLValueString($rows1['Cstjour_prcnt'],'double').
									  ", ".GetSQLValueString($rows1['CstJour_Posted'],'int').", ".GetSQLValueString($rows1['Journal_JVRef'],'double')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'CstJour',$vMessage);
							
							//break;
						}
						
					}
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['journaldt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'JournalDt',$vMessage);
					
					break;
				}		
			}	
			
			$query_update_dtincr="update journal set Journal_dtincr=$dtincr where journal_id=".$vJournalID;
			$result_dtincr=mysql_query($query_update_dtincr,$PDestConn);
		
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Journal',$vMessage);
		}
		
	}

	Return $vJournalID;	
}

function F_SynchroJournal($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
				 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
				 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
				 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup, ".
				 " Owner_Branch, Destination_Branch ".
				 " From Journal ".
				 " Where Journal_ID	= '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vJournalSynID		 = GetSQLValueString($rows['journal_id'],'int');
		$vJournalReference	 = GetSQLValueString($rows['journal_refgovernment'],'double');
		$vJournalFolio	 	 = GetSQLValueString($rows['journal_folio'],'double');
		$vJournalType        = GetSQLValueString($rows['journal_type'],'text');
		$vJournalTypeRef	 = GetSQLValueString($rows['Journal_typeref'],'text');
		$vJournalDate		 = GetSQLValueString($rows['Journal_Date'],'date');
		$vJournalSysDate     = GetSQLValueString($rows['Journal_SysDate'],'date');
		$vJournalTime		 = GetSQLValueString($rows['Journal_Time'],'date');
		$vAmnt1db		 	 = GetSQLValueString($rows['Amnt1_db'],'double');
		$vAmnt1cd		 	 = GetSQLValueString($rows['Amnt1_cd'],'double');
		$vAmnt2db		 	 = GetSQLValueString($rows['Amnt2_db'],'double');
		$vAmnt2cd		 	 = GetSQLValueString($rows['Amnt2_cd'],'double');
		$vJournalFlag		 = GetSQLValueString($rows['journal_flag'],'text');
		$vJournaldtincr		 = GetSQLValueString($rows['Journal_dtincr'],'double');
		$vJournalEdit 		 = GetSQLValueString($rows['Journal_Edit'],'int');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_Code'],'text');
		$vJournalRemark		 = GetSQLValueString($rows['Journal_Remark'],'text');
		$vJournalPosted		 = GetSQLValueString($rows['Journal_posted'],'int');
		$vUserAccount		 = GetSQLValueString($rows['User_account'],'text');
		$vUserName			 = GetSQLValueString($rows['User_Name'],'text');
		$vJournalConfirmed	 = GetSQLValueString($rows['Journal_Confirmed'],'int');
		$vConfirmedUser		 = GetSQLValueString($rows['Journal_ConfirmedUser'],'text');
		$vJournalManualNo	 = GetSQLValueString($rows['Manual_no'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['journal_belongstogroup'],'int');
		$vOwnerBranch 		 = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch  = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$sub_query  = " Select Count(*) From Journal ".
		              " Where Journal_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vJournalID = GetNextSequence1($PDestConn,'Journal_ID','');
			
			$sub_query = " Insert Into Journal (journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
						 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
						 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
						 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup, ".
						 " Owner_Branch, Destination_Branch, Journal_Syn_ID) ".
						 " Values ( ".$vJournalID.", ".$vJournalReference.", ".$vJournalFolio.", ".$vJournalType.", ".$vJournalTypeRef.
						 ", ".$vJournalDate.", ".$vJournalSysDate.", ".$vJournalTime.", ".$vAmnt1db.", ".$vAmnt1cd.", ".$vAmnt2db.", ".$vAmnt2cd.
						 ", ".$vJournalFlag.", ".$vJournaldtincr.", ".$vJournalEdit.", ".$vProjectCode.", ".$vCostcentCode.", ".$vJournalRemark.
						 ", ".$vJournalPosted.", ".$vUserAccount.", ".$vUserName.", ".$vJournalConfirmed.", ".$vConfirmedUser.
						 ", ".$vJournalManualNo.", ".$vBelongsToGroup.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vJournalSynID." ) ";
		}	
		else {
			$query  = " Select Journal_ID From Journal ".
					  " Where Journal_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vJournalID = $result[0];
		
			$sub_query = "  Update Journal Set journal_refgovernment = ".$vJournalReference.", journal_folio = ".$vJournalFolio. 
						 ",	journal_type = ".$vJournalType.", Journal_typeref = ".$vJournalTypeRef.", Journal_Date = ".$vJournalDate. 
						 ",	Journal_SysDate = ".$vJournalSysDate.", Journal_Time = ".$vJournalTime.", Amnt1_db = ".$vAmnt1db. 
						 ",	Amnt1_cd = ".$vAmnt1cd.", Amnt2_db = ".$vAmnt2db.", Amnt2_cd = ".$vAmnt2cd. 
						 ",	journal_flag = ".$vJournalFlag.", Journal_dtincr = ".$vJournaldtincr.", Journal_Edit = ".$vJournalEdit. 
						 ",	Project_Code = ".$vProjectCode.", Costcent_Code = ".$vCostcentCode.", Journal_Remark = ".$vJournalRemark.
						 ", Journal_posted = ".$vJournalPosted.", User_account = ".$vUserAccount.", User_Name = ".$vUserName. 
						 ", Journal_Confirmed = ".$vJournalConfirmed.", Journal_ConfirmedUser = ".$vConfirmedUser. 
						 ", Manual_no = ".$vJournalManualNo.", journal_belongstogroup = ".$vBelongsToGroup.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where Journal_Syn_ID = '".$PRecordID."'";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
		
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Journal Set Journal_Syn_ID = ".$vJournalID.
							 " Where Journal_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In JournalDt, CstJour
			//If ($vRecordExists > 0) {
				$query = " Delete From Bills Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
						 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Delete From Checks Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
						 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Update Checks Set JournalDt_Id2 = Null ".
						 " Where JournalDt_Id2 In (Select JournalDt_ID From JournalDt Inner Join Ledger on Ledger.Ledger_Number = JournalDt.Ledger_Number ".
						 " Where Journal_ID = '".$vJournalID."' ".
						 " And ((Ledger.Ledger_Activity=1 and JournalDt_dbcd='C') or (Ledger.Ledger_Activity=2 and JournalDt_dbcd='D')) ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Update Bills Set JournalDt_Id2 = Null ".
						 " Where JournalDt_Id2 In (Select JournalDt_ID From JournalDt Inner Join Ledger on Ledger.Ledger_Number = JournalDt.Ledger_Number ".
						 " Where Journal_ID = '".$vJournalID."' ".
						 " And ((Ledger.Ledger_Activity=3 and JournalDt_dbcd='C') or (Ledger.Ledger_Activity=4 and JournalDt_dbcd='D')) ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From JournalDt Where Journal_ID = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			//}
			
			$dtincr = 0;
			
			//Insert Related Details From JournalDt
			$query = " Select journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
					 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
					 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
					 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code, ".
					 " JournalDt_Syn_ID, Journal_Syn_ID ".
					 " From JournalDt ".
					 " Where Journal_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vJournalDtID = GetNextSequence1($PDestConn,'JournalDt_ID','');
				
				$dtincr += 1;
				$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
				$vJournalDtID = $vJournalID.''.$dtincr_pad;
				
				
				$sub_query = " Insert Into JournalDt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
							 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
							 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
							 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code, JournalDt_Syn_ID, Journal_Syn_ID ) ".
							 " Values ( ".$vJournalDtID.", ".$vJournalID.", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['Document'],'text').
							 ", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Journaldt_DBCD'],'text').
							 ", ".GetSQLValueString($rows['Journaldt_dbcdAra'],'text').", ".GetSQLValueString($rows['Journaldt_Desc'],'text').
							 ", ".GetSQLValueString($rows['journaldt_desc1'],'text').", ".GetSQLValueString($rows['Journal_date'],'date').
							 ", ".GetSQLValueString($rows['Journaldt_valuedate'],'date').", ".GetSQLValueString($rows['Journal_BelongsToGroup'],'int').
							 ", ".GetSQLValueString($rows['manual_no'],'text').", ".GetSQLValueString($rows['Journaldt_Amount'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_Amount1'],'double').", ".GetSQLValueString($rows['Journaldt_Amount2'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_posted'],'int').", ".GetSQLValueString($rows['Journaldt_reconciled'],'int').
							 ", ".GetSQLValueString($rows['Journaldt_reconciledref'],'text').", ".GetSQLValueString($rows['Reconciliation_date'],'date').
							 ", ".GetSQLValueString($rows['Reconciliation_Sysdate'],'date').", ".GetSQLValueString($rows['Journal_JVRef'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_JVMode'],'text').", ".GetSQLValueString($rows['Detail_Code'],'text').
							 ", ".GetSQLValueString($rows['journaldt_id'],'double').", ".$vJournalSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {	
					$vResult = 'T';
					
					//InCase Insert JournalDt Done, Then Inserts Related CstJour
					$query1 = " Select Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
                              " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ".
					          " From CstJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						
						$sub_query1 = " Insert Into CstJour (Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
									  " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Costcent_code'],'text').", ".GetSQLValueString($rows1['project_code'],'text').
									  ", ".GetSQLValueString($rows1['Cstjour_amount'],'double').", ".GetSQLValueString($rows1['Cstjour_amount1'],'double').
									  ", ".GetSQLValueString($rows1['Cstjour_amount2'],'double').", ".GetSQLValueString($rows1['Cstjour_prcnt'],'double').
									  ", ".GetSQLValueString($rows1['CstJour_Posted'],'int').", ".GetSQLValueString($rows1['Journal_JVRef'],'double')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'CstJour',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A CstJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
					//InCase Insert JournalDt Done, Then Inserts Related ChkJour
					$query1 = " Select Journaldt_id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Currency_code, Chk_Amount, ".
                              " Chk_Amount1, Chk_Amount2, Chk_Type, Chk_bank_in, Chk_col_ret, ChkJour_Posted, Synchronized ".
					          " From ChkJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vCheckNo  	   = GetSQLValueString($rows1['Chk_Number'],'int');
						$vLedgerNo	   = GetSQLValueString($rows1['Ledger_Number'],'int');
						$vJournalDtId1 = GetSQLValueString($rows1['Journaldt_id'],'int');
						
						
						$sub_query1 = " Insert Into ChkJour (Journaldt_id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Currency_code, Chk_Amount, ".
									  " Chk_Amount1, Chk_Amount2, Chk_Type, Chk_bank_in, Chk_col_ret, ChkJour_Posted ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Ledger_Number'],'text').", ".GetSQLValueString($rows1['Chk_Number'],'text').
									  ", ".GetSQLValueString($rows1['Chk_Bank'],'text').", ".GetSQLValueString($rows1['Chk_ValueDate'],'date').
									  ", ".GetSQLValueString($rows1['Currency_code'],'text').", ".GetSQLValueString($rows1['Chk_Amount'],'double').
									  ", ".GetSQLValueString($rows1['Chk_Amount1'],'double').", ".GetSQLValueString($rows1['Chk_Amount2'],'double').
									  ", ".GetSQLValueString($rows1['Chk_Type'],'text').", ".GetSQLValueString($rows1['Chk_bank_in'],'text').
									  ", ".GetSQLValueString($rows1['Chk_col_ret'],'text').", ".GetSQLValueString($rows1['ChkJour_Posted'],'int')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							$vCheckID = F_SynchroRelatedChecks($vJournalDtId1, $vLedgerNo, $vCheckNo, $vJournalDtID, 'I', $PLocConn, $PDestConn);
						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'ChkJour',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A ChkJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
					//InCase Insert JournalDt Done, Then Inserts Related BillJour
					$query1 = " Select Journaldt_id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, ".
                              " Bill_Amount, Bill_Amount1, Bill_Amount2, Bill_type, Synchronized ".
					          " From BillJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vBillNo  	   = GetSQLValueString($rows1['Bill_Number'],'int');
						$vLedgerNo	   = GetSQLValueString($rows1['Ledger_Number'],'int');
						$vJournalDtId1 = GetSQLValueString($rows1['Journaldt_id'],'int');
												
						$sub_query1 = " Insert Into BillJour (Journaldt_id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, ".
									  " Bill_Amount, Bill_Amount1, Bill_Amount2, Bill_type ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Ledger_Number'],'text').", ".GetSQLValueString($rows1['Bill_Number'],'text').
									  ", ".GetSQLValueString($rows1['Bill_Bank'],'text').", ".GetSQLValueString($rows1['Bill_ValueDate'],'date').
									  ", ".GetSQLValueString($rows1['Currency_Code'],'text').", ".GetSQLValueString($rows1['Bill_Amount'],'double').
									  ", ".GetSQLValueString($rows1['Bill_Amount1'],'double').", ".GetSQLValueString($rows1['Bill_Amount2'],'double').
									  ", ".GetSQLValueString($rows1['Bill_type'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							$vBillID = F_SynchroRelatedBills($vJournalDtId1, $vLedgerNo, $vBillNo, $vJournalDtID, 'I', $PLocConn, $PDestConn);
						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'BillJour',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A BillJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['journaldt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'JournalDt',$vMessage);
					
					break;
				}		
			}	
		
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Journal',$vMessage);
		}
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Owner_Branch ".
					 " From Journal Where Journal_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query = " Delete From Bills Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
				 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
		$result = mysql_query($query, $PDestConn);
				
		$query = " Delete From Checks Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
				 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$query = "Delete From JournalDt Where Journal_ID = '".$vJournalID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($result) {
				$vResult  = 'T';
			
				$query = "Delete From Journal Where Journal_ID = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'JournalDt',$vMessage);
			}
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Checks/Bills',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vJournalID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroPaymentRequest($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select PaymentRqst_ID, PaymentRqst_Refgovernment, PaymentRqst_Date, PaymentRqst_Name, PaymentRqst_Remark, ".
				 " PaymentRqst_Amount, PaymentRqst_Amount1, PaymentRqst_Amount2, PaymentRqst_Mode, Ledger_Number, PaymentRqst_Desc, ".
				 " Currency_Code, Project_Code, Costcent_code, PaymentRqst_Edit, PaymentRqst_Posted, PaymentRqst_Vat, PaymentRqst_ValueDate, ".
				 " PaymentRqst_dtincr, PaymentRqst_Used, PaymentRqst_AmountC1, PaymentRqst_AmountC2, PaymentRqst_AmountD1, PaymentRqst_AmountD2, ".
				 " PaymentRqst_BelongsToGrp, Synchronized, PaymentRqst_AmntModified, PaymentRqst_manualno, paymentrqst_include, PaymentRqst_App, ".
				 " PaymentRqst_Confirmed, Touser_account, User_Confirmed, Owner_Branch, Destination_Branch  ".
				 " From PaymentRqst ".
				 " Where PaymentRqst_ID	= '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vPaymentRqstSynID	  = GetSQLValueString($rows['PaymentRqst_ID'],'int');
		$vPaymentRqstRef	  = GetSQLValueString($rows['PaymentRqst_Refgovernment'],'double');
		$vPaymentRqstDate	  = GetSQLValueString($rows['PaymentRqst_Date'],'date');
		$vPaymentRqstName     = GetSQLValueString($rows['PaymentRqst_Name'],'text');
		$vPaymentRqstRemark	  = GetSQLValueString($rows['PaymentRqst_Remark'],'text');
		$vPaymentRqstAmount   = GetSQLValueString($rows['PaymentRqst_Amount'],'double');
		$vPaymentRqstAmount1  = GetSQLValueString($rows['PaymentRqst_Amount1'],'double');
		$vPaymentRqstAmount2  = GetSQLValueString($rows['PaymentRqst_Amount2'],'double');
		$vPaymentRqstMode	  = GetSQLValueString($rows['PaymentRqst_Mode'],'double');
		$vLedgerNumber 		  = GetSQLValueString($rows['Ledger_Number'],'text');
		$vPaymentRqstDesc	  = GetSQLValueString($rows['PaymentRqst_Desc'],'text');
		$vCurrencyCode		  = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		  = GetSQLValueString($rows['Costcent_code'],'text');
		$vPaymentRqstEdit	  = GetSQLValueString($rows['PaymentRqst_Edit'],'int');
		$vPaymentRqstPosted	  = GetSQLValueString($rows['PaymentRqst_Posted'],'int');
		$vPaymentRqstVat	  = GetSQLValueString($rows['PaymentRqst_Vat'],'int');
		$vValueDate			  = GetSQLValueString($rows['PaymentRqst_ValueDate'],'date');
		$vPaymentRqstdtincr	  = GetSQLValueString($rows['PaymentRqst_dtincr'],'double');
		$vPaymentRqstUsed	  = GetSQLValueString($rows['PaymentRqst_Used'],'int');
		$vPaymentRqstAmountC1 = GetSQLValueString($rows['PaymentRqst_AmountC1'],'double');
		$vPaymentRqstAmountC2 = GetSQLValueString($rows['PaymentRqst_AmountC2'],'double');
		$vPaymentRqstAmountD1 = GetSQLValueString($rows['PaymentRqst_AmountD1'],'double');
		$vPaymentRqstAmountD2 = GetSQLValueString($rows['PaymentRqst_AmountD2'],'double');
		$vBelongsToGroup	  = GetSQLValueString($rows['PaymentRqst_BelongsToGrp'],'int');
		$vSynchronized		  = GetSQLValueString($rows['Synchronized'],'int');
		$vAmntModified		  = GetSQLValueString($rows['PaymentRqst_AmntModified'],'double');
		$vManualNo			  = GetSQLValueString($rows['PaymentRqst_manualno'],'text');
		$vPaymentRqstInclude  = GetSQLValueString($rows['paymentrqst_include'],'int');
		$vPaymentRqstApp	  = GetSQLValueString($rows['PaymentRqst_App'],'int');
		$vConfirmed		  	  = GetSQLValueString($rows['PaymentRqst_Confirmed'],'int');
		$vUserAccount		  = GetSQLValueString($rows['Touser_account'],'text');
		$vUserConfirmed		  = GetSQLValueString($rows['User_Confirmed'],'text');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch   = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		
		$sub_query  = " Select Count(*) From PaymentRqst ".
		              " Where PaymentRqst_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vPaymentRqstID = GetNextSequence1($PDestConn,'PaymentRqst_ID','');
			
			$sub_query = " Insert Into PaymentRqst (PaymentRqst_ID, PaymentRqst_Refgovernment, PaymentRqst_Date, PaymentRqst_Name, PaymentRqst_Remark, ".
						 " PaymentRqst_Amount, PaymentRqst_Amount1, PaymentRqst_Amount2, PaymentRqst_Mode, Ledger_Number, PaymentRqst_Desc, ".
						 " Currency_Code, Project_Code, Costcent_code, PaymentRqst_Edit, PaymentRqst_Posted, PaymentRqst_Vat, PaymentRqst_ValueDate, ".
						 " PaymentRqst_dtincr, PaymentRqst_Used, PaymentRqst_AmountC1, PaymentRqst_AmountC2, PaymentRqst_AmountD1, PaymentRqst_AmountD2, ".
						 " PaymentRqst_BelongsToGrp, Synchronized, PaymentRqst_AmntModified, PaymentRqst_manualno, paymentrqst_include, PaymentRqst_App, ".
						 " PaymentRqst_Confirmed, Touser_account, User_Confirmed, Owner_Branch, Destination_Branch, PaymentRqst_Syn_ID ) ".
						 " Values ( ".$vPaymentRqstID.", ".$vPaymentRqstRef.", ".$vPaymentRqstDate.", ".$vPaymentRqstName.", ".$vPaymentRqstRemark.
						 ", ".$vPaymentRqstAmount.", ".$vPaymentRqstAmount1.", ".$vPaymentRqstAmount2.", ".$vPaymentRqstMode.", ".$vLedgerNumber.", ".$vPaymentRqstDesc.
						 ", ".$vCurrencyCode.", ".$vProjectCode.", ".$vCostcentCode.", ".$vPaymentRqstEdit.", ".$vPaymentRqstPosted.", ".$vPaymentRqstVat.", ".$vValueDate.
						 ", ".$vPaymentRqstdtincr.", ".$vPaymentRqstUsed.", ".$vPaymentRqstAmountC1.", ".$vPaymentRqstAmountC2.", ".$vPaymentRqstAmountD1.", ".$vPaymentRqstAmountD2.
						 ", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vAmntModified.", ".$vManualNo.", ".$vPaymentRqstInclude.", ".$vPaymentRqstApp.
						 ", ".$vConfirmed.", ".$vUserAccount.", ".$vUserConfirmed.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vPaymentRqstSynID." ) ";
		}	
		
		else {
			$query  = " Select PaymentRqst_ID From PaymentRqst ".
					  " Where PaymentRqst_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPaymentRqstID = $result[0];
		
			$sub_query = "  Update PaymentRqst Set PaymentRqst_Refgovernment = ".$vPaymentRqstRef.", PaymentRqst_Date = ".$vPaymentRqstDate. 
						 ",	PaymentRqst_Name = ".$vPaymentRqstName.", PaymentRqst_Remark = ".$vPaymentRqstRemark.
						 ",	PaymentRqst_Amount = ".$vPaymentRqstAmount.", PaymentRqst_Amount1 = ".$vPaymentRqstAmount1.
						 ",	PaymentRqst_Amount2 = ".$vPaymentRqstAmount2.", PaymentRqst_Mode = ".$vPaymentRqstMode.
						 ",	Ledger_Number = ".$vLedgerNumber.", PaymentRqst_Desc = ".$vPaymentRqstDesc.
						 ", Currency_Code = ".$vCurrencyCode.",	Project_Code = ".$vProjectCode.", Costcent_Code = ".$vCostcentCode.
						 ", PaymentRqst_Edit = ".$vPaymentRqstEdit.", PaymentRqst_Posted = ".$vPaymentRqstPosted.", PaymentRqst_Vat = ".$vPaymentRqstVat. 
						 ", PaymentRqst_ValueDate = ".$vValueDate.", PaymentRqst_dtincr = ".$vPaymentRqstdtincr.", PaymentRqst_Used = ".$vPaymentRqstUsed.
						 ", PaymentRqst_AmountC1 = ".$vPaymentRqstAmountC1.", PaymentRqst_AmountC2 = ".$vPaymentRqstAmountC2.
						 ", PaymentRqst_AmountD1 = ".$vPaymentRqstAmountD1.", PaymentRqst_AmountD2 = ".$vPaymentRqstAmountD2.
						 ", PaymentRqst_BelongsToGrp = ".$vBelongsToGroup.", PaymentRqst_AmntModified = ".$vAmntModified.", PaymentRqst_manualno = ".$vManualNo.
						 ", paymentrqst_include = ".$vPaymentRqstInclude.", PaymentRqst_App = ".$vPaymentRqstApp.", PaymentRqst_Confirmed = ".$vConfirmed.
						 ", Touser_account = ".$vUserAccount.", User_Confirmed = ".$vUserConfirmed.", Destination_Branch = ".$vDestinationBranch.
						 "  Where PaymentRqst_Syn_ID = '".$PRecordID."'";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			//InCase Update, Delete All Related Details In PaymentRqstDt
			If ($vRecordExists > 0) {
				$query = "Delete From PaymentRqstDt Where PaymentRqst_ID = '".$vPaymentRqstID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			//Insert Related Details From PaymentRqstDt
			$query = " Select PaymentRqstDt_ID, PaymentRqst_ID, Currency_Code, PaymentRqst_Date, Ledger_number, PaymentRqstdt_desc, PaymentRqstdt_desc1, ".
					 " PaymentRqstdt_ValueDate, PaymentRqstdt_Amount, PaymentRqstdt_Amount1, PaymentRqstdt_Amount2, PaymentRqstdt_dbcd, PaymentRqstdt_dbcdAra, ".
					 " Document, Synchronized, PaymentRqst_description2, PaymentRqstDt_Syn_ID, PaymentRqst_Syn_ID ".
					 " From PaymentRqstDt ".
					 " Where PaymentRqst_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vPaymentRqstDtID = GetNextSequence1($PDestConn,'PaymentRqstDt_ID','');
		
				$sub_query = " Insert Into PaymentRqstDt (PaymentRqstDt_ID, PaymentRqst_ID, Currency_Code, PaymentRqst_Date, Ledger_number, PaymentRqstdt_desc, ".
							 " PaymentRqstdt_desc1, PaymentRqstdt_ValueDate, PaymentRqstdt_Amount, PaymentRqstdt_Amount1, PaymentRqstdt_Amount2, PaymentRqstdt_dbcd, ".
							 " PaymentRqstdt_dbcdAra, Detail_Code, User_Account, TransDt_ManualNo, PaymentRqstDt_Syn_ID, PaymentRqst_Syn_ID ) ".
							 " Values ( ".$vPaymentRqstDtID.", ".$vPaymentRqstID.", ".GetSQLValueString($rows['Currency_Code'],'text').
							 ", ".GetSQLValueString($rows['PaymentRqst_Date'],'date').", ".GetSQLValueString($rows['Ledger_number'],'text').
							 ", ".GetSQLValueString($rows['PaymentRqstdt_desc'],'text').", ".GetSQLValueString($rows['PaymentRqstdt_desc1'],'text').
							 ", ".GetSQLValueString($rows['PaymentRqstdt_ValueDate'],'date').", ".GetSQLValueString($rows['PaymentRqstdt_Amount'],'double').
							 ", ".GetSQLValueString($rows['PaymentRqstdt_Amount1'],'double').", ".GetSQLValueString($rows['PaymentRqstdt_Amount2'],'double').
							 ", ".GetSQLValueString($rows['PaymentRqstdt_dbcd'],'text').", ".GetSQLValueString($rows['PaymentRqstdt_dbcdAra'],'text').
							 ", ".GetSQLValueString($rows['Document'],'text').", ".GetSQLValueString($rows['Synchronized'],'int').
							 ", ".GetSQLValueString($rows['PaymentRqst_description2'],'text').", ".GetSQLValueString($rows['PaymentRqstDt_ID'],'double').
							 ", ".$vPaymentRqstSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {	
					$vResult = 'T';
										
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PaymentRqstDt_ID']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PaymentRqstDt',$vMessage);
					
					break;
				}		
			}
		
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PaymentRqst',$vMessage);
		}
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select PaymentRqst_ID, Owner_Branch ".
					 " From PaymentRqst Where PaymentRqst_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vPaymentRqstID = $sub_result[0];
		$vOwnerBranch   = $sub_result[1];
		
				
		$query = "Delete From PaymentRqstDt Where PaymentRqst_ID = '".$vPaymentRqstID."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
			
			$query = "Delete From PaymentRqst Where PaymentRqst_ID = '".$vPaymentRqstID."'";
			$result = mysql_query($query, $PDestConn);
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PaymentRqstDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPaymentRqstID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroTrans($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
				 " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, ".
				 " Journal_Id, Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, Synchronized, ".
				 " User_Account, acctrx_Posted, PaymentRqst_Id, Trans_Confirmed, Trans_UserConfirmed, Trans_OldData, Owner_Branch, Destination_Branch  ".
				 " From Trans ".
				 " Where Trans_ID	= '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vTransSynID		  = GetSQLValueString($rows['Trans_ID'],'int');
		$vJournalSynID		  = GetSQLValueString($rows['Journal_Id'],'int');
		$vPaymentRqstSynID	  = GetSQLValueString($rows['PaymentRqst_Id'],'int');
		$vTransReference	  = GetSQLValueString($rows['Trans_Reference'],'double');
		$vTransDate		      = GetSQLValueString($rows['Trans_Date'],'date');
		$vTransSysDate        = GetSQLValueString($rows['Trans_SysDate'],'date');
		$vTransRemark	 	  = GetSQLValueString($rows['Trans_Remark'],'text');
		$vTransType           = GetSQLValueString($rows['Trans_Type'],'text');
		$vTransRepresentative = GetSQLValueString($rows['Trans_Representative'],'text');
		$vTransAmountDb1	  = GetSQLValueString($rows['Trans_AmountDb1'],'double');
		$vTransAmountDb2	  = GetSQLValueString($rows['Trans_AmountDb2'],'double');
		$vTransAmountcd1	  = GetSQLValueString($rows['Trans_Amountcd1'],'double');
		$vTransAmountcd2	  = GetSQLValueString($rows['Trans_Amountcd2'],'double');
		$vTransManualNo		  = GetSQLValueString($rows['Trans_ManualNo'],'text');
		$vCashReference		  = GetSQLValueString($rows['Trans_CashReference'],'double');
		$vCashTypeCode 		  = GetSQLValueString($rows['CashType_code'],'text');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		  = GetSQLValueString($rows['Costcent_code'],'text');
		$vCurrencyCode		  = GetSQLValueString($rows['Currency_Code'],'text');
		$vTransPosted		  = GetSQLValueString($rows['Trans_Posted'],'int');
		$vSynchronized		  = GetSQLValueString($rows['Synchronized'],'int');
		$vAcctrxPosted		  = GetSQLValueString($rows['acctrx_Posted'],'int');
		$vUserAccount		  = GetSQLValueString($rows['User_Account'],'text');
		$vBelongsToGroup	  = GetSQLValueString($rows['Trans_BelongsToGroup'],'int');
		$vTransConfirmed	  = GetSQLValueString($rows['Trans_Confirmed'],'int');
		$vTransUserConfirmed  = GetSQLValueString($rows['Trans_UserConfirmed'],'text');
		$vTransOldData	 	  = GetSQLValueString($rows['Trans_OldData'],'int');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch   = GetSQLValueString($rows['Destination_Branch'],'text');
		
		$vPaymentRqstID	 	  = F_Get_PaymentReqID($PDestConn, $vPaymentRqstSynID);
		
		
		$sub_query  = " Select Count(*) From Trans ".
		              " Where Trans_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vTransID = GetNextSequence1($PDestConn,'Trans_ID','');
			
			$sub_query = " Insert Into Trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
						 " Trans_ManualNo, Currency_Code, Trans_CashReference, CashType_code, Project_Code, Costcent_code, Trans_Posted, ".
						 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, User_Account, acctrx_Posted, ".
						 " PaymentRqst_Id, Trans_Confirmed, Trans_UserConfirmed, Trans_OldData, Owner_Branch, Destination_Branch, Trans_Syn_ID ) ".
						 " Values ( ".$vTransID.", ".$vTransReference.", ".$vTransDate.", ".$vTransSysDate.", ".$vTransRemark.", ".$vTransType.
						 ", ".$vTransRepresentative.", ".$vTransManualNo.", ".$vCurrencyCode.", ".$vCashReference.", ".$vCashTypeCode.", ".$vProjectCode.
						 ", ".$vCostcentCode.", ".$vTransPosted.", ".$vTransAmountDb1.", ".$vTransAmountDb2.", ".$vTransAmountcd1.", ".$vTransAmountcd2.
						 ", ".$vBelongsToGroup.", ".$vUserAccount.", ".$vAcctrxPosted.", ".$vPaymentRqstID.", ".$vTransConfirmed.", ".$vTransUserConfirmed.
						 ", ".$vTransOldData.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vTransSynID." ) ";
		}	
		else {
			$query  = " Select Trans_ID From Trans ".
					  " Where Trans_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vTransID = $result[0];
		
			$sub_query = "  Update Trans Set Trans_Reference = ".$vTransReference.", Trans_Date = ".$vTransDate. 
						 ",	Trans_SysDate = ".$vTransSysDate.", Trans_Remark = ".$vTransRemark.", Trans_Type = ".$vTransType. 
						 ",	Trans_Representative = ".$vTransRepresentative.", Trans_ManualNo = ".$vTransManualNo.
						 ",	Currency_Code = ".$vCurrencyCode.", Trans_CashReference = ".$vCashReference.", CashType_code = ".$vCashTypeCode. 
						 ",	Project_Code = ".$vProjectCode.", Costcent_Code = ".$vCostcentCode.", Trans_Posted = ".$vTransPosted.
						 ", Trans_AmountDb1 = ".$vTransAmountDb1.", Trans_AmountDb2 = ".$vTransAmountDb2.", Trans_Amountcd1 = ".$vTransAmountcd1. 
						 ", Trans_Amountcd2 = ".$vTransAmountcd2.", Trans_BelongsToGroup = ".$vBelongsToGroup. 
						 ", User_Account = ".$vUserAccount.", acctrx_Posted = ".$vAcctrxPosted.
						 ", Trans_Confirmed = ".$vTransConfirmed.", Trans_UserConfirmed = ".$vTransUserConfirmed.", Trans_OldData = ".$vTransOldData.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where Trans_Syn_ID = '".$PRecordID."'";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
		
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Trans Set Trans_Syn_ID = ".$vTransID.
							 " Where Trans_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In TransDt, CstJourDt
			If ($vRecordExists > 0) {
				$query = " Delete From BilljourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Delete From ChkjourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Delete From CstjourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From TransDt Where Trans_ID = '".$vTransID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			//Insert Related Details From TransDt
			$query = " Select TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ".
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, Detail_Code, ".
					 " Synchronized, User_Account, TransDt_ManualNo, TransDt_Syn_ID, Trans_Syn_ID ".
					 " From TransDt ".
					 " Where Trans_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vTransDtID = GetNextSequence1($PDestConn,'TransDt_ID','');
		
				$sub_query = " Insert Into TransDt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, ".
							 " TransDt_Description2, TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, ".
							 " TransDt_Sign, Detail_Code, User_Account, TransDt_ManualNo, TransDt_Syn_ID, Trans_Syn_ID ) ".
							 " Values ( ".$vTransDtID.", ".$vTransID.", ".GetSQLValueString($rows['Currency_Code'],'text').
							 ", ".GetSQLValueString($rows['Trans_Date'],'date').", ".GetSQLValueString($rows['Ledger_number'],'text').
							 ", ".GetSQLValueString($rows['TransDt_Description'],'text').", ".GetSQLValueString($rows['TransDt_Description2'],'text').
							 ", ".GetSQLValueString($rows['TransDt_ValueDate'],'date').", ".GetSQLValueString($rows['Transdt_Amount'],'double').
							 ", ".GetSQLValueString($rows['Transdt_Amount1'],'double').", ".GetSQLValueString($rows['Transdt_Amount2'],'double').
							 ", ".GetSQLValueString($rows['TransDt_dbcd'],'text').", ".GetSQLValueString($rows['TransDt_Sign'],'text').
							 ", ".GetSQLValueString($rows['Detail_Code'],'text').", ".GetSQLValueString($rows['User_Account'],'text').
							 ", ".GetSQLValueString($rows['TransDt_ManualNo'],'text').", ".GetSQLValueString($rows['TransDt_Id'],'double').", ".$vTransSynID." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {	
					$vResult = 'T';
					
					//InCase Insert TransDt Done, Then Inserts Related CstJourDt
					$query1 = " Select TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, ".
                              " CstJourDt_Amount1, CstJourDt_Amount2, Synchronized ".
					          " From CstJourDt ".
							  " Where TransDt_ID = '".$rows['TransDt_Id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						
						$sub_query1 = " Insert Into CstJourDt (TransDt_id, Project_code, Costcenter_Code, CstjourDt_Per, CstJourDt_Amount, ".
									  " CstJourDt_Amount1, CstJourDt_Amount2, User_Account ) ".
									  " Values ( ".$vTransDtID.", ".GetSQLValueString($rows1['Project_code'],'text').", ".GetSQLValueString($rows1['Costcenter_Code'],'text').
									  ", ".GetSQLValueString($rows1['CstjourDt_Per'],'double').", ".GetSQLValueString($rows1['CstJourDt_Amount'],'double').
									  ", ".GetSQLValueString($rows1['CstJourDt_Amount1'],'double').", ".GetSQLValueString($rows1['CstJourDt_Amount2'],'double').
									  ", ".GetSQLValueString($rows1['User_Account'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['TransDt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'CstJourDt',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A CstJourDt Then Exit Loop Of TransDt
					if ($vResult == 'P') break;
					
					//InCase Insert TransDt Done, Then Inserts Related ChkJourDt
					$query1 = " Select TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, ".
                              " Chk_Amount2, Ledger_Number, Chk_Type, Synchronized, User_Account ".
					          " From ChkJourDt ".
							  " Where TransDt_ID = '".$rows['TransDt_Id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
												
						$sub_query1 = " Insert Into ChkJourDt (TransDt_id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, ".
									  " Chk_Amount2, Ledger_Number, Chk_Type, User_Account ) ".
									  " Values ( ".$vTransDtID.", ".GetSQLValueString($rows1['Chk_number'],'text').", ".GetSQLValueString($rows1['Chk_bank'],'text').
									  ", ".GetSQLValueString($rows1['Chk_ValueDate'],'date').", ".GetSQLValueString($rows1['Currency_Code'],'text').
									  ", ".GetSQLValueString($rows1['Chk_Amount'],'double').", ".GetSQLValueString($rows1['Chk_Amount1'],'double').
									  ", ".GetSQLValueString($rows1['Chk_Amount2'],'double').", ".GetSQLValueString($rows1['Ledger_Number'],'text').
									  ", ".GetSQLValueString($rows1['Chk_Type'],'text').", ".GetSQLValueString($rows1['User_Account'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['TransDt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'ChkJourDt',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A ChkJourDt Then Exit Loop Of TransDt
					if ($vResult == 'P') break;
					
					//InCase Insert TransDt Done, Then Inserts Related BillJourDt
					$query1 = " Select TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, ".
                              " Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type, Synchronized ".
					          " From BillJourDt ".
							  " Where TransDt_ID = '".$rows['TransDt_Id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						
						$sub_query1 = " Insert Into BillJourDt (TransDt_id, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, Bill_Amount, ".
									  " Bill_Amount1, Bill_Amount2, Ledger_Number, Bill_type ) ".
									  " Values ( ".$vTransDtID.", ".GetSQLValueString($rows1['Bill_Number'],'text').", ".GetSQLValueString($rows1['Bill_Bank'],'text').
									  ", ".GetSQLValueString($rows1['Bill_ValueDate'],'date').", ".GetSQLValueString($rows1['Currency_Code'],'text').
									  ", ".GetSQLValueString($rows1['Bill_Amount'],'double').", ".GetSQLValueString($rows1['Bill_Amount1'],'double').
									  ", ".GetSQLValueString($rows1['Bill_Amount2'],'double').", ".GetSQLValueString($rows1['Ledger_Number'],'text').
									  ", ".GetSQLValueString($rows1['Bill_type'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['TransDt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'BillJourDt',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A BillJourDt Then Exit Loop Of TransDt
					if ($vResult == 'P') break;
					
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['TransDt_Id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'TransDt',$vMessage);
					
					break;
				}		
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedTransJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
					
				$sub_query1 = " Update Trans Set Journal_ID = '".$vJournalID."' ".
							  " Where Trans_ID = '".$vTransID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}			
		
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Trans',$vMessage);
		}
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Trans_ID, Owner_Branch ".
					 " From Trans Where Trans_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID   = $sub_result[0];
		$vTransID	  = $sub_result[1];
		$vOwnerBranch = $sub_result[2];
		if(empty($vJournalID)) $vJournalID = -1;
		
		// Manage Checks After Delete
		$sub_query1 = " Select ChkJourDt_Id, Chk_Number, Chk_Type, Ledger_Number ".
					  " From ChkJourDt ".
					  " WHERE ChkjourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
		
		$sub_result1=mysql_query($sub_query1,$PDestConn);
		while($sub_row1=mysql_fetch_row($sub_result1)){	
			$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
			$sub_result2 = selectData($PDestConn, $sub_query2);
			$vChkCount     = $sub_result2[0];
			$vJournalDtId2  = $sub_result2[1];
					
			if (empty($vChkCount)) $vChkCount = 0;
					
			if ($vChkCount > 0) {
				if ($sub_row1[2] == 'C') {
					$sub_query3  = " UPDATE checks set journaldt_id2 = Null Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				} else if ($vJournalDtId2 == 0) {
					$sub_query3  = " DELETE From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				}
						
				$sub_result3 = mysql_query($sub_query3, $PDestConn);
					
			}
		}
				
				
		// Manage Bills After Delete
		$sub_query1 = " Select BillJourDt_Id, Bill_Number, Bill_Type, Ledger_Number ".
					  " From BillJourDt ".
					  " WHERE BilljourDt.TransDt_id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
							  
		$sub_result1=mysql_query($sub_query1,$PDestConn);
		while($sub_row1=mysql_fetch_row($sub_result1)){	
			$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
			$sub_result2 = selectData($PDestConn, $sub_query2);
			$vBillCount     = $sub_result2[0];
			$vJournalDtId2  = $sub_result2[1];
					
			if (empty($vBillCount)) $vBillCount = 0;
					
			if ($vBillCount > 0) {
				if ($sub_row1[2] == 'C') {
					$sub_query3  = " UPDATE Bills set journaldt_id2 = Null Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				} else if ($vJournalDtId2 == 0) {
					$sub_query3  = " DELETE From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				}
						
				$sub_result3 = mysql_query($sub_query3, $PDestConn);
					
			}
		}
				
		$query = " Delete From BilljourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
		$result = mysql_query($query, $PDestConn);
				
		$query = " Delete From ChkjourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
		$result = mysql_query($query, $PDestConn);
				
		$query = " Delete From CstjourDt Where TransDt_Id In (Select TransDt_Id From TransDt Where Trans_Id = '".$vTransID."') ";
		$result = mysql_query($query, $PDestConn);
				
		$query = "Delete From TransDt Where Trans_ID = '".$vTransID."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
			
			$query = "Delete From Trans Where Trans_ID = '".$vTransID."'";
			$result = mysql_query($query, $PDestConn);
			
			if ($vJournalID != -1) {	
				$query = "Delete From Journal Where Journal_ID = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'TransDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vTransID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroRelatedTransJv($PRecordID, $PState, $PLocConn, $PDestConn) {

	If (($PState == 'I' || $PState == 'U') && $PRecordID != '' && $PRecordID != 'Null') {
		$query = " Select journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
				 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
				 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
				 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup ".
				 " From Journal ".
				 " Where Journal_ID	= '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vJournalSynID		 = GetSQLValueString($rows['journal_id'],'int');
		$vJournalReference	 = GetSQLValueString($rows['journal_refgovernment'],'double');
		$vJournalFolio	 	 = GetSQLValueString($rows['journal_folio'],'double');
		$vJournalType        = GetSQLValueString($rows['journal_type'],'text');
		$vJournalTypeRef	 = GetSQLValueString($rows['Journal_typeref'],'text');
		$vJournalDate		 = GetSQLValueString($rows['Journal_Date'],'date');
		$vJournalSysDate     = GetSQLValueString($rows['Journal_SysDate'],'date');
		$vJournalTime		 = GetSQLValueString($rows['Journal_Time'],'date');
		$vAmnt1db		 	 = GetSQLValueString($rows['Amnt1_db'],'double');
		$vAmnt1cd		 	 = GetSQLValueString($rows['Amnt1_cd'],'double');
		$vAmnt2db		 	 = GetSQLValueString($rows['Amnt2_db'],'double');
		$vAmnt2cd		 	 = GetSQLValueString($rows['Amnt2_cd'],'double');
		$vJournalFlag		 = GetSQLValueString($rows['journal_flag'],'text');
		$vJournaldtincr		 = GetSQLValueString($rows['Journal_dtincr'],'double');
		$vJournalEdit 		 = GetSQLValueString($rows['Journal_Edit'],'int');
		$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		 = GetSQLValueString($rows['Costcent_Code'],'text');
		$vJournalRemark		 = GetSQLValueString($rows['Journal_Remark'],'text');
		$vJournalPosted		 = GetSQLValueString($rows['Journal_posted'],'int');
		$vUserAccount		 = GetSQLValueString($rows['User_account'],'text');
		$vUserName			 = GetSQLValueString($rows['User_Name'],'text');
		$vJournalConfirmed	 = GetSQLValueString($rows['Journal_Confirmed'],'int');
		$vConfirmedUser		 = GetSQLValueString($rows['Journal_ConfirmedUser'],'text');
		$vJournalManualNo	 = GetSQLValueString($rows['Manual_no'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['journal_belongstogroup'],'int');
		
		$sub_query  = " Select Count(*) From Journal ".
		              " Where Journal_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vJournalID = GetNextSequence1($PDestConn,'Journal_ID','');
			
			$sub_query = " Insert Into Journal (journal_id, journal_refgovernment, journal_folio, journal_type, Journal_typeref, ".
						 " Journal_Date, Journal_SysDate, Journal_Time, Amnt1_db, Amnt1_cd, Amnt2_db, Amnt2_cd, journal_flag, ".
						 " Journal_dtincr, Journal_Edit, Project_Code, Costcent_Code, Journal_Remark, Journal_posted, ".
						 " User_account, User_Name, Journal_Confirmed, Journal_ConfirmedUser, Manual_no, journal_belongstogroup, ".
						 " Journal_Syn_ID) ".
						 " Values ( ".$vJournalID.", ".$vJournalReference.", ".$vJournalFolio.", ".$vJournalType.", ".$vJournalTypeRef.
						 ", ".$vJournalDate.", ".$vJournalSysDate.", ".$vJournalTime.", ".$vAmnt1db.", ".$vAmnt1cd.", ".$vAmnt2db.", ".$vAmnt2cd.
						 ", ".$vJournalFlag.", ".$vJournaldtincr.", ".$vJournalEdit.", ".$vProjectCode.", ".$vCostcentCode.", ".$vJournalRemark.
						 ", ".$vJournalPosted.", ".$vUserAccount.", ".$vUserName.", ".$vJournalConfirmed.", ".$vConfirmedUser.
						 ", ".$vJournalManualNo.", ".$vBelongsToGroup.", ".$vJournalSynID." ) ";
		}	
		else {
			$query  = " Select Journal_ID From Journal ".
					  " Where Journal_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vJournalID = $result[0];
		
			$sub_query = "  Update Journal Set journal_refgovernment = ".$vJournalReference.", journal_folio = ".$vJournalFolio. 
						 ",	journal_type = ".$vJournalType.", Journal_typeref = ".$vJournalTypeRef.", Journal_Date = ".$vJournalDate. 
						 ",	Journal_SysDate = ".$vJournalSysDate.", Journal_Time = ".$vJournalTime.", Amnt1_db = ".$vAmnt1db. 
						 ",	Amnt1_cd = ".$vAmnt1cd.", Amnt2_db = ".$vAmnt2db.", Amnt2_cd = ".$vAmnt2cd. 
						 ",	journal_flag = ".$vJournalFlag.", Journal_dtincr = ".$vJournaldtincr.", Journal_Edit = ".$vJournalEdit. 
						 ",	Project_Code = ".$vProjectCode.", Costcent_Code = ".$vCostcentCode.", Journal_Remark = ".$vJournalRemark.
						 ", Journal_posted = ".$vJournalPosted.", User_account = ".$vUserAccount.", User_Name = ".$vUserName. 
						 ", Journal_Confirmed = ".$vJournalConfirmed.", Journal_ConfirmedUser = ".$vConfirmedUser. 
						 ", Manual_no = ".$vJournalManualNo.", journal_belongstogroup = ".$vBelongsToGroup.
						 "  Where Journal_Syn_ID = '".$PRecordID."'";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
		
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update Journal Set Journal_Syn_ID = ".$vJournalID.
							 " Where Journal_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In JournalDt, CstJour
			If ($vRecordExists > 0) {
				$query = " Delete From Bills Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
						 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Delete From Checks Where (Journaldt_Id2 is null or Journaldt_Id2 = 0 or Journaldt_Id2 = '') ".
						 " And JournalDt_ID1 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Update Checks Set JournalDt_Id2 = Null ".
						 " Where JournalDt_Id2 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = " Update Bills Set JournalDt_Id2 = Null ".
						 " Where JournalDt_Id2 In (Select JournalDt_ID From JournalDt Where Journal_ID = '".$vJournalID."') ";
				$result = mysql_query($query, $PDestConn);
				
				$query = "Delete From JournalDt Where Journal_ID = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
			$dtincr = 0;
			
			//Insert Related Details From JournalDt
			$query = " Select journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
					 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
					 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
					 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code ".
					 " From JournalDt ".
					 " Where Journal_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				//$vJournalDtID = GetNextSequence1($PDestConn,'JournalDt_ID','');
				
				$dtincr += 1;
				$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
				$vJournalDtID = $vJournalID.''.$dtincr_pad;
				
				$sub_query = " Insert Into JournalDt (journaldt_id, journal_id, Ledger_Number, Document, Currency_Code, Journaldt_DBCD, Journaldt_dbcdAra, ".
							 " Journaldt_Desc, journaldt_desc1, Journal_date, Journaldt_valuedate, Journal_BelongsToGroup, manual_no, ".
							 " Journaldt_Amount, Journaldt_Amount1, Journaldt_Amount2, Journaldt_posted, Journaldt_reconciled, Journaldt_reconciledref, ".
							 " Reconciliation_date, Reconciliation_Sysdate, Journal_JVRef, Journaldt_JVMode, Detail_Code ) ".
							 " Values ( ".$vJournalDtID.", ".$vJournalID.", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['Document'],'text').
							 ", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Journaldt_DBCD'],'text').
							 ", ".GetSQLValueString($rows['Journaldt_dbcdAra'],'text').", ".GetSQLValueString($rows['Journaldt_Desc'],'text').
							 ", ".GetSQLValueString($rows['journaldt_desc1'],'text').", ".GetSQLValueString($rows['Journal_date'],'date').
							 ", ".GetSQLValueString($rows['Journaldt_valuedate'],'date').", ".GetSQLValueString($rows['Journal_BelongsToGroup'],'int').
							 ", ".GetSQLValueString($rows['manual_no'],'text').", ".GetSQLValueString($rows['Journaldt_Amount'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_Amount1'],'double').", ".GetSQLValueString($rows['Journaldt_Amount2'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_posted'],'int').", ".GetSQLValueString($rows['Journaldt_reconciled'],'int').
							 ", ".GetSQLValueString($rows['Journaldt_reconciledref'],'text').", ".GetSQLValueString($rows['Reconciliation_date'],'date').
							 ", ".GetSQLValueString($rows['Reconciliation_Sysdate'],'date').", ".GetSQLValueString($rows['Journal_JVRef'],'double').
							 ", ".GetSQLValueString($rows['Journaldt_JVMode'],'text').", ".GetSQLValueString($rows['Detail_Code'],'text')." )";
							 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {	
					$vResult = 'T';
					
					//InCase Insert JournalDt Done, Then Inserts Related CstJour
					$query1 = " Select Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
                              " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ".
					          " From CstJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						
						$sub_query1 = " Insert Into CstJour (Journaldt_id, Costcent_code, project_code, Cstjour_amount, Cstjour_amount1, ".
									  " Cstjour_amount2, Cstjour_prcnt, CstJour_Posted, Journal_JVRef ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Costcent_code'],'text').", ".GetSQLValueString($rows1['project_code'],'text').
									  ", ".GetSQLValueString($rows1['Cstjour_amount'],'double').", ".GetSQLValueString($rows1['Cstjour_amount1'],'double').
									  ", ".GetSQLValueString($rows1['Cstjour_amount2'],'double').", ".GetSQLValueString($rows1['Cstjour_prcnt'],'double').
									  ", ".GetSQLValueString($rows1['CstJour_Posted'],'int').", ".GetSQLValueString($rows1['Journal_JVRef'],'double')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if (!($sub_result1)) {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'CstJour',$vMessage);
							
							break;
						}
						
					}
					
					//If Problem In Inserting A CstJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
					//InCase Insert JournalDt Done, Then Inserts Related ChkJour
					$query1 = " Select Journaldt_id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Currency_code, Chk_Amount, ".
                              " Chk_Amount1, Chk_Amount2, Chk_Type, Chk_bank_in, Chk_col_ret, ChkJour_Posted, Synchronized ".
					          " From ChkJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vCheckNo  	   = GetSQLValueString($rows1['Chk_Number'],'int');
						$vLedgerNo	   = GetSQLValueString($rows1['Ledger_Number'],'int');
						$vJournalDtId1 = GetSQLValueString($rows1['Journaldt_id'],'int');
						
						
						$sub_query1 = " Insert Into ChkJour (Journaldt_id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Currency_code, Chk_Amount, ".
									  " Chk_Amount1, Chk_Amount2, Chk_Type, Chk_bank_in, Chk_col_ret, ChkJour_Posted ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Ledger_Number'],'text').", ".GetSQLValueString($rows1['Chk_Number'],'text').
									  ", ".GetSQLValueString($rows1['Chk_Bank'],'text').", ".GetSQLValueString($rows1['Chk_ValueDate'],'date').
									  ", ".GetSQLValueString($rows1['Currency_code'],'text').", ".GetSQLValueString($rows1['Chk_Amount'],'double').
									  ", ".GetSQLValueString($rows1['Chk_Amount1'],'double').", ".GetSQLValueString($rows1['Chk_Amount2'],'double').
									  ", ".GetSQLValueString($rows1['Chk_Type'],'text').", ".GetSQLValueString($rows1['Chk_bank_in'],'text').
									  ", ".GetSQLValueString($rows1['Chk_col_ret'],'text').", ".GetSQLValueString($rows1['ChkJour_Posted'],'int')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							$vCheckID = F_SynchroRelatedChecks($vJournalDtId1, $vLedgerNo, $vCheckNo, $vJournalDtID, 'I', $PLocConn, $PDestConn);
						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'ChkJour',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A ChkJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
					//InCase Insert JournalDt Done, Then Inserts Related BillJour
					$query1 = " Select Journaldt_id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, ".
                              " Bill_Amount, Bill_Amount1, Bill_Amount2, Bill_type, Synchronized ".
					          " From BillJour ".
							  " Where JournalDt_ID = '".$rows['journaldt_id']."'";

					//echo $query1; exit;		 
					$result1=mysql_query($query1,$PLocConn) or die(mysql_error());
					while($rows1=mysql_fetch_assoc($result1)){
						$vBillNo  	   = GetSQLValueString($rows1['Bill_Number'],'int');
						$vLedgerNo	   = GetSQLValueString($rows1['Ledger_Number'],'int');
						$vJournalDtId1 = GetSQLValueString($rows1['Journaldt_id'],'int');
						
						
						$sub_query1 = " Insert Into BillJour (Journaldt_id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Currency_Code, ".
									  " Bill_Amount, Bill_Amount1, Bill_Amount2, Bill_type ) ".
									  " Values ( ".$vJournalDtID.", ".GetSQLValueString($rows1['Ledger_Number'],'text').", ".GetSQLValueString($rows1['Bill_Number'],'text').
									  ", ".GetSQLValueString($rows1['Bill_Bank'],'text').", ".GetSQLValueString($rows1['Bill_ValueDate'],'date').
									  ", ".GetSQLValueString($rows1['Currency_Code'],'text').", ".GetSQLValueString($rows1['Bill_Amount'],'double').
									  ", ".GetSQLValueString($rows1['Bill_Amount1'],'double').", ".GetSQLValueString($rows1['Bill_Amount2'],'double').
									  ", ".GetSQLValueString($rows1['Bill_type'],'text')." )";
						//echo $sub_query1; exit;	 
						$sub_result1=mysql_query($sub_query1,$PDestConn);
						
						if ($sub_result1) {
							$vBillID = F_SynchroRelatedBills($vJournalDtId1, $vLedgerNo, $vBillNo, $vJournalDtID, 'I', $PLocConn, $PDestConn);
						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert ID= ".$rows1['Journaldt_id']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'BillJour',$vMessage);
							
							break;
						}
					}
					
					//If Problem In Inserting A BillJour Then Exit Loop Of JournalDt
					if ($vResult == 'P') break;
					
					
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['journaldt_id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'JournalDt',$vMessage);
					
					break;
				}		
			}	
		
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Journal',$vMessage);
		}
		
	}

	Return $vJournalID;	
}

function F_SynchroRelatedChecks($PRecordID, $PLedgerNo, $PCheckNo, $PJournalDtId, $PState, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Chk_number, journaldt_id1, ledger_number, Chk_bank, Chk_ValueDate, ".
				 " Currency_code, Chk_amount, Chk_amount1, Chk_amount2, Ledger_Activity ".
				 " From Checks ".
				 " Where Chk_Number	= '".$PCheckNo."' ".
				 " And Ledger_Number = '".$PLedgerNo."' ".
				 " And ((journaldt_id1 = '".$PRecordID."') or (journaldt_id2 = '".$PRecordID."')) ";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vChkNumber      = GetSQLValueString($rows['Chk_number'],'text');
		$vChkBank        = GetSQLValueString($rows['Chk_bank'],'text');
		$vLedgerNumber	 = GetSQLValueString($rows['ledger_number'],'text');
		$vChkValueDate	 = GetSQLValueString($rows['Chk_ValueDate'],'date');
		$vCurrencyCode	 = GetSQLValueString($rows['Currency_code'],'text');
		$vChkAmount		 = GetSQLValueString($rows['Chk_amount'],'double');
		$vChkAmount1	 = GetSQLValueString($rows['Chk_amount1'],'double');
		$vChkAmount2	 = GetSQLValueString($rows['Chk_amount2'],'double');
		$vLedgerActivity = GetSQLValueString($rows['Ledger_Activity'],'int');
		
		$sub_query  = " Select Count(*) From Checks ".
		              " Where Chk_Number  = '".$PCheckNo."' ".
					  " And Ledger_Number = '".$PLedgerNo."' ";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$sub_query = " Insert Into Checks (Chk_number, journaldt_id1, ledger_number, Chk_bank, Chk_ValueDate, ".
						 " Currency_code, Chk_amount, Chk_amount1, Chk_amount2, Ledger_Activity ) ".
						 " Values ( ".$vChkNumber.", ".$PJournalDtId.", ".$vLedgerNumber.", ".$vChkBank.", ".$vChkValueDate.
						 ", ".$vCurrencyCode.", ".$vChkAmount.", ".$vChkAmount1.", ".$vChkAmount2.", ".$vLedgerActivity." ) ";
		}	
		else {
			$sub_query = " Update Checks Set journaldt_id2 = ".$PJournalDtId.
						 " Where Chk_Number = '".$PCheckNo."' ".
						 " And Ledger_Number = '".$PLedgerNo."' ";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			$vResult = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Checks',$vMessage);
		}
		
	}

	Return 1;	

}

function F_SynchroRelatedBills($PRecordID, $PLedgerNo, $PBillNo, $PJournalDtId, $PState, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Bill_number, journaldt_id1, ledger_number, Bill_bank, Bill_ValueDate, ".
				 " Currency_code, Bill_amount, Bill_amount1, Bill_amount2, Ledger_Activity ".
				 " From Bills ".
				 " Where Bill_Number	= '".$PBillNo."' ".
				 " And Ledger_Number = '".$PLedgerNo."' ".
				 " And ((journaldt_id1 = '".$PRecordID."') or (journaldt_id2 = '".$PRecordID."')) ";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
			
		$vBillNumber     = GetSQLValueString($rows['Bill_number'],'text');
		$vBillBank       = GetSQLValueString($rows['Bill_bank'],'text');
		$vLedgerNumber	 = GetSQLValueString($rows['ledger_number'],'text');
		$vBillValueDate	 = GetSQLValueString($rows['Bill_ValueDate'],'date');
		$vCurrencyCode	 = GetSQLValueString($rows['Currency_code'],'text');
		$vBillAmount	 = GetSQLValueString($rows['Bill_amount'],'double');
		$vBillAmount1	 = GetSQLValueString($rows['Bill_amount1'],'double');
		$vBillAmount2	 = GetSQLValueString($rows['Bill_amount2'],'double');
		$vLedgerActivity = GetSQLValueString($rows['Ledger_Activity'],'int');
		
		$sub_query  = " Select Count(*) From Bills ".
		              " Where Bill_Number  = '".$PBillNo."' ".
					  " And Ledger_Number = '".$PLedgerNo."' ";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$sub_query = " Insert Into Bills (Bill_number, journaldt_id1, ledger_number, Bill_bank, Bill_ValueDate, ".
						 " Currency_code, Bill_amount, Bill_amount1, Bill_amount2, Ledger_Activity ) ".
						 " Values ( ".$vBillNumber.", ".$PJournalDtId.", ".$vLedgerNumber.", ".$vBillBank.", ".$vBillValueDate.
						 ", ".$vCurrencyCode.", ".$vBillAmount.", ".$vBillAmount1.", ".$vBillAmount2.", ".$vLedgerActivity." ) ";
		}	
		else {
			$sub_query = " Update Bills Set journaldt_id2 = ".$PJournalDtId.
						 " Where Bill_Number = '".$PBillNo."' ".
						 " And Ledger_Number = '".$PLedgerNo."' ";
		}

		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			$vResult = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Bills',$vMessage);
		}
		
	}

	Return 1;	

}

function F_SynchroPurchasesJv($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select PurchaseJV_Id, PurchaseJV_Reference, PurchaseJV_Date, Supplier_Code, Currency_Code, Project_Code, Costcenter_Code, Journal_Id, ".
				 " JournalDt_ValueDate, Journal_Type, PurchaseJV_Edit, PurchaseJV_Posted, PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, ".
				 " PurchaseJV_DiscAmount, PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, Purchase_Remark, Purchase_Mode, User_Account, PurchaseJV_VAT, ".
				 " PurchaseJV_VatBase1, PurchaseJV_VatBase2, PurchaseJV_Percharge, PurchaseJV_ChargeAmount, PurchaseJV_ChargeAmount1, PurchaseJV_ChargeAmount2, ".
				 " PurchaseJV_ChargeDebit, PurchaseJv_ChargeCredit, PurchaseJV_CreditAccount, PurchaseJV_CheckAccount, PurchaseJV_CashAccount, PurchaseJV_Amount, ".
				 " PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, PurchaseJV_CheckNo, PurchaseJV_CheckDate, PurchaseJV_Bank, PurchaseJV_BankBranch, PurchaseJV_CreditCur, ".
				 " PurchaseJV_CashCur, PurchaseJV_CheckCur, PurchaseJV_RetentionPer, PurchaseJV_RetentionAmt1, PurchaseJV_RetentionAmt2, PurchaseJV_RetentionAmt, ".
				 " PurchaseJV_VatAccount, PurchaseJV_BelongsToGroup, PurchaseJV_InvoiceNo, PurchaseJV_Taxable, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, ".
				 " PurchaseJV_NoneTaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, PurchaseJV_VatCheck, PurchaseJV_type, PurchaseJV_OriginType, ".
				 " PurchaseJV_manualVat, PurchaseJV_VATPER, Owner_Branch, Destination_Branch, PurchaseJV_Syn_ID  ".
				 " From PurchasesJV ".
				 " Where PurchaseJV_Id = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vPurchaseJVSynID	  = GetSQLValueString($rows['PurchaseJV_Id'],'int');
		$vJournalSynID		  = GetSQLValueString($rows['Journal_Id'],'int');
		$vPurchaseJVReference = GetSQLValueString($rows['PurchaseJV_Reference'],'double');
		$vPurchaseJVDate	  = GetSQLValueString($rows['PurchaseJV_Date'],'date');
		$vJournalDtValueDate  = GetSQLValueString($rows['JournalDt_ValueDate'],'date');
		$vSupplierCode		  = GetSQLValueString($rows['Supplier_Code'],'text');
		$vCurrencyCode		  = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		  = GetSQLValueString($rows['Costcenter_Code'],'text');
		$vJournalType 		  = GetSQLValueString($rows['Journal_Type'],'text');
		$vPurchaseJVPosted	  = GetSQLValueString($rows['PurchaseJV_Posted'],'int');
		$vPurchaseJVEdit	  = GetSQLValueString($rows['PurchaseJV_Edit'],'int');
		$vPurchaseJVTotal		   = GetSQLValueString($rows['PurchaseJV_Total'],'double');
		$vPurchaseJVTotalBase1	   = GetSQLValueString($rows['PurchaseJV_TotalBase1'],'double');
		$vPurchaseJVTotalBase2	   = GetSQLValueString($rows['PurchaseJV_TotalBase2'],'double');
		$vPurchaseJVDiscAmount     = GetSQLValueString($rows['PurchaseJV_DiscAmount'],'double');
		$vPurchaseJVDiscBase1	   = GetSQLValueString($rows['PurchaseJV_DiscAmount1'],'double');
		$vPurchaseJVDiscBase2      = GetSQLValueString($rows['PurchaseJV_DiscAmount2'],'double');
		$vPurchaseRemark 		   = GetSQLValueString($rows['Purchase_Remark'],'text');
		$vPurchaseMode			   = GetSQLValueString($rows['Purchase_Mode'],'int');
		$vUserAccount 			   = GetSQLValueString($rows['User_Account'],'text');
		$vPurchaseJVVAT			   = GetSQLValueString($rows['PurchaseJV_VAT'],'double');
		$vPurchaseJVVATBase1	   = GetSQLValueString($rows['PurchaseJV_VatBase1'],'double');
		$vPurchaseJVVATBase2	   = GetSQLValueString($rows['PurchaseJV_VatBase2'],'double');
		$vPurchaseJV_Percharge	   = GetSQLValueString($rows['PurchaseJV_Percharge'],'double');
		$vPurchaseJVChargeAmount   = GetSQLValueString($rows['PurchaseJV_ChargeAmount'],'double');
		$vPurchaseJVChargeAmount1  = GetSQLValueString($rows['PurchaseJV_ChargeAmount1'],'double');
		$vPurchaseJVChargeAmount2  = GetSQLValueString($rows['PurchaseJV_ChargeAmount2'],'double');
		$vPurchaseJVChargeDebit    = GetSQLValueString($rows['PurchaseJV_ChargeDebit'],'text');
		$vPurchaseJvChargeCredit   = GetSQLValueString($rows['PurchaseJv_ChargeCredit'],'text');
		$vPurchaseJVCreditAccount  = GetSQLValueString($rows['PurchaseJV_CreditAccount'],'text');
		$vPurchaseJVCheckAccount   = GetSQLValueString($rows['PurchaseJV_CheckAccount'],'text');
		$vPurchaseJVCashAccount    = GetSQLValueString($rows['PurchaseJV_CashAccount'],'text');
		$vPurchaseJVAmount 		   = GetSQLValueString($rows['PurchaseJV_Amount'],'double');
		$vPurchaseJVAmountBase1    = GetSQLValueString($rows['PurchaseJV_AmountBase1'],'double');
		$vPurchaseJVAmountBase2    = GetSQLValueString($rows['PurchaseJV_AmountBase2'],'double');
		$vPurchaseJVCheckNo 	   = GetSQLValueString($rows['PurchaseJV_CheckNo'],'text');
		$vPurchaseJVCheckDate	   = GetSQLValueString($rows['PurchaseJV_CheckDate'],'date');
		$vPurchaseJVBank		   = GetSQLValueString($rows['PurchaseJV_Bank'],'text');
		$vPurchaseJVBankBranch 	   = GetSQLValueString($rows['PurchaseJV_BankBranch'],'text');
		$vPurchaseJVCreditCur 	   = GetSQLValueString($rows['PurchaseJV_CreditCur'],'text');
		$vPurchaseJVCashCur 	   = GetSQLValueString($rows['PurchaseJV_CashCur'],'text');
		$vPurchaseJVCheckCur	   = GetSQLValueString($rows['PurchaseJV_CheckCur'],'text');
		$vPurchaseJVRetentionPer   = GetSQLValueString($rows['PurchaseJV_RetentionPer'],'double');
		$vPurchaseJVRetentionAmt1  = GetSQLValueString($rows['PurchaseJV_RetentionAmt1'],'double');
		$vPurchaseJVRetentionAmt2  = GetSQLValueString($rows['PurchaseJV_RetentionAmt2'],'double');
		$vPurchaseJVRetentionAmt   = GetSQLValueString($rows['PurchaseJV_RetentionAmt'],'double');
		$vPurchaseJVVatAccount 	   = GetSQLValueString($rows['PurchaseJV_VatAccount'],'text');
		$vPurchaseJVBelongsToGroup = GetSQLValueString($rows['PurchaseJV_BelongsToGroup'],'int');
		$vPurchaseJVInvoiceNo	   = GetSQLValueString($rows['PurchaseJV_InvoiceNo'],'text');
		$vPurchaseJVTaxable		   = GetSQLValueString($rows['PurchaseJV_Taxable'],'double');
		$vPurchaseJVTaxableBase1   = GetSQLValueString($rows['PurchaseJV_TaxableBase1'],'double');
		$vPurchaseJVTaxableBase2   = GetSQLValueString($rows['PurchaseJV_TaxableBase2'],'double');
		$vPurchaseJVNoneTaxable	   = GetSQLValueString($rows['PurchaseJV_NoneTaxable'],'double');
		$vPurchJVNoneTaxableBase1  = GetSQLValueString($rows['PurchJV_NoneTaxableBase1'],'double');
		$vPurchJVNoneTaxableBase2  = GetSQLValueString($rows['PurchJV_NoneTaxableBase2'],'double');
		$vPurchaseJVVatCheck 	   = GetSQLValueString($rows['PurchaseJV_VatCheck'],'int');
		$vPurchaseJVType	       = GetSQLValueString($rows['PurchaseJV_type'],'text');
		$vPurchaseJVOriginType	   = GetSQLValueString($rows['PurchaseJV_OriginType'],'text');
		$vPurchaseJVManualVat 	   = GetSQLValueString($rows['PurchaseJV_manualVat'],'int');
		$vPurchaseJVVATPER		   = GetSQLValueString($rows['PurchaseJV_VATPER'],'double');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
		
		$sub_query  = " Select Count(*) From PurchasesJV ".
		              " Where PurchaseJV_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vPurchaseJvID = GetNextSequence1($PDestConn,'PurchasesJV_ID','');
			
			$sub_query = " Insert Into PurchasesJV (PurchaseJV_Id, PurchaseJV_Reference, PurchaseJV_Date, Supplier_Code, Currency_Code, Project_Code, Costcenter_Code, ".
						 " JournalDt_ValueDate, Journal_Type, PurchaseJV_Edit, PurchaseJV_Posted, PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, ".
						 " PurchaseJV_DiscAmount, PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, Purchase_Remark, Purchase_Mode, User_Account, PurchaseJV_VAT, ".
						 " PurchaseJV_VatBase1, PurchaseJV_VatBase2, PurchaseJV_Percharge, PurchaseJV_ChargeAmount, PurchaseJV_ChargeAmount1, PurchaseJV_ChargeAmount2, ".
						 " PurchaseJV_ChargeDebit, PurchaseJv_ChargeCredit, PurchaseJV_CreditAccount, PurchaseJV_CheckAccount, PurchaseJV_CashAccount, PurchaseJV_Amount, ".
						 " PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, PurchaseJV_CheckNo, PurchaseJV_CheckDate, PurchaseJV_Bank, PurchaseJV_BankBranch, PurchaseJV_CreditCur, ".
						 " PurchaseJV_CashCur, PurchaseJV_CheckCur, PurchaseJV_RetentionPer, PurchaseJV_RetentionAmt1, PurchaseJV_RetentionAmt2, PurchaseJV_RetentionAmt, ".
						 " PurchaseJV_VatAccount, PurchaseJV_BelongsToGroup, PurchaseJV_InvoiceNo, PurchaseJV_Taxable, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, ".
						 " PurchaseJV_NoneTaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, PurchaseJV_VatCheck, PurchaseJV_type, PurchaseJV_OriginType, ".
						 " PurchaseJV_manualVat, PurchaseJV_VATPER, Owner_Branch, Destination_Branch, PurchaseJV_Syn_ID ) ".
						 " Values ( ".$vPurchaseJvID.", ".$vPurchaseJVReference.", ".$vPurchaseJVDate.", ".$vSupplierCode.", ".$vCurrencyCode.", ".$vProjectCode.", ".$vCostcentCode.
						 ", ".$vJournalDtValueDate.", ".$vJournalType.", ".$vPurchaseJVEdit.", ".$vPurchaseJVPosted.", ".$vPurchaseJVTotal.", ".$vPurchaseJVTotalBase1.
						 ", ".$vPurchaseJVTotalBase2.", ".$vPurchaseJVDiscAmount.", ".$vPurchaseJVDiscBase1.", ".$vPurchaseJVDiscBase2.", ".$vPurchaseRemark.", ".$vPurchaseMode.
						 ", ".$vUserAccount.", ".$vPurchaseJVVAT.", ".$vPurchaseJVVATBase1.", ".$vPurchaseJVVATBase2.", ".$vPurchaseJV_Percharge.", ".$vPurchaseJVChargeAmount.
						 ", ".$vPurchaseJVChargeAmount1.", ".$vPurchaseJVChargeAmount2.", ".$vPurchaseJVChargeDebit.", ".$vPurchaseJvChargeCredit.", ".$vPurchaseJVCreditAccount.
						 ", ".$vPurchaseJVCheckAccount.", ".$vPurchaseJVCashAccount.", ".$vPurchaseJVAmount.", ".$vPurchaseJVAmountBase1.", ".$vPurchaseJVAmountBase2.
						 ", ".$vPurchaseJVCheckNo.", ".$vPurchaseJVCheckDate.", ".$vPurchaseJVBank.", ".$vPurchaseJVBankBranch.", ".$vPurchaseJVCreditCur.", ".$vPurchaseJVCashCur.
						 ", ".$vPurchaseJVCheckCur.", ".$vPurchaseJVRetentionPer.", ".$vPurchaseJVRetentionAmt1.", ".$vPurchaseJVRetentionAmt2.", ".$vPurchaseJVRetentionAmt.
						 ", ".$vPurchaseJVVatAccount.", ".$vPurchaseJVBelongsToGroup.", ".$vPurchaseJVInvoiceNo.", ".$vPurchaseJVTaxable.", ".$vPurchaseJVTaxableBase1.
						 ", ".$vPurchaseJVTaxableBase2.", ".$vPurchaseJVNoneTaxable.", ".$vPurchJVNoneTaxableBase1.", ".$vPurchJVNoneTaxableBase2.", ".$vPurchaseJVVatCheck.
						 ", ".$vPurchaseJVType.", ".$vPurchaseJVOriginType.", ".$vPurchaseJVManualVat.", ".$vPurchaseJVVATPER.", ".$vOwnerBranch.", ".$vDestinationBranch.
						 ", ".$vPurchaseJVSynID." )";
		}	
		//Case Record Exists - Update
		else {
			$query  = " Select PurchaseJV_ID From PurchasesJV ".
					  " Where PurchaseJV_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vPurchaseJvID = $result[0];
						 
			$sub_query = "  Update PurchasesJV Set PurchaseJV_Reference = ".$vPurchaseJVReference.", PurchaseJV_Date = ".$vPurchaseJVDate. 
						 ",	Supplier_Code = ".$vSupplierCode.", Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.
						 ", Costcenter_Code = ".$vCostcentCode.", JournalDt_ValueDate = ".$vJournalDtValueDate.", Journal_Type = ".$vJournalType.  
						 ",	PurchaseJV_Edit = ".$vPurchaseJVEdit.", PurchaseJV_Posted = ".$vPurchaseJVPosted.", PurchaseJV_Total = ".$vPurchaseJVTotal. 
						 ",	PurchaseJV_TotalBase1 = ".$vPurchaseJVTotalBase1.", PurchaseJV_TotalBase2 = ".$vPurchaseJVTotalBase2. 
						 ",	PurchaseJV_DiscAmount = ".$vPurchaseJVDiscAmount.", PurchaseJV_DiscAmount1 = ".$vPurchaseJVDiscBase1. 
						 ", PurchaseJV_DiscAmount2 = ".$vPurchaseJVDiscBase2.", Purchase_Remark = ".$vPurchaseRemark. 
						 ",	Purchase_Mode = ".$vPurchaseMode.", User_Account = ".$vUserAccount.", PurchaseJV_VAT = ".$vPurchaseJVVAT. 
						 ",	PurchaseJV_VatBase1 = ".$vPurchaseJVVATBase1.", PurchaseJV_VatBase2 = ".$vPurchaseJVVATBase2.
						 ", PurchaseJV_Percharge = ".$vPurchaseJV_Percharge. ", PurchaseJV_ChargeAmount = ".$vPurchaseJVChargeAmount.
						 ", PurchaseJV_ChargeAmount1 = ".$vPurchaseJVChargeAmount1.",	PurchaseJV_ChargeAmount2 = ".$vPurchaseJVChargeAmount2.
						 ",	PurchaseJV_ChargeDebit = ".$vPurchaseJVChargeDebit.",	PurchaseJv_ChargeCredit = ".$vPurchaseJvChargeCredit.
						 ", PurchaseJV_CreditAccount = ".$vPurchaseJVCreditAccount.",	PurchaseJV_CheckAccount = ".$vPurchaseJVCheckAccount.
						 ", PurchaseJV_CashAccount = ".$vPurchaseJVCashAccount.", PurchaseJV_Amount = ".$vPurchaseJVAmount.
						 ", PurchaseJV_AmountBase1 = ".$vPurchaseJVAmountBase1.", PurchaseJV_AmountBase2 = ".$vPurchaseJVAmountBase2.
						 ", PurchaseJV_CheckNo = ".$vPurchaseJVCheckNo.", PurchaseJV_CheckDate = ".$vPurchaseJVCheckDate.", PurchaseJV_Bank = ".$vPurchaseJVBank.
						 ", PurchaseJV_BankBranch = ".$vPurchaseJVBankBranch.", PurchaseJV_CreditCur = ".$vPurchaseJVCreditCur.
						 ", PurchaseJV_CashCur = ".$vPurchaseJVCashCur.", PurchaseJV_CheckCur = ".$vPurchaseJVCheckCur.
						 ", PurchaseJV_RetentionPer = ".$vPurchaseJVRetentionPer.", PurchaseJV_RetentionAmt1 = ".$vPurchaseJVRetentionAmt1.
						 ", PurchaseJV_RetentionAmt2 = ".$vPurchaseJVRetentionAmt2.", PurchaseJV_RetentionAmt = ".$vPurchaseJVRetentionAmt.
						 ", PurchaseJV_VatAccount = ".$vPurchaseJVVatAccount.", PurchaseJV_BelongsToGroup = ".$vPurchaseJVBelongsToGroup.
						 ",	PurchaseJV_InvoiceNo = ".$vPurchaseJVInvoiceNo.", PurchaseJV_Taxable = ".$vPurchaseJVTaxable.
						 ",	PurchaseJV_TaxableBase1 = ".$vPurchaseJVTaxableBase1.", PurchaseJV_TaxableBase2 = ".$vPurchaseJVTaxableBase2.
						 ",	PurchaseJV_NoneTaxable = ".$vPurchaseJVNoneTaxable.", PurchJV_NoneTaxableBase1 = ".$vPurchJVNoneTaxableBase1.
						 ",	PurchJV_NoneTaxableBase2 = ".$vPurchJVNoneTaxableBase2.", PurchaseJV_VatCheck = ".$vPurchaseJVVatCheck.
						 ",	PurchaseJV_type = ".$vPurchaseJVType.", PurchaseJV_OriginType = ".$vPurchaseJVOriginType.
						 ",	PurchaseJV_manualVat = ".$vPurchaseJVManualVat.", PurchaseJV_VATPER = ".$vPurchaseJVVATPER.
						 ", Destination_Branch = ".$vDestinationBranch.
						 "  Where PurchaseJV_Syn_ID = '".$PRecordID."'";
		}

		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update PurchasesJV Set PurchaseJV_Syn_ID = ".$vPurchaseJvID.
							 " Where PurchaseJV_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In PurchasesJVDt
			If ($vRecordExists > 0) {
				$query = "Delete From PurchasesJVDt Where PurchaseJV_ID = '".$vPurchaseJvID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
							
			//Insert Related Details From PurchasesJVDt
			$query = " Select PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date, Supplier_Code, Currency_Code, Ledger_Number, PurchaseJVDt_Description, ".
					 " Project_Code, Costcenter_Code, PurchaseJVDt_Quantity, PurchaseJVDt_Price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, ".
					 " PurchaseJVDt_DiscPer, PurchaseJVDt_DiscAmount, PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, PurchaseJVDt_ExpireDate, ".
					 " PurchaseJVDt_Posted, Journal_Type, PurchaseJVDt_Discount, PurchaseJVDt_Discount1, PurchaseJVDt_Discount2, PurchaseJVDt_Charge, ".
					 " PurchaseJVDt_Charge1, PurchaseJVDt_Charge2, PurchaseJvDt_VAT, PurchaseJVDt_Description2, PurchaseJVDTCalcTotal, ".
					 " PurchaseJVDt_Syn_ID, PurchaseJV_Syn_ID ".
					 " From PurchasesJVDt ".
					 " Where PurchaseJV_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vPurchaseJvDtID = GetNextSequence1($PDestConn,'PurchasesJVDt_ID','');
				
				$sub_query = " Insert Into PurchasesJVDt (PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date, Supplier_Code, Currency_Code, Ledger_Number, PurchaseJVDt_Description, ".
							 " Project_Code, Costcenter_Code, PurchaseJVDt_Quantity, PurchaseJVDt_Price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, ".
							 " PurchaseJVDt_DiscPer, PurchaseJVDt_DiscAmount, PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, PurchaseJVDt_ExpireDate, ".
							 " PurchaseJVDt_Posted, Journal_Type, PurchaseJVDt_Discount, PurchaseJVDt_Discount1, PurchaseJVDt_Discount2, PurchaseJVDt_Charge, ".
							 " PurchaseJVDt_Charge1, PurchaseJVDt_Charge2, PurchaseJvDt_VAT, PurchaseJVDt_Description2, PurchaseJVDTCalcTotal, ".
							 " PurchaseJVDt_Syn_ID, PurchaseJV_Syn_ID ) ".
							 " Values ( ".$vPurchaseJvDtID.", ".$vPurchaseJvID.", ".GetSQLValueString($rows['PurchaseJV_Date'],'date').", ".GetSQLValueString($rows['Supplier_Code'],'text').
							 ", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['PurchaseJVDt_Description'],'text').
							 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['Costcenter_Code'],'text').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Quantity'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_Price'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_PriceBase1'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_DiscPer'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_DiscAmount'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_DiscAmount1'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_Discount2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_ExpireDate'],'date').", ".GetSQLValueString($rows['PurchaseJVDt_Posted'],'int').
							 ", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['PurchaseJVDt_Discount'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Discount1'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_Discount2'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Charge'],'double').", ".GetSQLValueString($rows['PurchaseJVDt_Charge1'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Charge2'],'double').", ".GetSQLValueString($rows['PurchaseJvDt_VAT'],'int').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Description2'],'text').", ".GetSQLValueString($rows['PurchaseJVDTCalcTotal'],'double').
							 ", ".GetSQLValueString($rows['PurchaseJVDt_Id'],'int').", ".$vPurchaseJVSynID." )";
								 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
						
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['PurchaseJVDt_Id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'PurchasesJVDt',$vMessage);
						
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
						
				$sub_query1 = " Update PurchasesJV Set Journal_ID = '".$vJournalID."' ".
							  " Where PurchaseJV_ID = '".$vPurchaseJvID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesJV',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, PurchaseJV_ID, Owner_Branch ".
					 " From PurchasesJV Where PurchaseJV_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID    = $sub_result[0];
		$vJournalType  = $sub_result[1];
		$vPurchaseJvID = $sub_result[2];
		$vOwnerBranch  = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query  = "Delete From PurchasesJVDt Where PurchaseJV_ID = '".$vPurchaseJvID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$vResult  = 'T';
			
			$query  = "Delete From PurchasesJV Where PurchaseJV_ID = '".$vPurchaseJvID."'";
			$result = mysql_query($query, $PDestConn);
				
			if ($vJournalID != -1) {
				$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}	
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'PurchasesJVDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vPurchaseJvID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}

function F_SynchroSalesJv($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	global $CompanyName;
	
	If ($PState == 'I' || $PState == 'U') {
		$query = " Select SalesJV_Id, SalesJV_Reference, SalesJV_Date, Client_Code, Currency_Code, Project_Code, Costcenter_Code, Journal_Id, ".
				 " JournalDt_ValueDate, Journal_Type, SalesJV_Edit, SalesJV_Posted, SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, ".
				 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, Sales_Remark, Sales_Mode, User_Account, SalesJV_VAT, ".
				 " SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, ".
				 " SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, SalesJV_Paid, SalesJv_AmountPaid, SalesJv_AmountPaidBase1, ".
				 " SalesJv_AmountPaidBase2, SalesJv_UnpaidAmnt, SalesJv_UnpaidAmntBase1, SalesJv_UnpaidAmntBase2, SalesJV_JvRef, SalesJV_Goods, ".
				 " SalesJV_Declaration, SalesJV_Packs, SalesJV_Weight, SalesJV_ValueGoods, SalesJV_PaymentMode, SalesJV_CheckNo, SalesJV_ChkDate, ".
				 " SalesJV_Bank, SalesJV_Type, SalesJV_PaidDate, Area_Code, SalesJV_BelongsToGroup, SalesJV_DownPayment, SalesJV_DownPaymentBase1, ".
				 " SalesJV_DownPaymentBase2, SalesJV_VatAccount, SalesJV_SettledAmount, SalesJV_SettledAmount1, SalesJV_SettledAmount2, SalesJV_DiscountPer, ".
				 " SalesJv_TruckNo, SalesJv_Driver, SalesJv_Destination, SalesJV_DiscountAccount, Salesman_Code, SalesJV_FormalityName, SalesJV_blnno, ".
				 " SalesJV_PortOfLoading, SalesJV_PortOfDischarge, SalesJV_VesselName, SalesJV_ContainerNo, SalesJV_Bulletin, SalesJV_Commodity,  ".
				 " SalesJV_ShippingLine, SalesJV_CustomReceipt, SalesJV_CustomDate, SalesJV_Freight, salesJV_ImportExport, SalesJV_PakingOfGrossWeight, ".
				 " SalesJV_ValueOfGoods, Salesjv_Reservation, Salesjv_CheckIn, Salesjv_CheckOut, Salesjv_RoomType, SalesJV_formalitydate,  ".
				 " SalesJV_formalityvalue, SalesJv_ManualNo, SalesJv_OldData, Owner_Branch, Destination_Branch, SalesJV_Syn_ID ".
				 " From SalesJV ".
				 " Where SalesJV_Id = '".$PRecordID."'";
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vSalesJVSynID	 	  = GetSQLValueString($rows['SalesJV_Id'],'int');
		$vJournalSynID		  = GetSQLValueString($rows['Journal_Id'],'int');
		$vClientID			  = GetSQLValueString($rows['Client_Id'],'int');
		$vSalesmanID		  = GetSQLValueString($rows['Salesman_Id'],'int');
		$vProjectID			  = GetSQLValueString($rows['Project_Id'],'int');
		$vCostCentID		  = GetSQLValueString($rows['CostCent_Id'],'int');
		$vCurrencyID		  = GetSQLValueString($rows['Currency_Id'],'int');
		$vAreaID			  = GetSQLValueString($rows['Area_Id'],'int');
		$vSalesJVReference 	  = GetSQLValueString($rows['SalesJV_Reference'],'double');
		$vSalesJVDate		  = GetSQLValueString($rows['SalesJV_Date'],'date');
		$vJournalDtValueDate  = GetSQLValueString($rows['JournalDt_ValueDate'],'date');
		$vClientCode		  = GetSQLValueString($rows['Client_Code'],'text');
		$vCurrencyCode		  = GetSQLValueString($rows['Currency_Code'],'text');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostcentCode		  = GetSQLValueString($rows['Costcenter_Code'],'text');
		$vJournalType 		  = GetSQLValueString($rows['Journal_Type'],'text');
		$vSalesJVPosted	 	  = GetSQLValueString($rows['SalesJV_Posted'],'int');
		$vSalesJVEdit		  = GetSQLValueString($rows['SalesJV_Edit'],'int');
		$vSalesJVTotal		  = GetSQLValueString($rows['SalesJV_Total'],'double');
		$vSalesJVTotalBase1	  = GetSQLValueString($rows['SalesJV_TotalBase1'],'double');
		$vSalesJVTotalBase2	  = GetSQLValueString($rows['SalesJV_TotalBase2'],'double');
		$vSalesJVDiscAmount   = GetSQLValueString($rows['SalesJV_DiscountAmount'],'double');
		$vSalesJVDiscBase1	  = GetSQLValueString($rows['SalesJV_DiscountAmount1'],'double');
		$vSalesJVDiscBase2    = GetSQLValueString($rows['SalesJV_DiscountAmount2'],'double');
		$vSalesRemark 		  = GetSQLValueString($rows['Sales_Remark'],'text');
		$vSalesMode			  = GetSQLValueString($rows['Sales_Mode'],'int');
		$vUserAccount 		  = GetSQLValueString($rows['User_Account'],'text');
		$vSalesJVVAT		  = GetSQLValueString($rows['SalesJV_VAT'],'double');
		$vSalesJVVATBase1	  = GetSQLValueString($rows['SalesJV_VatBase1'],'double');
		$vSalesJVVATBase2	  = GetSQLValueString($rows['SalesJV_VatBase2'],'double');
		$vSalesJVVatCheck 	  = GetSQLValueString($rows['SalesJV_VatCheck'],'int');
		$vSalesJVTaxable		   = GetSQLValueString($rows['SalesJV_Taxable'],'double');
		$vSalesJVTaxableBase1      = GetSQLValueString($rows['SalesJV_TaxableBase1'],'double');
		$vSalesJVTaxableBase2  	   = GetSQLValueString($rows['SalesJV_TaxableBase2'],'double');
		$vSalesJVNoneTaxable	   = GetSQLValueString($rows['SalesJV_NoneTaxable'],'double');
		$vSalesJVNoneTaxableBase1  = GetSQLValueString($rows['SalesJV_NoneTaxableBase1'],'double');
		$vSalesJVNoneTaxableBase2  = GetSQLValueString($rows['SalesJV_NoneTaxableBase2'],'double');
		$vSalesJVPaid			   = GetSQLValueString($rows['SalesJV_Paid'],'int');
		$vSalesJvAmountPaid  	   = GetSQLValueString($rows['SalesJv_AmountPaid'],'double');
		$vSalesJvAmountPaidBase1   = GetSQLValueString($rows['SalesJv_AmountPaidBase1'],'double');
		$vSalesJvAmountPaidBase2   = GetSQLValueString($rows['SalesJv_AmountPaidBase2'],'double');
		$vSalesJvUnpaidAmnt 	   = GetSQLValueString($rows['SalesJv_UnpaidAmnt'],'double');
		$vSalesJvUnpaidAmntBase1   = GetSQLValueString($rows['SalesJv_UnpaidAmntBase1'],'double');
		$vSalesJvUnpaidAmntBase2   = GetSQLValueString($rows['SalesJv_UnpaidAmntBase2'],'double');
		$vSalesJVJvRef 			   = GetSQLValueString($rows['SalesJV_JvRef'],'double');
		$vSalesJVGoods		 	   = GetSQLValueString($rows['SalesJV_Goods'],'text');
		$vSalesJVDeclaration 	   = GetSQLValueString($rows['SalesJV_Declaration'],'text');
		$vSalesJVPacks 	 		   = GetSQLValueString($rows['SalesJV_Packs'],'text');
		$vSalesJVWeight 	  	   = GetSQLValueString($rows['SalesJV_Weight'],'text');
		$vSalesJVValueGoods	 	   = GetSQLValueString($rows['SalesJV_ValueGoods'],'text');
		$vSalesJVPaymentMode	   = GetSQLValueString($rows['SalesJV_PaymentMode'],'text');
		$vSalesJVCheckNo	 	   = GetSQLValueString($rows['SalesJV_CheckNo'],'text');
		$vSalesJVChkDate	 	   = GetSQLValueString($rows['SalesJV_ChkDate'],'date');
		$vSalesJVBank	 	 	   = GetSQLValueString($rows['SalesJV_Bank'],'text');
		$vSalesJVType	 	       = GetSQLValueString($rows['SalesJV_Type'],'text');
		$vSalesJVPaidDate	 	   = GetSQLValueString($rows['SalesJV_PaidDate'],'date');
		$vAreaCode				   = GetSQLValueString($rows['Area_Code'],'text');
		$vSalesJVBelongsToGroup    = GetSQLValueString($rows['SalesJV_BelongsToGroup'],'int');
		$vSalesJVDownPayment	   = GetSQLValueString($rows['SalesJV_DownPayment'],'double');
		$vSalesJVDownPaymentBase1  = GetSQLValueString($rows['SalesJV_DownPaymentBase1'],'double');
		$vSalesJVDownPaymentBase2  = GetSQLValueString($rows['SalesJV_DownPaymentBase2'],'double');
		$vSalesJVVatAccount 	   = GetSQLValueString($rows['SalesJV_VatAccount'],'text');
		$vSalesJVSettledAmount	   = GetSQLValueString($rows['SalesJV_SettledAmount'],'double');
		$vSalesJVSettledAmount1    = GetSQLValueString($rows['SalesJV_SettledAmount1'],'double');
		$vSalesJVSettledAmount2    = GetSQLValueString($rows['SalesJV_SettledAmount2'],'double');
		$vSalesJVDiscountPer 	   = GetSQLValueString($rows['SalesJV_DiscountPer'],'double');
		$vSalesJvTruckNo		   = GetSQLValueString($rows['SalesJv_TruckNo'],'text');
		$vSalesJvDriver 	 	   = GetSQLValueString($rows['SalesJv_Driver'],'text');
		$vSalesJvDestination	   = GetSQLValueString($rows['SalesJv_Destination'],'text');
		$vSalesJVDiscountAccount   = GetSQLValueString($rows['SalesJV_DiscountAccount'],'text');
		$vSalesmanCode			   = GetSQLValueString($rows['Salesman_Code'],'text');
		
		$vFormalityName			   = GetSQLValueString($rows['SalesJV_FormalityName'],'text');
		$vSalesJVblnno			   = GetSQLValueString($rows['SalesJV_blnno'],'text');
		$vPortOfLoading			   = GetSQLValueString($rows['SalesJV_PortOfLoading'],'text');
		$vPortOfDischarge		   = GetSQLValueString($rows['SalesJV_PortOfDischarge'],'text');
		$vVesselName			   = GetSQLValueString($rows['SalesJV_VesselName'],'text');
		$vContainerNo			   = GetSQLValueString($rows['SalesJV_ContainerNo'],'text');
		$vBulletin				   = GetSQLValueString($rows['SalesJV_Bulletin'],'text');
		$vCommodity			  	   = GetSQLValueString($rows['SalesJV_Commodity'],'text');
		$vShippingLine		  	   = GetSQLValueString($rows['SalesJV_ShippingLine'],'text');
		$vCustomReceipt		  	   = GetSQLValueString($rows['SalesJV_CustomReceipt'],'text');
		$vCustomDate		  	   = GetSQLValueString($rows['SalesJV_CustomDate'],'date');
		$vFreight			  	   = GetSQLValueString($rows['SalesJV_Freight'],'text');
		$vImportExport		  	   = GetSQLValueString($rows['salesJV_ImportExport'],'text');
		$vPakingOfGrossWeight  	   = GetSQLValueString($rows['SalesJV_PakingOfGrossWeight'],'text');
		$vValueOfGoods  		   = GetSQLValueString($rows['SalesJV_ValueOfGoods'],'text');
		$vReservation  	   		   = GetSQLValueString($rows['Salesjv_Reservation'],'date');
		$vCheckIn  	  			   = GetSQLValueString($rows['Salesjv_CheckIn'],'date');
		$vCheckOut  	   		   = GetSQLValueString($rows['Salesjv_CheckOut'],'date');
		$vRoomType  			   = GetSQLValueString($rows['Salesjv_RoomType'],'text');
		$vFormalityDate  		   = GetSQLValueString($rows['SalesJV_formalitydate'],'date');
		$vFormalityValue  		   = GetSQLValueString($rows['SalesJV_formalityvalue'],'text');
		$vSalesJvManualNo  		   = GetSQLValueString($rows['SalesJv_ManualNo'],'text');
		$vSalesJvOldData  		   = GetSQLValueString($rows['SalesJv_OldData'],'int');
		$vOwnerBranch 			   = GetSQLValueString($rows['Owner_Branch'],'text');
		$vDestinationBranch        = GetSQLValueString($rows['Destination_Branch'],'text');
		
			
		$sub_query  = " Select Count(*) From SalesJV ".
		              " Where SaleJV_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vRecordExists = $sub_result[0];
		
		//Case Record Doesn't Exists - Insert
		If ($vRecordExists == 0) {	
			$vSalesJvID = GetNextSequence1($PDestConn,'SalesJV_Id','');
			
			$sub_query = " Insert Into SalesJV (SalesJV_Id, SalesJV_Reference, SalesJV_Date, Client_Code, Currency_Code, Project_Code, Costcenter_Code, ".
						 " JournalDt_ValueDate, Journal_Type, SalesJV_Edit, SalesJV_Posted, SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, ".
						 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, Sales_Remark, Sales_Mode, User_Account, SalesJV_VAT, ".
						 " SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, ".
						 " SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, SalesJV_Paid, SalesJv_AmountPaid, SalesJv_AmountPaidBase1, ".
						 " SalesJv_AmountPaidBase2, SalesJv_UnpaidAmnt, SalesJv_UnpaidAmntBase1, SalesJv_UnpaidAmntBase2, SalesJV_JvRef, SalesJV_Goods, ".
						 " SalesJV_Declaration, SalesJV_Packs, SalesJV_Weight, SalesJV_ValueGoods, SalesJV_PaymentMode, SalesJV_CheckNo, SalesJV_ChkDate, ".
						 " SalesJV_Bank, SalesJV_Type, SalesJV_PaidDate, Area_Code, SalesJV_BelongsToGroup, SalesJV_DownPayment, SalesJV_DownPaymentBase1, ".
						 " SalesJV_DownPaymentBase2, SalesJV_VatAccount, SalesJV_SettledAmount, SalesJV_SettledAmount1, SalesJV_SettledAmount2, SalesJV_DiscountPer, ".
						 " SalesJv_TruckNo, SalesJv_Driver, SalesJv_Destination, SalesJV_DiscountAccount, Salesman_Code, SalesJV_FormalityName, SalesJV_blnno, ".
						 " SalesJV_PortOfLoading, SalesJV_PortOfDischarge, SalesJV_VesselName, SalesJV_ContainerNo, SalesJV_Bulletin, SalesJV_Commodity,  ".
						 " SalesJV_ShippingLine, SalesJV_CustomReceipt, SalesJV_CustomDate, SalesJV_Freight, salesJV_ImportExport, SalesJV_PakingOfGrossWeight, ".
						 " SalesJV_ValueOfGoods, Salesjv_Reservation, Salesjv_CheckIn, Salesjv_CheckOut, Salesjv_RoomType, SalesJV_formalitydate,  ".
						 " SalesJV_formalityvalue, SalesJv_ManualNo, SalesJv_OldData, Owner_Branch, Destination_Branch, SalesJV_Syn_ID )  ".
						 " Values ( ".$vSalesJvID.", ".$vSalesJVReference.", ".$vSalesJVDate.", ".$vClientCode.", ".$vCurrencyCode.", ".$vProjectCode.", ".$vCostcentCode.
						 ", ".$vJournalDtValueDate.", ".$vJournalType.", ".$vSalesJVEdit.", ".$vSalesJVPosted.", ".$vSalesJVTotal.", ".$vSalesJVTotalBase1.
						 ", ".$vSalesJVTotalBase2.", ".$vSalesJVDiscAmount.", ".$vSalesJVDiscBase1.", ".$vSalesJVDiscBase2.", ".$vSalesRemark.", ".$vSalesMode.
						 ", ".$vUserAccount.", ".$vSalesJVVAT.", ".$vSalesJVVATBase1.", ".$vSalesJVVATBase2.", ".$vSalesJVVatCheck.", ".$vSalesJVTaxable.
						 ", ".$vSalesJVTaxableBase1.", ".$vSalesJVTaxableBase2.", ".$vSalesJVNoneTaxable.", ".$vSalesJVNoneTaxableBase1.", ".$vSalesJVNoneTaxableBase2.
						 ", ".$vSalesJVPaid.", ".$vSalesJvAmountPaid.", ".$vSalesJvAmountPaidBase1.", ".$vSalesJvAmountPaidBase2.", ".$vSalesJvUnpaidAmnt.
						 ", ".$vSalesJvUnpaidAmntBase1.", ".$vSalesJvUnpaidAmntBase2.", ".$vSalesJVJvRef.", ".$vSalesJVGoods.", ".$vSalesJVDeclaration.", ".$vSalesJVPacks.
						 ", ".$vSalesJVWeight.", ".$vSalesJVValueGoods.", ".$vSalesJVPaymentMode.", ".$vSalesJVCheckNo.", ".$vSalesJVChkDate.", ".$vSalesJVBank.
						 ", ".$vSalesJVType.", ".$vSalesJVPaidDate.", ".$vAreaCode.", ".$vSalesJVBelongsToGroup.", ".$vSalesJVDownPayment.", ".$vSalesJVDownPaymentBase1.
						 ", ".$vSalesJVDownPaymentBase2.", ".$vSalesJVVatAccount.", ".$vSalesJVSettledAmount.", ".$vSalesJVSettledAmount1.", ".$vSalesJVSettledAmount2.
						 ", ".$vSalesJVDiscountPer.", ".$vSalesJvTruckNo.", ".$vSalesJvDriver.", ".$vSalesJvDestination.", ".$vSalesJVDiscountAccount.", ".$vSalesmanCode.
						 ", ".$vFormalityName.", ".$vSalesJVblnno.", ".$vPortOfLoading.", ".$vPortOfDischarge.", ".$vVesselName.", ".$vContainerNo.", ".$vBulletin.
						 ", ".$vCommodity.", ".$vShippingLine.", ".$vCustomReceipt.", ".$vCustomDate.", ".$vFreight.", ".$vImportExport.", ".$vPakingOfGrossWeight.
						 ", ".$vValueOfGoods.", ".$vReservation.", ".$vCheckIn.", ".$vCheckOut.", ".$vRoomType.", ".$vFormalityDate.", ".$vFormalityValue.
						 ", ".$vSalesJvManualNo.", ".$vSalesJvOldData.", ".$vOwnerBranch.", ".$vDestinationBranch.", ".$vSalesJVSynID." )";
		}	
		
		//Case Record Exists - Update
		else {
			$query  = " Select SalesJV_ID From SalesJV ".
					  " Where SalesJV_Syn_ID = '".$PRecordID."'";
			$result = selectData($PDestConn, $query);
			$vSalesJvID = $result[0];
						 
			$sub_query = "  Update SalesJV Set SalesJV_Reference = ".$vSalesJVReference.", SalesJV_Date = ".$vSalesJVDate. 
						 ",	Client_Code = ".$vClientCode.", Currency_Code = ".$vCurrencyCode.", Project_Code = ".$vProjectCode.
						 ", Costcenter_Code = ".$vCostcentCode.", JournalDt_ValueDate = ".$vJournalDtValueDate.", Journal_Type = ".$vJournalType.  
						 ",	SalesJV_Edit = ".$vSalesJVEdit.", SalesJV_Posted = ".$vSalesJVPosted.", SalesJV_Total = ".$vSalesJVTotal. 
						 ",	SalesJV_TotalBase1 = ".$vSalesJVTotalBase1.", SalesJV_TotalBase2 = ".$vSalesJVTotalBase2. 
						 ",	SalesJV_DiscountAmount = ".$vSalesJVDiscAmount.", SalesJV_DiscountAmount1 = ".$vSalesJVDiscBase1. 
						 ", SalesJV_DiscountAmount2 = ".$vSalesJVDiscBase2.", Sales_Remark = ".$vSalesRemark. 
						 ",	Sales_Mode = ".$vSalesMode.", User_Account = ".$vUserAccount.", SalesJV_VAT = ".$vSalesJVVAT. 
						 ",	SalesJV_VatBase1 = ".$vSalesJVVATBase1.", SalesJV_VatBase2 = ".$vSalesJVVATBase2.
						 ", SalesJV_VatCheck = ".$vSalesJVVatCheck. ", SalesJV_Taxable = ".$vSalesJVTaxable.
						 ", SalesJV_TaxableBase1 = ".$vSalesJVTaxableBase1.",	SalesJV_TaxableBase2 = ".$vSalesJVTaxableBase2.
						 ",	SalesJV_NoneTaxable = ".$vSalesJVNoneTaxable.",	SalesJV_NoneTaxableBase1 = ".$vSalesJVNoneTaxableBase1.
						 ", SalesJV_NoneTaxableBase2 = ".$vSalesJVNoneTaxableBase2.",	SalesJV_Paid = ".$vSalesJVPaid.
						 ", SalesJv_AmountPaid = ".$vSalesJvAmountPaid.", SalesJv_AmountPaidBase1 = ".$vSalesJvAmountPaidBase1.
						 ", SalesJv_AmountPaidBase2 = ".$vSalesJvAmountPaidBase2.", SalesJv_UnpaidAmnt = ".$vSalesJvUnpaidAmnt.
						 ", SalesJv_UnpaidAmntBase1 = ".$vSalesJvUnpaidAmntBase1.", SalesJv_UnpaidAmntBase2 = ".$vSalesJvUnpaidAmntBase2.
						 ", SalesJV_JvRef = ".$vSalesJVJvRef.", SalesJV_Goods = ".$vSalesJVGoods.
						 ", SalesJV_Declaration = ".$vSalesJVDeclaration.", SalesJV_Packs = ".$vSalesJVPacks.
						 ", SalesJV_Weight = ".$vSalesJVWeight.", SalesJV_ValueGoods = ".$vSalesJVValueGoods.
						 ", SalesJV_PaymentMode = ".$vSalesJVPaymentMode.", SalesJV_CheckNo = ".$vSalesJVCheckNo.
						 ", SalesJV_ChkDate = ".$vSalesJVChkDate.", SalesJV_Bank = ".$vSalesJVBank.
						 ",	SalesJV_Type = ".$vSalesJVType.", SalesJV_PaidDate = ".$vSalesJVPaidDate.
						 ",	Area_Code = ".$vAreaCode.", SalesJV_BelongsToGroup = ".$vSalesJVBelongsToGroup.
						 ",	SalesJV_DownPayment = ".$vSalesJVDownPayment.", SalesJV_DownPaymentBase1 = ".$vSalesJVDownPaymentBase1.
						 ",	SalesJV_DownPaymentBase2 = ".$vSalesJVDownPaymentBase2.", SalesJV_VatAccount = ".$vSalesJVVatAccount.
						 ",	SalesJV_SettledAmount = ".$vSalesJVSettledAmount.", SalesJV_SettledAmount1 = ".$vSalesJVSettledAmount1.
						 ",	SalesJV_SettledAmount2 = ".$vSalesJVSettledAmount2.", SalesJV_DiscountPer = ".$vSalesJVDiscountPer.
						 ",	SalesJv_TruckNo = ".$vSalesJvTruckNo.", SalesJv_Driver = ".$vSalesJvDriver.
						 ",	SalesJv_Destination = ".$vSalesJvDestination.", SalesJV_DiscountAccount = ".$vSalesJVDiscountAccount.
						 ",	Salesman_Code = ".$vSalesmanCode.", Destination_Branch = ".$vDestinationBranch.
						 ", SalesJV_FormalityName = ".$vFormalityName.", SalesJV_blnno = ".$vSalesJVblnno.", SalesJV_PortOfLoading = ".$vPortOfLoading.
						 ",	SalesJV_PortOfDischarge = ".$vPortOfDischarge.", SalesJV_VesselName = ".$vVesselName.", SalesJV_ContainerNo = ".$vContainerNo.
						 ",	SalesJV_Bulletin = ".$vBulletin.", SalesJV_Commodity = ".$vCommodity.", SalesJV_ShippingLine = ".$vShippingLine.
						 ",	SalesJV_CustomReceipt = ".$vCustomReceipt.", SalesJV_CustomDate = ".$vCustomDate.", SalesJV_Freight = ".$vFreight.
						 ",	salesJV_ImportExport = ".$vImportExport.", SalesJV_PakingOfGrossWeight = ".$vPakingOfGrossWeight.", SalesJV_ValueOfGoods = ".$vValueOfGoods.
						 ",	Salesjv_Reservation = ".$vReservation.", Salesjv_CheckIn = ".$vCheckIn.", Salesjv_CheckOut = ".$vCheckOut.
						 ",	Salesjv_RoomType = ".$vRoomType.", SalesJV_formalitydate = ".$vFormalityDate.", SalesJV_formalityvalue = ".$vFormalityValue.
						 ",	SalesJv_ManualNo = ".$vSalesJvManualNo.", SalesJv_OldData = ".$vSalesJvOldData.
						 "  Where SalesJV_Syn_ID = '".$PRecordID."'";
		}
		
		
		//echo $sub_query; exit;	 
		$sub_result=mysql_query($sub_query,$PDestConn);

		if ($sub_result) {
			
			/*If ($vRecordExists == 0) {	
				//InCase Insert, Update Related ID In Source/Local DB
				$sub_query = " Update SalesJV Set SalesJV_Syn_ID = ".$vSalesJvID.
							 " Where SalesJV_ID = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);			 
			}*/
			
			//InCase Update, Delete All Related Details In SalesJVDt
			If ($vRecordExists > 0) {
				$query = "Delete From SalesJVDt Where SalesJV_ID = '".$vSalesJvID."'";
				$result = mysql_query($query, $PDestConn);
			}
			
							
			//Insert Related Details From SalesJVDt
			$query = " Select SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Client_Code, Currency_Code, Ledger_Number, SalesJVDt_Description, ".
					 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, ".
					 " SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDt_ExpireDate, ".
					 " SalesJVDt_Posted, Journal_Type, SalesJVDt_VAT, SalesJvDt_Description2, SalesJVDTCalcTotal, Salesman_Code, Area_code, ".
					 " SalesJvDt_ManualNo, SalesJVDt_Syn_ID, SalesJV_Syn_ID ".
					 " From SalesJVDt ".
					 " Where SalesJV_ID = '".$PRecordID."'";
			//echo $query; exit;		 
			$result=mysql_query($query,$PLocConn) or die(mysql_error());
			while($rows=mysql_fetch_assoc($result)){
				$vSalesJvDtID = GetNextSequence1($PDestConn,'SalesJVDt_Id','');
								
				$sub_query = " Insert Into SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Client_Code, Currency_Code, Ledger_Number, SalesJVDt_Description, ".
							 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, ".
							 " SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDt_ExpireDate, ".
							 " SalesJVDt_Posted, Journal_Type, SalesJVDt_VAT, SalesJvDt_Description2, SalesJVDTCalcTotal, Salesman_Code, Area_code, ".
							 " SalesJvDt_ManualNo, SalesJVDt_Syn_ID, SalesJV_Syn_ID ) ".
							 " Values ( ".$vSalesJvDtID.", ".$vSalesJvID.", ".GetSQLValueString($rows['SalesJV_Date'],'date').", ".GetSQLValueString($rows['Client_Code'],'text').
							 ", ".GetSQLValueString($rows['Currency_Code'],'text').", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['SalesJVDt_Description'],'text').
							 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['Costcenter_Code'],'text').
							 ", ".GetSQLValueString($rows['SalesJVDt_Quantity'],'double').", ".GetSQLValueString($rows['SalesJVDt_Price'],'double').
							 ", ".GetSQLValueString($rows['SalesJVDt_PriceBase1'],'double').", ".GetSQLValueString($rows['SalesJVDt_PriceBase2'],'double').
							 ", ".GetSQLValueString($rows['SalesJVDt_DiscountPer'],'double').", ".GetSQLValueString($rows['SalesJVDt_DiscountAmount'],'double').
							 ", ".GetSQLValueString($rows['SalesJVDt_DiscountAmount1'],'double').", ".GetSQLValueString($rows['SalesJVDt_DiscountAmount2'],'double').
							 ", ".GetSQLValueString($rows['SalesJVDt_ExpireDate'],'date').", ".GetSQLValueString($rows['SalesJVDt_Posted'],'int').
							 ", ".GetSQLValueString($rows['Journal_Type'],'text').", ".GetSQLValueString($rows['SalesJVDt_VAT'],'int').
							 ", ".GetSQLValueString($rows['SalesJvDt_Description2'],'text').", ".GetSQLValueString($rows['SalesJVDTCalcTotal'],'double').
							 ", ".GetSQLValueString($rows['Salesman_Code'],'text').", ".GetSQLValueString($rows['Area_code'],'text').
							 ", ".GetSQLValueString($rows['SalesJvDt_ManualNo'],'text').", ".GetSQLValueString($rows['SalesJVDt_Id'],'int').", ".$vSalesJVSynID." )";
								 
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);	
				if ($sub_result) {
					$vResult = 'T';
						
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert ID= ".$rows['SalesJVDt_Id']." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'SalesJVDt',$vMessage);
						
					break;
				}
			}

			if ($vResult == 'T') {
				// Synchro Related JV	
				$vJournalID	 = F_SynchroRelatedJv($vJournalSynID, 'I', $PLocConn, $PDestConn);
						
				$sub_query1 = " Update SalesJV Set Journal_ID = '".$vJournalID."' ".
							  " Where SalesJV_ID = '".$vSalesJvID."'";
				$sub_result1=mysql_query($sub_query1,$PDestConn);
			}	
			
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SalesJV',$vMessage);
		}
	
	}
	else if ($PState == 'D') {
		$sub_query = " Select Journal_Id, Journal_Type, SalesJV_ID, Owner_Branch ".
					 " From SalesJV Where SalesJV_Syn_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vJournalID    = $sub_result[0];
		$vJournalType  = $sub_result[1];
		$vSalesJvID	   = $sub_result[2];
		$vOwnerBranch  = $sub_result[3];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$query  = "Delete From SalesJVDt Where SalesJV_ID = '".$vSalesJvID."'";
		$result = mysql_query($query, $PDestConn);
			
		if ($result) {
			$vResult  = 'T';
			
			$query  = "Delete From SalesJV Where SalesJV_ID = '".$vSalesJvID."'";
			$result = mysql_query($query, $PDestConn);
				
			if ($vJournalID != -1) {
				$query = "Delete From Journal Where Journal_Id = '".$vJournalID."'";
				$result = mysql_query($query, $PDestConn);
			}	
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SalesJVDt',$vMessage);
		}
		
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vSalesJvID,'',$vOwnerBranch);
	}	
			
	
	
	Return $vResult;
}


function F_SynchroProject($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Project_Code, Project_Name, Project_Deactivate, Project_date, Project_description, ".
				 " Supplier_code, Project_BelongsToGroup, Synchronized, Project_posted, Project_Memo, ".
				 " Parent_Code, Project_Picture, Project_Metier, Project_Technician, Owner_Branch ".
				 " From Project ".
				 " Where Upper(Project_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vProjectId			 = GetSQLValueString($rows['Project_Id'],'int');
		$vProjectCode    	 = GetSQLValueString($rows['Project_Code'],'text');
		$vProjectName      	 = GetSQLValueString($rows['Project_Name'],'text');
		$vProjectDeactivate	 = GetSQLValueString($rows['Project_Deactivate'],'int');
		$vProjectDate		 = GetSQLValueString($rows['Project_date'],'date');
		$vProjectDescription = GetSQLValueString($rows['Project_description'],'text');
		$vSupplierCode		 = GetSQLValueString($rows['Supplier_code'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['Project_BelongsToGroup'],'int');
		$vSynchronized		 = GetSQLValueString($rows['Synchronized'],'int');
		$vProjectPosted      = GetSQLValueString($rows['Project_posted'],'int');
		$vProjectMemo		 = GetSQLValueString($rows['Project_Memo'],'text');
		$vProjectPicture	 = GetSQLValueString($rows['Project_Picture'],'text');
		$vParentCode		 = GetSQLValueString($rows['Parent_Code'],'text');
		$vProjectMetier		 = GetSQLValueString($rows['Project_Metier'],'text');
		$vProjectTechnician  = GetSQLValueString($rows['Project_Technician'],'text');
		//$vParentId			 = GetSQLValueString($rows['Parent_Id'],'int');
		//$vCreationDate		 = GetSQLValueString($rows['Project_CreationDate'],'date');
		$vOwnerBranch 		 = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Project ".
						  " Where Upper(Project_Code) = Upper(".$vProjectCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Project_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vProjectCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Project',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Project Set Synchronized = 0 ".
						  " Where Upper(Project_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Project ".
						  " Where Upper(Project_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Project (Project_Code, Project_Name, Project_Deactivate, Project_date, ".
							 " Project_description, Supplier_code, Project_BelongsToGroup, Synchronized, Project_posted, ".
							 " Project_Memo, Parent_Code, Project_Picture, Project_Metier, Project_Technician, Owner_Branch ) ".
							 " Values ( ".$vProjectCode.", ".$vProjectName.", ".$vProjectDeactivate.", ".$vProjectDate.
							 ", ".$vProjectDescription.", ".$vSupplierCode.", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vProjectPosted.
							 ", ".$vProjectMemo.", ".$vParentCode.", ".$vProjectPicture.", ".$vProjectMetier.", ".$vProjectTechnician.
							 ", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Project Set Project_Code = ".$vProjectCode.", Project_Name = ".$vProjectName.
							 ", Project_Deactivate = ".$vProjectDeactivate.", Project_date = ".$vProjectDate.
							 ", Project_description = ".$vProjectDescription.", Supplier_code = ".$vSupplierCode.
							 ", Project_BelongsToGroup = ".$vBelongsToGroup.", Project_posted = ".$vProjectPosted.
							 ", Project_Memo = ".$vProjectMemo.", Parent_Code = ".$vParentCode.
							 ", Project_Picture = ".$vProjectPicture.", Project_Metier = ".$vProjectMetier.
							 ", Project_Technician = ".$vProjectTechnician.
							 "  Where Upper(Project_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Project Set Synchronized = 1 ".
							  " Where Upper(Project_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Project',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Project_Code, Owner_Branch ".
					 " From Project Where Upper(Project_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vProjectCode = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Project Where Upper(Project_Code) = Upper('".$vProjectCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Project',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vProjectCode = trim($vProjectCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vProjectCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroCostCent($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Costcent_code, Costcent_name, Costcent_Deactivate, Ledger_number, ".
				 " Costcent_BelongsToGroup, Synchronized, Costcent_Posted, Parent_Code, ".
				 " Costcent_CreationDate, Owner_Branch ".
				 " From CostCent ".
				 " Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vCostcentId		 = GetSQLValueString($rows['CostCent_Id'],'int');
		$vCostcentCode    	 = GetSQLValueString($rows['Costcent_code'],'text');
		$vCostcentName       = GetSQLValueString($rows['Costcent_name'],'text');
		$vCostcentDeactivate = GetSQLValueString($rows['Costcent_Deactivate'],'int');
		$vLedgerNumber		 = GetSQLValueString($rows['Ledger_number'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['Costcent_BelongsToGroup'],'int');
		$vSynchronized		 = GetSQLValueString($rows['Synchronized'],'int');
		$vCostcentPosted     = GetSQLValueString($rows['Costcent_Posted'],'int');
		$vParentCode		 = GetSQLValueString($rows['Parent_Code'],'text');
		//$vParentId			 = GetSQLValueString($rows['Parent_Id'],'int');
		$vCreationDate		 = GetSQLValueString($rows['Costcent_CreationDate'],'date');
		$vOwnerBranch 		 = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From CostCent ".
						  " Where Upper(CostCent_Code) = Upper(".$vCostcentCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And CostCent_Id != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vCostcentCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'CostCent',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update CostCent Set Synchronized = 0 ".
						  " Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From CostCent ".
						  " Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into CostCent (Costcent_code, Costcent_name, Costcent_Deactivate, Ledger_number, ".
							 " Costcent_BelongsToGroup, Synchronized, Costcent_Posted, Parent_Code, ".
							 " Costcent_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vCostcentCode.", ".$vCostcentName.", ".$vCostcentDeactivate.", ".$vLedgerNumber.
							 ", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vCostcentPosted.", ".$vParentCode.
							 ", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update CostCent Set Costcent_code = ".$vCostcentCode.", Costcent_name = ".$vCostcentName.
							 ", Costcent_Deactivate = ".$vCostcentDeactivate.", Ledger_number = ".$vLedgerNumber.
							 ", Costcent_BelongsToGroup = ".$vBelongsToGroup.", Costcent_Posted = ".$vCostcentPosted.
							 ", Parent_Code = ".$vParentCode.", Costcent_CreationDate = ".$vCreationDate.
							 "  Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update CostCent Set Synchronized = 1 ".
							  " Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'CostCent',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select CostCent_Code, Owner_Branch ".
					 " From CostCent Where Upper(CostCent_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCostcentCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From CostCent Where Upper(CostCent_Code) = Upper('".$vCostcentCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'CostCent',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vCostcentCode = trim($vCostcentCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vCostcentCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroWarehouse($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Warehouse_code, Warehouse_name, Ledger_number, Warehouse_Category, Warehouse_BelongsToGroup, ".
				 " Synchronized, Warehouse_Posted, Warehouse_transit, warehouse_production, Parent_Code, ".
				 " Warehouse_CreationDate, Owner_Branch ".
				 " From Warehouse ".
				 " Where Upper(Warehouse_Code)	= Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vWarehouseId		  = GetSQLValueString($rows['Warehouse_Id'],'int');
		$vWarehouseCode    	  = GetSQLValueString($rows['Warehouse_code'],'text');
		$vWarehouseName       = GetSQLValueString($rows['Warehouse_name'],'text');
		$vLedgerNumber		  = GetSQLValueString($rows['Ledger_number'],'text');
		$vWarehouseCategory	  = GetSQLValueString($rows['Warehouse_Category'],'int');
		$vBelongsToGroup	  = GetSQLValueString($rows['Warehouse_BelongsToGroup'],'int');
		$vSynchronized		  = GetSQLValueString($rows['Synchronized'],'int');
		$vWarehousePosted     = GetSQLValueString($rows['Warehouse_Posted'],'int');
		$vWarehouseTransit    = GetSQLValueString($rows['Warehouse_transit'],'int');
		$vWarehouseProduction = GetSQLValueString($rows['warehouse_production'],'int');
		$vParentCode		  = GetSQLValueString($rows['Parent_Code'],'text');
		//$vParentId			  = GetSQLValueString($rows['Parent_Id'],'int');
		$vCreationDate		  = GetSQLValueString($rows['Warehouse_CreationDate'],'date');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Warehouse ".
						  " Where Upper(Warehouse_code) = Upper(".$vWarehouseCode.") ";
					
			//If ($PState == 'U')	$sub_query = $sub_query." And Warehouse_ID != '".$PRecordID."'";		
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vWarehouseCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Warehouse',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Warehouse Set Synchronized = 0 ".
						  " Where Upper(Warehouse_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Warehouse ".
						  " Where Upper(Warehouse_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$vWarehouseID = GetNextSequence1($PDestConn,'warehouse_id','');
				
				$sub_query = " Insert Into Warehouse (Warehouse_Id, Warehouse_code, Warehouse_name, Ledger_number, Warehouse_Category, Warehouse_BelongsToGroup, ".
							 " Synchronized, Warehouse_Posted, Warehouse_transit, warehouse_production, Parent_Code, Warehouse_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vWarehouseID.", ".$vWarehouseCode.", ".$vWarehouseName.", ".$vLedgerNumber.", ".$vWarehouseCategory.", ".$vBelongsToGroup.
							 ", ".$vSynchronized.", ".$vWarehousePosted.", ".$vWarehouseTransit.", ".$vWarehouseProduction.", ".$vParentCode.
							 ", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Warehouse Set Warehouse_code = ".$vWarehouseCode.", Warehouse_name = ".$vWarehouseName.
							 ", Ledger_number = ".$vLedgerNumber.", Warehouse_Category = ".$vWarehouseCategory.
							 ", Warehouse_BelongsToGroup = ".$vBelongsToGroup.", Warehouse_Posted = ".$vWarehousePosted.
							 ", Warehouse_transit = ".$vWarehouseTransit.", warehouse_production = ".$vWarehouseProduction.
							 ", Parent_Code = ".$vParentCode.", Warehouse_CreationDate = ".$vCreationDate.
							 "  Where Upper(Warehouse_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Warehouse Set Synchronized = 1 ".
							  " Where Upper(Warehouse_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Warehouse',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Warehouse_Code, Owner_Branch ".
					 " From Warehouse Where Upper(Warehouse_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vWarehouseCode = $sub_result[0];
		$vOwnerBranch   = $sub_result[1];
		
		$query = "Delete From Warehouse Where Upper(Warehouse_Code) = Upper('".$vWarehouseCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Warehouse',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch   = trim($vOwnerBranch,"'");
		$vWarehouseCode = trim($vWarehouseCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vWarehouseCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroArea($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Area_Code, Area_Name, Area_BelongsToGroup, Synchronized, Area_posted, ".
				 " Area_Tariff, Parent_Code, Area_CreationDate, Owner_Branch ".
				 " From Area ".
				 " Where Upper(Area_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vAreaId		  = GetSQLValueString($rows['Area_Id'],'int');
		$vAreaCode    	  = GetSQLValueString($rows['Area_Code'],'text');
		$vAreaName        = GetSQLValueString($rows['Area_Name'],'text');
		$vBelongsToGroup  = GetSQLValueString($rows['Area_BelongsToGroup'],'int');
		$vSynchronized	  = GetSQLValueString($rows['Synchronized'],'int');
		$vAreaPosted      = GetSQLValueString($rows['Area_posted'],'int');
		$vAreaTariff      = GetSQLValueString($rows['Area_Tariff'],'int');
		$vParentCode	  = GetSQLValueString($rows['Parent_Code'],'text');
		//$vParentId		  = GetSQLValueString($rows['Parent_Id'],'int');
		$vCreationDate	  = GetSQLValueString($rows['Area_CreationDate'],'date');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Area ".
						  " Where Upper(Area_Code) = Upper(".$vAreaCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Area_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vAreaCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Area',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Area Set Synchronized = 0 ".
						  " Where Upper(Area_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Area ".
						  " Where Upper(Area_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Area (Area_Code, Area_Name, Area_BelongsToGroup, Synchronized, Area_posted, ".
							 " Area_Tariff, Parent_Code, Area_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vAreaCode.", ".$vAreaName.", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vAreaPosted.
							 ", ".$vAreaTariff.", ".$vParentCode.", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Area Set Area_Code = ".$vAreaCode.", Area_Name = ".$vAreaName.
							 ", Area_BelongsToGroup = ".$vBelongsToGroup.", Area_posted = ".$vAreaPosted.
							 ", Area_Tariff = ".$vAreaTariff.", Parent_Code = ".$vParentCode.
							 ", Area_CreationDate = ".$vCreationDate.
							 "  Where Upper(Area_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Area Set Synchronized = 1 ".
							  " Where Upper(Area_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Area',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Area_Code, Owner_Branch ".
					 " From Area Where Upper(Area_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vAreaCode = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Area Where Upper(Area_Code) = Upper('".$vAreaCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Area',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vAreaCode    = trim($vAreaCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vAreaCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroCategory($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Category_Code, Category_Name, Category_BelongsToGroup, Synchronized, Category_Posted, ".
				 " Category_Price1, Category_Price2, Category_Price3, Category_Price4, Category_Price5, Category_Price6, ".
				 " Category_CreationDate, Owner_Branch ".
				 " From Category ".
				 " Where Upper(Category_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vCategoryId	  = GetSQLValueString($rows['Category_Id'],'int');
		$vCategoryCode    = GetSQLValueString($rows['Category_Code'],'text');
		$vCategoryName    = GetSQLValueString($rows['Category_Name'],'text');
		$vBelongsToGroup  = GetSQLValueString($rows['Category_BelongsToGroup'],'int');
		$vSynchronized	  = GetSQLValueString($rows['Synchronized'],'int');
		$vCategoryPosted  = GetSQLValueString($rows['Category_Posted'],'int');
		$vCategoryPrice1  = GetSQLValueString($rows['Category_Price1'],'double');
		$vCategoryPrice2  = GetSQLValueString($rows['Category_Price2'],'double');
		$vCategoryPrice3  = GetSQLValueString($rows['Category_Price3'],'double');
		$vCategoryPrice4  = GetSQLValueString($rows['Category_Price4'],'double');
		$vCategoryPrice5  = GetSQLValueString($rows['Category_Price5'],'double');
		$vCategoryPrice6  = GetSQLValueString($rows['Category_Price6'],'double');
		$vCreationDate	  = GetSQLValueString($rows['Category_CreationDate'],'date');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From Category ".
						  " Where Upper(Category_Code) = Upper(".$vCategoryCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Category_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vCategoryCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Category',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Category Set Synchronized = 0 ".
						  " Where Upper(Category_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Category ".
						  " Where Upper(Category_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Category (Category_Code, Category_Name, Category_BelongsToGroup, Synchronized, Category_Posted, ".
							 " Category_Price1, Category_Price2, Category_Price3, Category_Price4, Category_Price5, Category_Price6, ".
							 " Category_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vCategoryCode.", ".$vCategoryName.", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vCategoryPosted.
							 ", ".$vCategoryPrice1.", ".$vCategoryPrice2.", ".$vCategoryPrice3.", ".$vCategoryPrice4.", ".$vCategoryPrice5.", ".$vCategoryPrice6.
							 ", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Category Set Category_Code = ".$vCategoryCode.", Category_Name = ".$vCategoryName.
							 ", Category_BelongsToGroup = ".$vBelongsToGroup.", Category_Posted = ".$vCategoryPosted.
							 ", Category_Price1 = ".$vCategoryPrice1.", Category_Price2 = ".$vCategoryPrice2.", Category_Price3 = ".$vCategoryPrice3.
							 ", Category_Price4 = ".$vCategoryPrice4.", Category_Price5 = ".$vCategoryPrice5.", Category_Price6 = ".$vCategoryPrice6.
							 ", Category_CreationDate = ".$vCreationDate.
							 "  Where Upper(Category_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';		

				$sub_query  = " Update Category Set Synchronized = 1 ".
							  " Where Upper(Category_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);						
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Category',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Category_Id, Owner_Branch ".
					 " From Category Where Upper(Category_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCategoryCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From Category Where Upper(Category_Code) = Upper('".$vCategoryCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Category',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vCategoryCode = trim($vCategoryCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vCategoryCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroLedgerGrp($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select LedgerGrp_Code, LedgerGrp_Name, LedgerGrp_BelongsToGrp, LedgerGrp_Type, LedgerGrp_Reference, ".
				 " Synchronized, LedgerGrp_Posted, LedgerGrp_CreationDate, Owner_Branch ".
				 " From LedgerGrp ".
				 " Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vLedgerGrpId		  = GetSQLValueString($rows['LedgerGrp_Id'],'int');
		$vLedgerGrpCode  	  = GetSQLValueString($rows['LedgerGrp_Code'],'text');
		$vLedgerGrpName		  = GetSQLValueString($rows['LedgerGrp_Name'],'text');
		$vBelongsToGroup	  = GetSQLValueString($rows['LedgerGrp_BelongsToGrp'],'int');
		$vLedgerGrpType 	  = GetSQLValueString($rows['LedgerGrp_Type'],'int');
		$vLedgerGrpReference  = GetSQLValueString($rows['LedgerGrp_Reference'],'double');
		$vSynchronized	      = GetSQLValueString($rows['Synchronized'],'int');
		$vLedgerGrpPosted     = GetSQLValueString($rows['LedgerGrp_Posted'],'int');
		//$vProjectCode	      = GetSQLValueString($rows['Project_Code'],'text');
		//$vProjectId		 	  = GetSQLValueString($rows['Project_Id'],'int');
		$vCreationDate	 	  = GetSQLValueString($rows['LedgerGrp_CreationDate'],'date');
		$vOwnerBranch 	 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		/*$vCheckProjectID   = F_Check_ProjectID($PDestConn, $vProjectId);
		
		if ($vCheckProjectID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Project not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'LedgerGrp',$vMessage);
			
			Return $vResult;
		}*/
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From LedgerGrp ".
						  " Where Upper(LedgerGrp_Code) = Upper(".$vLedgerGrpCode.") ";
							  
			//If ($PState == 'U')	$sub_query = $sub_query." And LedgerGrp_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vLedgerGrpCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'LedgerGrp',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update LedgerGrp Set Synchronized = 0 ".
						  " Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From LedgerGrp ".
						  " Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into LedgerGrp (LedgerGrp_Code, LedgerGrp_Name, LedgerGrp_BelongsToGrp, LedgerGrp_Type, LedgerGrp_Reference, ".
							 " Synchronized, LedgerGrp_Posted, LedgerGrp_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vLedgerGrpCode.", ".$vLedgerGrpName.", ".$vBelongsToGroup.", ".$vLedgerGrpType.", ".$vLedgerGrpReference.
							 ", ".$vSynchronized.", ".$vLedgerGrpPosted.", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update LedgerGrp Set LedgerGrp_Code = ".$vLedgerGrpCode.", LedgerGrp_Name = ".$vLedgerGrpName.
							 ", LedgerGrp_BelongsToGrp = ".$vBelongsToGroup.", LedgerGrp_Type = ".$vLedgerGrpType.
							 ", LedgerGrp_Posted = ".$vLedgerGrpPosted.", LedgerGrp_CreationDate = ".$vCreationDate.
							 "  Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update LedgerGrp Set Synchronized = 1 ".
							  " Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'LedgerGrp',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select LedgerGrp_Code, Owner_Branch ".
					 " From LedgerGrp Where Upper(LedgerGrp_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vLedgerGrpCode = $sub_result[0];
		$vOwnerBranch   = $sub_result[1];
		
		$query = "Delete From LedgerGrp Where Upper(LedgerGrp_Code) = Upper('".$vLedgerGrpCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'LedgerGrp',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch   = trim($vOwnerBranch,"'");
		$vLedgerGrpCode = trim($vLedgerGrpCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vLedgerGrpCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroGrouping($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Group_Code, Group_Name, Group_BelongsToGroup, Group_Commission, Group_Commission2, Group_Posted, ".
				 " Synchronized, Group_Parent, Group_discountPer, Parent_Code, Group_CreationDate, ".
				 " Inventory_ledger, Charge_ledger, Revenue_ledger, Promotion_ledger, Discount_Ledger, Vat_ledger, Owner_Branch ".
				 " From Grouping ".
				 " Where Upper(Group_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vGroupId		 	= GetSQLValueString($rows['Group_Id'],'int');
		$vGroupCode  		= GetSQLValueString($rows['Group_Code'],'text');
		$vGroupName		 	= GetSQLValueString($rows['Group_Name'],'text');
		$vBelongsToGroup	= GetSQLValueString($rows['Group_BelongsToGroup'],'int');
		$vGroupCommission 	= GetSQLValueString($rows['Group_Commission'],'double');
		$vGroupCommission2  = GetSQLValueString($rows['Group_Commission2'],'double');
		$vSynchronized	    = GetSQLValueString($rows['Synchronized'],'int');
		$vGroupPosted       = GetSQLValueString($rows['Group_Posted'],'int');
		$vGroupParent       = GetSQLValueString($rows['Group_Parent'],'int');
		$vGroupDiscountPer  = GetSQLValueString($rows['Group_discountPer'],'double');
		$vParentCode	    = GetSQLValueString($rows['Parent_Code'],'text');
		//$vParentId		 	= GetSQLValueString($rows['Parent_Id'],'int');
		$vCreationDate	 	= GetSQLValueString($rows['Group_CreationDate'],'date');
		$vInventoryLedger	= GetSQLValueString($rows['Inventory_ledger'],'text');
		$vChargeLedger	    = GetSQLValueString($rows['Charge_ledger'],'text');
		$vRevenueLedger	    = GetSQLValueString($rows['Revenue_ledger'],'text');
		$vPromotionLedger	= GetSQLValueString($rows['Promotion_ledger'],'text');
		$vDiscountLedger	= GetSQLValueString($rows['Discount_Ledger'],'text');
		$vVatLedger	     	= GetSQLValueString($rows['Vat_ledger'],'text');
		$vOwnerBranch 	 	= GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From Grouping ".
						  " Where Upper(Group_Code) = Upper(".$vGroupCode.") ";
							  
			//If ($PState == 'U')	$sub_query = $sub_query." And Group_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vGroupCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Grouping',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Grouping Set Synchronized = 0 ".
						  " Where Upper(Group_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Grouping ".
						  " Where Upper(Group_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Grouping (Group_Code, Group_Name, Group_BelongsToGroup, Group_Commission, Group_Commission2, ".
							 " Group_Posted, Synchronized, Group_Parent, Group_discountPer, Parent_Code, Group_CreationDate, ".
							 " Inventory_ledger, Charge_ledger, Revenue_ledger, Promotion_ledger, Discount_Ledger, Vat_ledger, Owner_Branch ) ".
							 " Values ( ".$vGroupCode.", ".$vGroupName.", ".$vBelongsToGroup.", ".$vGroupCommission.", ".$vGroupCommission2.
							 ", ".$vGroupPosted.", ".$vSynchronized.", ".$vGroupParent.", ".$vGroupDiscountPer.", ".$vParentCode.
							 ", ".$vCreationDate.", ".$vInventoryLedger.", ".$vChargeLedger.", ".$vRevenueLedger.", ".$vPromotionLedger.
							 ", ".$vDiscountLedger.", ".$vVatLedger.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Grouping Set Group_Code = ".$vGroupCode.", Group_Name = ".$vGroupName.
							 ", Group_BelongsToGroup = ".$vBelongsToGroup.", Group_Commission = ".$vGroupCommission.
							 ", Group_Commission2 = ".$vGroupCommission2.", Group_Posted = ".$vGroupPosted.
							 ", Group_Parent = ".$vGroupParent.", Group_discountPer = ".$vGroupDiscountPer.
							 ", Parent_Code = ".$vParentCode.
							 ", Group_CreationDate = ".$vCreationDate.", Inventory_ledger = ".$vInventoryLedger.
							 ", Charge_ledger = ".$vChargeLedger.", Revenue_ledger = ".$vRevenueLedger.
							 ", Promotion_ledger = ".$vPromotionLedger.", Discount_Ledger = ".$vDiscountLedger.
							 ", Vat_ledger = ".$vVatLedger.
							 "  Where Upper(Group_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				//InCase Update, Delete All Related Details In TransactionSetup
				If ($vRecordExists > 0) {
					$query = "Delete From TransactionSetup Where Upper(Group_Code) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From TransactionSetup
				$query = " Select Auto, Group_code, Journal_type, Trans_RMAcc, Trans_RMVatAcc, Trans_NonRMAcc, Trans_NonRMVatAcc, ".
						 " Trans_RMTTCIncAcc, Trans_NonRMTTCIncAcc, Trans_Currency, Trans_DefaultCur, Trans_DirectStkDbt, Trans_DirectStkCrd, ".
						 " Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc, Trans_DiscountAcc, ".
						 " Trans_PromotionAcc, Trans_VATAccount ".
						 " From TransactionSetup ".
						 " Where Upper(Group_Code) =  Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
										
					$sub_query = " Insert Into TransactionSetup (Group_code, Journal_type, Trans_RMAcc, Trans_RMVatAcc, Trans_NonRMAcc, Trans_NonRMVatAcc, ".
								 " Trans_RMTTCIncAcc, Trans_NonRMTTCIncAcc, Trans_Currency, Trans_DefaultCur, Trans_DirectStkDbt, Trans_DirectStkCrd, ".
								 " Trans_DirectStkCur, Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc, Trans_DiscountAcc, ".	
								 " Trans_PromotionAcc, Trans_VATAccount ) ".
								 " Values ( ".GetSQLValueString($rows['Group_code'],'text').", ".GetSQLValueString($rows['Journal_type'],'text').
								 ", ".GetSQLValueString($rows['Trans_RMAcc'],'text').", ".GetSQLValueString($rows['Trans_RMVatAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_NonRMAcc'],'text').", ".GetSQLValueString($rows['Trans_NonRMVatAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_RMTTCIncAcc'],'text').", ".GetSQLValueString($rows['Trans_NonRMTTCIncAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_Currency'],'text').", ".GetSQLValueString($rows['Trans_DefaultCur'],'int').
								 ", ".GetSQLValueString($rows['Trans_DirectStkDbt'],'text').", ".GetSQLValueString($rows['Trans_DirectStkCrd'],'text').
								 ", ".GetSQLValueString($rows['Trans_DirectStkCur'],'text').", ".GetSQLValueString($rows['Trans_wasteDebitAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_wasteCreditAcc'],'text').", ".GetSQLValueString($rows['Trans_wasteDifferenceAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_DiscountAcc'],'text').", ".GetSQLValueString($rows['Trans_PromotionAcc'],'text').
								 ", ".GetSQLValueString($rows['Trans_VATAccount'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		

						$sub_query  = " Update Grouping Set Synchronized = 1 ".
									  " Where Upper(Group_Code) = Upper('".$PRecordCode."')";
						$sub_result=mysql_query($sub_query,$PLocConn);
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Group_code']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'TransactionSetup',$vMessage);
						
						break;
					}	
				}
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Grouping',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Group_Code, Owner_Branch ".
					 " From Grouping Where Upper(Group_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vGroupCode   = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Grouping Where Upper(Group_Code) = Upper('".$vGroupCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Grouping',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vGroupCode   = trim($vGroupCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vGroupCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroSubGroup($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select SubGroup_Code, SubGroup_Name, SubGroup_BelongsToGroup, Synchronized, SubGroup_Posted, ".
				 " Group_Code, Parent_Code, SubGroup_CreationDate, SubGroup_UpdateDate, SubGroup_Parent, ".
				 " SubGroup_Type, SubGroup_SequentialNumber, Owner_Branch ".
				 " From SubGroup ".
				 " Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vSubGroupId	   = GetSQLValueString($rows['SubGroup_Id'],'int');
		$vSubGroupCode     = GetSQLValueString($rows['SubGroup_Code'],'text');
		$vSubGroupName     = GetSQLValueString($rows['SubGroup_Name'],'text');
		$vBelongsToGroup   = GetSQLValueString($rows['SubGroup_BelongsToGroup'],'int');
		$vSynchronized	   = GetSQLValueString($rows['Synchronized'],'int');
		$vSubGroupPosted   = GetSQLValueString($rows['SubGroup_Posted'],'int');
		$vParentCode	   = GetSQLValueString($rows['Parent_Code'],'text');
		//$vParentId		   = GetSQLValueString($rows['Parent_Id'],'int');
		$vGroupCode		   = GetSQLValueString($rows['Group_Code'],'text');
		//$vGroupId		   = GetSQLValueString($rows['Group_Id'],'int');
		$vCreationDate	   = GetSQLValueString($rows['SubGroup_CreationDate'],'date');
		$vUpdateDate	   = GetSQLValueString($rows['SubGroup_UpdateDate'],'date');
		$vSubGroupParent   = GetSQLValueString($rows['SubGroup_Parent'],'int');
		$vSubGroupType 	   = GetSQLValueString($rows['SubGroup_Type'],'text');
		$vSequentialNumber = GetSQLValueString($rows['SubGroup_SequentialNumber'],'text');
		//$vSubGroupPolicy   = GetSQLValueString($rows['SubGroup_Policy'],'int');
		$vOwnerBranch 	   = GetSQLValueString($rows['Owner_Branch'],'text');
		
		$vCheckGroupCode  = F_Check_GroupCode($PDestConn, $rows['Group_Code']);
		
		if ($vCheckGroupCode == 0 ) {
			$vResult  = 'P';
			$vMessage = 'Group not found.';
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SubGroup',$vMessage);
			
			Return $vResult;
		}
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From SubGroup ".
						  " Where Upper(SubGroup_Code) = Upper(".$vSubGroupCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And SubGroup_ID != '".$PRecordCode."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vSubGroupCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SubGroup',$vMessage);
		}
		

						
		if ($vResult != 'P') {
			$sub_query  = " Update SubGroup Set Synchronized = 0 ".
						  " Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
							  
			$sub_query  = " Select Count(*) From SubGroup ".
						  " Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
				
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into SubGroup (SubGroup_Code, SubGroup_Name, SubGroup_BelongsToGroup, Synchronized, SubGroup_Posted, ".
							 " Group_Code, Parent_Code, SubGroup_CreationDate, SubGroup_UpdateDate, SubGroup_Parent, ".
							 " SubGroup_Type, SubGroup_SequentialNumber, Owner_Branch ) ".
							 " Values ( ".$vSubGroupCode.", ".$vSubGroupName.", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vSubGroupPosted.
							 ", ".$vGroupCode.", ".$vParentCode.", ".$vCreationDate.", ".$vUpdateDate.", ".$vSubGroupParent.
							 ", ".$vSubGroupType.", ".$vSequentialNumber.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update SubGroup Set SubGroup_Code = ".$vSubGroupCode.", SubGroup_Name = ".$vSubGroupName.
							 ", SubGroup_BelongsToGroup = ".$vBelongsToGroup.", SubGroup_Posted = ".$vSubGroupPosted.
							 ", Group_Code = ".$vGroupCode.", Parent_Code = ".$vParentCode.", SubGroup_CreationDate = ".$vCreationDate.
							 ", SubGroup_UpdateDate = ".$vUpdateDate.", SubGroup_Type = ".$vSubGroupType.", SubGroup_Parent = ".$vSubGroupParent.
							 ", SubGroup_SequentialNumber = ".$vSequentialNumber.
							 "  Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';		

				$sub_query  = " Update SubGroup Set Synchronized = 1 ".
							  " Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);						
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'SubGroup',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select SubGroup_Code, Owner_Branch ".
					 " From SubGroup Where Upper(SubGroup_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vSubGroupCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From SubGroup Where Upper(SubGroup_Code) = Upper('".$vSubGroupCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'SubGroup',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vSubGroupCode = trim($vSubGroupCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vSubGroupCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroAccType($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Acctype_code, Acctype_name, Acctype_BelongsToGroup, Acctype_ledger, Synchronized, Acctype_Posted, ".
				 " Acctype_Link, Acctype_Type, Acctype_SameLength, Owner_Branch ".
				 " From Acctype ".
				 " Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vAcctypeId	    	 = GetSQLValueString($rows['Acctype_Id'],'int');
		$vAcctypeCode   	 = GetSQLValueString($rows['Acctype_code'],'text');
		$vAcctypeName    	 = GetSQLValueString($rows['Acctype_name'],'text');
		$vBelongsToGroup	 = GetSQLValueString($rows['Acctype_BelongsToGroup'],'int');
		$vAcctypeLedger 	 = GetSQLValueString($rows['Acctype_ledger'],'text');
		$vSynchronized	 	 = GetSQLValueString($rows['Synchronized'],'int');
		$vAcctypePosted	     = GetSQLValueString($rows['Acctype_Posted'],'int');
		$vAcctypeLink   	 = GetSQLValueString($rows['Acctype_Link'],'double');
		$vAcctypeType   	 = GetSQLValueString($rows['Acctype_Type'],'int');
		$vAcctypeSameLength  = GetSQLValueString($rows['Acctype_SameLength'],'int');
		//$vProjectCode		 = GetSQLValueString($rows['Project_Code'],'text');
		//$vProjectId		  	 = GetSQLValueString($rows['Project_Id'],'int');
		//$vLedgerId		 	 = GetSQLValueString($rows['Ledger_Id'],'int');
		//$vCreationDate	 	 = GetSQLValueString($rows['Acctype_CreationDate'],'date');
		$vOwnerBranch 	 	 = GetSQLValueString($rows['Owner_Branch'],'text');
		
		$vCheckLedgerCode   = F_Check_LedgerCode($PDestConn, $rows['Acctype_ledger']);
		//$vCheckProjectID  = F_Check_ProjectID($PDestConn, $vProjectId);
		
		if ($vCheckLedgerCode == 0) {
			$vResult  = 'P';
			$vMessage = 'Ledger not found.';
			$vMessage = GetSQLValueString("Insert/Update Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Acctype',$vMessage);
			
			Return $vResult;
		}
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From Acctype ".
						  " Where Upper(Acctype_Code) = Upper(".$vAcctypeCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Acctype_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vAcctypeCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Acctype',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Acctype Set Synchronized = 0 ".
						  " Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Acctype ".
						  " Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$vAcctypeID = GetNextSequence1($PDestConn,'Acctype_increment','');
				
				$sub_query = " Insert Into Acctype (Acctype_increment, Acctype_code, Acctype_name, Acctype_BelongsToGroup, Acctype_ledger, Synchronized, ".
				             " Acctype_Posted, Acctype_Link, Acctype_Type, Acctype_SameLength, Owner_Branch ) ".
							 " Values ( ".$vAcctypeID.", ".$vAcctypeCode.", ".$vAcctypeName.", ".$vBelongsToGroup.", ".$vAcctypeLedger.", ".$vSynchronized.
							 ", ".$vAcctypePosted.", ".$vAcctypeLink.", ".$vAcctypeType.", ".$vAcctypeSameLength.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Acctype Set Acctype_code = ".$vAcctypeCode.", Acctype_name = ".$vAcctypeName.
							 ", Acctype_BelongsToGroup = ".$vBelongsToGroup.", Acctype_ledger = ".$vAcctypeLedger.
							 ", Acctype_Posted = ".$vAcctypePosted.", Acctype_Link = ".$vAcctypeLink.
							 ", Acctype_Type = ".$vAcctypeType.", Acctype_SameLength = ".$vAcctypeSameLength.
							 "  Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				//InCase Update, Delete All Related Details In AccTypeSetup
				If ($vRecordExists > 0) {
					$query = "Delete From AccTypeSetup Where Upper(Type_Code) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From AccTypeSetup
				$query = " Select AccTypeSetupInc, Type_Code, Type_Name, Ledger_Number, Ledger_activity, GeneratedType_code, GeneratedType_Name ".
						 " From AccTypeSetup ".
						 " Where Upper(Type_Code) =  Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
					$vCheckLedgerCode   = F_Check_LedgerCode($PDestConn, $rows['Ledger_Number']);
					if ($vCheckLedgerCode == 0) {
						$vResult  = 'P';
						$vMessage = 'Ledger not found.';
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Type_Code']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'AccTypeSetup',$vMessage);
						
						break;
					}
					
					$sub_query = " Insert Into AccTypeSetup (Type_Code, Type_Name, Ledger_Number, Ledger_activity, GeneratedType_code, GeneratedType_Name ) ".
								 " Values ( ".GetSQLValueString($rows['Type_Code'],'text').", ".GetSQLValueString($rows['Type_Name'],'text').
								 ", ".GetSQLValueString($rows['Ledger_Number'],'text').", ".GetSQLValueString($rows['Ledger_activity'],'int').
								 ", ".GetSQLValueString($rows['GeneratedType_code'],'text').", ".GetSQLValueString($rows['GeneratedType_Name'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		

						$sub_query  = " Update Acctype Set Synchronized = 1 ".
									  " Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
						$sub_result=mysql_query($sub_query,$PLocConn);						
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Type_Code']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'AccTypeSetup',$vMessage);
						
						break;
					}	
				}
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Acctype',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Acctype_Code, Owner_Branch ".
					 " From Acctype Where Upper(Acctype_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vAcctypeCode = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From AccTypeSetup Where Upper(Acctype_Code) = Upper('".$vAcctypeCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Acctype Where Upper(Acctype_Code) = Upper('".$vAcctypeCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Acctype',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vAcctypeCode = trim($vAcctypeCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vAcctypeCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroCurrency($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Currency_Id, Currency_Code, Currency_Name, Currency_twos, Currency_Plural, Synchronized, Currency_Posted, ".
				 " Currency_nature, Currency_NameArab, Currency_CountryArab, Currency_Type, Currency_CreationDate, Owner_Branch ".
				 " From Currency ".
				 " Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vCurrencyID	      = GetSQLValueString($rows['Currency_Id'],'int');
		$vCurrencyCode   	  = GetSQLValueString($rows['Currency_Code'],'text');
		$vCurrencyName    	  = GetSQLValueString($rows['Currency_Name'],'text');
		$vCurrencyTwos		  = GetSQLValueString($rows['Currency_twos'],'text');
		$vCurrencyPlural 	  = GetSQLValueString($rows['Currency_Plural'],'text');
		$vSynchronized	 	  = GetSQLValueString($rows['Synchronized'],'int');
		$vCurrencyPosted	  = GetSQLValueString($rows['Currency_Posted'],'int');
		$vCurrencyNature   	  = GetSQLValueString($rows['Currency_nature'],'int');
		$vCurrencyNameArab    = GetSQLValueString($rows['Currency_NameArab'],'text');
		$vCurrencyCountryArab = GetSQLValueString($rows['Currency_CountryArab'],'text');
		$vCurrencyType		  = GetSQLValueString($rows['Currency_Type'],'text');
		$vCreationDate	 	  = GetSQLValueString($rows['Currency_CreationDate'],'date');
		$vOwnerBranch 	 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From Currency ".
						  " Where Upper(Currency_Code) = Upper(".$vCurrencyCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Currency_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vCurrencyCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Currency',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Currency Set Synchronized = 0 ".
						  " Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Currency ".
						  " Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$vCurrencyID = GetNextSequence1($PDestConn,'currency_id','');
				
				$sub_query = " Insert Into Currency (Currency_Id, Currency_Code, Currency_Name, Currency_twos, Currency_Plural, Synchronized, ".
				             " Currency_Posted, Currency_nature, Currency_NameArab, Currency_CountryArab, Currency_Type, ".
							 " Currency_CreationDate, Owner_Branch ) ".
							 " Values ( ".$vCurrencyID.", ".$vCurrencyCode.", ".$vCurrencyName.", ".$vCurrencyTwos.", ".$vCurrencyPlural.", ".$vSynchronized.
							 ", ".$vCurrencyPosted.", ".$vCurrencyNature.", ".$vCurrencyNameArab.", ".$vCurrencyCountryArab.", ".$vCurrencyType.
							 ", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Currency Set Currency_Code = ".$vCurrencyCode.", Currency_Name = ".$vCurrencyName.
							 ", Currency_twos = ".$vCurrencyTwos.", Currency_Plural = ".$vCurrencyPlural.
							 ", Currency_Posted = ".$vCurrencyPosted.", Currency_nature = ".$vCurrencyNature.
							 ", Currency_NameArab = ".$vCurrencyNameArab.", Currency_CountryArab = ".$vCurrencyCountryArab.
							 ", Currency_Type = ".$vCurrencyType.", Currency_CreationDate = ".$vCreationDate.
							 "  Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				//InCase Update, Delete All Related Details In CurDt
				If ($vRecordExists > 0) {
					$query = "Delete From CurDt Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From CurDt
				$query = " Select CurDt_ID, Currency_code, Curdt_date, Curdt_rate, Curdt_parity, Curdt_Posted, Synchronized ".
						 " From CurDt ".
						 " Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
					$vCurDtID = GetNextSequence1($PDestConn,'curdt_id','');
					
					$sub_query = " Insert Into CurDt (curdt_id, Currency_Id, Currency_code, Curdt_date, Curdt_rate, Curdt_parity, Curdt_Posted, Synchronized ) ".
								 " Values ( ".$vCurDtID.", ".$vCurrencyID.", ".GetSQLValueString($rows['Currency_code'],'text').", ".GetSQLValueString($rows['Curdt_date'],'date').
								 ", ".GetSQLValueString($rows['Curdt_rate'],'double').", ".GetSQLValueString($rows['Curdt_parity'],'double').
								 ", ".GetSQLValueString($rows['Curdt_Posted'],'int').", ".GetSQLValueString($rows['Synchronized'],'int')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		

						$sub_query  = " Update Currency Set Synchronized = 1 ".
									  " Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
						$sub_result=mysql_query($sub_query,$PLocConn);						
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert ID= ".$rows['CurDt_ID']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'CurDt',$vMessage);
						
						break;
					}	
				}
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Currency',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Currency_Code, Owner_Branch ".
					 " From Currency Where Upper(Currency_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCurrencyCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From CurDt Where Upper(Currency_Code) = Upper('".$vCurrencyCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Currency Where Upper(Currency_Code) = Upper('".$vCurrencyCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Currency',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vCurrencyCode = trim($vCurrencyCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vCurrencyCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroCustomer($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Customer_Code, Customer_Name, Customer_Work, Customer_Address, Customer_Telephone1, Customer_Telephone2, ".
				 " Customer_Fax, Customer_Email, Customer_Homepage, Customer_CreditLimit, Customer_PaymentTerms, Customer_Remark, ".
				 " Customer_MaxDiscount, Category_Code, Area_Code, Salesmen_Code, Salesmen_Commission, Customer_SellingPrice, ".
				 " Currency_Code, Customer_VAT, Customer_VatNo, Customer_DiscountPer, Customer_cashMode, Profitcenter_code, Customer_Posted, ".
				 " Customer_BelongsToGroup, Synchronized, Company_Name, Custproject_code, Owner_Branch ".
				 " From Customer ".
				 " Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vCustomerId		 	= GetSQLValueString($rows['Customer_Id'],'int');
		$vCustomerCode  		= GetSQLValueString($rows['Customer_Code'],'text');
		$vCustomerName		 	= GetSQLValueString($rows['Customer_Name'],'text');
		$vCustomerWork	 		= GetSQLValueString($rows['Customer_Work'],'text');
		$vCustomerAddress 	    = GetSQLValueString($rows['Customer_Address'],'text');
		$vCustomerTelephone1	= GetSQLValueString($rows['Customer_Telephone1'],'text');
		$vCustomerTelephone2 	= GetSQLValueString($rows['Customer_Telephone2'],'text');
		$vCustomerFax 		    = GetSQLValueString($rows['Customer_Fax'],'text');
		$vCustomerEmail 		= GetSQLValueString($rows['Customer_Email'],'text');
		$vCustomerHomepage	    = GetSQLValueString($rows['Customer_Homepage'],'text');
		$vCustomerCreditLimit   = GetSQLValueString($rows['Customer_CreditLimit'],'double');
		$vCustomerPaymentTerms  = GetSQLValueString($rows['Customer_PaymentTerms'],'double');
		$vCustomerRemark 	  	= GetSQLValueString($rows['Customer_Remark'],'text');
		$vCustomerMaxDiscount   = GetSQLValueString($rows['Customer_MaxDiscount'],'double');
		$vCategoryCode 			= GetSQLValueString($rows['Category_Code'],'text');
		$vAreaCode 				= GetSQLValueString($rows['Area_Code'],'text');
		$vSalesmenCode 			= GetSQLValueString($rows['Salesmen_Code'],'text');
		$vSalesmenCommission  	= GetSQLValueString($rows['Salesmen_Commission'],'double');
		$vCustomerSellingPrice  = GetSQLValueString($rows['Customer_SellingPrice'],'text');
		$vCurrencyCode 			= GetSQLValueString($rows['Currency_Code'],'text');
		$vCustomerVAT     	    = GetSQLValueString($rows['Customer_VAT'],'int');
		$vCustomerVatNo 		= GetSQLValueString($rows['Customer_VatNo'],'text');
		$vCustomerDiscountPer  	= GetSQLValueString($rows['Customer_DiscountPer'],'double');
		$vCustomerCashMode      = GetSQLValueString($rows['Customer_cashMode'],'int');
		$vProfitcenterCode 		= GetSQLValueString($rows['Profitcenter_code'],'text');
		$vCustomerPosted        = GetSQLValueString($rows['Customer_Posted'],'int');
		$vSynchronized		    = GetSQLValueString($rows['Synchronized'],'int');
		$vBelongsToGroup		= GetSQLValueString($rows['Customer_BelongsToGroup'],'int');
		$vCompanyName		    = GetSQLValueString($rows['Company_Name'],'text');
		$vCustProjectCode	    = GetSQLValueString($rows['Custproject_code'],'text');
		$vOwnerBranch 		 	= GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I') {	
			$sub_query  = " Select Count(*) From Customer ".
						  " Where Upper(Customer_Code) = Upper(".$vCustomerCode.") ";
							  
			//If ($PState == 'U')	$sub_query = $sub_query." And Customer_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vCustomerCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Customer',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Customer Set Synchronized = 0 ".
						  " Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Customer ".
						  " Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Customer (Customer_Code, Customer_Name, Customer_Work, Customer_Address, Customer_Telephone1, ".
							 " Customer_Telephone2, Customer_Fax, Customer_Email, Customer_Homepage, Customer_CreditLimit, Customer_PaymentTerms, ".
							 " Customer_Remark, Customer_MaxDiscount, Category_Code, Area_Code, Salesmen_Code, Salesmen_Commission, Customer_SellingPrice, ".
							 " Currency_Code, Customer_VAT, Customer_VatNo, Customer_DiscountPer, Customer_cashMode, Profitcenter_code, Customer_Posted, ".
							 " Customer_BelongsToGroup, Synchronized, Company_Name, Custproject_code, Owner_Branch ) ".
							 " Values ( ".$vCustomerCode.", ".$vCustomerName.", ".$vCustomerWork.", ".$vCustomerAddress.", ".$vCustomerTelephone1.
							 ", ".$vCustomerTelephone2.", ".$vCustomerFax.", ".$vCustomerEmail.", ".$vCustomerHomepage.", ".$vCustomerCreditLimit.
							 ", ".$vCustomerPaymentTerms.", ".$vCustomerRemark.", ".$vCustomerMaxDiscount.", ".$vCategoryCode.", ".$vAreaCode.", ".$vSalesmenCode.
							 ", ".$vSalesmenCommission.", ".$vCustomerSellingPrice.", ".$vCurrencyCode.", ".$vCustomerVAT.", ".$vCustomerVatNo.
							 ", ".$vCustomerDiscountPer.", ".$vCustomerCashMode.", ".$vProfitcenterCode.", ".$vCustomerPosted.", ".$vBelongsToGroup.
							 ", ".$vSynchronized.", ".$vCompanyName.", ".$vCustProjectCode.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Customer Set Customer_Code = ".$vCustomerCode.", Customer_Name = ".$vCustomerName.
							 ", Customer_Work = ".$vCustomerWork.", Customer_Address = ".$vCustomerAddress.
							 ", Customer_Telephone1 = ".$vCustomerTelephone1.", Customer_Telephone2 = ".$vCustomerTelephone2.
							 ", Customer_Fax = ".$vCustomerFax.", Customer_Email = ".$vCustomerEmail.
							 ", Customer_Homepage = ".$vCustomerHomepage.", Customer_CreditLimit = ".$vCustomerCreditLimit.
							 ", Customer_PaymentTerms = ".$vCustomerPaymentTerms.", Customer_Remark = ".$vCustomerRemark.
							 ", Customer_MaxDiscount = ".$vCustomerMaxDiscount.", Category_Code = ".$vCategoryCode.
							 ", Area_Code = ".$vAreaCode.", Salesmen_Code = ".$vSalesmenCode.
							 ", Salesmen_Commission = ".$vSalesmenCommission.", Customer_SellingPrice = ".$vCustomerSellingPrice.
							 ", Currency_Code = ".$vCurrencyCode.", Customer_VAT = ".$vCustomerVAT.
							 ", Customer_VatNo = ".$vCustomerVatNo.", Customer_DiscountPer = ".$vCustomerDiscountPer.
							 ", Customer_cashMode = ".$vCustomerCashMode.", Profitcenter_code = ".$vProfitcenterCode.
							 ", Customer_Posted = ".$vCustomerPosted.", Customer_BelongsToGroup = ".$vBelongsToGroup.
							 ", Company_Name = ".$vCompanyName.", Custproject_code = ".$vCustProjectCode.
							 "  Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Customer Set Synchronized = 1 ".
							  " Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Customer',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Customer_Code, Owner_Branch ".
					 " From Customer Where Upper(Customer_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCustomerCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From Customer Where Upper(Customer_Code) = Upper('".$vCustomerCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Customer',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vCustomerCode = trim($vCustomerCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vCustomerCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroCoupon($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Coupon_Id, Coupon_Reference, Coupon_Name, Ledger_Number, Coupon_Active, Coupon_Posted, Coupon_Tel, ".
				 " Coupon_Remark, Coupon_Amount, Coupon_AmountBase1, Coupon_AmountBase2, Currency_Code, Coupon_AmountConsum, ".
				 " Coupon_AmountConsumBase1, Coupon_AmountConsumBase2, Coupon_Date, Synchronized, Owner_Branch ".
				 " From Coupon ".
				 " Where Coupon_Id = '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vCouponId			 	= GetSQLValueString($rows['Coupon_Id'],'int');
		$vCouponReference  		= GetSQLValueString($rows['Coupon_Reference'],'text');
		$vCouponName		 	= GetSQLValueString($rows['Coupon_Name'],'text');
		$vLedgerNumber		 	= GetSQLValueString($rows['Ledger_Number'],'text');
		$vCouponActive			= GetSQLValueString($rows['Coupon_Active'],'int');
		$vCouponPosted			= GetSQLValueString($rows['Coupon_Posted'],'int');
		$vCouponTel			    = GetSQLValueString($rows['Coupon_Tel'],'text');
		$vCouponRemark			= GetSQLValueString($rows['Coupon_Remark'],'text');
		$vCouponAmount			= GetSQLValueString($rows['Coupon_Amount'],'double');
		$vCouponAmountBase1		  = GetSQLValueString($rows['Coupon_AmountBase1'],'double');
		$vCouponAmountBase2	   	  = GetSQLValueString($rows['Coupon_AmountBase2'],'double');
		$vCurrencyCode			  = GetSQLValueString($rows['Currency_Code'],'text');
		$vCouponAmountConsum	  = GetSQLValueString($rows['Coupon_AmountConsum'],'double');
		$vCouponAmountConsumBase1 = GetSQLValueString($rows['Coupon_AmountConsumBase1'],'double');
		$vCouponAmountConsumBase2 = GetSQLValueString($rows['Coupon_AmountConsumBase2'],'double');
		$vCouponDate			  = GetSQLValueString($rows['Coupon_Date'],'date');
		$vSynchronized		      = GetSQLValueString($rows['Synchronized'],'int');
		$vOwnerBranch 	 	      = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Coupon ".
						  " Where Coupon_Id = ".$PRecordID;
							  
			//If ($PState == 'U')	$sub_query = $sub_query." And Coupon_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vCouponReference;
			$vMessage = GetSQLValueString("Insert ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Coupon',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Coupon Set Synchronized = 0 ".
						  " Where Coupon_Id = '".$PRecordID."'";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Coupon ".
						  " Where Coupon_Id = '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Coupon (Coupon_Id, Coupon_Reference, Coupon_Name, Ledger_Number, Coupon_Active, Coupon_Posted, Coupon_Tel, ".
							 " Coupon_Remark, Coupon_Amount, Coupon_AmountBase1, Coupon_AmountBase2, Currency_Code, Coupon_AmountConsum, ".
							 " Coupon_AmountConsumBase1, Coupon_AmountConsumBase2, Coupon_Date, Synchronized, Owner_Branch ) ".
							 " Values ( ".$vCouponId.", ".$vCouponReference.", ".$vCouponName.", ".$vLedgerNumber.", ".$vCouponActive.", ".$vCouponPosted.
							 ", ".$vCouponTel.", ".$vCouponRemark.", ".$vCouponAmount.", ".$vCouponAmountBase1.", ".$vCouponAmountBase2.", ".$vCurrencyCode.
							 ", ".$vCouponAmountConsum.", ".$vCouponAmountConsumBase1.", ".$vCouponAmountConsumBase2.", ".$vCouponDate.", ".$vSynchronized.
							 ", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Coupon Set Coupon_Reference = ".$vCouponReference.", Coupon_Name = ".$vCouponName.
							 ", Ledger_Number = ".$vLedgerNumber.", Coupon_Active = ".$vCouponActive.
							 ", Coupon_Posted = ".$vCouponPosted.", Coupon_Tel = ".$vCouponTel.
							 ", Coupon_Remark = ".$vCouponRemark.", Coupon_Amount = ".$vCouponAmount.
							 ", Coupon_AmountBase1 = ".$vCouponAmountBase1.", Coupon_AmountBase2 = ".$vCouponAmountBase2.
							 ", Currency_Code = ".$vCurrencyCode.", Coupon_AmountConsum = ".$vCouponAmountConsum.
							 ", Coupon_AmountConsumBase1 = ".$vCouponAmountConsumBase1.", Coupon_AmountConsumBase2 = ".$vCouponAmountConsumBase2.
							 ", Coupon_Date = ".$vCouponDate.
							 "  Where Coupon_Id = '".$PRecordID."'";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Coupon Set Synchronized = 1 ".
							  " Where Coupon_Id = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Coupon',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Coupon_Id, Owner_Branch ".
					 " From Coupon Where Coupon_Id = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCouponID	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Coupon Where Coupon_Id = '".$vCouponRef."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Coupon',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vCouponID,'',$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroVendor($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Ledger_Number, Ledger_Name, Ledger_Desc, Vendor_Remark, Vendor_Active, Synchronized, Owner_Branch ".
				 " From Vendor ".
				 " Where Upper(Ledger_Number) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vVendorId		  = GetSQLValueString($rows['Vendor_Id'],'int');
		$vLedgerNumber	  = GetSQLValueString($rows['Ledger_Number'],'text');
		$vLedgerName	  = GetSQLValueString($rows['Ledger_Name'],'text');
		$vLedgerDesc	  = GetSQLValueString($rows['Ledger_Desc'],'text');
		$vVendorRemark	  = GetSQLValueString($rows['Vendor_Remark'],'text');
		$vVendorActive	  = GetSQLValueString($rows['Vendor_Active'],'int');
		$vSynchronized	  = GetSQLValueString($rows['Synchronized'],'int');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Vendor ".
						  " Where Upper(Ledger_Number) = Upper(".$vLedgerNumber.") ";
							  
			//If ($PState == 'U')	$sub_query = $sub_query." And Vendor_ID != '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vLedgerNumber;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Vendor',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Vendor Set Synchronized = 0 ".
						  " Where Upper(Ledger_Number) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Vendor ".
						  " Where Upper(Ledger_Number) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Vendor (Ledger_Number, Ledger_Name, Ledger_Desc, Vendor_Remark, Vendor_Active, Synchronized, Owner_Branch ) ".
							 " Values ( ".$vLedgerNumber.", ".$vLedgerName.", ".$vLedgerDesc.", ".$vVendorRemark.", ".$vVendorActive.", ".$vSynchronized.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Vendor Set Ledger_Number = ".$vLedgerNumber.", Ledger_Name = ".$vLedgerName.
							 ", Ledger_Desc = ".$vLedgerDesc.", Vendor_Remark = ".$vVendorRemark.
							 ", Vendor_Active = ".$vVendorActive.
							 "  Where Upper(Ledger_Number) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Vendor Set Synchronized = 1 ".
							  " Where Upper(Ledger_Number) = '".$PRecordCode."'";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Vendor',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Ledger_Number, Owner_Branch ".
					 " From Vendor Where Upper(Ledger_Number) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vVendorCode  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Vendor Where Upper(Ledger_Number) = Upper('".$vVendorCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Vendor',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vVendorCode  = trim($vVendorCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vVendorCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroChecks($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Chk_increment, Chk_number, ledger_number, Chk_bank, Chk_ValueDate, Currency_code, Chk_amount, ".
				 " Chk_amount1, Chk_amount2, Ledger_Activity, Journaldt_id1, Journaldt_id2, Chk_bank_in, Chk_col_ret, ".
				 " Chk_posted, Check_visible, Chk_BankInDate, Synchronized, manual_no, Owner_Branch ".
				 " From Checks ".
				 " Where Chk_Increment = '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vCheckId		  = GetSQLValueString($rows['Chk_Increment'],'int');
		$vChkNumber  	  = GetSQLValueString($rows['Chk_number'],'text');
		$vLedgerNumber	  = GetSQLValueString($rows['ledger_number'],'text');
		$vChkBank		  = GetSQLValueString($rows['Chk_bank'],'text');
		$vChkValueDate	  = GetSQLValueString($rows['Chk_ValueDate'],'date');
		$vCurrencyCode	  = GetSQLValueString($rows['Currency_code'],'text');
		$vChkAmount		  = GetSQLValueString($rows['Chk_amount'],'double');
		$vChkAmount1	  = GetSQLValueString($rows['Chk_amount1'],'double');
		$vChkAmount2	  = GetSQLValueString($rows['Chk_amount2'],'double');
		$vLedgerActivity  = GetSQLValueString($rows['Ledger_Activity'],'int');
		$vJournaldtId1	  = GetSQLValueString($rows['Journaldt_id1'],'double');
		$vJournaldtId2	  = GetSQLValueString($rows['Journaldt_id2'],'double');
		$vChkBankIn		  = GetSQLValueString($rows['Chk_bank_in'],'text');
		$vChkColRet		  = GetSQLValueString($rows['Chk_col_ret'],'text');
		$vChkPosted		  = GetSQLValueString($rows['Chk_posted'],'int');
		$vCheckVisible	  = GetSQLValueString($rows['Check_visible'],'int');
		$vSynchronized	  = GetSQLValueString($rows['Synchronized'],'int');
		$vChkBankInDate	  = GetSQLValueString($rows['Chk_BankInDate'],'date');
		$vManualNo		  = GetSQLValueString($rows['manual_no'],'text');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
			
		$sub_query  = " Select Count(*) From Checks ".
					  " Where Upper(Chk_number) = Upper(".$vChkNumber.") ";
						  
		If ($PState == 'U')	$sub_query = $sub_query." And Chk_Increment != '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vDuplicateExists = $sub_result[0];
			
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vChkNumber;
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Checks',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Checks Set Synchronized = 0 ".
						  " Where Chk_Increment = '".$PRecordID."'";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Checks ".
						  " Where Chk_Increment = '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Checks (Chk_increment, Chk_number, ledger_number, Chk_bank, Chk_ValueDate, Currency_code, Chk_amount, ".
							 " Chk_amount1, Chk_amount2, Ledger_Activity, Journaldt_id1, Journaldt_id2, Chk_bank_in, Chk_col_ret, ".
							 " Chk_posted, Check_visible, Chk_BankInDate, Synchronized, manual_no, Owner_Branch ) ".
							 " Values ( ".$vCheckId.", ".$vChkNumber.", ".$vLedgerNumber.", ".$vChkBank.", ".$vChkValueDate.", ".$vCurrencyCode.
							 ", ".$vChkAmount.", ".$vChkAmount1.", ".$vChkAmount2.", ".$vLedgerActivity.", ".$vJournaldtId1.", ".$vJournaldtId2.
							 ", ".$vChkBankIn.", ".$vChkColRet.", ".$vChkPosted.", ".$vCheckVisible.", ".$vChkBankInDate.", ".$vSynchronized.
							 ", ".$vManualNo.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Checks Set Chk_number = ".$vChkNumber.", ledger_number = ".$vLedgerNumber.
							 ", Chk_bank = ".$vChkBank.", Chk_ValueDate = ".$vChkValueDate.
							 ", Currency_code = ".$vCurrencyCode.", Chk_amount = ".$vChkAmount.
							 ", Chk_amount1 = ".$vChkAmount1.", Chk_amount2 = ".$vChkAmount2.
							 ", Ledger_Activity = ".$vLedgerActivity.", Journaldt_id1 = ".$vJournaldtId1.
							 ", Journaldt_id2 = ".$vJournaldtId2.", Chk_bank_in = ".$vCouponAmountConsum.
							 ", Chk_col_ret = ".$vChkColRet.", Chk_posted = ".$vChkPosted.
							 ", Check_visible = ".$vCheckVisible.", Chk_BankInDate = ".$vChkBankInDate.
							 ", manual_no = ".$vManualNo.
							 "  Where Chk_Increment = '".$PRecordID."'";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Checks Set Synchronized = 1 ".
							  " Where Chk_Increment = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Checks',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Chk_Increment, Owner_Branch ".
					 " From Checks Where Chk_Increment = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vCheckId	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Checks Where Chk_Increment = '".$vCheckId."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Checks',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vCheckId,'',$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroBills($PTableName, $PRecordID, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Bill_Increment, Bill_number, ledger_number, Bill_bank, Bill_ValueDate, Currency_code, ".
				 " Bill_amount, Bill_amount1, Bill_amount2, Ledger_Activity, Journaldt_id1, Journaldt_id2, ".
				 " Bank_Reference, Synchronized, Owner_Branch ".
				 " From Bills ".
				 " Where Bill_Increment = '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vBillId		  = GetSQLValueString($rows['Bill_Increment'],'int');
		$vBillNumber  	  = GetSQLValueString($rows['Bill_number'],'text');
		$vLedgerNumber	  = GetSQLValueString($rows['ledger_number'],'text');
		$vBillBank		  = GetSQLValueString($rows['Bill_bank'],'text');
		$vBillValueDate	  = GetSQLValueString($rows['Bill_ValueDate'],'date');
		$vCurrencyCode	  = GetSQLValueString($rows['Currency_code'],'text');
		$vBillAmount	  = GetSQLValueString($rows['Bill_amount'],'double');
		$vBillAmount1	  = GetSQLValueString($rows['Bill_amount1'],'double');
		$vBillAmount2	  = GetSQLValueString($rows['Bill_amount2'],'double');
		$vLedgerActivity  = GetSQLValueString($rows['Ledger_Activity'],'int');
		$vJournaldtId1	  = GetSQLValueString($rows['Journaldt_id1'],'double');
		$vJournaldtId2	  = GetSQLValueString($rows['Journaldt_id2'],'double');
		$vBankReference	  = GetSQLValueString($rows['Bank_Reference'],'text');
		$vSynchronized	  = GetSQLValueString($rows['Synchronized'],'int');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
			
		$sub_query  = " Select Count(*) From Bills ".
					  " Where Upper(Bill_number) = Upper(".$vBillNumber.") ";
						  
		If ($PState == 'U')	$sub_query = $sub_query." And Bill_Increment != '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vDuplicateExists = $sub_result[0];
			
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vBillNumber;
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Bills',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Bills Set Synchronized = 0 ".
						  " Where Bill_Increment = '".$PRecordID."'";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Bills ".
						  " Where Bill_Increment = '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Bills (Bill_Increment, Bill_number, ledger_number, Bill_bank, Bill_ValueDate, Currency_code, ".
							 " Bill_amount, Bill_amount1, Bill_amount2, Ledger_Activity, Journaldt_id1, Journaldt_id2, ".
							 " Bank_Reference, Synchronized, Owner_Branch ) ".
							 " Values ( ".$vBillId.", ".$vBillNumber.", ".$vLedgerNumber.", ".$vBillBank.", ".$vBillValueDate.", ".$vCurrencyCode.
							 ", ".$vBillAmount.", ".$vBillAmount1.", ".$vBillAmount2.", ".$vLedgerActivity.", ".$vJournaldtId1.", ".$vJournaldtId2.
							 ", ".$vBankReference.", ".$vSynchronized.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Bills Set Bill_number = ".$vBillNumber.", ledger_number = ".$vLedgerNumber.
							 ", Bill_bank = ".$vBillBank.", Bill_ValueDate = ".$vBillValueDate.
							 ", Currency_code = ".$vCurrencyCode.", Bill_amount = ".$vBillAmount.
							 ", Bill_amount1 = ".$vBillAmount1.", Bill_amount2 = ".$vBillAmount2.
							 ", Ledger_Activity = ".$vLedgerActivity.", Journaldt_id1 = ".$vJournaldtId1.
							 ", Journaldt_id2 = ".$vJournaldtId2.", Bank_Reference = ".$vBankReference.
							 "  Where Bill_Increment = '".$PRecordID."'";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Bills Set Synchronized = 1 ".
							  " Where Bill_Increment = '".$PRecordID."'";
				$sub_result=mysql_query($sub_query,$PLocConn);
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Bills',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Bill_Increment, Owner_Branch ".
					 " From Bills Where Bill_Increment = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vBillId	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Bills Where Bill_Increment = '".$vBillId."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Bills',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vBillId,'',$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroBanks($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Bank_ID, Bank_Name, Bank_Branch, Bank_Telephone1, Bank_Telephone2, Bank_Fax, ".
				 " Bank_Address, Bank_Email, Bank_Website, Bank_creditlimit1, Bank_creditlimit2, Owner_Branch ".
				 " From Banks ".
				 " Where Bank_ID = '".$PRecordID."'";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vBankId		  = GetSQLValueString($rows['Bank_ID'],'int');
		$vBankName  	  = GetSQLValueString($rows['Bank_Name'],'text');
		$vBankBranch	  = GetSQLValueString($rows['Bank_Branch'],'text');
		$vBankTelephone1  = GetSQLValueString($rows['Bank_Telephone1'],'text');
		$vBankTelephone2  = GetSQLValueString($rows['Bank_Telephone2'],'text');
		$vBankFax	  	  = GetSQLValueString($rows['Bank_Fax'],'text');
		$vBankAddress	  = GetSQLValueString($rows['Bank_Address'],'text');
		$vBankEmail	  	  = GetSQLValueString($rows['Bank_Email'],'text');
		$vBankWebsite	  = GetSQLValueString($rows['Bank_Website'],'text');
		$vBankcreditlimit1= GetSQLValueString($rows['Bank_creditlimit1'],'double');
		$vBankcreditlimit2= GetSQLValueString($rows['Bank_creditlimit2'],'double');
		$vOwnerBranch 	  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		//Check For Duplicate of Name InCase Insert
		$vDuplicateExists = 0;
			
		$sub_query  = " Select Count(*) From Banks ".
					  " Where Upper(Bank_Name) = Upper(".$vBankName.") ";
						  
		If ($PState == 'U')	$sub_query = $sub_query." And Bank_ID != '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vDuplicateExists = $sub_result[0];
			
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Name: '.$vBankName;
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Banks',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Select Count(*) From Banks ".
						  " Where Bank_ID = '".$PRecordID."'";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
		
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$vBankId = GetNextSequence1($PDestConn,'Bank_ID','');
				
				$sub_query = " Insert Into Banks (Bank_ID, Bank_Name, Bank_Branch, Bank_Telephone1, Bank_Telephone2, ".
							 " Bank_Fax, Bank_Address, Bank_Email, Bank_Website, Bank_creditlimit1, Bank_creditlimit2, Owner_Branch ) ".
							 " Values ( ".$vBankId.", ".$vBankName.", ".$vBankBranch.", ".$vBankTelephone1.", ".$vBankTelephone2.", ".$vBankFax.
							 ", ".$vBankAddress.", ".$vBankEmail.", ".$vBankWebsite.", ".$vBankcreditlimit1.", ".$vBankcreditlimit2.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Banks Set Bank_Name = ".$vBankName.", Bank_Branch = ".$vBankBranch.
							 ", Bank_Telephone1 = ".$vBankTelephone1.", Bank_Telephone2 = ".$vBankTelephone2.
							 ", Bank_Fax = ".$vBankFax.", Bank_Address = ".$vBankAddress.", Bank_Email = ".$vBankEmail.
							 ", Bank_Website = ".$vBankWebsite.", Bank_creditlimit1 = ".$vBankcreditlimit1.
							 ", Bank_creditlimit2 = ".$vBankcreditlimit2.
							 "  Where Bank_ID = '".$PRecordID."'";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Banks',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Bank_ID, Owner_Branch ".
					 " From Banks Where Bank_ID = '".$PRecordID."'";
		$sub_result = selectData($PDestConn, $sub_query);
		$vBankId	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From Banks Where Bank_ID = '".$vBankId."'";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Banks',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,$vBankId,'',$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroSalesmen($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Ledger_number, Ledger_name, Ledger_Desc, Salesman_address, Salesman_Telephone1, ".
				 " Salesman_Telephone2, Salesman_Fax, Salesman_Email, Salesman_Remark, Salesman_commission,  ".
				 " Salesman_CreditLimit, Salesman_Bonus, Area_Code, Currency_Code, Salesman_posted, Salesman_BelongsToGroup, ".
				 " Synchronized, Manager_Code, Salesman_IsManager, Salesman_IsLedger, Salesman_MRef, Salesman_CreationDate, ".
				 " Owner_Branch ".
				 " From Salesmen ".
				 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vSalesmanId		  = GetSQLValueString($rows['Salesman_Id'],'int');
		$vSalesmanCode  	  = GetSQLValueString($rows['Ledger_number'],'text');
		$vSalesmanName 	 	  = GetSQLValueString($rows['Ledger_name'],'text');
		$vLedgerDesc   	 	  = GetSQLValueString($rows['Ledger_Desc'],'text');
		$vSalesmanAddress     = GetSQLValueString($rows['Salesman_address'],'text');
		$vSalesmanTelephone1  = GetSQLValueString($rows['Salesman_Telephone1'],'text');
		$vSalesmanTelephone2  = GetSQLValueString($rows['Salesman_Telephone2'],'text');
		$vSalesmanFax   	  = GetSQLValueString($rows['Salesman_Fax'],'text');
		$vSalesmanEmail  	  = GetSQLValueString($rows['Salesman_Email'],'text');
		$vSalesmanRemark   	  = GetSQLValueString($rows['Salesman_Remark'],'text');
		$vSalesmanCommission  = GetSQLValueString($rows['Salesman_commission'],'double');
		$vSalesmanCreditLimit = GetSQLValueString($rows['Salesman_CreditLimit'],'double');
		$vSalesmanBonus   	  = GetSQLValueString($rows['Salesman_Bonus'],'double');
		$vAreaCode 			  = GetSQLValueString($rows['Area_Code'],'text');
		$vCurrencyCode  	  = GetSQLValueString($rows['Currency_Code'],'text');
		$vSalesmanPosted 	  = GetSQLValueString($rows['Salesman_posted'],'int');
		$vBelongsToGroup 	  = GetSQLValueString($rows['Salesman_BelongsToGroup'],'int');
		$vSynchronized		  = GetSQLValueString($rows['Synchronized'],'int');
		$vManagerCode		  = GetSQLValueString($rows['Manager_Code'],'text');
		$vSalesmanIsManager	  = GetSQLValueString($rows['Salesman_IsManager'],'int');
		$vSalesmanIsLedger	  = GetSQLValueString($rows['Salesman_IsLedger'],'int');
		$vSalesmanMRef		  = GetSQLValueString($rows['Salesman_MRef'],'text');
		$vCreationDate		  = GetSQLValueString($rows['Salesman_CreationDate'],'date');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		
		/*$vCheckLedgerGroupID  = F_Check_LedgerGroupID($PDestConn, $vLedgerGrpId);
		
		if ($vCheckLedgerGroupID == 0 ) {
			$vResult  = 'P';
			$vMessage = 'LedgerGroup not found.';
			$vMessage = GetSQLValueString("Insert/Update ID= ".$PRecordID." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Salesmen',$vMessage);
			
			Return $vResult;
		}*/
		
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Salesmen ".
						  " Where Upper(Ledger_number) = Upper(".$vSalesmanCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Salesman_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vSalesmanCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Salesmen',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Salesmen Set Synchronized = 0 ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Salesmen ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Salesmen (Ledger_number, Ledger_name, Ledger_Desc, Salesman_address, Salesman_Telephone1, ".
							 " Salesman_Telephone2, Salesman_Fax, Salesman_Email, Salesman_Remark, Salesman_commission,  ".
							 " Salesman_CreditLimit, Salesman_Bonus, Area_Code, Currency_Code, Salesman_posted, Salesman_BelongsToGroup, ".
							 " Synchronized, Manager_Code, Salesman_IsManager, Salesman_IsLedger, Salesman_MRef, Salesman_CreationDate, ".
							 " Owner_Branch ) ".
							 " Values ( ".$vSalesmanCode.", ".$vSalesmanName.", ".$vLedgerDesc.", ".$vSalesmanAddress.
							 ", ".$vSalesmanTelephone1.", ".$vSalesmanTelephone2.", ".$vSalesmanFax.", ".$vSalesmanEmail.", ".$vSalesmanRemark.
							 ", ".$vSalesmanCommission.", ".$vSalesmanCreditLimit.", ".$vSalesmanBonus.", ".$vAreaCode.", ".$vCurrencyCode.
							 ", ".$vSalesmanPosted.", ".$vBelongsToGroup.", ".$vSynchronized.", ".$vManagerCode.", ".$vSalesmanIsManager.
							 ", ".$vSalesmanIsLedger.", ".$vSalesmanMRef.", ".$vCreationDate.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Salesmen Set Ledger_number = ".$vSalesmanCode.", Ledger_name = ".$vSalesmanName.
							 ", Ledger_Desc = ".$vLedgerDesc.", Salesman_address = ".$vSalesmanAddress.
							 ", Salesman_Telephone1 = ".$vSalesmanTelephone1.", Salesman_Telephone2 = ".$vSalesmanTelephone2.
							 ", Salesman_Fax = ".$vSalesmanFax.", Salesman_Email = ".$vSalesmanEmail.
							 ", Salesman_Remark = ".$vSalesmanRemark.", Salesman_commission = ".$vSalesmanCommission.
							 ", Salesman_CreditLimit = ".$vSalesmanCreditLimit.", Salesman_Bonus = ".$vSalesmanBonus.
							 ", Area_Code = ".$vAreaCode.", Currency_Code = ".$vCurrencyCode.
							 ", Salesman_posted = ".$vSalesmanPosted.", Salesman_BelongsToGroup = ".$vBelongsToGroup.
							 ", Manager_Code = ".$vManagerCode.", Salesman_IsManager = ".$vSalesmanIsManager.
							 ", Salesman_IsLedger = ".$vSalesmanIsLedger.", Salesman_MRef = ".$vSalesmanMRef.
							 ", Salesman_CreationDate = ".$vCreationDate.
							 "  Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Salesmen Set Synchronized = 1 ".
							  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);						
						
				//InCase Update, Delete All Related Details In SalesComm
				If ($vRecordExists > 0) {
					$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
					
					$query = "Delete From SalesComm Where Upper(Salesman_Code) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From SalesComm
				$query = " Select SalesComm_Id, Salesman_Code, SalesComm_StartDate, SalesComm_EndDate, SalesComm_TargetAmnt, ".
						 " SalesComm_TargetComm, Currency_Code, SalesComm_Commission ".
						 " From SalesComm ".
						 " Where Upper(Salesman_Code) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
										
					$sub_query = " Insert Into SalesComm (Salesman_Code, SalesComm_StartDate, SalesComm_EndDate, SalesComm_TargetAmnt, ".
								 " SalesComm_TargetComm, Currency_Code, SalesComm_Commission ) ".
								 " Values ( ".GetSQLValueString($rows['Salesman_Code'],'text').", ".GetSQLValueString($rows['SalesComm_StartDate'],'date').
								 ", ".GetSQLValueString($rows['SalesComm_EndDate'],'date').", ".GetSQLValueString($rows['SalesComm_TargetAmnt'],'double').
								 ", ".GetSQLValueString($rows['SalesComm_TargetComm'],'double').", ".GetSQLValueString($rows['Currency_Code'],'text').
								 ", ".GetSQLValueString($rows['SalesComm_Commission'],'double')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		
						
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Salesman_Code']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'SalesComm',$vMessage);
						
						break;
					}	
				}
				
				//Insert Related Details From TelephoneNo
				$query = " Select Telephone_increment, Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, ".
						 " TelephoneNo_ContactTitle, TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname,  ".
						 " telephoneno_email, telephoneno_reference, telephoneno_city1, telephoneno_city2, telephoneno_city3  ".
						 " From TelephoneNo ".
						 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
										
					$sub_query = " Insert Into TelephoneNo (Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, TelephoneNo_ContactTitle, ".
								 " TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname, telephoneno_email, telephoneno_reference, ".
							     " telephoneno_city1, telephoneno_city2, telephoneno_city3) ".
								 " Values ( ".GetSQLValueString($rows['Ledger_number'],'text').", ".GetSQLValueString($rows['TelephoneNo'],'text').
								 ", ".GetSQLValueString($rows['Telephone_name'],'text').", ".GetSQLValueString($rows['Telephone_posted'],'int').
								 ", ".GetSQLValueString($rows['TelephoneNo_ContactTitle'],'text').", ".GetSQLValueString($rows['TelephoneNo2'],'text').
								 ", ".GetSQLValueString($rows['TelephoneNo3'],'text').", ".GetSQLValueString($rows['telephoneno_fname'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_lname'],'text').", ".GetSQLValueString($rows['telephoneno_email'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_reference'],'text').", ".GetSQLValueString($rows['telephoneno_city1'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_city2'],'text').", ".GetSQLValueString($rows['telephoneno_city3'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		
											
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Ledger_number']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'TelephoneNo',$vMessage);
						
						break;
					}	
				}
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Salesmen',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Ledger_number, Owner_Branch ".
					 " From Salesmen Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vSalesmanCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$vSalesmanCode."')";
		$result = mysql_query($query, $PDestConn);
		
		$query = "Delete From SalesComm Where Upper(Salesman_Code) = Upper('".$vSalesmanCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Salesmen Where Upper(Ledger_number) = Upper('".$vSalesmanCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Salesmen',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vSalesmanCode = trim($vSalesmanCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vSalesmanCode,$vOwnerBranch);
	}

	Return $vResult;

}


function F_SynchroClients($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Ledger_number, Ledger_name, Ledger_Desc, Client_Work, Client_Address, Client_Telephone1, ".
				 " Client_Telephone2, Client_Fax, Client_Email, Client_homepage, Client_CreditLimit, Client_PaymentTerms, ".
				 " Client_Remark, Client_MaxDiscount, Area_Code, Salesmen_Code, Salesmen_Commission, Client_SellingPrice, ".
				 " Currency_Code, Client_VAT, Client_VatNo, Client_DiscountPer, ProfitCenter_CODE, Client_CashMode, ".
				 " Client_ChkTerms, Project_Code, Client_posted, Client_deactivatedate, Client_deactivate, Client_checkAccount, ".
				 " Client_BusinessType, Client_BelongsToGroup, Client_PaymentMode, ClientGrp_Code, Client_City, Client_State, ".
				 " Client_Country, Client_Group, Client_MotherCompany, Client_CompLegalType, Client_CompOwner, Client_ReferedBy, ".
				 " Client_SDINo, Client_DeliveryPhone, Client_DeliveryAddress, Client_DeliveryAssistant, Client_DlvAssistantTitle, ".
				 " Client_EvaluationPoints, Client_Tips, Client_ArchiveFileNo, Client_CreationDate, client_GCIno, CostCenter_Code,  ".
				 " client_local, client_export, Client_Detail, Client_DeliveryTransfer, Client_Rebate, Client_Target, Owner_Branch ".
				 " From Clients ".
				 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vSalesmanId		  = GetSQLValueString($rows['Salesman_Id'],'int');
		$vClientCode  	  	  = GetSQLValueString($rows['Ledger_number'],'text');
		$vClientName 	 	  = GetSQLValueString($rows['Ledger_name'],'text');
		$vLedgerDesc   	 	  = GetSQLValueString($rows['Ledger_Desc'],'text');
		$vClientWork 	  	  = GetSQLValueString($rows['Client_Work'],'text');
		$vClientAddress       = GetSQLValueString($rows['Client_Address'],'text');
		$vClientTelephone1 	  = GetSQLValueString($rows['Client_Telephone1'],'text');
		$vClientTelephone2	  = GetSQLValueString($rows['Client_Telephone2'],'text');
		$vClientFax   		  = GetSQLValueString($rows['Client_Fax'],'text');
		$vClientEmail  		  = GetSQLValueString($rows['Client_Email'],'text');
		$vClientRemark   	  = GetSQLValueString($rows['Client_Remark'],'text');
		$vClientHomePage	  = GetSQLValueString($rows['Client_homepage'],'text');
		$vClientCreditLimit   = GetSQLValueString($rows['Client_CreditLimit'],'double');
		$vClientPaymentTerms  = GetSQLValueString($rows['Client_PaymentTerms'],'double');
		$vClientMaxDiscount   = GetSQLValueString($rows['Client_MaxDiscount'],'double');
		$vAreaCode 			  = GetSQLValueString($rows['Area_Code'],'text');
		$vSalesmenCode 		  = GetSQLValueString($rows['Salesmen_Code'],'text');
		$vSalesmenCommission  = GetSQLValueString($rows['Salesmen_Commission'],'double');
		$vClientSellingPrice  = GetSQLValueString($rows['Client_SellingPrice'],'text');
		$vCurrencyCode  	  = GetSQLValueString($rows['Currency_Code'],'text');
		$vClientVAT 	 	  = GetSQLValueString($rows['Client_VAT'],'int');
		$vClientVatNo  		  = GetSQLValueString($rows['Client_VatNo'],'text');
		$vClientDiscountPer   = GetSQLValueString($rows['Client_DiscountPer'],'double');
		$vProfitCenterCODE    = GetSQLValueString($rows['ProfitCenter_CODE'],'text');
		$vClientCashMode 	  = GetSQLValueString($rows['Client_CashMode'],'int');
		$vClientChkTerms  	  = GetSQLValueString($rows['Client_ChkTerms'],'double');
		$vProjectCode 		  = GetSQLValueString($rows['Project_Code'],'text');
		$vClientPosted 		  = GetSQLValueString($rows['Client_posted'],'int');
		$vClientdeactivatedate= GetSQLValueString($rows['Client_deactivatedate'],'date');
		$vClientdeactivate 	  = GetSQLValueString($rows['Client_deactivate'],'int');
		$vClientCheckAccount  = GetSQLValueString($rows['Client_checkAccount'],'text');
		$vClientBusinessType  = GetSQLValueString($rows['Client_BusinessType'],'text');
		$vBelongsToGroup 	  = GetSQLValueString($rows['Client_BelongsToGroup'],'int');
		$vClientPaymentMode	  = GetSQLValueString($rows['Client_PaymentMode'],'text');
		$vClientGrpCode		  = GetSQLValueString($rows['ClientGrp_Code'],'text');
		$vClientState		  = GetSQLValueString($rows['Client_State'],'text');
		$vClientCity		  = GetSQLValueString($rows['Client_City'],'text');
		$vClientCountry		  = GetSQLValueString($rows['Client_Country'],'text');
		$vClientGroup		  = GetSQLValueString($rows['Client_Group'],'text');
		$vClientMotherCompany = GetSQLValueString($rows['Client_MotherCompany'],'text');
		$vClientCompLegalType = GetSQLValueString($rows['Client_CompLegalType'],'text');
		$ClientCompOwner	  = GetSQLValueString($rows['Client_CompOwner'],'text');
		$vClientReferedBy	  = GetSQLValueString($rows['Client_ReferedBy'],'text');
		$vClientSDINo		  = GetSQLValueString($rows['Client_SDINo'],'text');
		$ClientDeliveryPhone  = GetSQLValueString($rows['Client_DeliveryPhone'],'text');
		$vClientDeliveryAddress   = GetSQLValueString($rows['Client_DeliveryAddress'],'text');
		$vClientDeliveryAssistant = GetSQLValueString($rows['Client_DeliveryAssistant'],'text');
		$vClientDlvAssistantTitle = GetSQLValueString($rows['Client_DlvAssistantTitle'],'text');
		$vClientEvaluationPoints  = GetSQLValueString($rows['Client_EvaluationPoints'],'text');
		$vClientTips		  = GetSQLValueString($rows['Client_Tips'],'text');
		$vClientArchiveFileNo = GetSQLValueString($rows['Client_ArchiveFileNo'],'text');
		$vClientGCIno		  = GetSQLValueString($rows['client_GCIno'],'text');
		$vCostCenterCode	  = GetSQLValueString($rows['CostCenter_Code'],'text');
		$vClientLocal 	 	  = GetSQLValueString($rows['client_local'],'int');
		$vClientExport 	 	  = GetSQLValueString($rows['client_export'],'int');
		$vClientDetail 	 	  = GetSQLValueString($rows['Client_Detail'],'int');
		$vClientDeliveryTransfer  = GetSQLValueString($rows['Client_DeliveryTransfer'],'int');
		$vClientRebate 	 	  = GetSQLValueString($rows['Client_Rebate'],'double');
		$vClientTarget 	 	  = GetSQLValueString($rows['Client_Target'],'double');
		$vCreationDate		  = GetSQLValueString($rows['Client_CreationDate'],'date');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		
				 
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Clients ".
						  " Where Upper(Ledger_number) = Upper(".$vClientCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Salesman_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vClientCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Clients',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Clients Set Synchronized = 0 ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Clients ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Clients (Ledger_number, Ledger_name, Ledger_Desc, Client_Work, Client_Address, Client_Telephone1, ".
							 " Client_Telephone2, Client_Fax, Client_Email, Client_homepage, Client_CreditLimit, Client_PaymentTerms, ".
							 " Client_Remark, Client_MaxDiscount, Area_Code, Salesmen_Code, Salesmen_Commission, Client_SellingPrice, ".
							 " Currency_Code, Client_VAT, Client_VatNo, Client_DiscountPer, ProfitCenter_CODE, Client_CashMode, ".
							 " Client_ChkTerms, Project_Code, Client_posted, Client_deactivatedate, Client_deactivate, Client_checkAccount, ".
							 " Client_BusinessType, Client_BelongsToGroup, Client_PaymentMode, ClientGrp_Code, Client_City, Client_State, ".
							 " Client_Country, Client_Group, Client_MotherCompany, Client_CompLegalType, Client_CompOwner, Client_ReferedBy, ".
							 " Client_SDINo, Client_DeliveryPhone, Client_DeliveryAddress, Client_DeliveryAssistant, Client_DlvAssistantTitle, ".
							 " Client_EvaluationPoints, Client_Tips, Client_ArchiveFileNo, Client_CreationDate, client_GCIno, CostCenter_Code,  ".
							 " client_local, client_export, Client_Detail, Client_DeliveryTransfer, Client_Rebate, Client_Target, Owner_Branch ) ".
							 " Values ( ".$vClientCode.", ".$vClientName.", ".$vLedgerDesc.", ".$vClientWork.", ".$vClientAddress.", ".$vClientTelephone1.
							 ", ".$vClientTelephone2.", ".$vClientFax.", ".$vClientEmail.", ".$vClientHomePage.", ".$vClientCreditLimit.", ".$vClientPaymentTerms.
							 ", ".$vClientRemark.", ".$vClientMaxDiscount.", ".$vAreaCode.", ".$vSalesmenCode.", ".$vSalesmenCommission.", ".$vClientSellingPrice.
							 ", ".$vCurrencyCode.", ".$vClientVAT.", ".$vClientVatNo.", ".$vClientDiscountPer.", ".$vProfitCenterCODE.", ".$vClientCashMode.
							 ", ".$vClientChkTerms.", ".$vProjectCode.", ".$vClientPosted.", ".$vClientdeactivatedate.", ".$vClientdeactivate.", ".$vClientCheckAccount.
							 ", ".$vClientBusinessType.", ".$vBelongsToGroup.", ".$vClientPaymentMode.", ".$vClientGrpCode.", ".$vClientCity.", ".$vClientState.
							 ", ".$vClientCountry.", ".$vClientGroup.", ".$vClientMotherCompany.", ".$vClientCompLegalType.", ".$ClientCompOwner.", ".$vClientReferedBy.
							 ", ".$vClientSDINo.", ".$ClientDeliveryPhone.", ".$vClientDeliveryAddress.", ".$vClientDeliveryAssistant.", ".$vClientDlvAssistantTitle.
							 ", ".$vClientEvaluationPoints.", ".$vClientTips.", ".$vClientArchiveFileNo.", ".$vCreationDate.", ".$vClientGCIno.", ".$vCostCenterCode.
							 ", ".$vClientLocal.", ".$vClientExport.", ".$vClientDetail.", ".$vClientDeliveryTransfer.", ".$vClientRebate.", ".$vClientTarget.", ".$vOwnerBranch." ) ";
			}	
			else {
				$sub_query = "  Update Clients Set Ledger_number = ".$vClientCode.", Ledger_name = ".$vClientName.", Ledger_Desc = ".$vLedgerDesc.
							 ", Client_Work = ".$vClientWork.", Client_Address = ".$vClientAddress.", Client_Telephone1 = ".$vClientTelephone1.
							 ", Client_Telephone2 = ".$vClientTelephone2.", Client_Fax = ".$vClientFax.", Client_Email = ".$vClientEmail.
							 ", Client_homepage = ".$vClientHomePage.", Client_CreditLimit = ".$vClientCreditLimit.", Client_PaymentTerms = ".$vClientPaymentTerms.
							 ", Client_Remark = ".$vClientRemark.", Client_MaxDiscount = ".$vClientMaxDiscount.", Area_Code = ".$vAreaCode.
							 ", Salesmen_Code = ".$vSalesmenCode.", Salesmen_Commission = ".$vSalesmenCommission.", Client_SellingPrice = ".$vClientSellingPrice.
							 ", Currency_Code = ".$vCurrencyCode.", Client_VAT = ".$vClientVAT.", Client_VatNo = ".$vClientVatNo.
							 ", Client_DiscountPer = ".$vClientDiscountPer.", ProfitCenter_CODE = ".$vProfitCenterCODE.", Client_CashMode = ".$vClientCashMode.
							 ", Client_ChkTerms = ".$vClientChkTerms.", Project_Code = ".$vProjectCode.", Client_posted = ".$vClientPosted.
							 ", Client_deactivatedate = ".$vClientdeactivatedate.", Client_deactivate = ".$vClientdeactivate.", Client_checkAccount = ".$vClientCheckAccount.
							 ", Client_BusinessType = ".$vClientBusinessType.", Client_BelongsToGroup = ".$vBelongsToGroup.", Client_PaymentMode = ".$vClientPaymentMode.
							 ", ClientGrp_Code = ".$vClientGrpCode.", Client_City = ".$vClientCity.", Client_State = ".$vClientState.
							 ", Client_Country = ".$vClientCountry.", Client_Group = ".$vClientGroup.", Client_MotherCompany = ".$vClientMotherCompany.
							 ", Client_CompLegalType = ".$vClientCompLegalType.", Client_CompOwner = ".$ClientCompOwner.", Client_ReferedBy = ".$vClientReferedBy.
							 ", Client_SDINo = ".$vClientSDINo.", Client_DeliveryPhone = ".$ClientDeliveryPhone.", Client_DeliveryAddress = ".$vClientDeliveryAddress.
							 ", Client_DeliveryAssistant = ".$vClientDeliveryAssistant.", Client_DlvAssistantTitle = ".$vClientDlvAssistantTitle.
							 ", Client_EvaluationPoints = ".$vClientEvaluationPoints.", Client_Tips = ".$vClientTips.", Client_ArchiveFileNo = ".$vClientArchiveFileNo.
							 ", Client_CreationDate = ".$vCreationDate.", client_GCIno = ".$vClientGCIno.", CostCenter_Code = ".$vCostCenterCode.
							 ", client_local = ".$vClientLocal.", client_export = ".$vClientExport.", Client_Detail = ".$vClientDetail.
							 ", Client_DeliveryTransfer = ".$vClientDeliveryTransfer.", Client_Rebate = ".$vClientRebate.", Client_Target = ".$vClientTarget.
							 "  Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Clients Set Synchronized = 1 ".
							  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);	
						
				//InCase Update, Delete All Related Details In TelephoneNo
				If ($vRecordExists > 0) {
					$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
					
					$query = "Delete From ClientsIP Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From TelephoneNo
				$query = " Select Telephone_increment, Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, ".
						 " TelephoneNo_ContactTitle, TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname,  ".
						 " telephoneno_email, telephoneno_reference, telephoneno_city1, telephoneno_city2, telephoneno_city3  ".
						 " From TelephoneNo ".
						 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
										
					$sub_query = " Insert Into TelephoneNo (Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, TelephoneNo_ContactTitle, ".
								 " TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname, telephoneno_email, telephoneno_reference, ".
							     " telephoneno_city1, telephoneno_city2, telephoneno_city3) ".
								 " Values ( ".GetSQLValueString($rows['Ledger_number'],'text').", ".GetSQLValueString($rows['TelephoneNo'],'text').
								 ", ".GetSQLValueString($rows['Telephone_name'],'text').", ".GetSQLValueString($rows['Telephone_posted'],'int').
								 ", ".GetSQLValueString($rows['TelephoneNo_ContactTitle'],'text').", ".GetSQLValueString($rows['TelephoneNo2'],'text').
								 ", ".GetSQLValueString($rows['TelephoneNo3'],'text').", ".GetSQLValueString($rows['telephoneno_fname'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_lname'],'text').", ".GetSQLValueString($rows['telephoneno_email'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_reference'],'text').", ".GetSQLValueString($rows['telephoneno_city1'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_city2'],'text').", ".GetSQLValueString($rows['telephoneno_city3'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		
											
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Ledger_number']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'TelephoneNo',$vMessage);
						
						break;
					}	
				}
				
				//Insert Related Details From ClientsIP
				$query = " Select Clientip_id, Ledger_number, Clientip_IP, Clientip_upload, Clientip_download, Clientip_startDate, ".
						 " ClientIP_EndDate, Currency_code, Clientip_amount, Project_Code, Costcenter_code, ClientIP_LastTransDate, ".
						 " Area_Code, ClientIP_PeriodByMonth, Client_MacAddress, Client_port, Reason_disabled, Technician_Name,  ".
						 " Modem_IP, Subscriber_Name, Subscriber_Address, Client_Inst_Month, Client_Category, Client_TC,  ".
						 " Clientip_OldTransDate, Collection_name, service_name ".
						 " From ClientsIP ".
						 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
				
					$vClientsIPID = GetNextSequence1($PDestConn,'Delivery_ID','');
										
					$sub_query = " Insert Into ClientsIP (Clientip_id, Ledger_number, Clientip_IP, Clientip_upload, Clientip_download, Clientip_startDate, ".
								 " ClientIP_EndDate, Currency_code, Clientip_amount, Project_Code, Costcenter_code, ClientIP_LastTransDate, ".
								 " Area_Code, ClientIP_PeriodByMonth, Client_MacAddress, Client_port, Reason_disabled, Technician_Name,  ".
								 " Modem_IP, Subscriber_Name, Subscriber_Address, Client_Inst_Month, Client_Category, Client_TC,  ".
								 " Clientip_OldTransDatec, Collection_name, service_name ) ".
								 " Values ( ".$vClientsIPID.", ".GetSQLValueString($rows['Ledger_number'],'text').", ".GetSQLValueString($rows['Clientip_IP'],'text').
								 ", ".GetSQLValueString($rows['Clientip_upload'],'double').", ".GetSQLValueString($rows['Clientip_download'],'double').
								 ", ".GetSQLValueString($rows['Clientip_startDate'],'date').", ".GetSQLValueString($rows['ClientIP_EndDate'],'date').
								 ", ".GetSQLValueString($rows['Currency_code'],'text').", ".GetSQLValueString($rows['Clientip_amount'],'double').
								 ", ".GetSQLValueString($rows['Project_Code'],'text').", ".GetSQLValueString($rows['Costcenter_code'],'text').
								 ", ".GetSQLValueString($rows['ClientIP_LastTransDate'],'date').", ".GetSQLValueString($rows['Area_Code'],'text').
								 ", ".GetSQLValueString($rows['ClientIP_PeriodByMonth'],'double').", ".GetSQLValueString($rows['Client_MacAddress'],'text').
								 ", ".GetSQLValueString($rows['Client_port'],'double').", ".GetSQLValueString($rows['Reason_disabled'],'text').
								 ", ".GetSQLValueString($rows['Technician_Name'],'double').", ".GetSQLValueString($rows['Modem_IP'],'text').
								 ", ".GetSQLValueString($rows['Subscriber_Name'],'double').", ".GetSQLValueString($rows['Subscriber_Address'],'text').
								 ", ".GetSQLValueString($rows['Client_Inst_Month'],'date').", ".GetSQLValueString($rows['Client_Category'],'text').
								 ", ".GetSQLValueString($rows['Client_TC'],'text').", ".GetSQLValueString($rows['Clientip_OldTransDatec'],'date').
								 ", ".GetSQLValueString($rows['Collection_name'],'text').", ".GetSQLValueString($rows['service_name'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		
											
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Ledger_number']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'ClientsIP',$vMessage);
						
						break;
					}	
				}
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Clients',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Ledger_number, Owner_Branch ".
					 " From Clients Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vClientCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From ClientsIP Where Upper(Ledger_number) = Upper('".$vClientCode."')";
		$result = mysql_query($query, $PDestConn);
		
		$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$vClientCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Clients Where Upper(Ledger_number) = Upper('".$vClientCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Clients',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vClientCode  = trim($vClientCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vClientCode,$vOwnerBranch);
	}

	Return $vResult;

}


function F_SynchroSuppliers($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Ledger_number, Ledger_name, Ledger_Desc, Supplier_Representative, Supplier_Address, Supplier_Telephone1, ".
				 " Supplier_Telephone2, Supplier_Fax, Supplier_Email, Supplier_Homepage, Supplier_CreditLimit, Supplier_PaymentTerms, ".
				 " Suplier_Remark, Area_Code, Currency_Code, Supplier_VAT, Supplier_VatNo, Supplier_VatDate, Supplier_Approved, ".
				 " Supplier_BelongsToGroup, Supplier_Address2, Supplier_City, Supplier_State, Supplier_Country, Supplier_Group, ".
				 " SupplierGrp_Code, Project_Code, Costcenter_Code, Supplier_Tax1, Supplier_Tax2, Supplier_Tax3, Supplier_Tax4, ".
				 " Supplier_Tax5, Supplier_GCINO, Supplier_CompOwnerTitle, Supplier_CompOwner, Supplier_ReferedByTitle, Supplier_ReferedBy, ".
				 " Supplier_BusinessSector, Supplier_BusinessSectorDesc, Supplier_MotherCompany, Supplier_BType2, Supplier_BType3, ".
				 " Supplier_SubContractor, Supplier_TaxPercantage, Supplier_Import, Supplier_Export, Supplier_CreationDate, Owner_Branch ".
				 " From Suppliers ".
				 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vSalesmanId		  = GetSQLValueString($rows['Salesman_Id'],'int');
		$vSupplierCode 	  	  = GetSQLValueString($rows['Ledger_number'],'text');
		$vSupplierName 	 	  = GetSQLValueString($rows['Ledger_name'],'text');
		$vLedgerDesc   	 	  = GetSQLValueString($rows['Ledger_Desc'],'text');
		$vRepresentative  	  = GetSQLValueString($rows['Supplier_Representative'],'text');
		$vSupplierAddress     = GetSQLValueString($rows['Supplier_Address'],'text');
		$vSupplierTelephone1  = GetSQLValueString($rows['Supplier_Telephone1'],'text');
		$vSupplierTelephone2  = GetSQLValueString($rows['Supplier_Telephone2'],'text');
		$vSupplierFax   	  = GetSQLValueString($rows['Supplier_Fax'],'text');
		$vSupplierEmail 	  = GetSQLValueString($rows['Supplier_Email'],'text');
		$vSuplierRemark   	  = GetSQLValueString($rows['Suplier_Remark'],'text');
		$vSupplierHomepage	  = GetSQLValueString($rows['Supplier_Homepage'],'text');
		$vSupplierCreditLimit = GetSQLValueString($rows['Supplier_CreditLimit'],'double');
		$vSuppPaymentTerms    = GetSQLValueString($rows['Supplier_PaymentTerms'],'double');
		$vAreaCode 			  = GetSQLValueString($rows['Area_Code'],'text');
		$vCurrencyCode  	  = GetSQLValueString($rows['Currency_Code'],'text');
		$vSupplierVAT 	 	  = GetSQLValueString($rows['Supplier_VAT'],'int');
		$vSupplierVatNo  	  = GetSQLValueString($rows['Supplier_VatNo'],'text');
		$vSupplierVatDate     = GetSQLValueString($rows['Supplier_VatDate'],'date');
		$vSupplierApproved 	  = GetSQLValueString($rows['Supplier_Approved'],'text');
		$vBelongsToGroup 	  = GetSQLValueString($rows['Supplier_BelongsToGroup'],'int');
		$vSupplierAddress2 	  = GetSQLValueString($rows['Supplier_Address2'],'text');
		$vSupplierState		  = GetSQLValueString($rows['Supplier_State'],'text');
		$vSupplierCity		  = GetSQLValueString($rows['Supplier_City'],'text');
		$vSupplierCountry	  = GetSQLValueString($rows['Supplier_Country'],'text');
		$vSupplierGroup		  = GetSQLValueString($rows['Supplier_Group'],'text');
		$vSupplierGrpCode	  = GetSQLValueString($rows['SupplierGrp_Code'],'text');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostCenterCode	  = GetSQLValueString($rows['Costcenter_Code'],'text');
		$vSupplierTax1		  = GetSQLValueString($rows['Supplier_Tax1'],'int');
		$vSupplierTax2		  = GetSQLValueString($rows['Supplier_Tax2'],'int');
		$vSupplierTax3		  = GetSQLValueString($rows['Supplier_Tax3'],'int');
		$vSupplierTax4		  = GetSQLValueString($rows['Supplier_Tax4'],'int');
		$vSupplierTax5		  = GetSQLValueString($rows['Supplier_Tax5'],'int');
		$vSupplierGCINO	 	  = GetSQLValueString($rows['Supplier_GCINO'],'text');
		$vCompOwnerTitle	  = GetSQLValueString($rows['Supplier_CompOwnerTitle'],'text');
		$vSupplierCompOwner	  = GetSQLValueString($rows['Supplier_CompOwner'],'text');
		$vReferedByTitle   	  = GetSQLValueString($rows['Supplier_ReferedByTitle'],'text');
		$vSupplierReferedBy   = GetSQLValueString($rows['Supplier_ReferedBy'],'text');
		$vBusinessSector	  = GetSQLValueString($rows['Supplier_BusinessSector'],'text');
		$vBusinessSectorDesc  = GetSQLValueString($rows['Supplier_BusinessSectorDesc'],'text');
		$vMotherCompany		  = GetSQLValueString($rows['Supplier_MotherCompany'],'text');
		$vSupplierBType2	  = GetSQLValueString($rows['Supplier_BType2'],'text');
		$vSupplierBType3	  = GetSQLValueString($rows['Supplier_BType3'],'text');
		$vSubContractor		  = GetSQLValueString($rows['Supplier_SubContractor'],'int');
		$vTaxPercantage		  = GetSQLValueString($rows['Supplier_TaxPercantage'],'double');
		$vSupplierImport  	  = GetSQLValueString($rows['Supplier_Import'],'int');
		$vSupplierExport  	  = GetSQLValueString($rows['Supplier_Export'],'int');
		$vCreationDate		  = GetSQLValueString($rows['Supplier_CreationDate'],'date');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		
				 
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Suppliers ".
						  " Where Upper(Ledger_number) = Upper(".$vSupplierCode.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Supplier_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vSupplierCode;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Suppliers',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Suppliers Set Synchronized = 0 ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Suppliers ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Suppliers (Ledger_number, Ledger_name, Ledger_Desc, Supplier_Representative, Supplier_Address, Supplier_Telephone1, ".
							 " Supplier_Telephone2, Supplier_Fax, Supplier_Email, Supplier_Homepage, Supplier_CreditLimit, Supplier_PaymentTerms, ".
							 " Suplier_Remark, Area_Code, Currency_Code, Supplier_VAT, Supplier_VatNo, Supplier_VatDate, Supplier_Approved, ".
							 " Supplier_BelongsToGroup, Supplier_Address2, Supplier_City, Supplier_State, Supplier_Country, Supplier_Group, ".
							 " SupplierGrp_Code, Project_Code, Costcenter_Code, Supplier_Tax1, Supplier_Tax2, Supplier_Tax3, Supplier_Tax4, ".
							 " Supplier_Tax5, Supplier_GCINO, Supplier_CompOwnerTitle, Supplier_CompOwner, Supplier_ReferedByTitle, Supplier_ReferedBy, ".
							 " Supplier_BusinessSector, Supplier_BusinessSectorDesc, Supplier_MotherCompany, Supplier_BType2, Supplier_BType3, ".
							 " Supplier_SubContractor, Supplier_TaxPercantage, Supplier_Import, Supplier_Export, Supplier_CreationDate, Owner_Branch  ) ".
							 " Values ( ".$vSupplierCode.", ".$vSupplierName.", ".$vLedgerDesc.", ".$vRepresentative.", ".$vSupplierAddress.", ".$vSupplierTelephone1.
							 ", ".$vSupplierTelephone2.", ".$vSupplierFax.", ".$vSupplierEmail.", ".$vSupplierHomepage.", ".$vSupplierCreditLimit.", ".$vSuppPaymentTerms.
							 ", ".$vSuplierRemark.", ".$vAreaCode.", ".$vCurrencyCode.", ".$vSupplierVAT.", ".$vSupplierVatNo.", ".$vSupplierVatDate.", ".$vSupplierApproved.
							 ", ".$vBelongsToGroup.", ".$vSupplierAddress2.", ".$vSupplierCity.", ".$vSupplierState.", ".$vSupplierCountry.", ".$vSupplierGroup.
							 ", ".$vSupplierGrpCode.", ".$vProjectCode.", ".$vCostCenterCode.", ".$vSupplierTax1.", ".$vSupplierTax2.", ".$vSupplierTax3.
							 ", ".$vSupplierTax4.", ".$vSupplierTax5.", ".$vSupplierGCINO.", ".$vCompOwnerTitle.", ".$vSupplierCompOwner.", ".$vReferedByTitle.
							 ", ".$vSupplierReferedBy.", ".$vBusinessSector.", ".$vBusinessSectorDesc.", ".$vMotherCompany.", ".$vSupplierBType2.", ".$vSupplierBType3.
							 ", ".$vSubContractor.", ".$vTaxPercantage.", ".$vSupplierImport.", ".$vSupplierExport.", ".$vCreationDate.", ".$vOwnerBranch." ) ";
							 
			}	
			else {
				$sub_query = "  Update Suppliers Set Ledger_number = ".$vSupplierCode.", Ledger_name = ".$vSupplierName.", Ledger_Desc = ".$vLedgerDesc.
							 ", Supplier_Representative = ".$vRepresentative.", Supplier_Address = ".$vSupplierAddress.", Supplier_Telephone1 = ".$vSupplierTelephone1.
							 ", Supplier_Telephone2 = ".$vSupplierTelephone2.", Supplier_Fax = ".$vSupplierFax.", Supplier_Email = ".$vSupplierEmail.
							 ", Supplier_Homepage = ".$vSupplierHomepage.", Supplier_CreditLimit = ".$vSupplierCreditLimit.", Supplier_PaymentTerms = ".$vSuppPaymentTerms.
							 ", Suplier_Remark = ".$vSuplierRemark.", Area_Code = ".$vAreaCode.", Currency_Code = ".$vCurrencyCode.
							 ", Supplier_VAT = ".$vSupplierVAT.", Supplier_VatNo = ".$vSupplierVatNo.", Supplier_VatDate = ".$vSupplierVatDate.
							 ", Supplier_Approved = ".$vSupplierApproved.", Supplier_BelongsToGroup = ".$vBelongsToGroup.", Supplier_Address2 = ".$vSupplierAddress2.
							 ", Supplier_City = ".$vSupplierCity.", Supplier_State = ".$vSupplierState.", Supplier_Country = ".$vSupplierCountry.
							 ", Supplier_Group = ".$vSupplierGroup.", SupplierGrp_Code = ".$vSupplierGrpCode.", Project_Code = ".$vProjectCode.
							 ", Costcenter_Code = ".$vCostCenterCode.", Supplier_Tax1 = ".$vSupplierTax1.", Supplier_Tax2 = ".$vSupplierTax2.
							 ", Supplier_Tax3 = ".$vSupplierTax3.", Supplier_Tax4 = ".$vSupplierTax4.", Supplier_Tax5 = ".$vSupplierTax5.
							 ", Supplier_GCINO = ".$vSupplierGCINO.", Supplier_CompOwnerTitle = ".$vCompOwnerTitle.", Supplier_CompOwner = ".$vSupplierCompOwner.
							 ", Supplier_ReferedByTitle = ".$vReferedByTitle.", Supplier_ReferedBy = ".$vSupplierReferedBy.", Supplier_BusinessSector = ".$vBusinessSector.
							 ", Supplier_BusinessSectorDesc = ".$vBusinessSectorDesc.", Supplier_MotherCompany = ".$vMotherCompany.", Supplier_BType2 = ".$vSupplierBType2.
							 ", Supplier_BType3 = ".$vSupplierBType3.", Supplier_SubContractor = ".$vSubContractor.", Supplier_TaxPercantage = ".$vTaxPercantage.
							 ", Supplier_Import = ".$vSupplierImport.", Supplier_Export = ".$vSupplierExport.
							 "  Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				$vResult = 'T';
				
				$sub_query  = " Update Suppliers Set Synchronized = 1 ".
							  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);		
				
				//InCase Update, Delete All Related Details In TelephoneNo
				If ($vRecordExists > 0) {
					$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
					$result = mysql_query($query, $PDestConn);
				}
				
				//Insert Related Details From TelephoneNo
				$query = " Select Telephone_increment, Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, ".
						 " TelephoneNo_ContactTitle, TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname,  ".
						 " telephoneno_email, telephoneno_reference, telephoneno_city1, telephoneno_city2, telephoneno_city3  ".
						 " From TelephoneNo ".
						 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				//echo $query; exit;		 
				$result=mysql_query($query,$PLocConn) or die(mysql_error());
				while($rows=mysql_fetch_assoc($result)){
										
					$sub_query = " Insert Into TelephoneNo (Ledger_number, TelephoneNo, Telephone_name, Telephone_posted, TelephoneNo_ContactTitle, ".
								 " TelephoneNo2, TelephoneNo3, telephoneno_fname, telephoneno_lname, telephoneno_email, telephoneno_reference, ".
							     " telephoneno_city1, telephoneno_city2, telephoneno_city3) ".
								 " Values ( ".GetSQLValueString($rows['Ledger_number'],'text').", ".GetSQLValueString($rows['TelephoneNo'],'text').
								 ", ".GetSQLValueString($rows['Telephone_name'],'text').", ".GetSQLValueString($rows['Telephone_posted'],'int').
								 ", ".GetSQLValueString($rows['TelephoneNo_ContactTitle'],'text').", ".GetSQLValueString($rows['TelephoneNo2'],'text').
								 ", ".GetSQLValueString($rows['TelephoneNo3'],'text').", ".GetSQLValueString($rows['telephoneno_fname'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_lname'],'text').", ".GetSQLValueString($rows['telephoneno_email'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_reference'],'text').", ".GetSQLValueString($rows['telephoneno_city1'],'text').
								 ", ".GetSQLValueString($rows['telephoneno_city2'],'text').", ".GetSQLValueString($rows['telephoneno_city3'],'text')." )";
								 
					//echo $sub_query; exit;	 
					$sub_result=mysql_query($sub_query,$PDestConn);	
					if ($sub_result) {
						$vResult = 'T';		
						
					} else {
						$vResult  = 'P';
						$vMessage = mysql_error();
						$vMessage = GetSQLValueString("Insert Code= ".$rows['Ledger_number']." : ".$vMessage,'text');
						$vError   = InsertLog($PLocConn,'TelephoneNo',$vMessage);
						
						break;
					}	
				}
				
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Suppliers',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Ledger_number, Owner_Branch ".
					 " From Suppliers Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vSupplierCode = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From TelephoneNo Where Upper(Ledger_number) = Upper('".$vSupplierCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Suppliers Where Upper(Ledger_number) = Upper('".$vSupplierCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Suppliers',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vSupplierCode = trim($vSupplierCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vSupplierCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_SynchroLedger($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Ledger_number, Ledger_name, Ledger_Desc, Ledger_grpdet, Ledger_activity, Document, Ledger_number2, ".
				 " Ledger_name2, Acctype_increment, Project_Code, CostCenter_code, CashType_Code, ledger_type, Ledger_Deactivate, ".
				 " Ledger_RequiredDetail, Ledger_inactive, Ledger_inactivedate, Currency_Code, Ledger_BelongsToGroup, Ledger_WHT, ".
				 " Owner_Branch ".
				 " From Ledger ".
				 " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		$vLedgerNumber 	  	  = GetSQLValueString($rows['Ledger_number'],'text');
		$vLedgerName 	 	  = GetSQLValueString($rows['Ledger_name'],'text');
		$vLedgerDesc   	 	  = GetSQLValueString($rows['Ledger_Desc'],'text');
		$vLedgergrpdet  	  = GetSQLValueString($rows['Ledger_grpdet'],'int');
		$vLedgerActivity 	  = GetSQLValueString($rows['Ledger_activity'],'int');
		$vDocument			  = GetSQLValueString($rows['Document'],'text');
		$vLedgerNumber2		  = GetSQLValueString($rows['Ledger_number2'],'text');
		$vLedgerName2   	  = GetSQLValueString($rows['Ledger_name2'],'text');
		$vAcctypeincrement 	  = GetSQLValueString($rows['Acctype_increment'],'int');
		$vProjectCode		  = GetSQLValueString($rows['Project_Code'],'text');
		$vCostCenterCode	  = GetSQLValueString($rows['CostCenter_code'],'text');
		$vCashTypeCode		  = GetSQLValueString($rows['CashType_Code'],'double');
		$vLedgerType 		  = GetSQLValueString($rows['ledger_type'],'int');
		$vLedgerDeactivate 	  = GetSQLValueString($rows['Ledger_Deactivate'],'int');
		$vRequiredDetail 	  = GetSQLValueString($rows['Ledger_RequiredDetail'],'int');
		$vLedgerinactive 	  = GetSQLValueString($rows['Ledger_inactive'],'int');
		$vLedgerinactivedate  = GetSQLValueString($rows['Ledger_inactivedate'],'date');
		$vCurrencyCode  	  = GetSQLValueString($rows['Currency_Code'],'text');
		$vBelongsToGroup 	  = GetSQLValueString($rows['Ledger_BelongsToGroup'],'int');
		$vLedgerWHT 		  = GetSQLValueString($rows['Ledger_WHT'],'int');
		$vOwnerBranch 		  = GetSQLValueString($rows['Owner_Branch'],'text');
		
				 
		//Check For Duplicate of Code InCase Insert
		$vDuplicateExists = 0;
		If ($PState == 'I')	{
			$sub_query  = " Select Count(*) From Ledger ".
						  " Where Upper(Ledger_number) = Upper(".$vLedgerNumber.") ";
						  
			//If ($PState == 'U')	$sub_query = $sub_query." And Ledger_ID != '".$PRecordID."'";			  
			$sub_result = selectData($PDestConn, $sub_query);
			$vDuplicateExists = $sub_result[0];
		}	
		if ($vDuplicateExists > 0) {
			$vResult  = 'P';
			$vMessage = 'Duplicate Code: '.$vLedgerNumber;
			$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Ledger',$vMessage);
		}
		
		if ($vResult != 'P') {
			$sub_query  = " Update Ledger Set Synchronized = 0 ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result=mysql_query($sub_query,$PLocConn);
						  
			$sub_query  = " Select Count(*) From Ledger ".
						  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			$sub_result = selectData($PDestConn, $sub_query);
			$vRecordExists = $sub_result[0];
			
			//Case Record Doesn't Exists - Insert
			If ($vRecordExists == 0) {	
				$sub_query = " Insert Into Ledger (Ledger_number, Ledger_name, Ledger_Desc, Ledger_grpdet, Ledger_activity, Document, Ledger_number2, ".
							 " Ledger_name2, Acctype_increment, Project_Code, CostCenter_code, CashType_Code, ledger_type, Ledger_Deactivate, ".
							 " Ledger_RequiredDetail, Ledger_inactive, Ledger_inactivedate, Currency_Code, Ledger_BelongsToGroup, Ledger_WHT, ".
							 " Owner_Branch  ) ".
							 " Values ( ".$vLedgerNumber.", ".$vLedgerName.", ".$vLedgerDesc.", ".$vLedgergrpdet.", ".$vLedgerActivity.", ".$vDocument.
							 ", ".$vLedgerNumber2.", ".$vLedgerName2.", ".$vAcctypeincrement.", ".$vProjectCode.", ".$vCostCenterCode.", ".$vCashTypeCode.
							 ", ".$vLedgerType.", ".$vLedgerDeactivate.", ".$vRequiredDetail.", ".$vLedgerinactive.", ".$vLedgerinactivedate.", ".$vCurrencyCode.
							 ", ".$vBelongsToGroup.", ".$vLedgerWHT.", ".$vOwnerBranch." ) ";
							 
			}	
			else {
				$sub_query = "  Update Ledger Set Ledger_number = ".$vLedgerNumber.", Ledger_name = ".$vLedgerName.", Ledger_Desc = ".$vLedgerDesc.
							 ", Ledger_grpdet = ".$vLedgergrpdet.", Ledger_activity = ".$vLedgerActivity.", Document = ".$vDocument.
							 ", Ledger_number2 = ".$vLedgerNumber2.", Ledger_name2 = ".$vLedgerName2.", Acctype_increment = ".$vAcctypeincrement.
							 ", Project_Code = ".$vProjectCode.", CostCenter_code = ".$vCostCenterCode.", CashType_Code = ".$vCashTypeCode.
							 ", ledger_type = ".$vLedgerType.", Ledger_Deactivate = ".$vLedgerDeactivate.", Ledger_RequiredDetail = ".$vRequiredDetail.
							 ", Ledger_inactive = ".$vLedgerinactive.", Ledger_inactivedate = ".$vLedgerinactivedate.", Currency_Code = ".$vCurrencyCode.
							 ", Ledger_BelongsToGroup = ".$vBelongsToGroup.", Ledger_WHT = ".$vLedgerWHT.
							 "  Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
			}

			//echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$PDestConn);

			if ($sub_result) {
				
				$vResult = 'T';		

				$sub_query  = " Update Ledger Set Synchronized = 1 ".
							  " Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);						
			} else {
				$vResult  = 'P';
				$vMessage = mysql_error();
				$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
				$vError   = InsertLog($PLocConn,'Ledger',$vMessage);
			}
		}	
		
	}
	else if ($PState == 'D') {
		$sub_query = " Select Ledger_number, Owner_Branch ".
					 " From Ledger Where Upper(Ledger_number) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vLedgerNumber = $sub_result[0];
		$vOwnerBranch  = $sub_result[1];
		
		$query = "Delete From Ledger Where Upper(Ledger_number) = Upper('".$vLedgerNumber."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Ledger',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch  = trim($vOwnerBranch,"'");
		$vLedgerNumber = trim($vLedgerNumber,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vLedgerNumber,$vOwnerBranch);
	}

	Return $vResult;

}


function F_SynchroItems($PTableName, $PRecordID, $PRecordCode, $PState, $PBranchCode, $PSynchroAll, $PLocConn, $PDestConn) {
	If ($PState == 'I' || $PState == 'U'){
		$query = " Select Item_Code, Item_Description, Item_Barcode, Currency_code, Project_Code, CostCent_Code, ".
				 " Group_code, SubGroup_Code, Ledger_Number, Item_Remark, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
				 " Category_code, Item_Picture, Expire_Date, Item_Posted, Item_Package, Item_Vat, Item_Barcode2, ".
				 " Item_Barcode3, Item_Active, Item_TTCInclude, Item_BelongsToGroup, Item_CostMethod, Item_QtyToBeProduced, ".
				 " Item_WithSerialno, Item_ZeroPrice, Item_Visible, Item_Production, Item_LastDatePurchase, ".
				 " Item_LastPricePurchase, Item_NonStock, Item_Transfer, Item_Pack, Item_Weight, Item_SemiFinished, Item_FixedAsset, ".
				 " Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_Grammage, Item_ReverseProduction,  ".
				 " Item_SysDateTime, Item_InactiveDate, Item_Promotion, Item_Height, Item_Length, Item_Width, Item_Policy, ".
				 " Item_Discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, Item_Expire, Item_MinimumPrice, ".
				 " Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, ".
				 " Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, ".
				 " Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, ".
				 " Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, ItemSelling1TTCBase1, ItemSelling2TTCBase2, ".
				 " ItemSelling3TTCBase2, ItemSelling4TTCBase1, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ".
				 " ItemSelling4TTCBase2, Synchronized, Item_LongDescription, Item_MaxQty, Item_MinQty, Item_Unit, Owner_Branch ".
				 " From Items ".
				 " Where Upper(Item_Code) = Upper('".$PRecordCode."')";
				 
		//echo $query; exit;		 
		$result=mysql_query($query,$PLocConn) or die(mysql_error());
		$rows=mysql_fetch_assoc($result);
		
		//$vItemId			    = GetSQLValueString($rows['Item_Id'],'int');
		$vItemCode   		    = GetSQLValueString($rows['Item_Code'],'text');
		$vItemDescription   	= GetSQLValueString($rows['Item_Description'],'text');
		$vItemBarcode	 		= GetSQLValueString($rows['Item_Barcode'],'text');
		$vCurrencyCode	 		= GetSQLValueString($rows['Currency_code'],'text');
		$vProjectCode	 		= GetSQLValueString($rows['Project_Code'],'text');
		$vCostCentCode	 		= GetSQLValueString($rows['CostCent_Code'],'text');
		$vGroupCode	 		    = GetSQLValueString($rows['Group_code'],'text');
		$vSubGroupCode	  	    = GetSQLValueString($rows['SubGroup_Code'],'text');
		$vLedgerNumber	  	    = GetSQLValueString($rows['Ledger_Number'],'text');
		$vItemRemark		    = GetSQLValueString($rows['Item_Remark'],'text');
		$vItemUnitPurchaseDesc	= GetSQLValueString($rows['Item_UnitPurchaseDesc'],'text');
		$vItemUnitSalesDesc	  	= GetSQLValueString($rows['Item_UnitSalesDesc'],'text');
		$vCategoryCode			= GetSQLValueString($rows['Category_code'],'text');
		$vItemPicture		    = GetSQLValueString($rows['Item_Picture'],'text');
		$vExpireDate		    = GetSQLValueString($rows['Expire_Date'],'date');
		$vItemPosted 			= GetSQLValueString($rows['Item_Posted'],'int');
		$vItemPackage		    = GetSQLValueString($rows['Item_Package'],'text');
		$vItemVat	 		    = GetSQLValueString($rows['Item_Vat'],'double');
		$vItemBarcode2			= GetSQLValueString($rows['Item_Barcode2'],'text');
		$vItemBarcode3	 		= GetSQLValueString($rows['Item_Barcode3'],'text');
		$vItemActive 		    = GetSQLValueString($rows['Item_Active'],'int');
		$vItemTTCInclude 		= GetSQLValueString($rows['Item_TTCInclude'],'int');
		$vBelongsToGroup 		= GetSQLValueString($rows['Item_BelongsToGroup'],'int');
		$vItemCostMethod 		= GetSQLValueString($rows['Item_CostMethod'],'int');
		$vItemQtyToBeProduced	= GetSQLValueString($rows['Item_QtyToBeProduced'],'double');
		$vItemWithSerialno		= GetSQLValueString($rows['Item_WithSerialno'],'int');
		$vItemZeroPrice		    = GetSQLValueString($rows['Item_ZeroPrice'],'int');
		$vItemVisible 			= GetSQLValueString($rows['Item_Visible'],'int');
		$vItemProduction		= GetSQLValueString($rows['Item_Production'],'int');
		$vLastDatePurchase 		= GetSQLValueString($rows['Item_LastDatePurchase'],'date');
		$vLastPricePurchase		= GetSQLValueString($rows['Item_LastPricePurchase'],'double');
		$vItemNonStock 			= GetSQLValueString($rows['Item_NonStock'],'int');
		$vItemTransfer 			= GetSQLValueString($rows['Item_Transfer'],'int');
		$vItemPack 				= GetSQLValueString($rows['Item_Pack'],'int');
		$vItemWeight 			= GetSQLValueString($rows['Item_Weight'],'double');
		$vItemSemiFinished		= GetSQLValueString($rows['Item_SemiFinished'],'int');
		$vItemFixedAsset 		= GetSQLValueString($rows['Item_FixedAsset'],'int');
		$vItemTax	 			= GetSQLValueString($rows['Item_Tax'],'double');
		$vItemTax1	 			= GetSQLValueString($rows['Item_Tax1'],'double');
		$vItemTax2	 			= GetSQLValueString($rows['Item_Tax2'],'double');
		$vItemTax3 			 	= GetSQLValueString($rows['Item_Tax3'],'double');
		$vItemTax4		 	 	= GetSQLValueString($rows['Item_Tax4'],'double');
		$vItemTax5 			 	= GetSQLValueString($rows['Item_Tax5'],'double');
		$vItemGrammage 			= GetSQLValueString($rows['Item_Grammage'],'double');
		$vReverseProduction		= GetSQLValueString($rows['Item_ReverseProduction'],'int');
		$vItemSysDateTime 		= GetSQLValueString($rows['Item_SysDateTime'],'date');
		$vItemInactiveDate 		= GetSQLValueString($rows['Item_InactiveDate'],'date');
		$vItemPromotion			= GetSQLValueString($rows['Item_Promotion'],'int');
		$vItemHeight 			= GetSQLValueString($rows['Item_Height'],'double');
		$vItemLength 			= GetSQLValueString($rows['Item_Length'],'double');
		$vItemWidth 			= GetSQLValueString($rows['Item_Width'],'double');
		$vItemPolicy 			= GetSQLValueString($rows['Item_Policy'],'text');
		$vItemDiscount 			= GetSQLValueString($rows['Item_Discount'],'double');
		$vModifySellingPrice	= GetSQLValueString($rows['Item_ModifySellingPrice'],'int');
		$vItemVolume 			= GetSQLValueString($rows['Item_Volume'],'double');
		$vItemColor			 	= GetSQLValueString($rows['Item_Color'],'text');
		$vItemSize			 	= GetSQLValueString($rows['Item_Size'],'text');
		$vItemExpire			= GetSQLValueString($rows['Item_Expire'],'int');
		$vItemMinimumPrice 		= GetSQLValueString($rows['Item_MinimumPrice'],'double');
		$vSellingPrice1 		= GetSQLValueString($rows['Item_SellingPrice1'],'double');
		$vSellingPrice1Base1	= GetSQLValueString($rows['Item_SellingPrice1Base1'],'double');
		$vSellingPrice1Base2 	= GetSQLValueString($rows['Item_SellingPrice1Base2'],'double');
		$vSellingPrice2 		= GetSQLValueString($rows['Item_SellingPrice2'],'double');
		$vSellingPrice2Base1	= GetSQLValueString($rows['Item_SellingPrice2Base1'],'double');
		$vSellingPrice2Base2	= GetSQLValueString($rows['Item_SellingPrice2Base2'],'double');
		$vSellingPrice3 		= GetSQLValueString($rows['Item_SellingPrice3'],'double');
		$vSellingPrice3Base1	= GetSQLValueString($rows['Item_SellingPrice3Base1'],'double');
		$vSellingPrice3Base2	= GetSQLValueString($rows['Item_SellingPrice3Base2'],'double');
		$vSellingPrice4 		= GetSQLValueString($rows['Item_SellingPrice4'],'double');
		$vSellingPrice4Base1	= GetSQLValueString($rows['Item_SellingPrice4Base1'],'double');
		$vSellingPrice4Base2 	= GetSQLValueString($rows['Item_SellingPrice4Base2'],'double');
		$vSellingPrice5 		= GetSQLValueString($rows['Item_SellingPrice5'],'double');
		$vSellingPrice5Base1	= GetSQLValueString($rows['Item_SellingPrice5Base1'],'double');
		$vSellingPrice5Base2	= GetSQLValueString($rows['Item_SellingPrice5Base2'],'double');
		$vSellingPrice6 		= GetSQLValueString($rows['Item_SellingPrice6'],'double');
		$vSellingPrice6Base1	= GetSQLValueString($rows['Item_SellingPrice6Base1'],'double');
		$vSellingPrice6Base2	= GetSQLValueString($rows['Item_SellingPrice6Base2'],'double');
		$vItemSelling1TTCBase1	= GetSQLValueString($rows['ItemSelling1TTCBase1'],'double');
		$vItemSelling2TTCBase2	= GetSQLValueString($rows['ItemSelling2TTCBase2'],'double');
		$vItemSelling3TTCBase2	= GetSQLValueString($rows['ItemSelling3TTCBase2'],'double');
		$vItemSelling4TTCBase1	= GetSQLValueString($rows['ItemSelling4TTCBase1'],'double');
		$vItemSelling2TTCBase1	= GetSQLValueString($rows['ItemSelling2TTCBase1'],'double');
		$vItemSelling3TTCBase1	= GetSQLValueString($rows['ItemSelling3TTCBase1'],'double');
		$vItemSelling1TTCBase2	= GetSQLValueString($rows['ItemSelling1TTCBase2'],'double');
		$vItemSelling4TTCBase2	= GetSQLValueString($rows['ItemSelling4TTCBase2'],'double');
		$vItemMaxQty			= GetSQLValueString($rows['Item_MaxQty'],'double');
		$vItemMinQty			= GetSQLValueString($rows['Item_MinQty'],'double');
		$vItemUnit				= GetSQLValueString($rows['Item_Unit'],'double');
		$vSynchronized			= GetSQLValueString($rows['Synchronized'],'int');
		$vItemLongDescription 	= GetSQLValueString($rows['Item_LongDescription'],'text');
		$vOwnerBranch 			= GetSQLValueString($rows['Owner_Branch'],'text');
		
		
		$vResult = '';
		
		if ($vResult != 'P') {
		
			//Check For Duplicate of Code InCase Insert
			$vDuplicateExists = 0;
			If ($PState == 'I') {	
				$sub_query  = " Select Count(*) From Items ".
							  " Where Upper(Item_Code) = Upper(".$vItemCode.") ";
							  
				//If ($PState == 'U')	$sub_query = $sub_query." And Item_ID != '".$PRecordID."'";			  
				$sub_result = selectData($PDestConn, $sub_query);
				$vDuplicateExists = $sub_result[0];
				
				if ($vDuplicateExists > 0) {
					$vResult  = 'P';
					$vMessage = 'Duplicate Code: '.$vItemCode;
					$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'Items',$vMessage);
				}
			}
			if ($vResult != 'P') {
				$sub_query  = " Update Items Set Synchronized = 0 ".
							  " Where Upper(Item_Code) = Upper('".$PRecordCode."')";
				$sub_result=mysql_query($sub_query,$PLocConn);
							  
				$sub_query  = " Select Count(*) From Items ".
							  " Where Upper(Item_Code) = Upper('".$PRecordCode."')";
				$sub_result = selectData($PDestConn, $sub_query);
				$vRecordExists = $sub_result[0];
				
				//Case Record Doesn't Exists - Insert
				If ($vRecordExists == 0) {
					$vItemId = GetNextSequence1($PDestConn,'Item_Increment','');
					
					$sub_query = " Insert Into Items (Item_Id, Item_Code, Item_Description, Item_Barcode, Currency_code, Project_Code, CostCent_Code, ".
								 " Group_code, SubGroup_Code, Ledger_Number, Item_Remark, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
								 " Category_code, Item_Picture, Expire_Date, Item_Posted, Item_Package, Item_Vat, Item_Barcode2, ".
								 " Item_Barcode3, Item_Active, Item_TTCInclude, Item_BelongsToGroup, Item_CostMethod, Item_QtyToBeProduced, ".
								 " Item_WithSerialno, Item_ZeroPrice, Item_Visible, Item_Production, Item_LastDatePurchase, ".
								 " Item_LastPricePurchase, Item_NonStock, Item_Transfer, Item_Pack, Item_Weight, Item_SemiFinished, Item_FixedAsset, ".
								 " Item_Tax, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Item_Grammage, Item_ReverseProduction,  ".
								 " Item_SysDateTime, Item_InactiveDate, Item_Promotion, Item_Height, Item_Length, Item_Width, Item_Policy, ".
								 " Item_Discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, Item_Expire, Item_MinimumPrice, ".
								 " Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, ".
								 " Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, ".
								 " Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, ".
								 " Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, ItemSelling1TTCBase1, ItemSelling2TTCBase2, ".
								 " ItemSelling3TTCBase2, ItemSelling4TTCBase1, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ".
								 " ItemSelling4TTCBase2, Synchronized, Item_LongDescription, Item_MaxQty, Item_MinQty, Item_Unit, Owner_Branch ) ".
								 " Values ( ".$vItemId.", ".$vItemCode.", ".$vItemDescription.", ".$vItemBarcode.", ".$vCurrencyCode.", ".$vProjectCode.
								 ", ".$vCostCentCode.", ".$vGroupCode.", ".$vSubGroupCode.", ".$vLedgerNumber.", ".$vItemRemark.", ".$vItemUnitPurchaseDesc.
								 ", ".$vItemUnitSalesDesc.", ".$vCategoryCode.", ".$vItemPicture.", ".$vExpireDate.", ".$vItemPosted.", ".$vItemPackage.
								 ", ".$vItemVat.", ".$vItemBarcode2.", ".$vItemBarcode3.", ".$vItemActive.", ".$vItemTTCInclude.", ".$vBelongsToGroup.
								 ", ".$vItemCostMethod.", ".$vItemQtyToBeProduced.", ".$vItemWithSerialno.", ".$vItemZeroPrice.", ".$vItemVisible.
								 ", ".$vItemProduction.", ".$vLastDatePurchase.", ".$vLastPricePurchase.", ".$vItemNonStock.", ".$vItemTransfer.", ".$vItemPack.
								 ", ".$vItemWeight.", ".$vItemSemiFinished.", ".$vItemFixedAsset.", ".$vItemTax.", ".$vItemTax1.", ".$vItemTax2.
								 ", ".$vItemTax3.", ".$vItemTax4.", ".$vItemTax5.", ".$vItemGrammage.", ".$vReverseProduction.", ".$vItemSysDateTime.
								 ", ".$vItemInactiveDate.", ".$vItemPromotion.", ".$vItemHeight.", ".$vItemLength.", ".$vItemWidth.", ".$vItemPolicy.
								 ", ".$vItemDiscount.", ".$vModifySellingPrice.", ".$vItemVolume.", ".$vItemColor.", ".$vItemSize.", ".$vItemExpire.
								 ", ".$vItemMinimumPrice.", ".$vSellingPrice1.", ".$vSellingPrice1Base1.", ".$vSellingPrice1Base2.", ".$vSellingPrice2.
								 ", ".$vSellingPrice2Base1.", ".$vSellingPrice2Base2.", ".$vSellingPrice3.", ".$vSellingPrice3Base1.", ".$vSellingPrice3Base2.
								 ", ".$vSellingPrice4.", ".$vSellingPrice4Base1.", ".$vSellingPrice4Base2.", ".$vSellingPrice5.", ".$vSellingPrice5Base1.
								 ", ".$vSellingPrice5Base2.", ".$vSellingPrice6.", ".$vSellingPrice6Base1.", ".$vSellingPrice6Base2.", ".$vItemSelling1TTCBase1.
								 ", ".$vItemSelling2TTCBase2.", ".$vItemSelling3TTCBase2.", ".$vItemSelling4TTCBase1.", ".$vItemSelling2TTCBase1.", ".$vItemSelling3TTCBase1.
								 ", ".$vItemSelling1TTCBase2.", ".$vItemSelling4TTCBase2.", ".$vSynchronized.", ".$vItemLongDescription.", ".$vItemMaxQty.
								 ", ".$vItemMinQty.", ".$vItemUnit.", ".$vOwnerBranch." ) ";

				}	
				else {
					$sub_query = "  Update Items Set Item_Code = ".$vItemCode.", Item_Description = ".$vItemDescription.
								 ", Item_Barcode = ".$vItemBarcode.", Currency_code = ".$vCurrencyCode.
								 ", Project_Code = ".$vProjectCode.", CostCent_Code = ".$vCostCentCode.
								 ", Group_code = ".$vGroupCode.", SubGroup_Code = ".$vSubGroupCode.
								 ", Ledger_Number = ".$vLedgerNumber.", Item_Remark = ".$vItemRemark.
								 ", Item_UnitPurchaseDesc = ".$vItemUnitPurchaseDesc.", Item_UnitSalesDesc = ".$vItemUnitSalesDesc.
								 ", Category_code = ".$vCategoryCode.", Item_Picture = ".$vItemPicture.
								 ", Expire_Date = ".$vExpireDate.", Item_Posted = ".$vItemPosted.
								 ", Item_Package = ".$vItemPackage.", Item_Vat = ".$vItemVat.
								 ", Item_Barcode2 = ".$vItemBarcode2.", Item_Barcode3 = ".$vItemBarcode3.
								 ", Item_Active = ".$vItemActive.", Item_TTCInclude = ".$vItemTTCInclude.
								 ", Item_BelongsToGroup = ".$vBelongsToGroup.", Item_CostMethod = ".$vItemCostMethod.
								 ", Item_QtyToBeProduced = ".$vItemQtyToBeProduced.", Item_WithSerialno = ".$vItemWithSerialno.
								 ", Item_ZeroPrice = ".$vItemZeroPrice.", Item_Visible = ".$vItemVisible.
								 ", Item_Production = ".$vItemProduction.", Item_LastDatePurchase = ".$vLastDatePurchase.
								 ", Item_LastPricePurchase = ".$vLastPricePurchase.", Item_NonStock = ".$vItemNonStock.
								 ", Item_Transfer = ".$vItemTransfer.", Item_Pack = ".$vItemPack.", Item_Weight = ".$vItemWeight.
								 ", Item_SemiFinished = ".$vItemSemiFinished.", Item_FixedAsset = ".$vItemFixedAsset.", Item_Tax = ".$vItemTax.
								 ", Item_Tax1 = ".$vItemTax1.", Item_Tax2 = ".$vItemTax2.", Item_Tax3 = ".$vItemTax3.", Item_Tax4 = ".$vItemTax4.
								 ", Item_Tax5 = ".$vItemTax5.", Item_Grammage = ".$vItemGrammage.", Item_ReverseProduction = ".$vReverseProduction.
								 ", Item_SysDateTime = ".$vItemSysDateTime.", Item_InactiveDate = ".$vItemInactiveDate.", Item_Promotion = ".$vItemPromotion.
								 ", Item_Height = ".$vItemHeight.", Item_Length = ".$vItemLength.", Item_Width = ".$vItemWidth.", Item_Policy = ".$vItemPolicy.
								 ", Item_Discount = ".$vItemDiscount.", Item_ModifySellingPrice = ".$vModifySellingPrice.", Item_Volume = ".$vItemVolume.
								 ", Item_Color = ".$vItemColor.", Item_Size = ".$vItemSize.", Item_Expire = ".$vItemExpire.", Item_MinimumPrice = ".$vItemMinimumPrice.
								 ", Item_SellingPrice1 = ".$vSellingPrice1.", Item_SellingPrice1Base1 = ".$vSellingPrice1Base1.", Item_SellingPrice1Base2 = ".$vSellingPrice1Base2.
								 ", Item_SellingPrice2 = ".$vSellingPrice2.", Item_SellingPrice2Base1 = ".$vSellingPrice2Base1.", Item_SellingPrice2Base2 = ".$vSellingPrice2Base2.
								 ", Item_SellingPrice3 = ".$vSellingPrice3.", Item_SellingPrice3Base1 = ".$vSellingPrice3Base1.", Item_SellingPrice3Base2 = ".$vSellingPrice3Base2.
								 ", Item_SellingPrice4 = ".$vSellingPrice4.", Item_SellingPrice4Base1 = ".$vSellingPrice4Base1.", Item_SellingPrice4Base2 = ".$vSellingPrice4Base2.
								 ", Item_SellingPrice5 = ".$vSellingPrice5.", Item_SellingPrice5Base1 = ".$vSellingPrice5Base1.", Item_SellingPrice5Base2 = ".$vSellingPrice5Base2.
								 ", Item_SellingPrice6 = ".$vSellingPrice6.", Item_SellingPrice6Base1 = ".$vSellingPrice6Base1.", Item_SellingPrice6Base2 = ".$vSellingPrice6Base2.
								 ", ItemSelling1TTCBase1 = ".$vItemSelling1TTCBase1.", ItemSelling2TTCBase2 = ".$vItemSelling2TTCBase2.", ItemSelling3TTCBase2 = ".$vItemSelling3TTCBase2.
								 ", ItemSelling4TTCBase1 = ".$vItemSelling4TTCBase1.", ItemSelling2TTCBase1 = ".$vItemSelling2TTCBase1.", ItemSelling3TTCBase1 = ".$vItemSelling3TTCBase1.
								 ", ItemSelling1TTCBase2 = ".$vItemSelling1TTCBase2.", ItemSelling4TTCBase2 = ".$vItemSelling4TTCBase2.", Item_MaxQty = ".$vItemMaxQty.
								 ", Item_MinQty = ".$vItemMinQty.", Item_Unit = ".$vItemUnit.", Item_LongDescription = ".$vItemLongDescription.
								 "  Where Upper(Item_Code) = Upper('".$PRecordCode."')";
				
				}

				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$PDestConn);

				if ($sub_result) {
					$vResult = 'T';	
					
					//InCase Update, Delete All Related Details In ItemsDt, PackDt
					If ($vRecordExists > 0) {
						$query = "Delete From ItemsDt Where Upper(Item_Code) = Upper('".$PRecordCode."')";
						$result = mysql_query($query, $PDestConn);
						
						$query = "Delete From PackDt Where Upper(Item_Code) = Upper('".$PRecordCode."')";
						$result = mysql_query($query, $PDestConn);
					}
					
					
					//Insert Related Details From ItemsDt
					$query = " Select ItemDt_ID, Item_Code, ItemParam_Code, ItemDt_Value, ItemDt_Sign, ItemDt_Value2 ".
							 " From ItemsDt ".
							 " Where Upper(Item_Code) = Upper('".$PRecordCode."')";
					//echo $query; exit;		 
					$result=mysql_query($query,$PLocConn) or die(mysql_error());
					while($rows=mysql_fetch_assoc($result)){
						$sub_query = " Insert Into ItemsDt (Item_Code, ItemParam_Code, ItemDt_Value, ItemDt_Sign, ItemDt_Value2 ) ".
									 " Values ( ".GetSQLValueString($rows['Item_Code'],'text').", ".GetSQLValueString($rows['ItemParam_Code'],'text').
									 ", ".GetSQLValueString($rows['ItemDt_Value'],'text').", ".GetSQLValueString($rows['ItemDt_Sign'],'text').
									 ", ".GetSQLValueString($rows['ItemDt_Value2'],'text')." )";
									 
						//echo $sub_query; exit;	 
						$sub_result=mysql_query($sub_query,$PDestConn);	
						if ($sub_result) {
							$vResult = 'T';		

						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert Code= ".$rows['Item_Code']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'ItemsDt',$vMessage);
							
							break;
						}	
					}
					
					//Insert Related Details From PackDt
					$query = " Select Item_Code, Item_CodePackDt, Warehouse_Code, PackDt_Quantity, Packdt_Cost, ".
							 " Currency_Code, PackDt_CostPercentage, PackDt_PreCosting, PackDt_FromDate, PackDt_ToDate, ".
							 " PackDt_IdealQty, PackDt_PromoQty, PackDt_Promotion, PackDt_TotalPromotion ".
							 " From PackDt ".
							 " Where Upper(Item_Code) = Upper('".$PRecordCode."')";
					//echo $query; exit;		 
					$result=mysql_query($query,$PLocConn) or die(mysql_error());
					while($rows=mysql_fetch_assoc($result)){
										
						$sub_query = " Insert Into PackDt (Item_Code, Item_CodePackDt, Warehouse_Code, PackDt_Quantity, Packdt_Cost, ".
									 " Currency_Code, PackDt_CostPercentage, PackDt_PreCosting, PackDt_FromDate, PackDt_ToDate, ".
									 " PackDt_IdealQty, PackDt_PromoQty, PackDt_Promotion, PackDt_TotalPromotion ) ".
									 " Values ( ".GetSQLValueString($rows['Item_Code'],'text').", ".GetSQLValueString($rows['Item_CodePackDt'],'text').
									 ", ".GetSQLValueString($rows['Warehouse_Code'],'text').", ".GetSQLValueString($rows['PackDt_Quantity'],'double').
									 ", ".GetSQLValueString($rows['Packdt_Cost'],'double').", ".GetSQLValueString($rows['Currency_Code'],'text').
									 ", ".GetSQLValueString($rows['PackDt_CostPercentage'],'double').", ".GetSQLValueString($rows['PackDt_PreCosting'],'int').
									 ", ".GetSQLValueString($rows['PackDt_FromDate'],'date').", ".GetSQLValueString($rows['PackDt_ToDate'],'date').
									 ", ".GetSQLValueString($rows['PackDt_IdealQty'],'double').", ".GetSQLValueString($rows['PackDt_PromoQty'],'double').
									 ", ".GetSQLValueString($rows['PackDt_Promotion'],'int').", ".GetSQLValueString($rows['PackDt_TotalPromotion'],'double')." )";
									 
						//echo $sub_query; exit;	 
						$sub_result=mysql_query($sub_query,$PDestConn);	
						if ($sub_result) {
							$vResult = 'T';		

						} else {
							$vResult  = 'P';
							$vMessage = mysql_error();
							$vMessage = GetSQLValueString("Insert Code= ".$rows['Item_Code']." : ".$vMessage,'text');
							$vError   = InsertLog($PLocConn,'PackDt',$vMessage);
							
							break;
						}	
					}
					
					
				} else {
					$vResult  = 'P';
					$vMessage = mysql_error();
					$vMessage = GetSQLValueString("Insert Code= ".$PRecordCode." : ".$vMessage,'text');
					$vError   = InsertLog($PLocConn,'Items',$vMessage);
				}
			}	
		}
	}
	else if ($PState == 'D') {
		$sub_query = " Select Item_Code, Owner_Branch ".
					 " From Items Where Upper(Item_Code) = Upper('".$PRecordCode."')";
		$sub_result = selectData($PDestConn, $sub_query);
		$vItemCode 	  = $sub_result[0];
		$vOwnerBranch = $sub_result[1];
		
		$query = "Delete From ItemsDt Where Upper(Item_Code) = Upper('".$vItemCode."')";
		$result = mysql_query($query, $PDestConn);
						
		$query = "Delete From PackDt Where Upper(Item_Code) = Upper('".$vItemCode."')";
		$result = mysql_query($query, $PDestConn);
					
		$query = "Delete From Items Where Upper(Item_Code) = Upper('".$vItemCode."')";
		$result = mysql_query($query, $PDestConn);
				
		if ($result) {
			$vResult  = 'T';
		} else {
			$vResult  = 'P';
			$vMessage = mysql_error();
			$vMessage = GetSQLValueString("Delete Code= ".$PRecordCode." : ".$vMessage,'text');
			$vError   = InsertLog($PLocConn,'Items',$vMessage);
		}	
	
	}
	
	//InCase Table SynchroAll (To All Branches) Is True, Or Destination Branch = 'ALL'
	//Inserts The Synchronized Record In Table Synchro In Main DB For Other Branches To Get It
	if (($PSynchroAll == 1 || strtoupper($PBranchCode) == 'ALL') && $vResult != 'P') {
		$vOwnerBranch = trim($vOwnerBranch,"'");
		$vItemCode 	  = trim($vItemCode,"'");
		InsertSynchroDest($PDestConn,$PState,$PTableName,'',$vItemCode,$vOwnerBranch);
	}

	Return $vResult;

}

function F_Get_DeliveryDtRelatedID($PDestConn, $PDelRelatedID) {
	$query = " Select SorderDt_ID ".
	         " From SorderDt ".
			 " Where SorderDt_Syn_ID = '".$PDelRelatedID."' ".
			 " And SorderDt_Syn_ID Is Not Null And SorderDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_SalesDtRelatedID($PDestConn, $PSaRelatedID) {
	$query = " Select DeliveryDt_ID ".
	         " From DeliveryDt ".
			 " Where DeliveryDt_Syn_ID = '".$PSaRelatedID."' ".
			 " And DeliveryDt_Syn_ID Is Not Null And DeliveryDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PorderDtRelatedID($PDestConn, $PPorRelatedID) {
	$query = " Select PRqstDt_ID ".
	         " From PRequestDt ".
			 " Where PRqstDt_Syn_ID = '".$PPorRelatedID."' ".
			 " And PRqstDt_Syn_ID Is Not Null And PRqstDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PurchasesDtRelatedID($PDestConn, $PPurRelatedID) {
	$query = " Select PorderDt_ID ".
	         " From PorderDt ".
			 " Where PorderDt_Syn_ID = '".$PPurRelatedID."' ".
			 " And PorderDt_Syn_ID Is Not Null And PorderDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_GrnDtRelatedID($PDestConn, $PPurRelatedID) {
	$query = " Select PorderDt_ID ".
	         " From PorderDt ".
			 " Where PorderDt_Syn_ID = '".$PPurRelatedID."' ".
			 " And PorderDt_Syn_ID Is Not Null And PorderDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_SerialRelatedID($PDestConn, $PSerRelatedID) {
	$query = " Select Serial_ID ".
	         " From PurchasesSerialNo ".
			 " Where Serial_Syn_ID = '".$PSerRelatedID."' ".
			 " And Serial_Syn_ID Is Not Null And Serial_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_SorderTransferID($PDestConn, $PTransferID) {
	$query = " Select Transfer_ID ".
	         " From Transfer ".
			 " Where Transfer_Syn_ID = '".$PTransferID."' ".
			 " And Transfer_Syn_ID Is Not Null And Transfer_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PreProductionID($PDestConn, $PPreProductionID) {
	$query = " Select Production_ID ".
	         " From PreProduction ".
			 " Where Production_Syn_ID = '".$PPreProductionID."' ".
			 " And Production_Syn_ID Is Not Null And Production_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_AdjustRequestID($PDestConn, $PAdjustRequestID) {
	$query = " Select AdjustmentRequest_ID ".
	         " From AdjustmentRequest ".
			 " Where AdjustmentRequest_Syn_ID = '".$PAdjustRequestID."' ".
			 " And AdjustmentRequest_Syn_ID Is Not Null And AdjustmentRequest_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_AdjustRequestDtID($PDestConn, $PAdjustRequestDtID) {
	$query = " Select AdjustmentRequestDt_ID ".
	         " From AdjustmentRequestDt ".
			 " Where AdjustmentRequestDt_Syn_ID = '".$PAdjustRequestDtID."' ".
			 " And AdjustmentRequestDt_Syn_ID Is Not Null And AdjustmentRequestDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}


function F_Get_TransferReqID($PDestConn, $PTransferRequestID) {
	$query = " Select TransferRequest_ID ".
	         " From TransferRequest ".
			 " Where TransferRequest_Syn_ID = '".$PTransferRequestID."' ".
			 " And TransferRequest_Syn_ID Is Not Null And TransferRequest_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_TransferReqDtID($PDestConn, $PTransferRequestDtID) {
	$query = " Select TransferRequestDt_ID ".
	         " From TransferRequestDt ".
			 " Where TransferRequestDt_Syn_ID = '".$PTransferRequestDtID."' ".
			 " And TransferRequestDt_Syn_ID Is Not Null And TransferRequestDt_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PorderID($PDestConn, $PPorderID) {
	$query = " Select Porder_ID ".
	         " From Porder ".
			 " Where Porder_Syn_ID = '".$PPorderID."' ".
			 " And Porder_Syn_ID Is Not Null And Porder_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PurchaseReqID($PDestConn, $PPurchaseRequestID) {
	$query = " Select PRqst_ID ".
	         " From PRequest ".
			 " Where PRqst_Syn_ID = '".$PPurchaseRequestID."' ".
			 " And PRqst_Syn_ID Is Not Null And PRqst_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Get_PaymentReqID($PDestConn, $PPaymentRequestID) {
	$query = " Select PaymentRqst_ID ".
	         " From PaymentRqst ".
			 " Where PaymentRqst_Syn_ID = '".$PPaymentRequestID."' ".
			 " And PaymentRqst_Syn_ID Is Not Null And PaymentRqst_Syn_ID != '' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 'Null';
	
	Return $vResult;
}

function F_Check_ItemID($PDestConn, $PItemID) {
	$query = " Select Count(*) ".
	         " From Items ".
			 " Where Item_ID = '".$PItemID."' ";
	$result = selectData($PDestConn, $query);		 
	$vResult = $result[0];
	
	if(empty($vResult)) $vResult = 0;
	
	Return $vResult;
}

function F_Check_ClientID($PDestConn, $PClientID) {
	if ($PClientID != '' && $PClientID != 'Null') {
		$query = " Select Count(*) ".
				 " From Clients ".
				 " Where Client_ID = '".$PClientID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
	
	Return $vResult;
}

function F_Check_SupplierID($PDestConn, $PSupplierID) {
	if ($PSupplierID != '' && $PSupplierID != 'Null') {
		$query = " Select Count(*) ".
				 " From Suppliers ".
				 " Where Supplier_ID = '".$PSupplierID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;	
	
	Return $vResult;
}

function F_Check_SalesmanID($PDestConn, $PSalesmanID) {
	if ($PSalesmanID != '' && $PSalesmanID != 'Null') {
		$query = " Select Count(*) ".
				 " From Salesmen ".
				 " Where Salesman_ID = '".$PSalesmanID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
	
	Return $vResult;
}

function F_Check_CustomerID($PDestConn, $PCustomerID) {
	if ($PCustomerID != '' && $PCustomerID != 'Null') {
		$query = " Select Count(*) ".
				 " From Customer ".
				 " Where Customer_ID = '".$PCustomerID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;	
	
	Return $vResult;
}

function F_Check_ProjectID($PDestConn, $PProjectID) {
	if ($PProjectID != '' && $PProjectID != 'Null') {
		$query = " Select Count(*) ".
				 " From Project ".
				 " Where Project_ID = '".$PProjectID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
	
	Return $vResult;
}

function F_Check_CostCentID($PDestConn, $PCostCentID) {
	if ($PCostCentID != '' && $PCostCentID != 'Null') {
		$query = " Select Count(*) ".
				 " From CostCent ".
				 " Where CostCent_ID = '".$PCostCentID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_WarehouseID($PDestConn, $PWarehouseID) {
	if ($PWarehouseID != '' && $PWarehouseID != 'Null') {
		$query = " Select Count(*) ".
				 " From Warehouse ".
				 " Where Warehouse_ID = '".$PWarehouseID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_CurrencyID($PDestConn, $PCurrencyID) {
	if ($PCurrencyID != '' && $PCurrencyID != 'Null') {
		$query = " Select Count(*) ".
				 " From Currency ".
				 " Where Currency_ID = '".$PCurrencyID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_CouponID($PDestConn, $PCouponID) {
	if ($PCouponID != '' && $PCouponID != 'Null') {
		$query = " Select Count(*) ".
				 " From Coupon ".
				 " Where Coupon_ID = '".$PCouponID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_VendorID($PDestConn, $PVendorID) {
	if ($PVendorID != '' && $PVendorID != 'Null') {
		$query = " Select Count(*) ".
				 " From Vendor ".
				 " Where Vendor_ID = '".$PVendorID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_GroupID($PDestConn, $PGroupID) {
	if ($PGroupID != '' && $PGroupID != 'Null') {
		$query = " Select Count(*) ".
				 " From Grouping ".
				 " Where Group_ID = '".$PGroupID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}
function F_Check_GroupCode($PDestConn, $PGroupCode) {
	if ($PGroupCode != '' && $PGroupCode != 'Null') {
		$query = " Select Count(*) ".
				 " From Grouping ".
				 " Where Group_Code = '".$PGroupCode."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_SubGroupID($PDestConn, $PSubGroupID) {
	if ($PSubGroupID != '' && $PSubGroupID != 'Null') {
		$query = " Select Count(*) ".
				 " From SubGroup ".
				 " Where SubGroup_ID = '".$PSubGroupID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_CategoryID($PDestConn, $PCategoryID) {
	if ($PCategoryID != '' && $PCategoryID != 'Null') {
		$query = " Select Count(*) ".
				 " From Category ".
				 " Where Category_ID = '".$PCategoryID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_UnitID($PDestConn, $PUnitID) {
	if ($PUnitID != '' && $PUnitID != 'Null') {
		$query = " Select Count(*) ".
				 " From ItemUnits ".
				 " Where ItemUnit_ID = '".$PUnitID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_ItemTypeID($PDestConn, $PItemTypeID) {
	if ($PItemTypeID != '' && $PItemTypeID != 'Null') {
		$query = " Select Count(*) ".
				 " From ItemTypes ".
				 " Where ItemType_ID = '".$PItemTypeID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_ItemClassID($PDestConn, $PItemClassID) {
	if ($PItemClassID != '' && $PItemClassID != 'Null') {
		$query = " Select Count(*) ".
				 " From ItemClasses ".
				 " Where ItemClass_ID = '".$PItemClassID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_AreaID($PDestConn, $PAreaID) {
	if ($PAreaID != '' && $PAreaID != 'Null') {
		$query = " Select Count(*) ".
				 " From Area ".
				 " Where Area_ID = '".$PAreaID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_LedgerID($PDestConn, $PLedgerID) {
	if ($PLedgerID != '' && $PLedgerID != 'Null') {
		$query = " Select Count(*) ".
				 " From Ledger ".
				 " Where Ledger_ID = '".$PLedgerID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}
function F_Check_LedgerCode($PDestConn, $PLedgerCode) {
	if ($PLedgerCode != '' && $PLedgerCode != 'Null') {
		$query = " Select Count(*) ".
				 " From Ledger ".
				 " Where Ledger_Number = '".$PLedgerCode."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function F_Check_LedgerGroupID($PDestConn, $PLedgerGroupID) {
	if ($PLedgerGroupID != '' && $PLedgerGroupID != 'Null') {
		$query = " Select Count(*) ".
				 " From LedgerGrp ".
				 " Where LedgerGrp_ID = '".$PLedgerGroupID."' ";
		$result = selectData($PDestConn, $query);		 
		$vResult = $result[0];
		if(empty($vResult)) $vResult = 0;
	} else	
		$vResult = 1;
		
	Return $vResult;
}

function InsertSynchroDest($PDestConn,$PState,$PTableName,$PRecordID,$PRecordCode,$POwnerBranch) {
	$query = " Select Upper(Branch_Code) As BranchCode From Branches ".
			 " Where ifNull(Branch_Main,0) = 0 ".
			 " And Upper(Branch_Code) != Upper('".$POwnerBranch."') ";
	//echo $query; exit;		 
	$result=mysql_query($query,$PDestConn);
	while($rows=mysql_fetch_assoc($result)){
		$vDestinationBranch = $rows['BranchCode'];
		
		$sub_query = " call Syn_InsertSynchro(now(), ".GetSQLValueString($PState,'text').", ".GetSQLValueString($PTableName,'text').", ".GetSQLValueString($PRecordID,'int').", ".GetSQLValueString($PRecordCode,'text').", ".GetSQLValueString($vDestinationBranch,'text').", 'F') ";
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$PDestConn);
	}
					
}

function InsertSynchroLoc($PLocConn,$PState,$PTableName,$PRecordID,$PRecordCode,$POwnerBranch) {
	$query = " Select ifNull(Branch_Main,0) From Branches Where Upper(Branch_Code) = Upper('".$POwnerBranch."') ";
	$result = selectData($PLocConn, $query);
	$MainBranch = $result[0];
	
	if ($MainBranch == 1) {
		//If Record Is Added From Main Branch, Then Insert Same Record In Synchro For All Branches
		InsertSynchroDest($PLocConn,$PState,$PTableName,$PRecordID,$PRecordCode,$POwnerBranch);
	} else {
		$sub_query = " call Syn_InsertSynchro(now(), ".GetSQLValueString($PState,'text').", ".GetSQLValueString($PTableName,'text').", ".GetSQLValueString($PRecordID,'int').", ".GetSQLValueString($PRecordCode,'text').", Null, 'F') ";
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$PLocConn);
	}
}

function InsertLog($PLocConn,$PTableName,$PMessage) {

	$query = " call Syn_InsertLog(now(), '".$PTableName."', $PMessage, 0) ";
	//echo $query; exit;
	$result = mysql_query($query,$PLocConn);
	
	Return 1;
}

function GetNextSequence($PDestConn,$PCompany,$PProjCostCent,$PType,$PTableName,$PJourType,$PBranch,$PDate) {

	$SequenceVal = 0;
	
	mysql_query("START TRANSACTION");
	mysql_query("set @SequenceVal :=0 ", $PDestConn);
	
	$query = " call NextSequence2('".$PCompany."', '".$PProjCostCent."', '".$PType."', '".$PTableName."', '".$PJourType."', '".$PBranch."', '".$PDate."', 0, 0, @SequenceVal) ";
	//echo $query; exit;
	$result = mysql_query($query,$PDestConn);
	
	$query  = " select @SequenceVal from dual ";
	$result = selectData($PDestConn, $query);
	$SequenceVal = $result[0];
	
	mysql_query("COMMIT");
	
	Return $SequenceVal;	
}

function GetNextSequence1($PDestConn,$PFieldName,$PProjCostCent) {

	$SequenceVal = 0;
	
	//mysql_query("START TRANSACTION");
	mysql_query("set @SequenceVal :=0 ", $PDestConn);
	
	$query = " call NextSequence1(".GetSQLValueString($PFieldName,'text').", ".GetSQLValueString($PProjCostCent,'text').", @SequenceVal) ";
	//echo $query; exit;
	$result = mysql_query($query,$PDestConn);
	
	$query  = " select @SequenceVal from dual ";
	$result = selectData($PDestConn, $query);
	$SequenceVal = $result[0];
	
	//mysql_query("COMMIT");
	
	Return $SequenceVal;	
}

function GetRemoteConnection($PLocConn) {
	//Destination/Remote Connection
	$query = " Select Branch_DbServer As DbServer, Branch_DbName As DbName, Branch_DbUser As DbUser, Branch_DbPass As DbPass ".
	         " From Branches ".
			 " Where ifNull(Branch_Main,0) = 1 ".
			 " Limit 1 ";
	//echo $query; exit;		 
	$result=mysql_query($query, $PLocConn) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){
		extract($rows);
	}
		 
	$conn = mysql_connect($DbServer,$DbUser,$DbPass,true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName,$conn) or die("Could not find remote DB");
	
	Return $conn;
}

//Method to query database and get the first row
if (!function_exists('selectData')) {
	function selectData($conn, $query){
		$result = mysql_query($query, $conn);
		$cur = mysql_fetch_row($result);		
		return $cur;
	}
}

if (!function_exists('GetSQLValueString')) {
	function GetSQLValueString($theValue, $theType) 
	{
	  $theValue = trim($theValue);	
	  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

	  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

	  switch ($theType) {
		case "text":
		  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
		  break;    
		case "long":
		case "int":
		  $theValue = ($theValue != "") ? $theValue : "Null";
		  break;
		case "double":
		  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
		  break;
		case "date":
		  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
		  break;
	  }
	  return $theValue;
	}
}
?>