<?php
include("../include/session.php");
include("../include/db.php");



    if (isset($_GET['new_button']) )
	   {
		 $action='outWiz0.php';
	   }
		 
	if (isset($_GET['finish_button']) )
	  {
		$action='viewDelivery.php?DelNoText='.$_SESSION['delNoteText'] ;
	  }	 

	
	$orderNo = $_SESSION['orderNo'];
	$custNo =  $_SESSION['CustomerNoText'];
	$delDate =  $_SESSION['DeliveryDateText'];
	$comments = $_SESSION['RemarksText'];
	$delNoteNo = $_SESSION['delNoteText'];
	$delCol = $_SESSION['delColText'];
	$deliverTo = $_SESSION['DeliverText1'];
	$plotNo = $_SESSION['DeliverText2'];
	$place = $_SESSION['DeliverText3'];
	$contact= $_SESSION['contactText'];
	$delAddress = '';
	$transporter = $_SESSION['TransporterText'];
	$regNo = $_SESSION['RegNoText'];
	$LineNo = $_SESSION['orderNum'];
	
	$pallets = $_SESSION['PalletsText']; 
	$palletsPrice = $_SESSION['PalletsPriceText'];  
	
	
	
	$L = 0;
	
	while ($L < $LineNo) {
	  $productId[$L] =  $_SESSION['ProductIdText'.$L];
	  $price[$L] =  $_SESSION['PriceText'.$L] ;	
	  $delQuantity[$L] = $_SESSION['QuantityText'.$L];
	  $BatchCodeOne[$L] = $_SESSION['BatchCode1Text'.$L];
	  $BatchCodeTwo[$L] = $_SESSION['BatchCode2Text'.$L];
	  //echo "<br>" .$L." product: ".$productId[$L];
	  $L++;
	}
	$userId = $_SESSION['username'];
	date_default_timezone_set('Africa/Khartoum');
	$entryDate = date("Y-m-d H:i:s",time()-3600); 
	
	
	$name_query = "SELECT CompanyName FROM nam_customer WHERE CustNo = $custNo";
	$name_result = execsql($name_query);
	$custName = mysql_result($name_result, 0, "CompanyName");
	$entry="30";
	$reference=$delNoteNo;
	 
	$L = 0;
	while ($L < $LineNo) { 
	
	    //where the entry allready exist
	  	//checking if the entry already exists
		
		$check_query = "SELECT quantity, batchCodeOne, batchCodeTwo FROM nam_sales WHERE delNote = $delNoteNo AND productId = $productId[$L] AND price > 0  ";
	  	$check_result = execsql($check_query);
	  	$check_num = mysql_num_rows($check_result);
	
		//if the entry exists
		if ($check_num > 0) {
	    $batch1 = mysql_result($check_result, 0, "batchCodeOne");
		$batch2 = mysql_result($check_result, 0, "batchCodeTwo");
		if ($batch1=="") {$batch1= $BatchCodeOne[$L];}	
		if ($batch2=="") {$batch2= $BatchCodeTwo[$L];}
		
		//updating the existing lines with the additional quantity	
		$addQuantity = "UPDATE nam_sales SET  quantity=quantity+'".$delQuantity[$L]."', price='".$price[$L]."', batchCodeOne='".$batch1."' , batchCodeTwo='".$batch2."' WHERE delNote = ". $delNoteNo ." AND productId = ". $productId[$L]." AND price > 0 ";
	    execsql($addQuantity);
		
						
		//updating reserved number in nam_orders table
		$ReservedQuantity = "UPDATE nam_orders SET  reserved=reserved-".$delQuantity[$L]." WHERE orderNo = ". $orderNo ." AND productId = ". $productId[$L] ;
		execsql($ReservedQuantity);
				
		//updating quantity (stock amount) in products table
		$StockQuantity = "UPDATE nam_products SET quantity=quantity - ".$delQuantity[$L]." WHERE  productId = ". $productId[$L] ;
	    execsql($StockQuantity);
		
		//counting the new stock level
		$totalQuery= "SELECT quantity FROM nam_products WHERE productId = '$productId[$L]'";
		$totalResult = execsql($totalQuery);
		$total = mysql_result($totalResult, 0, "quantity");
		
		//inserting additional quantity in nam_itemhistory
		
		if ($delQuantity[$L] != 0) {
		$historyQuery = "INSERT INTO nam_itemhistory (productId, entry, reference, quantity, total, date, entryDate, userId) VALUES ('".$productId[$L]."','".$entry."','".$reference."','".$delQuantity[$L]."', '".$total."','".$delDate."','".$entryDate."','".$userId."')";
	 	execsql($historyQuery);
		
		}
		
		}
		 
		else  {
		
		//if the entry does not exist, a new entry is made
		//inserting lines on delivery note sales table
		if ($delQuantity[$L]>0)	{	 
	  	$del_query = "INSERT INTO nam_sales ( delNote, custNo, client, orderNo, date, comments, quantity, price, productId, batchCodeOne, batchCodeTwo, delAddress, transporter, regNo) VALUES ('" . $delNoteNo . "', '" . $custNo . "', '" . $custName . "','" . $orderNo . "', '" . $delDate . "', '" . $comments . "', '" . $delQuantity[$L] . "','" . $price[$L] . "', '" . $productId[$L] . "','" . $BatchCodeOne[$L] . "','" . $BatchCodeTwo[$L] . "','" . $delAddress . "','" . $transporter . "','" . $regNo . "' ) ";
		execsql($del_query); 
		
		
		//updating reserved number in nam_orders table
		$ReservedQuantity = "UPDATE nam_orders SET  reserved=reserved - ".$delQuantity[$L]." WHERE orderNo = ". $orderNo ." AND productId = ". $productId[$L] ;
		execsql($ReservedQuantity);     
				
		//updating quantity (stock amount) in products table
		$StockQuantity = "UPDATE nam_products SET quantity=quantity - ".$delQuantity[$L]." WHERE  productId = ". $productId[$L] ;
		execsql($StockQuantity);
						
		//counting the new stock level
		$totalQuery= "SELECT quantity FROM nam_products WHERE productId = '$productId[$L]'";
		$totalResult = execsql($totalQuery);
		$total = mysql_result($totalResult, 0, "quantity");
		
		//updating item History
		
		$historyQuery = "INSERT INTO nam_itemhistory (productId, entry, reference, quantity, total, date, entryDate, userId) VALUES ('".$productId[$L]."','".$entry."','".$reference."','".$delQuantity[$L]."', '".$total."','".$delDate."','".$entryDate."','".$userId."')";
	 	execsql($historyQuery);
		
		}
		
		}
		$L++;
	}
	
	if ($pallets!=0) {
	
	$pallets_query = "INSERT INTO nam_sales ( delNote, custNo, client, orderNo, date, quantity, price, productId, delAddress, transporter, regNo) VALUES ('" . $delNoteNo . "', '" . $custNo . "', '" . $custName . "','" . $orderNo . "', '" . $delDate . "','" . $pallets . "','" . $palletsPrice . "', '10000', '" . $delAddress . "','" . $transporter . "','" . $regNo . "' ) ";
		execsql($pallets_query); 
		
		$pallets_quantityQuery = "SELECT quantity FROM nam_products WHERE productId = '10000'";
	$pallets_quantityResult = mySQL_query($pallets_quantityQuery);
	$pallets_totalQuantity = mysql_result($pallets_quantityResult, 0, "quantity") - $pallets;
	
	$deliveredQuery = "INSERT INTO nam_delivered_address (delCol, deliverTo, address, place,  delNoteNo, orderNo, transporter, regNo, contact) VALUES ('" . $delCol . "','" . $deliverTo . "', '" . $plotNo . "','" . $place . "',  '" . $delNoteNo . "', '" . $orderNo . "','" . $transporter . "','" . $regNo . "','" . $contact . "' ) ";
	execsql($deliveredQuery); 
	
	
	$pallets_stockQuery = "UPDATE nam_products SET  quantity = '".$pallets_totalQuantity."' , lastModDate = '".$entryDate."'  WHERE productId = '10000'";
	$pallets_stockResult = mySQL_query($pallets_stockQuery);
		
	$entry="31";	
	$historyQuery = "INSERT INTO nam_itemhistory (productId, entry, reference, quantity, total, date, entryDate, userId) VALUES ('10000','".$entry."','".$reference."', '".$pallets."', '".$pallets_totalQuantity."','".$delDate."','".$entryDate."','".$userId."')";
	$historyResult = mySQL_query($historyQuery);
	
	}
	
	$actionQuery = "INSERT INTO nam_action_tracking (entry_date, user, action, details) VALUES ('".$entryDate."' ,'".$userId."','Delivery' ,'".$delNoteNo."' )";
	$actionResult = mySQL_query($actionQuery);
	
	
	
	$_SESSION['orderNo'] = '';
     $_SESSION['error']=0;
	 $_SESSION['delNoteText']='';
	 $_SESSION['complete'] = '';
	 $_SESSION['no_pallets'] = '';
	 $_SESSION['orderNum'] ='';
	 $_SESSION['OrderNoText'] = '';
	 $_SESSION['CustomerNoText'] = '';
	 $_SESSION['CustomerNameText'] = '';
	 $_SESSION['DeliveryDateText'] = date('Y-m-d');
	 $_SESSION['DeliverText1'] = '';
	 $_SESSION['DeliverText2'] = '';
	 $_SESSION['DeliverText3'] = '';
	 $_SESSION['contactText'] = '';
	 $_SESSION['PalletsPriceText'] = '';
	 $_SESSION['PalletsText'] = '';
	 
	 $i=0;
		While ($i<10) {
			    $_SESSION['DeliverCheck'.$i] = '';
				$_SESSION['ProductIdText'.$i] = '';
         		$_SESSION['ProductNameText'.$i] = '';
				$_SESSION['QuantityText'.$i] = '';
				$_SESSION['PriceText'.$i] = '';
			    $_SESSION['BatchCode1Text'.$i] = '';
				$_SESSION['BatchCode2Text'.$i] = '';
				$_SESSION['TotalText'.$i] = '';
				$i++;
				
		$_SESSION['PalletsText'] = '';
		}
	
    
	 $_SESSION['PlaceText'] = '';
	 $_SESSION['TransporterText'] = '';
	 $_SESSION['RegNoText'] = '';
	 $_SESSION['RemarksText'] = '';
	
	
	
	?>
<script language="javascript" type="text/javascript">
        <!--
		  window.location=" <?php echo $action?> ";
        -->
       </script>

