<?php
session_start();
?>
<?
	include("user.php");
	include("class.php");
	include("topic.php");
	@include("article.php");
	
	if ($_SESSION['user']) {
		if ($_SESSION['admin'] == 0)
			header("Location: index.php");
	}
	else
		header("Location: index.php");
	
	if (!$_GET['class'])
		header("Location: classes.php");
	
	$classid = $_GET['class'];
	$class = getClass($classid);
	$roster = getRoster_Inst($classid);
	$showSearch = false;
	
	if ($_POST['curSelect']) {
		$showSearch = true;
		$type = "all";
		$info = null;
		$comparator = "and";
		$topicID = $info = $_POST['topics'.$classid];
		if ($_POST['curSelect'] == 2) {
			$type = "author";
			$info = $_POST['authorName'];
		}
		else if ($_POST['curSelect'] == 3) {
			$type = "title";
			$info = $_POST['titleName'];
		}
		else if ($_POST['curSelect'] == 4) {
			$type = "topic";
			$topicID = $info = $_POST['topics'.$classid];
			
			if ($_POST['searchPosition']) {
				$type = "position";
				$positionID = $info = $_POST['selPosition'];
  			$allPositions = getPositions($_POST['topics'.$classid]);
  			$countPositions = count($allPositions);
			//        echo("There are ".$countPositions." positions for topic # ".$_POST['topics'.$classid]."<br>");
			$countArguments = 0;
			$max = $countPositions;
			$argPerPosition = array();
			for ($i = 0; $i < $max; $i++){
				$args = count(getArguments($_POST['topics'.$classid],$allPositions[$i]['ID']));
//				         echo("For position ".$allPositions[$i]['ID']." ".$positionID." ".$thisPosition." there are ".$args." arguments<br>");
				array_push($argPerPosition,$allPositions[$i]['ID'],$args);
				$countArguments = $countArguments + $args;
			}
				if ($_POST['searchReasons']) {
					$type = 'reason';
					$info = array();
					$comparator = $_POST['comp'];
	  			$sumReasonLine = "";
	  			$reasons = getReasons($positionID, false);
					
					$max = count(getReasons($positionID, false));
		 		  $reasonSelected = 0;
					for ($i = 0; $i < $max; $i++) {
						if ($_POST['reasons'.$positionID.'_'.$i]) {
							array_push($info, $_POST['reasons'.$positionID.'_'.$i]);
       				$reasonSelected = $reasonSelected + 1;
						  if ($reasonSelected == 1)
							  $sumReasonLine = $sumReasonLine . " <i>".$reasons[$i]['Reason']."</i>";
						  else
							  $sumReasonLine = $sumReasonLine." ".$comparator." <i>".$reasons[$i]['Reason']."</i>";
						}

					}
				}	
			}
		}
		
		$sortOrder = array();
//		for ($j = 1; $j < 6; $j++) {
//			if ($_POST['sort_position'] == $j)
//				array_push($sortOrder, "position");
//			else if ($_POST['sort_author'] == $j)
//				array_push($sortOrder, "author");
//			else if ($_POST['sort_title'] == $j)
//				array_push($sortOrder, "title");
//			else if ($_POST['sort_date'] == $j)
//				array_push($sortOrder, "date");
//			else if ($_POST['sort_source'] == $j)
//				array_push($sortOrder, "source");
//		}

// Sort order hard coded
	array_push($sortOrder, "position");
	array_push($sortOrder, "author");
	array_push($sortOrder, "title");
	array_push($sortOrder, "date");
	array_push($sortOrder, "source");

		//for($k = 0; $k < count($sortOrder); $k++)
		//	echo($sortOrder[$k]."<br>");
		
		
// $articles = substantiveSearch($type,$info,$comparator,$sortOrder,$classid);
//  echo("Type ".$type.", Info ".$info.", Operator ".$comparator.", Classid ".$classid.", Count ".count($articles)."<br>");
  	$articles = queryLibSearch($type,$info,$comparator,$sortOrder,$classid);

	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><? echo($class['CourseName']." - ".$class['SectionLetter']." - Class Report"); ?></title>
<script language='javascript'>
<!-- 

	function changeTopic(topicid) {
		oldtopic = document.getElementById('selTopic').value;
		oldposition = document.getElementById('selPosition').value;
		document.getElementById('positions'+oldtopic+'div').style.display = 'none';
		if (oldposition > 0)
			document.getElementById('reasons'+oldposition+'div').style.display = 'none';
		document.getElementById('positions'+topicid+'div').style.display = 'block'; 
		document.getElementById('selTopic').value = topicid;
		var positionid = null;
		var i = 1;
		while ((position = document.getElementById('positions'+topicid+'_'+i)) != null) {
			if (position.checked) {
				positionid = position.value;
				break;
			}
			else
				i++;
		}
		if (!positionid) {
			positionid = -1;
		}
		else
			document.getElementById('reasons'+positionid+'div').style.display = 'block';
		document.getElementById('selPosition').value = positionid;
	}
	
	function changePosition(positionid) {
		oldposition = document.getElementById('selPosition').value;
		if (oldposition > 0)
			document.getElementById('reasons'+oldposition+'div').style.display = 'none';
		document.getElementById('reasons'+positionid+'div').style.display = 'block';
		document.getElementById('selPosition').value = positionid;			
	}
	
	function changeUp(doShow, curSel) {
		if (doShow)
			document.getElementById('positionDIV').style.display='block';
		else
			document.getElementById('positionDIV').style.display='none';
			
		document.getElementById('curSelect').value = curSel;
	}
	
	function allowReasons(allow) {
		document.getElementById('searchReasons').disabled = !allow;
	}
	
	function switchComp(andComp) {
		if (andComp)
			document.getElementById('comp').value = 'and';
		else
			document.getElementById('comp').value = 'or';
	}
	
	function goBack() {
		window.location = 'classes.php';
	}
// -->
</script>
</head>

<?
	include("header.php");
	if ($_GET['report']) {
		if ($_GET['report'] == 1 && $showSearch) {
// Inserted from QueryLib.php
	$topicText = "";
	$positionText = "";
	echo("<span style='position:absolute; left:20px'><br><table border=1 style=\"background-color:lightblue;\">");
	if ($_POST['searchPosition'])
  	$count = $countArguments;
	else
	  $count = count($articles);
  if ($count == 0) {
    $tText = getTopic($_POST['topics'.$classid]);
    $topicText = $tText['Topic'];
    echo("</table>");
    echo("</span><br><b><u>Topic: $topicText</u></b><br><br>");
    echo("No articles currently in library for this topic.");
  }
  else {
	foreach($articles as $article) {
		if ($article['Topic'] != $topicText) {
			$topicText = $article['Topic'];
			echo("</table>");
//			echo("</span><br><b><u>Topic: $topicText</u></b><span style='position:relative; left:20px'><br><br>");
			echo("</span><br><b><u>Topic: $topicText</u></b><br>");

			if ($_POST['searchPosition'])
				$count = $countArguments;
			else
				$count = count($articles);
			$firstArticle = true;
			$firstPosition = true;
			echo("<table cellpadding=6px>");
		}
		if ($article['Position'] != $positionText) {
			if ($firstArticle){
				$firstArticle = false;
				$p = 0;
				$positionText = $article['Position'];
				echo("</table><br><b>$positionText</b><br>");

			}
			else {
				if ($p != 0){
					if ($firstPosition){
						$firstPosition = false;
						$percent = $p/$count*100;
						if ($p != 1)
							$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
						else
							$sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
						echo("</table><br>".$sumLine."<br>");
						echo("<table border=1 cellpadding=6px>");
					}
				}
				$positionText = $article['Position'];
				echo("</table><br><b>$positionText</b><br>");
				$p = 0;
			}
			echo("<table border=1 cellpadding=6px>");
      echo("<col width = '14%'>");
      echo("<col width = '22%'>");
      echo("<col width = '8%'>");
      echo("<col width = '22%'>");
      echo("<col width = '12%'>");
      echo("<col width = '22%'>");
//added
        echo("<tr>");
        echo("<th>Author</th>");
        echo("<th>Article</th>");
        echo("<th>Date</th>");
        echo("<th>Source</th>");
        echo("<th>Web Address</th>");
        echo("<th>Reasons</th>");
        echo("</tr>");
		}
		echo("<td>".$article['Author']."</td>");
		echo("<td>".$article['Title']."</td>");
		echo("<td>".$article['Date']."</td>");
		echo("<td>".$article['Source']."</td>");
    if ($article['URL'] && $article['URL'] != ''){
      if (substr($article['URL'],0,7) != 'http://')
         $article['URL'] = 'http://'.$article['URL'];
         echo("<td><a href='".$article['URL']."' target=_blank>");
         if (strlen($article['URL'])>20)
            $article['URL'] = substr($article['URL'], 0, 20)."...";
         echo($article['URL']."</a></td>");
    }
    else
       echo("<td>No address provided.</td>");
       
// changed		echo("<td width=\"150px\"><a href=\"".$article['URL']."\">".$article['URL']."</a></td>");
//		echo("<td colspan=3><b><i>");
    echo("<td>");
		$reasonList = getArticleReasons($article['ID']);
//		if (count($reasonList) > 1)
//			echo("Reasons:<br>");
//		else
//			echo("Reason:");
//		echo("</i></b>");
		foreach($reasonList as $a_r)
			echo("*".$a_r['Reason']."<br>");
		echo("</td></tr>");
		echo("</tr>");
		$p++;
	}
	if ($_POST['searchReasons']){
		$argcount = count(getArguments($_POST['topics'.$classid],$positionID));
		if ($count != 0){
			$percent = $p/$argcount*100;
      if ($p == 0)
   			$sumLine = "No arguments with reasons ".$sumReasonLine.", found from ".$argcount." arguments for the position<br>";
      else {  
			if ($p != 1)
				$sumLine = $p." arguments with reasons ".$sumReasonLine.", <br> &nbsp &nbsp".$percent." percent of ".$argcount." arguments for the position<br>";
			else
				$sumLine = $p." argument with reasons ".$sumReasonLine.", <br> &nbsp &nbsp".$percent." percent of ".$argcount." argument for the position<br>";
      }
		}
		else 
			$sumLine = "No arguments with reasons ".$sumReasonLine.", found from ".$argcount." arguments for the position<br>";
	}
	else {       
		if ($firstPosition){
			if ($count !=0 ){
				$percent = $p/$count*100;
        if ($p == 0) {
          $positionText = "FirstPosition";
					$sumLine = "No arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
        }  
        else {
  				if ($p !=1)
  					$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
  				else
  					$sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total argument";
        }
			}
		}
		else {
			if ($count != 0){
				$percent = $p/$count*100;
        if ($p == 0) {
//          $textPosition = getPositionName($positionID);
//          $currentPosition = $textPosition['Position'];
//          if ($currentPosition == $thisPosition) {
//          $tText = getTopic($_POST['topics'.$classid]);
//          $topicText = $tText['Topic'];
//          echo("</table>");
//          echo("</span><br><b><u>Topic: $topicText</u></b><br>"); 
//          echo("<table>");
            $textPosition = getPositionName($positionID);
            $thisPosition = $textPosition['Position'];

            $positionText = $thisPosition;
//   				echo("</table><br><b>$positionText</b><br>");
//          echo("<table>");
					$sumLine = "No arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
//}
        } 
        else { 
			  	if ($p != 1)
			  		$sumLine = $p." arguments <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
				  else
					  $sumLine = $p." argument <i>".$positionText."</i>, ".$percent." percent of ".$count." total arguments";
        }
			}
		}
	}
  if ($p == 0) {
     $tText = getTopic($_POST['topics'.$classid]);
     $topicText = $tText['Topic'];
     echo("</table>");
     echo("</span><br><b><u>Topic: $topicText</u></b><br>"); 
     echo("<table>");
     $textPosition = getPositionName($positionID);
     $thisPosition = $textPosition['Position'];
     $positionText = $thisPosition;
     echo("</table><br><b>$positionText</b><br>");
     echo("<table>");
  }  
	echo("</table><br>".$sumLine."<br>");
  }
	echo("<table>");
//
  
			echo("</table>");
			echo("<br><br><input type='button' value='New Substantive Report' onclick='window.location=\"report.php?class=$classid&report=1\"'><br><br>");
			echo("</span><input type='button' value='Change Report' onclick='window.location=\"report.php?class=$classid\"' /> ");
			echo("<input type='button' value='View Classes' onclick='goBack()' />");

		}
		else if ($_GET['report'] == 1 && !$showSearch) {
?>
<div style='position:relative; left:20px'>
<form name='substantivesearch' id='substantivesearch' method='POST'>
<input type='hidden' name='curSelect' id='curSelect' value=4>
	<b>Substantive Report:</b><br><br>

	<div style='position:relative; left:20px'>
	<table cellpadding=3px>

		<tr>
			<td><input type='radio' name='select' id='selectTopic' style=display:none checked onchange='changeUp(true, 4)'></td>
			<td>Select a Topic &nbsp</td>
      <td>
<?
	$topics = getTopics($classid);
	$seltopic = $topics[0]['ID'];
	echo("<select id='topics".$classid."' name='topics".$classid."' ");
	echo("onchange='changeTopic(this.options[this.selectedIndex].value)'>");
	$first2 = true;
	foreach($topics as $t) {
		if (count(getPositions($t['ID'])) > 0) {
			echo("<option value='".$t['ID']."'");
			if ($first2) {
				echo(" SELECTED");
				$first2 = false;
			}
			echo(">".$t['Topic']."</option>");
		}
	}
	echo("</select>");
	echo("<input type='hidden' id='selTopic' name='selTopic' value='$seltopic'>");
?>
			</td>
		</tr>
	</table>
	<div style="display:block; position:relative; left:20px" id='positionDIV'>
	<input type='checkbox' name='searchPosition' id='searchPosition' onclick='allowReasons(this.checked)'> By Position:
	<div style="position:relative; left:20px">
	<table cellpadding=3px>
			<tr>
				<td colspan=2>
<?
	$first = true;
	foreach($topics as $t) {
		$positions = getPositions($t['ID']);
		echo("<div id='positions".$t['ID']."div' style='position:relative; left:20px; display:");
		if ($first) {
			echo("block'>");
			$first = false;
			$selposition = $positions[0]['ID'];
		}
		else
			echo("none'>");
		echo("<table><tr>");
		$first2 = true;
		$j = 1;
		for($i = 0; $i < count($positions); $i++) {
			if ($i % 3 === 0)
				echo("</tr><tr>");
			echo("<td colspan=2><input type='radio' name='positions".$t['ID']."' value='".$positions[$i]['ID'].
				 "' onclick='changePosition(this.value)' id='positions".$t['ID']."_".$j."' ");
			if ($first2) {
				echo("CHECKED");
				$first2 = false;
			}
			echo(" />".$positions[$i]['Position']." &nbsp; &nbsp;</td>");
			$j++;
		}
		echo("</tr></table></div>");
	}
	echo("<input type='hidden' id='selPosition' name='selPosition' value=$selposition />");
?>
				</td>
			</tr>
		</table>
	</div>
	<input type='checkbox' name='searchReasons' id='searchReasons' disabled> By Reasons:
		<div style='position:relative; left:20px'>
			<input type='radio' name='and_or' id='and' onclick='switchComp(true)' checked> And &nbsp; &nbsp;
			<input type='radio' name='and_or' id='or' onclick='switchComp(false)'> Or
			<input type='hidden' name='comp' id='comp' value='and'>
		</div>
		<div style='position:relative; left:20px'>
<?
	$first = true;
	foreach($topics as $t) {
		$positions = getPositions($t['ID']);
		foreach($positions as $p) {
			$reasons = getReasons($p['ID'], false);
			echo("<div id='reasons".$p['ID']."div' style='position:relative; left: 20px; display:");
			if ($first) {
				echo("block'>");
				$first = false;
			}
			else
				echo("none'>");
			for ($i = 0; $i < count($reasons); $i++) {
				echo("<input type='checkbox' id='reasons".$p['ID']."_".$i."' name='reasons".$p['ID']."_".$i.
					 "' value='".$reasons[$i]['ID']."'> ".$reasons[$i]['Reason']."<br>");
			}
			echo("</div>");
		}
	}
?>
		</div>
	</div>
</div>
<?
// Sorting order is hard coded!!
//<br><u>Sort</u>:<br>
//<div style='position:relative; left:20px'>
//	<table cellspacing=3px>
//		<tr>
//			<td align='right'>
//				<input type='text' name='sort_position' id='sort_position' 
//					   style='text-align:center'
//					   value=1 size=1 maxlength=1></td>
//			<td>Position</td>
//		</tr>
//		<tr>
//			<td align='right'>
//				<input type='text' name='sort_author' id='sort_author' 
//					   style='text-align:center'
//					   value=2 size=1 maxlength=1></td>
//			<td>Author</td>
//		</tr>
//		<tr>
//			<td align='right'>
//				<input type='text' name='sort_title' id='sort_title' 
//					   style='text-align:center'
//					   value=3 size=1 maxlength=1></td>
//			<td>Title</td>
//		</tr>
//		<tr>
//			<td align='right'>
//				<input type='text' name='sort_date' id='sort_date' 
//					   style='text-align:center'
//					   value=4 size=1 maxlength=1></td>
//			<td>Date</td>
//		</tr>
//		<tr>
//			<td align='right'>
//				<input type='text' name='sort_source' id='sort_source' 
//					   style='text-align:center'
//					   value=5 size=1 maxlength=1></td>
//			<td>Source</td>
//		</tr>
//	</table>
//
?>
</div>

<br><input type='submit' value='Query Database'><br>
</div>
</form>
<br>
	<input type='button' value='Change Report' onclick='window.location="report.php?class=<? echo $classid; ?>"' /> 
	<input type='button' value='View Classes' onclick='goBack()' />
</div>
<?
		} else if ($_GET['report'] == 2) {
?>
<div style='position:relative; left:20px'>
	<b>Progress Report:</b><br /><br />
	<div style='position:relative; left:20px'>
	<?
		$topics = getTopics($classid);
		if (count($topics) == 0)
			echo("There are no topics set up for this class.  No report can be generated.<br><br>");
		foreach($topics as $t) {
			echo("<b>Topic:</b> ".$t['Topic']."<br>".$t['RequiredArgs']." articles are required.<br>");
			echo("<table border=1 cellpadding='5px' >");
			echo("<tr><th>Student</th><th>Submitted</th><th>Approved</th></tr>");
			foreach($roster as $user) {
				echo("<tr><td><a href='editarticles.php?id=".$user['ID']."&class=$classid' style='font-variant:small-caps'>".
					 $user['FirstName']." ".$user['LastName']."</a></td>");
				$submitted = getArticles($user['ID'], $classid, false);
				$num_submit = 0;
				$num_approve = 0;
				foreach($submitted as $sub) {
					$reas = getArticleReasons($sub['ID']);
					$top = getTopicFromReason($reas[0]['ID']);
					if ($top['ID'] == $t['ID']) {
						$num_submit++;
						if ($sub['Approved'] == 1)
							$num_approve++;
					}
				}
				if ($num_submit < $t['RequiredArgs'])
					echo("<td bgcolor='#FFB3B3' align='center'>".$num_submit."</td>");
				else
					echo("<td align='center'>".$num_submit."</td>");
				if ($num_approve < $t['RequiredArgs'])
					echo("<td bgcolor='#FFB3B3' align='center'>".$num_approve."</td>");
				else
					echo("<td align='center'>".$num_approve."</td></tr>");
			}
			echo("</table><br><br>");
		}
	?>
	</div>
	<input type='button' value='Change Report' onclick='window.location="report.php?class=<? echo $classid; ?>"' /> 
	<input type='button' value='View Classes' onclick='goBack()' />
</div>
<?
		} else if ($_GET['report'] == 3) {
			foreach($roster as $user) {
				$body = $user['FirstName'].",\n\nHere is your progress report for ".$class['CourseName']." (".
						$class['SectionLetter']."):\n\n\n";
				$topics = getTopics($classid);
				$submitted = getArticles($user['ID'], $classid, false);
				foreach($topics as $t) {
					$articles = array();
					foreach($submitted as $sub) {
						$reas = getArticleReasons($sub['ID']);
						$top = getTopicFromReason($reas[0]['ID']);
						if ($top['ID'] == $t['ID'])
							array_push($articles, $sub);
					}
					if (count($articles) > 0) {
						$body = $body."You have entered the following articles for the topic \"".$t['Topic']."\":\n\n";
						$num_approve = 0;
						foreach($articles as $a) {
							$body = $body."\t".$a['Author']." , '".$a['Title']."' -- ";
							if ($a['Approved'] == 1) {
								$body = $body."approved\n";
								$num_approve++;
							} 
							else {
								if ($a['UnapproveReason'] == 'Pending approval')
									$body = $body.$a['UnapproveReason']."\n";
								else
									$body = $body."rejected -- ".$a['UnapproveReason']."\n";
							}
						}
						if ($num_approve == $t['RequiredArgs'])
							$body = $body."\nYou have completed all the arguments for this topic.  Good job!\n\n-----\n\n";
						else {
							if ($num_approve > 0)
								$body = $body."\nOf the assigned ".$t['RequiredArgs']." arguments, you have completed ".
										$num_approve.".  You must still enter ".($t['RequiredArgs']-$num_approve).
										" more arguments and have them approved.\n\n-----\n\n";
							else
								$body = $body."\nNone of your articles have been approved.  You must still enter ".
										$t['RequiredArgs']." more arguments and have them approved.\n\n-----\n\n";
						}
					}
					else
						$body = $body."You have not submitted any articles for the topic \"".$t['Topic']."\".\n".
								"Please submit ".$t['RequiredArgs']." arguments soon.\n\n-----\n\n";	    
				}
				$sender = getUserName($_SESSION['user']);
				$body = $body."Thank you,\n".$sender['FirstName']." ".$sender['LastName'];
				mail($user['Email'], "Progress Report", $body, "From: donotreply@syll.net");
			}
			updateEmailReport($classid);
			header("Location: report.php?class=$classid");
		}
	} else {
?>
<div style='position:relative; left:20px'>
	<b>Select the type of report to generate:</b><br /><br />
	<span style='position:relative; left:20px'>
	<a href='report.php?class=<? echo $classid; ?>&report=1' style='font-variant:small-caps'>Substantive</a>
	 - Allows a search-based report of articles submitted under this class.<br />
	<a href='report.php?class=<? echo $classid; ?>&report=2' style='font-variant:small-caps'>Progress</a>
	 - Displays a list of students, detailing the total articles entered and how many are approved.<br />
	<a href='report.php?class=<? echo $classid; ?>&report=3' style='font-variant:small-caps'>Email</a>
	 - Automatically sends personal progress reports to students, detailing each article's status.<br />
	 &nbsp; &nbsp; &nbsp; <i><b>Last report sent on:</b> <? echo $class['ReportSent']; ?></i>
	</span><br /><br />
	<input type='button' value='View Classes' onclick='goBack()' />
</div> 
<? 	} 
include("footer.php"); ?>
</html>
