<?php
require '../2_Projects/FileOperations.php';
$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);
}else{
	return;
}
echo ("<head><link rel='stylesheet' type='text/css' href='../CSS/Font.css'>

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js'></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $('p').toggle();
    });
});
</script>
<STYLE TYPE='text/css'>

TD{font-size: 10pt;}

</STYLE>
</head>");

if($debug)echo ("<script>document.write(document.URL); </script>");

$fetcher_id = $_GET[fetcher_id];
$MDF_id = $_GET[MDF_id];

$start_time_day = $_POST[start_hour] . ":" . $_POST[start_minute];
$stop_time_day = $_POST[stop_hour] . ":" . $_POST[stop_minute];
if(count($_POST[day_of_week]) > 0)foreach($_POST[day_of_week]  as $str)$dow .= $str . ",";
if($start_time_day == ":")$start_time_day = "";
if($stop_time_day == ":")$stop_time_day = "";
if($dow == ",")$dow = "";
$dom = $_POST[day_of_month];

// Perform DB actions (add/edit)
if(isset($_POST["NotUpdateTable"]))header("Location: MDF.php");
if(isset($_POST["UpdateTable"])){
	// Add MDF fetcher and frequency information
	if($fetcher_id == "add" && $MDF_id == "add"){

		// exit if name not defined
		if($_POST[name_Field] == "" || $_POST[name_Field] == NULL){
			echo "Please go back and define name";
			echo ("<form action='MDF.php'><input type='submit' value='BACK' /></form>");
			exit;
		}

		//$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
		$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Fetcher'",$con);
		while($row = mysql_fetch_array($res))$fetcher_id = $row[0];
		$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Frequency'",$con);
		while($row = mysql_fetch_array($res))$frequency_id = $row[0];
		//mysql_query("INSERT INTO Frequency(times_per_period,period) VALUES('{$_POST[TPPField]}','{$_POST[TimeSpan]}')",$con);
		mysql_query("INSERT INTO Frequency(period,times_per_period,sta_tm_day,end_tm_day,day_o_week,day_o_mnth)
																VALUES('{$_POST[TimeSpan]}','{$_POST[TPPField]}','{$start_time_day}','{$stop_time_day}','{$dow}','{$dom}')",$con);

		mysql_query("INSERT INTO Fetcher(name,description,frequency_id,EG_user,EG_password,EG_appdestinationLocal,EG_IP) VALUES('MDF{$_POST[name_Field]}','{$_POST[descrField]}','{$frequency_id}','{$_POST[unameField]}','{$_POST[pwdField]}','{$_POST[appField]}','{$_POST[IPField]}')",$con);

	// Update MDF fetcher and frequency information as edited in the GUI
	}elseif($fetcher_id == $MDF_id){
		$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
		while($row = mysql_fetch_array($res))$frequency_id = $row[0];
		mysql_query("UPDATE Fetcher SET name='MDF{$_POST[name_Field]}',
																		description='{$_POST[descrField]}',
																		EG_user='{$_POST[unameField]}',
																		EG_password='{$_POST[pwdField]}',
																		EG_appdestinationLocal='{$_POST[appField]}',
																		EG_IP='{$_POST[IPField]}' WHERE fetcher_id={$fetcher_id}",$con);

		mysql_query("UPDATE Frequency SET period='{$_POST[TimeSpan]}',
											times_per_period='{$_POST[TPPField]}',
											sta_tm_day = '{$start_time_day}',
											end_tm_day = '{$stop_time_day}',
											day_o_week = '{$dow}',
											day_o_mnth = '{$dom}'
									WHERE frequency_id = '{$frequency_id}'",$con);
	}
	if(isset($_POST[createentities])){
		mysql_query("UPDATE HighLevInfo SET value='yes' WHERE name = 'MDF'",$con);
	}else{
		mysql_query("UPDATE HighLevInfo SET value='no' WHERE name = 'MDF'",$con);
	}
	header("Location: MDF.php");
}

// Insert previously stored values into the GUI
if($fetcher_id != "add" && $MDF_id != "add"){
	$res = mysql_query("SELECT name,description,frequency_id,EG_user,EG_password,EG_appdestinationLocal,EG_IP FROM Fetcher WHERE fetcher_id={$fetcher_id}",$con);
	while($row = mysql_fetch_array($res)){
		$name	= substr($row[0],3);
		$description	= $row[1];
		$frequency_id	= $row[2];
		$EG_user	= $row[3];
		$EG_password	= $row[4];
		$EG_appdestinationLocal	= $row[5];
		$EG_IP	= $row[6];
	}
	if($frequency_id > 0){
		$res = mysql_query("SELECT times_per_period,period,sta_tm_day,end_tm_day,day_o_week,day_o_mnth  FROM Frequency WHERE frequency_id={$frequency_id}",$con);
		while($row=mysql_fetch_array($res)){
			$times_per_period = $row[0];
			$period = $row[1];
			$start_time_day = $row[2];
			$stop_time_day = $row[3];
			$day_of_week = $row[4];
			$day_of_month = $row[5];
		}

		$sel_min = "";
		$sel_hr = "";
		$sel_day= "";
		$sel_wk = "";
		$sel_mnth = "";
		if($period == "MINUTE"){
			$sel_min = "selected";
		}elseif($period == "HOURLY"){
			$sel_hr = "selected";
		}elseif($period == "DAILY"){
			$sel_day= "selected";
		}elseif($period == "WEEKLY"){
			$sel_wk = "selected";
		}elseif($period == "MONTHLY"){
			$sel_mnth = "selected";
		}elseif($period == "" || $period = NULL){
		}else{
			echo ("<h3> old format frequency defined please delete and redefine </h3>");
		}
	}
}
$res = mysql_query("SELECT value FROM HighLevInfo WHERE name='MDF'",$con);
while($row=mysql_fetch_array($res))$MDF_ON=$row[0];
if($MDF_ON == "yes")$MDF_ON = "checked";

// Extract information about local apps
$handle = fopen("AppList.txt","r");
$i = 0;
$applist = array();
$tokens = array();
while (($line = fgets($handle)) != false) {
	if(substr($line,0,1) != "#"){
		$tokens = explode(",",$line);
		$applist[$i] = $tokens[0];
		$exelist[$i] = $tokens[1];
		$i++;
	}
}
fclose($handle);

// Display form
echo("
	<form action='AddEditMDF.php?act=updateTable&MDF_id={$fetcher_id}&fetcher_id={$fetcher_id}' method='post' id='main_form'>
	<table>
	<tr>
		<td>Name</td>
		<td><input 	type='text'  	name='name_Field'	 value='{$name}'	size = '60' /></td>
	</tr><tr>
		<td>Parameters</td>
		<td><input 	type='text'  	name='descrField'	value='{$description}'	size = '60' /></td>
	</tr><tr>
		<td>IP address</td>
		<td><input 	type='text'  	name='IPField'	value='{$EG_IP}'	size = '60' /></td>
	</tr><tr>
		<td>User name</td>
		<td><input 	type='text'  	name='unameField'	value='{$EG_user}'	size = '60' /></td>
	</tr><tr>
		<td>Password</td>
		<td><input 	type='password'  	name='pwdField'	value='{$EG_password}'	size = '60' /></td>
	</tr><tr>
		<td>Frequency</td>
		<td><input type='number' min='1' step='1' size='40' name='TPPField' value='{$times_per_period}'/>

		<select name='TimeSpan'>
		<option value = 'MINUTE'  {$sel_min}>Minute(s)</option>
		<option value = 'HOURLY'  {$sel_hr}>Hour(s)</option>");
if($oper_sys == "windows"){
      echo ("	<option value = 'DAILY'   {$sel_day}>Day(s)</option>
      				<option value = 'WEEKLY'  {$sel_wk}>Week(s)</option>
      				<option value = 'MONTHLY' {$sel_mnth}>Month(s)</option>");
}
echo ("</select>
	</tr><tr>
		<td>App</td>
		<td>");

		echo ("<select name='appField' >");
		$i = 0;
		foreach($exelist as $item){
			if(trim($item) == trim($EG_appdestinationLocal))$j = $i;
			$i++;
		}
		$i = 0;
		foreach($applist as $item){
			$selected = "";
			if($i == $j)$selected = "selected";
			echo "<option  {$selected} value=\"{$exelist[$i]}\" name=\"{$exelist[$i]}\">{$item}</option>";
			$i++;
		}
echo ("</select>");
echo("
		</td>
	</tr>
</table><table>
	<tr>
		<td>Create dynamic entities from fetched file?</td>
		<td><input 	type='checkbox'  	name='createentities'	{$MDF_ON}/></td>
	</tr>
</table>
<button type='submit' name='UpdateTable' value='OK' >OK</button>
<button type='submit' name='NotUpdateTable' value='Cancel' >Cancel</button>
<br/>
</form>
");

if($GeekMode)echo_advanced_frequency_options("main_form",$start_time_day,$stop_time_day,$day_of_week,$day_of_month,$oper_sys);
echo("
");
?>
