<?php
require '../2_Projects/FileOperations.php';
$con = mysql_connect($website,$userid,$pw);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}

$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;
}
mysql_query("SET foreign_key_checks = 0",$con);
$scope_id = $_GET[scope_id];
$output_id = $_GET[output_id];
$master_id = $_GET[master_id];
$mode = $_GET[mode];
echo ("<head><link rel='stylesheet' type='text/css' href='../CSS/Font.css'></head>");
if($debug)echo ("<script>  document.write(document.URL); </script>");
if($mode == "edit"){
	// Cannot edit if attribute is entity
	if($scope_id == $master_id){
		echo ("This is the first entry in the scope. It has to be set to entity and cannot be edited");
		echo ("<button onclick='javascript:window.close()'>OK</button>");
		echo ("<script>	window.opener.document.location.href ='Scope.php?output_id={$output_id}';</script>");
		exit;
	}
}

// Actions when this script posts the form to itself
if($_GET[act] == "yes"){
	if($_POST[ruleField] == NULL)$_POST[ruleField] = "-";
	if($_POST[textField] == NULL)$_POST[textField] = "";

	// If user clicked cancel then delete scope entry "entity"
	if(isset($_POST[NotUpdateTable])){
		$res = mysql_query("SELECT COUNT(master_id) FROM Scope WHERE master_id = {$master_id}",$con);
		while($row = mysql_fetch_array($res))$mi = $row[0];
		if($mi == 1)mysql_query("DELETE FROM Scope WHERE master_id = {$master_id}",$con);

	}elseif($mode == "add" && $_POST[attribute] != "entity"){
		mysql_query("INSERT INTO Scope(output_id,attribute,rule,text,master_id)	VALUES({$output_id},'{$_POST[attribute]}','{$_POST[ruleField]}','{$_POST[textField]}',{$master_id})",$con);

	}elseif($mode == "add" && $_POST[attribute] == "entity"){
		$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Scope'",$con);
		mysql_query("INSERT INTO Scope(output_id,attribute)	VALUES({$output_id},'{$_POST[attribute]}')",$con);
//		$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
		while($row = mysql_fetch_array($res))$mi = $row[0];
		mysql_query("UPDATE Scope SET master_id={$mi} WHERE scope_id={$mi}",$con);

	}elseif($mode == "edit" && $_POST[attribute] == "entity"){
		// Not allowed taken care of in "mode = edit" block above

	}elseif($mode == "edit" && $_POST[attribute] != "entity"){
		//Delete all scope_id greater than & equal to {$scope_id} where master_id = {$master_id}
		mysql_query("DELETE FROM Scope WHERE scope_id >= {$scope_id} AND master_id = {$master_id}",$con);

		// Now insert the new scope in
		mysql_query("INSERT INTO Scope(output_id,attribute,rule,text,master_id)	VALUES({$output_id},'{$_POST[attribute]}','{$_POST[ruleField]}','{$_POST[textField]}',{$master_id})",$con);
	}
	echo ("<script>	window.opener.document.location.href ='Scope.php?output_id={$output_id}';</script>");
	echo ("<script>window.close()</script>");
}

if($master_id == NULL || $master_id == 0){
	$res = mysql_query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'Scope'",$con);
	mysql_query("INSERT INTO Scope(attribute,output_id) VALUES('entity',{$output_id})",$con);
//	$res = mysql_query("SELECT LAST_INSERT_ID()",$con);
	while($row = mysql_fetch_array($res))$mi = $row[0];
	mysql_query("UPDATE Scope SET master_id={$mi} WHERE scope_id={$mi}",$con);

	// Recall this page
	Header("Location: AddEditScope.php?mode={$mode}&scope_id={$scope_id}&output_id={$output_id}&master_id={$mi}");
}

// List all attributes owned by entities that are scoped on
echo ("<form action='AddEditScope.php?act=yes&output_id={$output_id}&mode={$mode}&master_id={$master_id}&scope_id={$scope_id}' method='post'>");
echo ("<table>");
echo ("<tr>");
echo("<td>Available tags </td>");

$m = 0;
$res = mysql_query("SELECT COUNT(scope_id) FROM Scope WHERE master_id={$master_id}",$con);
while($row = mysql_fetch_array($res))$m = $row[0];
if($m == 0 || $m == 1){ // no scopes have been defined so select everything for display
	echo ("<td><select name='attribute'>
				<option disabled>Static Attributes</option>");

	$result1 = mysql_query("SELECT DISTINCT(attribute) AS attribute FROM Static;",$con);
	while ($rowA = mysql_fetch_array($result1))echo("<option>" .$rowA[0]. "</option>");

	echo ("<option disabled>Dynamic Attributes</option>");
	$result1 = mysql_query("SELECT DISTINCT(attribute) AS attribute FROM Dynamic;",$con);
	while ($rowA = mysql_fetch_array($result1))echo("<option>" .$rowA[0]. "</option>");
	echo("</select></td></tr>");
	echo("<tr><td>Rule</td>");
	echo("<td><select name='ruleField'>
			<option>-</option>
			<option>=</option>
			<option>Contains</option>
			</select>
			</td>");
	echo("</tr>");
	echo("<tr><td>Text</td>");
	echo ("<td><input type='text' autocomplete='off' name='textField' maxlength = '60' size = '60'></td>");
	echo("</tr>");

}else{ // previous scopes have been defined develop hierarchy
	$resultA = mysql_query("SELECT attribute,rule,text FROM Scope WHERE scope_id = {$m}",$con);
	//echo("SELECT attribute,rule,text FROM Scope WHERE scope_id = {$master_id} <br/>");
	while($rowA = mysql_fetch_array($resultA)){
		$attribute = $rowA[0];
		$ruleC = $rowA[1];
		$textC = $rowA[2];
	}
	echo ("<td>
	<select name='attribute'>
	<option>entity</option>"); // set attribute equal or not equal to "entity" so that it can be treated accordingly when posting this form

	// First display Static
	$ii = 0;
	$NumSelectedSourceID = 0;
	$SelectedSourceID = array();
	$KeepSourceID = array();
	$resultA = mysql_query("SELECT COUNT(source_id) FROM Source",$con);
	while($rowA = mysql_fetch_array($resultA))$COUNTsource_id = $rowA[0];
	if($COUNTsource_id > 0){
		$resultA = mysql_query("SELECT source_id FROM Source",$con);
		while($rowA = mysql_fetch_array($resultA)){
			$SelectedSourceID[$ii] = $rowA[0];
			$ii++;
		}
		$NumSelectedSourceID = $ii;
	}

	$ii = 0;
	$resultA = mysql_query("SELECT scope_id,attribute,rule,text FROM Scope WHERE master_id={$master_id}",$con);
	////echo("<option>SELECT scope_id,attribute,rule,text FROM Scope WHERE master_id={$master_id}</option>");
	unset($KeepSourceID);
	$KeepSourceID = array();
	while($rowA = mysql_fetch_array($resultA)){
		$AttFromScope = $rowA[1];
		if($AttFromScope == "entity")continue;
		$rule = $rowA[2];
		$text = $rowA[3];

		$resultB = mysql_query("SELECT COUNT(source_id) FROM Static",$con);
		while($rowB = mysql_fetch_array($resultB))$COUNTsource_id = $rowB[0];
		if($COUNTsource_id > 0){
			$resultB = mysql_query("SELECT source_id,attribute,value FROM Static",$con);
			while($rowB = mysql_fetch_array($resultB)){
				$Sid = $rowB[0];
				$AttFrom = $rowB[1];
				$ValueFromStatic = $rowB[2];
				if($rule == "-"){ // get this scope if Static.attribute = Scope.attribute
					if($AttFromScope == $AttFrom){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>- Got $AttFrom with source_id $Sid</option>");
					}
				}elseif($rule == "="){ // get this scope if Static.value equals Scope.text
					if($text == $ValueFromStatic){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>= Got $AttFrom with source_id $Sid</option>");
					}
				}elseif($rule == "Contains"){ // get this scope if Static.value contains Scope.text
					if(gettype(strpos($ValueFromStatic,$text)) == "integer"){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>C Got $AttFrom with source_id $Sid</option>");
					}
				}// More rules to be added here
			}
		}
		$NumKeepSourceID = $ii;

		for($m = 0; $m < $NumSelectedSourceID; $m++){
			$keep = false;
			for($n = 0; $n < $NumKeepSourceID; $n++){
				if($SelectedSourceID[$m] == $KeepSourceID[$n]){
					$keep = true;
				}
			}
			if(!$keep)$SelectedSourceID[$m] = 0;
		}
	}

	// Get total number of source_id to display static (and later dynamic) attributes for
	$nStatic = 0;
	for($m = 0; $m < $NumSelectedSourceID; $m++){
		if($SelectedSourceID[$m] != 0)$nStatic++;
	}

	// Make string to display to user
	if($nStatic > 0){
		$stringStatic = "source_id = ";
		for($m = 0; $m < $NumSelectedSourceID; $m++){
			if($SelectedSourceID[$m] != 0 || $SelectedSourceID[$m] != NULL){
				$stringStatic .= $SelectedSourceID[$m] . " OR source_id = ";
			}
		}
		$stringStatic = rtrim($stringStatic, " OR source_id = ");
		//echo ("<option> stringStatic = {$stringStatic} </option>");
	}

	// Now display dynamic scopes
	$ii = 0;

	unset($SelectedSourceID);
	$SelectedSourceID = array();
	$KeepSourceID = array();
	$resultA = mysql_query("SELECT COUNT(source_id) FROM Source",$con);
	while($rowA = mysql_fetch_array($resultA))$COUNTsource_id = $rowA[0];
	if($COUNTsource_id > 0){
		$resultA = mysql_query("SELECT source_id FROM Source",$con);
		while($rowA = mysql_fetch_array($resultA)){
			$SelectedSourceID[$ii] = $rowA[0];
			$ii++;
		}
		$NumSelectedSourceID = $ii;
	}

	$resultA = mysql_query("SELECT scope_id,attribute,rule,text FROM Scope WHERE master_id={$master_id}",$con);
	unset($KeepSourceID);
	$KeepSourceID = array();
	while($rowA = mysql_fetch_array($resultA)){
		$AttFromScope = $rowA[1];
//echo("<option>AttFromScope = {$AttFromScope} </option>");
		if($AttFromScope == "entity")continue;
		$rule = $rowA[2];
		$text = $rowA[3];
		$resultB = mysql_query("SELECT COUNT(source_id) FROM Dynamic",$con);
		while($rowB = mysql_fetch_array($resultB))$COUNTsource_id = $rowB[0];
		if($COUNTsource_id > 0){
			$resultB = mysql_query("SELECT source_id,attribute,value FROM Dynamic",$con);
			while($rowB = mysql_fetch_array($resultB)){
				$Sid = $rowB[0];
				$AttFrom = $rowB[1];
				$ValueFromDynamic = $rowB[2];
//echo("<option> att from dynamic {$AttFrom}</option>");
//echo("<option> value from dynamic {$ValueFromDynamic}</option>");
				if($rule == "-"){ // get this scope if Dynamic.attribute = Scope.attribute
					if($AttFromScope == $AttFrom){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>- Got $AttFrom with source_id $Sid</option>");
					}
				}elseif($rule == "="){ // get this scope if Static.value equals Scope.text
					if($text == $ValueFromDynamic){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>= Got $AttFrom with source_id $Sid</option>");
					}
				}elseif($rule == "Contains"){ // get this scope if Static.value contains Scope.text
					if(gettype(strpos($ValueFromDynamic,$text)) == "integer"){
						$KeepSourceID[$ii] = $Sid;
						$ii++;
						//echo("<option>Contains Got $AttFrom with source_id $Sid</option>");
					}
				}// More rules to be added here



				/*
				if($AttFromScope == $AttFrom){
					$KeepSourceID[$ii] = $Sid;
					$ii++;
				}
				*/
			}
		}
		$NumKeepSourceID = $ii;
		//echo("<option>NumKeepSourceID = {$NumKeepSourceID}</option>");
		//echo("<option>KeepSourceID = {$KeepSourceID[0]}</option>");
		//echo("<option>KeepSourceID = {$KeepSourceID[1]}</option>");
		//echo("<option>KeepSourceID = {$KeepSourceID[2]}</option>");
		for($m = 0; $m < $NumSelectedSourceID; $m++){
			$keep = false;
			for($n = 0; $n < $NumKeepSourceID; $n++){
				if($SelectedSourceID[$m] == $KeepSourceID[$n]){
					$keep = true;
				}
			}
			if(!$keep)$SelectedSourceID[$m] = 0;
		}
	}

	// Get total number of source_id to display dynamic attributes for
	$nDynamic = 0;
	for($m = 0; $m < $NumSelectedSourceID; $m++){
		if($SelectedSourceID[$m] != 0)$nDynamic++;
	}

	// Display to user
	if($nDynamic > 0){
		$stringDynamic = "source_id = ";
		for($m = 0; $m < $NumSelectedSourceID; $m++){
			if($SelectedSourceID[$m] != 0 || $SelectedSourceID[$m] != NULL){
				$stringDynamic .= $SelectedSourceID[$m] . " OR source_id = ";
			}
		}
		$stringDynamic = rtrim($stringDynamic, " OR source_id = ");
		//echo ("<option> stringDynamic = {$stringDynamic} </option>");
	}
	if($nStatic > 0 && $nDynamic == 0){
		$string = $stringStatic;
	}elseif($nStatic == 0 && $nDynamic > 0){
		$string = $stringDynamic;
	}else{
		$string = $stringStatic . " OR " . $stringDynamic;
	}
	//echo("<option> nS = $nStatic nD = $nDynamic</option>");
	//echo("<option> string = $string </option>");
	//echo ("<option> 1  scope_id {$scope_id} attribute {$attribute} rule {$ruleC} text {$textC}</option>");
	echo("<option disabled>Static Attributes</option>");
	$resultA = mysql_query("SELECT COUNT(attribute) FROM Static WHERE {$string}",$con);
	while($rowA = mysql_fetch_array($resultA))$COUNTsource_id = $rowA[0];
	if($COUNTsource_id > 0){
		$resultA = mysql_query("SELECT DISTINCT(attribute) FROM Static WHERE {$string}",$con);
		while($rowA = mysql_fetch_array($resultA)){
			$selected = "";
			if($attribute == $rowA[0])$selected = " selected ";
			echo("<option {$selected}>{$rowA[0]}</option>");
		}
	}
	echo("<option disabled>Dynamic Attributes</option>");
	$resultA = mysql_query("SELECT COUNT(attribute) FROM Dynamic WHERE {$string}",$con);
	while($rowA = mysql_fetch_array($resultA))$COUNTsource_id = $rowA[0];
	if($COUNTsource_id > 0){
		$resultA = mysql_query("SELECT DISTINCT(attribute) FROM Dynamic WHERE {$string}",$con);
		while($rowA = mysql_fetch_array($resultA)){
			$selected = "";
			if($attribute == $rowA[0])$selected = " selected ";
			echo("<option {$selected}>{$rowA[0]}</option>");
		}
	}

	// Close the select block
	echo("</select></td></tr>");


	// Output rule and text
	if($ruleC == "-"){
		$SelectAll = " selected ";
	}elseif($ruleC == "="){
		$Equals = " selected ";
	}elseif($ruleC == "Contains"){
		$Contains = " selected ";
	}
	echo("<tr><td>Rule</td>");
	echo("<td><select name='ruleField'>
			<option {$SelectAll}>-</option>
			<option {$Equals}>=</option>
			<option {$Contains}>Contains</option>
			</select>
			</td>");
	echo("</tr>");
	echo("<tr><td>Text</td>");
	echo ("<td><input type='text' autocomplete='off' name='textField' maxlength = '60' size = '60' value={$textC}></td>");
	echo("</tr>");

}

//echo ("</tr>");
echo ("</table>");
echo ("<button 	type='submit' name='UpdateTable' value='OK'>OK</button>&nbsp");
echo ("<button type='submit' name='NotUpdateTable' value='Cancel'>Cancel</button>");
echo ("</form>");
?>
