<?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"]);
		if(isset($_GET["delete"]))
			{
			$delete=htmlspecialchars($_GET["delete"]);
			$s = OCIParse($c, "select nom from tp where id_tp=".$delete);
			OCIExecute($s, OCI_DEFAULT);
			OCIFetch($s);
			$nom=htmlspecialchars(ociresult($s,"NOM"));
			$s = OCIParse($c, "update tp set nom=nom-1 where id_type=".$id." and nom>".$nom);
			OCIExecute($s, OCI_DEFAULT);
			$s = OCIParse($c, "delete from tp where id_tp=".$delete);
			OCIExecute($s, OCI_DEFAULT);
			echo "<meta http-equiv='refresh' content='0; url=tp.php?id=".$id."'>"; 
			}
	if(isset($_GET["insert"]))
		{
		$s = OCIParse($c, "select id_listop,name from list_of_operation");
		OCIExecute($s, OCI_DEFAULT);
		$i=0;
		while (OCIFetch($s))
			{
			$name[$i]=htmlspecialchars(ociresult($s,"NAME"));
			$listop[$i]=htmlspecialchars(ociresult($s,"ID_LISTOP"));
			$i++;
			}
		$s = OCIParse($c, "select nom from tp where id_type=".$id." order by nom");
		OCIExecute($s, OCI_DEFAULT);
		$j=0;
		while (OCIFetch($s))
			{
			$nom[$j]=htmlspecialchars(ociresult($s,"NOM"));
			$j++;
			}
		}
	else
		{
		$s = OCIParse($c, "select tp.id_tp, tp.nom, tp.notes, loo.name from tp join list_of_operation loo on loo.id_listop=tp.id_listop where tp.id_type=".$id." order by tp.nom");
		OCIExecute($s, OCI_DEFAULT);
		$i=0;
		while (OCIFetch($s))
			{
			$id_tp[$i]=htmlspecialchars(ociresult($s,"ID_TP"));
			$nom[$i]=htmlspecialchars(ociresult($s,"NOM"));
			$name_op[$i]=htmlspecialchars(ociresult($s,"NAME"));
			$notes[$i]=htmlspecialchars(ociresult($s,"NOTES"));
			
			if($id_tp[$i]=="")
				$id_tp[$i]="—";
	
			if($nom[$i]=="")
				$nom[$i]="—";
			
			if($name_op[$i]=="")
				$name_op[$i]="—";

			if($notes[$i]=="")
				$notes[$i]="—";

			$i++;
			}
		$s = OCIParse($c, "select type_name from products_type where id_type=".$id);
		OCIExecute($s, OCI_DEFAULT);
		while (OCIFetch($s))
			{
			$name_type=htmlspecialchars(ociresult($s,"TYPE_NAME"));
			}
		echo "<title>Техпроцесс ".$name_type."</title>";
		}
	}
elseif(isset($_GET["id_tp"]))
	{
	$id_tp=htmlspecialchars($_GET["id_tp"]);
	if(isset($_GET["res"]))
		{
		$res_us=htmlspecialchars($_GET["res"]);
		$s = OCIParse($c, "insert into tp_res_us(id_tp, id_resus) values(".$id_tp.", ".$res_us.")");
		OCIExecute($s, OCI_DEFAULT);
		echo "<meta http-equiv='refresh' content='0; url=tp.php?id_tp=".$id_tp."'>";
		}
	if(isset($_GET["del"]))
		{
		$del=htmlspecialchars($_GET["del"]);
		$s = OCIParse($c, "delete from tp_res_us where id_tp=".$id_tp." and id_resus =".$del);
		OCIExecute($s, OCI_DEFAULT);
		echo "<meta http-equiv='refresh' content='0; url=tp.php?id_tp=".$id_tp."'>";
		}
	$s = OCIParse($c, "select * from tp where id_tp=".$id_tp);
	OCIExecute($s, OCI_DEFAULT);
	while (OCIFetch($s))
		{
		$id_type=htmlspecialchars(ociresult($s,"ID_TYPE"));
		$nom=htmlspecialchars(ociresult($s,"NOM"));
		$id_listop=htmlspecialchars(ociresult($s,"ID_LISTOP"));
		$notes=htmlspecialchars(ociresult($s,"NOTES"));
		}
	$s = OCIParse($c, "select id_listop,name from list_of_operation");
	OCIExecute($s, OCI_DEFAULT);
	$i=0;
	while (OCIFetch($s))
		{
		$name[$i]=htmlspecialchars(ociresult($s,"NAME"));
		$listop[$i]=htmlspecialchars(ociresult($s,"ID_LISTOP"));
		$i++;
		}
	$sql="select resources.name, res_usage.rcount, res_usage.id_resus 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."where tp_res_us.id_tp=".$id_tp." and res_usage.deleted=1";	
	$s = OCIParse($c, $sql);
	OCIExecute($s, OCI_DEFAULT);
	$n=0;
	while (OCIFetch($s))
		{
		$resus[$n]=htmlspecialchars(ociresult($s,"NAME"));
		$rcount[$n]=htmlspecialchars(ociresult($s,"RCOUNT"));
		$id_resus[$n]=htmlspecialchars(ociresult($s,"ID_RESUS"));
		$n++;
		}
	$s = OCIParse($c, "select (resources.name||'--'||res_usage.rcount) as resname,res_usage.id_resus from res_usage join resources on resources.id_res=res_usage.id_res where res_usage.deleted=1");
	OCIExecute($s, OCI_DEFAULT);
	$m=0;
	while (OCIFetch($s))
		{
		$idresus[$m]=htmlspecialchars(ociresult($s,"ID_RESUS"));
		$resname[$m]=htmlspecialchars(ociresult($s,"RESNAME"));
		$m++;
		}
	}

else
	{
	if(count($_POST) > 0)
	{
		if(isset($_POST["op_id"]))
			{
			$id_type=htmlspecialchars($_POST["id_type"]);
			$id_tp=htmlspecialchars($_POST["id_tp"]);
			$operation=htmlspecialchars($_POST["op_id"]);
			$notes=htmlspecialchars($_POST["NOTES"]);
			$s = OCIParse($c, "update tp set notes='".$notes."', id_listop=".$operation." where id_tp=".$id_tp);
			OCIExecute($s, OCI_DEFAULT);
			echo "<meta http-equiv='refresh' content='0; url=tp.php?id=".$id_type."'>";
			}
		elseif(isset($_POST["id_type"]))
			{
			$id_type=htmlspecialchars($_POST["id_type"]);
			$operation=htmlspecialchars($_POST["operation"]);
			$nom=htmlspecialchars($_POST["nom"]);
			$notes=htmlspecialchars($_POST["NOTES"]);
			$s = OCIParse($c, "select id_tp from tp where id_type=".$id_type." and nom=".$nom);
			OCIExecute($s, OCI_DEFAULT);
			if(OCIFetch($s)!=0)
				{
				$s = OCIParse($c, "update tp set nom=nom+1 where id_type=".$id_type." and id_tp in (select id_tp from tp where id_type=".$id_type." and nom>=".$nom.")");
				OCIExecute($s, OCI_DEFAULT);
				}
			$s = OCIParse($c, "insert into tp(id_type, id_listop, nom, notes) values(".$id_type.",".$operation.",".$nom.",'".$notes."')");
			OCIExecute($s, OCI_DEFAULT);
			echo "<meta http-equiv='refresh' content='0; url=tp.php?id=".$id_type."'>";
			}
		elseif(isset($_POST["ops_id"]))
			{
			$id=htmlspecialchars($_POST["id"]);
			$ops_id=$_POST["ops_id"];
			$nom_id=$_POST["nom_id"];
			for($i=0;$i<count($ops_id);$i++)
				{
				$s = OCIParse($c, "update tp set nom=".$nom_id[$i]." where id_tp=".$ops_id[$i]);
				OCIExecute($s, OCI_DEFAULT);
				}
			echo "<meta http-equiv='refresh' content='0; url=tp.php?id=".$id."'>"; 
			}
	}
	$s = OCIParse($c, "select pt.type_name,pt.id_type, (select count(*) from tp where tp.id_type=pt.id_type) as coun  from products_type pt");
	OCIExecute($s, OCI_DEFAULT); 
	$i=0;
	while (OCIFetch($s)) {
		$id_type[$i]=ociresult($s,"ID_TYPE");
		$name[$i]=htmlspecialchars(ociresult($s,"TYPE_NAME"));
		$count[$i]=htmlspecialchars(ociresult($s,"COUN"));
		if($name[$i]=="")
			$name[$i]="—";
	
		if($count[$i]=="")
			$count[$i]="—";	
		$i++;
	}
  echo "<title>Тех. процессы</title>";
}
OCICommit($c);
OCILogoff($c);
?>

<script language="JavaScript">
		function confirm(count){
			var arr = new Array();
			var tmp;
			for(var k=0;k<count*3;k++)
				{
				arr[k]=0;
				}
			for(var k=0;k<count;k++)
				{
				tmp=3*k+2;
				if(document.forms[0].elements[tmp].value<1)
					{
					alert('Порядковый номер операции должен быть положительным!');
					return false;
					}
				arr[document.forms[0].elements[tmp].value]++;
				if(arr[document.forms[0].elements[tmp].value]>1)
					{
					alert('Не должно быть повторяющихся номеров операций!Операция №'+document.forms[0].elements[tmp].value);
					return false;
					}
				}
			for(var k=1;k<count+1;k++)
				{
				if(arr[k]==0 && arr[k-1]==1)
					{
					alert('КЭП: Порядковые номера должны быть без разрыва!Операция №'+k+' пропущена');
					return false;
					}
				}
			return true;
			}
		function num(count){
			var tmp;
			for(var k=0;k<count;k++)
				{
				tmp=3*k;
				if(document.forms[0].elements[tmp].checked){
					return document.forms[0].elements[tmp].value;
					}
				}
			}
		function nom(count){
			for(var k=0;k<count;k++)
				{
				tmp=3*k;
				if(document.forms[0].elements[tmp].checked){
					return document.forms[0].elements[tmp+2].value;
					}
				}
			}	
		function sel(count){
			var objSel = document.forms[0].elements[count+3];
			if ( objSel.selectedIndex != -1)
				{
				return (objSel.options[objSel.selectedIndex].value);
				}
			 return 0;
		}
	</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($id_listop))
		{
		echo "<form method='post' action='tp.php'>\n";

		echo "<table border=1><tr><td>Операция</td><td><select name='op_id' >\n";
		for($k=0;$k<$i;$k++)
			{
			if($id_listop==$listop[$k])
				{
				$check="selected";
				}
			else
				{
				$check="";
				}
			echo "<option value='".$listop[$k]."' ".$check.">".$name[$k]."</option>\n";
			}
		echo "</select></tr><tr><td>Порядковый номер</td><td>".$nom."</td></tr>\n";
		echo "<tr><td>Примечание</td><td><textarea name='NOTES' cols='30' rows='7'>".$notes."</textarea></td></tr>\n";
		echo "<tr><td>Спецификации ресурсов</td><td><table border=1>";
		for($k=0;$k<$n;$k++)
			{
			echo "<tr><td><input type='radio' name='lololo' value=".$id_resus[$k]."><br/></td><td>".$resus[$k]."</td><td>".$rcount[$k]."</td></td>\n";
			}		
		echo "</table>";
		if($_SESSION['user']=='technolog')
			{
			echo "<input type='button' value=' Удалить ' onclick='location.href=\"tp.php?id_tp=".$id_tp."&del=\"+nom(".$n.");'>";
			echo "<br/><br/>";
		
		echo "<select name='resname' id='resname'>";
		for($k=0;$k<$m;$k++)
			{
			echo "<option value='".$idresus[$k]."'>".$resname[$k]."</option>\n";
			}
		
		echo "</select><br/><input type='button' value='Добавить' onclick='location.href=\"tp.php?id_tp=".$id_tp."&res=\"+sel(".$n.");'><br/></td></tr>";
		echo "<input type='hidden' name='id_type' value=".$id_type."><br/><input type='hidden' name='id_tp' value=".$id_tp."><br/></table>";
		echo "<input type='submit' value='Сохранить'> ";
		echo "<input type='reset' value=' Отменить ' onclick='location.href=\"tp.php?id=".$id_type."\";'/>";
		echo "</form>\n";
		}
		}
	elseif(isset($_GET["insert"]))
		{
		echo "<form method='post' action='tp.php'>\n";
		echo "<table border=1><tr><td>Операция</td><td><select name='operation' >\n";
		for($k=0;$k<$i;$k++)
			{
			echo "<option value='".$listop[$k]."'>".$name[$k]."</option>\n";
			}
		echo "</select></tr><tr><td>Порядковый номер</td><td><select name='nom'>\n";
		$fl=0;
		for($l=0;$l<$j;$l++)
			{
			if($_GET["insert"]==$nom[$l])
				{
				$fl++;
				$check="selected";
				}
			else
				{
				$check="";
				}
			echo "<option value='".$nom[$l]."' ".$check.">".$nom[$l]."</option>\n";
			}
		if($fl==0)
			{
			$check="selected";
			}
		else
			{
			$check="";
			}
		echo "<option value='".($nom[$j-1]+1)."' ".$check.">В конец</option></select></tr>\n";	
		echo "<tr><td>Примечание</td><td><textarea name='NOTES' cols='30' rows='7'></textarea></td></tr>\n";
		echo "<input type='hidden' name='id_type' value=".$id."><br/></table>";
		if($_SESSION['user']=='technolog'){
		echo "<input type='submit' value='Сохранить'> ";
		echo "<input type='reset' value=' Отменить ' onclick='location.href=\"tp.php?id=".$id."\";'/>";
		}
		echo "</form>\n";
		}
	elseif(isset($name_type))
		{
		echo "<H3>Тех. процесс изготовления ".$name_type.", id=".$id."</H3>\n";
		echo "<form method='post' action='tp.php' onsubmit='return confirm(".$i.");'>\n";
		
		echo "<table border=1><tr><th></th><th>Номер записи</th><th>Номер операции</th><th>Операция</th><th>Примечание</th></tr>\n";
		$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."><td><input type='radio' name='trolo' value=".$id_tp[$j]."><br/></td>\n";
			echo "<td bgcolor=".$color."><a href='tp.php?id_tp=".$id_tp[$j]."'>".$id_tp[$j]."</a><input type='hidden' name='ops_id[]' value='".$id_tp[$j]."'/><br/></td>\n";
			echo "<td bgcolor=".$color."><input type='text' name='nom_id[]' size='15' value='".$nom[$j]."'/><br/></td>\n";
			echo "<td bgcolor=".$color.">".$name_op[$j]."</td>\n";
			echo "<td bgcolor=".$color.">".$notes[$j]."</td></tr>\n";
			}
		echo "</table>";
		if($_SESSION['user']=='technolog'){
		echo "<input type='submit' value='Сохранить'>\n";
		echo "<input type='button' value='   Вставить  ' onclick='location.href=\"tp.php?id=".$id."&insert=\"+nom($i);'>\n";
		echo "<input type='button' value='   Изменить  ' onclick='location.href=\"tp.php?id_tp=\"+num($i);'>\n";
		echo "<input type='button' value='  Удалить   ' onclick='location.href=\"tp.php?id=".$id."&delete=\"+num($i);'>\n";
		echo "<input type='button' value='   Назад    ' onclick='location.href=\"tp.php\";'>\n";
		
		}
		echo "<input type='hidden' name='id' value='".$id."'/><br/>\n";
		echo "<input type='button' value='Экспорт в PDF' onclick='window.open(\"pdf.php?pdf=".$id."\");'>\n";
		echo "</form>";
		}
	elseif(isset($nom_id))
		{
			echo "<p>Последовательность операций успешно изменена</p>";
		}
	else
		{
		echo "<table border=1><tr><th>Название</th><th>Количество операций</th></tr>\n";
		$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><td bgcolor=".$color."><a href='tp.php?id=".$id_type[$j]."'>Тех. процесс ".$name[$j]."</a></td><td bgcolor=".$color.">".$count[$j]."</td></tr>\n"; 
			
			}
		echo "</table>";
	//echo "<p><b>Автоматизированнаая система управления </b>предприятием, производящим радиоэлектро аппаратуру блаблабла охуенно пиздато все ебануться нахуй как ебошит заебись.</p>";

		}
	?>
	</td>
	</tr>
	</table>
</body>
</html>