<?php

//unique society identifier
$GroupingID = "6613";

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

$error_email = "admin@sucs.org";
$mode = 'login';
//login
if(!empty($_REQUEST['sid'])&&!empty($_REQUEST['transactionID'])){
//set signup details
	
	$sid = $_REQUEST['sid'];
        $transactionID = $_REQUEST['transactionID'];
                                            
	//set POST variables
	$url = "https://$suapi_user:$suapi_pass@hap.swansea-union.co.uk/memberships/Membership.asmx/GetMemberByTransactionID";
	$fields = array(
	       'transactionID'=>urlencode($transactionID),
	       'GroupingID'=>urlencode($GroupingID),
	       );
	//url-ify the data for the POST
	$field_string = "";
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	//open connection
	$ch = curl_init();

	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	//execute post
	$result = curl_exec($ch);
	
	//close connection
	curl_close($ch);
	if(!$result){
	}else{	
  		$re1='.*?';	
		$re2='(\\{.*?\\})';	
		if ($c=preg_match_all ("/".$re1.$re2."/is", $result, $matches))
		{
		  	$json_string=$matches[1][0];
		}else{
			  //ERROR
		}
		$array = json_decode($json_string,TRUE);
		if($array['cardNumber'] == $sid && $sid != ""){
		  	$mode = 'form';

			// connect to sucs database
                        $sucsDB = NewADOConnection('postgres8');
				
			// SET THIS FOR DEBUG MODE
			// $sucsDB->debug = true;
			// SET THIS TO YOUR DB FOR TESTING
                        $sucsDB->Connect('dbname=sucs user=apache');

			$sucsDB->SetFetchMode(ADODB_FETCH_ASSOC);
			$fullName = $array['firstName']." ".$array['lastName'];
			$query = "INSERT INTO transactions (transactionID,fullName,emailAddress,cardNumber,personID) values(?, ?, ?, ?, ?)";
			$attribs[] = $transactionID;
			$attribs[] = $fullName;
			$attribs[] = $array['emailAddress'];
			$attribs[] = $array['cardNumber'];
			$attribs[] = $array['personID'];

			$valid = true;
			if(!$sucsDB->Execute($query,$attribs)) {
				// We did this because Adodb ErrorNo command is broken
				$query = "SELECT * FROM transactions WHERE transactionID = ?";
				unset($attribs);
				$attribs[]=$transactionID;
				if($sucsDB->Execute($query,$attribs)) {
				
					$query = "SELECT * FROM transactions WHERE transactionID = ?";
					$attribs= array();
					$attribs[]=$transactionID;
					$data = $sucsDB->GetAll($query,$attribs); 
					if(is_array($data)&&sizeof($data)==1&&$data[0]['signupid']==NULL){
						// As it stands this shouldn't happen but if it does, no reason not to let them carry on
						$valid = true;
					} elseif(is_array($data)&&sizeof($data)==1&&$data[0]['signupid']!=NULL) {
						$query = "SELECT * FROM signup WHERE sid = ? AND username IS NULL";
						unset($attribs);
						$attribs[]=$sid;
						$data = $sucsDB->Execute($query, $attribs);
						if(!$data) {
							mail(  
                                                        	$error_email,
	                                                        "SUSignup Error",
        	                                                "An error occured in the susignup system at stage 0\n Love the signup system.\n\nP.S. The Error is:\n ".$sucsDB->ErrorMsg(),
                	                                        "From: \"SUCS Admin\" <admin@sucs.org>"
                                                );
							$valid=false;
						} else if($data->RecordCount()==0) {
							$smarty->assign("username", $data->fields['username']);
							$mode='numpty2';		
							// This happens if they already ahve a SUCS account and are trying to create a new signupid  
							$valid = false;
						} else {
							$smarty->assign("id", $data->fields['id']);
							$smarty->assign("pass", $data->fields['password']);
							$mode='numpty';
							// If this happens they tried to get a new signupid/pass after already getting one, and should get weekly reminders about it  
							$valid = false;
						}
					} else {
						$mode="error";
						mail(
							$error_email,
							"SUSignup Error",
							"An error occured in the susignup system at stage 1\n Love the signup system.\n\nP.S. The Error is:\n ".$sucsDB->ErrorMsg(),
							"From: \"SUCS Admin\" <admin@sucs.org>"
						);

						$valid = false;
					}

				} else {
					$mode="error";
					mail(
						$error_email,
						"SUSignup Error",
						"An error occured in the susignup system at stage 2\n Love the signup system.\n\nP.S. The Error is:\n ".$sucsDB->ErrorMsg(),
						"From: \"SUCS Admin\" <admin@sucs.org>"
					);

					$valid = false;
				}
			}

			if($valid)
			{
				$pass = make_password();		
				unset($query);
				$query = "insert into signup (password,sid,issuedby) values( ?, ?, ?) returning id";
				unset($attribs);
				$attribs[]=addslashes($pass);
				$attribs[]=$array['cardNumber'];
				$attribs[]='99999';
			
				$id = $sucsDB->Execute($query,$attribs);
				$id = $id->fields['id'];
				if (!$id) {
					$mode="error";
					mail(   
						$error_email,
						"SUSignup Error",
						"An error occured in the susignup system at stage 3\n Love the signup system.\n\nP.S. The Error is:\n ".$sucsDB->ErrorMsg(),
						"From: \"SUCS Admin\" <admin@sucs.org>"
					);
				} else {
					$query = "update transactions set signupid=? WHERE transactionID=?";
					unset($attribs);
					$attribs[]=$id;
					$attribs[]=$transactionID;
					if(!$sucsDB->Execute($query,$attribs)) {
						$mode="error";
						mail(
							$error_email,
							"SUSignup Error",
							"An error occured in the susignup system at stage 4\n Love the signup system.\n\nP.S. The Error is:\n ".$sucsDB->ErrorMsg(),
							"From: \"SUCS Admin\" <admin@sucs.org>"
						);
						print($sucsDB->ErrorMsg());
					} else {
		        	              	$smarty->assign("id", $id);
              				        $smarty->assign("pass", $pass);
						mail(
							$array['emailAddress'].','.$sid.'@swansea.ac.uk',
							"SUCS Signup Information",
							"Thankyou for joining Swansea University Computer Society, your signup details are below;\nSignupID: $id\nSignup Password: $pass\nIf you have successfully completed signup immediately then you can disregard this message.\n\nSUCS Admin Team.",
							"From: \"SUCS Admin\" <admin@sucs.org>"
						);

					}
				}
			} else {
				//ERROR
			}

		  }


	}


}

$smarty->assign("mode", $mode);
$output = $smarty->fetch("susignup.tpl");

$smarty->assign("title", "Join");
$smarty->assign("body", $output);


?>