<?
/* 
   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("xml.inc.php");
 require_once("../user.inc.php");

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

 //function get_cwsf_award_winners()
 function get_winners_for_award($awardid)
 {
 	global $config;
 	$winners=array();

 	$q=mysql_query("SELECT * FROM award_awards WHERE id='$awardid' AND year='".$config['FAIRYEAR']."'");
	if(mysql_num_rows($q)==1)
	{
		$award=mysql_fetch_object($q);
		$pq=mysql_query("SELECT * FROM award_prizes WHERE award_awards_id='$award->id'");
		while($prize=mysql_fetch_object($pq))
		{
			$wq=mysql_query("SELECT 
						projects.id,
						projects.projectnumber,
						projects.title,
						projects.summary,
						projects.registrations_id,
						projects.projectdivisions_id
						
					FROM 
						winners,
						projects
					WHERE 
						winners.projects_id=projects.id AND
						awards_prizes_id='$prize->id' AND 
						winners.year='".$config['FAIRYEAR']."'");
						echo mysql_error();
			while($project=mysql_fetch_object($wq))
			{
				$sq=mysql_query("SELECT * FROM students WHERE registrations_id='$project->registrations_id' AND year='".$config['FAIRYEAR']."'");
				$students=array();
				while($s=mysql_fetch_object($sq))
				{
					$schoolq=mysql_query("SELECT * FROM schools WHERE id='$s->schools_id'");
					$school=array();
					if($schoolr=mysql_fetch_object($schoolq)) {
						$school=array(
									"xml_type"=>"school",
									"schoolname"=>$schoolr->school,
									"schoollang"=>$schoolr->schoollang,
									"schoollevel"=>$schoolr->schoollevel,
									"board"=>$schoolr->board,
									"district"=>$schoolr->district,
									"phone"=>$schoolr->phone,
									"fax"=>$schoolr->fax,
									"address"=>$schoolr->address,
									"city"=>$schoolr->city,
									"province_code"=>$schoolr->province_code,
									"postalcode"=>$schoolr->postalcode,
									"principal"=>$schoolr->principal,
									"schoolemail"=>$schoolr->schoolemail,
									"sciencehead"=>$schoolr->sciencehead,
									"scienceheademail"=>$schoolr->scienceheademail,
									"scienceheadphone"=>$schoolr->scienceheadphone
								);
					}
					$students[]=array(
								"xml_type"=>"student",
								"firstname"=>$s->firstname,
								"lastname"=>$s->lastname,
								"email"=>$s->email,
								"gender"=>$s->sex,
								"grade"=>$s->grade,
								"language"=>$s->lang,
								"birthdate"=>$s->dateofbirth,
								"address1"=>$s->address,
								"address2"=>"",
								"city"=>$s->city,
								"province"=>$s->province,
								"postalcode"=>$s->postalcode,
								"phone"=>$s->phone,
								"teachername"=>$s->teachername,
								"teacheremail"=>$s->teacheremail,
								"school"=>$school
							);

				}
				$prizewinners[]=array(
						"xml_type"=>"project",
						"projectid"=>$project->id,
						"projectnumber"=>$project->projectnumber,
						"title"=>$project->title,
						"abstract"=>$project->summary,
						"students"=>$students,
						);
			}
			$winners[]=array(
			"xml_type"=>"prize",
			"identifier"=>$prize->external_identifier,
			"projects"=>$prizewinners
			);
		}
		//print_r($award);
	}
	return $winners;
 }


 if($_GET['action']=="send")
 {
 	if(count($_GET['send'])) {
		require_once("xml.inc.php");
		foreach($_GET['send'] AS $awardid) {


			 $q=mysql_query("SELECT award_awards.id, 
	 			award_awards.name AS awardname,
	 			award_awards.external_identifier,
	 			award_awards.external_postback,
				award_sources.name AS sourcename,
				award_sources.username,
				award_sources.password
	 			FROM 
					award_awards 
				JOIN award_sources ON award_awards.award_sources_id=award_sources.id
				WHERE award_sources.enabled='yes' 
				AND award_awards.id='$awardid'");

			if($r=mysql_fetch_object($q)) {
				echo i18n("Sending award winners for %1 to %2...",array($r->awardname,$r->sourcename));
				if(!($r->username && $r->password && $r->external_postback)) {
					echo error(i18n("Username, Password or Postback Address missing, cannot send winners for this award"));
					continue;
				}
				$winners=get_winners_for_award($r->id);
				echo "<br />";
				if(count($winners)==0) {
					echo "&nbsp;&nbsp;".i18n("No winner(s) selected for this award... reporting no winners")."<br />";
				}

				$reg=array("awardwinners"=>array(
					"username"=>$r->username,
					"password"=>$r->password,
					"identifier"=>$r->external_identifier,
					"prizes"=>$winners
					)
				);

				$output="";
				xmlCreateRecurse($reg);
				$xmldata=$output;

				$ch = curl_init(); /// initialize a cURL session
				curl_setopt ($ch, CURLOPT_URL,$r->external_postback);
				curl_setopt ($ch, CURLOPT_HEADER, 0); /// Header control
				curl_setopt ($ch, CURLOPT_POST, 1);  /// tell it to make a POST, not a GET
				curl_setopt ($ch, CURLOPT_POSTFIELDS, "xml=$xmldata");  /// put the query string here starting with "?"
				curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); /// This allows the output to be set into a variable $datastream
				curl_setopt ($ch, CURLOPT_POSTFIELDSIZE, 0);
				curl_setopt ($ch, CURLOPT_TIMEOUT, 360);
				curl_setopt ($ch, CURLOPT_SSLVERSION, 3);
				$datastream = curl_exec ($ch); /// execute the curl session and return the output to a variable $datastream
				$datastream = str_replace(" standalone=\"yes\"","",$datastream);
				// echo "curl close <br />";
				curl_close ($ch); /// close the curl session
				echo i18n("Response from server:");
				$response=xml_parsexml($datastream);
				if($response && is_array($response)) {
					$keys=array_keys($response);
					if($keys[0]=="awardwinnersresponse") {
						$status=$response['awardwinnersresponse'][0]['status'][0];
						$statusmessage=$response['awardwinnersresponse'][0]['statusmessage'][0];
						if($status=="success")
							echo happy(i18n("Success: %1",array($statusmessage)));
						else
							echo error(ucfirst($status).": ".$statusmessage); //not translated, because it came right from the server!
					}
					else
					{
						echo error(i18n("Invalid XML response.  Expecting '%1', received '%2'",array("awardwinnersresponse",$keys[0])));
						echo "datastream: ".htmlspecialchars($datastream);
					}
				}
				else
				{
					echo error(i18n("Invalid response.  Couldn't parse XML or no data returned",array("awardwinnersresponse",$keys[0])));
					echo "datastream: ".htmlspecialchars($datastream);

				}

			}
			echo "<br />";
		}
	}
 }
 else
 {
	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"));
		$links=false;
	}
	else
		$links=true;

	 $q=mysql_query("SELECT award_awards.id, 
	 			award_awards.name AS awardname,
				 award_sources.name AS sourcename
	 			FROM 
					award_awards 
				JOIN award_sources ON award_awards.award_sources_id=award_sources.id
				WHERE award_sources.enabled='yes' 
				ORDER BY award_sources.name, award_awards.name");
				echo mysql_error();
	 echo "<table class=\"tableview\">";
	 echo "<tr><th>".i18n("Award Name")."</th>";
	 echo "<th>".i18n("Source Name")."</th>";
	 echo "<th>".i18n("Send")."</th>";
	 echo "</tr>";
	 while($r=mysql_fetch_object($q)) {
		echo "<tr>";
		echo "<td>$r->awardname</td>\n";
		echo "<td>$r->sourcename</td>";
		echo "<td align=\"center\">";
		if($links)
			echo "<a href=\"award_upload.php?action=send&send[]=$r->id\">".i18n("send")."</a>";
		else
			echo "n/a";
		echo "</td>";
		echo "</tr>";
		$sendurl.="&send[]=$r->id";
	 }
	 echo "</table>\n";
	 echo "<br />";
	 
	 if($links)
		 echo "<a href=\"award_upload.php?action=send$sendurl\">".i18n("Send all awards")."</a>";

 }
 send_footer();
?>