<?php
header("Content-type: text/html; charset=windows-1256");
session_start();

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

include("config.inc.php");
include("function.inc.php");
include("Functions_Synchro.php");

set_time_limit(0);

$HideMenu   = $_POST["HideMenu"]; if ($HideMenu == ""){$HideMenu = $_GET["HideMenu"];}   
$actionmode = $_GET["actionmode"]; if ($actionmode == ""){$actionmode = $_POST["actionmode"];}   
$mainmode   = $_GET["mainmode"]; if ($mainmode == ""){$mainmode = $_POST["mainmode"];}   
$message 	= $_GET["message"]; if ($message == ""){$message = $_POST["message"];}
$itemid 	= $_GET["itemid"]; if ($itemid == ""){$itemid = $_POST["itemid"];} 


$item_id 		   = $_POST["item_id"]; if ($item_id == ""){$item_id = $_GET["item_id"];} 
//$checkduplicate    = $_POST["checkduplicate"]; if ($checkduplicate == ""){$checkduplicate = $_GET["checkduplicate"];} 
$setcode 		   = $_POST["setcode"]; if ($setcode == ""){$setcode = $_GET["setcode"];} 
$numrow 		   = $_POST["numrow"]; if ($numrow == ""){$numrow = $_GET["numrow"];} 
$numbertaxes 	   = $_POST["numbertaxes"]; if ($numbertaxes == ""){$numbertaxes = $_GET["numbertaxes"];} 
$item_attribute    = $_POST["item_attribute"]; if ($item_attribute == ""){$item_attribute = $_GET["item_attribute"];} 
$item_policy 	   = $_POST["item_policy"]; if ($item_policy == ""){$item_policy = $_GET["item_policy"];} 
$ItemDt_ID 		   = $_POST["ItemDt_ID"]; if ($ItemDt_ID == ""){$ItemDt_ID = $_GET["ItemDt_ID"];} 
$itemactive 	   = $_POST["itemactive"]; if ($itemactive == ""){$itemactive = $_GET["itemactive"];} 
$item_semifinished = $_POST["item_semifinished"]; if ($item_semifinished == ""){$item_semifinished = $_GET["item_semifinished"];} 
$Itempackdt 	   = $_POST["Itempackdt"]; if ($Itempackdt == ""){$Itempackdt = $_GET["Itempackdt"];} 
$Itempackwarehouse = $_POST["Itempackwarehouse"]; if ($Itempackwarehouse == ""){$Itempackwarehouse = $_GET["Itempackwarehouse"];} 
$barcodeindex 	   = $_POST["barcodeindex"]; if ($barcodeindex == ""){$barcodeindex = $_GET["barcodeindex"];} 

$reverse_production	= $_POST["reverse_production"]; if ($reverse_production == ""){$reverse_production = $_GET["reverse_production"];} 
$nonstock_item 		= $_POST["nonstock_item"]; if ($nonstock_item == ""){$nonstock_item = $_GET["nonstock_item"];} 
$item_production 	= $_POST["item_production"]; if ($item_production == ""){$item_production = $_GET["item_production"];} 
$ttc_include 		= $_POST["ttc_include"]; if ($ttc_include == ""){$ttc_include = $_GET["ttc_include"];} 
$item_pack 			= $_POST["item_pack"]; if ($item_pack == ""){$item_pack = $_GET["item_pack"];} 
$item_promotion 	= $_POST["item_promotion"]; if ($item_promotion == ""){$item_promotion = $_GET["item_promotion"];} 
$item_withserialno 	= $_POST["item_withserialno"]; if ($item_withserialno == ""){$item_withserialno = $_GET["item_withserialno"];} 
$EvaluateQtyUnit 	= $_POST["EvaluateQtyUnit"]; if ($EvaluateQtyUnit == ""){$EvaluateQtyUnit = $_GET["EvaluateQtyUnit"];} 
$item_print 		= $_POST["item_print"]; if ($item_print == ""){$item_print = $_GET["item_print"];} 

$item_code 	= $_POST["item_code"]; if ($item_code == ""){$item_code = $_GET["item_code"];} 
$item_vat 	= $_POST["item_vat"]; if ($item_vat == ""){$item_vat = $_GET["item_vat"];} 
$item_vattype 	= $_POST["item_vattype"]; if ($item_vattype == ""){$item_vattype = $_GET["item_vattype"];} 
$currency 	= $_POST["currency"]; if ($currency == ""){$currency = $_GET["currency"];} 
$item_description 	= $_POST["item_description"]; if ($item_description == ""){$item_description = $_GET["item_description"];} 
$group_code 		= $_POST["group_code"]; if ($group_code == ""){$group_code = $_GET["group_code"];} 
$group_name 		= $_POST["group_name"]; if ($group_name == ""){$group_name = $_GET["group_name"];} 
$subgroup_code 		= $_POST["subgroup_code"]; if ($subgroup_code == ""){$subgroup_code = $_GET["subgroup_code"];} 
$subgroup_name 		= $_POST["subgroup_name"]; if ($subgroup_name == ""){$subgroup_name = $_GET["subgroup_name"];} 
$project_code 		= $_POST["project_code"]; if ($project_code == ""){$project_code = $_GET["project_code"];} 
$project_name 		= $_POST["project_name"]; if ($project_name == ""){$project_name = $_GET["project_name"];} 
$item_remark 		= $_POST["item_remark"]; if ($item_remark == ""){$item_remark = $_GET["item_remark"];} 
$item_weight 		= $_POST["item_weight"]; if ($item_weight == ""){$item_weight = $_GET["item_weight"];} 
$item_netweight		= $_POST["item_netweight"]; if ($item_netweight == ""){$item_netweight = $_GET["item_netweight"];} 
$item_color			= $_POST["item_color"]; if ($item_color == ""){$item_color = $_GET["item_color"];} 
$item_volume		= $_POST["item_volume"]; if ($item_volume == ""){$item_volume = $_GET["item_volume"];} 
$item_active 		= $_POST["item_active"]; if ($item_active == ""){$item_active = $_GET["item_active"];} 
$item_minqty 		= $_POST["item_minqty"]; if ($item_minqty == ""){$item_minqty = $_GET["item_minqty"];} 
$item_maxqty 		= $_POST["item_maxqty"]; if ($item_maxqty == ""){$item_maxqty = $_GET["item_maxqty"];} 
$item_unitsales 	= $_POST["item_unitsales"]; if ($item_unitsales == ""){$item_unitsales = $_GET["item_unitsales"];} 
$item_quantity 		= $_POST["item_quantity"]; if ($item_quantity == ""){$item_quantity = $_GET["item_quantity"];} 
$item_unitpurchase	= $_POST["item_unitpurchase"]; if ($item_unitpurchase == ""){$item_unitpurchase = $_GET["item_unitpurchase"];} 
$item_location   	= $_POST["item_location"]; if ($item_location == ""){$item_location = $_GET["item_location"];} 
$item_barcode 		= $_POST["item_barcode"]; if ($item_barcode == ""){$item_barcode = $_GET["item_barcode"];} 
$item_barcode2 		= $_POST["item_barcode2"]; if ($item_barcode2 == ""){$item_barcode2 = $_GET["item_barcode2"];} 
$item_barcode3 		= $_POST["item_barcode3"]; if ($item_barcode3 == ""){$item_barcode3 = $_GET["item_barcode3"];} 
$GeneratedLines 	= $_POST["GeneratedLines"]; if ($GeneratedLines == ""){$GeneratedLines = $_GET["GeneratedLines"];} 
$itemtype 		    = $_POST["itemtype"]; if ($itemtype == ""){$itemtype = $_GET["itemtype"];} 
$cost 				= $_POST["cost"]; if ($cost == ""){$cost = $_GET["cost"];} 
$item_lastcostprice = $_POST["item_lastcostprice"]; if ($item_lastcostprice == ""){$item_lastcostprice = $_GET["item_lastcostprice"];} 
$item_disporder		= $_POST["item_disporder"]; if ($item_disporder == ""){$item_disporder = $_GET["item_disporder"];} 

$transfer 			= $_POST["transfer"]; if ($transfer == ""){$transfer = $_GET["transfer"];} 
$Item_ModifySellingPrice= $_POST["Item_ModifySellingPrice"]; if ($Item_ModifySellingPrice == ""){$Item_ModifySellingPrice = $_GET["Item_ModifySellingPrice"];} 
$lastcost 			= $_POST["lastcost"]; if ($lastcost == ""){$lastcost = $_GET["lastcost"];} 
$sellingprice1 		= $_POST["sellingprice1"]; if ($sellingprice1 == ""){$sellingprice1 = $_GET["sellingprice1"];} 
$sellingprice1base1	= $_POST["sellingprice1base1"]; if ($sellingprice1base1 == ""){$sellingprice1base1 = $_GET["sellingprice1base1"];} 
$sellingprice1base2	= $_POST["sellingprice1base2"]; if ($sellingprice1base2 == ""){$sellingprice1base2 = $_GET["sellingprice1base2"];} 
$sellingprice2 		= $_POST["sellingprice2"]; if ($sellingprice2 == ""){$sellingprice2 = $_GET["sellingprice2"];} 
$sellingprice2base1 = $_POST["sellingprice2base1"]; if ($sellingprice2base1 == ""){$sellingprice2base1 = $_GET["sellingprice2base1"];} 
$sellingprice2base2 = $_POST["sellingprice2base2"]; if ($sellingprice2base2 == ""){$sellingprice2base2 = $_GET["sellingprice2base2"];} 
$sellingprice3 		= $_POST["sellingprice3"]; if ($sellingprice3 == ""){$sellingprice3 = $_GET["sellingprice3"];} 
$sellingprice3base1	= $_POST["sellingprice3base1"]; if ($sellingprice3base1 == ""){$sellingprice3base1 = $_GET["sellingprice3base1"];} 
$sellingprice3base2	= $_POST["sellingprice3base2"]; if ($sellingprice3base2 == ""){$sellingprice3base2 = $_GET["sellingprice3base2"];} 
$sellingprice4 		= $_POST["sellingprice4"]; if ($sellingprice4 == ""){$sellingprice4 = $_GET["sellingprice4"];} 
$sellingprice4base1 = $_POST["sellingprice4base1"]; if ($sellingprice4base1 == ""){$sellingprice4base1 = $_GET["sellingprice4base1"];} 
$sellingprice4base2 = $_POST["sellingprice4base2"]; if ($sellingprice4base2 == ""){$sellingprice4base2 = $_GET["sellingprice4base2"];} 
$sellingprice5 		= $_POST["sellingprice5"]; if ($sellingprice5 == ""){$sellingprice5 = $_GET["sellingprice5"];} 
$sellingprice5base1 = $_POST["sellingprice5base1"]; if ($sellingprice5base1 == ""){$sellingprice5base1 = $_GET["sellingprice5base1"];} 
$sellingprice5base2 = $_POST["sellingprice5base2"]; if ($sellingprice5base2 == ""){$sellingprice5base2 = $_GET["sellingprice5base2"];} 
$sellingprice6 		= $_POST["sellingprice6"]; if ($sellingprice6 == ""){$sellingprice6 = $_GET["sellingprice6"];} 
$sellingprice6base1 = $_POST["sellingprice6base1"]; if ($sellingprice6base1 == ""){$sellingprice6base1 = $_GET["sellingprice6base1"];} 
$sellingprice6base2 = $_POST["sellingprice6base2"]; if ($sellingprice6base2 == ""){$sellingprice6base2 = $_GET["sellingprice6base2"];} 

$attribute_code 	= $_POST["attribute_code"]; if ($attribute_code == ""){$attribute_code = $_GET["attribute_code"];} 
$attribute_desc 	= $_POST["attribute_desc"]; if ($attribute_desc == ""){$attribute_desc = $_GET["attribute_desc"];} 
$attribute_value 	= $_POST["attribute_value"]; if ($attribute_value == ""){$attribute_value = $_GET["attribute_value"];} 
$attribute_unit 	= $_POST["attribute_unit"]; if ($attribute_unit == ""){$attribute_unit = $_GET["attribute_unit"];} 


$Item_QtyToBeProduced 	= $_POST["Item_QtyToBeProduced"]; if ($Item_QtyToBeProduced == ""){$Item_QtyToBeProduced = $_GET["Item_QtyToBeProduced"];} 
$item_packgroupcode 	= $_POST["item_packgroupcode"]; if ($item_packgroupcode == ""){$item_packgroupcode = $_GET["item_packgroupcode"];} 
$item_packgroupname 	= $_POST["item_packgroupname"]; if ($item_packgroupname == ""){$item_packgroupname = $_GET["item_packgroupname"];} 
$item_packcode 			= $_POST["item_packcode"]; if ($item_packcode == ""){$item_packcode = $_GET["item_packcode"];} 
$item_packdesc	 		= $_POST["item_packdesc"]; if ($item_packdesc == ""){$item_packdesc = $_GET["item_packdesc"];} 
$item_packbarcode 		= $_POST["item_packbarcode"]; if ($item_packbarcode == ""){$item_packbarcode = $_GET["item_packbarcode"];} 
$item_packqty 			= $_POST["item_packqty"]; if ($item_packqty == ""){$item_packqty = $_GET["item_packqty"];} 
$item_packcost 			= $_POST["item_packcost"]; if ($item_packcost == ""){$item_packcost = $_GET["item_packcost"];} 
$item_packfromdate 		= $_POST["item_packfromdate"]; if ($item_packfromdate == ""){$item_packfromdate = $_GET["item_packfromdate"];} 
$item_packtodate 		= $_POST["item_packtodate"]; if ($item_packtodate == ""){$item_packtodate = $_GET["item_packtodate"];} 
$item_promoqty 			= $_POST["item_promoqty"]; if ($item_promoqty == ""){$item_promoqty = $_GET["item_promoqty"];} 

$manufacture_code 	 = $_POST["manufacture_code"]; if ($manufacture_code == ""){$manufacture_code = $_GET["manufacture_code"];} 
$manufacture_desc    = $_POST["manufacture_desc"]; if ($manufacture_desc == ""){$manufacture_desc = $_GET["manufacture_desc"];} 
$manufacture_codePrv = $_POST["manufacture_codePrv"]; if ($manufacture_codePrv == ""){$manufacture_codePrv = $_GET["manufacture_codePrv"];} 

$rebate_id 			 = $_POST["rebate_id"]; if ($rebate_id == ""){$rebate_id = $_GET["rebate_id"];} 
$rebate_rangefrom    = $_POST["rebate_rangefrom"]; if ($rebate_rangefrom == ""){$rebate_rangefrom = $_GET["rebate_rangefrom"];} 
$rebate_rangeto 	 = $_POST["rebate_rangeto"]; if ($rebate_rangeto == ""){$rebate_rangeto = $_GET["rebate_rangeto"];} 
$rebate_per			 = $_POST["rebate_per"]; if ($rebate_per == ""){$rebate_per = $_GET["rebate_per"];} 

/// Ereg Replace

$item_remark = ereg_replace("'", "\'", trim($item_remark));
$item_description   = ereg_replace("'", "\'", trim($item_description));
$item_location = ereg_replace("'", "\'", trim($item_location));

$item_code 	   = ereg_replace("'", "\'", trim($item_code));
$item_barcode  = ereg_replace("'", "\'", trim($item_barcode));
$item_barcode2 = ereg_replace("'", "\'", trim($item_barcode2));
$item_barcode3 = ereg_replace("'", "\'", trim($item_barcode3));

$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");


/// Belongs to group
$query_login="select login_belongstogrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlogin=mysql_query($query_login,$connection) or die(mysql_error());
$row_login=mysql_fetch_row($resultlogin);
$belongstogroup=$row_login[0];


$query_setup=" Select base1 As base1, base2 as base2, Setup_Branch,DecimalBase, DecimalBase1, DecimalBase2,remaining_length as remaininglength from setup";
$result= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetup=mysql_fetch_array($result)){
	extract($rowsetup);
}
	
$query_setup=" Select CashReg_BarcodeLength as CashReg_BarcodeLength from cashregister where CashReg_BarcodeLength is not null and CashReg_BarcodeLength<>0 ";
$result= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetup=mysql_fetch_array($result)){
	extract($rowsetup);
}	
//echo$CashReg_BarcodeLength;exit;



	
	
//Read From Module Table
$querymodule=" Select ifNull(Module_Synchro,0) As Module_Synchro,ifNull(Module_AutoItemcode,0) as Module_AutoItemcode From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

	
 
if(empty($project_code))  $project_code='null';
else  $project_code="'$project_code'"; 
  
 if(empty($group_code))  $group_code='null';
else  $group_code="'$group_code'"; 

if(empty($subgroup_code))  $subgroup_code='null';
else  $subgroup_code="'$subgroup_code'";




if($item_quantity=='')	$item_quantity=1;	

if($item_tax6=='')	  $item_tax6=0;	
if($item_tax1=='')	  $item_tax1=0;
if($item_tax2=='')	  $item_tax2=0;	
if($item_tax3=='')	  $item_tax3=0;
if($item_tax4=='')	  $item_tax4=0;	
if($item_tax5=='')	  $item_tax5=0;
if($item_vat=='')	  $item_vat=0;
if($item_vattype=='') $item_vattype=1;

if($sellingprice1=='')	$sellingprice1='0';	
if($sellingprice2=='')	$sellingprice2='0';
if($sellingprice3=='')	$sellingprice3='0';
if($sellingprice4=='')	$sellingprice4='0';
if($sellingprice5=='')	$sellingprice5='0';
if($sellingprice6=='')	$sellingprice6='0';

if($item_weight=='')		$item_weight='0';	
if($item_netweight=='')		$item_netweight='0';
if($item_volume=='')		$item_volume='0';	
if($item_lastcostprice=='')	$item_lastcostprice='0';	
if($item_disporder =='')	$item_disporder	='0';	

if (!empty($item_packfromdate))	{
	$item_packfromdate  = explodeword($item_packfromdate);
	$item_packfromdate  = "'$item_packfromdate'";

}	
else {
	$item_packfromdate= 'null';
}

if (!empty($item_packtodate))	{
	$item_packtodate  = explodeword($item_packtodate);
	$item_packtodate  = "'$item_packtodate'";

}	
else {
	$item_packtodate= 'null';
}


if (empty($item_packcost)) $item_packcost = 0;
if (empty($item_packqty))  $item_packqty = 0;
if (empty($item_promoqty)) $item_promoqty = 0;
if (empty($Item_QtyToBeProduced)) $Item_QtyToBeProduced = 0;


/// Picture Upload
/*
if($item_picture!=""){
	$filename='itemsimages';
	if (!file_exists($filename)) {
		echo"folder does not exist";
		mkdir("./itemsimages", 0700);
}
	move_uploaded_file($_FILES["item_picture"]["tmp_name"],
	"itemsimages/" . $_FILES["item_picture"]["name"]);
	$item_picture="itemsimages/" . $_FILES["item_picture"]["name"];
}*/

/// Picture Upload

//$file = $_FILES['image']['tmp_name'];
//$vItemPicture=$_FILES['image']['name'];


	
$now=date('Y-m-d');

//$sellingprice1base1=ConvertCurrency($currency, $base1, $now, $sellingprice1, $connection);
//$sellingprice1base2=ConvertCurrency($currency, $base2, $now, $sellingprice1, $connection);
//$sellingprice2base1=ConvertCurrency($currency, $base1, $now, $sellingprice2, $connection);
//$sellingprice2base2=ConvertCurrency($currency, $base2, $now, $sellingprice2, $connection);
//$sellingprice3base1=ConvertCurrency($currency, $base1, $now, $sellingprice3, $connection);
//$sellingprice3base2=ConvertCurrency($currency, $base2, $now, $sellingprice3, $connection);
//$sellingprice4base1=ConvertCurrency($currency, $base1, $now, $sellingprice4, $connection);
//$sellingprice4base2=ConvertCurrency($currency, $base2, $now, $sellingprice4, $connection);
//$sellingprice5base1=ConvertCurrency($currency, $base1, $now, $sellingprice5, $connection);
//$sellingprice5base2=ConvertCurrency($currency, $base2, $now, $sellingprice5, $connection);
//$sellingprice6base1=ConvertCurrency($currency, $base1, $now, $sellingprice6, $connection);
//$sellingprice6base2=ConvertCurrency($currency, $base2, $now, $sellingprice6, $connection);

	if($itemtype=='pack'){
		$item_pack=1;
		$item_production=0;
		$reverse_production=0;
	}
	else if($itemtype=='reverse'){
		$item_pack=0;
		$item_production=0;
		$reverse_production=1;
	}
	else if($itemtype=='production'){
		$item_pack=0;
		$item_production=1;
		$reverse_production=0;
	}
	
	if($item_minqty=='')
		$item_minqty=0;
	
	if($item_maxqty=='')
		$item_maxqty=0;	
		
	if($item_withserialno=='')
		$item_withserialno=0;	

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

	if($EvaluateQtyUnit=='')
		$EvaluateQtyUnit=0;	
		
	if($transfer=='')
		$transfer=0;
		

if($sellingprice1base1=='') $sellingprice1base1=0;		
if($sellingprice1base2=='') $sellingprice1base2=0;		
if($sellingprice2base1=='') $sellingprice2base1=0;		
if($sellingprice2base2=='') $sellingprice2base2=0;		
if($sellingprice3base1=='') $sellingprice3base1=0;		
if($sellingprice3base2=='') $sellingprice3base2=0;		
if($sellingprice4base1=='') $sellingprice4base1=0;
if($sellingprice4base2=='') $sellingprice4base2=0;
if($sellingprice5base1=='') $sellingprice5base1=0;
if($sellingprice5base2=='') $sellingprice5base2=0;
if($sellingprice6base1=='') $sellingprice6base1=0;
if($sellingprice6base2=='') $sellingprice6base2=0;



if($Module_AutoItemcode==1 and $mainmode=='insert' and $item_code=='') {

$item_code = Get_AutoItemCode($subgroup_code,$group_code,$category_code, $remaininglength,$connection);

 
}

		
$item_code=trim($item_code);
//echo $item_code;exit;

if($mainmode=='checkduplicate'){
	$query="select count(*) from items where item_code='".$item_code."' ";
		
	if($item_id != '')
		$query = $query. " and item_id != '".$item_id."'";
			
	$result=mysql_query($query, $connection);
	$row=mysql_fetch_row($result);
	$rowcount=$row[0];

	if($rowcount > 0){
		$message="Item Code Already exists.";
	}
}

if($mainmode=='insert'){

		fbegin();
		$item_id = get_nextsequence('Item_Increment','',$connection);
		fcommit();
		
	$query_items="insert into items (item_id,Item_Code,Item_Unit,Group_code,SubGroup_Code,Item_tax,item_printed,Project_Code,Item_tax1,Item_TTCinclude,".
				"Item_tax2,Item_tax3,ITEM_ACTIVE,Item_tax4,Item_Remark,Currency_code,Item_tax5,Item_Vat,Item_Description,item_location,item_BelongsToGroup,Item_CostMethod,Item_UnitSalesDesc,
				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,item_pack,Item_ReverseProduction,Item_Production,item_promotion,Item_NonStock,
				Item_Weight,ITEM_MINQTY,ITEM_MAXQTY,item_withserialno,Item_ModifySellingPrice,EvaluateQtyUnit,item_transfer,item_barcode,item_barcode2,item_barcode3,Item_SemiFinished, 
				Item_UnitPurchaseDesc, Item_Volume,Item_NetWeight, Item_Color, item_lastcostprice, item_disporder, item_vattype, Owner_Branch)
				values('".$item_id."','".$item_code."','".$item_quantity."',$group_code,$subgroup_code,'".$item_tax1."',$item_print,$project_code,'".$item_tax2."',$ttc_include,".
				"'".$item_tax3."','".$item_tax4."','".$item_active."','".$item_tax5."','".$item_remark."','".$currency."','".$item_tax6."','".$item_vat."','".$item_description."','".$item_location."',$belongstogroup,$cost,'".$item_unitsales."',
				$sellingprice1,$sellingprice1base1,$sellingprice1base2,
				$sellingprice2,$sellingprice2base1,$sellingprice2base2,
				$sellingprice3,$sellingprice3base1,$sellingprice3base2,
				$sellingprice4,$sellingprice4base1,$sellingprice4base2,
				$sellingprice5,$sellingprice5base1,$sellingprice5base2,
				$sellingprice6,$sellingprice6base1,$sellingprice6base2,'".$item_pack."','".$reverse_production."','".$item_production."','".$item_promotion."','".$nonstock_item."',
				'".$item_weight."','$item_minqty','$item_maxqty','".$item_withserialno."','".$Item_ModifySellingPrice."','".$EvaluateQtyUnit."','".$transfer."',
				'".$item_barcode."','".$item_barcode2."','".$item_barcode3."','$item_semifinished', '".$item_unitpurchase."', '".$item_volume."', 
				'".$item_netweight."','".$item_color."', $item_lastcostprice, '".$item_disporder."', $item_vattype, '".$Setup_Branch."')";

	//echo$query_items;exit;			
	$result_items=mysql_query($query_items,$connection);
	$message= mysql_error();
	/*if($message==''){
		$FileName='itemfile';
		copytotextfile($connection,$FileName,$item_id);
		
	}*/	
	
	if ($result_items) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'I','ITEMS','',$item_code,$Setup_Branch);
		}
	}	
}

if($mainmode=='calculateaverage'){


function Get_CostPrice($PItemCode, $PItemCurr, $PCostMethod, $PDate, $PCurrCode, $PCurBase1, $PCurBase2, $connection) {

	$ItemCost = 0;
			
	if ($PCostMethod == 1) {
		$query = "SELECT ifNull(GetLastValuesFunc('".$PCurBase1."', '".$PCurBase2."', '".$PItemCode."'),0) From Dual ";
		$result = selectData($connection, $query);
		//echo $query;
		$ItemCost = $result[0];
		$ItemCost = ConvertCurrency($PItemCurr, $PCurrCode, ($PDate), $ItemCost, $connection);
	}
	else if ($PCostMethod == 0) {
		$query = "SELECT ifNull(MeanCostCur('".$PItemCode."', '".($PDate)."', 1, '".$PCurBase1."', '".$PCurrCode."'),0) From Dual ";
		$result = selectData($connection, $query);
		//echo $query;
		$ItemCost = $result[0];
	}

	Return	$ItemCost;
}

function displayToday(){
	return strftime("%Y")."-".strftime("%m")."-".strftime("%d");
}


	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$currency_code."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$currency_code."' )";
	$result = selectData($connection, $query);
	$rate_dt = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$rate_dt1 = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$rate_dt2 = $result[0];
	

$ItemCode   = $_POST["ItemCode"]; if ($ItemCode == ""){$ItemCode = $_GET["ItemCode"];}
$currency_code   = $_POST["currency_code"]; if ($currency_code == ""){$currency_code = $_GET["currency_code"];}

$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), Currency_Code, ".
						 " ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0), ifNull(Item_Unit,0) ".
						 " FROM Items WHERE Item_Code = '".$ItemCode."'";
			$sub_result = selectData($connection, $sub_query);
			$ItemCostMethod  = $sub_result[5];	
			$vAdjDate         = displayToday();
			
$vPrice      = Get_CostPrice($ItemCode, $currency_code, $ItemCostMethod, $vAdjDate, $currency_code, $base1, $base2, $connection);
$vPriceBase1 = ($vPrice*$rate_dt)/$rate_dt1;
$vPriceBase2 = ($vPrice*$rate_dt)/$rate_dt2;

echo number_format($vPrice, $DecimalBase)."[BRK]".number_format($vPriceBase1, $DecimalBase1)."[BRK]".number_format($vPriceBase2, $DecimalBase2);

exit;
}

//echo $mainmode;
if($mainmode=='edit'){

//echo $mainmode;
	
	$query_items="update items set  Item_Code='".$item_code."',
									Item_Unit='".$item_quantity."',
									Group_code=$group_code,
									SubGroup_Code=$subgroup_code,
									Item_tax='".$item_tax1."',
									item_printed=$item_print,
									Project_Code=$project_code,
									Item_tax1='".$item_tax2."',
									Item_TTCinclude=$ttc_include,
									Item_tax2='".$item_tax3."',
									Item_tax3='".$item_tax4."',
									ITEM_ACTIVE='".$item_active."',
									Item_tax4='".$item_tax5."',
									Item_Remark='".$item_remark."',
									Currency_code='".$currency."',
									Item_tax5='".$item_tax6."',
									Item_Vat='".$item_vat."',
									item_vattype=$item_vattype,
									Item_Description='".$item_description."',
									item_location='".$item_location."',
									Item_CostMethod=$cost,";
										
									if($item_active==0 && $itemactive==1)
										$query_items=$query_items."item_inactivedate=now(),";
									else if($item_active==1 && $itemactive==0)
										$query_items=$query_items."item_inactivedate=null,";
					
									$query_items=$query_items."Item_UnitSalesDesc='".$item_unitsales."', Item_UnitPurchaseDesc='".$item_unitpurchase."',
									Item_SellingPrice1='$sellingprice1',
									Item_SellingPrice1Base1='$sellingprice1base1',
									Item_SellingPrice1Base2='$sellingprice1base2',
									Item_SellingPrice2='$sellingprice2',
									Item_SellingPrice2Base1='$sellingprice2base1',
									Item_SellingPrice2Base2='$sellingprice2base2',
									Item_SellingPrice3='$sellingprice3',
									Item_SellingPrice3Base1='$sellingprice3base1',
									Item_SellingPrice3Base2='$sellingprice3base2',
									Item_SellingPrice4='$sellingprice4',
									Item_SellingPrice4Base1='$sellingprice4base1',
									Item_SellingPrice4Base2='$sellingprice4base2',
									Item_SellingPrice5='$sellingprice5',
									Item_SellingPrice5Base1='$sellingprice5base1',
									Item_SellingPrice5Base2='$sellingprice5base2',
									Item_SellingPrice6='$sellingprice6',
									Item_SellingPrice6Base1='$sellingprice6base1',
									Item_SellingPrice6Base2='$sellingprice6base2',
									item_pack='".$item_pack."',
									Item_ReverseProduction='".$reverse_production."',
									Item_Production='".$item_production."',
									item_promotion='".$item_promotion."',
									Item_NonStock='".$nonstock_item."',
									Item_Weight='".$item_weight."',
									Item_NetWeight='".$item_netweight."',
									Item_Volume='".$item_volume."',
									item_disporder='".$item_disporder."',
									Item_Color='".$item_color."',
									ITEM_MINQTY='$item_minqty',
									ITEM_MAXQTY='$item_maxqty',
									item_withserialno='".$item_withserialno."',
									Item_ModifySellingPrice='".$Item_ModifySellingPrice."',
									EvaluateQtyUnit='".$EvaluateQtyUnit."',
									item_transfer='".$transfer."',
									item_barcode='".$item_barcode."',
									item_barcode2='".$item_barcode2."',
									item_barcode3='".$item_barcode3."',
									Item_SemiFinished='$item_semifinished',
									item_lastcostprice = $item_lastcostprice
					                where item_id='".$item_id."'";
	
	//echo $query_items;exit;
	
	SubmittoHistory(	 	$item_id,$_SESSION['username'],$currency
							,$sellingprice1,$sellingprice1base1,$sellingprice1base2
							,$sellingprice2,$sellingprice2base1,$sellingprice2base2
							,$sellingprice3,$sellingprice3base1,$sellingprice3base2
							,$sellingprice4,$sellingprice4base1,$sellingprice4base2
							,$sellingprice5,$sellingprice5base1,$sellingprice5base2
							,$sellingprice6,$sellingprice6base1,$sellingprice6base2
						,$connection);
						
						
	$result_items=mysql_query($query_items,$connection);
	$message= mysql_error();
	
	
						


				
	if ($result_items) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}
	
	/*if($message==''){
		$FileName='itemfile';
		copytotextfile($connection,$FileName,$item_id);
	}	*/
	//exit;		
}

if($mainmode=='uploadimage' && $item_id != ''){

	if (isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) { 

		$image_name = addslashes($_FILES['photo']['name']);
		$image_size = getimagesize($_FILES['photo']['tmp_name']);
		$image_type =$_FILES['photo']['type'];
		//	echo$_FILES['photo']['size'];
			
		if ($image_size == FALSE) {
			$error['photo'] = "That's not an image.";
		
		}
		else {
			if ($_FILES['photo']['size'] > 204800) {
				$error['photo'] = "Image is too large.";
			}
			else {
				$image = addslashes(file_get_contents($_FILES['photo']['tmp_name']));
			}
		}

		//echo $image; exit;
		if($image != '') {
			$query_items="Update Items Set Item_picture='$image' Where item_id='".$item_id."'";
			$result_items=mysql_query($query_items,$connection);
		}	
	}
}


if($mainmode=='delete'){
	$query = "select item_code from items where item_id='".$itemid."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];

	$deleteitem = "delete from items where item_id='".$itemid."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Item is used .";
		//echo $message;
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'D','ITEMS','',$item_code,$Setup_Branch);
		}
	}
}

if($mainmode=='editbarcode'){
	$query = "select item_code from items where item_id='".$item_id."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];

	$update_barcode="update items set item_barcode='".$item_barcode."',
										item_barcode2='".$item_barcode2."',
										item_barcode3='".$item_barcode3."'
					where item_id='".$item_id."'";

	$result_items=mysql_query($update_barcode,$connection);	
	$message= mysql_error();
	
	if ($result_items) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}

}

if($mainmode=='getsequential'){

	$query_sequential="select max(item_code) from items where item_policy='S'";
	$result_sequential=mysql_query($query_sequential,$connection);	
	$row_sequential=mysql_fetch_row($result_sequential);
	$item_code=$row_sequential[0];
	
	if($item_code=='')
		$item_code=0;
		
	$item_code=$item_code+1;
	
	$query_items="insert into items (item_code,item_policy) values('".$item_code."','S')";
	$result_items=mysql_query($query_items,$connection);
	$item_id=mysql_insert_id();
	$message= mysql_error();
}

if($actionmode=='submitattribute'){

	if($ItemDt_ID==''){
		$query="insert into itemsdt(Item_Code,ItemParam_Code,itemdt_value)
				values ('".$item_code."','".$attribute_code."','".$attribute_value."')";
		$result=mysql_query($query,$connection);
		$message=mysql_error();
	
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($ItemDt_ID!=''){
		$query="update itemsdt set 
								ItemParam_Code='".$attribute_code."',
								itemdt_value='".$attribute_value."'
								
				where ItemDt_ID='".$ItemDt_ID."'";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		$message=mysql_error();
		
		if ($result) {
			if ($Module_Synchro == 1) {
				$query = "select item_code from itemsdt where ItemDt_ID='".$ItemDt_ID."'";
				$result=mysql_query($query,$connection);
				$rows=mysql_fetch_row($result);
				$item_code=$rows[0];
	
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	
	
	
	$vTabFocus='Attributes';
}

else if($actionmode=='deleteattribute'){
	$query = "select item_code from itemsdt where ItemDt_ID='".$ItemDt_ID."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	
	
	$deleteitem = "delete from itemsdt where ItemDt_ID='".$ItemDt_ID."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Attribute is used .";
		//echo $message;
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}
	
	$vTabFocus='Attributes';
}

else if($actionmode=='submitmanufacture'){

	if($manufacture_code!=$manufacture_codePrv){
		$query="insert into itemmanufacture(Item_Code,Item_ManufactureCode,Item_ManufactureDesc)
				values ('".$item_code."','".$manufacture_code."','".$manufacture_desc."')";
		$result=mysql_query($query,$connection);
		$message=mysql_error();
	
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($manufacture_code==$manufacture_codePrv){
		$query="update itemmanufacture set 
						Item_ManufactureDesc='".$manufacture_desc."'
				where Item_ManufactureCode='".$manufacture_code."'";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		$message=mysql_error();
		
		if ($result) {
			if ($Module_Synchro == 1) {
				$query = "select item_code from itemmanufacture where Item_ManufactureCode='".$manufacture_code."'";
				$result=mysql_query($query,$connection);
				$rows=mysql_fetch_row($result);
				$item_code=$rows[0];
	
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	
	
	$vTabFocus='Manufactured Code';
}

else if($actionmode=='deletemanufacture'){
	$query = "select item_code from itemmanufacture where Item_ManufactureCode='".$manufacture_code."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	
	$deleteitem = "delete from itemmanufacture where Item_ManufactureCode='".$manufacture_code."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Manufacture Code is used .";
		//echo $message;
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}
	
	$vTabFocus='Manufactured Code';
}

else if($actionmode=='submitrebate'){

	if($rebate_id==''){
		$query="insert into itemsrebate(Item_Code, ItemRebate_RangeFrom, ItemRebate_RangeTo, ItemRebate_Per)
				values ('".$item_code."','".$rebate_rangefrom."','".$rebate_rangeto."','".$rebate_per."')";
		$result=mysql_query($query,$connection);
		$message=mysql_error();
	
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($rebate_id!=''){
		$query="update itemsrebate set 
				ItemRebate_RangeFrom='".$rebate_rangefrom."',
				ItemRebate_RangeTo='".$rebate_rangeto."',
				ItemRebate_Per='".$rebate_per."'
				where ItemRebate_Id='".$rebate_id."'";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		$message=mysql_error();
		
		if ($result) {
			if ($Module_Synchro == 1) {
				$query = "select item_code from itemsrebate where ItemRebate_Id='".$rebate_id."'";
				$result=mysql_query($query,$connection);
				$rows=mysql_fetch_row($result);
				$item_code=$rows[0];
	
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	
	
	$vTabFocus='Item Rebate';
}

else if($actionmode=='deleterebate'){
	$query = "select item_code from itemsrebate where ItemRebate_Id='".$rebate_id."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	
	
	$deleteitem = "delete from itemsrebate where ItemRebate_Id='".$rebate_id."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Record in use .";
		//echo $message;
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}
	
	$vTabFocus='Item Rebate';
}

else if($actionmode=='copyreceipes'){
	$query="delete from packdt where item_code='".$item_code."'";
	$result=mysql_query($query,$connection);
	
	if($result){
		$query="insert into packdt (item_code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty)
			select '".$item_code."',Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty from packdt where item_code='".$item_packcode."'";
		
		$result=mysql_query($query,$connection);
		
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
}

else if($actionmode=='submitpack'){

		
	if($Itempackdt=='' && $Itempackwarehouse==''){
		$query="insert into packdt(Item_Code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty,Group_Code)
				values ('".$item_code."','".$item_packcode."','".$item_warehousecode."',$item_packqty,$item_packcost,$item_packfromdate,$item_packtodate,$item_promoqty,'".$item_packgroupcode."')";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		$message=mysql_error();
	
		if ($result) {
			$query="update items set Item_QtyToBeProduced=$Item_QtyToBeProduced where Item_Code = '".$item_code."'";
			$result=mysql_query($query,$connection);
		
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($Itempackdt!='' && $Itempackwarehouse!=''){
		$query="update packdt set 
						Item_CodePackDt='".$item_packcode."',
						Group_Code='".$item_packgroupcode."',
						PackDt_Quantity=$item_packqty,
						PackDt_CostPercentage=$item_packcost,
						PackDt_FromDate=$item_packfromdate,
						PackDt_ToDate=$item_packtodate,
						Packdt_PromoQty=$item_promoqty						
				where Warehouse_Code='".$Itempackwarehouse."' and Item_CodePackDt='".$Itempackdt."' and item_code='".$item_code."'";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		$message=mysql_error();
		
		if ($result) {
			$query="update items set Item_QtyToBeProduced=$Item_QtyToBeProduced where Item_Code = '".$item_code."'";
			$result=mysql_query($query,$connection);
		
			if ($Module_Synchro == 1) {
				$query = "select item_code from packdt where Warehouse_Code='".$Itempackwarehouse."' and Item_CodePackDt='".$Itempackdt."' and item_code='".$item_code."'";
				$result=mysql_query($query,$connection);
				$rows=mysql_fetch_row($result);
				$item_code=$rows[0];
	
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	
	
	
	
	$vTabFocus='Pack';
}

else if($actionmode=='deletepack'){

	$deleteitem = "delete from packdt where Warehouse_Code='".$Itempackwarehouse."' and Item_CodePackDt='".$Itempackdt."' and item_code='".$item_code."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Pack Item is used .";
		//echo $message;
	}
	
	if ($result) {
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
		}
	}
	
	$vTabFocus='Pack';
}

else if($actionmode=='generatebarcode2'){

	$query="call GenerateBarcode2('$CashReg_BarcodeLength')  ";
	//echo$query;exit;
	$result=mysql_query($query,$connection) or die(mysql_error());
}

else if($actionmode=='generatetextfile'){
	$FileName='itemfile';
	copytotextfile($connection,$FileName,$item_id,$barcodeindex,$GeneratedLines);

}


$message = ereg_replace(" ", "%20", $message);

/*if($actionmode=='submitattribute' || $actionmode=='generatebarcode2' || $actionmode=='deletepack' || $actionmode=='submitpack' || $actionmode=='copyreceipes' || $actionmode=='deletemanufacture' || $actionmode=='submitmanufacture'
|| $actionmode=='deleteattribute' || $actionmode=='submitattribute')
header ("Location: ./Form_Items.php?item_id=$item_id&mainmode=editmode&vTabFocus=$vTabFocus&message=".$message);

else 
	header ("Location: ./Form_Items.php?mainmode=&message=".$message);*/

if ($mainmode != 'checkduplicate') {	
	if ($mainmode != 'delete') {
		header ("Location: ./Form_Items.php?item_id=$item_id&mainmode=&vTabFocus=$vTabFocus&HideMenu=".$HideMenu."&message=".$message);
	} 
	else {
		header ("Location: ./Form_Items.php?mainmode=&HideMenu=".$HideMenu."&message=".$message);
	}	
}

$return_arr = array();

$row_array['message'] = $message;
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);
	
mysql_close($connection);
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."<BR>";
	Return	$result[0];

}
function selectData($conn, $query){
	$result = mysql_query($query, $conn);
	$cur = mysql_fetch_row($result);		
	return $cur;
}

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}


function copytotextfile($conn,$FileName,$item_id,$barcodeindex,$GeneratedLines){


	mkdir("./export", 0700);
	$FileHandle = fopen("./export/".$FileName.".txt", 'a') or die("can't open file");

	$query="select rpad(ITEM_CODE,20,' '),rpad(ITEM_DESCRIPTION,100,' '),rpad(ITEM_BARCODE,20,' '),rpad(ITEM_BARCODE2,20,' '),rpad(ITEM_BARCODE3,20,' '), ".
			" rpad(Currency_code,6,' '),lpad(round(ifnull(Item_SellingPrice1,0),2),20,' '),lpad(round(ifnull(Item_SellingPrice1Base1,0),2),20,' '), ".
			" lpad(round(ifnull(Item_SellingPrice1Base2,0),2),20,' ') ".
			" from items where item_id='".$item_id."'";
	//echo$query;exit;
	$result = mysql_query($query, $conn);			
	$row=mysql_fetch_row($result);
	
	$item_code=$row[0];
	$ITEM_DESCRIPTION=$row[1];
	$ITEM_BARCODE=$row[2];
	$ITEM_BARCODE2=$row[3];
	$ITEM_BARCODE3=$row[4]; 
	$Currency_code=$row[5];
	$Item_SellingPrice1=$row[6];
	$Item_SellingPrice1Base1=$row[7];
	$Item_SellingPrice1Base2=$row[8];
	$numberoflines=$row[9];

	$stringData=$item_code.','.$ITEM_DESCRIPTION.',';
	$stringData=$stringData.$barcodeindex.',';
	
	$stringData=$stringData.$ITEM_BARCODE.',';
	$stringData=$stringData.$ITEM_BARCODE2.',';
	$stringData=$stringData.$ITEM_BARCODE3.','.$Currency_code.','.$Item_SellingPrice1.','.$Item_SellingPrice1Base1.','.$Item_SellingPrice1Base2;
	
	for($i=1;$i<=$GeneratedLines;$i++){
	fwrite($FileHandle,$stringData);
	fwrite($FileHandle,"\r\n");
	}
}


function SubmittoHistory($item_id,$username,$currency_code,$sellingprice1,$sellingprice1base1,$sellingprice1base2,$sellingprice2,$sellingprice2base1,$sellingprice2base2
							,$sellingprice3,$sellingprice3base1,$sellingprice3base2,$sellingprice4,$sellingprice4base1,$sellingprice4base2
							,$sellingprice5,$sellingprice5base1,$sellingprice5base2,$sellingprice6,$sellingprice6base1,$sellingprice6base2,$connection){


$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
					from Items where item_id =  ".$item_id;
					
$result=mysql_query($query, $connection) or die( mysql_error());
while($row=mysql_fetch_array($result)){
	extract($row);
}

if($Item_SellingPrice1!=$sellingprice1 or $Item_SellingPrice1Base1!=$sellingprice1base1 or $Item_SellingPrice1Base2!=$sellingprice1base2 or  $Item_SellingPrice2!=$sellingprice2
	or $Item_SellingPrice2Base1!=$sellingprice2base1 or $Item_SellingPrice2Base2!=$sellingprice2base2	or $Item_SellingPrice3!=$sellingprice3
	or $Item_SellingPrice3Base1!=$sellingprice3base1 or $Item_SellingPrice3Base2!=$sellingprice3base2 or $Item_SellingPrice4!=$sellingprice4
	or  $Item_SellingPrice4Base1!=$sellingprice4base1 or $Item_SellingPrice4Base2!=$sellingprice4base2 or $Item_SellingPrice5!=$sellingprice5
	or $Item_SellingPrice5Base1!=$sellingprice5base1 or  $Item_SellingPrice5Base2!=$sellingprice5base2 or $Item_SellingPrice6!=$sellingprice6
	or $Item_SellingPrice6Base1!=$sellingprice6base1 or $Item_SellingPrice6Base2!=$sellingprice6base2
	) {	$changed = 1;}	
	
$query = "select max(ifnull(groupid,0)) + 1 from sellingpricehistory";
$result=mysql_query($query, $connection) or die( mysql_error());
$row=mysql_fetch_array($result);
$sameid = $row[0];
if($sameid=='')
	$sameid = 0;
	
{
if($Item_SellingPrice1!=$sellingprice1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'I',".GetSQLValueString($Item_SellingPrice1, 'double').",".GetSQLValueString($sellingprice1, 'double').",now(),'$currency_code',$sameid)";
	
	$result=mysql_query($query, $connection) or die( mysql_error());
	}		
/*	
if( $Item_SellingPrice1Base1!=$sellingprice1base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice1Base1',".GetSQLValueString($Item_SellingPrice1Base1, 'double').",".GetSQLValueString($sellingprice1base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice1Base2!=$sellingprice1base2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice1Base2',".GetSQLValueString($Item_SellingPrice1Base2, 'double').",".GetSQLValueString($sellingprice1base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
if( $Item_SellingPrice2!=$sellingprice2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'II',".GetSQLValueString($Item_SellingPrice2, 'double').",".GetSQLValueString($sellingprice2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
	/*
if( $Item_SellingPrice2Base1!=$sellingprice2base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice2Base1',".GetSQLValueString($Item_SellingPrice2Base1, 'double').",".GetSQLValueString($sellingprice2base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice2Base2!=$sellingprice2base2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice2Base2',".GetSQLValueString($Item_SellingPrice2Base2, 'double').",".GetSQLValueString($sellingprice2base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
if( $Item_SellingPrice3!=$sellingprice3) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'III',".GetSQLValueString($Item_SellingPrice3, 'double').",".GetSQLValueString($sellingprice3, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}/*
if( $Item_SellingPrice3Base1!=$sellingprice3base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice3Base1',".GetSQLValueString($Item_SellingPrice3Base1, 'double').",".GetSQLValueString($sellingprice3base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice3Base2!=$sellingprice3base2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice3Base2',".GetSQLValueString($Item_SellingPrice3Base2, 'double').",".GetSQLValueString($sellingprice3base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
if( $Item_SellingPrice4!=$sellingprice4) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'IV',".GetSQLValueString($Item_SellingPrice4, 'double').",".GetSQLValueString($sellingprice4, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}/*
if( $Item_SellingPrice4Base1!=$sellingprice4base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice4Base1',".GetSQLValueString($Item_SellingPrice4Base1, 'double').",".GetSQLValueString($sellingprice4base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice4Base2!=$sellingprice4base2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice4Base2',".GetSQLValueString($Item_SellingPrice4Base2, 'double').",".GetSQLValueString($sellingprice4base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
if( $Item_SellingPrice5!=$sellingprice5) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'V',".GetSQLValueString($Item_SellingPrice5, 'double').",".GetSQLValueString($sellingprice5, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}/*
if( $Item_SellingPrice5Base1!=$sellingprice5base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice5Base1',".GetSQLValueString($Item_SellingPrice5Base1, 'double').",".GetSQLValueString($sellingprice5base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice5Base2!=$sellingprice5base2) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice5Base2',".GetSQLValueString($Item_SellingPrice5Base2, 'double').",".GetSQLValueString($sellingprice5base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
if( $Item_SellingPrice6!=$sellingprice6) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'VI',".GetSQLValueString($Item_SellingPrice6, 'double').",".GetSQLValueString($sellingprice6, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}/*
if( $Item_SellingPrice6Base1!=$sellingprice6base1) 
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice6Base1',".GetSQLValueString($Item_SellingPrice6Base1, 'double').",".GetSQLValueString($sellingprice6base1, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}
if( $Item_SellingPrice6Base2!=$sellingprice6base2)
{
	$query = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid)
					values('$username',$item_id,'Item_SellingPrice6Base2',".GetSQLValueString($Item_SellingPrice6Base2, 'double').",".GetSQLValueString($sellingprice6base2, 'double').",now(),'$currency_code',$sameid)";
	$result=mysql_query($query, $connection) or die( mysql_error());
	}*/
}
				
	
//echo $query;						
}

function Get_AutoItemCode($subgroup_code,$group_code,$category_code, $remaininglength,$connection){

$query_setup=" select fieldorder,name from (
				Select category_order fieldorder,'categories' as Name from setup
				union
				Select group_order,'grouping'  from setup
				union
				Select subgroup_order, 'subgroup' from setup
				) q1 order by q1.fieldorder asc";
				//echo $query_setup;
$resultcode= mysql_query($query_setup,$connection) or die( mysql_error());
while($rowsetuptcode=mysql_fetch_array($resultcode)){
	extract($rowsetuptcode);
	
	if($name=='subgroup'  and $subgroup_code!='null'){
		$q = " select substr(if(subgroup_length>0,".$subgroup_code.",''),1,subgroup_length) from subgroup where subgroup_code = ".$subgroup_code." ";
		//echo $q."<br>";
		$resultdt= mysql_query($q,$connection) or die( mysql_error());
		$rowdt=mysql_fetch_array($resultdt);
		$fromsubgroup=$rowdt[0];
		if($item_code=='')
			$item_code=$fromsubgroup;
			else
			$item_code=$item_code."-".$fromsubgroup;
			
			
	}

	if($name=='grouping' and $group_code!='null'){
		$q = " select substr(if(group_length>0,".$group_code.",''),1,group_length) from grouping where group_code = ".$group_code." ";
		//echo $q."<br>";
		$resultdt= mysql_query($q,$connection) or die( mysql_error());
		$rowdt1=mysql_fetch_array($resultdt);
		$fromgroup=$rowdt1[0];
		if($item_code=='')
			$item_code=$fromgroup;
			else
			$item_code=$item_code."-".$fromgroup;
	}

	if($name=='categories' and  $category_code!='null'){
		$q = " select substr(if(category_length>0,".$category_code.",''),1,category_length) from category where category_code = ".$category_code." ";
		//echo $q."<br>";
		$resultdt= mysql_query($q,$connection) or die( mysql_error());
		$rowdt1=mysql_fetch_array($resultdt);
		$fromcategory=$rowdt1[0];
		if($item_code=='')
			$item_code=$fromcategory;
			else
			$item_code=$item_code."-".$fromcategory;
	}
	
}
		$q = "Select concat('".$item_code."','-',LPAD(ifnull(max(replace(item_code , '".$item_code."-','')),1) + 1 , $remaininglength, '0')) from items where item_code like '".$item_code."%'";
	//	echo $q;
	//	exit;
		$resultdt= mysql_query($q,$connection) or die( mysql_error());
		$rowdt1=mysql_fetch_array($resultdt);
		
		
return $rowdt1[0];

}

?>