<?PHP
/***
 * SU Signup admin 
 * Allows us to search the SU api for a given student number and checks if they're a SUCS member.
 * If they are - allows account renewal
 * If not - allows signup to be bootstrapped as per susignup component
 ***/

include("../lib/member_functions.php");
include("../suapi.inc.php");

//Restrict access to staff. 
$permission="sucsstaff";

if (isset($session->groups[$permission])) {
	//Setup smarty magic, step 1
	$smarty->assign("staff", TRUE);

	if(!isset($_REQUEST['mode'])) {
		$mode = 'menu';
	} else {
		$mode = urldecode($_REQUEST['mode']);
	}

	//Set up SUCS DB Connection.
	//Note that $DB is the generic sucssite connection
	
	$sucsDB = NewADOConnection('postgres8');
	$sucsDB->Connect('dbname=sucs user=apache');
	$sucsDB->SetFetchMode(ADODB_FETCH_ASSOC);

	if ($mode == 'search') {
		if (empty($_REQUEST['sid']) || empty($_REQUEST['snsubmit'])) {
			$mode = 'error';
			$smarty->assign("error_text", "Invalid search request");	
		}else{
			$pres=preg_match("/^[0-9]{6}$/",$_REQUEST['sid'],$sid);
			if ($pres!=1) {
				$mode = 'error';
				$smarty->assign("error_text", "Search term doesn't look like a valid student ID");
			} else {
				$url = "https://$suapi_user:$suapi_pass@hap.swansea-union.co.uk/memberships/Membership.asmx/IsPersonMember?strCriteria=".$sid[0]."&GroupingId=6613";
				$apiReq = curl_init();
				curl_setopt($apiReq, CURLOPT_URL, $url);
				curl_setopt($apiReq, CURLOPT_RETURNTRANSFER, TRUE);

				$apiResult = curl_exec($apiReq);
				if ($apiResult === FALSE) {
					$mode = 'error';
					$smarty->assign("error_text", "An error occurred communicating with the SUSU API. Please try again later.");
				}else {
					// Ostensibly we now have a valid search result from the SU - go to work
					$xml=new SimpleXMLElement($apiResult);
					$ismember = $xml[0];
					if ($ismember=="true") {
						//Yay, we have a student who has paid and needs to be signed up.
						//Check they don't have a signup slip already
						$query = "SELECT transactionid, signupid FROM transactions WHERE cardNumber = ?;";
						$qres = $sucsDB->Execute($query, $sid);
						
						if ($qres->RecordCount()==0) {
							// No transaction, but might have unused signup slip. If so, retrieve values.
							$query = "SELECT id, username, password FROM signup WHERE sid=?;";
							$qres = $sucsDB->Execute($query, array($sid[0]));
							if ($qres && $qres->RecordCount() > 0) {
								if ($qres->RecordCount() > 1) {
									$mode='error';
									$smarty->assign("error_text", "Student has multiple signup slips in the DB. Bork! Bork! Bork!");
								} else if (!empty($qres->fields['username'])) {
									$mode='error';
									$smarty->assign("error_text", "Student hasn't tried to use the SU signup component (No transaction in DB), but has a previously used Signup Slip with username ".$qres->fields['username'].".<br />Is this a renewal? If not, ask an admin to generate a new signup slip for this student");
									//TODO: Add option to generate new signup slip?
								} else {
									$id = $qres->fields['id'];
									$pass = $qres->fields['password'];
								}
							} else {
								$pass = make_password();
								$query = "INSERT INTO signup (password,sid,issuedby) VALUES ( ?, ?, ?) RETURNING id";
								$attribs[]=addslashes($pass);
								$attribs[]=$sid[0];
								$attribs[]='99999'; //SUCS Magic internal use UID

								$id = $sucsDB->Execute($query,$attribs);
								$id = $id->fields['id'];
								if (!$id) {
									$mode="error";
									$smarty->assign("error_text", "An error occurred generating a signup ID. Report the following message to the admins:<br /><pre>".$sucsDB->ErrorMsg()."</pre>");
								} else {
									$smarty->assign('slipid', $id);
									$smarty->assign('slippass', $pass);
									$smarty->assign('sid', $sid[0]);
								}
							}
						} else {
							//Retrieve existing slip
							$id = $qres->fields['signupid'];
							$tid = $qres->fields['transactionid'];
							if (empty($id)) {
								$pass = make_password();
								$query = "INSERT INTO signup (password,sid,issuedby) VALUES ( ?, ?, ?) RETURNING id";
								$attribs[]=addslashes($pass);
								$attribs[]=$sid[0];
								$attribs[]='99999'; //SUCS Magic internal use UID

								$qres = $sucsDB->Execute($query,$attribs);
								if (!$qres) {
									$mode="error";
									$smarty->assign("error_text", "An error occurred generating a signup ID. Report the following message to the admins:<br /><pre>".$sucsDB->ErrorMsg()."</pre>");
								} else {
									$id = $qres->fields['id'];
									$query = "UPDATE transactions SET signupid=? WHERE transactionid=?;";
									$qres = $sucsDB->Execute($query, array($id, $tid));
									$smarty->assign('slipid', $id);
									$smarty->assign('slippass', $pass);
									$smarty->assign('sid', $sid[0]);
								}

							}else {
								$query = "SELECT username, password FROM signup WHERE id=?;";
								$qres = $sucsDB->Execute($query, array($id));
								if (!$qres) {
									$mode="error";
									$smarty->assign("error_text", "The user appears to have generated a signup ID using the SU Signup system (Slip ID: ".$id."), but the password for that slip can't be retrieved.<br />Request assistance.");
								} else if ($qres->fields['username'] !== NULL) {
									$mode="error";
									$smarth->assign("error_text", "This user appears to have completed signup, with username <strong>".$qres->fields['username']."</strong><br />Check that this user exists, and offer to reset their password if necessary.");
								}
								$pass = $qres->fields['password'];
								$smarty->assign('slipid', $id);
								$smarty->assign('slippass', $pass);
								$smarty->assign('sid', $sid[0]);
							}
						}

						if(!$mode=='error') {
							//Right, this should be the point where we hand off to signup
							$smarty->assign('slipid', $id);
							$smarty->assign('slippass', $pass);
							$smarty->assign('sid', $sid[0]);
						}

					}else{
						$mode='error';
						$smarty->assign("error_text", "Student does not appear to have paid. Extract fees");
					}
				}
			}
		}
	}
}
$smarty->assign('title', 'SU Signup Admin');
$smarty->assign('mode', $mode);
$body = $smarty->fetch("susignup-admin.tpl");
$smarty->assign('body', $body);
$smarty->assign("extra_styles", array("$baseurl/css/susignup-admin.css"));

function su_json_decode($text) {
	$re1='.*?';
	$re2='(\\{.*?\\})';
	if ($c=preg_match_all ("/".$re1.$re2."/is", $text, $matches))
	{
		$json_string=$matches[1][0];
	}else{
		  return FALSE;
	}
	return json_decode($json_string,TRUE);
}