<?php
$PageSecurity = 4;
$PageName = 'Purchase Order';
include('includes/DefineSuppTransClass.php');
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');   
$POListFormId=$px->GetFormId('PO_SelectOSPurchOrder.php');  
   
    $title = _('Purchase Order Items');
	$identifier=$_GET['identifier'];
	$supplier = $_GET['suppid'];
	$final_qtation = $_GET['final_quat'];
	$tt = $_GET['sitecode'];
////new (manvi)/////
	$sitecode = $_GET['sitecode'];
	$sitename = $_GET['sitename'];
	$reqno = $_GET['requisiton'];
	
	 $REQSQL = "SELECT Reqno FROM materialrequisitions WHERE requisitionno='".$_GET['requisiton']."' and CompanyId='".$_SESSION['ACGCompanyId']."' ";

	$RES = DB_query($REQSQL,$db);
	$MYROW = DB_fetch_array($RES);
	$Reqno = $MYROW['Reqno'];

	$Prefix_SQL = "Select prefix_id,prefix_code,prefix_name from prefix_tbl Where prefix_name ='".$PageName."'";
	$Prefix_Result = DB_query($Prefix_SQL,$db);
	$Prefix_Row = DB_fetch_array($Prefix_Result);
	$Prefix_code = $Prefix_Row['prefix_code'];
	$Prefix_date = date("y");
	$Prefix_date++;
	$CurrentFinancialYear = date("y")."-".$Prefix_date; 
if (!isset($_SESSION['PO'.$identifier]))
	{
		header('Location:' . $rootpath . '/PO_SelectOSPurchOrder.php?' . SID);
		exit;
	} 
$Maximum_Number_Of_Parts_To_Show=50;
if(isset($_POST['StockID2']) && $_GET['Edit']=='')
{
	
	    $sql = "SELECT stockmaster.description,
				purchdata.suppliers_partno,
				stockmaster.pkg_type,
				stockmaster.units,
				stockmaster.netweight,		
				stockmaster.kgs,
				stockmaster.volume
				FROM purchdata INNER JOIN stockmaster
				ON purchdata.stockid=stockmaster.stockid
				WHERE purchdata.stockid='" . $_POST['StockID2'] . "' AND
				purchdata.supplierno='".$_SESSION['PO'.$identifier]->SupplierID."'";
	
		$ErrMsg = _('The stock record of the stock selected') . ': ' . $_POST['Stock'] . ' ' . 
			_('cannot be retrieved because');
		$DbgMsg = _('The SQL used to retrieve the supplier details and failed was');
		$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
		$myrow = DB_fetch_row($result);
		
		$_POST['ItemDescription'] = $myrow[0];
		$_POST['suppliers_partno'] = $myrow[1];
		$_POST['package'] = $myrow[2];
		$_POST['uom'] = $myrow[3];
		$_POST['nw'] = $myrow[4];
		$_POST['gw'] = $myrow[5];
		$_POST['cuft'] = $myrow[6];
	} 
if(isset($_POST['UpdateLines']) OR isset($_POST['Commit'])) 
{
	 if(isset($_SESSION['PO'.$identifier]->LineItems))
		 {
			foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine)
			  {
				if($POLine->Deleted==False)
				   {
						$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Quantity=$_POST['Qty'.$POLine->LineNo];
						$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Price=$_POST['Price'.$POLine->LineNo];
						$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->nw=$_POST['nw'.$POLine->LineNo];
						$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ReqDelDate=$_POST['ReqDelDate'.$POLine->LineNo];
				   }
			  }
		 }
	}
if(isset($_POST['Commit']))
{
	//print_r($_POST);
	$cti=1;
	foreach($_POST as $key => $value)
	 {
		if(substr($key, 0, 3)=='Qty')
			 {
					$ItemCode=substr($key, 3, strlen($key)-3);
			
					$Quantity=$value;
					$AlreadyOnThisOrder =0;
					if($_SESSION['PO_AllowSameItemMultipleTimes'] ==false)
					{
						if (count($_SESSION['PO'.$identifier]->LineItems)!=0)
						{
							foreach ($_SESSION['PO'.$identifier]->LineItems AS $OrderItem)
							 {
							
								if (($OrderItem->StockID == $ItemCode) and ($OrderItem->Deleted==false))
								 {
									$AlreadyOnThisOrder = 1;
									prnMsg( _('The item') . ' ' . $ItemCode . ' ' . _('is already on this order') . '. ' . _('The system will not allow the same item on the order more than once') . '. ' . _('However you can change the quantity ordered of the existing line if necessary'),'error');
								}
							} 
						}
					}
					if($AlreadyOnThisOrder!=1 and $Quantity>0)
					{
						 $purchdatasql='SELECT COUNT(supplierno)
										FROM purchdata
										WHERE purchdata.supplierno = "' . $_SESSION['PO'.$identifier]->SupplierID . '"
										AND purchdata.stockid="'. $ItemCode . '"';
						$purchdataresult=DB_query($purchdatasql, $db);
						$myrow=DB_fetch_row($purchdataresult);
						
						if($myrow[0]>0)
							{
							 	 $sql = "SELECT stockmaster.description,
									stockmaster.stockid,
									stockmaster.units,
									stockmaster.decimalplaces,
									stockmaster.kgs,
									stockmaster.netweight,
									stockcategory.stockact,
									chartmaster.accountname,
									purchdata.price,
									purchdata.conversionfactor,				
									purchdata.supplierdescription,
									purchdata.suppliersuom,
									purchdata.suppliers_partno,
									purchdata.leadtime
								    FROM stockcategory,
									chartmaster,
									stockmaster LEFT JOIN purchdata
								    ON stockmaster.stockid = purchdata.stockid
								    AND purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
								    WHERE chartmaster.accountcode = stockcategory.stockact
									AND stockcategory.categoryid = stockmaster.categoryid
									AND stockmaster.stockid = '". $ItemCode . "'
									AND purchdata.effectivefrom = 
									(SELECT max(effectivefrom) 
									 FROM purchdata 
									 WHERE purchdata.stockid='". $ItemCode . "'
									 AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "')";
							}
						else 
							{
							 $sql='SELECT stockmaster.description,
									stockmaster.stockid,
									stockmaster.units,
									stockmaster.decimalplaces,
									stockmaster.kgs,
									stockmaster.netweight,
									stockcategory.stockact,
									chartmaster.accountname
								FROM stockcategory,
									chartmaster,
									stockmaster
								WHERE chartmaster.accountcode = stockcategory.stockact
									AND stockcategory.categoryid = stockmaster.categoryid
									AND stockmaster.stockid = "'. $ItemCode . '"';
							}
		
						$ErrMsg = _('The supplier pricing details for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
						$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');
						$result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);
		
						if($myrow = DB_fetch_array($result1))
						{

							foreach($_POST['Rate'] as $key=>$val)
							{
								$vv = new PurchOrder();
								if(is_numeric($_POST['Rate'][$key]))
									{
										   $_SESSION['PO'.$identifier] = $vv->add_to_order($_SESSION['PO'.$identifier]->LinesOnOrder+1,
											$_POST['ProductID'][$key],
											0, /*Serialised */
											0, /*Controlled */
											$_POST['quantity'][$key], /* Qty */
											$_POST['ProductDes'][$key],
											$_POST['Rate'][$key],
											'',
											'',
											$_SESSION['PO'.$identifier]->deliverydate,
											$_POST['Discount'][$key],
											$_POST['NetRate'][$key],
											'',
											$_POST['LeadTime'][$key],
											$_POST['PreIns'][$key],
											$_POST['Specification'][$key],
											$_POST['Quantum'][$key],
											'',
											'',
											'',
											'',
											'',
											'',
											'',
											'',
											'',
											$Quantity*$myrow['price'],
											'',
											$_POST['Discount'][$key],
											$_POST['NetRate'][$key],
											$_POST['LeadTime'][$key],								
											$_POST['PreIns'][$key],
											$_POST['Specification'][$key],
											$_POST['Quantum'][$key]
											);
										//print_r($_SESSION['PO'.$identifier]);	
									}
								else 
									{ 
										$_SESSION['PO'.$identifier]= $vv->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
											$ItemCode,
											0, /*Serialised */
											0, /*Controlled */
											$qty, /* Qty */
											$myrow['description'],
											0,
											$myrow['units'],
											$myrow['stockact'],
											$_SESSION['PO'.$identifier]->deliverydate,
											0,
											0,
											0,
											0,
											0,
											$myrow['accountname'],
											0,
											'',
											'',
											'',
											0,
											0,
											'',
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0,
											0
											);
									}
						  }
				}
		     else 
		      {
					prnMsg (_('The item code') . ' ' . $ItemCode . ' ' . _('does not exist in the database and therefore cannot be added to the order'),'error');
					if ($debug==1)
						{
							echo "<br>".$sql;
						}
					include('includes/footer.inc');
					exit;
			  }
		} 
	  }
	$cti++;
   }
//////First do some validation
 /////Is the delivery information all entered
 /*Start off assuming the best */
	    
 	   //$InputError=0; 
	   /*if($_SESSION['PO'.$identifier]->DelAdd1=='' || strlen($_SESSION['PO'.$identifier]->DelAdd1)<3)
	     {
			prnMsg( _('The purchase order can not be committed to the database because there is no delivery steet address specified'),'error');
			$InputError=1;
	   	 }
	   	 else if(empty($_SESSION['PO'.$identifier]->Location) || $_SESSION['PO'.$identifier]->Location=='')
	   	 {
			prnMsg( _('The purchase order can not be committed to the database because there is no location specified to book any stock items into'),'error');
			$InputError=1;
		 }*/
	/* elseif ($_SESSION['PO'.$identifier]->LinesOnOrder <=0){
		prnMsg( _('The purchase order can not be committed to the database because there are no lines entered on this order'),'error');
		$InputError=1;
	}*/

     //////////////////If all clear then proceed to update the database////////////
	if ($InputError!=1){
		$emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION['PO'.$identifier]->Initiator.'"';
		$emailresult=DB_query($emailsql, $db);
		$emailrow=DB_fetch_array($emailresult);
		$sql = 'BEGIN';
		$result = DB_query($sql,$db);

		if ($_SESSION['ExistingOrder']==0){ /*its a new order to be inserted */
		
		//////////////////////////////////////////////////// Start Purchases Order No With Site code and Current Financial Session ////////////////////////			
			  $sql = "Select PO_Orderno from purchorders where sitecode = '".$_POST['sitecode']."'";
			  $result = DB_query($sql,$db);
	          $numrows = DB_num_rows($result);
			  //echo $numrows;
			  //exit;
			   if($numrows>0)
				 {
					 $i=0;
					 $strmax = "";
					 $myrow=DB_Fetch_array($result);
					// echo $myrow['Reqno'];
					// if($myrow['sitecode'] !='')
					// {
							
							  $val = substr($myrow['PO_Orderno'],0,19);
							  $strchar1 = substr($myrow['PO_Orderno'],0,6);
							  $strchar = $strChar1."/".$_POST['sitecode']."/".$CurrentFinancialYear."/";
							  /*print_r($strchar);
							  exit;*/
							 /*if($val!="")
							 {
								 $arr[$i] = $val;
								 $i++;
							}
					print_r($strchar);exit;*/
					if($numrows>0)
					{ 
						$maxval =  $numrows;
					}
					else
					{
						$maxval=0;
					}
				//}
			//else
			{
			    $strChar = $Prefix_code."/".$_POST['sitecode']."/".$CurrentFinancialYear."/";
			}
	    }
		else
		{
		        $strChar = $Prefix_code."/".$_POST['sitecode']."/".$CurrentFinancialYear."/";
		}
		$strFinal = $maxval+1;
		$strBothFinal = $strChar.str_pad($strFinal,4,"0",STR_PAD_LEFT);
				
	//////////////////////////////////////////////////// End Purchases Purchases Order No  With Site code and Current Financial Session ////////////////////////	
		
			$date = date($_SESSION['DefaultDateFormat']);
			$StatusComment=$date.' - Order Created by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['PO'.$identifier]->Initiator.
			'</a> - '.$_SESSION['PO'.$identifier]->StatusMessage.'<br>';
			$s =  'PO'.$_GET['identifier'];
		    $OrderNo[$s] = GetNextTransNo(18,$db);
		    $port = $_POST['port'];
	        $supptel = $_POST['supptel'];
	        $Contact = $_POST['Contact'];
			$vendor_quotation_no="select vernder_quotation from  venderquotations where id='".$_REQUEST['final_quat']."'";
			$rs=DB_query($vendor_quotation_no,$db);
			$row_vendor_quotation=DB_fetch_array($rs);
 		    	$sql = " Insert INTO purchorders(
					orderno,
					supplierno,
					comments,
					orddate,
					rate,
					initiator,
					requisitionno,
					sitecode,
					site,
					basic_amt,  
					total_tax_amt,  
					sur_oct_perc,  
					sur_oct_amt,
					deladd1,
					deladd2,
					deladd3,
					deladd4,
					deladd5,
					deladd6,
					version1,
					realorderno,
					revised,
					deliveryby,
					status1,
					stat_comment,
					deliverydate,
					payment_terms,
					PO_Orderno,vendor_quotation_no,CompanyId)
				VALUES('',
					'" . $_REQUEST['suppid'] . "',
					'" . $_SESSION['PO'.$identifier]->Comments . "',
					'" . date('Y-m-d') . "',
					'" . $_SESSION['PO'.$identifier]->ExRate . "',
					'" . $_SESSION['PO'.$identifier]->Initiator . "',
					'" . $_POST['requisiton'] . "',
					'" . $_REQUEST['sitecode'] . "',
					'" . $_REQUEST['sitename'] . "',
					'" . $_REQUEST['basic_amt'] . "',
					'" . $_REQUEST['total_tax_amt'] . "',
					'" . $_REQUEST['sur_oct_perc'] . "',
					'" . $_REQUEST['sur_oct_amt'] . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd1 . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd2 . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd3 . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd4 . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd5 . "',
					'" . $_SESSION['PO'.$identifier]->DelAdd6 . "',
					'" . $_SESSION['PO'.$identifier]->version . "',			
					'" . $_SESSION['PO'.$identifier]->OrderNo2 . "',
					'" . FormatDateForSQL($date) . "',
					'" . $_SESSION['PO'.$identifier]->deliveryby . "',	
					'" . 'Pending' . "',
					'" . $StatusComment . "',
					'" . FormatDateForSQL($_SESSION['PO'.$identifier]->deliverydate) . "',
					'" . $_SESSION['PO'.$identifier]->paymentterms1 . "',
					'" . $strBothFinal . "'	,
					'".$row_vendor_quotation['vernder_quotation']."','".$_SESSION['ACGCompanyId']."'
				)";
				
 
// echo "<pre>";
 //print_r($sql); exit;
			$ErrMsg =  _('The purchase order header record could not be inserted into the database because');
			$DbgMsg = _('The SQL statement used to insert the purchase order header record and failed was');
			$result = DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
			$last_id = DB_Last_Insert_ID($db,'purchorders','id');
			
//*********************************************************************************************************			
$update_comprative_detail="update comprative_detail set status_active =1 where comprative_id='".$_SESSION['lastcomprative_id']."'";
 $result_comprative_detail = DB_query($update_comprative_detail,$db);

    $update_venderquotations="update venderquotations set 	status_lock =1 where id='".$_REQUEST['final_quat']."'"; 
	$result_venderquotations = DB_query($update_venderquotations ,$db);
//**********************************************************************************************************			
			//echo "Last ID inserted is ".($last_id);
			if($last_id != '')
			{			
			for($i=1;$i<$_POST['PO_count']; $i++)
			{
			$checksql = "Select count(podetailitem) as totalp from purchorderdetails WHERE orderno='".$last_id."' And itemcode='" . $_POST['ProductID'] . "'";
			$resultchk =DB_query($checksql,$db);
			$chkrow=DB_fetch_array($resultchk);
						
			if($chkrow['totalp']==0)
			{
		 $sql2 = "INSERT INTO purchorderdetails (
							 orderno,
							 itemcode,
							 deliverydate,
							 itemdescription,
							 glcode,
							 shiptref,
							 Rate,
							 quatity,
							 discount_type,
							 Discount,
							 discount_amount,
							 Sub_total,
							 Lead_Time,
							 Pre_Delevery_Ins,
							 Specification,
							 Quantum,
							 Product_Cost_Without_Taxes,
							 Total_Charges_Cost,
							 grand_total_amount,
							 subtotal_amount,
							 quantityrecd,
							 tax_name,
							 Tax_value,
							 Tax_amount,
							 Amount_with_tax,
							 make,
							 color,   
							 grade,
							 uom
							 )
					VALUES ('".$last_id."',
							'" .$_POST['ProductID'][$i]. "',
							'" .FormatDateForSQL($_POST['ReqDelDate'][$i])."',
							'" .$_POST['ProductDes'][$i]."',
							'',
							'',
							'" .  $_POST['Rate'][$i]."',
							'" .  $_POST['quantity'][$i]."',
							'" .  $_POST['discount_type'][$i]."',
							'" .  $_POST['Discount'][$i]. "',
							'" .  $_POST['discount_amount'][$i]. "',
							'" .  $_POST['NetRate'][$i] . "',
							'" .  $_POST['LeadTime'][$i] . "',
							'" .  $_POST['PreIns'][$i] . "',
							'" .  $_POST['Specification'][$i] . "',
							'" .  $_POST['Quantum'][$i] . "',
							'',
							'" .  $_POST['totalcharge'] . "',
							'" .  $_POST['grand_total_amount']. "',
							'" .  $_POST['TWT'] ." ',
							'',
							'" .  $_POST['taxid'][$i] ." ',
							'" .  $_POST['taxvalue'][$i] ." ',
							'" .  $_POST['total_tax_amoun'][$i] ." ',
							'" .  $_POST['total_amount_with_taxes'][$i] ." ',
							'" .  $_POST['make'][$i] ." ',
							'" .  $_POST['color'][$i] ." ',
							'" .  $_POST['grade'][$i] ." ',
							'" .  $_POST['unit'][$i] ." '
							)";
		 					//echo "<pre>";
							//print_r($sql2); exit;
					$ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');
					$DbgMsg =_('The SQL statement used to insert the purchase order detail record and failed was');
					$result =DB_query($sql2,$db,$ErrMsg,$DbgMsg);
					$sql = "update purchorderdetails SET grand_total_amount = '" . $_POST['TWT']. "' where orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";							
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
					}
					else
					{
					$sql= "UPDATE purchorderdetails SET
							 orderno='" . $getoredrdata['orderno'] . "',
							 itemcode='" . $POLine->StockID . "',
							 deliverydate='" . FormatDateForSQL($POLine->ReqDelDate) . "',
							 itemdescription='" . $POLine->ItemDescription . "',
							  quatity1='" . $POLine->GLCode . "',
							   Rate1='" . $POLine->ShiptRef . "',
							 quatity='" . $POLine->Quantity ."',
							 Rate='" . $POLine->Price ."',
							 Discount='" . $POLine->Discount ."',
							 Sub_total='" . $POLine->NetRate ."',
							 Lead_Time='" . $POLine->Lead_Time . "',
							 Pre_Delevery_Ins='" . $POLine->preIns ."',
							 Specification='" . $POLine->Specification."',
							 Quantum='" . $POLine->Quantum ."',
							 Product_Cost_Without_Taxes='" . $POLine->suppliers_partno ."',
							 Total_Charges_Cost='" . $POLine->subtotal_amount ."',
							 grand_total_amount='" . $POLine->package ."',
							 subtotal_amount='" . $POLine->package ."'
							 WHERE podetailitem='".$chkrow['podetailitem']."'";
							 $ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');
					         $DbgMsg =_('The SQL statement used to UPDATE the purchase order detail record and failed was');
							 $result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
					 }
					}
					//echo "hhh".$sql;exit;
				}
				
			} /* end of the loop round the detail line items on the order */
		echo '<p>';
			
			
			
			$vendor_sql="select vendor_name from suppliers where vendor_code='".$_REQUEST['suppid']."'";
			$result = DB_query($vendor_sql ,$db);
			$vendor_row = DB_fetch_array($result);
			
			prnMsg(_('Purchase order') . ' ' . $strBothFinal . ' ' . _('on Vendor - ') . ' ' . 
		     	$vendor_row['vendor_name'] . ' ' . _('has been created'),'success');
			echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/printer.png" title="' . 
				_('Print') . '" alt="">' . ' ' . _('Print Purchase Order') . '';
				
			//	header("Location:".$rootpath."/MR_SelectOSMaterialRequi.php?");
		} else { /*its an existing order need to update the old order info */
	//	 		$_SESSION['PO'.$identifier]->version += 0.01;
			$date = date($_SESSION['DefaultDateFormat']);
		     /*Update the purchase order header with any changes */
			 
			 //site = intostocklocation(old)

	         	$sql = "UPDATE purchorders SET
		     		   supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "' ,
					   comments='" . $_SESSION['PO'.$identifier]->Comments . "',
					   rate=" . $_SESSION['PO'.$identifier]->ExRate . ",
					   initiator='" . $_SESSION['PO'.$identifier]->Initiator . "',
					   requisitionno= '" . $Reqno . "',
					   version1= '" .  $_SESSION['PO'.$identifier]->version . "',
					   deliveryby='" . $_SESSION['PO'.$identifier]->deliveryby . "',					
					   deliverydate='" . FormatDateForSQL($_SESSION['PO'.$identifier]->deliverydate) . "',
					   revised= '" . FormatDateForSQL($date) . "',
					   sitecode = '" . $_REQUEST['sitecode'] . "',
		   			  site='" . $_REQUEST['sitename'] . "',
					  deladd1='" . $_SESSION['PO'.$identifier]->DelAdd1 . "',
					  deladd2='" . $_SESSION['PO'.$identifier]->DelAdd2 . "',
					  deladd3='" . $_SESSION['PO'.$identifier]->DelAdd3 . "',
					  deladd4='" . $_SESSION['PO'.$identifier]->DelAdd4 . "',
					  deladd5='" . $_SESSION['PO'.$identifier]->DelAdd5 . "',
					  deladd6='" . $_SESSION['PO'.$identifier]->DelAdd6 . "',
					  allowprint=" . $_SESSION['PO'.$identifier]->AllowPrintPO . ",
					  payment_terms=" . $_SESSION['PO'.$identifier]->paymentterms . "
		     		  WHERE orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";

			$ErrMsg =  _('The purchase order could not be updated because');
			$DbgMsg = _('The SQL statement used to update the purchase order header record, that failed was');
			$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);		
			
			/*Now Update the purchase order detail records */
			foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) {
				$sql='UPDATE purchorders SET status="'._('Pending').'" WHERE orderno=' . $_SESSION['PO'.$identifier]->OrderNo;
				$result=DB_query($sql,$db);
				if ($POLine->Deleted==true) {
					if ($POLine->PODetailRec!='') {
						 $sql="DELETE FROM purchorderdetails WHERE podetailitem='" . $POLine->PODetailRec . "'";
						
						$ErrMsg =  _('The purchase order could not be deleted because');
						$DbgMsg = _('The SQL statement used to delete the purchase order header record, that failed was');
						$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);
					}
				} else if ($POLine->PODetailRec=='') {

		      	 $sql = "INSERT INTO purchorderdetails (
									orderno,
									itemcode,
									deliverydate,
									itemdescription,
									glcode,
									unitprice,
									quantityord,
									shiptref,
									jobref,
									itemno,
									uom,
									suppliers_partno,
									subtotal_amount,
									package,
									pcunit,
									nw,
									gw,
									cuft,
									total_quantity,
									total_amount
									)
								VALUES ('". $_SESSION['PO'.$identifier]->OrderNo . "',
									'" . $POLine->StockID . "',
									'" . FormatDateForSQL($POLine->ReqDelDate) . "',
									'" . $POLine->ItemDescription . "',
									" . $POLine->GLCode . ",
									" . $POLine->Price . ",
									" . $POLine->Quantity . ",
									'" . $POLine->ShiptRef . "',
									'" . $POLine->JobRef . "',
									'" . $POLine->itemno . "',
									'" . $POLine->uom . "',
									'" . $POLine->suppliers_partno . "',
									'" . $POLine->subtotal_amount . "',
									'" . $POLine->package . "',
									'" . $POLine->pcunit . "',
									'" . $POLine->nw . "',
									'" . $POLine->gw . "',
									'" . $POLine->cuft . "',
									'" . $POLine->total_quantity . "',
									'" . $POLine->total_amount . "'
								)";

				} else {
					if ($POLine->Quantity==$POLine->QtyReceived){
					$sql = "UPDATE purchorderdetails SET
								itemcode='" . $POLine->StockID . "',
								deliverydate ='" . FormatDateForSQL($POLine->ReqDelDate) . "',
								itemdescription='" . $POLine->ItemDescription . "',
								glcode=" . $POLine->GLCode . ",
								unitprice=" . $POLine->Price . ",
								quantityord=" . $POLine->Quantity . ",
								shiptref='" . $POLine->ShiptRef . "',
								jobref='" . $POLine->JobRef . "',
								itemno='" . $POLine->itemno . "',
								uom='" . $POLine->uom . "',
								suppliers_partno='" . $POLine->suppliers_partno . "',
								subtotal_amount='" . $POLine->subtotal_amount . "',
								package='" . $POLine->package . "',
								pcunit='" . $POLine->pcunit . "',
								nw='" . $POLine->nw . "',
								gw='" . $POLine->gw . "',
								cuft='" . $POLine->cuft . "',
								total_quantity='" . $POLine->total_quantity . "',
								total_amount='" . $POLine->total_amount . "',
								completed=1
							    WHERE podetailitem=" . $POLine->PODetailRec;
					} else {
						$sql = "UPDATE purchorderdetails SET
								itemcode='" . $POLine->StockID . "',
								deliverydate ='" . FormatDateForSQL($POLine->ReqDelDate) . "',
								itemdescription='" . $POLine->ItemDescription . "',
								glcode=" . $POLine->GLCode . ",
								unitprice=" . $POLine->Price . ",
								quantityord=" . $POLine->Quantity . ",
								shiptref='" . $POLine->ShiptRef . "',
								jobref='" . $POLine->JobRef . "',
								itemno='" . $POLine->itemno . "',
								uom='" . $POLine->uom . "',
								suppliers_partno='" . $POLine->suppliers_partno . "',
								subtotal_amount='" . $POLine->subtotal_amount . "',
								package='" . $POLine->package . "',
								pcunit='" . $POLine->pcunit . "',
								nw='" . $POLine->nw . "',
								gw='" . $POLine->gw . "',
								cuft='" . $POLine->cuft . "',
								total_quantity='" . $POLine->total_quantity . "',
								total_amount='" . $POLine->total_amount . "'
								WHERE podetailitem=" . $POLine->PODetailRec;
					}
				}

				$ErrMsg = _('One of the purchase order detail records could not be updated because');
				$DbgMsg = _('The SQL statement used to update the purchase order detail record that failed was');
				$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
		     } /* end of the loop round the detail line items on the order */
		     echo '<br><br>';
		     prnMsg(_('Purchase order') . ' ' . $_SESSION['PO'.$identifier]->OrderNo . ' ' . _('has been updated'),'success');
		     if ($_SESSION['PO'.$identifier]->AllowPrintPO==1){
			 //    echo '<br><a target="_blank" href="'.$rootpath.'/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $_SESSION['PO'.$identifier]->OrderNo . '">' . _('Print Purchase Order') . '</a>';
		     }
		} /*end of if its a new order or an existing one */

		$sql = 'COMMIT';
		$Result = DB_query($sql,$db);
		
		// Updating purchase orders taxes 
			
				if(isset($_POST['taxDescName_'])){				
				foreach ($_POST['taxDescName_'] as $k => $v) 
				//for($k=1;$k<$_POST['PO_count']; $k++)
				{	
			 	$chkSql = "select count(*) as `totCount` from purchordertax 
						   where orderno = '".$_SESSION['PO'.$identifier]->OrderNo."' and taxgroupid = ".$v;
				$chkresult =DB_query($chkSql,$db,$ErrMsg,$DbgMsg,true);		
				$chkrow=DB_fetch_array($chkresult);
				if($chkrow['totCount']>0)
				{	
				 $sql = "UPDATE purchordertax SET
							tax = '" . $_POST['tax_qty'][$k]. "' ,
							amount='" . $_POST['tax_percentage_'][$k] . "',
							taxgroupid=" . $_POST['taxDescName_'][$k] . ",
							Product_Cost_With_Taxes='".$_POST['TWT']."'
							WHERE orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."' and taxgroupid = ".$_POST['taxDescName_'][$k];
				}
				else
				{
				  $sql = "insert into purchordertax SET
							tax = '" . $_POST['taxvalue'][$k]. "' ,
							amount='" . $_POST['total_tax_amoun'][$k] . "',
							taxgroupid=" . $_POST['taxid'][$k] . ",
							Product_Cost_With_Taxes='".$_POST['TWT']."',
							orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";
				}
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);	
					
					$sql = "update purchorderdetails SET
							Product_Cost_Without_Taxes = '" . $_POST['TWT']. "',
							subtotal_amount='".$_POST['Total']."'									
							where orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";					
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
			}
		}
		$count = $_POST['count_charges'];
		for($PO=1;$PO<$count; $PO++)
		{
		 $sql = "INSERT into po_charge(id, 
										ch_name, 
										Inclusive, 
										As_Per_Actual, 
										charges, 
										charges_Amount, 
										Orderno 
										) 
										Values('',
										'" . $_POST['chargename'][$PO]."',
										'" . $_POST['incl'][$PO]."',
										'" . $_POST['actual'][$PO]."',
										'" . $_POST['charge_amt'][$PO]."',
										'".  $_POST['charge_perc'][$PO]."', 
										'" . $last_id ."')";
										//echo "<pre>";
										//print_r($sql);
		$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
		}
		
			$sql = "update purchorderdetails SET
							Total_Charges_Cost = '" . $_POST['TotalCharge']. "' 									
							where orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";					
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
			
			
		
		unset($_SESSION['PO'.$identifier]); /*Clear the PO data to allow a newy to be input*/
		
		echo "<br><a href='index.php?route=PO_SelectOSPurchOrder&modid=".$_REQUEST['modid']."&frmid=".$POListFormId."" . SID . "'>" . _('Return To PO List') . '</a>';
		
		include('includes/footer.inc');
		exit;
	}
if(isset($_GET['Delete']))
{
	if($_SESSION['PO'.$identifier]->Some_Already_Received($_POST['LineNo'])==0){
		$_SESSION['PO'.$identifier]->LineItems[$_GET['Delete']]->Deleted=True;
		include ('includes/PO_UnsetFormVbls.php');
	} else {
		prnMsg( _('This item cannot be deleted because some of it has already been received'),'warn');
	}}
if(isset($_POST['LookupPrice']) and isset($_POST['StockID2']))
{
	$sql = "SELECT purchdata.price,
			purchdata.conversionfactor,
			purchdata.supplierdescription
		FROM purchdata
		WHERE  purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
		AND purchdata.stockid = '". strtoupper($_POST['StockID2']) . "'";

	$ErrMsg = _('The supplier pricing details for') . ' ' . strtoupper($_POST['StockID']) . ' ' . _('could not be retrieved because');
	$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');
	$LookupResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

	if (DB_num_rows($LookupResult)==1){
		$myrow = DB_fetch_array($LookupResult);
		$_POST['Price'] = $myrow['price']/$myrow['conversionfactor'];
	} else {
		prnMsg(_('Sorry') . ' ... ' . _('there is no purchasing data set up for this supplier') . '  - ' . $_SESSION['PO'.$identifier]->SupplierID . ' ' . _('and item') . ' ' . strtoupper($_POST['StockID']),'warn');
	}}
if(isset($_POST['UpdateLine']))
{
	$AllowUpdate=true; /*Start assuming the best ... now look for the worst*/

	if ($_POST['Qty']==0 OR $_POST['Price'] < 0){
		$AllowUpdate = false;
		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to set the quantity ordered to zero, or the price is set to an amount less than 0'),'error');
	}

	if ($_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->QtyInv > $_POST['Qty'] OR $_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->QtyReceived > $_POST['Qty']){
		$AllowUpdate = false;
		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to make the quantity ordered a quantity less than has already been invoiced or received this is of course prohibited') . '. ' . _('The quantity received can only be modified by entering a negative receipt and the quantity invoiced can only be reduced by entering a credit note against this item'),'error');
	}

	if ($_SESSION['PO'.$identifier]->GLLink==1) {
	/*Check for existance of GL Code selected */
		$sql = 'SELECT accountname 
				FROM chartmaster 
				WHERE accountcode =' .  $_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->GLCode;
		$ErrMsg = _('The account name for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');
		$DbgMsg = _('The SQL used to retrieve the account details but failed was');
		$GLActResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);
		if (DB_error_no($db)!=0 OR DB_num_rows($GLActResult)==0){
			$AllowUpdate = false;
			prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('The GL account code selected does not exist in the database see the listing of GL Account Codes to ensure a valid account is selected'),'error');
		} else {
			$GLActRow = DB_fetch_row($GLActResult);
			$GLAccountName = $GLActRow[0];
		}
	}

	include ('PO_Chk_ShiptRef_JobRef.php');

	if (!isset($_POST['JobRef'])) {
		$_POST['JobRef']='';
	}

	if ($AllowUpdate == true) {

		$_SESSION['PO'.$identifier]->update_order_item(
					$_POST['LineNo'],
					$_POST['Qty'],
					$_POST['Price'],
					$_POST['ItemDescription'],
					$_POST['GLCode'],
					$GLAccountName,
					$_POST['ReqDelDate'],
					$_POST['ShiptRef'],
					$_POST['JobRef'],
					$_POST['itemno'],
					$_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->uom,
					$_POST['suppliers_partno'],
					$_POST['Qty']*$_POST['Price'],
					$_POST['package'],
					$_POST['pcunit'],
					$_POST['nw'],
					$_POST['gw'],
					$_POST['cuft'],
					$_POST['Qty'],
					$_POST['Qty']*$_POST['Price']
					);

		include ('includes/PO_UnsetFormVbls.php');
	}}
if(isset($_POST['EnterLine']))
{ /*Inputs from the form directly without selecting a stock item from the search */

	$AllowUpdate = true; /*always assume the best */

	if (!is_numeric($_POST['Qty'])){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the order item must be numeric'),'error');
	}
	if ($_POST['Qty']<0){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the ordered item entered must be a positive amount'),'error');
	}
	if (!is_numeric($_POST['Price'])){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The price entered must be numeric'),'error');
	}
	if (!is_date($_POST['ReqDelDate'])){
// mark on 081013
		$AllowUpdate = False;
		prnMsg( _('Cannot Enter this order line') . '</b><br>' . _('The date entered must be in the format') . ' ' . $_SESSION['DefaultDateFormat'], 'error');
	}

//	include ('PO_Chk_ShiptRef_JobRef.php');

 /*Then its not a stock item */

		/*need to check GL Code is valid if GLLink is active */
		if ($_SESSION['PO'.$identifier]->GLLink==1){

			$sql = 'SELECT accountname 
					FROM chartmaster 
					WHERE accountcode =' . (int) $_POST['GLCode'];
			$ErrMsg =  _('The account details for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');
			$DbgMsg =  _('The SQL used to retrieve the details of the account, but failed was');
			$GLValidResult = DB_query($sql,$db,$ErrMsg,$DbgMsg,false,false);
			if (DB_error_no($db) !=0) {
				$AllowUpdate = false;
				prnMsg( _('The validation process for the GL Code entered could not be executed because') . ' ' . DB_error_msg($db), 'error');
				if ($debug==1){
					prnMsg (_('The SQL used to validate the code entered was') . ' ' . $sql,'error');
				}
				include('includes/footer.inc');
				exit;
			}
			if (DB_num_rows($GLValidResult) == 0) { /*The GLCode entered does not exist */
				$AllowUpdate = false;
				prnMsg( _('Cannot enter this order line') . ':<br>' . _('The general ledger code') . ' - ' . $_POST['GLCode'] . ' ' . _('is not a general ledger code that is defined in the chart of accounts') . ' . ' . _('Please use a code that is already defined') . '. ' . _('See the Chart list from the link below'),'error');
			} else {
				$myrow = DB_fetch_row($GLValidResult);
				$GLAccountName = $myrow[0];
			}
		} /* dont bother checking the GL Code if there is no GL code to check ie not linked to GL */
		else {
			$_POST['GLCode']=0;
		}
		if (strlen($_POST['ItemDescription'])<=3){
			$AllowUpdate = false;
			prnMsg(_('Cannot enter this order line') . ':<br>' . _('The description of the item being purchase is required where a non-stock item is being ordered'),'warn');
		}

		if ($AllowUpdate == true){
		  $_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
						'',
						0, /*Serialised */
						0, /*Controlled */
						$_POST['Qty'],
						$_POST['ItemDescription'],
						$_POST['Price'],
						_('each'),
						$_POST['GLCode'],
						$_POST['ReqDelDate'],
						$_POST['ShiptRef'],
						$_POST['JobRef'],
						0,
						0,
						$GLAccountName,
						2,
						$_POST['itemno'],						
						$_POST['uom'],
						$_POST['suppliers_partno'],
						$_POST['subtotal_amount'],
						$_POST['package'],
						$_POST['pcunit'],
						$_POST['nw'],
						$_POST['gw'],
						$_POST['cuft'],
						$_POST['total_quantity'],
						$_POST['total_amount']
						);
		   include ('includes/PO_UnsetFormVbls.php');
		}
	}
	
echo "<form name=form1 action='index.php?route=PO_Items&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."&identifier=".$identifier. "&suppid=".$supplier. "&final_quat=".$final_qtation. "' method=post>";

if (isset($_POST['NonStockOrder']))
{
	echo '<br><table><tr><td>'._('Description of Item').'</td>';
	echo '<td><input type=text name=ItemDescription size=40></td></tr>';
	echo '<tr><td>'._('General Ledger Code').'</td>';
	echo '<td><select name="GLCode">';
	$sql='SELECT 
			accountcode, 
			accountname 
		  FROM chartmaster 
		  ORDER BY accountcode ASC';
	$result=DB_query($sql, $db);
	while ($myrow=DB_fetch_array($result)) {
		echo '<option value="'.$myrow['accountcode'].'">'.$myrow['accountcode'].' - '.$myrow['accountname'].'</option>';
	}
	echo '</td></tr>';
	echo '<tr><td>'._('Quantity to purchase').'</td>';
	echo '<td><input type=text class=number name=Qty size=10></td></tr>';
	echo '<tr><td>'._('Price per item').'</td>';
	echo '<td><input type=text class=number name=Price size=10></td></tr>';
	echo '<tr><td>'._('Delivery Date').'</td>';
	echo '<td><input type=text class=date alt="'.$_SESSION['DefaultDateFormat'].'" name=ReqDelDate size=11
			value="'.$_SESSION['PO'.$identifier]->deliverydate .'"></td></tr>';
	echo '</table>';
	echo '<input type=submit name="EnterLine" value="Enter Item">';}
	
if(!isset($_GET['Edit']) || isset($_GET['suppid']) && isset($_GET['final_quat']) && isset($_GET['sitecode']) && isset($_GET['sitename']))
{?>
<br>
<h3 align="center"><strong>ORDER SUMMARY</strong></h3>
<br/><br/>
<br/>
<?php         
$sql2="SELECT * FROM vendorquotationdetails WHERE vendorquotationdetails.quotation_no='". $final_qtation ."'"; 
$result2=DB_query($sql2, $db);
$myrow2=DB_fetch_array($result2);
$requisition=$myrow2['pr_no']; ?>
<fieldset><legend><strong><h3>Item Details</h3></strong></legend>
<div align="center">
<div style="overflow:auto; width:800px; height:200px"> 
  <table width="100%" border="0" cellpadding="5">
    <tr>
      <th><strong>Item Code</strong></th>
      <th><strong>Item Description</strong></th>
       <th><strong>Unit</strong></th>
	  <th><strong>Flexo/Offset</strong></th>
 	   <th><strong>Quantity</strong></th>
      <th><strong>Rate</strong></th>
      <th><strong>Discount Type</strong></th>
      <th><strong>Discount</strong></th>
      <th><strong>Discount Amount</strong></th>
      <th><strong>SubTotal</strong></th>
      <!--<th><strong>Tax Name</strong></th>
      <th><strong>Tax Value</strong></th>
      <th><strong>Total Tax Amount</strong></th>
      <th><strong>Total Amount With Taxes</strong></th>-->
    </tr>
      <?php 				
$vend_sql="SELECT * FROM venderquotations WHERE id='".$final_qtation."'";
$result_vend=DB_query($vend_sql,$db);
$myrowvender=DB_fetch_array($result_vend);
  
$totalcharges = $myrowvender['totalcharge'];
$grandtotal   = $myrowvender['grand_total']; 
$totalamount  = $myrowvender['total_amt'];
$taxnameid    = $myrowvender['taxnameid'];

 $sql="SELECT * FROM vendorquotationdetails WHERE quotation_no='".$final_qtation."'";
$result=DB_query($sql,$db);
$i=1;
while($myrow=DB_fetch_array($result))
{
//echo "<pre>";
//print_r($myrow);
if($i%2==0)
{$bg="#CCCCCC";}
else
$bg="#C8BECB";
?>
    <tr bgcolor="<?php echo $bg;?>">
      <td><?php echo $myrow['prod_id'];?>
          <input type="hidden" name="ProductID[<?php echo $i;?>]" size="10" value="<?php echo $myrow['prod_id'];?>" readonly />
      </td>
      <td><?php echo $myrow['prod_dec'];?>
          <input type="hidden" name="ProductDes[<?php echo $i;?>]" size="45" value="<?php echo $myrow['prod_dec'];?>" readonly /></td>
      
      <td><?php 
	  $unitname=$s->getField('unitsofmeasure','unitid',$myrow['uom'],'unitname');
	  echo $unitname;?>
          <input type="hidden" name="unit[<?php echo $i;?>]" size="45" value="<?php echo $myrow['uom'];?>" readonly /> </td>

      <td>
		  <?php $query_item=DB_query("select * from item_master where StockID='".$myrow['prod_id']."'", $db);
		  	$item_row=DB_fetch_array($query_item);
		   ?>
	
	  	<?php echo $item_row['fexo_offset'];?> </td>
      <td><input type="hidden" name="quantity[<?php echo $i;?>]" size="5" value="<?php echo $myrow['quantity'];?>" id="Quantity_<?php echo $i;?>" readonly />
          <?php echo $myrow['quantity'];?></td>
      <td><?php echo $myrow['rate'];?>
          <input type="hidden" name="Rate[<?php echo $i;?>]" id="Rate_<?php echo $i;?>" value="<?php echo $myrow['rate'];?>" size="4" readonly/>
      </td>
      <td><?php 
	  if($myrow['discount']=='0')
	  echo "N/A";
	  else
	  echo $myrow['discount_type'];?>
          <input type="hidden" name="discount_type[<?php echo $i;?>]" id="discount_type_<?php echo $i;?>" value="<?php echo $myrow['discount_type'];?>" readonly/>
      </td>
      <td><?php 	   
if($myrow['discount_type']=="PercentAmt")
{?>
      <?php echo $myrow['discount'];?>%
          <input type="hidden" name="Discount[<?php echo $i;?>]" id="Discount_<?php echo $i;?>" value="<?php echo $myrow['discount'];?>" onblur="DiscountAmount(this.value,<?php echo $i;?>)" size="8" readonly />
      <?php 	 }
else 
{?>
      <?php echo $myrow['discount'];?>
          <input type="hidden" name="Discount[<?php echo $i;?>]" id="Discount_<?php echo $i;?>" value="<?php echo $myrow['discount'];?>" onblur="DiscountAmount(this.value,<?php echo $i;?>)" size="8" readonly />
      <?php } ?></td>
      <td><?php echo $myrow['discount_amount'];?>
          <input type="hidden" id="discount_amount_<?php echo $i;?>" name="discount_amount[<?php echo $i;?>]" value="<?php echo $myrow['discount_amount'];?>" readonly/></td>
      <td><?php echo $myrow['sub_total'];?>
          <input type="hidden" id="NetRate_<?php echo $i;?>" name="NetRate[<?php echo $i;?>]" value="<?php echo $myrow['sub_total'];?>" size="8" readonly/></td>
      
	  <?php 	  
//$tax_sql = "Select tax_code from sales_tax_master where salestax_id='".$myrow['taxnameid']."'";
//$tax_res = DB_query($tax_sql,$db);
//$tax_row = DB_fetch_array($tax_res);
?>
      <!--<td><?php //echo $tax_row['tax_code'];?>
          <input type="hidden" name="taxid[<?php //echo $i;?>]" id="taxid_<?php //echo $i;?>" value="<?php //echo $myrow['taxnameid'];?>" /></td>
      <td><?php //echo $myrow['taxvalue'];?>
          <input type="hidden" name="taxvalue[<?php //echo $i;?>]" value="<?php //echo $myrow['taxvalue'];?>" size="8" readonly /></td>
      <td><?php //echo $myrow['taxamount'];?>
          <input type="hidden" name="total_tax_amoun[<?php //echo $i;?>]" value="<?php //echo $myrow['taxamount'];?>" size="8" readonly /></td>
      <td><?php //echo $myrow['totalamountwithtax'];?>
          <input type="hidden" name="total_amount_with_taxes[<?php //echo $i;?>]" value="<?php //echo $myrow['totalamountwithtax'];?>" size="8" readonly /></td>-->

      <?php 
$i++;
}?>
      <input type="hidden" name="PO_count" value="<?php echo $i;?>" />
    </tr>
  </table>
  </div></div></fieldset>
<br/>

<table width="35%" border="0">
<tr>
<td bgcolor="#FFFFFF">
<table width="100%" cellpadding="1" cellspacing="1" border="0">
  <tr>
    <th><strong>Basic Amount</strong></th>
    <td><?php echo $myrowvender['basic_amt'];?>
  <input type="hidden" name="basic_amt" id="basic_amt" value="<?php echo $myrow['basic_amt'];?>" /></td></tr>
  <tr>
    <th><strong>Excise Duty </strong></th>
    <td nowrap="nowrap">
    	    <select name="exciseDuty" id="exciseDuty" style="width:48%;" onchange="claculateExcise(this.value)">
    	    <?php 
    	    $excise_sql=DB_query("Select * from excise_tax where id='".$myrowvender['Excise_Duty']."'",$db);
			while($excise_row=DB_fetch_array($excise_sql))
			{?>
				<option value="<?php echo $excise_row['id'];?>"><?php echo $excise_row['caption'];?></option>
			<?php 	
			}
    	    ?> 
  	      </select><div id="exciseId"><input name="exciseValue" id="exciseValue" type="text" value="<?php echo $myrowvender['Excise_Duty_value'];?>" size="25" style="width:48%;" /></div>
    	   </td></td>
  </tr>
  <tr>
    <th><strong>Edu Cess </strong></th>
    <td><input name="rate3" type="text" value="<?php echo $myrowvender['Edu_Cess_perc'];?>" size="3" />
      % = 
      <?php echo $myrowvender['Edu_Cess'];?>
        <input type="hidden" name="edu_cess" id="edu_cess" value="<?php echo $myrowvender['Edu_Cess'];?>" /></td>
  </tr>
  <tr>
    <th><strong>SHE Cess </strong></th>
    <td><input name="rate" type="text" value="<?php echo $myrowvender['SHE_Cess_perc'];?>" size="3" readonly="true"/>
      % = <?php echo $myrowvender['SHE_Cess'];?>
        <input type="hidden" name="she_cess" id="she_cess" value="<?php echo $myrowvender['SHE_Cess'];?>" /></td>
  </tr>
  <tr>                      
    <th><strong>Taxable Amount </strong></th>
    <td><?php echo $myrowvender['taxable_amt'];?>
        <input type="hidden" name="taxable" id="taxable" value="<?php echo $myrowvender['taxable_amt'];?>" /></td>
  </tr>
  <tr>
    <th><strong>VAT/CST</strong></th>
    <td><?php 
	$tax_sql=DB_query("Select tax_code from sales_tax_master where salestax_id='".$myrowvender['taxname']."'",$db);
	$tax_row=DB_fetch_array($tax_sql);
	echo $tax_row['tax_code']
	;?>
        <input type="hidden" name="taxid" id="taxid" value="<?php echo $myrowvender['taxname'];?>" /></td>
  </tr>
  <tr>
  <th><strong>VAT/CST Amount</strong></th>
	<td><?php echo $myrowvender['taxvalue'];?> 
      <input type="hidden" name="tax_rate" id="tax_rate" value="<?php echo $myrowvender['taxvalue'];?>" /></td>
  </tr>
  <tr>
  <th><strong>Surcharge %</strong></th>
	<td><?php echo $myrowvender['sur_oct_perc'];?> %
      <input type="hidden" name="sur_oct_perc" id="sur_oct_perc" value="<?php echo $myrowvender['sur_oct_perc'];?>" /></td>
  </tr>
  <tr>
  <th><strong>Surcharge Amount </strong></th>
	<td><?php echo $myrowvender['sur_oct_amt'];?>
	  <input type="hidden" name="sur_oct_amt" id="sur_oct_amt" value="<?php echo $myrowvender['sur_oct_amt'];?>" /></td>
  </tr>
  <tr>
  <th><strong>Freight</strong></th>
	<td><?php echo $myrowvender['totalcharge'];?>
	  <input type="hidden" name="totalcharge" id="totalcharge" value="<?php echo $myrowvender['totalcharge'];?>" /></td>
  </tr>
  
  <tr>
    	    <th>Pkg Charges</th>
    	    <td><?php echo $myrowvender['pkg_charges'];?><input name="pkg_charges" id="packagingCharges" type="hidden" value="<?php echo $myrowvender['pkg_charges'];?>" size="25" style="width:98%;" /></td>
    	    
  	    </tr>
  	    <tr>
    	    <th>Additional Charges</th>
    	    <td><?php echo $myrowvender['add_charges'];?><input name="add_charges" id="additionalCharges" type="hidden" value="<?php echo $myrowvender['add_charges'];?>" size="25" style="width:98%;" /></td>
    	    
  	    </tr>
    	  <tr>
    	    <th>Round Off</th>
    	    <td><?php echo $myrowvender['roundOff'];?><input name="roundOff" type="hidden" value="<?php echo $myrowvender['roundOff'];?>" size="25" style="width:98%;" /></td>
    	    
  	    </tr>
  
  <tr>
  <th><strong>Grand Total</strong></th>
	<td><?php echo $myrowvender['grand_total'];?>
	  <input type="hidden" name="grand_total_amount" id="grand_total_amount" value="<?php echo $myrowvender['grand_total'];?>" /></td>
  </tr>
</table>
</td>
</tr>
</table>
<div class="centre">
<input type="hidden" name="sitecode" value="<?php echo $_GET['sitecode'];?>">
<input type="hidden" name="sitename" value="<?php echo $_GET['sitename'];?>">		
<input type="hidden" name="requisiton" size="30" value="<?php echo $Reqno;?>">
<input type="submit" name="Commit" value="Process Order"><?php }
echo '</form>';
?>
<?php 
include('includes/footer.inc');
?>
<script type="text/javascript">
var TotalPercent=0;
var TotalAmount=0;
var finalAmount=0;
function ChargeCalculater(Amt,Amtid)
  {
     var AsPerActual=document.getElementById(Amtid).value;
	 var ActualType=document.getElementById("AsPerActual_"+Amtid).value;
	 if(document.getElementById(Amtid).value !='')
	 {
	 if(ActualType=='PercentAmt')
	   {
	     var Total= document.getElementById("Total").value;
		 var charge= parseFloat(Total) * parseFloat(AsPerActual)/100;
		 TotalPercent= parseFloat(TotalPercent) + parseFloat(charge);
		 document.getElementById("actual_"+Amtid).value= charge;
	   }
	 else
	   {
	     document.getElementById("actual_"+Amtid).value=AsPerActual; 
		 TotalAmount=parseFloat(TotalAmount) + parseFloat(AsPerActual);
	   }
	    finalAmount= parseFloat(TotalAmount) + parseFloat(TotalPercent);
		//alert(finalAmount);
		//document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		
		if(isNaN(finalAmount))
		{
			 var TotalCharge =document.getElementById("TotalCharge").value;
			 var AsPerActual=document.getElementById(Amtid).value;
			
			if(AsPerActual !='')
			{	
			 var finalAmountTotal2= parseFloat(AsPerActual) + parseFloat(TotalCharge);
			  document.getElementById("TotalCharge").value=finalAmountTotal2;
			}
			else
			{
			   document.getElementById("TotalCharge").value=TotalCharge;
			}
		}
		else
		{
		  document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		}
		
	}
		
	return true;
  }

function FinalGrandTotal(A)
   {
      var GTWC=document.getElementById("TWT").value;
	  var FinalGT= parseFloat(GTWC) + parseFloat(A);
		if(isNaN(FinalGT))
		{
		  document.getElementById("GrandTotal").value=parseFloat(0);
		}
		else
		{
		  document.getElementById("GrandTotal").value=parseFloat(FinalGT);
		 }
		  
   }
function ChargeAmount(CA,ID)
 {
   if (CA=='YES')
     {
	   //alert(CA);
	   document.getElementById(ID).readOnly=true;
	   document.getElementById("actual_"+ID).disabled=true;
	   document.getElementById("AsPerActual_"+ID).disabled=true;
	 }
	else if (CA!='YES')
	 {
	    document.getElementById(ID).readOnly=false;
	    document.getElementById("AsPerActual_"+ID).disabled=false; 
		document.getElementById("actual_"+ID).disabled=false;
	 }    
  // alert(ID);
 }
var Total=0;
function DiscountAmount(DA,i)
{
	var discount_percent = document.getElementById("PerAmo_"+i).value;
	var rate = document.getElementById("Rate_"+i).value;
	var discount = document.getElementById("Discount_"+i).value;
	var quantity = document.getElementById("Quantity_"+i).value;
	var totalPrice = quantity*rate;
	if(discount_percent=='PercentAmt')
	{
		var percent = totalPrice * discount/100;
		var subTotal = totalPrice - percent;
	}
	else if(discount_percent=='Amount')
	{
		var percent = discount;
		var subTotal = totalPrice-percent;
	}
	document.getElementById("NetRate_"+i).value = subTotal;
	Total=parseFloat(Total) + parseFloat(subTotal);
	document.getElementById("Total").value=Total;
	return true;
}	

//alert(Total);
var GrandTax=0;
var GrandTotal=0;	
function TaxAmount(Tax,Name)
  {
    
	var Total=document.getElementById("Total").value;
	document.getElementById("tax_"+Name).value = Total*Tax/100;
	GrandTax=GrandTax + Total*Tax/100;
    GrandTotal = parseFloat(Total) + parseFloat(GrandTax);
	document.getElementById("TWT").value=GrandTotal;
	//alert(GrandTotal);
  }

function fillUpValueFromVendor(v){
var v = v;
return true;
//var url = "<--?php echo $rootpath;?>/VenderQutations.php?RequisitionNo=<--?php echo $_REQUEST['RequisitionNo']; ?>&vendorresult=1&vendor="+v;
// alert(url);
//location.replace(url);
}
</script>