<?php

require '../2_Projects/FileOperations.php';
$StdRend = $StandardRendering;
$con = mysql_connect($website,$userid,$pw);
if (!$con) {
	 die('Could not connect: ' . mysql_error());
}
mysql_query("SET foreign_key_checks = 0",$con);

$curDB = "../CurrentlyOpenedDBName.tmp";
if(file_exists ($curDB)){
	$f = fopen($curDB, "r");
	$dbase   = trim(fgets($f)); // linked database name
	fclose($f);
	mysql_select_db($dbase, $con);
	//echo "Connected to " . $dbase . "<br/>";
}else{
	//No database currently open
	return;
}
echo ("<head><link rel='stylesheet' type='text/css' href='../CSS/Font.css'></head>");
if($debug)echo ("<script>  document.write(document.URL); </script>");
if($_GET[act] == "yes"){
	if(isset($_POST[NotUpdateTable])){
		 echo("<script>document.getElementById('#Return').click();</script>");
	}
	if(isset($_POST[UpdateTable])){
		 if($_GET[PK] == "add"){
		 $res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Dynamic'",$con);

		 if(CurrentlyFetchingData($con)){
				echo "Cannot create new attributes while data fetch is running, stop data fetch.
				<a href='../Common/BlankPage.html' > <button  type='button'>OK</button>  	</a>";
				exit;
			}
			// Data fetch is always to be stopped when adding more dynamic entities
			mysql_query("INSERT INTO Dynamic(source_id,attribute,value,status)
						                    VALUES({$_GET[FK]},'{$_POST[attributeField]}','{$_POST[valueField]}','stopped')",$con);
			//$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
			while($row = mysql_fetch_array($res))$PK = $row[0];
			$_GET[PK] = $PK; // Overload so that code below this section will work if an index is passed to $_GET[PK] and also if "add" is passed
		}else{
			mysql_query("UPDATE Dynamic SET attribute='{$_POST[attributeField]}' WHERE dynamic_id={$_GET[PK]}",$con);
			mysql_query("UPDATE Dynamic SET value='{$_POST[valueField]}' WHERE dynamic_id={$_GET[PK]}",$con);
		}

		// If fetcher has not been linked then create fetcher now
		if($_POST[fetcher_id] == "add"){
			$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Fetcher'",$con);

			mysql_query("INSERT INTO Fetcher(input_method) VALUES('{$_POST[inputField]}')",$con);

			//$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
			while($row = mysql_fetch_array($res))$mi = $row[0];
			mysql_query("UPDATE Dynamic SET fetcher_id = {$mi} WHERE dynamic_id = {$PK}",$con);
		}else{
			mysql_query("UPDATE Fetcher SET input_method='{$_POST[inputField]}' WHERE fetcher_id = {$_POST[fetcher_id]}",$con);
			mysql_query("UPDATE Dynamic SET fetcher_id={$_POST[fetcher_id]} WHERE dynamic_id={$_GET[PK]}",$con);
		}
		if($_POST[inputField] == "MDF")mysql_query("UPDATE Dynamic SET MDF_status='MDF' WHERE dynamic_id={$_GET[PK]}",$con);

		echo ("<a id='#Return' href='../Common/BlankPage.html' target='WorkingFrame'></a> ");
		echo ("<a id='#ReloadTopRight' href='RightTop.php' target='TopRightFrame'></a> ");
		echo ("<a id='#Reload1' href='Dynamic.php?source_id={$_GET[FK]}&dynamic_id={$_GET[PK]}' target='DynamicFrame'></a> ");
		echo ("<a id='#Reload2' href='Source.php?source_id={$_GET[FK]}&loadothers=no' target='SourceFrame'></a> ");

		// If fetcher is fileX then create directory structure
		$res = mysql_query("SELECT source_id FROM Dynamic WHERE dynamic_id={$PK}",$con);
		while ($row = mysql_fetch_array($res))$source_id = $row[0];
		$res = mysql_query("SELECT name FROM Source WHERE source_id = {$source_id}",$con);
		while ($row = mysql_fetch_array($res))$source_name = $row[0];
		$res = mysql_query("SELECT attribute FROM Dynamic WHERE dynamic_id = {$PK}",$con);
		while ($row = mysql_fetch_array($res))$dyn_attrib = $row[0];

		$source_dir = preg_replace('/\s+/', '_', $source_name);
		$dyn_dir = preg_replace('/\s+/', '_', $dyn_attrib);

		if(!file_exists("../../Inputs/FileX"))mkdir("../../Inputs/FileX");
		if(!file_exists("../../Inputs/FileX/{$dbase}"))mkdir("../../Inputs/FileX/{$dbase}");
		if(!file_exists("../../Inputs/FileX/{$dbase}/{$source_name}_{$source_id}"))mkdir("../../Inputs/FileX/{$dbase}/{$source_dir}_{$source_id}");
		if(!file_exists("../../Inputs/FileX/{$dbase}/{$source_name}_{$source_id}/{$dyn_attrib}_{$_GET[PK]}"))mkdir("../../Inputs/FileX/{$dbase}/{$source_dir}_{$source_id}/{$dyn_dir}_{$_GET[PK]}");

		echo("<script>document.getElementById('#Reload2').click();</script>");
		echo("<script>document.getElementById('#Reload1').click();</script>");
		echo("<script>document.getElementById('#Return').click();</script>");
		echo("<script>document.getElementById('#ReloadTopRight').click();</script>");
	}
}

$PK = $_GET[PK];
$FK = $_GET[FK];
if($PK == "add"){
	$add = true;
	$edit = false;
}else{
	$add = false;
	$edit = true;
}
if($edit){
	$res = mysql_query("SELECT count(attribute) FROM Dynamic WHERE dynamic_id={$PK}",$con);
	$res = mysql_query("SELECT attribute,value,status FROM Dynamic WHERE dynamic_id={$PK}",$con);
	while($row = mysql_fetch_array($res)){
		$attribute = $row[0];
		$value = $row[1];
		$status = $row[2];
	}
}

echo ("<form action='AddEditDynamic.php?act=yes&PK={$PK}&FK={$FK}' method='post'<br/>");
echo ("<table><br/>");
echo ("<tr>");
echo ("<td> <button type='submit' {$StdRend} >Tag </button></td>");
echo 	("<td><input 	type='text' autocomplete='off'
						name='attributeField'
						value='{$attribute}'
						maxlength = '{$smaStr}'
						size = '60'
						placeholder='Enter attribute name here'>
		</td>");
echo ("</tr>");
echo ("<tr>");
echo ("<td> <button type='submit' {$StdRend} >Value </button></td>");
echo 	("<td><input 	type='text'  autocomplete='off'
						name='valueField'
						value='{$value}'
						maxlength = '{$smaStr}'
						size = '60'
						placeholder='Enter value here'>
		</td>");
echo ("</tr>");

// Get linked fetcher
if($PK != "add"){
	$res = mysql_query("SELECT COUNT(fetcher_id) FROM Dynamic WHERE dynamic_id={$PK}",$con);
	while($row = mysql_fetch_array($res))$Kount = $row[0];
}
if($Kount > 0){ // fetcher has previously been linked
	$res = mysql_query("SELECT fetcher_id FROM Dynamic WHERE dynamic_id={$PK}",$con);
	while($row = mysql_fetch_array($res))$fetcher_id = $row[0];

	$res = mysql_query("SELECT input_method FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
	while($row = mysql_fetch_array($res))$input_method = $row[0];
	if($input_method == "Manual"){
		$Manual = "selected";
	}elseif($input_method == "File Exchange"){
		$FileX = "selected";
	}elseif($input_method == "Online"){
		$Online = "selected";
	}elseif($input_method == "MDF"){
		$MDF = "selected";
	}
}else{
	$fetcher_id = "add";
}
echo ("<tr>");
echo ("<td><button type='submit' {$StdRend} > Input method </button></td>");
echo 	("<td>
		<select name='inputField'>");
if(!$DemoMode)echo("<option {$Manual}> Manual </option>");
echo ("<option {$FileX}> File Exchange </option>
		   <option {$Online} value='Online'> Device </option>");
if(!$DemoMode)echo("<option {$MDF}> MDF </option>");

echo("		</select></td>");
echo ("</tr>");
echo ("</table><br/>");
echo ("<input type='hidden' name='fetcher_id' value='{$fetcher_id}' />");
echo ("<button type='submit' name='UpdateTable' value='OK' >OK</button>&nbsp");
echo ("<button type='submit' name='NotUpdateTable' value='Cancel' >Cancel</button>");
echo ("</form><br/>");

?>
