<?php
session_start();
session_cache_limiter("private");
if(!isset($_SESSION['user']))
	header("Location: login.php");
if( ($_SESSION['user'] == "rab") || ($_SESSION['user'] == "admin"))
	header("Location: index.php");
$login="<p>Вы зашли, как Пользователь<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($_POST["point"])){
	$point=htmlspecialchars($_POST["point"]);
	if(isset($_POST["ready"])){
			$finish=1;
			$slot=htmlspecialchars($_POST["id_slot"]);
			$slt_value=htmlspecialchars($_POST["slt_value"]);
			$s = OCIParse($c, "begin find_frame_exmpl(:bind1, :bind2, :bind3); end;");
			OCIBindByName($s, ":bind1", $point);
			OCIBindByName($s, ":bind2", $slot); 
			OCIBindByName($s, ":bind3", $slt_value); 
			OCIExecute($s, OCI_DEFAULT);
	
			$s = OCIParse($c, "select * from tmp");
			OCIExecute($s, OCI_DEFAULT);
			$i=0;
			while (OCIFetch($s)){
				$slot_values[$i]=ociresult($s,"SLT_VALUE");
				$slt_name[$i]=ociresult($s,"ID_SLOTS");
				$i++;
			}
	}else{
		
		
		$nom=htmlspecialchars($_POST["nom"]);
	
		if($nom == 1){
			$s = OCIParse($c, "delete from tmp");
			OCIExecute($s, OCI_DEFAULT);
	
			$s = OCIParse($c, "insert into tmp(id_fr_exmpl, id_exmpl, id_frames, id_slots, slt_value) select id_fr_exmpl, id_exmpl, id_frames, id_slots, slt_value from Frame_exmpl where id_frames=".$point);
			OCIExecute($s, OCI_DEFAULT);
		}else{
			$slot=htmlspecialchars($_POST["id_slot"]);
			$slt_value=htmlspecialchars($_POST["slt_value"]);
			$s = OCIParse($c, "begin find_frame_exmpl(:bind1, :bind2, :bind3); end;");
			OCIBindByName($s, ":bind1", $point);
			OCIBindByName($s, ":bind2", $slot); 
			OCIBindByName($s, ":bind3", $slt_value); 
			OCIExecute($s, OCI_DEFAULT);
		}
	
		$s = OCIParse($c, "select frame_name from frames where id_frames=".$point);
		OCIExecute($s, OCI_DEFAULT);
		OCIFetch($s);
		$frame_name=htmlspecialchars(ociresult($s,"FRAME_NAME"));
	
		$s = OCIParse($c, "select count(distinct(id_slots)) as cnt from tmp");
		OCIExecute($s, OCI_DEFAULT);
		OCIFetch($s);
		$count=htmlspecialchars(ociresult($s,"CNT"));
	
		$s = OCIParse($c, "select slots.slot_name, slots.id_slots from slots where id_slots in (select distinct(id_slots) from tmp ) order by id_slots");
		OCIExecute($s, OCI_DEFAULT);
		$i=0;
	
		while (OCIFetch($s)){
			if($i == ($nom-1)){
				$id_slot=htmlspecialchars(ociresult($s,"ID_SLOTS"));
				$slot_name=htmlspecialchars(ociresult($s,"SLOT_NAME"));
				break;
			}
			$i++;
		}
		if(isset($id_slot)){
			if($i == ($count-1)){
				$ready=1;
			}
			$s = OCIParse($c, "select distinct(slt_value) from tmp where id_slots=".$id_slot." and id_frames=".$point);
			OCIExecute($s, OCI_DEFAULT);
			$i=0;
			while (OCIFetch($s)){
				$slt_values[$i]=ociresult($s,"SLT_VALUE");
				$i++;
			}
		}
	}
	/*$frame_name=htmlspecialchars(ociresult($s,"FRAME_NAME"));
	$s = OCIParse($c, "select slots_to_frames.id_slots as id_slots, slots.slot_name as slot_name, slots.id_field as id_field from slots_to_frames join slots on slots.id_slots=slots_to_frames.id_slots where slots_to_frames.id_frames=".$point);
	OCIExecute($s, OCI_DEFAULT);
	$i=0;
	while (OCIFetch($s))
			{
				$slots_id[$i]=htmlspecialchars(ociresult($s,"ID_SLOTS"));
				$slots_name[$i]=htmlspecialchars(ociresult($s,"SLOT_NAME"));
				$field_id[$i]=htmlspecialchars(ociresult($s,"ID_FIELD"));
				//echo $field_id[$i].";";
				$i++;
			}
	if(isset($field_id)){
	
	for($i=0;$i<count($field_id);$i++)
		{
			$s = OCIParse($c, "select tables.table_name as TABLE_NAME, fields.field_name as FIELD_NAME from fields join  tables on tables.id_tables=fields.id_table where id_fields=".$field_id[$i]);
			OCIExecute($s, OCI_DEFAULT);
			OCIFetch($s);
			$table_name=htmlspecialchars(ociresult($s,"TABLE_NAME"));
			$field_name=htmlspecialchars(ociresult($s,"FIELD_NAME"));
			//echo $table_name." ".$field_name;
			$s2 = OCIParse($c, "select distinct(".$field_name.") as VV from ".$table_name);
			//echo "select distinct(".$field_name.") as vv from ".$table_name;
			OCIExecute($s2, OCI_DEFAULT);
			$j=0;
			//$slots_values[$i]=array();
			while (OCIFetch($s2))
					{
						if(htmlspecialchars(ociresult($s2,"VV")) != "")
							{
							$slots_values[$i][$j]=htmlspecialchars(ociresult($s2,"VV"));
							//echo $slots_values[$i][$j].";".$i."-".$j;
							$j++;
							}
					}
					//print_r($slots_values);
		}
	} */
	if(isset($_GET["error"])){
		$error = "<h2>Не все слоты фрейма созданы из одной таблицы!</h2>";
	}
}
elseif(isset($_POST["id_frame"])){
	$id_frame=htmlspecialchars($_POST["id_frame"]);
	$table_name = "";
	$where = "";
	foreach($_POST as $key => $value)
		{
			//echo substr($key,0,4);
			
			if(substr($key,0,4) == "slt_"){
				$id_slt=substr($key,4);
				$sql = "select fields.field_name, tables.table_name from fields join tables on tables.id_tables = fields.id_table where fields.id_fields = (select id_field from slots where id_slots = ".$id_slt.")";
				$s = OCIParse($c, $sql);
				OCIExecute($s, OCI_DEFAULT);
				OCIFetch($s);
				$table = htmlspecialchars(ociresult($s,"TABLE_NAME"));
				$field = htmlspecialchars(ociresult($s,"FIELD_NAME"));
				if($table_name == ""){
					$table_name = $table;
				}
				if($table_name != $table){
					echo "<meta http-equiv='refresh' content='0; url=generate_tp.php?point=".$id_frame."&error'>"; 
				}
				$where = $where." ".$field." = '".$value."' and ";
			}
		}
	$where=substr($where,0,strlen($where)-4);
	$where = "select id_listop, name from ".$table_name." where ".$where;
	//echo $where;
	$s = OCIParse($c, $where);
	OCIExecute($s, OCI_DEFAULT);
	$i = 0;
	while (OCIFetch($s))
			{
				$id_listop[$i] = htmlspecialchars(ociresult($s,"ID_LISTOP"));
				$name[$i] = htmlspecialchars(ociresult($s,"NAME"));
				$i++;
			}
}elseif(isset($_POST["ids"]) && isset($_POST["nomen"])){
	$ids = $_POST["ids"];
	$nomen = htmlspecialchars($_POST["nomen"]);
	//echo $nomen;
	//print_r($ids);
	$s = OCIParse($c, "insert into products_type(type_name,notes,deleted) values('".$nomen."',' ',1)");
	//echo "insert into products_type(type_name,notes,deleted) values('".$nomen."',' ',1)";
	OCIExecute($s, OCI_DEFAULT);
	$s = OCIParse($c, "select id_type  from products_type where type_name='".$nomen."'");
	//echo "select id_type  from products_type where type_name='".$nomen."'";
	OCIExecute($s, OCI_DEFAULT);
	OCIFetch($s);
	$id_type = htmlspecialchars(ociresult($s,"ID_TYPE"));
	for($i=0;$i<count($ids);$i++){
		$s = OCIParse($c, "insert into tp(id_type, id_listop, nom, notes) values(".$id_type.",".$ids[$i].",".($i+1).",' ')");
		OCIExecute($s, OCI_DEFAULT);
	}
	echo "<meta http-equiv='refresh' content='0; url=tp.php?id=".$id_type."'>"; 
}else{
	$s = OCIParse($c, "select * from frames");
	OCIExecute($s, OCI_DEFAULT);
	$i=0;
	while (OCIFetch($s))
			{
				$frames_name[$i]=htmlspecialchars(ociresult($s,"FRAME_NAME"));
				$frames_id[$i]=htmlspecialchars(ociresult($s,"ID_FRAMES"));
				$i++;
			}
}
OCICommit($c);
OCILogoff($c);
?>
<title>Генерирование ТП</title>

	</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($frames_id))
		{
			echo "<form action='generate_tp.php' method='post'>";
			echo "Целевой фрейм: <select name='point'>";
			echo "<option value=-1></option>";
			for($i=0;$i<count($frames_id);$i++)
				{
					echo "<option value=".$frames_id[$i].">".$frames_name[$i]."</option>";
				}
			echo "</select>";
			echo "<input type='submit' value=' Далее '>";
			echo "<input type='hidden' name='nom' value=1>";
			echo "</form>";
		}
	elseif(isset($point)&& !(isset($finish)))
		{
			//print_r($slots_values);
			if(isset($error)){
				echo $error;
			}
			echo "<form action='generate_tp.php' method='post'>";
			echo "Целевой фрейм <b>".$frame_name."</b>";
			echo "<input type='hidden' name='nom' value=".($nom+1).">";
			echo "<input type='hidden' name='point' value=".$point." />";
			echo "<input type='hidden' name='id_slot' value=".$id_slot." />";
			if(isset($ready)){
				echo "<input type='hidden' name='ready' value=1 />";
			}
			echo "<table border=1><tr><td>".$slot_name." </td><td>";
			echo "<td><select name=slt_value>";
					echo "<option value=-1></option>";
					for($j=0;$j<count($slt_values);$j++)
						{
							echo "<option value='".$slt_values[$j]."'>".$slt_values[$j]."</option>";
						}
					echo "</select></td></tr>";
			echo "</table>";
			echo "<input type='submit' value='Подбор' /><input type='button' onclick='location.href=\"generate_tp.php\"' value='К началу' />";
			echo "</form>";
			/*if(isset($slots_name)){
			echo "<form action='generate_tp.php' method='post'>";
			echo "Целевой фрейм <b>".$frame_name."</b>";
			echo "<table border=1><input type='hidden' name='id_frame' value=".$point." />";
			for($i=0;$i<count($slots_name);$i++)
				{
					echo "<tr><td>".$slots_name[$i]." </td><td><select name=slt_".$slots_id[$i].">";
					echo "<option value=-1></option>";
					for($j=0;$j<count($slots_values[$i]);$j++)
						{
							echo "<option value='".$slots_values[$i][$j]."'>".$slots_values[$i][$j]."</option>";
						}
					echo "</select></td></tr>";
				}
			echo "</table>";
			echo "<input type='submit' value='Подбор' /><input type='button' onclick='location.href=\"generate_tp.php\"' value='Назад' />";
			echo "</form>";
			}else{
				echo "Фрейм <b>".$frame_name."</b> не содержит слотов!";
				echo "<input type='button' onclick='location.href=\"generate_tp.php\"' value='Назад' />";
			}*/
		}
	elseif(isset($slt_name)){
		echo "Найдено следующее решение:<br/>";
		echo "<form action='generate_tp.php' method='post'><table border=1>";
		echo "<input type='hidden' name='id_frame' value=".$point.">";
		for($i=0;$i<count($slt_name);$i++)
			{
				echo "<tr><td>".$slt_name[$i]." </td><td>".$slot_values[$i];
				echo "<input type='hidden' name='slt_".$slt_name[$i]."' value='".$slot_values[$i]."'</td></tr>";
			}
			
		echo "</table>";
		echo "<input type='submit'  value='Перейти к генерации ТП' />";
	}
	elseif(isset($id_frame)){
		if(isset($name)){
			echo "<p>По указанным параметрам был построен следующий ТП:</p>";
			echo "<form action='generate_tp.php' method='post'><table border=1><tr><td>ID</td><td>Операция</td></tr>";
			for($i=0;$i<count($name);$i++){
				echo "<tr><td><input type='hidden' name='ids[]' value=".$id_listop[$i].">".$id_listop[$i]."</td><td>".$name[$i]."</td></tr>";
			}
			echo "</table>";
			echo "Имя устройства:<input type='text' name='nomen' value=''><br/>";
			echo "<input type='submit'  value='Перейти к редактированию ТП' />";
			echo "<input type='button' onclick='location.href=\"generate_tp.php?point=".$id_frame."\"' value='Назад' /> </form>";
		}
		else{
			echo "<p>По данным параметрам ничего не найдено!</p>";
			echo "<input type='button' onclick='location.href=\"generate_tp.php?point=".$id_frame."\"' value='Назад' />";
		}
	}

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