<?php

session_start();

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

include("config.inc.php");

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

$mainaction 	= $_POST['mainaction']; 
$attribute_code = $_POST['attribute_code']; if($attribute_code == '') $attribute_code = $_GET['attribute_code']; 
$attribute_name = $_POST['attribute_name']; 
$attribute_unit = $_POST['attribute_unit']; 

if($mainaction=='insert'){
	$search = "select 1 from itemsparam where ItemParam_Code = '$attribute_code'";
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query_attributes="insert into itemsparam(ItemParam_Code, ItemParam_Name, Unit_Code)
						values('".$attribute_code."',".strformat($attribute_name).",".strformat($attribute_unit).")";
		$result_attributes=mysql_query($query_attributes,$connection);
		$message= mysql_error();
	} else {
		$message = "Parameter Code Already Exists!";
	}
}

if($mainaction=='edit'){
	$query_attributesdt="update itemsparam set ItemParam_Name = ".strformat($attribute_name).", Unit_Code = ".strformat($attribute_unit)."
						where ItemParam_Code='".$attribute_code."'";
	$result_attributesdt=mysql_query($query_attributesdt,$connection);
	$message= mysql_error();
}

if($mainaction=='delete'){
	$search = "select 1 from itemsdt where ItemParam_Code = '".$attribute_code."'";// echo $search;exit;
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query_delete="delete from itemsparam where ItemParam_Code='".$attribute_code."'";
		$result_delete=mysql_query($query_delete,$connection);
		$message= mysql_error();
	} else {
		$message = "Cannot delete! Parameter Code Already In Use!";
	}
}


echo "<form name='attributeaction' method='post'>".
	 "<input type='hidden' name='message' id='message' value='$message'>".
	 "<input type='hidden' name='mainaction' id='mainaction' value=''>".
	 "<script> document.attributeaction.action='Form_Item_Attribute.php';".
	 " document.attributeaction.submit(); </script>";
	 
function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}
	
mysql_close($connection);

?>