<?php
	require_once("../system.engine/system.core.php");
	$l->setPrefix("ajax.handle.submit.signup");
	
	$mPong = array();
	$a = &$mPong;
	$p = &$_POST;
	
	global $systemHandler;
	$systemExecution = $systemHandler->loadHandler("EXECUTION");
	$systemHash = $systemHandler->loadHandler("HASH");
	$systemSession = $systemHandler->loadHandler("SESSION");
	/* ### DO YOUR CODES ONLY FROM HERE ### */

	// 1. Validate first- and lastname
	if(strlen($p["registerFirstname"]) > 0 && strlen($p["registerLastname"]) > 0 && strlen($p["registerFirstname"]) <= 20 && strlen($p["registerLastname"]) <= 20) {
		// 2. Validate the email
		if(filter_var($p["registerMail"], FILTER_VALIDATE_EMAIL)) {
			// 3. Check if the email is already in use?
			if($systemExecution->runQuery("SELECT COUNT(id) AS mailCount FROM web_user WHERE mail = '%s'", $p["registerMail"])->fetch_object()->mailCount == 0) {
				$mPassword = $systemHash->hashString($p["registerPass"]);
				$mSecretHash = $systemHash->hashString($p["registerMail"].$p["registerPass"]);
				$systemExecution->runQuery("INSERT INTO web_user (mail, firstname, lastname, password, signup_time, signin_time, secret_hash, profile_hash) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", array($p["registerMail"], $p["registerFirstname"], $p["registerLastname"], $mPassword, time(), time(), $mSecretHash, 0));
				$systemSession->appendSession("USER", $systemExecution->runQuery("SELECT id FROM web_user WHERE mail = '%s' AND password = '%s'", array($p["registerMail"], $mPassword))->fetch_object()->id);
				$systemExecution->runQuery("INSERT INTO web_albums(album_name, album_owner_id, album_privacy, album_is_standard, album_date_created) VALUES ('%s', '%s', '%s', '%s', '%s')", array($p["registerFirstname"]."'s pictures", $systemSession->loadSession("USER"), "friends", "yes", time()));
				$systemHandler->loadHandler("MAIL")->submitRegistrationMail($p["registerMail"], $p["registerFirstname"].' '.$p["registerLastname"]);
				$a["isValid"] = true;
			} else $a["isValid"] = $l->getValue("emailinuse");
		} else $a["isValid"] = $l->getValue("emailinvalid");
	} else $a["isValid"] = $l->getValue("firstlastnameinvalid");
	
	/* ### DO NOT CHANGE ANYTHING FROM HERE ### */
	header("Content-Type: application/json");
	echo json_encode($mPong);
?>