<?php

	require_once 'config.php';
	require_once 'dbh.inc.php';
	require_once 'checkLogin.php';
	

	// EXAMPLE INPUT...
	// array(3) { ["name"]=> string(0) "" ["email"]=> string(0) "" ["addUser"]=> string(0) "" }


	if(isset($_POST['addUser'])) {

		$name = mysqli_real_escape_string($connection, trim($_POST['name']));
		$email = mysqli_real_escape_string($connection, trim($_POST['email']));
		
		// Check if name is not an empty string
		if($name === '') {
			http_response_code(400);
			echo json_encode(array("error" => "Must specify name."));
			exit();
		}
		
		
		// Check if email is not an empty string
		// And that email is valid email
		// And that email is from UPR
		// And that email is not already registered
		if($email === '') {
			http_response_code(400);
			echo json_encode(array("error" => "Must specify email."));
			exit();
		} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			http_response_code(400);
			echo json_encode(array("error" => "Invalid email."));
			exit();
		} else if(explode("@", $email)[1] !== "upr.edu") {
			http_response_code(400);
			echo json_encode(array("error" => "Email has to be from UPR."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM researcher WHERE email = '$email';")->num_rows !== 0) {
			http_response_code(400);
			echo json_encode(array("error" => "Given email already registered."));
			exit();
		}
		
		// Insert user
		$queryUser = "INSERT INTO researcher (`name`, `email`) VALUES ('$name', '$email');";
		mysqli_query($connection, $queryUser) or die("Error: " . mysqli_error($connection));
		
		header("Location: ../users.php");

	}