<?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']; 
$Unit_Code 		 = $_POST['Unit_Code']; if($Unit_Code == '') $Unit_Code = $_GET['Unit_Code']; 
$Old_Unit 		 = $_POST['Old_Unit'];
$txtSynchronized = $_POST['txtSynchronized']; 
if($txtSynchronized == '') $txtSynchronized = 0;

if($mainaction=='insert'){
	$search = "select 1 from unit where Unit_Code = '$Unit_Code'";
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query_unit="insert into unit(Unit_Code, Synchronized)
						values('".$Unit_Code."',".$txtSynchronized." )";
		$result_unit=mysql_query($query_unit,$connection);
		$message= mysql_error();
	} else {
		$message = "Unit Code Already Exists!";
	}
}

if($mainaction=='edit'){
	$query_unit="update unit set Unit_Code = '".$Unit_Code."', Synchronized = ".$txtSynchronized."
						where Unit_Code='".$Old_Unit."'";
	$result_unit=mysql_query($query_unit,$connection);
	$message= mysql_error();
}

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


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

?>