<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

include("config.inc.php");
include("function.inc.php");
include("Functions_Synchro.php");
include("functions_items.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"];} 
 //echo $currency; exit;

$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_showInSalesReport = $_POST["Item_showInSalesReport"]; if ($Item_showInSalesReport == ""){$Item_showInSalesReport = $_GET["Item_showInSalesReport"];} 
$item_isNotAvailable = $_POST["item_isNotAvailable"]; if ($item_isNotAvailable == ""){$item_isNotAvailable = $_GET["item_isNotAvailable"];} 

$item_code 			= $_POST["item_code"]; if ($item_code == ""){$item_code = $_GET["item_code"];} 
$item_code          = trim(strtoupper($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"];} 
$item_descriptionf1	= $_POST["item_descriptionf1"]; if ($item_descriptionf1 == ""){$item_descriptionf1 = $_GET["item_descriptionf1"];} 
$item_descriptionf2	= $_POST["item_descriptionf2"]; if ($item_descriptionf2 == ""){$item_descriptionf2 = $_GET["item_descriptionf2"];} 
$supplier_code 		= $_POST["supplier_code"]; if ($supplier_code == ""){$supplier_code = $_GET["supplier_code"];} 
$supplier_name 		= $_POST["supplier_name"]; if ($supplier_name == ""){$supplier_name = $_GET["supplier_name"];} 
$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"];} 
$costcent_code 		= $_POST["costcent_code"]; if ($costcent_code == ""){$costcent_code = $_GET["costcent_code"];} 
$costcent_name 		= $_POST["costcent_name"]; if ($costcent_name == ""){$costcent_name = $_GET["costcent_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"];} 
$warehouse_code		= $_POST["warehouse_code"]; if ($warehouse_code == ""){$warehouse_code = $_GET["warehouse_code"];} 
$item_remark 		= $_POST["item_remark"]; if ($item_remark == ""){$item_remark = $_GET["item_remark"];} 
$item_package 		= $_POST["item_package"]; if ($item_package == ""){$item_package = $_GET["item_package"];} 
$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_sgan 		= $_POST["item_sgan"]; if ($item_sgan == ""){$item_sgan = $_GET["item_sgan"];} 



$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_longdescription 	= $_POST["item_longdescription"]; if ($item_longdescription == ""){$item_longdescription = $_GET["item_longdescription"];} 
$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"];} 
$item_minimumprice 	= $_POST["item_minimumprice"]; if ($item_minimumprice == ""){$item_minimumprice = $_GET["item_minimumprice"];}
$item_discountper 	= $_POST["item_discountper"];// if($item_discountper == ""){$item_discountper = $_GET["item_discountper"];}
$item_fixedcost 	= $_POST["item_fixedcost"];// if($item_discountper == ""){$item_discountper = $_GET["item_discountper"];}
//echo "<br><br><br><br>Discount: " . $item_discountper;


$transfer 			= $_POST["transfer"]; if ($transfer == ""){$transfer = $_GET["transfer"];} 
$Item_ModifySellingPrice= $_POST["Item_ModifySellingPrice"]; if ($Item_ModifySellingPrice == ""){$Item_ModifySellingPrice = $_GET["Item_ModifySellingPrice"];} 
$category_code 		= $_POST["category_code"]; if ($category_code == ""){$category_code = $_GET["category_code"];} 
$category_name 		= $_POST["category_name"]; if ($category_name == ""){$category_name = $_GET["category_name"];} 
$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"];} 

$item_businessPt1 = $_POST["item_businessPt1"]; if ($item_businessPt1 == ""){$item_businessPt1 = $_GET["item_businessPt1"];} 
$item_businessPt2 = $_POST["item_businessPt2"]; if ($item_businessPt2 == ""){$item_businessPt2 = $_GET["item_businessPt2"];} 
$item_businessPt3 = $_POST["item_businessPt3"]; if ($item_businessPt3 == ""){$item_businessPt3 = $_GET["item_businessPt3"];} 
$item_businessPt4 = $_POST["item_businessPt4"]; if ($item_businessPt4 == ""){$item_businessPt4 = $_GET["item_businessPt4"];} 
$item_businessPt5 = $_POST["item_businessPt5"]; if ($item_businessPt5 == ""){$item_businessPt5 = $_GET["item_businessPt5"];} 
$item_businessPt6 = $_POST["item_businessPt6"]; if ($item_businessPt6 == ""){$item_businessPt6 = $_GET["item_businessPt6"];} 

$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_warehousecode 	= $_POST["item_warehousecode"]; if ($item_warehousecode == ""){$item_warehousecode = $_GET["item_warehousecode"];} 
$item_warehousedesc 	= $_POST["item_warehousedesc"]; if ($item_warehousedesc == ""){$item_warehousedesc = $_GET["item_warehousedesc"];} 
$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_stage 			= $_POST["item_stage"]; if ($item_stage == ""){$item_stage = $_GET["item_stage"];} 
$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"];} 

$txtitemreducer			 	= $_POST["txtitemreducer"]; 			if ($txtitemreducer == ""){$txtitemreducer = $_GET["txtitemreducer"];} 
$txtitemretarder			= $_POST["txtitemretarder"]; 			if ($txtitemretarder == ""){$txtitemretarder = $_GET["txtitemretarder"];} 

$txtitemShade			 	= $_POST["txtitemShade"]; 				if ($txtitemShade == ""){$txtitemShade = $_GET["txtitemShade"];} 
$txtitemStrength			= $_POST["txtitemStrength"]; 			if ($txtitemStrength == ""){$txtitemStrength = $_GET["txtitemStrength"];} 
$txtitemPacking			 	= $_POST["txtitemPacking"]; 			if ($txtitemPacking == ""){$txtitemPacking = $_GET["txtitemPacking"];} 
$itemViscosityDirect		= $_POST["itemViscosityDirect"]; 		if ($itemViscosityDirect == ""){$itemViscosityDirect = $_GET["itemViscosityDirect"];} 
$itemViscosityReduced		= $_POST["itemViscosityReduced"]; 		if ($itemViscosityReduced == ""){$itemViscosityReduced = $_GET["itemViscosityReduced"];} 

$txtitemgloss			 	= $_POST["txtitemgloss"]; 				if ($txtitemgloss == ""){$txtitemgloss = $_GET["txtitemgloss"];} 
$txtitemAdhesion			= $_POST["txtitemAdhesion"]; 			if ($txtitemAdhesion == ""){$txtitemAdhesion = $_GET["txtitemAdhesion"];} 

$txtitemAlkali			 	= $_POST["txtitemAlkali"]; 				if ($txtitemAlkali == ""){$txtitemAlkali = $_GET["txtitemAlkali"];} 
$txtitemscuff			 	= $_POST["txtitemscuff"]; 				if ($txtitemscuff == ""){$txtitemscuff = $_GET["txtitemscuff"];} 
$item_tax6			 	 	= $_POST["item_tax6"]; 					if ($item_tax6 == ""){$item_tax6 = $_GET["item_tax6"];} 
$item_tax1			 		= $_POST["item_tax1"]; 					if ($item_tax1 == ""){$item_tax1 = $_GET["item_tax1"];} 
$item_tax2			 		= $_POST["item_tax2"]; 					if ($item_tax2 == ""){$item_tax2 = $_GET["item_tax2"];} 
$item_tax3			 		= $_POST["item_tax3"]; 					if ($item_tax3 == ""){$item_tax3 = $_GET["item_tax3"];} 
$item_tax4			 		= $_POST["item_tax4"];	 				if ($item_tax4 == ""){$item_tax4 = $_GET["item_tax4"];} 
$item_tax5				 	= $_POST["item_tax5"]; 					if ($item_tax5 == ""){$item_tax5 = $_GET["item_tax5"];} 
$remaininglength			= $_POST["remaininglength"]; 			if ($remaininglength == ""){$remaininglength = $_GET["remaininglength"];} 
$item_codeexport			= $_POST["item_codeexport"]; 			if ($item_codeexport == ""){$item_codeexport = $_GET["item_codeexport"];} 
$item_descriptionexporten	= $_POST["item_descriptionexporten"]; 	if ($item_descriptionexporten == ""){$item_descriptionexporten = $_GET["item_codeexport"];} 
$item_descriptionexportar	= $_POST["item_descriptionexportar"]; 	if ($item_descriptionexportar == ""){$item_descriptionexportar = $_GET["item_descriptionexportar"];} 
$item_descriptionexportfr	= $_POST["item_descriptionexportfr"]; 	if ($item_descriptionexportfr == ""){$item_descriptionexportfr = $_GET["item_descriptionexportfr"];} 
$item_reducer				= $_POST["item_reducer"]; 				if ($item_reducer == ""){$item_reducer = $_GET["item_reducer"];} 
$currency_code				= $_POST["currency_code"]; 				if ($currency_code == ""){$currency_code = $_GET["currency_code"];} 
$username					= $_POST["username"]; 					if ($username == ""){$username = $_GET["username"];} 
$item_subsequence			= $_POST["item_subsequence"]; 			if ($item_subsequence == ""){$item_subsequence = $_GET["item_subsequence"];} 
$last_SubItemSeq			= $_POST["last_SubItemSeq"]; 			if ($last_SubItemSeq == ""){$last_SubItemSeq = $_GET["last_SubItemSeq"];} 
$vproject					= $_POST["vproject"]; 					if ($vproject == ""){$vproject = $_GET["vproject"];} 
$item_invoiceType			= $_POST["item_invoiceType"]; 			if ($item_invoiceType == ""){$item_invoiceType = $_GET["item_invoiceType"];} 
$item_isCatalogue			= $_POST["item_isCatalogue"]; 			if ($item_isCatalogue == ""){$item_isCatalogue = $_GET["item_isCatalogue"];} 
$item_isFees				= $_POST["item_isFees"]; 				if ($item_isFees == ""){$item_isFees = $_GET["item_isFees"];} 
$itemmobile					= $_POST["itemmobile"]; 				if ($itemmobile == ""){$itemmobile = $_GET["itemmobile"];} 
$Item_withdisc				= $_POST["Item_withdisc"]; 				if ($Item_withdisc == ""){$Item_withdisc = $_GET["Item_withdisc"];} 
$priceByQty					= $_POST["priceByQty"]; 				if ($priceByQty == ""){$priceByQty = $_GET["priceByQty"];} 

if($Item_withdisc == '') $Item_withdisc = 0;
if($priceByQty == '') $priceByQty = 0;

if($item_subsequence != ''){
	$seqlen = strlen($item_subsequence);
	$seqs = str_split($item_subsequence,1);
	$i=1;
	foreach($seqs as $seq){
		if($seq == '#' && $i != $seqlen) $addedseq = '0';
		else if($seq == '#' && $i == $seqlen) $addedseq = '1';
		else if($seq == '*') $addedseq = 'A';
		else if($seq == '-') $addedseq = '-';
		$AddedSeq=$AddedSeq.$addedseq;	
		$i++;
	}
}

if($last_SubItemSeq != '') $AddedSeq = $last_SubItemSeq;

if($AddedSeq == '') $AddedSeq = "NULL";
else $AddedSeq = "'".$AddedSeq."'";
//echo $txtitemreducer; exit;

/// Ereg Replace

$item_remark = ereg_replace("'", "\'", trim($item_remark));
$item_package = ereg_replace("'", "\'", trim($item_package));
$item_description   = ereg_replace("'", "\'", trim($item_description));
$item_descriptionf1 = ereg_replace("'", "\'", trim($item_descriptionf1));
$item_descriptionf2 = ereg_replace("'", "\'", trim($item_descriptionf2));
$item_longdescription = ereg_replace("'", "\'", trim($item_longdescription));

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

if($item_isCatalogue == '') $item_isCatalogue = 0;
if($item_isFees == '') 		$item_isFees = 0;
if($itemmobile == '') 		$itemmobile = 0;

if($item_fixedcost == '') $item_fixedcost = 0;
$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

/// Belongs to group
$query_login="select login_belongstogrp, user_name, language 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];
$username = $row_login[1];
$language = $row_login[2];


$querylang="select language, buttonclear, save, print, find, clear, results, page,	Add_button,check_button,remainchar,submit_button,excel
		from ".$_SESSION['dbLabel'].".buttons_label where language='$language' ";


$resultlang=mysql_query($querylang,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlang)){
		//extract($rows);
		
		$buttonclear=$rows[1];
		$save=$rows[2];
		$print=$rows[3];
		$find=$rows[4];
		$clear=$rows[5];
		$results=$rows[6];
		$page=$rows[7];
		$add=$rows[8];
		$check=$rows[9];
		$Remaining=$rows[10];
		$submit_button=$rows[11];
		$excel=$rows[12];
		
	}

//echo $_SESSION['dbName'];

$query_setup=" Select base1 As base1, base2 as base2, Setup_Branch,DecimalBase, DecimalBase1, DecimalBase2,remaining_length as remaininglength, ifnull(Project_FromItems,0) as Project_FromItems,
				ifnull(alwaysClearPage,0) as alwaysClearPage, ifnull(subgroup_autoIncrement,0) as subgroup_autoIncrement 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;

//fetching the name of the current user
$query_user_name = "select User_Name from ".$_SESSION['dbLabel'].".users where user_account='".$_SESSION['useraccount']."'";
$result_user_name = mysql_query($query_user_name, $connection);
$rows_user_name = mysql_fetch_array($result_user_name);
extract($rows_user_name);
	
	
//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 ($actionmode == 'addPriceByQty' ){
	$item_code = $_GET['item_code'];
	$fromqty = $_GET['fromqty'];
	$toqty = $_GET['toqty'];
	$qtyprice = $_GET['qtyprice'];
	$qtyprice1b = $_GET['qtyprice1b'];
	$qtyprice2b = $_GET['qtyprice2b'];
	$priceByQty_id = $_GET['priceByQty_id'];
	$priceByQty = $_GET['priceByQty'];
	$currency = $_GET['currency'];
	
	if($fromqty == '') $fromqty = 0;
	if($toqty == '') $toqty = 0;
	if($qtyprice == '') $qtyprice = 0;
	if($qtyprice1b == '') $qtyprice1b = 0;
	if($qtyprice2b == '') $qtyprice2b = 0;
	if($priceByQty == '') $priceByQty = 0;
	
	$update = "update items set item_priceByQty = '$priceByQty' where item_code = '$item_code'";//echo $update;
	$res = mysql_query($update, $connection);
	
	if($priceByQty_id == ''){
		$ins = "insert into item_priceByQty (item_code, fromQty, toQty, qtyPrice, qtyPriceb1, qtyPriceb2) values 
				('$item_code', $fromqty, $toqty, $qtyprice, $qtyprice1b, $qtyprice2b)";//echo $ins;
		$res = mysql_query($ins, $connection);
		$message = mysql_error();		
	} else {
		$up = "update item_priceByQty set item_code = '$item_code', fromQty = $fromqty, toQty = $toqty, qtyPrice = $qtyprice, 
				qtyPriceb1 = $qtyprice1b, qtyPriceb2 = $qtyprice2b 
				where priceByQty_id = $priceByQty_id ";
		$res = mysql_query($up, $connection);	
		$message = mysql_error();
	}
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	showPriceByQty ($item_code,$priceByQty,$currency, $base1,$base2,$connection);
	exit;
}

if ($actionmode == 'deletePriceByQty' ){
	$item_code = $_GET['item_code'];
	$priceByQty_id = $_GET['priceByQty_id'];
	$priceByQty = $_GET['priceByQty'];
	$currency = $_GET['currency'];
	
	$query = "delete from item_priceByQty where priceByQty_id = $priceByQty_id ";
	$res = mysql_query($query, $connection);	
	$message = mysql_error();
		
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	showPriceByQty ($item_code,$priceByQty,$currency, $base1,$base2,$connection);
	exit;
}	
// Create Item Code from Subgroup 
if ($actionmode == 'subGroupItemCode' && $subgroup_code != '' && $subgroup_autoIncrement == 1 && $item_code == ''){
	$queryseq = "select ifnull(subgroup_itemSequence,0)+1, subgroup_length from subgroup where subgroup_code = '$subgroup_code';";
	$resseq = mysql_query($queryseq,$connection);
	$rowseq = mysql_fetch_row($resseq);
	$seq = $rowseq[0];
	$length = $rowseq[1];
	
	$queryItem = "select concat('$subgroup_code','-',LPAD('$seq','$length',0))";
	$resItem = mysql_query($queryItem,$connection);
	$rowItem = mysql_fetch_row($resItem);
	$message = mysql_error();
	$itemcode = $rowItem[0];
	if ($length == '') $message .= "Subgroup Length is no defined";
	else if ($itemcode == '') $message .= "No Item Code was Created";
	
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	echo $itemcode;
	echo "[BRK]";
	echo $seq;
	exit;
}
// Save Item Option
if ($actionmode == 'saveOpt'){
	
	$opt_id 	= $_GET['opt_id'];
	$ItemCode 	= $_GET['ItemCode'];
	$optCode 	= $_GET['optCode'];
	$optQty 	= $_GET['optQty'];
	
	if ($optQty == '') $optQty = 0;
	
	$ErrorExists = 0;
	//check duplicate item
	$queryChk = "select 1 from item_option where itemOption_code = ".GetSQLValueString($optCode,'text')." and if('$opt_id'='', 1=1, itemOption_id <> '$opt_id') 
					and item_code = '$ItemCode' ";
	$resChk = mysql_query($queryChk, $connection);
	$numRow = mysql_num_rows($resChk);
	
	if ($numRow > 0){
		$ErrorExists = 1;
		$messsage = "Duplicate Item Code. Item Already Exists!";
	}
	
	if ($ErrorExists == 0 && $opt_id == ''){
		$queryins = "insert into item_option (itemOption_code, item_code, itemOption_qty) values (".GetSQLValueString($optCode,'text').", ".GetSQLValueString($ItemCode,'text').", $optQty );";
		$resins = mysql_query($queryins, $connection);
		$messsage = mysql_error();
	}
	
	if ($ErrorExists == 0 && $opt_id != ''){
		$queryup = "update item_option set itemOption_code = ".GetSQLValueString($optCode,'text').", 
						item_code = ".GetSQLValueString($ItemCode,'text').", itemOption_qty =  $optQty 
					where itemOption_id = $opt_id";
		$resup = mysql_query($queryup, $connection);
		$messsage = mysql_error();
	}
	
	echo "[BRK]";
	echo $messsage;
	echo "[BRK]";
	item_option($ItemCode, '', $submit_button, $clear, $connection);
	echo "[BRK]";
exit;
}
if ($actionmode == 'getOpt'){
	$opt_id 	= $_GET['opt_id'];
	$ItemCode 	= $_GET['ItemCode'];
	echo "[BRK]";
	item_option($ItemCode, $opt_id, $submit_button, $clear, $connection);
	echo "[BRK]";
	exit;
}

if ($actionmode == 'deleteOpt'){
	$opt_id 	= $_GET['opt_id'];
	$ItemCode 	= $_GET['ItemCode'];
	
	$querydel = "delete from item_option where itemOption_id = $opt_id";
	$resdel = mysql_query($querydel, $connection);
	$messsage = mysql_error();
	
	echo "[BRK]";
	echo $messsage;
	echo "[BRK]";
	item_option($ItemCode, '', $submit_button, $clear, $connection);
	echo "[BRK]";
	exit;
}
if($actionmode == 'insertcostcentprice'){
	$query = "insert into costcenterPrice (costcenter_code,item_code, min_price) values ('$costcent_codep','$item_code',$min_price);";
	$res = mysql_query($query,$connection);
	echo "[BRK]";
	itemcostcentprice('', $item_code, $connection);
	echo "[BRK]";
	showitemcostcentprice($costcenterprice_id, $item_code, $connection);
	exit;
}
else if($actionmode == 'updatecostcentprice'){
	$query = "update costcenterPrice set costcenter_code = '$costcent_codep', min_price = $min_price where costcenterprice_id = $costcenterprice_id;";
	$res = mysql_query($query,$connection);
	echo "[BRK]";
	itemcostcentprice('', $item_code, $connection);
	echo "[BRK]";
	showitemcostcentprice($costcenterprice_id, $item_code, $connection);
	exit;
}
else if($actionmode == 'getItemCostcenterPrice'){
	echo "[BRK]";
	itemcostcentprice($costcenterprice_id,  $item_code,$connection);
	echo "[BRK]";
	showitemcostcentprice($costcenterprice_id, $item_code, $connection);
	exit;
}
else if($actionmode == 'deleteItemCostcenterPrice'){
	$query = "delete from costcenterPrice where costcenterprice_id = $costcenterprice_id";
	$res = mysql_query($query,$connection);
	echo "[BRK]";
	itemcostcentprice('',  $item_code,$connection);
	echo "[BRK]";
	showitemcostcentprice('',  $item_code,$connection);
	exit;
}
if( $mainmode == 'CopyItem' && $item_code != '' && $itemcopy != ''){
	$query = " select Item_Unit,Ledger_Number,Group_code,SubGroup_Code,Item_tax,item_printed,Project_Code,Item_tax1,Item_TTCinclude,CostCent_Code,Item_tax2,Item_tax3,ITEM_ACTIVE,Item_tax4,Item_Remark,Currency_code,".
			 " Item_tax5,Item_Package,Item_Vat,Item_Description,item_longdescription,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_sgan,ITEM_MAXQTY,item_withserialno,Item_ModifySellingPrice,EvaluateQtyUnit,item_transfer,item_barcode,item_barcode2,item_barcode3,category_code,Item_SemiFinished, Item_WarehouseCode, 
			   Item_UnitPurchaseDesc, Item_Volume, Item_DescriptionF1, Item_DescriptionF2, Item_NetWeight, Item_Color, item_lastcostprice, item_disporder, item_minimumprice, item_vattype, Owner_Branch, item_discountper,
			   item_codeexport,item_descriptionexporten,item_descriptionexportar,item_descriptionexportfr,item_fixedcost,item_reducer,item_retarder, item_Shade,item_Strength,item_Packing,item_ViscosityDirect,
			   item_ViscosityReduced,item_gloss,item_Adhesion,item_Alkali,item_scuff, Item_SubSequence,Item_SysDateTime, item_createdBy, last_SubItemSeq, Item_showInSalesReport,
			   item_businessPt1,item_businessPt2,item_businessPt3,item_businessPt4,item_businessPt5,item_businessPt6, item_gift, item_businessPoint, item_invoiceType, item_isCatalogue, item_isFees, item_mobile, item_class,
			   item_isNotAvailable, ifnull(Item_withdisc,0) as Itemwithdisc, ifnull(item_priceByQty,0) as item_priceByQty
			   from items where item_code = '$itemcopy';";
	$result = mysql_query($query, $connection);
	$rws = mysql_fetch_array($result);
	extract($rws);
	
	if($item_quantity == '') 					$item_quantity 				= $Item_Unit;
	if($supplier_code == '') 					$supplier_code 				= $Ledger_Number;
	if($group_code == '') 						$group_code 				= $Group_code;
	if($subgroup_code == '') 					$subgroup_code 				= $SubGroup_Code;
	if($item_tax1 == '') 						$item_tax1 					= $Item_tax;
	if($item_print == '') 						$item_print 				= $item_printed;
	if($project_code == '') 					$project_code	 			= $Project_Code;
	if($item_tax2 == '') 						$item_tax2 					= $Item_tax1;
	if($Item_TTCinclude == '') 					$Item_TTCinclude 			= $ttc_include;
	if($costcent_code == '') 					$costcent_code 				= $CostCent_Code;
	if($item_tax3 == '') 						$item_tax3 					= $Item_tax2;
	if($item_tax4 == '') 						$item_tax4 					= $Item_tax4;
	if($item_active == '') 						$item_active 				= $ITEM_ACTIVE;
	if($item_tax5 == '') 						$item_tax5 					= $ITEM_ACTIVE;
	if($Item_Remark == '') 						$Item_Remark 				= $item_remark;
	if($currency == '') 						$currency 					= $Currency_code;
	if($item_tax6 == '') 						$item_tax6 					= $Item_tax5;
	if($item_package == '') 					$item_package 				= $Item_Package;
	if($item_vat == '') 						$item_vat	 				= $Item_Vat;
	if($item_description == '') 				$item_description 			= $Item_Description;
	if($item_longdescription == '') 			$item_longdescription 		= $item_longdescription;
	if($cost == '') 							$cost 						= $Item_CostMethod;
	if($item_unitsales == '') 					$item_unitsales 			= $Item_UnitSalesDesc;
	if($sellingprice1 == '') 					$sellingprice1 				= $Item_SellingPrice1;
	if($sellingprice1base1 == '') 				$sellingprice1base1 		= $Item_SellingPrice1Base1;
	if($sellingprice1base2 == '') 				$sellingprice1base2 		= $Item_SellingPrice1Base2;
	if($sellingprice2 == '') 					$sellingprice2 				= $Item_SellingPrice2;
	if($sellingprice2base1 == '') 				$sellingprice2base1 		= $Item_SellingPrice2Base1;
	if($sellingprice2base2 == '') 				$sellingprice2base2 		= $Item_SellingPrice2Base2;
	if($sellingprice3 == '') 					$sellingprice3 				= $Item_SellingPrice3;
	if($sellingprice3base1 == '') 				$sellingprice3base1 		= $Item_SellingPrice3Base1;
	if($sellingprice3base2 == '') 				$sellingprice3base2 		= $Item_SellingPrice3Base2;
	if($sellingprice4 == '') 					$sellingprice4 				= $Item_SellingPrice4;
	if($Item_SellingPrice4Base1 == '') 			$Item_SellingPrice4Base1 	= $Item_SellingPrice4Base1;
	if($sellingprice4base2 == '') 				$sellingprice4base2 		= $Item_SellingPrice4Base2;
	if($sellingprice5 == '') 					$sellingprice5 				= $Item_SellingPrice5;
	if($sellingprice5base1 == '') 				$sellingprice5base1 		= $Item_SellingPrice5Base1;
	if($sellingprice5base2 == '') 				$sellingprice5base2 		= $Item_SellingPrice5Base2;
	if($sellingprice6 == '') 					$sellingprice6 				= $Item_SellingPrice6;
	if($sellingprice6base1 == '') 				$sellingprice6base1 		= $Item_SellingPrice6Base1;
	if($sellingprice6base2 == '') 				$sellingprice6base2 		= $Item_SellingPrice6Base2;
	if($item_pack == '') 						$item_pack 					= $item_pack;
	if($reverse_production == '') 				$reverse_production 		= $Item_ReverseProduction;
	if($item_production == '') 					$item_production 			= $Item_Production;
	if($item_promotion == '') 					$item_promotion 			= $item_promotion;
	if($nonstock_item == '') 					$nonstock_item 				= $Item_NonStock;
	if($item_weight == '') 						$item_weight 				= $Item_Weight;						
	if($item_minqty == '') 						$item_minqty 				= $ITEM_MINQTY;
	
	if($item_sgan == '') 						$item_sgan 				    = $item_sgan;
	
	if($item_maxqty == '') 						$item_maxqty 				= $ITEM_MAXQTY;
	if($item_withserialno == '') 				$item_withserialno 			= $item_withserialno;
	if($Item_ModifySellingPrice == '') 			$Item_ModifySellingPrice 	= $Item_ModifySellingPrice;
	if($EvaluateQtyUnit == '') 					$EvaluateQtyUnit 			= $EvaluateQtyUnit;
	if($transfer == '') 						$transfer 					= $item_transfer;		
	if($item_barcode == '') 					$item_barcode 				= $item_barcode;
	if($item_barcode2 == '') 					$item_barcode2 				= $item_barcode2;
	if($item_barcode3 == '') 					$item_barcode3 				= $item_barcode3;
	if($category_code == '') 					$category_code 				= $category_code;
	if($item_semifinished == '') 				$item_semifinished 			= $Item_SemiFinished;
	if($warehouse_code == '') 					$warehouse_code 			= $Item_WarehouseCode;			
	if($item_unitpurchase == '') 				$item_unitpurchase 			= $Item_UnitPurchaseDesc;
	if($item_volume == '') 						$item_volume 				= $Item_Volume;
	if($item_descriptionf1 == '') 				$item_descriptionf1 		= $Item_DescriptionF1;
	if($item_descriptionf2 == '') 				$item_descriptionf2 		= $Item_DescriptionF2;
	if($item_netweight == '') 					$item_netweight 			= $Item_NetWeight;
	if($item_color == '') 						$item_color 				= $Item_Color;		
	if($item_lastcostprice == '') 				$item_lastcostprice 		= $item_lastcostprice;
	if($item_disporder == '') 					$item_disporder 			= $item_disporder;
	if($item_minimumprice == '') 				$item_minimumprice 			= $item_minimumprice;
	if($item_vattype == '') 					$item_vattype 				= $item_vattype;
	if($Setup_Branch == '') 					$Setup_Branch 				= $Owner_Branch;				
	if($item_discountper == '') 				$item_discountper 			= $item_discountper;			
	if($item_codeexport == '') 					$item_codeexport 			= $item_codeexport;
	if($item_descriptionexporten == '') 		$item_descriptionexporten 	= $item_descriptionexporten;
	if($item_descriptionexportar == '') 		$item_descriptionexportar 	= $item_descriptionexportar;
	if($item_descriptionexportfr == '') 		$item_descriptionexportfr 	= $item_descriptionexportfr;
	if($item_fixedcost == '') 					$item_fixedcost 			= $item_fixedcost;				
	if($txtitemreducer == '') 					$txtitemreducer 			= $item_reducer;		
	if($item_reducer == '') 					$item_reducer 				= $item_retarder;
	if($txtitemShade == '') 					$txtitemShade 				= $item_Shade;
	if($txtitemStrength == '') 					$txtitemStrength 			= $item_Strength;
	if($txtitemPacking == '') 					$txtitemPacking 			= $item_Packing;
	if($itemViscosityDirect == '') 				$itemViscosityDirect 		= $item_ViscosityDirect;				
	if($itemViscosityReduced == '') 			$itemViscosityReduced 		= $item_ViscosityReduced;			
	if($txtitemgloss == '') 					$txtitemgloss 				= $item_gloss;
	if($txtitemAdhesion == '') 					$txtitemAdhesion 			= $item_Adhesion;
	if($txtitemAlkali == '') 					$txtitemAlkali 				= $item_Alkali;
	if($txtitemscuff == '') 					$txtitemscuff 				= $item_scuff;
	if($item_subsequence == '') 				$item_subsequence 			= $Item_SubSequence;

	if($item_businessPt1 == '') 				$item_businessPt1 			= $item_businessPt1;						
	if($item_businessPt2 == '') 				$item_businessPt2 			= $item_businessPt2;						
	if($item_businessPt3 == '') 				$item_businessPt3 			= $item_businessPt3;						
	if($item_businessPt4 == '') 				$item_businessPt4 			= $item_businessPt4;						
	if($item_businessPt5 == '') 				$item_businessPt5 			= $item_businessPt5;						
	if($item_businessPt6 == '') 				$item_businessPt6 			= $item_businessPt6;						
	if($itemclass == '') 						$itemclass 					= $item_class;						
	if($item_isNotAvailable == '') 				$item_isNotAvailable 		= $item_isNotAvailable;						
	if($Item_withdisc == '') 					$Item_withdisc 				= $Itemwithdisc;						
	if($priceByQty == '') 						$priceByQty 				= $item_priceByQty;						

	fbegin();
		$item_id = get_nextsequence('Item_Increment','',$connection);
	fcommit();					
				
	$query_items="insert into items (item_id,Item_Code,Item_Unit,Ledger_Number,Group_code,SubGroup_Code,Item_tax,item_printed,Project_Code,Item_tax1,Item_TTCinclude,CostCent_Code,".
				"Item_tax2,Item_tax3,ITEM_ACTIVE,Item_tax4,Item_Remark,Currency_code,Item_tax5,Item_Package,Item_Vat,Item_Description,item_longdescription,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_sgan,ITEM_MAXQTY,item_withserialno,Item_ModifySellingPrice,EvaluateQtyUnit,item_transfer,item_barcode,item_barcode2,item_barcode3,category_code,Item_SemiFinished, Item_WarehouseCode, 
				Item_UnitPurchaseDesc, Item_Volume, Item_DescriptionF1, Item_DescriptionF2, Item_NetWeight, Item_Color, item_lastcostprice, item_disporder, item_minimumprice, item_vattype, Owner_Branch, item_discountper,item_codeexport,item_descriptionexporten,item_descriptionexportar,
				item_descriptionexportfr,item_fixedcost,item_reducer,item_retarder, item_Shade,item_Strength,item_Packing,item_ViscosityDirect,item_ViscosityReduced,item_gloss,item_Adhesion,item_Alkali,item_scuff, 
				Item_SubSequence,Item_SysDateTime, item_createdBy, last_SubItemSeq, Item_showInSalesReport, item_businessPt1,item_businessPt2,item_businessPt3,item_businessPt4,item_businessPt5,item_businessPt6,
				item_gift, item_businessPoint, item_invoiceType, item_isCatalogue, item_isFees, item_mobile, item_class, item_isNotAvailable, Item_withdisc, item_priceByQty)
				values('".$item_id."','".trim(strtoupper($item_code))."','".$item_quantity."',".strformat($supplier_code).",".strformat($group_code).",".strformat($subgroup_code).",".strformat($item_tax1).",".strformat($item_print).",".strformat($project_code).",".strformat($item_tax2).",".strformat($ttc_include).",".strformat($costcent_code).",".
				"".strformat($item_tax3).",".strformat($item_tax4).",".strformat($item_active).",".strformat($item_tax5).",".strformat($item_remark).",'".$currency."',".strformat($item_tax6).",".strformat($item_package).",'".$item_vat."',".strformat($item_description).",".strformat($item_longdescription).",$belongstogroup,".strformat($cost).",".strformat($item_unitsales).",
				".strformat($sellingprice1).",".strformat($sellingprice1base1).",".strformat($sellingprice1base2).",
				".strformat($sellingprice2).",".strformat($sellingprice2base1).",".strformat($sellingprice2base2).",
				".strformat($sellingprice3).",".strformat($sellingprice3base1).",".strformat($sellingprice3base2).",
				".strformat($sellingprice4).",".strformat($sellingprice4base1).",".strformat($sellingprice4base2).",
				".strformat($sellingprice5).",".strformat($sellingprice5base1).",".strformat($sellingprice5base2).",
				".strformat($sellingprice6).",".strformat($sellingprice6base1).",".strformat($sellingprice6base2).",".strformat($item_pack).",".strformat($reverse_production).",".strformat($item_production).", ".strformat($item_promotion).",".strformat($nonstock_item).",
				".strformat($item_weight).",".strformat($item_minqty).",".strformat($item_sgan).",".strformat($item_maxqty).",".strformat($item_withserialno).",".strformat($Item_ModifySellingPrice).", ".strformat($EvaluateQtyUnit).",".strformat($transfer).",
				".strformat($item_barcode).", ".strformat($item_barcode2).",".strformat($item_barcode3).",".strformat($category_code).",".strformat($item_semifinished).",".strformat($warehouse_code).", ".strformat($item_unitpurchase).", ".strformat($item_volume).", 
				".strformat($item_descriptionf1).",".strformat($item_descriptionf2).", ".strformat($item_netweight).",".strformat($item_color).", ".strformat($item_lastcostprice).", ".strformat($item_disporder).", ".strformat($item_minimumprice).", ".strformat($item_vattype).", ".strformat($Setup_Branch).", ".$item_discountper."
				, ".strformat($item_codeexport)."
				, ".strformat($item_descriptionexporten)."
				, ".strformat($item_descriptionexportar)."
				, ".strformat($item_descriptionexportfr)."
				, ".strformat($item_fixedcost)."
				, ".strformat($txtitemreducer).", ".strformat($item_reducer).",  ".strformat($txtitemShade).", ".strformat($txtitemStrength).", ".strformat($txtitemPacking).", ".strformat($itemViscosityDirect).", ".strformat($itemViscosityReduced).",".strformat($txtitemgloss).", ".strformat($txtitemAdhesion).",".strformat($txtitemAlkali).", ".strformat($txtitemscuff).", ".strformat($item_subsequence)."
				, now(), '".$_SESSION['useraccount']."', $AddedSeq, $Item_showInSalesReport, ".strformat($item_businessPt1).", ".strformat($item_businessPt2).",".strformat($item_businessPt3)."
				,".strformat($item_businessPt4).", ".strformat($item_businessPt5).",".strformat($item_businessPt6).",".strformat($item_gift).", ".strformat($item_businessPoint)."
				, ".strformat($item_invoiceType).",".strformat($item_isCatalogue).", ".strformat($item_isFees).", ".strformat($item_mobile).", ".strformat($itemclass).", ".strformat($item_isNotAvailable).", ".strformat($Item_withdisc).",
				".strformat($priceByQty)."
				)"; //echo $query_items;echo "<br>";
	$result_items = mysql_query($query_items,$connection);
	if($config['log_file'] == 1){
		$transType = "I";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '".trim(strtoupper($item_code))."', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'items', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	if ($result_items) {
		
		
		$queryparam = "	insert into itemsdt (Item_Code, ItemParam_Code)
						select '".$item_code."',ItemParam_Code
						from itemsparam
						where ItemParam_Code not in (select ItemParam_Code from itemsdt where Item_Code = '".$item_code."') "; //echo $queryparam;echo "<br>";
		$resparam = mysql_query($queryparam, $connection);
			
		if($Project_FromItems == 1 && $vproject == 1){	
			$maxproj = "select ifnull(max(project_id),0)+1 from project";
			$resmax = mysql_query($maxproj,$connection);
			$rwmax = mysql_fetch_row($resmax);
			$project_id = $rwmax[0];
			
			$query_project = "insert into project (Project_Code, Project_Name, Project_Deactivate, Project_date, Project_BelongsToGroup, Synchronized,Project_posted, project_id)
							values ('".$item_code."','".$item_description."',0,now(),0,0,0,$project_id)"; //echo $query_project;echo "<br>";exit;
			$resproj = mysql_query($query_project, $connection);
			$upd = "update items set Project_Code = '$item_code' where item_code = '$item_code';";
			$res = mysql_query($upd, $connection);
		
			
		}
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'I','ITEMS','',$item_code,$Setup_Branch);
		}
	}	
	//exit;			
} 


$costcent_code = "".$costcent_code;
$project_code = "".$project_code;
 
if($costcent_code == '')  $costcent_code= "NULL" ;
else  $costcent_code="'$costcent_code'";

if($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(empty($supplier_code))  $supplier_code="NULL";
else  $supplier_code="'$supplier_code'";

if(empty($category_code))  $category_code="NULL";
else  $category_code="'$category_code'";

if(empty($warehouse_code))  $warehouse_code="NULL";
else  $warehouse_code="'$warehouse_code'";

if($item_quantity=='')	$item_quantity=1;	
if ($txtitemPacking=='') $txtitemPacking=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_businessPt1=='')	$item_businessPt1='0';	
if($item_businessPt2=='')	$item_businessPt2='0';
if($item_businessPt3=='')	$item_businessPt3='0';
if($item_businessPt4=='')	$item_businessPt4='0';
if($item_businessPt5=='')	$item_businessPt5='0';
if($item_businessPt6=='')	$item_businessPt6='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($item_minimumprice=='')	$item_minimumprice='0';
if($item_discountper=='') $item_discountper='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;


if($item_subsequence == '') $item_subsequence = "NULL";
else $item_subsequence = "'".$item_subsequence."'";

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

	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_sgan=='')
		$item_sgan=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($txtitemPacking == '') $txtitemPacking = "NULL";
else $txtitemPacking = 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($mainmode == 'AddCode'){
$itemcode = $_GET['itemcode'];
	$query = "select item_sequence from setup;";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	$item_sequences = '&'.$row[0];
	$item_sequences++;
	$item_sequences = explode('&', $item_sequences);
	$item_sequence = $item_sequences[1];
	$queryup = "update setup set item_sequence = '$item_sequence';";
	$res = mysql_query($queryup, $connection);
	echo "[BRK]";

	echo $itemcode.$item_sequence;
	echo "[BRK]";
	echo $item_sequence;
	exit;
}


if($Module_AutoItemcode==1 && $mainmode=='insert' && $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();
		
		if($group_code!=''){
			$q = "select Group_discountPer from grouping where group_code = ".$group_code." ";
//			echo $q."<br>";
//			exit;
			$resultdt= mysql_query($q,$connection) or die( mysql_error());
			$rowdt1=mysql_fetch_array($resultdt);
			$discper=$rowdt1[0];
			if($discper>0)
				$item_discountper = $discper;
		}
		
	if($item_fixedcost=='')	
		$item_fixedcost="NULL";
		
	
	$query_items="insert into items (item_id,Item_Code,Item_Unit,Ledger_Number,Group_code,SubGroup_Code,Item_tax,item_printed,Project_Code,Item_tax1,Item_TTCinclude,CostCent_Code,".
				"Item_tax2,Item_tax3,ITEM_ACTIVE,Item_tax4,Item_Remark,Currency_code,Item_tax5,Item_Package,Item_Vat,Item_Description,item_longdescription,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_sgan,ITEM_MAXQTY,item_withserialno,Item_ModifySellingPrice,EvaluateQtyUnit,item_transfer,item_barcode,item_barcode2,item_barcode3,category_code,Item_SemiFinished, Item_WarehouseCode, 
				Item_UnitPurchaseDesc, Item_Volume, Item_DescriptionF1, Item_DescriptionF2, Item_NetWeight, Item_Color, item_lastcostprice, item_disporder, item_minimumprice, item_vattype, Owner_Branch, item_discountper,item_codeexport,item_descriptionexporten,item_descriptionexportar,
				item_descriptionexportfr,item_fixedcost,item_reducer,item_retarder, item_Shade,item_Strength,item_Packing,item_ViscosityDirect,item_ViscosityReduced,item_gloss,item_Adhesion,item_Alkali,item_scuff, 
				Item_SubSequence,Item_SysDateTime, item_createdBy, last_SubItemSeq, Item_showInSalesReport, item_businessPt1,item_businessPt2,item_businessPt3,item_businessPt4,item_businessPt5,item_businessPt6,
				item_gift, item_businessPoint, item_invoiceType, item_isCatalogue, item_isFees, item_mobile, item_class, item_isNotAvailable,item_costper, Item_withdisc,
				item_priceByQty)
				values('".$item_id."','".trim(strtoupper($item_code))."','".$item_quantity."',$supplier_code,$group_code,$subgroup_code,'".$item_tax1."',$item_print,$project_code,'".$item_tax2."',$ttc_include,$costcent_code,".
				"'".$item_tax3."','".$item_tax4."','".$item_active."','".$item_tax5."','".$item_remark."','".$currency."','".$item_tax6."','".$item_package."','".$item_vat."','".$item_description."','".$item_longdescription."',$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_sgan','$item_maxqty','".$item_withserialno."','".$Item_ModifySellingPrice."','".$EvaluateQtyUnit."','".$transfer."',
				'".$item_barcode."','".$item_barcode2."','".$item_barcode3."',$category_code,'$item_semifinished', $warehouse_code, '".$item_unitpurchase."', '".$item_volume."', 
				'".$item_descriptionf1."','".$item_descriptionf2."', '".$item_netweight."','".$item_color."', $item_lastcostprice, '".$item_disporder."', $item_minimumprice, $item_vattype, '".$Setup_Branch."', " . $item_discountper . "
				, '".$item_codeexport."'
				, '".$item_descriptionexporten."'
				, '".$item_descriptionexportar."'
				, '".$item_descriptionexportfr."'
				, ".$item_fixedcost."
				, '$txtitemreducer', '$item_reducer',  '$txtitemShade', '$txtitemStrength', $txtitemPacking, '$itemViscosityDirect', '$itemViscosityReduced','$txtitemgloss', '$txtitemAdhesion','$txtitemAlkali', '$txtitemscuff', $item_subsequence
				, now(), '".$_SESSION['useraccount']."', $AddedSeq, $Item_showInSalesReport, '$item_businessPt1', '$item_businessPt2','$item_businessPt3','$item_businessPt4','$item_businessPt5','$item_businessPt6'
				, ".strformat($item_gift).", ".strformat($item_businessPoint).", ".strformat($item_invoiceType).",".strformat($item_isCatalogue).", ".strformat($item_isFees).", ".strformat($itemmobile).", ".strformat($itemclass)."
				, ".strformat($item_isNotAvailable).", '$item_costper', '$Item_withdisc','$priceByQty')";

			//echo $query_items;exit;	
	$result_items=mysql_query($query_items,$connection);
	$message= mysql_error();
	if($message == ''){
			if ($subgroupItemSeq != '' && $subgroup_autoIncrement == 1 && $subgroup_code != "NULL"){
				$up = "update subgroup set subgroup_itemSequence = '$subgroupItemSeq' where subgroup_code = $subgroup_code ";
				$res = mysql_query($up,$connection);
			}
		 
		 
	 
		 
		 
			 $item__code = trim(strtoupper($item_code));
			 
			 
				 


		
// send notification
		$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
												where notification_name='item_created' and ifnull(view_access,0) = 1 ";
		$resacc = mysql_query($queryacc, $connection);
		
		
									
		//echo $queryacc;
		while ($rwacc = mysql_fetch_array($resacc)){
		$querynot .= "call sendNotification('item_created', '$rwacc[0]', $rwacc[1], $rwacc[2], $item_id, '" .$_SESSION['useraccount'] ."')  ";
		 // echo $querynot;exit;
										
		
		}		
		
			$resnot = mysql_query($querynot, $connection);
			//echo $querynot; exit;
// end send notification		
		 
		 // end by rod
		
		$itemSeq = $_POST['itemSeq'];
		if($itemSeq != ''){
			$queryseq = "update setup set item_sequence = '$itemSeq';";
			$resseq = mysql_query($queryseq, $connection);
		}
	}
	if($config['log_file'] == 1){
		$transType = "I";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '".trim(strtoupper($item_code))."', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'items', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	
	
	if ($result_items) {
		$queryparam = "	insert into itemsdt (Item_Code, ItemParam_Code)
						select '".$item_code."',ItemParam_Code
						from itemsparam
						where ItemParam_Code not in (select ItemParam_Code from itemsdt where Item_Code = '".$item_code."') "; //echo $queryparam;exit;
		$resparam = mysql_query($queryparam, $connection);
		
	if($Project_FromItems == 1 && $vproject == 1){	
		$maxproj = "select ifnull(max(project_id),0)+1 from project";
		$resmax = mysql_query($maxproj,$connection);
		$rwmax = mysql_fetch_row($resmax);
		$project_id = $rwmax[0];
		
		$query_project = "insert into project (Project_Code, Project_Name, Project_Deactivate, Project_date, Project_BelongsToGroup, Synchronized,Project_posted, project_id)
						values ('".$item_code."','".$item_description."',0,now(),0,0,0,$project_id)"; //echo $query_project;exit;
		$resproj = mysql_query($query_project, $connection);
	}
		if ($Module_Synchro == 1) {
			InsertSynchroLoc($connection,'I','ITEMS','',$item_code,$Setup_Branch);
		}
	}	
$querysellingprice = "insert into clientssellingprice (clientssellingprice_code, clientssellingprice_amount, clientssellingprice_currency, clientssellingprice_amountb1,
						  clientssellingprice_amountb2, clientssellingprice_amount2, clientssellingprice_amount2b1, clientssellingprice_amount2b2, clientssellingprice_amount3,
						  clientssellingprice_amount3b1, clientssellingprice_amount3b2, clientssellingprice_amount4, clientssellingprice_amount4b1, clientssellingprice_amount4b2,
						  clientssellingprice_amount5, clientssellingprice_amount5b1, clientssellingprice_amount5b2, clientssellingprice_amount6, clientssellingprice_amount6b1,
						  clientssellingprice_amount6b2 , clientssellingprice_default) values ('$item_code' , $sellingprice1 , '$currency' , $sellingprice1base1,$sellingprice1base2, $sellingprice2,$sellingprice2base1,$sellingprice2base2,
				$sellingprice3,$sellingprice3base1,$sellingprice3base2,
				$sellingprice4,$sellingprice4base1,$sellingprice4base2,
				$sellingprice5,$sellingprice5base1,$sellingprice5base2,
				$sellingprice6,$sellingprice6base1,$sellingprice6base2 , 1)";
				
	$sellpriceresult = mysql_query ($querysellingprice , $connection);			
				//echo $querysellingprice; exit; 
	 
	}

if($mainmode=='calculateaverage'){


function Get_CostPrice($PItemCode,$PWHCode, $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) {
		if ($PWHCode=='') {
				$query = "SELECT ifNull(MeanCostCur('".$PItemCode."', '".($PDate)."', 1, '".$PCurBase1."', '".$PCurrCode."'),0) From Dual ";
		} else {
				$query = "SELECT ifNull(MeanCostCurByWH('".$PItemCode."', '".($PDate)."', 1, '".$PCurBase1."', '".$PCurrCode."','".$PWHCode."'),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();
	if ($WHCode=='') {			
		$vPrice      = Get_CostPrice($ItemCode,$WHCode, $currency_code, $ItemCostMethod, $vAdjDate, $currency_code, $base1, $base2, $connection);
	} else {
		$vPrice      = Get_CostPrice($ItemCode,$WHCode, $currency_code, $ItemCostMethod, $vAdjDate, $currency_code, $base1, $base2, $connection);
	}
$vPriceBase1 = ($vPrice*$rate_dt)/$rate_dt1;
$vPriceBase2 = ($vPrice*$rate_dt)/$rate_dt2;
//$vPrice=$WHCode;
//echo number_format($vPrice, $DecimalBase)."[BRK]".number_format($vPriceBase1, $DecimalBase1)."[BRK]".number_format($vPriceBase2, $DecimalBase2);
echo $vPrice."[BRK]".number_format($vPriceBase1, $DecimalBase1)."[BRK]".number_format($vPriceBase2, $DecimalBase2);

exit;
}


if($mainmode=='edit'){

if($item_fixedcost=='')	
	$item_fixedcost='null';

	
	$query_items="update items set  Item_Code='".trim(strtoupper($item_code))."',
									Item_Unit='".$item_quantity."',
									Ledger_Number=$supplier_code,
									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,
									CostCent_Code=$costcent_code,
									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_Package='".$item_package."',
									Item_Vat='".$item_vat."',
									item_vattype=$item_vattype,
									Item_Description='".$item_description."',
									Item_DescriptionF1='".$item_descriptionf1."',
									Item_DescriptionF2='".$item_descriptionf2."',
									item_longdescription='".$item_longdescription."',
									Item_CostMethod=$cost, item_fixedcost = $item_fixedcost, ";
										
									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."', ";
	if($FI_SellingPriceInItems == 1)
		$query_items=$query_items."	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', ";
		$query_items=$query_items."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_discountper='".$item_discountper."',
									Item_Color='".$item_color."',
									ITEM_MINQTY='$item_minqty',
									item_sgan  ='$item_sgan',									
									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."',
									category_code=$category_code,
									Item_SemiFinished='$item_semifinished',
									Item_WarehouseCode = $warehouse_code,
									item_lastcostprice = $item_lastcostprice,
									item_minimumprice = $item_minimumprice 
									,item_codeexport = '$item_codeexport'
									,item_descriptionexporten = '$item_descriptionexporten' 
									,item_descriptionexportar = '$item_descriptionexportar'
									,item_descriptionexportfr = '$item_descriptionexportfr' 
									,item_fixedcost = $item_fixedcost, item_reducer='$txtitemreducer', item_retarder='$txtitemretarder',
									item_Shade='$txtitemShade',item_Strength='$txtitemStrength',item_Packing=$txtitemPacking,
									item_ViscosityDirect='$itemViscosityDirect',item_ViscosityReduced='$itemViscosityReduced '
									,item_gloss='$txtitemgloss',item_Adhesion='$txtitemAdhesion',item_Alkali='$txtitemAlkali',item_scuff='$txtitemscuff', Item_SubSequence = $item_subsequence
									,last_SubItemSeq = $AddedSeq
									,Item_showInSalesReport = $Item_showInSalesReport
									,item_businessPt1 = '$item_businessPt1'
									,item_businessPt2 = '$item_businessPt2'
									,item_businessPt3 = '$item_businessPt3'
									,item_businessPt4 = '$item_businessPt4'
									,item_businessPt5 = '$item_businessPt5'
									,item_businessPt6 = '$item_businessPt6'
									,item_gift = ".strformat($item_gift)."
									,item_businessPoint = ".strformat($item_businessPoint)."
									,item_invoiceType = ".strformat($item_invoiceType)."
									,item_isCatalogue = ".strformat($item_isCatalogue)."
									,item_isFees = ".strformat($item_isFees)."
									,item_mobile = ".strformat($itemmobile)."
									,item_class = ".strformat($itemclass)."
									,item_isNotAvailable = ".strformat($item_isNotAvailable)."
									,item_costper = '$item_costper'
									,Item_withdisc = '$Item_withdisc'
									,item_priceByQty = '$priceByQty'
									where item_id='".$item_id."'";
	
	//echo$query_items;exit;
	if($FI_SellingPriceInItems == 1)
	SubmittoHistory($item_id,$username,$currency
							,$sellingprice1,$sellingprice1base1,$sellingprice1base2
							,$sellingprice2,$sellingprice2base1,$sellingprice2base2
							,$sellingprice3,$sellingprice3base1,$sellingprice3base2
							,$sellingprice4,$sellingprice4base1,$sellingprice4base2
							,$sellingprice5,$sellingprice5base1,$sellingprice5base2
							,$sellingprice6,$sellingprice6base1,$sellingprice6base2
						,$connection);
		//	echo $username;exit;			
						
	$result_items=mysql_query($query_items,$connection);
	if($config['log_file'] == 1){
		$transType = "U";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '".trim(strtoupper($item_code))."', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'items', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	$message= mysql_error();
	
	
						


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

	
	$querycompare = "select clientssellingprice_id, clientssellingprice_amount, clientssellingprice_currency, clientssellingprice_amountb1, clientssellingprice_amountb2, clientssellingprice_amount2, clientssellingprice_amount2b1, clientssellingprice_amount2b2, clientssellingprice_amount3, clientssellingprice_amount3b1, clientssellingprice_amount3b2, clientssellingprice_amount4, clientssellingprice_amount4b1, clientssellingprice_amount4b2, clientssellingprice_amount5, clientssellingprice_amount5b1, clientssellingprice_amount5b2, clientssellingprice_amount6, clientssellingprice_amount6b1, clientssellingprice_amount6b2, client_code
					from clientssellingprice where clientssellingprice_code = '$item_code' and clientssellingprice_default=1 ";
					
	$rescompare = mysql_query($querycompare , $connection);	
	//echo $querycompare; exit;
	$comp = mysql_fetch_row ($rescompare);
	
	if ( $sellingprice1 != $comp[1] or $sellingprice2 != $comp[5] or $sellingprice3 != $comp[8] or $sellingprice4 != $comp[11] or $sellingprice5 != $comp[14] or $sellingprice6 != $comp[17] ) {
		
		
	$querysellingprice = "insert into clientssellingprice (clientssellingprice_code, clientssellingprice_amount, clientssellingprice_currency, clientssellingprice_amountb1,
						  clientssellingprice_amountb2, clientssellingprice_amount2, clientssellingprice_amount2b1, clientssellingprice_amount2b2, clientssellingprice_amount3,
						  clientssellingprice_amount3b1, clientssellingprice_amount3b2, clientssellingprice_amount4, clientssellingprice_amount4b1, clientssellingprice_amount4b2,
						  clientssellingprice_amount5, clientssellingprice_amount5b1, clientssellingprice_amount5b2, clientssellingprice_amount6, clientssellingprice_amount6b1,
						  clientssellingprice_amount6b2) values ('$item_code' , $sellingprice1 , '$currency' , $sellingprice1base1,$sellingprice1base2, $sellingprice2,$sellingprice2base1,$sellingprice2base2,
						  $sellingprice3,$sellingprice3base1,$sellingprice3base2,
						  $sellingprice4,$sellingprice4base1,$sellingprice4base2,
						  $sellingprice5,$sellingprice5base1,$sellingprice5base2,
						  $sellingprice6,$sellingprice6base1,$sellingprice6base2)";
				
	$sellpriceresult = mysql_query ($querysellingprice , $connection);			
				//echo $querysellingprice; exit; 
	
	$lastid = mysql_insert_id();
	//echo $lastid; exit;
	$queryup = "update clientssellingprice set clientssellingprice_default=0 where clientssellingprice_code= '$item_code' and clientssellingprice_id!= $lastid";
	$queryupdate = "update clientssellingprice set clientssellingprice_default=1 where  clientssellingprice_id= $lastid ";
	//echo $queryup; echo "<br>";
	//	echo $queryupdate; echo "<br>"; exit;

	$res1 = mysql_query ($queryup , $connection);
	$res2 = mysql_query ($queryupdate , $connection);

	}
	
	
}


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

	if(is_uploaded_file($_FILES['photo']['tmp_name'])) { 

		$fileType1 = $_FILES['photo']['type'];$fileName1 = $_FILES['photo']['name'];
		$tmpName1  = $_FILES['photo']['tmp_name'];$fileSize1 = $_FILES['photo']['size'];

		$dest_dir='./uploads/items_photos';
		$foldername = $dest_dir;

		if (!is_dir($foldername)){
			mkdir($foldername, 0700, true);}
		
		
		$dest1 = $foldername.'\\'.$fileName1;
		//echo "dest1".$dest1;
		$fileName1 = 'items_photos/'.$fileName1;
		$picture=$fileName1;

		$fp1 = fopen($tmpName1, 'r');
		$content1 = fread($fp1, $fileSize1);
		//$content1 = addslashes($content1);
		fclose($fp1);
		if(!get_magic_quotes_gpc())
			$fileName1 = addslashes($fileName1);

		$r1 = move_uploaded_file ($tmpName1, $dest1);

		//echo $image; exit;
		if($picture != '') {
			$query_items="Update Items Set Item_picture='$picture' Where item_id='".$item_id."'";
			$result_items=mysql_query($query_items,$connection);
			if($config['log_file'] == 1){
			$query_items_history = "insert into items (item_id, item_picture, item_date, operator_id, item_schema, item_status) 
			                        values ('".$item_id."', '$picture', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
			$result_items_history = mysql_query($query_items_history, $connection_history);
			}
		}	
	}
}

if($mainmode=='removeimage' && $item_id != ''){
	$query = "update items set Item_Picture = null where item_code = '$item_code';";
	$res = mysql_query($query, $connection);	
}
if($mainmode=='delete'){
	$query = "select item_code, Item_Description from items where item_id='".$itemid."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	$item_description=$rows[1];
    if($config['log_file'] == 1){
		$transType = "D";
		$company = explode("_", $_SESSION['dbName']);
		$currCompany = strtoupper($company[0]);	
		$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '".trim(strtoupper($item_code))."', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'items', '$currCompany')";
		//echo $query_insertToHistory;exit;
		$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
	}
	$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($config['log_file'] == 1){
	$deleteitem_history = "insert into items (item_code, item_description, item_date, operator_id, item_schema, item_status) 
	                       values ('".$item_code."', '".$item_description."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
	        $result_history = mysql_query($deleteitem_history, $connection_history);
			}
	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);	
	if($config['log_file'] == 1){
	$update_barcode_history = "insert into items(item_barcode, item_barcode2, item_barcode3, item_id, item_date, operator_id, item_schema, item_status)
	                           values ('".$item_barcode."', '".$item_barcode2."', '".$item_barcode3."', '".$item_id."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
	$result_items_history = mysql_query($update_barcode_history, $connection_history);
	}
	$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);
	if($config['log_file'] == 1){
	$query_items_history = "insert into items (item_code,item_policy, item_date, operator_id, item_schema, item_status) values('".$item_code."','S', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_items_history = mysql_query($query_items_history, $connection_history);
	}
	$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);
		if($config['log_file'] == 1){
		$query_history = "insert into itemsdt(Item_Code,ItemParam_Code,itemdt_value, itemdt_date, itemdt_operator_id, itemdt_schema, itemdt_status)
				values ('".$item_code."','".$attribute_code."','".$attribute_value."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
		
		$result_history = mysql_query($query_history, $connection_history);
		}
		$message=mysql_error();
	
		if ($result) {
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($ItemDt_ID!=''){
		
		$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];
	
		
		$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);
		if($config['log_file'] == 1){
		$query_history = "INSERT into itemsdt (item_code,ItemParam_Code, itemdt_value, itemdt_date, itemdt_operator_id, itemdt_schema, itemdt_status)
		                  values ('".$item_code."','".$attribute_code."', '".$attribute_value."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
		$result_history = mysql_query($query_history, $connection_history);
		}
		$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, ItemDt_ID, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2 from itemsdt where ItemDt_ID='".$ItemDt_ID."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	$ItemDt_ID=$rows[1];
	$ItemParam_Code=$rows[2];
	$itemdt_value=$rows[3];
	$itemdt_sign=$rows[4];
	$itemdt_value2=$rows[5];
	
	$deleteitem = "delete from itemsdt where ItemDt_ID='".$ItemDt_ID."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	if($config['log_file'] == 1){
	$deleteitem_history = "insert into itemsdt (item_code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2,itemdt_date, itemdt_operator_id, itemdt_schema, itemdt_status)
	                       values ('".$item_code."', '".$ItemParam_Code."', '".$itemdt_value."', '".$itemdt_sign."', '".$itemdt_value2."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
	    $result_history = mysql_query($deleteitem_history, $connection_history);
	
	}
	
	
	$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);
		if($config['log_file'] == 1){
		$query_history = "insert into itemmanufacture(Item_Code,Item_ManufactureCode,Item_ManufactureDesc, Item_Manufacture_Date, Item_Manufacture_operator_id, Item_Manufacture_schema, Item_Manufacture_status)
				values ('".$item_code."','".$manufacture_code."','".$manufacture_desc."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
		
		$result_history = mysql_query($query_history, $connection_history);
		}
		
		$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);
		if($config['log_file'] == 1){
		$query_history = "insert into itemmanufacture (Item_ManufactureDesc, Item_ManufactureCode,
		Item_Manufacture_Date, Item_Manufacture_operator_id, Item_Manufacture_schema, Item_Manufacture_status) values ('".$manufacture_desc."', '".$manufacture_code."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
		$result_history = mysql_query($query_history, $connection_history);
		}
		$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, Item_ManufactureDesc, Item_ManufactureCode from itemmanufacture where Item_ManufactureCode='".$manufacture_code."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	$Item_ManufactureDesc=$rows[1];
	$Item_ManufactureCode=$rows[2];
	
	$deleteitem = "delete from itemmanufacture where Item_ManufactureCode='".$manufacture_code."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	if($config['log_file'] == 1){
	$deleteitem_history = "insert into itemmanufacture (item_code, Item_ManufactureDesc, Item_ManufactureCode, 
	Item_Manufacture_Date, Item_Manufacture_operator_id, Item_Manufacture_schema, Item_Manufacture_status) values ('".$item_code."', '".$Item_ManufactureDesc."', '".$Item_ManufactureCode."', now(),
						   '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
	    $result_item = mysql_query($deleteitem_history, $connection_history);
	}
	$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);
		
		if($config['log_file'] == 1){
		$query_history = "insert into itemsrebate(Item_Code, ItemRebate_RangeFrom, ItemRebate_RangeTo, ItemRebate_Per,ItemRebate_date, ItemRebate_operator_id, ItemRebate_schema, ItemRebate_status)
				values ('".$item_code."','".$rebate_rangefrom."','".$rebate_rangeto."','".$rebate_per."',now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
		$result_history = mysql_query($query_history, $connection_history);
		}
		$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);
		if($config['log_file'] == 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];
		$query_history = "insert into itemsrebate (item_code,ItemRebate_RangeFrom, ItemRebate_RangeTo, ItemRebate_Per, 
		ItemRebate_date, ItemRebate_operator_id, ItemRebate_schema, ItemRebate_status
		) values ('".$item_code."','".$rebate_rangefrom."', '".$rebate_rangeto."', '".$rebate_per."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
		$result_history = mysql_query($query_history, $connection_history);
		//echo $result_history;exit;
		}
		$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, ItemRebate_RangeFrom, ItemRebate_RangeTo, ItemRebate_Per from itemsrebate where ItemRebate_Id='".$rebate_id."'";
	$result=mysql_query($query,$connection);
	$rows=mysql_fetch_row($result);
	$item_code=$rows[0];
	$ItemRebate_RangeFrom=$rows[1];
	$ItemRebate_RangeTo=$rows[2];
	$ItemRebate_Per=$rows[3];
	
	
	$deleteitem = "delete from itemsrebate where ItemRebate_Id='".$rebate_id."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
    if($config['log_file'] == 1){
	$deleteitem_history = "insert into itemsrebate (item_code, ItemRebate_RangeFrom, ItemRebate_RangeTo, ItemRebate_Per, 
	ItemRebate_date, ItemRebate_operator_id, ItemRebate_schema, ItemRebate_status) values ('".$item_code."', '".$ItemRebate_RangeFrom."', '".$ItemRebate_RangeTo."', '".$ItemRebate_Per."',
						  now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
	$result_history = mysql_query($deleteitem_history, $connection_history);
	//echo $deleteitem_history;
	//exit;
	}
	$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_packdt = "select Item_Code, Warehouse_Code, packdt_price from packdt where Item_Code = '".$item_code."'";
	$result_packdt = mysql_query($query_packdt, $connection);
	$rows_packdt = mysql_fetch_array($result_packdt);
	extract($rows_packdt);
	$query="delete from packdt where item_code='".$item_code."'";
	$result=mysql_query($query,$connection);
	
	if($result){
		
		if($config['log_file'] == 1){
		$query_history = "insert into packdt (Item_Code, Warehouse_Code, packdt_price, packdt_date, packdt_operator_id, packdt_schema, packdt_status) 
		                  values ('".$Item_Code."', '".$Warehouse_Code."', '".$packdt_price."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
		$result_history = mysql_query($query_history, $connection_history);

		
		
		}
		$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($config['log_file'] == 1){
		    $query_history = "insert into packdt (item_code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty,packdt_date, packdt_operator_id, packdt_schema, packdt_status)
			select '".$item_code."',Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I' from packdt where item_code='".$item_packcode."'";
		    $result_history = mysql_query($query_history, $connection_history);
			}
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
}

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

		
	if($Itempackdt=='' && $Itempackwarehouse==''){
	
		if($item_stage != '')
		$query="insert into packdt(Item_Code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty,Group_Code,item_stage, currency_code)
				values ('".$item_code."','".$item_packcode."','".$item_warehousecode."',$item_packqty,$item_packcost,$item_packfromdate,$item_packtodate,$item_promoqty,'".$item_packgroupcode."','$item_stage', '".$currency."')";
		else
		$query="insert into packdt(Item_Code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty,Group_Code, currency_code)
				values ('".$item_code."','".$item_packcode."','".$item_warehousecode."',$item_packqty,$item_packcost,$item_packfromdate,$item_packtodate,$item_promoqty,'".$item_packgroupcode."', '".$currency."')";
		//echo$query;exit;
		$result=mysql_query($query,$connection);
		if($config['log_file'] == 1){
		$query_history = "insert into packdt(Item_Code,Item_CodePackDt,Warehouse_Code,PackDt_Quantity,PackDt_CostPercentage,PackDt_FromDate,PackDt_ToDate,Packdt_PromoQty,Group_Code, packdt_date, packdt_operator_id, packdt_schema, packdt_status)
				values ('".$item_code."','".$item_packcode."','".$item_warehousecode."',$item_packqty,$item_packcost,$item_packfromdate,$item_packtodate,$item_promoqty,'".$item_packgroupcode."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
		$result_history = mysql_query($query_history, $connection_history);
		}
		$message=mysql_error();
	
		if ($result) {
			$query="update items set Item_QtyToBeProduced=$Item_QtyToBeProduced where Item_Code = '".$item_code."'";
			$result=mysql_query($query,$connection);
			if($config['log_file'] == 1){
		    $query_history = "insert into items(Item_QtyToBeProduced, Item_Code, item_date, operator_id, item_schema, item_status) 
			                  values ($Item_QtyToBeProduced, '".$item_code."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
			$result_history = mysql_query($query_history, $connection_history);
			}
			if ($Module_Synchro == 1) {
				InsertSynchroLoc($connection,'U','ITEMS','',$item_code,$Setup_Branch);
			}
		}
	}
	else if($Itempackdt!='' && $Itempackwarehouse!=''){ 
		$query="update packdt set 
						Item_CodePackDt='".$item_packcode."',
						Warehouse_Code='".$item_warehousecode."',
						Group_Code='".$item_packgroupcode."',
						PackDt_Quantity=$item_packqty,
						PackDt_CostPercentage=$item_packcost,
						PackDt_FromDate=$item_packfromdate,
						PackDt_ToDate=$item_packtodate,
						Packdt_PromoQty=$item_promoqty,
						item_stage = '$item_stage',
                        currency_code = '".$currency."'						
				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($config['log_file'] == 1){
		$query_history = "insert into packdt (Item_CodePackDt, Warehouse_Code, Group_Code, PackDt_Quantity, PackDt_CostPercentage,
		                  PackDt_FromDate, PackDt_ToDate, Packdt_PromoQty, item_code, packdt_date, packdt_operator_id, packdt_schema, packdt_status) 
						  values ('".$item_packcode."', '".$item_warehousecode."', '".$item_packgroupcode."', $item_packqty, $item_packcost,
						  $item_packfromdate, $item_packtodate, $item_promoqty, '".$item_code."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
		$result_history = mysql_query($query_history, $connection_history);
		
		
		
		//echo $query_history;exit;
		}
		if ($result) {
			$query="update items set Item_QtyToBeProduced=$Item_QtyToBeProduced where Item_Code = '".$item_code."'";
			$result=mysql_query($query,$connection);
		    if($config['log_file'] == 1){
			$query_history = "insert into items (Item_QtyToBeProduced, Item_Code,item_date, operator_id, item_schema, item_status) 
			                  values ($Item_QtyToBeProduced, '".$item_code."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
			$result_history = mysql_query($query_history, $connection_history);
			}
			
			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'){

    $query_packdt = "select Item_Code, Warehouse_Code from packdt where Warehouse_Code='".$Itempackwarehouse."' and Item_CodePackDt='".$Itempackdt."' and item_code='".$item_code."'";
	$result_packdt = mysql_query($query_packdt, $connection);
	$rows_packdt = mysql_fetch_array($result_packdt);
	extract($rows_packdt);
	$deleteitem = "delete from packdt where Warehouse_Code='".$Itempackwarehouse."' and Item_CodePackDt='".$Itempackdt."' and item_code='".$item_code."'";
	//	echo $deleteledger;
	$result=mysql_query($deleteitem,$connection);
	
	if($config['log_file'] == 1){
		$query_history = "insert into packdt (Item_Code, Warehouse_Code, Item_CodePackDt, packdt_date, packdt_operator_id, packdt_schema, packdt_status) 
		                  values ('".$Item_Code."', '".$Itempackwarehouse."',  '".$Itempackdt."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
		$result_history = mysql_query($query_history, $connection_history);

		
		
		}
	
	$errornum= mysql_errno();
		
	if($errornum=='1451') {
		$message="Delete Not Allowed . Pack Item is used .";
		//echo $message;
	}
	
	if ($result) {
	    if($config['log_file'] == 1){
	    $query_history = "insert into packdt (Item_Code, Warehouse_Code, packdt_price, packdt_date, packdt_operator_id, packdt_schema, packdt_status) 
		                  values ('".$Item_Code."', '".$Warehouse_Code."', '".$packdt_price."', now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
		$result_history = mysql_query($query_history, $connection_history);
		}
		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=='insert' || $mainmode=='edit'  || $mainmode == 'CopyItem') && $alwaysClearPage == 1)
	$pageclear = 1;
else if (($mainmode=='insert' || $mainmode == 'CopyItem') && $alwaysClearPage == 0)
	$pageclear = 1;
else $pageclear = 0;
if ($mainmode != 'checkduplicate') {	
	if ($mainmode != 'delete') {
	header ("Location: ./Form_Items.php?item_id=$item_id&mainmode=&vTabFocus=$vTabFocus&HideMenu=".$HideMenu."&message=".$message."&currency=".$currency."&item_discountper=".$item_discountper."&pageclear=$pageclear");	
	}
	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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory_history(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'I',".GetSQLValueString($Item_SellingPrice1, 'double').",".GetSQLValueString($sellingprice1, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_history = mysql_query($query_history, $connection_history);
	}
	}		
/*	
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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'II',".GetSQLValueString($Item_SellingPrice2, 'double').",".GetSQLValueString($sellingprice2, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I)";
	$result_history = mysql_query($query_history, $connection_history);
	}
	
	}
	/*
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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'III',".GetSQLValueString($Item_SellingPrice3, 'double').",".GetSQLValueString($sellingprice3, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_history = mysql_query($query_history, $connection_history);		
    }	
	}/*
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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'IV',".GetSQLValueString($Item_SellingPrice4, 'double').",".GetSQLValueString($sellingprice4, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_history = mysql_query($query_history, $connection_history);
	}
	}/*
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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'V',".GetSQLValueString($Item_SellingPrice5, 'double').",".GetSQLValueString($sellingprice5, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_history = mysql_query($query_history, $connection_history);
	}
	}/*
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($config['log_file'] == 1){
	$query_history = " insert into sellingpricehistory(username, item_id, fieldname, value_before,value_after, datemodified, currency_code,groupid, selling_date, selling_operator_id, selling_schema, selling_status)
					values('$username',$item_id,'VI',".GetSQLValueString($Item_SellingPrice6, 'double').",".GetSQLValueString($sellingprice6, 'double').",now(),'$currency_code',$sameid, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'I')";
	$result_history = mysql_query($query_history, $connection_history);
	}
	}/*
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;exit;
$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];

}
function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}
?>