<?php

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


include("config.inc.php");
include("function.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");


$querylog="SELECT FI_QtyBudget as loginaccess from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')	";
	$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlog)){
		extract($rows);
	}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");

$mainmode  	= $_POST['mainmode'];
$tempid	   	= $_POST['tempid'];
$item_code 	= $_POST['item_code'];

$txtKeyword = $_POST['txtKeyword'];
$perpage 	= $_POST['perpage'];
$startrange = $_POST['startrange'];

$message = '';
$ErrorExists = 0;

if ($mainmode == 'insert' || $mainmode == 'edit'){
	$queryItem  = "select 1 from items where item_code = ".GetSQLValueString($item_code,'text')." ";
	$resItem 	= mysql_query($queryItem, $connection);
	$numItem  	= mysql_num_rows($resItem);
	if ($numItem == 0){
		$ErrorExists = 1;
		$message = "Insert/Edit Not Allowed! Check for Item Code!";	
	}
	
	$queryCheck = "select 1 from Budget_ItemsTemplate where item_code = ".GetSQLValueString($item_code,'text')." and if ('$tempid'='', 1=1, template_id <> '$tempid')";
	$resCheck 	= mysql_query($queryCheck, $connection);
	$numRow 	= mysql_num_rows($resCheck); 
	if ($numRow > 0){
		$ErrorExists = 1;
		$message = "Insert Not Allowed! Item Already Exists!";	
	}
}

if ($mainmode == 'insert' && $ErrorExists == 0 && $tempid == ''){
	$insert = "insert into Budget_ItemsTemplate (item_code) values (".GetSQLValueString($item_code,'text').") ";
	$result = mysql_query($insert, $connection);
	$message = mysql_error();	
}

if ($mainmode == 'edit' && $ErrorExists == 0 && $tempid != ''){
	$update = "update Budget_ItemsTemplate set item_code = ".GetSQLValueString($item_code,'text')." where template_id = $tempid ";
	$result = mysql_query($update, $connection);
	$message = mysql_error();	
}

if ($mainmode == 'delete' && $tempid != ''){
	$delete = "delete from Budget_ItemsTemplate where template_id = $tempid ";
	$result = mysql_query($delete, $connection);
	$message = mysql_error();	
}

echo "<form name='itemtempAction' method='POST' action='Form_BudgetQuantityTemplate.php'>
	<input type='hidden' name='mainmode' value=''>
	<input type=hidden name='message' value='$message'>
	<input type=hidden name='tempid' value=''>
	<input type=hidden name='txtKeyword' value='$txtKeyword'>
	<input type=hidden name='perpage' value='$perpage'>
	<input type=hidden name='startrange' value='$startrange'>
	</form>";
echo "<script>
		document.itemtempAction.submit();
	 </script>";
?>