<?php

// gib errars plox
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

// this is the php for sucs.org/susignup

// Include shit we need.
include "../lib/member_functions.php";
include "../lib/date.php";

// include the suapiv2 stuff like check_su_sid_and_trans()
include "suapiv2.php";

// since the rewrite by ~imranh this no longer sends out emails
// feel free to add it
// Where do errors go?
$error_email = "admin@sucs.org";

// By default display a page asking for sid and transid
// this is called "login"
$mode = 'login';

// if somone has post'd data to the page then do shit
if(!empty($_REQUEST['sid'])&&!empty($_REQUEST['transactionID'])){

	// stick the post'd data in a variable we can call easily
	$sid = $_REQUEST['sid'];
        $transactionID = $_REQUEST['transactionID'];

	// check if the data posted is valid
	if(check_su_sid_and_trans($sid,$transactionID)){

		// check to see if they are already a valid and paid member
		$tmpresult = $sucsDB->Execute("SELECT * FROM members WHERE sid=?", array($sid));
		if($tmpresult->fields["sid"] == $sid && $tmpresult->fields["paid"] == paidUntil(time())){
			// let them know they are already signed up and renewed
			trigger_error("You are a numpty and have already signed up and paid for this year.", E_USER_ERROR);
		// else if check to see if they have signedup and paid for the new year but haven't renewed
		}else if ($tmpresult->fields["sid"] == $sid && $tmpresult->fields["paid"] != paidUntil(time())){
			// update our db to indicate that they ahev paid for thsi year
			$sucsDB->Execute("UPDATE members SET paid=?, lastupdate=DEFAULT, lastedit=? WHERE sid=?", array(paidUntil(time()), "99999", $sid));
			// let them know that their account has been renewed
			trigger_error("Your SUCS account has been renewed.", E_USER_INFO);
		// else if they aren't in the SUCS DB but have a signup slip, take them back to that part of signup
		$singuptmpresult = $sucsDB->Execute("SELECT * FROM signup WHERE sid=?", array($sid));
		} else if ($tmpresult->fields == false && $signuptmpresult->fields["sid"] == $sid) {
			$mode = "form";
			$smarty->assign("id",$signuptmpresult->fields["id"]);
			$smarty->assign("pass",$signuptmpresult->fields["password"]);
		// else if they aren't in the SUCS DB, then bootstrap signup process
		} else if ($tmpresult->fields == false && $signuptmpresult->fields == false) {
			$mode = "form";
			$pass = make_password();
			$iddata = $sucsDB->Execute("insert into signup (password,sid,issuedby) values( ?, ?, ?) returning id",array($pass,$sid,"99999"));
			$id = $iddata->fields['id'];
			$smarty->assign("id", $id);
			$smarty->assign("pass", $pass);
		} else {
			// they should never get here
			echo("fuck you");
		}
	} else {
		trigger_error("That Student Number and Transaction ID combo are invalid.", E_USER_ERROR);
	}
}


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

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


?>