<?php

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


	// EXAMPLE INPUT...
	// array(9) { ["title"]=> string(5) "title" ["description"]=> string(11) "description" ["type"]=> string(4) "type" ["duration"]=> string(1) "1" ["start"]=> string(10) "2019-11-22" ["end"]=> string(10) "2019-11-29" ["institution"]=> string(1) "1" ["expiry_time"]=> string(2) "60" ["newExperience"]=> string(0) "" }

	// IF USER ENTERS PAGE AFTER 'Create' BUTTON HAS BEEN PRESSED (FROM home.php), INSERT NEW EXPERIENCE TO DATABASE
	// ELSE (IF USER ENTERED THIS PAGE WITHOUT SUBMITING A FORM) REDIRECT TO home.php
	if(isset($_POST['newExperience'])) {

		
		// CLEAN USER INPUT
		$title = mysqli_real_escape_string($connection, trim($_POST['title']));
		$description = mysqli_real_escape_string($connection, trim($_POST['description']));
		$type = mysqli_real_escape_string($connection, trim($_POST['type']));
		$duration_weeks = mysqli_real_escape_string($connection, trim($_POST['duration']));
		$start_date = mysqli_real_escape_string($connection, trim($_POST['start']));
		$end_date = mysqli_real_escape_string($connection, trim($_POST['end']));
		$institution = mysqli_real_escape_string($connection, trim($_POST['institution']));
		$expiry_time = mysqli_real_escape_string($connection, trim($_POST['expiry_time']));
		
		
		// Check that experienceTitle is not an empty string
		// And that it doesn't exceed 60 characters (database limit)
		if($title === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience title."));
			exit();
		} else if(mb_strlen($title) > 60) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience title too long (max. is 60 characters)."));
			exit();
		}
		
		
		// Check that experienceDescription is not an empty string
		// And that it doesn't exceed 100 characters (database limit)
		if($description === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience description."));
			exit();
		} else if(mb_strlen($description) > 100) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience description too long (max. is 100 characters)."));
			exit();
		}
		

		// Check that experienceType is Course-Based Research or Independent Research
		if($type !== "Course-Based Research" && $type !== "Independent Research") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify valid experience type (either 'Course-Based Research' or 'Independent Research')."));
			exit();
		} else if(mb_strlen($type) > 60) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience type too long (max. is 60 characters)."));
			exit();
		}
		
		
		// Check that startDate is not an empty string
		// And that startDate is in appropriate format YYYY-MM-DD (e.g. 2222-02-22)
		// WARNING: only handling AST
		// HELP: https://www.codexworld.com/how-to/validate-date-input-string-in-php/
		
		function validDate($date) {
			$d = date_create_from_format("Y-m-d", $date);
			return $d && date_format($d, "Y-m-d") === $date;
		}
		
		if($start_date === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience's start date."));
			exit();
		} else if(!validDate($start_date)) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience's start date ($start_date) given in wrong format (use YYYY-MM-DD instead)."));
			exit();
		}


		// Check that endDate is not an empty string
		// And that endDate is in appropriate format YYYY-MM-DD (e.g. 2222-02-22)
		// WARNING: only handling AST
		// HELP: https://www.codexworld.com/how-to/validate-date-input-string-in-php/
		if($end_date === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify experience's end date."));
			exit();
		} else if(!validDate($end_date)) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience's end date ($end_date) given in wrong format (use YYYY-MM-DD instead)."));
			exit();
		}
		
		
		// Calculate duration in seconds
		$duration_seconds = strtotime($end_date) - strtotime($start_date);
		
		
		// Check that endDate occurs after the startDate
		if($duration_seconds <= 0) {
			http_response_code(400);
			echo json_encode(array("error" => "Experience's end date ($end_date) must occur at least a day after the start date ($start_date)."));
			exit();
		}
		
		
		// Change seconds to weeks and round up
		$duration_weeks = round($duration_seconds / 604800); // 60 * 60 * 24 * 7
		
		
		// Check that institutionID is not an empty string
		// And that the institutionID given is in database
		if($institution === "") {
			http_response_code(400);
			echo json_encode(array("error" => "Please specify institution ID."));
			exit();
		} else if(mysqli_query($connection, "SELECT * FROM institution WHERE id = '$institution';")->num_rows !== 1) {
			http_response_code(400);
			echo json_encode(array("error" => "Given institution ID not in database."));
			exit();
		}
		
		
		// Check that expiryTime is permitted (30min, 1hr, 2hr, 3hr, 6hr, 12hr, 18hr, 24hr)
		$permittedExpiryTimes = array("30", "60", "120", "180", "360", "720", "1080", "1440");
		if(!in_array($expiry_time, $permittedExpiryTimes, TRUE)) {
			http_response_code(400);
			echo json_encode(array("error" => "Expiry time given is not permitted (use only 30, 60, 120, 180, 360, 720, 1080 or 1440)."));
			exit();
		}
		
		
		
		
		
		/*** START OF DB QUERIES ***/
// 		exit();
// 		while(TRUE) {
// 			exit();
// 		}
// 		exit();	
		/*** IF IT GOT THROUGH VALIDATION, IT'S TOO LATE ***/
		
		
		
		
		
		// INSERTAR A TABLA experience EL TÍTULO, DESCRIPCIÓN, TIPO, DURACIÓN, START Y END DE LA EXPERIENCIA NUEVA
		$queryInsert = "INSERT INTO `experience` (`title`, `description`, `type`, `duration_weeks`, `start_date`, `end_date`, `expiry_time`) VALUES ('$title', '$description', '$type', '$duration_weeks', '$start_date', '$end_date', '$expiry_time');";
		if(!mysqli_query($connection, $queryInsert)) die("Error: ".mysqli_error($connection));
		
		
		// BUSCAR id DE LA EXPERIENCIA ACABADA DE INSERTAR
		$id_experience = mysqli_insert_id($connection) or die('Error: '.mysqli_error($connection));
		
		
		// CREAR HASH PARA EL ENVÍO DEL URL A ESTUDIANTES
		$hash = substr(sha1($id_experience), 0, 40);
		$queryHash = "UPDATE experience SET hash_id = '$hash' WHERE id = '$id_experience';";
		if(!mysqli_query($connection, $queryHash)) die("Error: ".mysqli_error($connection));

		
		// ASOCIAR LA EXPERIENCIA NUEVA CON LA INSTITUCIÓN ESCOGIDA
		$queryHookExperienceToInstitution = "INSERT INTO `institution_experience` (`id_institution`, `id_experience`) VALUES ('$institution', '$id_experience');";
		if(!mysqli_query($connection, $queryHookExperienceToInstitution)) die("Error: ".mysqli_error($connection));
		
		
		// ASOCIAR LA EXPERIENCIA NUEVA CON EL USUARIO
		$queryHookExperienceToUser = "INSERT INTO `researcher_experience` (`id_researcher`, `id_experience`) VALUES ('" . $_SESSION['dbUserData']['id_researcher'] . "', '$id_experience')";
		if(!mysqli_query($connection, $queryHookExperienceToUser)) die("Error: ".mysqli_error($connection));
		
		// MAKE IT CLIENT SIDE!!!!!!!! HAVE TO SEND IT IN SERVER RESPONSE!!!!!!!
// 		header('Location: ../viewExperience.php?view=$id_experience');
// 		exit();
		
	}
	
	
	