<?php
session_start();
session_cache_limiter("private");
if(!isset($_SESSION['user']))
	header("Location: login.php");
if($_SESSION['user'] == "expert")
	header("Location: index.php");
$login="<p>Вы зашли, как ".$_SESSION['user'].".<input type='button' onclick='location.href=\"login.php?logoff\";'/ value='Выход'>";
?>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<?php
$fh = fopen('login.cfg', "r") or die("Can't open file!");
$login = fread($fh, filesize('login.cfg'));
fclose($fh);
$fh = fopen('pass.cfg', "r") or die("Can't open file!");
$pass = fread($fh, filesize('pass.cfg'));
fclose($fh);
$fh = fopen('sid.cfg', "r") or die("Can't open file!");
$sid = fread($fh, filesize('sid.cfg'));
fclose($fh);
  
$c=OCILogon($login, $pass, $sid);
if(!$c)
			{
			echo "Невозможно подключится к базе: " . var_dump( OCIError() );
			die();
			}
if(isset($_GET["id"])) 
	{	//переданные какие-то параметры через GET для ПРОСМОТРА некоторого ресурса
		$id=htmlspecialchars($_GET["id"]);
		$sql="select res_usage.id_resus, res_usage.deleted, resources.name as resus, res_usage.rcount, products_type.type_name,";
		$sql=$sql." list_of_operation.name as op, res_usage.notes  from res_usage";
		$sql=$sql." join resources on resources.id_res=res_usage.id_res";
		$sql=$sql." left join TP_res_us on TP_res_us.id_resus=res_usage.id_resus";
		$sql=$sql." left join tp on tp.id_tp=TP_res_us.id_tp";
		$sql=$sql." left join products_type on products_type.id_type=tp.id_type";
		$sql=$sql." left join list_of_operation on list_of_operation.id_listop=tp.id_listop where res_usage.id_resus=".$id;
		$s = OCIParse($c, $sql);
		OCIExecute($s, OCI_DEFAULT);
		$n=0;
		//OCIFetch($s);
		
		//$type_name[$n]=htmlspecialchars(ociresult($s,"TYPE_NAME"));
		//$op[$n]=htmlspecialchars(ociresult($s,"OP"));
		//$n++;
		while (OCIFetch($s))
			{
			if($n==0)
				{
				$info["RESUS"]=htmlspecialchars(ociresult($s,"RESUS"));
				$info["NOTES"]=htmlspecialchars(ociresult($s,"NOTES"));
				$info["DELETED"]=htmlspecialchars(ociresult($s,"DELETED"));
				$info["RCOUNT"]=htmlspecialchars(ociresult($s,"RCOUNT"));
				}
			$type_name[$n]=htmlspecialchars(ociresult($s,"TYPE_NAME"));
			$op[$n]=htmlspecialchars(ociresult($s,"OP"));
			$n++;
			}
		$s = OCIParse($c, "select id_res, name from resources");
		OCIExecute($s, OCI_DEFAULT);
		$i=0;
		while (OCIFetch($s))
			{
			$id_res[$i]=htmlspecialchars(ociresult($s,"ID_RES"));
			$name_res[$i]=htmlspecialchars(ociresult($s,"NAME"));
			$i++;
			}
		echo "<title>Спецификация ресурса '".$info["RESUS"]."'</title>";
	}
elseif(isset($_GET["delete"]))
	{
		$id=htmlspecialchars($_GET["delete"]);
		$s = OCIParse($c, "update res_usage set deleted=0 where id_resus=".$id);
		OCIExecute($s, OCI_DEFAULT);
		echo "<meta http-equiv='refresh' content='0; url=res_us.php'>"; 
		echo "<title>Удалена спецификация ресурса</title>";
	}
elseif(isset($_GET["restore"]))
	{
		$id=htmlspecialchars($_GET["restore"]);
		$s = OCIParse($c, "update res_usage set deleted=1 where id_resus=".$id);
		OCIExecute($s, OCI_DEFAULT);
		echo "<meta http-equiv='refresh' content='0; url=res_us.php'>"; 
		echo "<title>Восстановлена спецификация ресурса</title>";
	}
elseif(isset($_GET["new"]))
	{
		echo "<title>Заведение новой спецификации ресурса</title>";
		$s = OCIParse($c, "select name, id_res from resources where deleted=1");
		OCIExecute($s, OCI_DEFAULT);
		$i=0;
		while(OCIFetch($s))
			{
			$res_name[$i]=htmlspecialchars(ociresult($s,"NAME"));
			$id_res[$i]=htmlspecialchars(ociresult($s,"ID_RES"));
			$i++;
			}
	}	
else
	{				
		if(count($_POST) > 0) 
		{	//переданные какие-то параметры через POST для СОХРАНЕНИЯ отредактированных данных
			$inf["ID"]=htmlspecialchars($_POST["id"]);
			$inf["RCOUNT"]=htmlspecialchars($_POST["RCOUNT"]);
			$inf["ID_RES"]=htmlspecialchars($_POST["ID_RES"]);
			$inf["NOTES"]=htmlspecialchars($_POST["NOTES"]);
			if(isset($_POST["status"]))
				{
				$inf["DELETED"]=htmlspecialchars($_POST["status"]);
				}
			else
				{
				$inf["DELETED"]=1;
				}
			if($inf["ID"]=="new"){
				$s = OCIParse($c, "insert into res_usage(rcount,notes,deleted,id_res) values('".$inf["RCOUNT"]."','".$inf["NOTES"]."','".$inf["DELETED"]."',".$inf["ID_RES"].")");
			}else{
				$s = OCIParse($c, "update res_usage set rcount='".$inf["RCOUNT"]."',id_res='".$inf["ID_RES"]."', notes='".$inf["NOTES"]."',  deleted='".$inf["DELETED"]."' where id_resus=".$inf["ID"]);
			}
			OCIExecute($s, OCI_DEFAULT);
		}
		//страница отделов открыта для просмотра информации по всем ресурсам
		$sql="select distinct(res_usage.id_resus) as id_resus, res_usage.deleted, resources.name as resus, res_usage.rcount, ";
		$sql=$sql."  res_usage.notes  from res_usage";
		$sql=$sql." join resources on resources.id_res=res_usage.id_res";
		//$sql=$sql." join TP_res_us on TP_res_us.id_resus=res_usage.id_resus";
		//$sql=$sql." join tp on tp.id_tp=TP_res_us.id_tp";


		if(isset($_GET["deleted"]))
			{
			$s = OCIParse($c, $sql." where res_usage.deleted=0 order by id_resus");
			echo "<title>Удаленные спецификации ресурсов</title>";
			}
		else
			{
			$s = OCIParse($c, $sql." where res_usage.deleted=1 order by id_resus");
			echo "<title>Спецификации ресурсов</title>";
			}
		OCIExecute($s, OCI_DEFAULT); 
		$i=0;
		while(OCIFetch($s)) 
			{//заполнение массивов данными ресурсам
			$id_resus[$i]=ociresult($s,"ID_RESUS");
			$name_op[$i]=htmlspecialchars(ociresult($s,"OP"));
			$type_name[$i]=htmlspecialchars(ociresult($s,"TYPE_NAME"));
			$resus[$i]=htmlspecialchars(ociresult($s,"RESUS"));
			$notes[$i]=htmlspecialchars(ociresult($s,"NOTES"));
			$rcount[$i]=htmlspecialchars(ociresult($s,"RCOUNT"));
			if($name_op[$i]=="")
				$name_op[$i]="—";
				
			if($type_name[$i]=="")
				$type_name[$i]="—";
						
			if($resus[$i]=="")
				$resus[$i]="—";
				
			if($rcount[$i]=="")
				$rcount[$i]="—";
				
			if($notes[$i]=="")
				$notes[$i]="—";
				
			$i++;
			}		
	}
OCICommit($c);
OCILogoff($c);
?>
	<script language="JavaScript">
		function num(count){
			for(var k=0;k<count;k++)
				{
				if(document.forms[0].elements[k].checked){
					return document.forms[0].elements[k].value;
					}
				}
			}
		function check(){
			var objSel = document.forms[0].elements[1];
			if ( objSel.selectedIndex != 0)
				{
				return true;
				}
			alert('Ресур не выбран!');
			 return false;
		}
	</script>
	<link rel="stylesheet" href="/style/style.css" type="text/css" />
	</head>
	<body>
		<table border=1>
			<tr>
				<td width=300 valign=top>
					<iframe src="menu.php" height=550 id="myIframe" scrolling=auto frameborder=0 >
						Ваш бразуер не поддерживает фрэймы, для работы АСУ воспользуйтесь другим ПО
					</iframe>
				</td>
	<td width=900 valign=top><table width="700"><td align='right'>Вы зашли как <?php echo $_SESSION['user'];?>, <input type='button' onclick='location.href="login.php?logoff";'/ value='Выход'></td></table><br/>
<?php


	if(isset($info)){
		echo "\n\n<form method='post' action='res_us.php'><input type='hidden' name='id' value='".$id."' />";
		echo "\n<table border=1>";
		echo "\n<tr>";
		echo "\n<td>Название ресурса: </td>";
		echo "\n<td><select name='ID_RES'>";
		for($k=0;$k<$i;$k++)
			{
			if($name_res[$k]==$info["RESUS"])
				{
				$check="selected";
				}
			else
				{
				$check="";
				}
			echo "<option value='".$id_res[$k]."' ".$check.">".$name_res[$k]."</option>\n";
			}
		echo "</select></td>";
		echo "\n</tr><tr>";
		echo "\n<td>Количество: </td>";
		echo "\n<td> <input name='RCOUNT' type='text' value='".$info["RCOUNT"]."' size='40'/></td>";
		echo "\n</tr><tr>";
		echo "\n<td>Устройства и операции: </td>\n<td>";
		if($op[0]!="")
			{
			echo "<table border=1><tr><th>Операция</th><th>Устройство</th></tr> ";
			for($k=0;$k<$n;$k++)
				{
				echo "<tr><td>".$op[$k]."</td><td>".$type_name[$k]."</td></tr>";
				}
			echo " </table>";
			}
		else
			echo "—";
		echo "\n</td></tr><tr>";
		
		echo "\n<td>Статус ресурса:</td>";
		if($info["DELETED"]==1)
			{
			echo "\n<td><input name='status' type='RADIO' value=1 checked>Активен<br/>";
			echo "<input name='status' type='RADIO' value=0>Удален<br/></td>";
			}
		else
			{
			echo "\n<td><input name='status' type='RADIO' value=1>Активен<br/>";
			echo "<input name='status' type='RADIO' value=0 checked>Удален<br/></td>";
			}
		echo "\n</tr><tr>";
		echo "\n<td>Примечание</td>";
		echo "\n<td><textarea name='NOTES' cols='30' rows='7'>".$info["NOTES"]."</textarea></td>";
		echo "\n</tr><table>";
		if($_SESSION['user']=='admin')
			echo "\n<input type='submit' value='Сохранить'>";
		echo "\n<input type='reset' value='Отменить' onclick='location.href=\"res_us.php\";'>";
		if($info["DELETED"]==1)
			{
			if($_SESSION['user']=='admin')
				echo "\n<input type='button' value='  Удалить  ' onclick='location.href=\"res_us.php?delete=".$id."\";'>";
			}
		echo "\n</form>";
	}elseif(isset($_GET["delete"]))
		{
		echo "\n<b>Спецификация ресурса успешно удалена.</b>";
	}
	elseif(isset($_GET["restore"]))
		{
		echo "\n<b>Спецификация ресурса успешно востановлена.</b>";
	}elseif(isset($_GET["new"])){
		echo "\n\n<form method='post' action='res_us.php' onsubmit='return check();'><input type='hidden' name='id' value='new' />";
		echo "\n<table border=1>";
		echo "\n<tr>";
		echo "\n<td>Название ресурса: </td>";
		echo "\n<td> <select name='ID_RES'>";
		echo "<option selected></option>";
		for($k=0;$k<$i;$k++)
			{
			echo "<option value=".$id_res[$k].">".$res_name[$k]."</option>";
			}
		echo "</select></td>";
		echo "\n</tr><tr>";
		echo "\n<td>Количество: </td>";
		echo "\n<td> <input name='RCOUNT' type='text'  size='40'/></td>";
		echo "\n</tr><tr>";
		echo "\n<td>Статус ресурса:</td>";
		echo "\n<td><input name='status' type='RADIO' value=1>Активен<br/>";
		echo "<input name='status' type='RADIO' value=0>Удален<br/></td>";
		echo "\n</tr><tr>";
		echo "\n<td>Примечание</td>";
		echo "\n<td><textarea name='NOTES' cols='30' rows='7'></textarea></td>";
		echo "\n</tr><table>";
		if($_SESSION['user']=='admin')
			echo "\n<input type='submit' value='Сохранить'>";
		echo "\n<input type='reset' value='Отменить' onclick='location.href=\"res_us.php\";'>";
		echo "\n</form>";
	}
	else{	
	//если переменная $id  НЕ инициализированна, то вывод данных из предзаполненных массивов в таблицу
	if(isset($_GET["deleted"]))
		{
		echo "<h3>Удаленные спецификации ресурсов</h3>";
		}
	else
		{
		echo "<h3>Спецификации ресурсов</h3>";
		}
	echo "<form >";
	echo "\n\n<table border=1 ><tr><th> </th><th> Номер спецификации</th><th>Ресурс</th><th>Количество</th><th>Примечание</th></tr>";
	$rn=0;
	for($j=0;$j<$i;$j++)
		{
		if($rn>3)
				$rn=0;
			if($rn==0)
				$color="#fbec5d";
			if($rn==1)
				$color="#fcdd76";
			if($rn==2)
				$color="#ffdb58";
			if($rn==3)
				$color="#f0dc82";
			$rn++;
		echo "	<tr bgcolor='".$color."'>\n";
		echo "		<td><input type=radio name='id' value=".$id_resus[$j]."><br/></td>\n";
		echo "		<td>\n";
		echo "			<a href='res_us.php?id=".$id_resus[$j]."'>".$id_resus[$j]."</a>\n";
		echo "		</td>\n";
		echo "		<td>".$resus[$j]."</td>\n";
		echo "		<td>".$rcount[$j]."</td>\n";
		echo "		<td>".$notes[$j]."</td>\n";
		echo "	</tr>\n"; 
		}
	echo "</table>\n\n";
	if(!isset($_GET["deleted"]))
		{
		if($_SESSION['user']=='admin')
			echo "\n<input type='button' value='   Создать   ' onclick='location.href=\"res_us.php?new\"'>";
		}
	if($_SESSION['user']=='admin')
		echo "\n<input type='button' value='  Изменить  ' onclick='location.href=\"res_us.php?id=\"+num($i);'>";
	if(!isset($_GET["deleted"]))
		{
		if($_SESSION['user']=='admin')
			echo "\n<input type='button' value='  Удалить  ' onclick='location.href=\"res_us.php?delete=\"+num($i);'>";
		}
	else
		{
		if($_SESSION['user']=='admin')
			echo "\n<input type='button' value='  Восстановить  ' onclick='location.href=\"res_us.php?restore=\"+num($i);'>";
		}
	echo "\n</form>";
	}
	
	
?>
				</td>
			</tr>
		</table>
	</body>
</html>