<?php
/*
24/01/2011 - Made the strlength check from 5 to 8 for clearPage and clearGarbage
*/
	session_start();
	
	$al =  $_SESSION['dbLabel'];
	$ac = $_SESSION['dbName'];

	include("config.inc.php");
	$db_user = $config['dbUser'];
	$db_pass = $config['dbPass'];
	$db_server = $config['dbServer'];

	//06/08/2010 - Anuj
	function openALConnection(){
		global $al;
		global $db_user;
		global $db_pass;
		global $db_server;

		$conn = mysql_connect($db_server, $db_user, $db_pass);
		mysql_select_db($al, $conn);
		return $conn;
	}

	function openConnection(){
		global $ac;
		global $db_user;
		global $db_pass;
		global $db_server;

		$conn = mysql_connect($db_server, $db_user, $db_pass);
		mysql_select_db($ac, $conn);
		return $conn;
	}

	function openPConnection(){
		global $ac;
		global $db_user;
		global $db_pass;
		global $db_server;

		$conn = mysql_pconnect($db_server, $db_user, $db_pass);
		mysql_select_db($ac, $conn);
		return $conn;
	}
		
	function openIConnection(){
		global $ac;
		global $db_user;
		global $db_pass;
		global $db_server;

		$iconn = mysqli_connect($db_server, $db_user, $db_pass, $ac);
		mysqli_autocommit($iconn, false);
		return $iconn;
	}	

	function updateIData($iconn, $query, $commit){
		mysqli_autocommit($iconn, false);
		if (mysqli_query($iconn, $query)){
			if ($commit){
				mysqli_commit($iconn);
			}
			return true;
		}else{
			return false;
		}		
	}
	
	


	function mround($number, $precision=0) { 
    
		$precision = ($precision == 0 ? 1 : $precision);    
		$pow = pow(10, $precision); 
		
		$ceil = ceil($number * $pow)/$pow; 
		$floor = floor($number * $pow)/$pow; 
		
		$pow = pow(10, $precision+1); 
		
		$diffCeil     = $pow*($ceil-$number); 
		$diffFloor     = $pow*($number-$floor)+($number < 0 ? -1 : 1); 
		
		if($diffCeil >= $diffFloor) return $floor; 
		else return $ceil; 
	} 

function mabsolute($number) {
   include('config.inc.php');
   
	   
	$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
	mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");
		
	//Read From Setup Table							
	$querysetup= " select DecimalBase from setup ";
	$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
	while($rowsetup=mysql_fetch_array($resultsetup)){
		extract($rowsetup);
	}

   // jp removed Exponencial
   return  str_replace(',','',number_format(abs($number),$DecimalBase)) ;
}

	/*
	function getWarehouseQuery($aconn, $username, $column){
		$q = "";
		$query = "SELECT warehouse_code FROM loginstk WHERE user_account = '".$username."' AND warehouse_code IS NOT NULL ";
		$result = mysql_query($query, $aconn);
		while ($cur = mysql_fetch_row($result)){
			$q = $q . " AND ".$column." = '".$cur[0]."' ";
		}
		return $q;		
	}

	function getProjectQuery($aconn, $username, $column){
		$q = "";		
		$this_query = "SELECT project_code FROM loginstk WHERE user_account = '".$username."' AND project_code IS NOT NULL ";
		$result = selectData($aconn, $this_query);
		if ($result[0] != ""){
			$q = " AND ".$column." IN (".$this_query.")";
		}
		echo "<br><br>".$q;
		return $q;		
	}
	*/

	function displayList($field, $name, $value, $prints, $conn, $query, $onChange, $w1, $w2){
		if ($w1 == ""){
			$w1 = "50%";
		}
		if ($w2 == ""){
			$w2 = "50%";
		}
		
		print "<td align='right' width='".$w1."'><font size='2' face='Verdana' color='#A0A0A0'>".$name."</font></td><td width='".$w2."'>";
		if ($prints == 'yes'){
			print "<input type='hidden' name='".$field."' value='".$value."'>";
		}else{
			if ($onChange == ''){
				print "<select name='".$field."'>";
			}else{
				print "<select name='".$field."' ".$onChange.">";
			}
		}
		if ($prints != 'yes'){
			print "<option value=''>---</option>";
		}		 
		
		$result = mysql_query($query, $conn);
		while($cur = mysql_fetch_row($result)){
			if ($cur[0] == $value){
				if ($prints == 'yes'){
					print "<font size='2' face='Verdana'><b>&nbsp;&nbsp;".$cur[1]."</b></font>";
				}else{
					print "<option selected value='".$cur[0]."'>".$cur[1]."</option>";
				}
			}else{
				if ($prints != 'yes'){
					print "<option value='".$cur[0]."'>".$cur[1]."</option>";
				}
			}
		}		
		
		if ($prints == 'yes'){
			print "&nbsp;";
		}else{
			print "</select>";		
		}
		print "</td>";	
	}

	//displayArrayList
	function displayArrayList($field, $name, $value, $prints, $v1, $v2, $onChange, $w1, $w2){		
		if ($w1 == ""){
			$w1 = "50%";
		}
		if ($w2 == ""){
			$w2 = "50%";
		}
		
		print "<td align='right' width='".$w1."'><font size='2' face='Verdana'>".$name."</font></td><td width='".$w2."'>";
		if ($prints == 'yes'){
			print "<input type='hidden' name='".$field."' value='".$value."'>";
		}else{
			if ($onChange == ''){
				print "<select name='".$field."'>";
			}else{
				print "<select name='".$field."' ".$onChange.">";
			}
		}
		if ($prints != 'yes'){
			print "<option value=''>---</option>";
		}
		
		for ($i=0;$i<count($v1);$i++){
			if ($v1[$i] == $value){
				if ($prints == 'yes'){
					print "<font size='2' face='Verdana'><b>&nbsp;&nbsp;".$v2[$i]."</b></font>";
				}else{
					print "<option selected value='".$v1[$i]."'>".$v2[$i]."</option>";
				}
			}else{
				if ($prints != 'yes'){
					print "<option value='".$v1[$i]."'>".$v2[$i]."</option>";
				}
			}
		}
		
		if ($prints == 'yes'){
			print "&nbsp;";
		}else{
			print "</select>";		
		}		
		print "</td>";	
	}

	//Date Functions
	//Return Today's Date in YYYYMMDD format
	function insertToday(){
		return strftime("%Y") . strftime("%m") . strftime("%d");
	}

	//Return Date in DD/MM/YYYY format
	function displayToday(){
		return strftime("%d")."/".strftime("%m")."/".strftime("%Y");
	}

	//Return Today's Date in YYYYMMDD format. Supplied Format: DD/MM/YYYY
	function insertDate($data){
		return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
	}

	//Return Date in YYYYMMDD format. Supplied Format: YYYY-MM-DD
	function insertParadoxDate($data){
		return substr($data, 0, 4) . substr($data, 5, 2) . substr($data, 8, 2);
	}

	//Return Date in YYYY-MM-DD format. Supplied Format: YYYYMMDD
	function displayParadoxDate($data){
		return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2);
	}

	//Return Date in YYYY-MM-DD HH:MM:SS format. Supplied Format: DD/MM/YYYY
	function insertMySQLDate($data){
		if($data == "" || $data == null)
		{
			$data = date('d/m/Y');
		}
		$data = insertDate($data);
		return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");
	}
	
	//Return Date in YYYY-MM-DD format. Supplied Format: DD/MM/YYYY
	function MySQLDateNoTime($data){
		$data = insertDate($data);
		return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." 23:59:59";
	}

	//Return Date in DD/MM/YYYY format
	function displayDate($data){
		return substr($data, 6, 2)."/".substr($data, 4, 2)."/".substr($data, 0, 4);		
	}

	//Return Current Time in HH:MM:SS format
	function displayNow(){
		return strftime("%H").":".strftime("%M").":".strftime("%S");
	}

	// Return the number of days between the two dates format YYYY-MM-DD:
	function dateDiff ($d1, $d2) {
		return round(abs(strtotime($d1)-strtotime($d2))/86400);
	}  

	//Display Textbox
	function displayTextbox($field, $name, $value, $prints, $maxlength, $w1, $w2){
		/*
		$field = Textbox Name
		$name = Display Name
		$value = Textbox Value
		$prints = Form to be printed or not
		$maxlength = Maxlength of Textbox data value and physical size of textbox		
		$w1 = Width of the table cell <td> displaying the Textbox Name
		$w1 = Width of the table cell <td> displaying the Textbox
		*/
		if ($w1 == ""){
			$w1 = "50%";
		}
		if ($w2 == ""){
			$w2 = "50%";
		}
		
		$maxlen = "1024";

		if ($maxlength == ""){
			$maxlength = "30";
		}else{
			$maxlen = $maxlength;
		}
		if ($prints == 'yes'){
			print "<td align='right' width='".$w1."'><input type='hidden' name='".$field."' value='".$value."'><font face='Verdana' size='2' color='#A0A0A0'>".$name."</font></td><td width='".$w2."'><font face='Verdana' size='2'><b>&nbsp;&nbsp;".$value."</b></font></td>";
		}else{
			print "<td align='right' width='".$w1."'><font face='Verdana' size='2' color='#A0A0A0'>".$name."</font></td><td width='".$w2."'><input size='".$maxlength."' name='".$field."' maxlength='".$maxlen."' value='".$value."'></td>";
		}
	}

	//Display Text Area
	function displayTextarea($field, $name, $value, $prints, $rows, $cols, $w1, $w2){
		/*
		$field = Textarea Name
		$name = Display Name
		$value = Textarea Value
		$prints = Form to be printed or not
		$rows = Textarea rows
		$cols = Textarea columns
		$w1 = Width of the table cell <td> displaying the Textarea Name
		$w1 = Width of the table cell <td> displaying the Textarea
		*/
		if ($w1 == ""){
			$w1 = "50%";
		}
		if ($w2 == ""){
			$w2 = "50%";
		}
		if ($rows == ""){
			$rows = "5";
		}
		if ($cols == ""){
			$cols = "30";
		}
		if ($prints == 'yes'){
			print "<td align='right' width='".$w1."'><input type='hidden' name='".$field."' value='".$value."'><font face='Verdana' size='2' color='#A0A0A0'>".$name."</font></td><td width='".$w2."%'><font size='2' face='Verdana'><b>&nbsp;&nbsp;".$value."</b></font></td>";
		}else{
			print "<td align='right' width='".$w1."'><font size='2' face='Verdana' color='#A0A0A0'>".$name."</font></td><td width='".$w2."%'><textarea name='".$field."' rows='".$rows."' cols='".$cols."'>".$value."</textarea></td>";
		}
	}

	//Function to add Comma to a given Number
	function addComma($data){
		return number_format($data, 2, '.', ',');
	}

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

	//Method to Insert/ Update/ Delete Record in Database
	function updateData($conn, $query, $commit){
		if (mysql_query($query, $conn)){				
			return true;
		}else{
			return false;
		}
	}

	function getUserAccess($db, $user_account){		
		global $user;
		global $userpass;
		global $server;

		$this_conn = mysql_connect($server, $user, $userpass, $db);
		$query = "SELECT Fi_salesordermod, Fi_salesorderdel, Fi_sorderwithprice, FI_sorderconfirmed from login where user_account= '".$user_account."'";
		$result = mysql_query($query, $this_conn);
		$cur = mysql_fetch_row($result);
		return $cur;
	}

	function getSNoFlag($conn, $sno_flag, $id, $qty){
		if ($sno_flag){
			$query = "SELECT COUNT(Serial_ID) FROM purchasesserialno WHERE deliverydt_id = '".$id."' AND SerialNo_Used = 1";
			//echo $qty;
			$result = selectData($conn, $query);
			if (is_numeric($result[0]) == true && $result[0] == $qty){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	function getQtyFlag($conn, $sno_flag, $id){
		if ($sno_flag == false){
			$query = "SELECT deliverydt_quantity FROM deliverydt WHERE deliverydt_id = '".$id."'";
			$result = selectData($conn, $query);
			if (is_numeric($result[0]) == true && $result[0] > 0){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
	}

	function footer($module){
		print "<table width='100%' cellspacing='0' cellpadding='0'>";
		switch($module){
			case "SO":
				break;
			case "S":
				print "<tr><td width='45%' align='left'><img src='img/dot.gif' height='2' width='80%'><br><font face='3'>CUSTOMER'S SIGNATURE</font></td> <td>&nbsp;</td> <td width='45%' align='right'><img src='img/dot.gif' height='2' width='80%'><br><font face='3'>AUTHORIZED BY</font></td></tr>";
				break;
			case "W":
				print "<tr><td width='30%' align='left'><img src='img/dot.gif' height='2' width='80%'><br><font face='3'>RECEIVED BY</font></td> <td width='40%' align='center'><img src='img/dot.gif' height='2' width='80%'><br><font face='3'>DRIVER</font></td> <td width='30%' align='right'><img src='img/dot.gif' height='2' width='80%'><br><font face='3'>DELIVERED BY</font></td></tr>";
				break;				
		}
		print "<tr><td width='10%' align='left' vAlign='top'><br><img src='img/dot.gif' height='1' width='100%'><br><img src='img/dajcom/samsung.gif'></td> <td width='80%' align='center' vAlign='top'><br><img src='img/dot.gif' height='1' width='100%'><br><font face='Verdana' size='1'>41, Creek Rd, Apapa - Lagos <br>Sales: 01-7949988 01-4600600 08055007700, Fax: 01-4600601 <br><b>VAT Reg No: APV1600245536 <br>TIN No: 01590812.0001</b> <br>Email: sales@dajcom.com service@dajcom.com www.dajcom.com</font></td> <td width='50%' align='right' vAlign='top'><br><img src='img/dot.gif' height='1' width='100%'><br><img src='img/dajcom/chigo.gif'></td></tr>";
		print "</table>";

	}

	function selectDataCol($conn, $query){
		$array = "";
		$i = 0;
		$result = mysql_query($query, $conn);
		while($cur = mysql_fetch_row($result)){
			$array[$i] = $cur[0];
			$i++;
		}		
		return $array;
	}

	function clearGarbage($iconn){
		$query = "DELETE FROM chkjourdt WHERE LENGTH(User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' ";
		if (updateIData($iconn, $query, false)){
			//echo "<br><br>".$query;
			$query = "DELETE FROM cstjourdt WHERE LENGTH(User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' ";
			if (updateIData($iconn, $query, false)){
				//echo "<br><br>".$query;
				$query = "DELETE FROM acclink WHERE LENGTH(User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' ";
				if (updateIData($iconn, $query, false)){
					//echo "<br><br>".$query;
					$query = "DELETE FROM TransDt WHERE LENGTH(User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' AND Trans_id IN (SELECT Trans_id from Trans WHERE LENGTH(User_Account) > 8 AND (Trans_Reference IS NULL OR Trans_Reference = '') ) ";
					if (updateIData($iconn, $query, false)){
						//echo "<br><br>".$query;
						$query = "DELETE FROM trans WHERE LENGTH(User_Account) > 8 AND (Trans_Reference IS NULL OR Trans_Reference = '') AND User_Account NOT LIKE '%".insertToday()."%' ";
						if (updateIData($iconn, $query, false)){
							//echo "<br><br>".$query;
							mysqli_commit($iconn);
						}
					}
				}
			}
		}
		
		//$query = "UPDATE purchasesserialno, deliverydt SET purchasesserialno.DeliveryDt_id = NULL, SerialNo_Used = 0 WHERE purchasesserialno.DeliveryDt_id = deliverydt.DeliveryDt_id AND LENGTH(deliverydt.User_Account) > 8 AND (purchasesserialno.Journal_Type = 'PI' OR purchasesserialno.Journal_Type = 'AI' OR purchasesserialno.Journal_Type = 'TR')  AND deliverydt.User_Account NOT LIKE '%".insertToday()."%' ";		
		//echo "<br><br>".$query;
		$query = "DELETE FROM purchasesserialno WHERE purchasesserialno.DeliveryDt_id IN (SELECT deliverydt.DeliveryDt_id FROM deliverydt WHERE LENGTH(deliverydt.User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' AND delivery_id IN (SELECT Delivery_Id from Deliveries WHERE LENGTH(User_Account) > 8 AND (delivery_reference IS NULL OR delivery_reference = '') AND User_Account NOT LIKE '%".insertToday()."%')) AND purchasesserialno.Journal_Type = 'DI' ";
		//echo "\n\r".$query;
		if (updateIData($iconn, $query, false)){			
			$query = "DELETE FROM deliverydt WHERE LENGTH(User_Account) > 8  AND User_Account NOT LIKE '%".insertToday()."%'  AND delivery_id IN (SELECT Delivery_Id from Deliveries WHERE LENGTH(User_Account) > 8 AND (delivery_reference IS NULL OR delivery_reference = '') AND User_Account NOT LIKE '%".insertToday()."%') ";
			//echo "\n\r".$query;
			if (updateIData($iconn, $query, false)){				
				$query = "DELETE FROM deliveries WHERE LENGTH(User_Account) > 8 AND (delivery_reference IS NULL OR delivery_reference = '') AND User_Account NOT LIKE '%".insertToday()."%' ";
				//echo "\n\r".$query;
				if (updateIData($iconn, $query, false)){					
					mysqli_commit($iconn);
				}
			}
		}

		$query = "DELETE FROM sorderdt WHERE LENGTH(User_Account) > 8 AND User_Account NOT LIKE '%".insertToday()."%' AND sorder_id IN (SELECT sorder_id from sorder WHERE LENGTH(User_Account) > 8 AND (sorder_reference IS NULL OR sorder_reference = '')) ";
		if (updateIData($iconn, $query, false)){
			//echo "<br><br>".$query;
			$query = "DELETE FROM sorder WHERE LENGTH(User_Account) > 8 AND (sorder_reference IS NULL OR sorder_reference = '') AND User_Account NOT LIKE '%".insertToday()."%' ";
			if (updateIData($iconn, $query, false)){
				//echo "<br><br>".$query;
				mysqli_commit($iconn);
			}
		}		
	}
	
	function clearPage($iconn, $username, $module){
		if (($module == "" || $module == "Receipt") && strlen($username) > 8){			
			$query = "DELETE FROM chkjourdt WHERE User_Account = '".$username."'";
			if (updateIData($iconn, $query, false)){
				//echo "<br><br>".$query;
				$query = "DELETE FROM cstjourdt WHERE User_Account = '".$username."'";
				if (updateIData($iconn, $query, false)){
					//echo "<br><br>".$query;
					$query = "DELETE FROM acclink WHERE User_Account = '".$username."'";
					if (updateIData($iconn, $query, false)){
						//echo "<br><br>".$query;
						$query = "DELETE FROM TransDt WHERE User_Account = '".$username."' AND Trans_id IN (SELECT Trans_id from Trans WHERE LENGTH(User_Account) > 8 AND (Trans_Reference IS NULL OR Trans_Reference = '') ) ";
						//echo "<br><br>".$query;
						if (updateIData($iconn, $query, false)){							
							$query = "DELETE FROM trans WHERE User_Account = '".$username."' AND (Trans_Reference IS NULL OR Trans_Reference = '')";
							if (updateIData($iconn, $query, false)){
								//echo "<br><br>".$query;
								mysqli_commit($iconn);
							}
						}
					}
				}
			}
		}

		if (($module == "" || $module == "Sales") && strlen($username) > 8){
			$query = "DELETE FROM purchasesserialno WHERE purchasesserialno.DeliveryDt_id IN ( SELECT deliverydt.DeliveryDt_id FROM Deliverydt WHERE deliverydt.User_Account = '".$username."' AND delivery_id IN (SELECT Delivery_Id from Deliveries WHERE LENGTH(User_Account) > 8 AND (delivery_reference IS NULL OR delivery_reference = ''))) AND purchasesserialno.Journal_Type = 'DI' ";			
			if (updateIData($iconn, $query, false)){
				//echo "<br><br>".$query;
				$query = "DELETE FROM deliverydt WHERE User_Account = '".$username."' AND delivery_id IN (SELECT Delivery_Id from Deliveries WHERE LENGTH(User_Account) > 8 AND (delivery_reference IS NULL OR delivery_reference = '') )";
				if (updateIData($iconn, $query, false)){
					//echo "<br><br>".$query;
					$query = "DELETE FROM deliveries WHERE User_Account = '".$username."' AND (delivery_reference IS NULL OR delivery_reference = '')";
					if (updateIData($iconn, $query, false)){
						//echo "<br><br>".$query;
						mysqli_commit($iconn);
					}
				}
			}
		}

		if (($module == "" || $module == "SalesOrder") && strlen($username) > 8){
			$query = "DELETE FROM sorderdt WHERE User_Account = '".$username."' AND sorder_id IN (SELECT sorder_id from sorder WHERE LENGTH(User_Account) > 8 AND (sorder_reference IS NULL OR sorder_reference = '')) ";
			if (updateIData($iconn, $query, false)){
				//echo "<br><br>".$query;
				$query = "DELETE FROM sorder WHERE User_Account = '".$username."' AND (sorder_reference IS NULL OR sorder_reference = '')";
				if (updateIData($iconn, $query, false)){
					//echo "<br><br>".$query;
					mysqli_commit($iconn);
				}
			}
		}		
	}

	//Add Zeros to Employee Code
	function addZero($data, $length){
		//global $session_variable;
		$l = strlen($data);
		//if ($l < $_SESSION[$session_variable.'EmployeeCodeLength']){
		if ($l < $length){
			//for ($i=$l;$i<$_SESSION[$session_variable.'EmployeeCodeLength'];$i++){
			for ($i=$l;$i<$length;$i++){
				$data = "0".$data;
			}
		}
		return $data;
	}

	function jFolio($conn){
		$darray = getDate();
		$month =  $darray[mon];
		$query = "SELECT IFNULL((Journal_seq+1), 1) FROM jfolio WHERE Journal_Date = '".$month."'";
		$result = selectData($conn, $query);
		$query = "UPDATE jfolio SET Journal_seq = '".$result[0]."' WHERE Journal_Date = '".$month."'";
		updateData($conn, $query);
		return ($month.addZero($result[0], 4));
	}

	function getBase12($conn, $base, $cur, $date){
		if ($base == 1){
			$query = "SELECT MAX(Curdt_rate) FROM curdt WHERE Curdt_date <= '".$date."' AND Currency_code = '".$cur."' ";
		}else if ($base == 2){
			$query = "SELECT MAX(Curdt_parity) FROM curdt WHERE Curdt_date <= '".$date."' AND Currency_code = '".$cur."' ";
		}
		$result = selectData($conn, $query);
		if (is_numeric($result[0])){
			return $result[0];
		}else{
			return 1;
		}
	}
	
function SendMail($from, $namefrom, $to, $nameto, $subject, $message) {
	include("config.inc.php");
	
	$smtpServer = $config['MailServer'];           //ip address of the mail server.  This can also be the local domain name
	$port       = $config['MailPort'];             // should be 25 by default, but needs to be whichever port the mail server will be using for smtp 
	$timeout    = $config['MailTimeOut'];		   // typical timeout. try 45 for slow servers
	$username   = $config['MailUserName'];         // the login for your smtp
	$password   = $config['MailUserPass'];		   // the password for your smtp
	$localhost  = $config['MailLocalServer'];	   // Defined for the web server.  Since this is where we are gathering the details for the email
	$newLine = "\r\n";			 
	$secure = 0;				                   // change to 1 if your server is running under SSL

	//connect to the host and port
	$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
	$smtpResponse = fgets($smtpConnect, 4096);
	if(empty($smtpConnect)) {
	   $output = "Failed to connect: $smtpResponse";
	   //echo $output;
	   return $output;
	}
	else {
	   $logArray['connection'] = "<p>Connected to: $smtpResponse";
	   //echo "<p />connection accepted<br>".$smtpResponse."<p />Continuing<p />";
	}

	//you have to say HELO again after TLS is started
	fputs($smtpConnect, "HELO $localhost". $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['heloresponse2'] = "$smtpResponse";
	
	
	//request for auth login
	fputs($smtpConnect,"AUTH LOGIN" . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['authrequest'] = "$smtpResponse";

	//send the username
	fputs($smtpConnect, base64_encode($username) . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['authusername'] = "$smtpResponse";

	//send the password
	fputs($smtpConnect, base64_encode($password) . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['authpassword'] = "$smtpResponse";

	//email from
	fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['mailfromresponse'] = "$smtpResponse";

	//email to
	fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['mailtoresponse'] = "$smtpResponse";

	//the email
	fputs($smtpConnect, "DATA" . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['data1response'] = "$smtpResponse";

	//construct headers
	$headers = "MIME-Version: 1.0" . $newLine;
	$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
	$headers .= "To: $nameto <$to>" . $newLine;
	$headers .= "From: $namefrom <$from>" . $newLine;

	//observe the . after the newline, it signals the end of message
	fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['data2response'] = "$smtpResponse";

	// say goodbye
	fputs($smtpConnect,"QUIT" . $newLine);
	$smtpResponse = fgets($smtpConnect, 4096);
	$logArray['quitresponse'] = "$smtpResponse";
	$logArray['quitcode'] = substr($smtpResponse,0,3);
	fclose($smtpConnect);
	
	//a return value of 221 in $retVal["quitcode"] is a success
	return($logArray);
}

function SendSorderMail($Preference, $PUserAccount, $PClient, $PCltBalance, $PCltCreditLimit, $PCurr, $PSetupMsg) {
	include("config.inc.php");
	
	$from     = $config['EmailFrom'];
	$namefrom = $config['EmailFromName'];
	$to       = $config['EmailTo'];
	$nameto   = $config['EmailToName'];
	$subject = "SalesOrder raised of reference: ".$Preference;
	
	$message = "Dear All". "<br><br>".
			   "Ref: ". $Preference. "<br>".
			   "Username: ". $PUserAccount ."<br>".
			   "Client: ". $PClient ."<br>". 
			   "Balance: " . number_format($PCltBalance,2) ." ". $PCurr ."<br>". 
			   "Credit Limit: " . number_format($PCltCreditLimit,2) ." ". $PCurr ."<br>". 
				$PSetupMsg. "<br><br>";
			   
	//echo $from.", ".$namefrom.", ". $to.", ". $nameto.", ". $subject.", ". $message; exit;		   
	// this is it, lets send that email!
	$Errors = SendMail($from, $namefrom, $to, $nameto, $subject, $message);

	
	return $Errors;
}

function CashPaymentInvoice($PInvoiceID, $PMode, $PModuleDelivery, $PUserAccount, $PDbLabel, $PDbName, $connection) {
	$message = '';
	if ($PMode == 'I') {
		if ($PModuleDelivery == 1) {
			$sub_query = " Select Sale_Reference, Journal_ID, Client_Code, ".
						 " (ifNull(Sale_Total,0) + IfNull(Sale_VAT,0) + IfNull(Sale_TransportAmount,0) + IfNull(Sale_BonusAmount,0) - IfNull(Sale_DiscountAmount,0) + ".
						 "  (ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0))) As Sale_NetTotal,  ".
						 " ( ifNull(Sale_TotalBase1,0) + IfNull(Sale_VatBase1,0) + IfNull(Sale_TransportBase1,0) + IfNull(Sale_BonusBase1,0) - IfNull(Sale_DiscountBase1,0) + ".
						 "  (ifNull(sale_Tax1Base1,0) + ifNull(sale_Tax2Base1,0) + ifNull(sale_Tax3Base1,0) + ifNull(sale_Tax4Base1,0) + ifNull(sale_Tax5Base1,0))) As Sale_NetTotalB1,  ".
						 " ( ifNull(Sale_TotalBase2,0) + IfNull(Sale_VatBase2,0) + IfNull(Sale_TransportBase2,0) + IfNull(Sale_BonusBase2,0) - IfNull(Sale_DiscountBase2,0) + ".
						 "  (ifNull(sale_Tax1Base2,0) + ifNull(sale_Tax2Base2,0) + ifNull(sale_Tax3Base2,0) + ifNull(sale_Tax4Base2,0) + ifNull(sale_Tax5Base2,0))) As Sale_NetTotalB2  ".
						 " From Sales ".
						 " Where Sales.Sale_Id = '".$PInvoiceID."'";
		} else {
			$sub_query = " Select Delivery_Reference, Journal_ID, Client_Code, ".
						 " (ifNull(Delivery_Total,0) + IfNull(Delivery_VAT,0) + IfNull(Delivery_TransportAmount,0) + IfNull(Delivery_BonusAmount,0) - IfNull(Delivery_DiscountAmount,0) + ".
						 "  (ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0))) As Delivery_NetTotal,  ".
						 " ( ifNull(Delivery_TotalBase1,0) + IfNull(Delivery_VatBase1,0) + IfNull(Delivery_TransportAmountBase1,0) + IfNull(Delivery_BonusBase1,0) - IfNull(Delivery_DiscountBase1,0) + ".
						 "  (ifNull(Delivery_Tax1Base1,0) + ifNull(Delivery_Tax2Base1,0) + ifNull(Delivery_Tax3Base1,0) + ifNull(Delivery_Tax4Base1,0) + ifNull(Delivery_Tax5Base1,0))) As Delivery_NetTotalB1,  ".
						 " ( ifNull(Delivery_TotalBase2,0) + IfNull(Delivery_VatBase2,0) + IfNull(Delivery_TransportAmountBase2,0) + IfNull(Delivery_BonusBase2,0) - IfNull(Delivery_DiscountBase2,0) + ".
						 "  (ifNull(Delivery_Tax1Base2,0) + ifNull(Delivery_Tax2Base2,0) + ifNull(Delivery_Tax3Base2,0) + ifNull(Delivery_Tax4Base2,0) + ifNull(Delivery_Tax5Base2,0))) As Delivery_NetTotalB2  ".
						 
						 " From Deliveries ".
						 " Where Deliveries.Delivery_Id = '".$PInvoiceID."'";
		}
		
		//echo $sub_query;
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_rows=mysql_fetch_array($sub_result);
		
		$vInvRef         = $sub_rows[0];
		$vJournalID      = $sub_rows[1];
		$vClientCode     = $sub_rows[2];
		$vInvNetTotal    = $sub_rows[3];
		$vInvNetTotalB1  = $sub_rows[4];
		$vInvNetTotalB2  = $sub_rows[5];
			
		if (empty($vInvNetTotal))   $vInvNetTotal = 0;
		if (empty($vInvNetTotalB1)) $vInvNetTotalB1 = 0;
		if (empty($vInvNetTotalB2)) $vInvNetTotalB2 = 0;
	
	
		$sub_query = " Select JournalDt_ID From JournalDt Where Journal_Id = '".$vJournalID."' And Ledger_Number = '".$vClientCode."' And Journaldt_dbcd = 'C' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_rows=mysql_fetch_array($sub_result);
		$vJournalDtID = $sub_rows[0];
		
		$sub_query = " Select * From ".$PDbLabel.".AccLink Where Link_Id = '".$PInvoiceID."' And Link_Type = 'SI' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		$sub_rowscount=mysql_num_rows($sub_result);
		
		$vMainCompanyName=explode('_',$PDbName);
		$DirCompany  = $vMainCompanyName[0];
		$DirYear	 = $vMainCompanyName[1];
		
		if ($sub_rowscount == 0) {
			$query = " INSERT INTO ".$PDbLabel.".AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
					 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, CompanyName, DirYear, Link_DirYear, User_Account ) ".
					 " VALUES ( '".$vJournalDtID."', '".$PInvoiceID."', '".$vInvRef."', 'SI', 'JV', $vInvNetTotal, $vInvNetTotalB1, $vInvNetTotalB2, $vInvNetTotal, $vInvNetTotalB1, $vInvNetTotalB2, 0, 0, 0, ".
					 "          $vInvNetTotal, $vInvNetTotalB1, $vInvNetTotalB2, '".$vJournalDtID."', Null, '".$DirCompany."', '".$DirYear."', '".$DirYear."', '".$PUserAccount."') ";
		
		} else {
			$query = " UPDATE ".$PDbLabel.".AccLink SET ".
					 " Journal_Id = '".$vJournalDtID."', TraJournal_ID = '".$vJournalDtID."', ".
					 " Sale_NetTotal = $vInvNetTotal, Sale_NetTotalBase1 = $vInvNetTotalB1, Sale_NetTotalBase2 = $vInvNetTotalB2, ".
					 " Sale_PaidAmnt = $vInvNetTotal, Sale_PaidAmntbase1 = $vInvNetTotalB1, Sale_PaidAmntbase2 = $vInvNetTotalB2, ".
					 " Sale_NetToPay = $vInvNetTotal, Sale_NetToPayBase1 = $vInvNetTotalB1, Sale_NetToPayBase2 = $vInvNetTotalB2 ".
					 " WHERE Link_ID = '".$PInvoiceID."'";
		}
		
		$result=mysql_query($query,$connection);
		
		if(!$result) {
			$message  = mysql_error($connection);
		}	
	}
	else if ($PMode == 'D') {
		$query = " DELETE From ".$PDbLabel.".AccLink WHERE Link_ID = '".$PInvoiceID."'";
		$result=mysql_query($query,$connection);
		
		if(!$result) {
			$message  = mysql_error($connection);
		}
	}
	
	return $message;
}


function  UpdateTransaction($SSaId,$txtClientCode,$txtProjectCode,$txtCostCentCode,$JOURNALDT_VALUEDATE,$connection){


	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}
//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(module_paymentterms,0) As Module_PaymentTerms, ".
             " ifNull(module_creditlimit,0) As Module_CreditLimit, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder, ifNull(Module_InvoiceCheckLimit,0) As Module_InvoiceCheckLimit, ".
			 " ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ".
			 " ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject,ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj,  ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ifNull(Module_ChangeInvoiceItems,0) As Module_ChangeInvoiceItems, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate ".
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}
	

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, TipsAccount, CashCur From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}
	
//Check If Client Is Changed ==> Change VAT Accounts
		$sub_query7 = " Select Client_Code,Delivery_Date,ifNull(Delivery_DiscountPer,0) From Temp_Deliveries Where Delivery_ID = '".$SSaId."'";
		//echo $sub_query7;
		$sub_result7 = selectData($connection, $sub_query7);
		$vPreClientCode = $sub_result7[0];
		$PSaDate = $sub_result7[1];
		$PSaDiscount = $sub_result7[2];
		
		if ($vPreClientCode != trim($txtClientCode) and $txtClientCode!='' and $SSaId!='') {
			$sub_query = "SELECT Client_SellingPrice, ifNull(Client_DiscountPer,0),currency_code FROM Clients WHERE Ledger_Number = '".$txtClientCode."'";
	//echo "<br><br>".$sub_query;
	//exit;
			$sub_result = selectData($connection, $sub_query);
			$c_sp	   = $sub_result[0];
			$c_discper = $sub_result[1];
			$client_cur = $sub_result[2];
	
			
			
			$Acc_Query = " SELECT Salesmen_Code,Currency_Code,client_discountonInvoice,Client_Address,ifNull(Client_VAT,0) FROM Clients where ledger_Number = '".$txtClientCode."'  ";
			//echo$Acc_Query;
			$Acc_Result = selectData($connection, $Acc_Query);
			$SalesmanCode = $Acc_Result[0];
			$txtCurr = $Acc_Result[1];
			$client_discountonInvoice = $Acc_Result[2];
			$Client_DeliveryAddress = $Acc_Result[3];
			$PSaVatChkbx = $Acc_Result[4];
			
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
			$result = selectData($connection, $query);
			$rate_dt = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
			$result = selectData($connection, $query);
			$rate_dt1 = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
			$result = selectData($connection, $query);
			$rate_dt2 = $result[0];

	
	
			if($client_discountonInvoice=='') $client_discountonInvoice = 0;

			$Acc_Query = " SELECT VatAccount FROM salessetup ";
			$Acc_Result = selectData($connection, $Acc_Query);
		
			$vSaVatAcc = $Acc_Result[0];
			$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			
			$query = " UPDATE temp_deliveries SET ".
					 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', Delivery_VatAccount = '".$vSaVatAcc."' ".
					 " ,Project_Code='".$txtProjectCode."',Costcent_code = '".$txtCostCentCode."' ".
					 " WHERE Delivery_id = '".$SSaId."' ";
			$result=mysql_query($query,$connection);
			
			$sub_query7 = " Select DeliveryDt.DeliveryDt_ID, DeliveryDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0),Deliveries.Currency_Code,Deliveries.Delivery_Date ".
						  " From Temp_Deliveries as Deliveries,Temp_DeliveryDt as DeliveryDt".
						  " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ".
						  " Where DeliveryDt.Delivery_ID = '".$SSaId."' and DeliveryDt.Delivery_id = Deliveries.Delivery_id";
						  
			$sub_result7=mysql_query($sub_query7,$connection) or die(mysql_error());
			while($sub_rows7=mysql_fetch_array($sub_result7)){
				
					$vCurrencyCode=$sub_rows7[4];			
					$vDate=$sub_rows7[5];			
					$sub_query = " SELECT if('".$client_cur."'='$base1',Item_SellingPrice1Base1,if('".$client_cur."'='$base2',Item_SellingPrice1Base2,Item_SellingPrice1))
									, if('".$client_cur."'='$base1',Item_SellingPrice2Base1,if('".$client_cur."'='$base2',Item_SellingPrice2Base2,Item_SellingPrice2))
									, if('".$client_cur."'='$base1',Item_SellingPrice3Base1,if('".$client_cur."'='$base2',Item_SellingPrice3Base2,Item_SellingPrice3))
									, if('".$client_cur."'='$base1',Item_SellingPrice4Base1,if('".$client_cur."'='$base2',Item_SellingPrice4Base2,Item_SellingPrice4))
									, if('".$client_cur."'='$base1',Item_SellingPrice5Base1,if('".$client_cur."'='$base2',Item_SellingPrice5Base2,Item_SellingPrice5))
									, if('".$client_cur."'='$base1',Item_SellingPrice6Base1,if('".$client_cur."'='$base2',Item_SellingPrice6Base2,Item_SellingPrice6)) ".
									 
								 " ,ifNull(Item_Promotion, 0), ifNull(Item_NonStock, 0), ifNull(item_zeroPrice, 0), Item_UnitSalesDesc, Item_UnitPurchaseDesc, ".
								 " Currency_Code, ifNull(Item_MinimumPrice, 0) As Item_MinimumPrice, ifNull(Item_Unit,1), ifNull(Item_Vat,0), ifNull(Item_Pack,0), ".
								 " ifNull(Item_Expire,0), ifNull(item_withserialno,0), Items.Project_Code, Items.CostCent_Code, ifNull(Item_CostMethod,0), Item_Description, ifNull(Item_Package,0) ".
								 " ,Item_SellingPrice1Base1,Item_SellingPrice1Base2".
								 " ,Item_SellingPrice2Base1,Item_SellingPrice2Base2".
								 " ,Item_SellingPrice3Base1,Item_SellingPrice3Base2".
								 " ,Item_SellingPrice4Base1,Item_SellingPrice4Base2".
								 " ,Item_SellingPrice5Base1,Item_SellingPrice5Base2".
								 " FROM items WHERE Item_Code = '$sub_rows7[1]'";
						
					//echo "<br><br>".$sub_query;
					
					$sub_result = selectData($connection, $sub_query);
					$i_sp 		 = $sub_result[0];
					$i_promo     = $sub_result[6];
					$i_nonstock  = $sub_result[7];
					$i_zeroprice = $sub_result[8];
					$i_unit1     = $sub_result[9];
					$i_unit2 	 = $sub_result[10]; 
					$i_curr  	 = $sub_result[11];
					$i_minprice	 = $sub_result[12];
					$i_unitcoef	 = $sub_result[13];
					$i_vat		 = $sub_result[14];
					$i_pack		 = $sub_result[15];
					$i_itemexpire	  = $sub_result[16];
					$i_itemwithserial = $sub_result[17];
					$i_project 		  = $sub_result[18];
					$i_costcent 	  = $sub_result[19];
					$i_costmethod	  = $sub_result[20];
					$i_itemname		  = $sub_result[21];
					
					
					$i_itemunit		  = $sub_result[13];
					$i_itempackage		  = $sub_result[22];
					
						
					switch ($c_sp){
						case "II":
							$i_sp = $sub_result[1]; break;
						case "III":
							$i_sp = $sub_result[2]; break;
						case "IV":
							$i_sp = $sub_result[3]; break;
						case "V":
							$i_sp = $sub_result[4]; break;
						case "VI":
							$i_sp = $sub_result[5]; break;
					}
					
					if(($i_sp == 0 || $i_sp == '') && ($i_pack == 1)){
						$query = " SELECT Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice1Base1,if(Currency_Code='$base2',Item_SellingPrice1Base2,Item_SellingPrice1)),0)*PackDt_Quantity), 0)) As Item_SellingPrice1, ".
								 " Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice2Base1,if(Currency_Code='$base2',Item_SellingPrice2Base2,Item_SellingPrice2)),0)*PackDt_Quantity), 0)) As Item_SellingPrice2, ".
								 " Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice3Base1,if(Currency_Code='$base2',Item_SellingPrice3Base2,Item_SellingPrice3)),0)*PackDt_Quantity), 0)) As Item_SellingPrice3, ".
								 " Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice4Base1,if(Currency_Code='$base2',Item_SellingPrice4Base2,Item_SellingPrice4)),0)*PackDt_Quantity), 0)) As Item_SellingPrice4, ".
								 " Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice5Base1,if(Currency_Code='$base2',Item_SellingPrice5Base2,Item_SellingPrice5)),0)*PackDt_Quantity), 0)) As Item_SellingPrice5, ".
								 " Sum(if(ifNull(PackDt_CostPercentage,0) > 0, (ifNull(if(Currency_Code='$base1',Item_SellingPrice6Base1,if(Currency_Code='$base2',Item_SellingPrice6Base2,Item_SellingPrice6)),0)*PackDt_Quantity), 0)) As Item_SellingPrice6, ".
								 " 0 As Item_Promotion ".
								 " FROM items ".
								 " INNER JOIN packdt on packdt.item_codepackdt = items.item_code ".
								 " WHERE packdt.Item_Code = ".GetSQLValueString($vItemCode,"text")."";
						
						//echo "<br><br>".$query;
						$result = selectData($connection, $query);
						$i_sp = $result[0];
						$i_promo = $result[6];	
						
						switch ($c_sp){
							case "II":
								$i_sp = $result[1]; break;
							case "III":
								$i_sp = $result[2]; break;
							case "IV":
								$i_sp = $result[3]; break;
							case "V":
								$i_sp = $result[4]; break;
							case "VI":
								$i_sp = $result[5]; break;
						}
						
					}
				
				
				
				$ItemGroupCode = $sub_rows7[2];
				$ItemNonStock  = $sub_rows7[3];
			
			//echo $i_curr;exit;
			//Convert SellPrice To Invoice Currency
			if($i_curr!= $base1 and $i_curr!= $base2){
			$query = "SELECT ifNull(convertcurfunc('".$i_curr."', '".$vCurrencyCode."', '".$vDate."', 0, 0, '', '', ifNull(".$i_sp.",0)),0) From Dual ";
			$result = selectData($connection, $query);
			$i_sp	= $result[0];
			if (empty($i_sp)) $i_sp = 0;
			}
			
			
				// Get DirectStock Accounts
				$query = " SELECT VatAccount, VATAccountNonStock FROM salessetup ";
				$result = selectData($connection, $query);
						
				$vSaStpVatAcc 		  	  	= $result[0];
				$vSaStpVatNonStockAcc 	  	= $result[1];
						
					
				$query = " SELECT Trans_VATAccount FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$result = selectData($connection, $query);
				$vTranStpVatAcc = $result[0];
				
				if ($Module_RawMaterial == 1) {
					$vSaDtVatAcc = $vTranStpVatAcc;
				} 
				else {
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
									
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				
				$query = " UPDATE temp_deliverydt SET ".
						 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', DeliveryDt_VatAccount = '".$vSaDtVatAcc."' ".
						 " ,currency_code =  '".$txtCurr."' ".
						 " ,deliverydt_clientdiscount =  ".$client_discountonInvoice." ".
						 " ,deliverydt_itemdiscount = GetDiscountValue( '".ereg_replace("'", "\'", trim($txtClientCode))."',item_code) ".
						 " ,DeliveryDt_DiscountPer = $client_discountonInvoice + GetDiscountValue( '".ereg_replace("'", "\'", trim($txtClientCode))."',item_code) ".
						 " ,Deliverydt_Price = $i_sp".
						 " ,DeliveryDt_PriceBase1 = ifNull(convertcurfunc('".$txtCurr."', '".$base1."', '".$vDate."', 0, 0, '', '', ifNull(".$i_sp.",0)),0)".
						 " ,DeliveryDt_PriceBase2 = ifNull(convertcurfunc('".$txtCurr."', '".$base2."', '".$vDate."', 0, 0, '', '', ifNull(".$i_sp.",0)),0)".
						  " WHERE DeliveryDt_id = '".$sub_rows7[0]."' ";
				//echo $query."<br>";	
				//exit;
				$result=mysql_query($query,$connection);
			
			}
			
		$query = " UPDATE temp_deliveries SET ".
				 " Salesman_Code = '".$SalesmanCode."' ".
				 " ,Currency_Code = '".$txtCurr."' ".
				 " ,Delivery_ShippedTo = '".$Client_DeliveryAddress."' ".
				 " ,JOURNALDT_VALUEDATE = '".insertMySQLDate($JOURNALDT_VALUEDATE)."' ".
				 " WHERE Delivery_id = '$SSaId' ";
				 //, Project_Code = $ProjectCode, Costcent_code = $CostCentCode 
		//echo $query;		
	//	EXIT;
		$result=mysql_query($query,$connection);
		
	 
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts1($SSaId, $PSaDate, $PSaVatChkbx, $PSaDiscount, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
		$message  = $message . $CalculateResult;
		
		
		}
		
}


function  UpdateTransactionSorder($SSaId,$txtClientCode,$txtProjectCode,$txtCostCentCode,$JOURNALDT_VALUEDATE,$connection){


	$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}
//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(module_paymentterms,0) As Module_PaymentTerms, ".
             " ifNull(module_creditlimit,0) As Module_CreditLimit, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder, ifNull(Module_InvoiceCheckLimit,0) As Module_InvoiceCheckLimit, ".
			 " ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ".
			 " ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject,ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj,  ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ifNull(Module_ChangeInvoiceItems,0) As Module_ChangeInvoiceItems, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate ".
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}
	

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, TipsAccount, CashCur From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}
	
//Check If Client Is Changed ==> Change VAT Accounts
		$sub_query7 = " Select Client_Code,Sorder_Date,ifNull(Sorder_discountper,0) From Temp_Sorder Where Sorder_ID = '".$SSaId."'";
		//echo $sub_query7;
		$sub_result7 = selectData($connection, $sub_query7);
		$vPreClientCode = $sub_result7[0];
		$PSaDate = $sub_result7[1];
		$PSaDiscount = $sub_result7[2];
		
		if ($vPreClientCode != trim($txtClientCode) and $txtClientCode!='' and $SSaId!='') {
			$Acc_Query = " SELECT Salesmen_Code,Currency_Code,client_discountonInvoice,Client_Address,ifNull(Client_VAT,0) FROM Clients where ledger_Number = '".$txtClientCode."'  ";
			//echo$Acc_Query;
			$Acc_Result = selectData($connection, $Acc_Query);
			$SalesmanCode = $Acc_Result[0];
			$txtCurr = $Acc_Result[1];
			$client_discountonInvoice = $Acc_Result[2];
			$Client_DeliveryAddress = $Acc_Result[3];
			$PSaVatChkbx = $Acc_Result[4];
			
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
			$result = selectData($connection, $query);
			$rate_dt = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
			$result = selectData($connection, $query);
			$rate_dt1 = $result[0];
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
			$result = selectData($connection, $query);
			$rate_dt2 = $result[0];

	
	
			if($client_discountonInvoice=='') $client_discountonInvoice = 0;

			$Acc_Query = " SELECT VatAccount FROM salessetup ";
			$Acc_Result = selectData($connection, $Acc_Query);
		
			$vSaVatAcc = $Acc_Result[0];
			$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaVatAcc = $sub_resultVat[0];
			
			$query = " UPDATE temp_sorder SET ".
					 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."' ".
					 " ,Project_Code='".$txtProjectCode."',Costcent_code = '".$txtCostCentCode."' ".
					 " WHERE Sorder_id = '".$SSaId."' ";
			$result=mysql_query($query,$connection);
			
			$sub_query7 = " Select SorderDt_ID, SorderDt.Item_Code, Items.Group_Code, ifNull(Items.Item_NonStock,0) ".
						  " From Temp_SorderDt as SorderDt ".
						  " Inner Join Items on SorderDt.Item_Code = Items.Item_Code ".
						  " Where Sorder_ID = '".$SSaId."'";
						  
			$sub_result7=mysql_query($sub_query7,$connection) or die(mysql_error());
			while($sub_rows7=mysql_fetch_array($sub_result7)){
				$ItemGroupCode = $sub_rows7[2];
				$ItemNonStock  = $sub_rows7[3];
			
				// Get DirectStock Accounts
				$query = " SELECT VatAccount, VATAccountNonStock FROM salessetup ";
				$result = selectData($connection, $query);
						
				$vSaStpVatAcc 		  	  	= $result[0];
				$vSaStpVatNonStockAcc 	  	= $result[1];
						
					
				$query = " SELECT Trans_VATAccount FROM transactionsetup ".
						 " WHERE Journal_type = 'SI' ".
						 " AND Group_code = '".$ItemGroupCode."'  ";
								 
				$result = selectData($connection, $query);
				$vTranStpVatAcc = $result[0];
				
				if ($Module_RawMaterial == 1) {
					$vSaDtVatAcc = $vTranStpVatAcc;
				} 
				else {
					if ($ItemNonStock == 1)
						$vSaDtVatAcc = $vSaStpVatNonStockAcc;
					else	
						$vSaDtVatAcc = $vSaStpVatAcc;
									
				}
				
				$sub_queryVat = " SELECT GetVATAccount('".trim($txtClientCode)."','".$vSaDtVatAcc."') from dual ";
				$sub_resultVat = selectData($connection, $sub_queryVat);
				if ($sub_resultVat[0] != '') $vSaDtVatAcc = $sub_resultVat[0];
				
				
				$query = " UPDATE temp_Sorderdt SET ".
						 " Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."'  ".
						 " ,sorderdt_clientdiscount =  ".$client_discountonInvoice." ".
						 " ,sorderdt_itemdiscount = GetDiscountValue( '".ereg_replace("'", "\'", trim($txtClientCode))."',item_code) ".
						 " ,Sorderdt_discount = $client_discountonInvoice + GetDiscountValue( '".ereg_replace("'", "\'", trim($txtClientCode))."',item_code) ".
						 " WHERE SorderDt_id = '".$sub_rows7[0]."' ";
				//echo $query."<br>";	
				$result=mysql_query($query,$connection) or die(mysql_error());
			
			}
			
		$query = " UPDATE temp_sorder SET ".
				 " Salesman_Code = '".$SalesmanCode."' ".
				 " ,Currency_Code = '".$txtCurr."' ".
				 " ,Sorder_DeliveryPlace = '".$Client_DeliveryAddress."' ".
				 " ,Sorder_MaturityDate = '".insertMySQLDate($JOURNALDT_VALUEDATE)."' ".
				 " WHERE Sorder_id = '$SSaId' ";
				 //, Project_Code = $ProjectCode, Costcent_code = $CostCentCode 
		//echo $query;		
	//	EXIT;
		$result=mysql_query($query,$connection) or die(mysql_error());
		
	 
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmountsSorder($SSaId, $PSaDate, $PSaVatChkbx, $PSaDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
						   
		$message  = $message . $CalculateResult;
		
		
		}
		
}



function Calculate_MasterAmounts1($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PBonusAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {

	$vSaDtTotal = 0;
	$vItemVat    = 0;
	
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountPer    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaTransportAmtTTC = 0;
	$vSaBonusAmt   	    = 0;
	$vSaBonusAmtB1      = 0;
	$vSaBonusAmtB2      = 0;
	$vSaBonusAmtTTC     = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
		
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;

	$vSaDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(Delivery_VatChkbx, 0) From Temp_Deliveries Where Delivery_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}
	
	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_DeliveryDt SET  ".
				 " DeliveryDt_Price = DeliveryDt_PriceTTC, ".
				 " DeliveryDt_PriceBase1 = DeliveryDt_PriceTTCBase1, ".
				 " DeliveryDt_PriceBase2 = DeliveryDt_PriceTTCBase2 ".
				 " Where Delivery_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	else if ($PSalesTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE Temp_DeliveryDt SET  ".
				 " DeliveryDt_Price      = (DeliveryDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase1 = (DeliveryDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " DeliveryDt_PriceBase2 = (DeliveryDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Delivery_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}	
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " DeliveryDt_Quantity, (ifNull(DeliveryDt_DiscountAmount,0) - ifNull(DeliveryDt_TransportAmount,0) - ifNull(DeliveryDt_BonusAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_DeliveryDt ".
				 " Where Delivery_ID = ".$PId;
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PSalesTTC == 1) {
		if ($PMode == 'P') {
			$vSaDiscountAmtTTC  = $PDiscAmt;					
			$vSaDiscountAmt     = ($vSaDiscountAmtTTC / (1 + $PSetupVatPercentage/100));
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
				$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $PSetupVatPercentage/100));
			}	
		}
		
		$vSaTransportAmtTTC = $PTransportAmt;					
		$vSaTransportAmt    = ($vSaTransportAmtTTC / (1 + $PSetupVatPercentage/100));
		$vSaBonusAmtTTC 	= $PBonusAmt;					
		$vSaBonusAmt    	= ($vSaBonusAmtTTC / (1 + $PSetupVatPercentage/100));
		
		if ($PVatChk == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $PSetupVatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PMode == 'P') {
			$vSaDiscountAmt      = $PDiscAmt;					
		} else {
			if ($vSaDiscountPer > 0) {
				$vSaDiscountAmt     = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			}	
		}
		
		$vSaTransportAmt    = $PTransportAmt;
		$vSaTransportAmtTTC = 0;
		$vSaBonusAmt    	= $PBonusAmt;
		$vSaBonusAmtTTC 	= 0;
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
	
				
	//$vSaTransportAmt   = $PTransportAmt;	
	//$vSaTransportAmtB1 = ($vSaTransportAmt*$PRate)/$PRate1;
	//$vSaTransportAmtB2 = ($vSaTransportAmt*$PRate)/$PRate2;	
				
					
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$PRate)/$PRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$PRate)/$PRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$PRate)/$PRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$PRate)/$PRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$PRate)/$PRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$PRate)/$PRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$PRate)/$PRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$PRate)/$PRate2;
	$vSaVatBase1 		 = ($vSaVat*$PRate)/$PRate1;
	$vSaVatBase2 		 = ($vSaVat*$PRate)/$PRate2;
	$vSaTransportAmtB1   = ($vSaTransportAmt*$PRate)/$PRate1;
	$vSaTransportAmtB2   = ($vSaTransportAmt*$PRate)/$PRate2;	
	$vSaBonusAmtB1 	     = ($vSaBonusAmt*$PRate)/$PRate1;
	$vSaBonusAmtB2	     = ($vSaBonusAmt*$PRate)/$PRate2;	
					

	$vSaTax1B1  = ($vSaTax1*$PRate)/$PRate1;
	$vSaTax1B2  = ($vSaTax1*$PRate)/$PRate2;		
	$vSaTax2B1  = ($vSaTax2*$PRate)/$PRate1;
	$vSaTax2B2  = ($vSaTax2*$PRate)/$PRate2;		
	$vSaTax3B1  = ($vSaTax3*$PRate)/$PRate1;
	$vSaTax3B2  = ($vSaTax3*$PRate)/$PRate2;		
	$vSaTax4B1  = ($vSaTax4*$PRate)/$PRate1;
	$vSaTax4B2  = ($vSaTax4*$PRate)/$PRate2;		
	$vSaTax5B1  = ($vSaTax5*$PRate)/$PRate1;
	$vSaTax5B2  = ($vSaTax5*$PRate)/$PRate2;	
	
	fbegin1();
	
	$sub_query1 = " UPDATE temp_deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_DiscountPer = $vSaDiscountPer, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_VatChkbx = $PVatChk, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_TransportAmount = $vSaTransportAmt, Delivery_TransportAmountBase1 = $vSaTransportAmtB1, Delivery_TransportAmountBase2 = $vSaTransportAmtB2, Delivery_TransportTTC = $vSaTransportAmtTTC, ".
				  " Delivery_BonusAmount = $vSaBonusAmt, Delivery_BonusBase1 = $vSaBonusAmtB1, Delivery_BonusBase2 = $vSaBonusAmtB2, Delivery_BonusTTC = $vSaBonusAmtTTC, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2  ".
				  " WHERE Delivery_ID = ".$PId;
		
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit1();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback1();
	}
			
	Return $error;		

}

		 
function Calculate_MasterAmountsSorder($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {
 
	$vSorDtTotal = 0;
	$vItemVat    = 0;
	
	$vSorTaxable 		 = 0;
	$vSorNoneTaxable 	 = 0;
	$vSorGrossTotal 	 = 0;
	$vSorDiscountAmt 	 = 0;
	$vSorDiscountPer 	 = 0;
	$vSorTransportAmt    = 0;
	$vSorTransportAmtB1  = 0;
	$vSorTransportAmtB2  = 0;
	$vSorTransportAmtTTC = 0;
	$vSorVat 	  = 0;
	$vSorVatBase1 = 0;
	$vSorVatBase2 = 0;
		
	$vSorTax1 = 0;
	$vSorTax2 = 0;
	$vSorTax3 = 0;
	$vSorTax4 = 0;
	$vSorTax5 = 0;
	$vSorTax1B1 = 0;
	$vSorTax2B1 = 0;
	$vSorTax3B1 = 0;
	$vSorTax4B1 = 0;
	$vSorTax5B1 = 0;
	$vSorTax1B2 = 0;
	$vSorTax2B2 = 0;
	$vSorTax3B2 = 0;
	$vSorTax4B2 = 0;
	$vSorTax5B2 = 0;

	$vSorDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(Sorder_VATChckbx, 0) From Temp_Sorder Where Sorder_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}
	
	/*if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_SorderDt SET  ".
				 " SorderDt_Price = SorderDt_PriceTTC, ".
				 " SorderDt_PriceBase1 = ((SorderDt_PriceTTC*$PRate)/$PRate1), ".
				 " SroderDt_PriceBase2 = ((SorderDt_PriceTTC*$PRate)/$PRate2) ".
				 " Where Sorder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	else if ($PSalesTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE Temp_SorderDt SET  ".
				 " SorderDt_Price      = (SorderDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " SorderDt_PriceBase1 = (((SorderDt_PriceTTC*$PRate)/$PRate1) / (1 + Item_Vat/100)), ".
				 " SroderDt_PriceBase2 = (((SorderDt_PriceTTC*$PRate)/$PRate2) / (1 + Item_Vat/100)) ".
				 " Where Sorder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}*/	
	
	
		
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0)*ifNull(SorderDt_Discount,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SorderDt_Quantity, (ifNull(SorderDt_DiscountAmount,0) - ifNull(SorderDt_TransportAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ".
				 " ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0)*ifNull(SorderDt_Discount,0))/100)) As TotalTTC ".
				 " From Temp_SorderDt ".
				 " Where Sorder_ID = ".$PId;
										 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSorDtTotal    = $sub_rows[1];
		$vItemVat       = $sub_rows[2];
		$vSorDtTotalTTC = $sub_rows[10];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
		//if ($PSalesTTC ==1 && $PVatChk == 0) {					
			//$vSorTaxable     = $vSorTaxable     + ($vSorDtTotalTTC*$tax_flag);
			//$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotalTTC*$notax_flag);
		//} else {
			$vSorTaxable     = $vSorTaxable     + ($vSorDtTotal*$tax_flag);
			$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotal*$notax_flag);
		//}
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSorDtTotal > 0)
			$vSorVat = $vSorVat + (($vSorDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSorDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSorTax1 = $vSorTax1 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSorTax2 = $vSorTax2 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSorTax3 = $vSorTax3 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSorTax4 = $vSorTax4 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSorTax5 = $vSorTax5 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSorGrossTotal = $vSorTaxable + $vSorNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vSorDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vSorDiscountPer > 0)
			$vSorDiscountAmt = (($vSorGrossTotal * $vSorDiscountPer) / 100);
	}	

	if ($PSalesTTC == 1) {
		$vSorTransportAmtTTC = $PTransportAmt;					
		$vSorTransportAmt    = ($vSorTransportAmtTTC / (1 + $PSetupVatPercentage/100));	
	} else {
		$vSorTransportAmt    = $PTransportAmt;
		$vSorTransportAmtTTC = 0;
	}
				
					
	$vSorNetTotal         = $vSorGrossTotal + $vSorVat - $vSorDiscountAmt;
	$vSorTaxableBase1     = ($vSorTaxable*$PRate)/$PRate1;
	$vSorTaxableBase2     = ($vSorTaxable*$PRate)/$PRate2;
	$vSorNoneTaxableBase1 = ($vSorNoneTaxable*$PRate)/$PRate1;
	$vSorNoneTaxableBase2 = ($vSorNoneTaxable*$PRate)/$PRate2;
	$vSorDiscountAmtBase1 = ($vSorDiscountAmt*$PRate)/$PRate1;
	$vSorDiscountAmtBase2 = ($vSorDiscountAmt*$PRate)/$PRate2;
	$vSorGrossTotalBase1  = ($vSorGrossTotal*$PRate)/$PRate1;
	$vSorGrossTotalBase2  = ($vSorGrossTotal*$PRate)/$PRate2;
	$vSorVatBase1 		  = ($vSorVat*$PRate)/$PRate1;
	$vSorVatBase2 		  = ($vSorVat*$PRate)/$PRate2;
	$vSorTransportAmtB1   = ($vSorTransportAmt*$PRate)/$PRate1;
	$vSorTransportAmtB2   = ($vSorTransportAmt*$PRate)/$PRate2;	
					

	$vSorTax1B1  = ($vSorTax1*$PRate)/$PRate1;
	$vSorTax1B2  = ($vSorTax1*$PRate)/$PRate2;		
	$vSorTax2B1  = ($vSorTax2*$PRate)/$PRate1;
	$vSorTax2B2  = ($vSorTax2*$PRate)/$PRate2;		
	$vSorTax3B1  = ($vSorTax3*$PRate)/$PRate1;
	$vSorTax3B2  = ($vSorTax3*$PRate)/$PRate2;		
	$vSorTax4B1  = ($vSorTax4*$PRate)/$PRate1;
	$vSorTax4B2  = ($vSorTax4*$PRate)/$PRate2;		
	$vSorTax5B1  = ($vSorTax5*$PRate)/$PRate1;
	$vSorTax5B2  = ($vSorTax5*$PRate)/$PRate2;	
	
	fbegin1();
	
	$sub_query1 = " UPDATE temp_sorder SET ".
				  " Sorder_Taxable = $vSorTaxable, Sorder_TaxableBase1 = $vSorTaxableBase1, Sorder_TaxableBase2 = $vSorTaxableBase2, ".
				  " Sorder_NoneTaxable = $vSorNoneTaxable, Sorder_NoneTaxableBase1 = $vSorNoneTaxableBase1, Sorder_NoneTaxableBase2 = $vSorNoneTaxableBase2, ".
				  " Sorder_DiscountAmount = $vSorDiscountAmt, Sorder_DiscountBase1 = $vSorDiscountAmtBase1, Sorder_DiscountBase2 = $vSorDiscountAmtBase2, ".
				  " Sorder_DiscountPer = $vSorDiscountPer, Sorder_VAT = $vSorVat, Sorder_VATBase1 = $vSorVatBase1, Sorder_VATBase2 = $vSorVatBase2, ".
				  " Sorder_VATChckbx = $PVatChk, ".
				  " Sorder_tax1 = $vSorTax1, Sorder_tax1base1 = $vSorTax1B1, Sorder_tax1base2 = $vSorTax1B2,  ".
				  " Sorder_tax2 = $vSorTax2, Sorder_tax2base1 = $vSorTax2B1, Sorder_tax2base2 = $vSorTax2B2,  ".
				  " Sorder_tax3 = $vSorTax3, Sorder_tax3base1 = $vSorTax3B1, Sorder_tax3base2 = $vSorTax3B2,  ".
				  " Sorder_tax4 = $vSorTax4, Sorder_tax4base1 = $vSorTax4B1, Sorder_tax4base2 = $vSorTax4B2,  ".
				  " Sorder_tax5 = $vSorTax5, Sorder_tax5base1 = $vSorTax5B1, Sorder_tax5base2 = $vSorTax5B2  ";
				  
	//if ($PTransportAmt > 0)			  
		$sub_query1 = $sub_query1.", Sorder_TransportAmount = $vSorTransportAmt, Sorder_TransportBase1 = $vSorTransportAmtB1, Sorder_TransportBase2 = $vSorTransportAmtB2, Sorder_TransportTTC = $vSorTransportAmtTTC ";
		
	$sub_query1 = $sub_query1." WHERE Sorder_id = ".$PId ;
	//echo $sub_query1."<br>";exit;	
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	
	if ($sub_result1){
		fcommit1();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback1();
	}
			
	Return $error;		

}

	  	  
function fbegin1()
{
	mysql_query("START TRANSACTION");
}
function fcommit1(){
	mysql_query("COMMIT");
}
function frollback1()
{
	mysql_query("ROLLBACK");
}
?>
