<?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']; 
$type_id 		 = $_POST['type_id']; if($type_id == '') $type_id = $_GET['type_id']; 
$constraint_code = $_POST['constraint_code']; 
$constraint_desc = $_POST['constraint_desc']; 


if($mainaction=='insert'){
	$search = "select 1 from Constraint_Type where constraint_code = '$constraint_code'";
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query="insert into Constraint_Type(constraint_code, constraint_desc)
						values('".$constraint_code."',".strformat($constraint_desc).")";
		$result=mysql_query($query,$connection);
		$message= mysql_error();
	} else {
		$message = "Constraint Code Already Exists!";
	}
}

if($mainaction=='edit'){
	$search = "select 1 from Constraint_Type where constraint_code = '$constraint_code'";
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query_attributesdt="update Constraint_Type set constraint_code = '".$constraint_code."', constraint_desc = ".strformat($constraint_desc)."
						where type_id='".$type_id."'";
		$result_attributesdt=mysql_query($query_attributesdt,$connection);
		$message= mysql_error();
	} else {
		$message = "Constraint Code Already Exists!";
	}
}

if($mainaction=='delete'){
	$search = "select 1 from Form_Constraint where constraint_typeId = '".$type_id."'";// echo $search;exit;
	$res = mysql_query($search,$connection);
	$numrow = mysql_num_rows($res);
	if($numrow == 0){
		$query_delete="delete from Constraint_Type where type_id='".$type_id."'";
		$result_delete=mysql_query($query_delete,$connection);
		$message= mysql_error();
	} else {
		$message = "Cannot delete! Constraint Code Already In Use!";
	}
}


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

?>