<?
/* 
   This file is part of the 'Science Fair In A Box' project
   SFIAB Website: http://www.sfiab.ca

   Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
   Copyright (C) 2007 James Grant <james@lightbox.org>
   Copyright (C) 2007 David Grant <dave@lightbox.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation, version 2.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/
?>
<?
 require_once("../common.inc.php");
 require_once("../user.inc.php");
 require_once("reports.inc.php");

 user_auth_required('committee');

 
 /* Load the user's volunteer position selections */

 $edit_mode = array_key_exists('edit', $_GET);

 $action = $_GET['action'];
 if($action=='') $action = $_POST['action'];

 if($action == 'unlink') {
 	$id = intval($_GET['id']);
	mysql_query("DELETE FROM reports_committee WHERE
			users_id='{$_SESSION['users_uid']}' AND id='$id'");
	$_SESSION['messages'][] = 'unlinked';
	header("Location: reports.php?edit=1");
	exit;
 }

 $reports_id = 0;
 if($action == 'reload') {
 	$edit_mode = true;
 	$reports_id = intval($_POST['reports_id']);
 }

 if($action == 'add') {
 	$reports_id = intval($_POST['reports_id']);
	/* reports_id might be < 0, that's ok */
	$category = $_POST['category'];
	$category_exist = $_POST['category_exist'];
	$comment = mysql_escape_string(stripslashes($_POST['comment']));

	if($category_exist != '') $category = $category_exist;
	$category = mysql_escape_string(stripslashes(trim($category)));

	if($category == '') {
		$_SESSION['messages'][] = 'nocategory';
		header("Location: reports.php?edit=1");
		exit;
	}
	
	if($reports_id > 0) {
		$type = $_POST['type'];
		$stock = $_POST['stock'];
		if(!array_key_exists($type, $report_options['type']['values'])) {
			echo "Invalid format: type=$type";
			exit;
		}
		if(!array_key_exists($stock, $report_stock)) {
			echo "Invalid stock: stock=$stock";
			exit;
		}
	} else {
		$type = '';
		$stock = '';
	}

	mysql_query("INSERT INTO `reports_committee` 
		(`id`, `users_id` , `reports_id` , `category` , `comment` , `format` , `stock`)
		VALUES (
			NULL , '{$_SESSION['users_uid']}', 
			'$reports_id', '$category', '$comment', 
			'$type', '$stock' );");
	$_SESSION['messages'][] = 'added';
	header("Location: reports.php?edit=1");
	exit;
 }


 //send the header
 if($edit_mode == false) {
	 send_header("My Reports", 
 			array("Committee Main" => "committee_main.php"),
            "print/export_reports"
			);

	/* Send a greeting */
	echo i18n('Welcome to the new report interface.  You can select and save specific reports under specific categories so you can always find the report you need without having to go through the list each time.  To begin customizing this list, click on the "Click Here to edit your Report List" link at the bottom of this page.  ');
	echo i18n('The old report list is still available').' <a href="reports_old.php">'.i18n('here').'</a>, but will be deleted in the summer of 2008';
	echo '<br /><br />';


 } else {
	 send_header("Edit My Reports", 
 			array("Committee Main" => "committee_main.php",
	 			"My Reports" => "admin/reports.php"),
                "print/export_reports"
			);
 }

 require_once("../ajax.inc.php");

 
 foreach($_SESSION['messages'] as $m) {
 	switch($m) {
	case 'nocategory':
	 	echo error(i18n("You must select a category or type a new category name to add a report to your list"));
		break;
	case 'added':
	 	echo happy(i18n("Report successfully added"));
		break;
	case 'unlinked':
	 	echo happy(i18n("Report successfully removed"));
		break;
	}
 }
 $_SESSION['messages'] = array();

 /* Load all the users reports */
 $q = mysql_query("SELECT reports_committee.*,reports.name
 			FROM reports_committee 
				LEFT JOIN reports ON reports.id=reports_committee.reports_id
 			WHERE users_id='{$_SESSION['users_uid']}'
			ORDER BY category,id");
 echo mysql_error();
 if(mysql_num_rows($q) == 0) {
 	echo i18n('You have no reports saved');
 } else {
 	/* List each report with info */
	if($edit_mode == true) {
		echo i18n('Deleting all the reports from a category will also delete the category.');
		echo '<br />';
		echo '<br />';
		echo '<a href="reports.php">'.i18n('Click here when you are finished editing your report list').'</a>';
		echo '<br />';
		echo '<br />';
	}

	$last_category = '';
	$x=0;
	echo "<table class=\"tableedit\">";
	while($i = mysql_fetch_object($q)) {
		$trclass = ($x % 2 == 0) ? "even" : "odd";
		$x++;
		if($last_category != $i->category) {
			/* New category */
			echo '<tr><td colspan=\"2\"><h3>';
			if($edit_mode == true) echo i18n('Category').': ';
			echo "{$i->category}</h3></td></tr>";
			$last_category = $i->category;
		}

		if($i->reports_id > 0) { 
			$name = $i->name;
			$url = "admin/reports_gen.php?id={$i->reports_id}&show_options=1";
		} else {
			$name = $report_custom[-$i->reports_id]['name'];
			$url = $report_custom[-$i->reports_id]['custom_url'];
		}

		if($edit_mode == false) 
			$name = "<a href=\"{$config['SFIABDIRECTORY']}/$url\">$name</a>";

		echo "<tr class=\"$trclass\"><td>";

		if($edit_mode == true) 
			echo "<a title=\"Remove Report\" href=\"reports.php?action=unlink&id={$i->id}\"><img src=\"".$config['SFIABDIRECTORY']."/images/16/button_cancel.".$config['icon_extension']."\" border=\"0\" alt=\"Remove Report\" /></a>&nbsp;";
		echo $name.'</td>';

/*
		if($i->reports_id > 0) {
			echo '<tr><td width=\"20px\"></td><td>';
			echo '<span style=\"font-size: 0.75em;\">';
			echo i18n('Format').": {$i->format}, ";
			echo i18n('Paper').": {$report_stock[$i->stock]['name']}, ";
			echo i18n('Year').": {$config['FAIRYEAR']}";
			echo '</span>';
			echo '</td></tr>';
		}
*/

		echo "<td><span style=\"font-size: 0.85em;\">{$i->comment}</span></td></tr>";
	}
	echo "</table>";
		
 }

 /* Load available reports */
 $reports = report_load_all();

 if($edit_mode == false) {
 	echo '<hr />';
	echo '<a href="reports.php?edit=1">'.i18n('Click here to edit your Report List').'</a>';

 	echo '<hr />';
	echo "<h3>".i18n("All Reports")."</h3>";

	/* Print all the reports in a pulldown menu for generation */
	echo "<form method=\"get\" name=\"reportgen\" action=\"reports_gen.php\">";
	echo "<input type=\"hidden\" name=\"show_options\" value=\"1\" />";
	echo "<select name=\"id\" id=\"report\">";
	echo "<option value=\"0\">".i18n("Select a Report")."</option>\n";
	$x=0;
	foreach($reports as $r) {
		echo "<option value=\"{$r['id']}\">{$r['name']}</option>\n";
	}
	echo "</select>";
	echo "<input type=\"submit\" value=\"".i18n("Generate Report")."\"></form>";
	echo "<br />";

 	send_footer();
	exit;
 }

 echo '<hr />';

 ?>
	<script type="text/javascript">
	function add_reload()
	{
		var url="report.ajax.php?reports_id="+document.addreport.reports_id.options[document.addreport.reports_id.selectedIndex].value;
//		alert(url);
		http.open("GET",url,true);
		http.onreadystatechange=handleResponse;
		http.send(null);
		return true;
	}

	function handleResponse()
	{
		try {
			if(http.readyState==4)
			{
				//eval the JSON to get the object if the length is big enough (custom reports return json [])
				if(http.responseText.length>3) {
					document.addreport.type.disabled=false;
					document.addreport.stock.disabled=false;
					document.addreport.type.style.display='';
					document.addreport.stock.style.display='';
					document.getElementById('reporttypecustom').style.display='none';
					document.getElementById('reportstockcustom').style.display='none';

/* dont use JSON anymore since it adds an extra PHP-side requirement, we'll just get a 3 line response with one thing per line that we need
					var obj=eval('('+http.responseText+')');
					if(obj['option']['type']) {
						for(i=0;i<document.addreport.type.options.length;i++) {
							if(document.addreport.type.options[i].value==obj['option']['type'])
								document.addreport.type.selectedIndex=i;
						}
					}
					else
						document.addreport.type.selectedIndex=0;

					if(obj['option']['stock']) {
						for(i=0;i<document.addreport.stock.options.length;i++) {
							if(document.addreport.stock.options[i].value==obj['option']['stock'])
								document.addreport.stock.selectedIndex=i;
						}
					}
					else
						document.addreport.stock.selectedIndex=0;

					if(obj['desc'])
						document.addreport.comment.value=obj['desc'];
*/
					var lines=http.responseText.split('\n');
					var reportType=lines[0];
					var reportStock=lines[1];
					var reportDesc=lines[2];

					if(reportType) {
						for(i=0;i<document.addreport.type.options.length;i++) {
							if(document.addreport.type.options[i].value==reportType)
								document.addreport.type.selectedIndex=i;
						}
					}
					else
						document.addreport.type.selectedIndex=0;

					if(reportStock) {
						for(i=0;i<document.addreport.stock.options.length;i++) {
							if(document.addreport.stock.options[i].value==reportStock)
								document.addreport.stock.selectedIndex=i;
						}
					}
					else
						document.addreport.stock.selectedIndex=0;

					if(reportDesc);
						document.addreport.comment.value=reportDesc;
				}
				else
				{
					document.addreport.type.disabled=true;
					document.addreport.stock.disabled=true;
					document.addreport.type.style.display='none';
					document.addreport.stock.style.display='none';
					document.getElementById('reporttypecustom').style.display='';
					document.getElementById('reportstockcustom').style.display='';
					document.addreport.comment.value='';
				}
			}
		}
		catch(e) {
			alert('caught error: '+e);
		}
	}
	</script>
 <?

 /* Create an add report box */
 echo '<h3>'.i18n('Add a Report to your Report List').'</h3>';
 echo "<form method=\"post\" name=\"addreport\"action=\"reports.php\">";
 echo "<input type=\"hidden\" name=\"action\" value=\"add\">";
 echo "<table class=\"tableedit\">\n";
 echo '<tr><td colspan="2">';
 echo "<select name=\"reports_id\" onChange=\"add_reload()\">";
 echo "<option value=\"\">".i18n("Choose a report")."</option>\n";
 $x=0;
 foreach($reports as $r) {
 	$x++;
	$sel = ($reports_id == $r['id']) ? 'selected="selected"' : '';
	echo "<option value=\"{$r['id']}\" $sel>$x. {$r['name']}</option>";

 }
 $rid = -1;
 foreach($report_custom as $r) {
 	$x++;
	$sel = ($reports_id == $rid) ? 'selected="selected"' : '';
	echo "<option value=\"$rid\" $sel>$x. {$r['name']}</option>";
	$rid--;
 }

 echo "</select></td></tr>";

 echo "<tr><td>".i18n("Category").":</td><td>";
 $q = mysql_query("SELECT DISTINCT category FROM reports_committee
 		WHERE users_id='{$_SESSION['users_uid']}'
		ORDER BY category");

 echo i18n("Existing Category").": <select name=\"category_exist\">";
 echo "<option value=\"\">-- ".i18n('Use New Category')." --</option>";
 while($i = mysql_fetch_object($q)) {
 	echo "<option value=\"{$i->category}\">{$i->category}</option>";
 }
 echo "</select><br />";
 echo i18n("OR New Category").": <input type=\"text\" name=\"category\">";
 echo "</td></tr>";

 $option_keys = array('type','stock');
 foreach($report_options as $ok=>$o) {
 	if(!in_array($ok, $option_keys)) continue;
 	echo "<tr><td>{$o['desc']}:</td>";
	echo "<td><select name=\"$ok\" id=\"$ok\">";
	foreach($o['values'] as $k=>$v) {
		echo "<option value=\"$k\">$v</option>\n";
	}
	echo "</select><span id=\"report{$ok}custom\" style=\"display: none;\">".i18n("Custom")."</span></td></tr>";
 }
 echo "<tr><td>".i18n("Comments").":</td><td>";
 echo "<textarea rows=\"3\" cols=\"60\" name=\"comment\"></textarea></td></tr>";
 echo "<tr><td colspan=\"2\"><input type=\"submit\" value=\"".i18n("Add Report to My Reports")."\" /></td></tr>";


 echo '</table></form>';



 echo '<hr />';
 echo '<h3>Descriptions for All Reports</h3>';
 echo i18n('Click on the report number to try the report with the default report options before you add it to your Report List');
 echo '<br /><br />';
 echo "<table class=\"tableedit\">\n";
 $x=0;
 foreach(array_merge($reports, $report_custom) as $r) {
	$trclass = ($x % 2 == 0) ? "even" : "odd";
	$x++;
 	echo "<tr class=\"$trclass\">";
	if($r['custom_url'] == '') {
		$url = "admin/reports_gen.php?id={$r['id']}";
	} else {
		$url = $r['custom_url'];
	}
	echo "<td><a href=\"{$config['SFIABDIRECTORY']}/$url\">$x.</a></td>";
	echo "<td><table cellspacing=0 cellpadding=0 width=\"100%\"><tr>";

	echo "<td><b>{$r['name']}</b></td>";
	echo "<td align=\"right\">Created By: {$r['creator']}</td></tr>";
	echo "<tr><td colspan=\"2\">{$r['desc']}</td></tr>";
	echo "</table></tr>";
 }
	
echo "</table>";

 echo "<br />";

send_footer();
?>
