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

   Copyright (C) 2007 James Grant <james@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('../projects.inc.php');
require_once('curl.inc.php');
user_auth_required('committee', 'admin');

//function get_cwsf_award_winners()
function get_winners($awardid)
{
 	global $config;

	/* Mappings of the name we want => to the column name returned in MYSQL */
	$school_fields = array( 'schoolname'=>'school',
				'schoollang'=>'schoollang',
				'schoollevel'=>'schoollevel',
				'board'=>'board',
				'district'=>'district',
				'phone'=>'phone',
				'fax'=>'fax',
				'address'=>'address',
				'city'=>'city',
				'province_code'=>'province_code',
				'postalcode'=>'postalcode',
				'schoolemail'=>'schoolemail');
/*				'principal'=>'principal',
				'sciencehead'=>'sciencehead',
				'scienceheademail'=>'scienceheademail',
				'scienceheadphone'=>'scienceheadphone');*/

	$student_fields = array('firstname'=>'firstname',
				'lastname'=>'lastname',
				'email'=>'email',
				'gender'=>'sex',
				'grade'=>'grade',
				'language'=>'lang',
				'birthdate'=>'dateofbirth',
				'address'=>'address',
				'city'=>'city',
				'province'=>'province',
				'postalcode'=>'postalcode',
				'phone'=>'phone',
				'teachername'=>'teachername',
				'teacheremail'=>'teacheremail');



	/* Get the award */
 	$q=mysql_query("SELECT * FROM award_awards WHERE id='$awardid' AND year='{$config['FAIRYEAR']}'");
	if(mysql_num_rows($q)!=1) {
		error_("Can't find award id $awardid");
		return false;
	}
	$award=mysql_fetch_assoc($q);

	/* Get the fair for the div/cat mappings */
	$q = mysql_query("SELECT * FROM fairs WHERE id='{$award['award_source_fairs_id']}'");
	$fair = mysql_fetch_assoc($q);
	$catmap = unserialize($fair['catmap']);
	$divmap = unserialize($fair['divmap']);

 	$winners=array(	'prizes' => array(),
			'award_name' => $award['name'],
			'external_identifier' => $award['external_identifier'],
			'postback' => $award['external_postback']);

	/* Get the prizes */
	$q=mysql_query("SELECT * FROM award_prizes WHERE award_awards_id='{$award['id']}'");
	while($prize=mysql_fetch_assoc($q)) {
		$pid = $prize['id'];
		$wq=mysql_query("SELECT projects.* FROM award_prizes
					LEFT JOIN winners ON winners.awards_prizes_id=award_prizes.id
					LEFT JOIN projects ON projects.id=winners.projects_id
				WHERE 
					awards_prizes_id='$pid' AND 
					winners.year='{$config['FAIRYEAR']}'");
		echo mysql_error();
		/* Get all projects assigned to this prize */
		$prizewinners = array();
		while($project=mysql_fetch_assoc($wq)) {

			/* Get the students */
			$sq=mysql_query("SELECT * FROM students WHERE registrations_id='{$project['registrations_id']}'
						AND year='{$config['FAIRYEAR']}'");
			$students=array();
			while($s=mysql_fetch_assoc($sq)) {

				/* Get the student's school */
				$schoolq=mysql_query("SELECT * FROM schools WHERE id='{$s['schools_id']}'");
				$schoolr=mysql_fetch_assoc($schoolq);
				$school = array("xml_type"=>"school");/* for ysc compatability */
				foreach($school_fields as $k=>$v) 
					$school[$k] = $schoolr[$v];

				/* Pack up the student data too */
				$student = array('xml_type'=>'student',/* for ysc compatability */
						'school' => $school);
				foreach($student_fields as $k=>$v) 
					$student[$k] = $s[$v];
				
				$students[] = $student;

			}
			/* Turn our load ID into a server-side cat/div id */
			$cat_id = $catmap[$project['projectcategories_id']];
			$div_id = $divmap[$project['projectdivisions_id']];

			/* Save the project info => students */
			$prizewinners[]=array(	'xml_type' => 'project',/* for ysc compatability */
						'projectid'=>$project['id'],
						'projectnumber'=>$project['projectnumber'],
						'title'=>$project['title'],
						'abstract'=>$project['summary'],
						'projectcategories_id'=>$cat_id,
						'projectdivisions_id'=>$div_id,
						'students'=>$students );
		}
		/* Save the prize info => projects */
		$winners['prizes'][$prize['prize']] = array(
				'xml_type'=>'prize', /* For ysc compatability */
				'identifier'=>$prize['prize'], /* for ysc compatability */
				'projects'=>$prizewinners);
	}
	return $winners;
}

switch($_GET['action']) {
case 'award_upload':
	$award_awards_id = intval($_GET['id']);
	$winners = get_winners($award_awards_id);

	/* Get the fair */
	$q = mysql_query("SELECT award_source_fairs_id FROM award_awards WHERE id='$award_awards_id'");
	$a = mysql_fetch_assoc($q);
	$q = mysql_query("SELECT * FROM fairs WHERE id='{$a['award_source_fairs_id']}'");
	$fair = mysql_fetch_assoc($q);

	echo '<br />';
	if($winners == false) {
		echo notice(i18n('No winners selected for this award'));
	} else {
		if($fair['type'] == 'ysc') {
			$req=array("awardwinners"=>array(
					"username"=>$fair['username'],
					"password"=>$fair['password'],
					"identifier"=>$winners['external_identifier'],
					"prizes"=>$winners,
					)
				);
			$url = $winners['external_postback'];
		} else {
			$req = array('award_upload' => $winners);
			$req['award_upload']['year'] = $config['FAIRYEAR'];
			$url = ''; /* url is ignored for type = sfiab */
		}
		echo i18n("Sending %1 winners to %2...", array('<b>'.$winners['award_name'].'</b>', 
								'<b>'.$fair['name'].'</b>'));
		echo '<br />';
				
		$data = curl_query($fair, $req, $url);

		if($data['error'] != 0) {
			echo error("Server said: $data");
		} else {
			echo notice("{$fair['name']} server said: <pre>".join("\n", $data['notice'])."</pre>");
			echo happy(i18n("Upload completed successfully"));
		}
	}
	exit;
case 'catdiv_load':
	$fairs_id = intval($_GET['id']);
	$q = mysql_query("SELECT * FROM fairs WHERE id='$fairs_id'");
	$fair = mysql_fetch_assoc($q);

	$req = array('get_categories' => array('year' => $config['FAIRYEAR']),
			'get_divisions' => array('year' => $config['FAIRYEAR'])
			);
	$data = curl_query($fair, $req);

	$ret = array();
	$ret['categories'] = $data['categories'];
	$ret['divisions'] = $data['divisions'];

	/* If selected mappings don't exist, try to discover some */
	if(trim($fair['catmap']) != '') {
		$ret['catmap'] = unserialize($fair['catmap']);
	} else {
		$ret['catmap'] = array();
		/* Load ours */
		$q=mysql_query("SELECT * FROM projectcategories WHERE year='{$config['FAIRYEAR']}' ORDER BY mingrade");
		while($r=mysql_fetch_object($q)) {
			foreach($data['categories'] as $id=>$c) {
				if($c['mingrade'] == $r->mingrade) {
					$ret['catmap'][$r->id] = $id;
					break;
				}
			}
		}
	}
	if(trim($fair['divmap']) != '') {
		$ret['divmap'] = unserialize($fair['divmap']);
	} else {
		$ret['divmap'] = array();
		$q=mysql_query("SELECT * FROM projectdivisions WHERE year='{$config['FAIRYEAR']}' ORDER BY id");
		while($r=mysql_fetch_object($q)) {
			$lowest = 999;
			$lowest_id = 0;
			foreach($data['divisions'] as $id=>$d) {
				/* Who knew levenshtein was builtin to php as of PHP 4 */
				$l = levenshtein($d['division'], $r->division);
				if($l < $lowest) {
					$lowest = $l;
					$lowest_id = $id;
				}
			}
			$ret['divmap'][$r->id] = $lowest_id;
		}
	}
	echo json_encode($ret);
	exit;

case 'catdiv_save':
 	$fairs_id = intval($_POST['award_source_fairs_id']);

	$cat = array();
	foreach($_POST['cat'] AS $key=>$c) {
		$cat[intval($key)] = intval($c);
	}
	$div = array();
	foreach($_POST['div'] AS $key=>$d) {
		$div[intval($key)] = intval($d);
	}
	
	$catmap = mysql_real_escape_string(serialize($cat));
	$divmap = mysql_real_escape_string(serialize($div));
	mysql_query("UPDATE fairs SET catmap='$catmap',divmap='$divmap' WHERE id='$fairs_id'");
	echo "UPDATE fairs SET catmap='$catmap',divmap='$divmap' WHERE id='$fairs_id'";
	echo mysql_error();

	happy_("Category/Division mapping information saved");
	exit;

case 'confirm_load':
	$award_awards_id = intval($_GET['id']);
	$winners = get_winners($award_awards_id);
	print_r($winners);
	exit;

case 'additional_materials':
	$award_awards_id = intval($_GET['award_awards_id']);
	$q = mysql_query("SELECT award_source_fairs_id,external_identifier FROM award_awards WHERE id='$award_awards_id'");
	$a = mysql_fetch_assoc($q);
	$q = mysql_query("SELECT * FROM fairs WHERE id='{$a['award_source_fairs_id']}'");
	$fair = mysql_fetch_assoc($q);
	$req = array('award_additional_materials' => array(
				'year'=>$config['FAIRYEAR'],
				'identifier'=>$a['external_identifier'])
			);
	$data = curl_query($fair, $req, $url);
	foreach($data['award_additional_materials']['pdf']['header'] as $h) 
		header($h);
	echo base64_decode($data['award_additional_materials']['pdf']['data64']);
	exit;
}


 send_header("Award Upload",
 		array('Committee Main' => 'committee_main.php',
			'Administration' => 'admin/index.php',
			'Awards Main' => 'admin/awards.php')
			);
 echo "<br />";

?>
<script type="text/javascript">

var fairs_id = -1;
var award_awards_id = -1;
function catdiv_load()
{
	$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=catdiv_load&id="+fairs_id,
        function(json) {
//		alert(json.toSource());
		$(".upload_cat").html("");
		for(var i in json.categories ) {
			var c = json.categories[i];
			$(".upload_cat").append("<option value=\""+i+"\">"+c.category+" (grade "+c.mingrade+" - "+c.maxgrade+")</option>");
		}
		$(".upload_div").html("");
		for(var i in json.divisions ) {
			var d = json.divisions[i];
			$(".upload_div").append("<option value=\""+i+"\">"+d.division+"</option>");
		}

		for(var i in json.catmap) {
			var v = json.catmap[i];
			$("#cat\\["+i+"\\]").val(v);
		}
		for(var i in json.divmap) {
			var v = json.divmap[i];
			$("#div\\["+i+"\\]").val(v);
		}
	});
	
}
function award_upload(id)
{
	$("#award_upload_status").load("<?=$_SERVER['PHP_SELF']?>?action=award_upload&id="+id);
}

function catdiv_save()
{
	$("#award_source_fairs_id").val(fairs_id);
	$("#debug").load("<?=$_SERVER['PHP_SELF']?>?action=catdiv_save",
			$('#catdiv_form').serializeArray());
	return false;
}
function catdiv_next()
{
	$('#upload_tabs').tabs('option', 'selected', -1);
	$('#upload_tabs').tabs('option', 'disabled', []);
	$('#upload_tabs').tabs('select', 1);
	return false;
}

function confirm_load()
{
	$("#confirm_data").load("<?=$_SERVER['PHP_SELF']?>?action=confirm_load&id="+award_awards_id);
}

function confirm_upload()
{
	$("#popup_upload").dialog('close');
	award_upload(award_awards_id);
}

function popup_upload(fid,aaid)
{
	var w = (document.documentElement.clientWidth * 0.7);
	var h = (document.documentElement.clientHeight * 0.8);

	fairs_id = fid;
	award_awards_id = aaid;

	/* Force no tabs to be selected, need to set collapsible 
	 * to true first */
	$('#upload_tabs').tabs('option', 'collapsible', true);
	$('#upload_tabs').tabs('option', 'selected', -1);
	$('#upload_tabs').tabs('option', 'disabled', [1]);
	$('#upload_tabs').tabs('select', 0);

	/* Don't let anything collapse */
	$('#upload_tabs').tabs('option', 'collapsible', false);

	/* Show the dialog */
	$('#popup_upload').dialog('option', 'width', w);
	$('#popup_upload').dialog('option', 'height', h);
	$("#popup_upload").dialog('open');

	return true;
}

/* Setup the popup window */
$(document).ready(function() { 
	$("#popup_upload").dialog({
			bgiframe: true, autoOpen: false,
			modal: true, resizable: false,
			draggable: false,
		});

	$("#upload_tabs").tabs({
			show: function(event, ui) { 
				switch(ui.panel.id) {
				case 'upload_tab_catdiv':
					catdiv_load();
					break;			
				case 'upload_tab_confirm':
					confirm_load();
					break;			
				}
				return true;
			},
			collapsible: true,
			selected: -1, /* None selected */
		});
});
</script>

<div id="popup_upload" title="Upload Award" style="display: none">
<div id="upload_tabs">
	<ul><li><a href="#upload_tab_catdiv"><span><?=i18n('Category/Division Mapping')?></span></a></li>
	<li><a href="#upload_tab_confirm"><span><?=i18n('Confirm Upload')?></span></a></li>
	</ul>

<div id="upload_tab_catdiv">
	<br />
	<form id="catdiv_form">
	<input type="hidden" name="award_source_fairs_id" id="award_source_fairs_id" value="0" />
	<h4><?=i18n("Category Mapping")?></h4>
	<br />
	<table class="editor">
	<tr><th><?=i18n("Our Category")?></th><th><?=i18n("Server Category")?></th></tr>
<?
	$q = mysql_query("SELECT * FROM projectcategories WHERE year='{$config['FAIRYEAR']}' ORDER BY mingrade");
	while($c = mysql_fetch_assoc($q)) {
		echo "<tr><td>{$c['category']}&nbsp;=> </td>";
		echo "<td><select id=\"cat[{$c['id']}]\" name=\"cat[{$c['id']}]\" class=\"upload_cat\">";
		while($sr=mysql_fetch_object($sq)) {
			echo "<option value=\"-1\">Loading...</option>";
		}
		echo '</select></td></tr>';
	}
?>
	</table>
	<br />
	<h4><?=i18n("Division Mapping")?></h4>
	<br />
	<table class="editor">
	<tr><th style="width: 50%;"><?=i18n("Our Division")?></th><th><?=i18n("Server Division")?></th></tr>
<?
	$q = mysql_query("SELECT * FROM projectdivisions WHERE year='{$config['FAIRYEAR']}' ORDER BY division");
	while($d = mysql_fetch_assoc($q)) {
		echo "<tr><td>{$d['division']}&nbsp;=> </td>";
		echo "<td><select id=\"div[{$d['id']}]\" name=\"div[{$d['id']}]\" class=\"upload_div\">";
		while($sr=mysql_fetch_object($sq)) {
			echo "<option value=\"-1\">Loading...</option>";
		}
		echo '</select></td></tr>';
	}
?>
	</table>
	<br />
	<br />
	<table style="border-width:0; width:100%">
	<tr><td></td>
	<td><input type="submit" onClick="#" disabled="disabled" value="<?=i18n("<< Prev")?>" /></td>
	<td><input type="submit" onClick="catdiv_save();return false;" value="<?=i18n("Save")?>" /></td>
	<td><input type="submit" onClick="catdiv_next();return false;" value="<?=i18n("Next >>")?>" /></td>
	</tr></table>
	<br />

	</form>
</div>
<div id="upload_tab_confirm">
	<br />
	<h4><?=i18n("Confirm Upload")?></h4>
	<br />
	<table style="border-width:0; width:100%">
	<tr><td></td>
	<td><input type="submit" onClick="confirm_prev();return false;" value="<?=i18n("<< Prev")?>" /></td>
	<td><input type="submit" onClick="confirm_upload();return false;" value="<?=i18n("Upload")?>" /></td>
	<td><input type="submit" onClick="#" disabled="disabled" value="<?=i18n("Next >>")?>" /></td>
	</tr></table>
	<br />
	
	<p><?=i18n("The following data will be sent to the server:")?></p>
	<pre id="confirm_data"></pre>
</div>

</div></div>

<?


if(!function_exists('curl_init')) {
	echo error(i18n("CURL Support Missing"));
	echo notice(i18n("Your PHP installation does not support CURL.  You will need to have CURL support added by your system administrator before being able to access external award sources"));
	send_footer();
	exit;
}

$q = mysql_query("SELECT award_awards.id, award_awards.name AS awardname,
			  fairs.name as fairname, award_source_fairs_id, 
			  fairs.type as fairtype, award_awards.external_additional_materials
			FROM award_awards 
			LEFT JOIN fairs ON fairs.id=award_awards.award_source_fairs_id 
			WHERE award_awards.award_source_fairs_id IS NOT NULL
				AND award_awards.year='{$config['FAIRYEAR']}'
			ORDER BY fairs.name, award_awards.name");
echo mysql_error();

?>

<table class="tableview">
<tr><th><?=i18n("Award Name")?></th>
<th><?=i18n("Source Name")?></th>
<th><?=i18n("Send")?></th>
<th><?=i18n("Additional<br />Info")?></th>
</tr>
<?
while($r=mysql_fetch_object($q)) {
	echo "<tr><td>{$r->awardname}</td>\n";
	echo "<td>{$r->fairname}</td>";
	echo "<td align=\"center\">";
	if($r->fairtype == 'sfiab')
		echo "<a href=\"#\" onClick=\"popup_upload({$r->award_source_fairs_id},{$r->id})\" >".i18n("send")."</a>";
	else
		echo "<a href=\"#\" onClick=\"award_upload({$r->id})\" >".i18n("send")."</a>";
	echo "</td><td>";

	if($r->external_additional_materials) {
		echo "<a href=\"{$_SERVER['PHP_SELF']}?action=additional_materials&award_awards_id={$r->id}\" target=\"_blank\">".i18n("download")."</a>";
	}
	
	echo "</td></tr>";
}
?>
</table>
<br />

<div id="award_upload_status"></div>
<?
/*<a href="award_upload.php?action=send<?=$sendurl?>"><?=i18n("Send all awards")?></a> */
send_footer();
?>
