<?php

require '../Common/openDB.php';
$StdRend = $StandardRendering;
$SelRend = $SelectedRendering;
$NSelRend = $NotSelectedRendering;
$NPTR = $NonPrintingTitleRendering;
$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;
}

$selectionMade = false;

echo ("
<html>
<head>
   	<link rel='stylesheet' type='text/css' href='../CSS/Font.css'>
	<link rel='stylesheet' type='text/css' href='../CSS/HeaderContentFooter.css'>
	<link rel='stylesheet' type='text/css' href='../CSS/Buttons.css'>

	<!-- ALternate lines have different colours -->
	<style type='text/css'>
      tr:nth-child(2n) {
             background-color: #f2f2f2;
        }
	</style>
</head>
<body>
");

// Get output_id if specified
$output_id = $_GET[output_id];
$res = mysql_query("SELECT COUNT(scope_id) FROM Scope",$con);
while($row = mysql_fetch_array($res))$NumScopes = $row[0];

echo ("<form method='post'>");
echo ("<div id='header'>");
echo ("<h4>Scope definition");
if($debug)echo ("<script>  document.write(document.URL); </script>");
echo ("</h4></div>");
echo ("<div id='content'>");
if($NumScopes > 0){
	echo ("<table width='100%'>");
	if($output_id != NULL){
		$res = mysql_query("SELECT count(scope_id) FROM Scope WHERE output_id={$output_id}",$con);
		while($row = mysql_fetch_array($res))$NumScopesWithThisFK = $row[0];
		if($NumScopesWithThisFK > 0){
			echo ("<tr><td>
					<button type='submit' {$StdRend} > <b> Tag </b> </button>
				</td>
				<td>
					<button type='submit' {$StdRend} > <b> Rule </b> </button>
				</td>
				<td>
					<button type='submit' {$StdRend} > <b> Value </b> </button>
				</td>
				<!--td>
					<button type='submit' {$StdRend} > <b> Matches </b> </button>
				</td-->
			</tr>");
			$res = mysql_query("SELECT scope_id,attribute,rule,text,master_id FROM Scope WHERE output_id={$output_id} ORDER BY master_id ASC, scope_id ASC",$con);
			$master_id = 0;
			while($row = mysql_fetch_array($res)){
				$show = true;
				if(!$GeekMode){
					$resX = mysql_query("SELECT MIN(master_id) FROM Scope WHERE output_id = {$output_id}",$con);
					while($rowX = mysql_fetch_array($resX))$mmid = $rowX[0];
					if($row[4] > $mmid)$show = false;
					if($row[1] == "entity")$show = false;
					$hover_text = "";
				}else{
					$hover_text = "Select a scope or scoped item and press + to add to THAT scope \nOR press + with scope deselected to add a new scope";
				}
				if(!$show)continue;
				$attribute = $row[1];
				$rule = $row[2];
				$text = $row[3];
				if($attribute == "entity" && $DemoMode)continue;
				if($attribute == "entity"){$attribute = "---";$rule="---";$text="---";}
				if($rule == "-")$text = "";
				if($_GET[delete] != NULL){
					// Get master_id of this scope and delete all scope_id greater than or equal to this with same master_id
					$resultA = mysql_query("SELECT master_id FROM Scope WHERE scope_id = {$_GET[delete]}",$con);
					while($rowA = mysql_fetch_array($resultA))$mi = $rowA[0];
					mysql_query("DELETE FROM Scope WHERE scope_id>={$_GET[delete]} AND master_id = {$mi}",$con);
					header("Location: Scope.php?output_id={$output_id}");
				}else{
					echo ("<tr>");
					if($_POST[selectedItem2] == $row[0]){
						$scope_id = $_POST[selectedItem2];
						$selected_id = $scope_id;
						$master_id = $row[4];
						$Render = $SelRend;
					}else{
						$Render = $NSelRend;
					}
					//if($attribute == "entity"){$attribute = "*";$rule=" ";$text=" ";$Render=$NPTR;}
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2'
						formaction='Scope.php?scope_id={$row[0]}&output_id={$output_id}'
						title='{$hover_text}' > &nbsp" .$attribute. "</button>
						</td>");
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2'
						formaction='Scope.php?scope_id={$row[0]}&output_id={$output_id}' > &nbsp" .$rule. "</button>
						</td>");
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2'
						formaction='Scope.php?scope_id={$row[0]}&output_id={$output_id}' > &nbsp" .$text. "</button>
						</td>");

					/*
					echo (	"<td>".
						"<button type='submit' {$Render} value= '" . $row[0] . "' name = 'selectedItem2'
						formaction='Scope.php?scope_id={$row[0]}&output_id={$output_id}' > &nbsp" .$Matches. "</button>
						</td>");
					*/
					echo ("</tr>");

				}
			}
		}
	}
	echo("</table>");
}
echo "</div>";
echo ("<div id='footer'>");
if($output_id != NULL){
	if(!$GeekMode){ // Get minimum master_id for this output_id
		$res = mysql_query("SELECT MIN(master_id) FROM Scope WHERE output_id = {$output_id}",$con);
		while($row = mysql_fetch_array($res))$master_id = $row[0];
	}
	echo ("<button class='btnAdd' type='submit' name='AddRecord' formaction='Scope.php?master_id={$master_id}&output_id={$output_id}'>+</button>");
}
if($scope_id != NULL){

	// Get number of matches
	$res = mysql_query("SELECT attribute,rule,text FROM Scope WHERE scope_id = {$scope_id}",$con);
	while($row = mysql_fetch_array($res)){
		$Matches = getMatchedEntities($row[0],$row[1],$row[2],$con,"both");
	}

	echo ("<button class='btnEdit' type='submit' name='EditRecord' formaction='Scope.php?master_id={$master_id}' style='float: right;'>Edit</button>");
	echo "<button class='btnDelete' type='submit' value= '" . $row[0] . "' name = 'delete'
		formaction='Scope.php?delete=$scope_id&output_id=$output_id' >−</button>";
	echo ("<a style='float:right;'> Matched: {$Matches} </a>");
}
echo ("<input type='hidden' name='scope_id' value='{$scope_id}'/>");
echo ("<input type='hidden' name='master_id' value='{$master_id}'/>");
echo ("<input type='hidden' name='output_id' value='{$output_id}'/>");
echo ("</div>");
echo ("</form>");

// Redirect execution based on JS
echo ("<a id='#AddRecord' href='#' onClick=\" window.open('AddEditScope.php?mode=add&scope_id=add&output_id={$_POST[output_id]}&master_id={$_POST[master_id]}','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a><br/> ");
//echo ("<a id='#AddRecord' href='#' onClick=\" window.open('../Common/BlankPage.html','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a><br/> ");
echo ("<a id='#EditRecord' href='#' onClick=\" window.open('AddEditScope.php?mode=edit&scope_id={$_POST[scope_id]}&output_id={$_POST[output_id]}&master_id={$_POST[master_id]}','MyWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=yes,width=600,height=400') \"></a><br/> ");

if(isset($_POST[AddRecord]))echo("<script>document.getElementById('#AddRecord').click();</script>");
if(isset($_POST[EditRecord]))echo("<script>document.getElementById('#EditRecord').click();</script>");

echo ("</body></html>");
?>
