<?php
header("Content-type: text/html; charset=utf-8");

session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}


include("config.inc.php");
include("Functions_Sales.php");

set_time_limit(0);

$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 Login Table
$querylog=" select ifNull(Unmodify_sellingprice,0) As Unmodify_SellingPrice, ifNull(FC_CashRegisterQtyRet,0) As FC_CashRegisterQtyRet, ".
          " ifNull(FC_CashRegisterDisc,0) As FC_CashRegisterDisc, ifNull(FC_DiscountPerLimit,0) As FC_DiscountPerLimit ".
          " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' ".
		  " and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
//echo $querylog;

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1 as Base1Curr, base2 as Base2Curr, grid_color1, grid_color2, ifNull(ShowSlipNumber,0) As ShowSlipNumber, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage,ifnull(cashreg_colortheme,'default') as cashreg_colortheme 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 ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
             " ifNull(Module_Delivery,0) As Module_Delivery From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}



//Read From CashRegister Table
$queryCashRegister=" Select Upper(CashRegister_Name) As CashRegister_Name, Currency_Code As StpCurrCode, CostCenter_Code As StpCostCentCode, Project_Code As StpProjectCode, ".
                   " CashRegister_SerialNo, CashRegister_Discount, CashRegisterTTC, Client_Account As StpClientAccount, Warehouse_Code As StpWarehouseCode, ifNull(CashReg_Vendor,0) As CashReg_Vendor,  ".
				   " ifNull(CashReg_ForcingVendor,0) As CashReg_ForcingVendor, EditItemPriceUp, EditItemPriceDown ".
				   " From CashRegister ".
				   " Where CashRegister_Name = '".$_SESSION['cashregister']."' ";
$resultCashRegister=mysql_query($queryCashRegister,$connection) or die(mysql_error());
while($rowCashRegister=mysql_fetch_array($resultCashRegister)){
	extract($rowCashRegister);
}

//Warehouse List
$querywarehouse=" select distinct warehouse.warehouse_code, warehouse_name ".
				" from warehouse where warehouse_code in (select warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."') ".
				" order by warehouse.warehouse_code";
$resultwh = mysql_query($querywarehouse,$connection) or die(mysql_error());
$whexist   = mysql_num_rows($resultwh);
if ($whexist == 0)
	$querywarehouse="select warehouse_code,warehouse_name from warehouse order by warehouse_code";
	
$resultwarehouse=mysql_query($querywarehouse,$connection) or die(mysql_error());



$mainaction = $_GET["mainaction"]; if ($mainaction == ""){$mainaction = $_POST["mainaction"];}   
$actionmode = $_GET["actionmode"]; if ($actionmode == ""){$actionmode = $_POST["actionmode"];}   
$message 	= $_GET["message"]; if ($message == ""){$message = $_POST["message"];}   
$passchecked = $_GET["passchecked"]; if ($passchecked == ""){$passchecked = $_POST["passchecked"];}   
$string 	 = $_GET["string"]; if ($string == ""){$string = $_POST["string"];}   

$PRetId 	= $_GET["PRetId"]; if ($PRetId == ""){$PRetId = $_POST["PRetId"];}   
$PRetDtId 	= $_GET["PRetDtId"]; if ($PRetDtId == ""){$PRetDtId = $_POST["PRetDtId"];}   
$PRetDate 	= $_GET["PRetDate"]; if ($PRetDate == ""){$PRetDate = $_POST["PRetDate"];}   
$PRetCurr 	= $_GET["PRetCurr"]; if ($PRetCurr == ""){$PRetCurr = $_POST["PRetCurr"];}   
$PRetCashRegister 	= $_GET["PRetCashRegister"]; if ($PRetCashRegister == ""){$PRetCashRegister = $_POST["PRetCashRegister"];}   
$PRetClientCode 	= $_GET["PRetClientCode"]; if ($PRetClientCode == ""){$PRetClientCode = $_POST["PRetClientCode"];}   
$PRetProjectCode 	= $_GET["PRetProjectCode"]; if ($PRetProjectCode == ""){$PRetProjectCode = $_POST["PRetProjectCode"];}   
$PRetCostCentCode 	= $_GET["PRetCostCentCode"]; if ($PRetCostCentCode == ""){$PRetCostCentCode = $_POST["PRetCostCentCode"];}   

$txtRetDtId 	  = $_POST["txtRetDtId"]; if ($txtRetDtId == ""){$txtRetDtId = $_GET["txtRetDtId"];}   
$txtItemCode   	  = $_POST["txtItemCode"]; if ($txtItemCode == ""){$txtItemCode = $_GET["txtItemCode"];}   
$txtItemBarcode   = $_POST["txtItemBarcode"]; if ($txtItemBarcode == ""){$txtItemBarcode = $_GET["txtItemBarcode"];}   
$txtItemDesc   	  = $_POST["txtItemDesc"]; if ($txtItemDesc == ""){$txtItemDesc = $_GET["txtItemDesc"];}   
$txtWarehouseCode = $_POST["txtWarehouseCode"]; if ($txtWarehouseCode == ""){$txtWarehouseCode = $_GET["txtWarehouseCode"];}   
$txtPOQty   	  = $_POST["txtPOQty"]; if ($txtPOQty == ""){$txtPOQty = $_GET["txtPOQty"];}   
$txtExistingQty   = $_POST["txtExistingQty"]; if ($txtExistingQty == ""){$txtExistingQty = $_GET["txtExistingQty"];}   
$txtAvailableQty  = $_POST["txtAvailableQty"]; if ($txtAvailableQty == ""){$txtAvailableQty = $_GET["txtAvailableQty"];}   
$txtRetDtVendor   = $_POST["txtRetDtVendor"]; if ($txtRetDtVendor == ""){$txtRetDtVendor = $_GET["txtRetDtVendor"];}   
$txtRetDtSlip     = $_POST["txtRetDtSlip"]; if ($txtRetDtSlip == ""){$txtRetDtSlip = $_GET["txtRetDtSlip"];}   
$txtRetDtPrice    = $_POST["txtRetDtPrice"]; if ($txtRetDtPrice == ""){$txtRetDtPrice = $_GET["txtRetDtPrice"];}   
$txtRetDtPriceTTC = $_POST["txtRetDtPriceTTC"]; if ($txtRetDtPriceTTC == ""){$txtRetDtPriceTTC = $_GET["txtRetDtPriceTTC"];} 
$txtRetDtDiscount = $_POST["txtRetDtDiscount"]; if ($txtRetDtDiscount == ""){$txtRetDtDiscount = $_GET["txtRetDtDiscount"];} 
$txtRetDtTotal    = $_POST["txtRetDtTotal"]; if ($txtRetDtTotal == ""){$txtRetDtTotal = $_GET["txtRetDtTotal"];} 

$discount_user = $_GET["discount_user"]; if ($discount_user == ""){$discount_user = $_POST["discount_user"];}   
 
if($_SESSION['discount_userX'] != ''){
	$querylog=" select ifNull(FC_CashRegisterDisc,0) As FC_CashRegisterDisc, ifNull(FC_DiscountPerLimit,0) As FC_DiscountPerLimit ".
			  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['discount_userX']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
	$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlog)){
		extract($rows);
	}
	$_SESSION['discount_userX']='';
}

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

HERE;

if($cashreg_colortheme=='red'){
	echo'<link rel="stylesheet" type="text/css" media="all" href="css-v2/style-red.css">';
	echo'<link rel="stylesheet" type="text/css" href="js/menu-v2/menu-red.css" />';
}	
else if($cashreg_colortheme=='' || $cashreg_colortheme=='default')	{
	echo'<link rel="stylesheet" type="text/css" media="all" href="css-v2/style-default.css">';
	echo'<link rel="stylesheet" type="text/css" href="js/menu-v2/menu-default.css" />';
}


print <<<HERE

<script type="text/javascript" language="javascript">


function SubmitRecord(DiscountPerLimit,CashRegForcingVendor) {
	x = document.retaildt;
	
	var result = CheckFields(DiscountPerLimit,CashRegForcingVendor);
	var RetId    = x.PRetId.value;
	var RetDtId  = x.txtRetDtId.value;
	var vMainMode = x.mainaction.value;
	var vMode= x.actionmode.value;
	
	if (RetDtId == '')
		vMode = 'submitrecord';	
	else
		vMode = 'editdt';	
	   
	if (result == 1) {
		x.action="Form_Retail_Actions.php?mode="+vMode+"&mainmode="+vMainMode+"&SRetId="+RetId+"&SRetDtId="+RetDtId;
		x.submit();
		
	}	
}

function ChangeLocation() {
	x = document.retaildt;
	var vMode = x.actionmode.value;
	
	if (vMode == 'submitrecord') {
		
		opener.document.retail.actionmode.value = x.actionmode.value;
		opener.document.retail.mainaction.value = x.mainaction.value;
		//opener.document.retail.message.value = x.message.value;
		opener.document.retail.txtId.value = x.PRetId.value;
		opener.document.retail.string.value = x.string.value;

		//To Check later if the window is opened
		opener.document.retail.openwin.value = 1;

		opener.document.retail.submit();
		
		self.focus();
	} 
	else if (vMode == 'submitrecord' || vMode == 'editdt') {
		opener.document.retail.actionmode.value = x.actionmode.value;
		opener.document.retail.mainaction.value = x.mainaction.value;
		opener.document.retail.txtId.value = x.PRetId.value;
		opener.document.retail.message.value = x.message.value;
		opener.document.retail.string.value = x.string.value;
		opener.document.retail.submit();
		
		self.close();
	
	}
	
	if (document.getElementById('txtItemBarcode').type == 'text') {
		if (x.txtItemBarcode.value == '')
			x.txtItemBarcode.focus();
		else 
			if (document.getElementById('txtRetDtVendor').type == 'text') 
				x.txtRetDtVendor.focus();
	}	
}



function CheckFields(DiscountPerLimit,CashRegForcingVendor){
  
    x = document.retaildt;
	
	var RetDtItem          = x.txtItemCode.value;
	var RetDtItemBarcode   = x.txtItemBarcode.value;
	var RetDtWarehouseCode = x.txtWarehouseCode.value;
	var RetDtQty           = x.txtRetDtQty.value;
	var RetDtPrice         = x.txtRetDtPrice.value;
	var RetDtDiscount 	   = x.txtRetDtDiscount.value;
	var RetDtVendorCode    = x.txtRetDtVendor.value;
	
	
	var vModuleQtyReturn  = x.ModuleQtyReturn.value;
	var vPassChecked      = x.passchecked.value;
	
	var vmode = x.actionmode.value;
	
	if (RetDtPrice == '')    RetDtPrice = 0;
	if (RetDtDiscount == '') RetDtDiscount = 0;
	
	RetDtDiscount    = parseFloat(RetDtDiscount);
	DiscountPerLimit = parseFloat(DiscountPerLimit);
		
	if (RetDtItem=='' && RetDtItemBarcode=='')
	{
		alert("Item is mandatory!");
		x.txtItemBarcode.focus();
		return 0;
	}
	else if (RetDtQty < 0 && vModuleQtyReturn==0 && vPassChecked==0)
	{
		
		win = window.open('Form_Retail_Password.php?actionmode=returnitem1',
						  'Form_Retail_Password', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=400,height=200,left=200,top=100');		
		win.creator = self;
		win.focus();
		
		x.passchecked.value = '';
		
		return 0;
	}
	else if (RetDtWarehouseCode=='')
	{
		alert("Warehouse is mandatory!");
		x.txtWarehouseCode.focus();
		return 0;
	}
	else if ((RetDtPrice*1 != RetDtPrice/1 ) || RetDtPrice < 0) {
		alert('Price should be a POSITIVE and NUMERIC value. ');
		x.txtItemPrice.focus();
		return 0;
	}
	else if (RetDtDiscount > 0 && DiscountPerLimit >= 0 && RetDtDiscount > DiscountPerLimit) {
		alert('Discount should be less than or equal to allowed limit ('+DiscountPerLimit+')');
		x.txtRetDtDiscount.focus();
		return 0;
	}
	else if (CashRegForcingVendor == 1 && RetDtVendorCode == '') {
		alert("Vendor is mandatory!");
		x.txtRetDtVendor.focus();
		return 0;
	} 
		
	
	else
	return 1 ;	
}






//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.retaildt;
	var vmode = x.actionmode.value;
	
	if (Option == 'D')
	{
		x.txtRetDtId.value='';
		x.txtItemBarcode.value='';
		x.txtItemCode.value='';
		x.txtItemDesc.value='';
		x.txtWarehouseCode.value='';
		x.txtRetDtQty.value='';
		x.txtPOQty.value='';
		x.txtAvailableQty.value='';
		x.txtExistingQty.value='';
		x.txtRetDtPrice.value='';
		x.txtRetDtPriceTTC.value='';
		x.txtRetDtDiscount.value='';
		x.txtRetDtTotal.value='';
		x.txtRetDtSlip.value='';
		x.txtRetDtVendor.value='';
		
		x.message.value='';
		x.actionmode.value = '';
	
	}

}


function CalcRetDtTotal(dec) {
	x = document.retaildt;
	var vmode = x.actionmode.value;
	var Qty = x.txtRetDtQty.value;
	var Price = x.txtRetDtPrice.value;
	var Discount = x.txtRetDtDiscount.value;
	if (Qty == '') Qty = 0;
	if (Price == '') Price = 0;
	if (Discount == '') Discount = 0;
	
	Qty = parseInt(Qty);
	Price = parseFloat(Price);
	Discount = parseFloat(Discount);
	
	if (Qty > 0 && Price >= 0)
	   x.txtRetDtTotal.value = Math.round(((Qty*Price) - (Qty*Price*Discount/100))*Math.pow(10,dec))/Math.pow(10,dec);

}

function SetRetDtPrice(dec, vatperc) {
	x = document.retaildt;
	
	var PriceTTC = x.txtRetDtPriceTTC.value;
	
	if (PriceTTC == '') PriceTTC = 0;
	PriceTTC = parseFloat(PriceTTC);
	
	if (PriceTTC > 0)
	   x.txtRetDtPrice.value = Math.round((PriceTTC / (1 + vatperc/100))*Math.pow(10,dec))/Math.pow(10,dec);

	   
}


function showlistItems(str){
  var vdate, vid, vItemBarCode;
  x = document.retaildt;
  
  vdate = x.PRetDate.value;
  vid   = x.PRetId.value;
  vItemBarCode  = x.txtItemBarcode.value;
  vItemWh       = x.txtWarehouseCode.value;
  
  vItemBarCode = vItemBarCode.replace('&','%26');
  vItemWh	   = vItemWh.replace('&','%26');
  
  window.open('List_ItemsBarcode.php?frm=1&PItem_Code='+vItemBarCode+'&TransDate='+vdate+'&ItemWh='+vItemWh,'mywindow','width=970,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistVendors(str){
  var vVendorCode;
  x = document.retaildt;
  
  vVendorCode  = x.txtRetDtVendor.value;
  vVendorCode = vVendorCode.replace('&','%26');
  
  window.open('List_Vendors.php?frm=1&PVendorCode='+vVendorCode,'mywindow','width=750,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function RefreshPage()
{
  //document.retaildt.action='Form_RetailDetail.php';
  document.retaildt.submit();

}

function Barcodekd(e)
{
	x=document.retaildt;
	
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        x.btnSubmitRecord.click();
		return false;
    }
    return true;
}

function OnHelp()
{
	return false;
}
function kd(e)
{ 
	x=document.retaildt;
	if (!e) { var e = window.event;}
    var intKey = (window.Event) ? e.which : e.keyCode;
	
	 
	// Block browser short cuts     
	//F3, F4, F5, F6, F11 key
	if (intKey == 114 || intKey == 115 || intKey == 117 || intKey == 122) {
		if(e.preventDefault) // non-IE browsers         
			e.preventDefault();     
		else  // IE Only  
		{
			e.keyCode=0;  
			e.returnValue = false; 
			
		}	
	}

	
    if (intKey == 112) { //F1 key
		if ('onhelp' in window) {   // Internet Explorer
	       window.onhelp = OnHelp;
		}
	
		if (document.getElementById('txtItemBarcode').type == 'text')
			showlistItems(1);
			
		return false;
	}
	else if (intKey == 113) { //F2 key
		x.btnSubmitRecord.click();
		return false;
	}
	else if (intKey == 114) { //F3 key
		x.txtRetDtDiscount.focus();
		return false;
	}
	else if (intKey == 119) { //F8 key
		if (document.getElementById('txtRetDtSlip').type == 'text')
			x.txtRetDtSlip.focus();
			
		return false;
	}
	else if (intKey == 120) { //F9 key
		if (document.getElementById('txtRetDtVendor').type == 'text')
			showlistVendors(1);
			
		return false;
	}
	else if (intKey == 121) { //F10 key
		x.txtRetDtPrice.focus();
		return false;
	}
	else if (intKey == 122) { //F11 key
		x.txtRetDtQty.focus();
		return false;
	}
	else if (intKey == 123) { //F12 key
		if (document.getElementById('txtItemBarcode').type == 'text')
			x.txtItemBarcode.focus();
			
		return false;
	}
	else if (intKey == 13) { //enter key
	
		if(document.activeElement.id == 'txtItemBarcode') {
			if (x.txtItemBarcode.value != '')
				x.submit();
			
			if (document.getElementById('txtRetDtVendor').type == 'text') 
				x.txtRetDtVendor.focus();
				
		}	
		else if(document.activeElement.id == 'txtRetDtVendor') {
			if (document.getElementById('txtRetDtSlip').type == 'text')
				x.txtRetDtSlip.focus();
		}
		else if(document.activeElement.id == 'txtRetDtSlip') {
			if (document.getElementById('txtItemBarcode').type == 'text')
				x.txtItemBarcode.focus();
		}
		
		return false;
    }
	else if (intKey == 27) { //ESC key
	
		self.close();
		
		return false;
	}
	
	
    return true;
}

function OpenKeyboard(field){
	
	VirtualKeyboard.attachInput(field);
	VirtualKeyboard.open(field,'td');
}



function AdminPriv(){
	
	win = window.open('Form_RetailDiscount_PasswordAdmin.php?actionmode=AllowDiscount',
	'Form_Retail_Password', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=400,height=200,left=200,top=100');		
	win.creator = self;
	win.focus();

	x.passchecked.value = '';

	return 0;
}
</script>

<title>Retail Detail - Add Items</title>

<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}

.style15 {color: #5151FF; font-size: 10px;}
.style16 {
	font-size: 13px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #FFFFFF ;font-size: 10px;}

 button {
  padding: 0 0 0 0;
  margin: 0 3px 0 3px;
  border: none;
  cursor: pointer;
  text-decoration: none;
  outline: none;
  white-space: nowrap;
  overflow: visible;
  height: 22px; 
  font-family: 11px Arial, sans-serif;
  font-size: 13px;
  color: #000000;
  background: none;
  font-weight: bold;

}
</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body onLoad='ChangeLocation();' onkeydown='return kd(event);'>
<form name='retaildt' method='post'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='message' value='$message'>
<input type='hidden' name='PRetDate' value='$PRetDate'>
<input type='hidden' name='PRetId' value='$PRetId'>
<input type='hidden' name='PRetDtId' value='$PRetDtId'>
<input type='hidden' name='discount_user' value='$discount_user'>

<input type='hidden' name='PRetCashRegister' value='$PRetCashRegister'>
<input type='hidden' name='PRetClientCode' value='$PRetClientCode'>
<input type='hidden' name='PRetCurr' value='$PRetCurr'>
<input type='hidden' name='PRetProjectCode' value='$PRetProjectCode'>
<input type='hidden' name='PRetCostCentCode' value='$PRetCostCentCode'>

<input type='hidden' name='ModuleQtyReturn' value='$FC_CashRegisterQtyRet'>	
<input type='hidden' name='passchecked' value='$passchecked'>	

<input type='hidden' name='string' value='$string'>
HERE;


$PriceLabel = 'Price';	
if ($CashRegisterTTC == 1) 	
	$PriceLabel = 'Price TTC';	
	
if (empty($txtWarehouseCode))
	$txtWarehouseCode = $StpWarehouseCode;

if($txtRetDtQty=='') $txtRetDtQty=1;
//Edit Retail Detail Mode
if($PRetDtId != ''){
	$sub_query = " Select SaleDt_ID, RetailDt.Item_code, RetailDt.Item_Barcode, Item_Description, RetailDt.Warehouse_Code, ".
	             " SaleDt_Quantity, Round(SaleDt_Price, ".$DecimalBase."), SaleDt_PriceBase1, SaleDt_PriceBase2, ".
				 " Round(SaleDt_DiscountPer, ".$DecimalBase."), ".
				 " Round(((SaleDt_Quantity*SaleDt_Price)-((SaleDt_Quantity*SaleDt_Price*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
				 " Round(SaleDt_PriceTTC, ".$DecimalBase."), ".
				 " Round(((SaleDt_Quantity*SaleDt_PriceTTC)-((SaleDt_Quantity*SaleDt_PriceTTC*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC, ".
				 " RetailDt.Vendor_Code, RetailDt.Slip_Number  ".
				 " From Temp_RetailDt As RetailDt Left Join Items on RetailDt.Item_code = Items.Item_code ".
				 " Where RetailDt.SaleDt_ID = ".$PRetDtId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			   
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
    $sub_rows=mysql_fetch_array($sub_result);
	
	$txtRetDtId        = $sub_rows[0];
	$txtItemCode       = $sub_rows[1];
	$txtItemBarcode    = $sub_rows[2];
	$txtItemDesc       = $sub_rows[3];
	$txtWarehouseCode  = $sub_rows[4];
	$txtRetDtQty       = $sub_rows[5];
	
	if ($CashRegisterTTC == 1) 	
		$txtRetDtPrice 	= $sub_rows[11];
	else
		$txtRetDtPrice 	= $sub_rows[6];
		
	$txtRetDtDiscount  = $sub_rows[9];
	
	if ($CashRegisterTTC == 1) 	
		$txtRetDtTotal  = $sub_rows[12];
	else
		$txtRetDtTotal  = $sub_rows[10];
		
	$txtRetDtVendor = $sub_rows[13];
	$txtRetDtSlip   = $sub_rows[14];
}

if ($txtItemBarcode != '' && $txtItemCode == '') {
	$sub_query  = " Select Item_Code, Item_Description From Items Where Item_Barcode = '".$txtItemBarcode."' ";
	$sub_result = selectData($connection, $sub_query);
	
	$txtItemCode       = $sub_result[0];
	$txtItemDesc       = $sub_result[1];
	$txtRetDtQty       = 1;
}


if($txtItemCode != ''){

	$min_sorder_qty = 0;
	$min_available_qty = 9999999999;
	$min_exists_qty = 9999999999;
	$available_qty = 0;
	$exist_qty = 0;
	
	if (empty($PRetId)) $PRetId = 0;
	if (empty($PRetDtId)) $PRetDtId = 0;
	
	
	$sub_query1  = " Select ifNull(Item_Pack,0), ifNull(Item_ModifySellingPrice,0) From Items Where Item_Code = '".$txtItemCode."' ";
	$sub_result1 = selectData($connection, $sub_query1);
	$ItemPack = $sub_result1[0];
	$ItemModifySellingPrice = $sub_result1[1];
	
	if($ItemPack == 1){
		$sub_query1 = "SELECT Item_CodePackDt, Sum(PackDt_Quantity) FROM packdt WHERE Item_Code = '".$txtItemCode."' Group By Item_CodePackDt ";
		$sub_result1 = mysql_query($sub_query1, $connection);			
		//echo $sub_query1;
		while($cur = mysql_fetch_row($sub_result1)){
		
			$sub_query5 = " SELECT ifnull(QtyExists('".$cur[0]."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."', $PRetDtId, 'RI', '', ''),0) As QtyExists ";
			//echo "<br><br>".$sub_query5;
			$sub_result5 = selectData($connection, $sub_query5);
			if (empty($sub_result5[0])) $sub_result5[0] = 0;
			
			$sub_query4 = " Select ifNull(Sum(ifNull(SaleDt_Quantity,0)),0) FROM Temp_RetailDt ".
						  " WHERE Item_code = '".$cur[0]."'  And  Warehouse_code = '".$txtWarehouseCode."' And Sale_ID = $PRetId And SaleDt_ID != ifNull('".$PRetDtId."',0) ".
						  " And SaleDt_ID Not In (Select SaleDt_ID From RetailDt Where Sale_ID  = $PRetId) ";
			$sub_result4 = selectData($connection, $sub_query4);
			
			$exist_qty = (($sub_result5[0] - $sub_result4[0]) / $cur[1]); 
			if ($exist_qty < $min_exists_qty ){
				$min_exists_qty = $exist_qty;
					
				$vItemCode    = $cur[0];
				$vItemPackQty = $cur[1];
				$temp_qty     = $sub_result4[0];
			}
			
		}

		$sub_query2  = " SELECT ifnull(QtyBooking_Temp('".$vItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."'),0)";
		$sub_query3 = " SELECT ifnull(QtyExistsWSorder_Temp('".$vItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."', $PRetDtId, 'RI', '', ''),0) QtyExists ";
		
		//echo "<br><br>".$sub_query2;
		//echo "<br><br>".$sub_query3;
					
		$sub_result2 = selectData($connection, $sub_query2);
		$sub_result3 = selectData($connection, $sub_query3);
			
		if ($sub_result2[0] < 0) {$sub_result2[0] = 0;}
		
		$min_available_qty = abs(($sub_result3[0] - $temp_qty) / $vItemPackQty);
		$min_sorder_qty    = ($sub_result2[0] / $vItemPackQty);
		
			
		$min_sorder_qty = ceil($min_sorder_qty);
		//$min_available_qty = floor($min_available_qty);
		$min_available_qty = floor($min_exists_qty) - ceil($min_sorder_qty);
		$min_exists_qty = floor($min_exists_qty);	
		
	}else{
		$sub_query2 = "SELECT ifnull(QtyBooking_Temp('".$txtItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."', 0),0) ";
		$sub_result2 = selectData($connection, $sub_query2);
		if ($sub_result2[0] < 0){$sub_result2[0] = 0;}
		$min_sorder_qty = $sub_result2[0];
		//echo $sub_query2;
		
		$sub_query3  = " Select QtyExistsWSorder_Temp('".$txtItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."', $PRetDtId, 'RI', '', '', 0) QtyExists From Dual ";
		$sub_result3 = selectData($connection, $sub_query3);
		$min_available_qty = $sub_result3[0];

		$sub_query4 = " Select ifNull(Sum(ifNull(SaleDt_Quantity,0)),0) FROM Temp_RetailDt ".
					  " WHERE Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$txtWarehouseCode."' And Sale_ID = $PRetId And SaleDt_ID != ifNull('".$PRetDtId."',0) ".
					  " And SaleDt_ID Not In (Select SaleDt_ID From RetailDt Where Sale_ID  = $PRetId) ";
		$sub_result4 = selectData($connection, $sub_query4);
		
		/*$sub_query5 = " Select cast(ifNull(Sum(ifNull(QuantityProduceIn,0) - ifNull(QuantityProduceOut,0) + ifNull(QuantityEntered,0) - ifNull(QuantityDelivered,0)),0) as decimal(20,2)) as QuantityExists From StkTransaction ".
					  " Where StkTransaction.Item_Code = '".$txtItemCode."' ".
					  " And (('".$txtWarehouseCode."' = '' and 1 = 1) or ('".$txtWarehouseCode."' != '' and ifNull(StkTransaction.Warehouse_Code, -1) = ifNull('".$txtWarehouseCode."', ifNull(StkTransaction.Warehouse_Code, -1))) ) ".
					  " And Transaction_Date <= '".insertMySQLDate($PRetDate)."' ";*/
		$sub_query5 = " SELECT ifnull(QtyExists('".$txtItemCode."', '".$txtWarehouseCode."', '".insertMySQLDate($PRetDate)."', $PRetDtId, 'RI', '', ''),0) As QtyExists ";				   			  
		$sub_result5 = selectData($connection, $sub_query5);
		$min_exists_qty = $sub_result5[0];
		//echo $sub_query5;
		
		$min_available_qty = $min_available_qty - $sub_result4[0];
		$min_exists_qty    = $min_exists_qty  - $sub_result4[0];
		$min_sorder_qty    = $min_sorder_qty;

	}
	//echo $query;
	$txtPOQty        = $min_sorder_qty;
	$txtAvailableQty = $min_available_qty;
	$txtExistingQty  = $min_exists_qty;
	
	
	$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$PRetClientCode."'";
	//echo "<br><br>".$query;
	$result = selectData($connection, $query);
	$c_sp = $result[0];

	
	
	$query = " Select Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, ".
	         " Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, ".
			 " Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, ".
			 " Currency_Code, ifNull(Item_Promotion,0), ifNull(Item_NonStock,0) ".
			 " From Items Where Item_Code = '".$txtItemCode."'";
				
		
	//echo "<br><br>".$query;
	$result = selectData($connection, $query);
	$i_sp       = $result[0];
	$i_curr     = $result[18];
	$i_promo    = $result[19];
	$i_nonstock = $result[20];
	
		
	if ($PRetCurr != $i_curr) {
		if ($PRetCurr == $Base1Curr) {
			$Item_SellingPrice1 = $result[1];
			$Item_SellingPrice2 = $result[4];
			$Item_SellingPrice3 = $result[7];
			$Item_SellingPrice4 = $result[10];
			$Item_SellingPrice5 = $result[13];
			$Item_SellingPrice6 = $result[16];
		}
		else if ($PRetCurr == $Base2Curr) {
			$Item_SellingPrice1 = $result[2];
			$Item_SellingPrice2 = $result[5];
			$Item_SellingPrice3 = $result[8];
			$Item_SellingPrice4 = $result[11];
			$Item_SellingPrice5 = $result[14];
			$Item_SellingPrice6 = $result[17];
		}
		else {
			$Item_SellingPrice1 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[0],  $connection);
			$Item_SellingPrice2 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[3],  $connection);
			$Item_SellingPrice3 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[6],  $connection);
			$Item_SellingPrice4 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[9],  $connection);
			$Item_SellingPrice5 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[12], $connection);
			$Item_SellingPrice6 = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $result[15], $connection);
			
		}
		
	} else {
		$Item_SellingPrice1 = $result[0];
		$Item_SellingPrice2 = $result[3];
		$Item_SellingPrice3 = $result[6];
		$Item_SellingPrice4 = $result[9];
		$Item_SellingPrice5 = $result[12];
		$Item_SellingPrice6 = $result[15];
	}
	
	//$i_sp   = ConvertCurrency($i_curr, $PRetCurr, insertMySQLDate($PRetDate), $i_sp, $connection);
		
	switch ($c_sp){
		case "I":
			$i_sp = $Item_SellingPrice1; break;
		case "II":
			$i_sp = $Item_SellingPrice2; break;
		case "III":
			$i_sp = $Item_SellingPrice3; break;
		case "IV":
			$i_sp = $Item_SellingPrice4; break;
		case "V":
			$i_sp = $Item_SellingPrice5; break;
		case "VI":
			$i_sp = $Item_SellingPrice6; break;
	}
		
	
	
	
	//if($i_promo == 1) $i_sp = 0; 
	if($i_promo == 1 && $ItemPack != 1) $i_sp = 0; 
	if($PRetDtId == '') $txtRetDtPrice = $i_sp;
	
	$txtRetDtPrice  = round($txtRetDtPrice, $DecimalBase);

}

//echo $ItemModifySellingPrice."Sdsds";
// User Has No Access To Modify The Price	
$ModeModifySellPrice = '';
if ($Unmodify_SellingPrice == 1 || ($ItemModifySellingPrice == 0 && $txtItemCode != ''))	
	$ModeModifySellPrice = ' readonly ';

//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' style='table-layout:fixed' width='700px;'>";
echo"<tr>
		<td id='search-top1' style='height:34px; width:31px;'>&nbsp;</td>
	  	<td id='search-top2' style='height:34px; width:700px' align='center' valign='middle'>
			<table border='0'>
			<tr><td><span class='style3'>Add Items</span></td></tr>
			</table>
		</td>
		<td id='search-top3' style='height:34px; width:31px;'>&nbsp;</td>
	</tr>";


 echo"<tr  height='25'><td id='search-content1' style='height:34px; width:31px;'>&nbsp;</td>
				<td  align='left' id='search-content2'><table width='100%' align='left' border='0'>";
		
	echo"	<tr >";
echo"	  <td colspan='2' align='center'>
	 <button type='button' id='btnSubmitRecord' name='btnSubmitRecord'  value='F2:Submit Record'  onclick='SubmitRecord($FC_DiscountPerLimit,$CashReg_ForcingVendor)'  title='Submit Record'><span><span>F2:Submit Record</span></span></button>";
echo"	  </td>";
echo"	</tr>";			
		echo"</table></td><td id='search-content3' style='width:31px;'>&nbsp;</td>
		      </tr>";
	  
echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		 <td id='search-content2' >";  

	  
echo"  
        <table border='0' cellpadding='1' style='table-layout:fixed' align='left' valign='top' >
          <col width=100>
		  <col width=200>
		  <col width=80>
		  <col width=140>
		  <col width=90>
		  <col width=70>

		   <tr bgcolor='#F7F7F7' height='20'>	
			 <td colspan='6' align='center'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td></tr>
		   <tr bgcolor='#F7F7F7' height='15'>	
			 <td colspan='6' align='center'><span class='style16'>F1:Items List - Esc:Close</span></td></tr>";	 


echo"	  <tr bgcolor='#F7F7F7' height='25'>";
echo"<td><span class='style1'>Date/Time</span></td>";
$sub_query4 = " Select date_format(sale_date,'%d/%m/%Y %h:%i %p') From Temp_Retail Where Sale_ID  = $PRetId";
$sub_result4 = selectData($connection, $sub_query4);
echo "<tD><b>".$sub_result4[0]."</td>";
echo"</tr>";
echo"	  <tr bgcolor='#F7F7F7' height='25'>
			 <input type='hidden' name='txtRetDtId' value='$txtRetDtId' >
             <td valign='center' align='left' ><span class='style1'>Warehouse&nbsp;<span class='style26'>*</span></span></td>";			 
		
		if ($PRetDtId == '') {
			echo"<td colspan='5'><select name='txtWarehouseCode' id='txtWarehouseCode' style='font-size:11px; width:250px; height:18px;' onchange='RefreshPage();' >";
			echo"<option></option>";
			while($wrhf=mysql_fetch_row($resultwarehouse)){
				echo"<option ";
				if ($txtWarehouseCode==$wrhf[0]) echo " selected ";
				echo" value='$wrhf[0]'>$wrhf[0] - $wrhf[1]</option>";
			}
			
			echo"</select></td>";
		} else {
			echo " <td colspan='5'><input type='hidden' name='txtWarehouseCode' value='$txtWarehouseCode' >
					<b>$txtWarehouseCode</b></td>";
		}	
echo"	  </tr>";		
		
					
echo"	  <tr bgcolor='#F7F7F7' height='25'>
			 <td valign='center' align='left' ><span class='style1'>F12:Barcode&nbsp;<span class='style26'>*</span></span></td>";
			 
		if ($PRetDtId == '') {
		    echo " <td colspan='3'><input type='hidden' name='txtItemCode' value='$txtItemCode' >
			            <input type='text' name='txtItemBarcode' id='txtItemBarcode' value='$txtItemBarcode'  maxlength='40'  style='font-size:12px; width:110px; height:18px;'  />
						<input type='text' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc' style='font-size:12px; width:270px; height:18px;' />
						<label><span class='style1'><img src='img/openlist.png' title=' Select Item '  width='17' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistItems(1); ' /></span></label></td>";
		} else {
			echo " <td colspan='3'><input type='hidden' name='txtItemCode' value='$txtItemCode' ><input type='hidden' name='txtItemBarcode' id='txtItemBarcode' value='$txtItemBarcode' >
			                       <input type='hidden' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc'  />
					<b>$txtItemBarcode &nbsp;&nbsp; $txtItemDesc</b></td>";
		}


echo "		<td align='left'><span class='style1'>Existing Qty</span></td>
			<td align='right'><b>".number_format($txtExistingQty,2)."</b> <input type='hidden' name='txtExistingQty' value='$txtExistingQty' ></td>
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td align='left' valign='center' ><span class='style1'>F11:Qty&nbsp;</span></td>
			 <td align='left' ><input type='text' name='txtRetDtQty' value='$txtRetDtQty' maxlength='20' onBlur='CalcRetDtTotal($DecimalBase);'  style='font-size:12px; width:100px; height:18px;' ></td>";
			 
if ($CashReg_Vendor == 1){
    echo "   <td align='left' valign='center' ><span class='style1'>F9:Vendor</span></td>
	         <td ><input type='text' value='$txtRetDtVendor'  name='txtRetDtVendor' id='txtRetDtVendor' maxlength='10' style='font-size:12px; width:110px; height:18px;' >
						<label><span class='style1'><img src='img/openlist.png' title=' Select Vendor '  width='17' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistVendors(1); ' /></span></label></td>";
} else {
	echo "   <td align='left' colspan='2' ><input type='hidden' name='txtRetDtVendor' id='txtRetDtVendor' value='$txtRetDtVendor' >&nbsp;</td>";
}	


echo "		 <td align='left'><span class='style1'>Booking Qty</span></td>
			 <td align='right'><b>".number_format($txtPOQty,2)."</b><input type='hidden' name='txtPOQty' value='$txtPOQty' ></td>
		  </tr>	 	
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style1'>F10:$PriceLabel&nbsp;</span></td> 
			 <td align='left'><input type='text' name='txtRetDtPrice' value='$txtRetDtPrice' maxlength='20' 
			 onBlur='CalcRetDtTotal($DecimalBase);' style='text-align:right; font-size:12px; width:100px; height:18px;' $ModeModifySellPrice>";
			 
if ($CashRegisterTTC != 1) {
	echo "   <span class='style1'>TTC:</span>";
	echo "   <input type='text' name='txtRetDtPriceTTC' value='$txtRetDtPriceTTC' maxlength='20' onBlur='SetRetDtPrice(4,$Setup_VatPercentage);' style='text-align:right; font-size:12px; width:60px; height:18px;' $ModeModifySellPrice>";
} else {
	echo "   <input type='hidden' name='txtRetDtPriceTTC' value='$txtRetDtPriceTTC'>";
}

echo "  </td>";
			
			
if ($ShowSlipNumber == 1){
    echo "   <td align='left' valign='center' ><span class='style1'>F8:Slip No.</span></td>
	         <td ><input type='text' value='$txtRetDtSlip'  name='txtRetDtSlip' id='txtRetDtSlip' maxlength='20' style='font-size:12px; width:110px; height:18px;'></td>";
} else {
	echo "   <td align='left' colspan='2' ><input type='hidden' name='txtRetDtSlip' id='txtRetDtSlip' value='$txtRetDtSlip' >&nbsp;</td>";
}	
			 
echo "		 <td align='left'><span class='style1'>Real Qty</span></td>
			 <td align='right'><b>".number_format($txtAvailableQty,2)."</b> <input type='hidden' name='txtAvailableQty' value='$txtAvailableQty' ></td>
		  </tr>	"; 	
		  
if ($CashRegister_Discount == 1 && $FC_CashRegisterDisc == 1) {
	echo "<tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style1'>F3:Disc(%)</span></td> 
			 <td align='left' colspan='3'><input type='text' name='txtRetDtDiscount' value='$txtRetDtDiscount' maxlength='20' onBlur='CalcRetDtTotal($DecimalBase);'  style='text-align:right; font-size:12px; width:100px; height:18px;' ></td>
			 <td align='left' colspan='2'>&nbsp;</td>
		  </tr>";
} else 	{
	echo "<tr bgcolor='#F7F7F7' height='25'>
			<td valign='center' align='left' ><span class='style1'>F3:Disc(%)</span></td> 
			<td align='left' colspan='3'>
				<input type='text' name='txtRetDtDiscount' value='$txtRetDtDiscount' maxlength='20' onBlur='CalcRetDtTotal($DecimalBase);'  style='text-align:right; font-size:12px; width:100px; height:18px;' readOnly>
				<button type='button' id='btnSubmitRecord' name='btnSubmitRecord'  value='Admin Priv. Discount'  onclick='AdminPriv();'  title='Admin Priv. Discount'><span><span>Admin Priv. Discount</span></span></button>
			</td>

			<td align='left' colspan='2'>&nbsp;</td>
		</tr>";
}

		  
echo "	  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style1'>Total</span></td> 
			 <td align='left' colspan='3'><input type='text' name='txtRetDtTotal' value='$txtRetDtTotal' maxlength='20' style='text-align:right; font-size:12px; width:100px; height:18px;' ></td>
			 <td align='left' colspan='2'>&nbsp;</td>
		  </tr>	"; 	
	 echo "</table></td><td id='search-content3' style='width:31px;'>&nbsp;</td></tr>";			 
	echo"	<tr >
		<td id='search-bottom1' style='height:34px; width:31px;'>&nbsp;</td>
		<td id='search-bottom2' style='height:34px; width:560px;' valign='top'>&nbsp; ";
		//include("toolbar.php");
		
		echo"</td>
		<td id='search-bottom3' style='height:34px; width:31px;' valign='top'></td>";
echo" </tr>";	  
   echo"</table>";


print <<<HERE
</form>
</body>

HERE;

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	$result = selectData($connection, $query);
	//echo $query;
	Return	$result[0];

}
?>