<?php

if (isset($_POST["leave_team"])) {
	quitTeam();
	exit();
}

$tournaments_response = $DB->query("SELECT `id`, `name` FROM `tournaments` WHERE `year` = '$YEAR';");

if (isset($_POST["send_document"])) {
	$error_message = sendDocument();
}

if (isset($_POST["request_validation"])) {
	if (!checkCanValidate())
		$error_message = "Votre équipe ne peut pas demander la validation : il manque soit des participants, soit des documents.";
	else
		$_SESSION["team"]->setValidationStatus(ValidationStatus::WAITING);
}

if (isset($_SESSION["user_id"]) && isset($_SESSION["team"]) && $_SESSION["team"] !== null) {
	/** @var Team $team */
	$team = $_SESSION["team"];

	$tournament = Tournament::fromId($team->getTournamentId());

	$documents_req = $DB->prepare("SELECT `file_id`, `type`, COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `tournament` = ? GROUP BY `type`, `uploaded_at` ORDER BY `type`, `uploaded_at` DESC;");
	$documents_req->execute([$_SESSION["user_id"], $_SESSION[$team->isSelectedForFinal() ? $FINAL->getId() : $tournament->getId()]]);
}
else
    require_once "server_files/403.php";

if (isset($_POST["team_edit"])) {
	$error_message = updateTeam();
}

function sendDocument()
{
	global $LOCAL_PATH, $DB;
	
	$type = strtoupper(htmlspecialchars($_POST["type"]));
	if (!isset($type) || ($type != "PARENTAL_CONSENT" && $type != "PHOTO_CONSENT" && $type != "SANITARY_PLUG"))
		return "Le type de document est invalide. Merci de ne pas formuler vos propres requêtes.";
	
	$file = $_FILES["document"];
	
	if ($file["size"] > 5000000 || $file["error"])
		return "Une erreur est survenue. Merci de vérifier que le fichier pèse moins que 5 Mo.";
	
	if (finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file["tmp_name"]) != 'application/pdf')
		return "Le fichier doit être au format PDF.";
	
	if (!is_dir("$LOCAL_PATH/files") && !mkdir("$LOCAL_PATH/files"))
		return "Les droits sont insuffisants. Veuillez contacter l'administrateur du serveur.";
	
	$alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
	
	do {
		$id = "";
		for ($i = 0; $i < 64; ++$i) {
			$id .= $alphabet[rand(0, strlen($alphabet) - 1)];
		}
	} while (file_exists("$LOCAL_PATH/files/$id"));
	
	if (!rename($file["tmp_name"], "$LOCAL_PATH/files/$id"))
		return "Une erreur est survenue lors de l'envoi du fichier.";
	
	$req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `tournament`, `type`)
                VALUES (?, ?, ?, ?, ?);");
	$req->execute([$id, $_SESSION["user_id"], $_SESSION["team_id"], $_SESSION[isset($_SESSION["final_id"]) ? "final_id" : "tournament_id"], $type]);
	
	return false;
}

function updateTeam()
{
	global $DB, $YEAR, $URL_BASE, $team;

	$name = htmlspecialchars($_POST["name"]);
	
	if (!isset($name) || $name == "")
		return "Vous devez spécifier un nom d'équipe.";

	$result = $DB->query("SELECT `id` FROM `teams` WHERE `name` = '" . $name . "' AND `id` != " . $team->getId() . " AND `year` = '$YEAR';");
	if ($result->fetch())
		return "Une équipe existe déjà avec ce nom.";
	
	$trigram = strtoupper(htmlspecialchars($_POST["trigram"]));
	
	if (!preg_match("#^[A-Z][A-Z][A-Z]$#", $trigram))
		return "Le trigramme entré n'est pas valide.";
	
	$result = $DB->query("SELECT `id` FROM `teams` WHERE `trigram` = '" . $trigram . "' AND `id` != '" . $team->getId() . "' AND `year` = '$YEAR';");
	if ($result->fetch())
		return "Une équipe a déjà choisi ce trigramme.";
	
	$tournament_id = intval(htmlspecialchars($_POST["tournament"]));
	$tournament = Tournament::fromId($tournament_id);
	if ($tournament === null)
		return "Le tournoi spécifié n'existe pas.";

	$team->setName($name);
	$team->setTrigram($trigram);
	$team->setTournamentId($tournament_id);
	$_SESSION["tournament"] = $tournament;
	
	header("Location: $URL_BASE/mon_equipe");
	
	return false;
}

function checkCanValidate()
{
	global $DB, $team, $tournament, $YEAR;

	$can_validate = $team->getValidationStatus() == ValidationStatus::NOT_READY;
	$can_validate &= $team->getEncadrants()[0] != NULL;
	$can_validate &= $team->getParticipants()[3] != NULL;
	for ($i = 1; $i <= 2; ++$i) {
		if ($team->getEncadrants()[$i - 1] === NULL)
			continue;
		
		$req = $DB->prepare("SELECT COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `type` = ? GROUP BY `uploaded_at` ORDER BY `uploaded_at` DESC;");
		$req->execute([$team->getEncadrants()[$i - 1], "PHOTO_CONSENT"]);
		$d = $req->fetch();
		$can_validate &= $d["version"] > 0;
		
		$req = $DB->prepare("SELECT COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `type` = ? GROUP BY `uploaded_at` ORDER BY `uploaded_at` DESC;");
		$req->execute([$team->getEncadrants()[$i - 1], "SANITARY_PLUG"]);
		$d = $req->fetch();
		$can_validate &= $d["version"] > 0;
	}
	for ($i = 1; $i <= 6; ++$i) {
		if ($team->getParticipants()[$i] === NULL)
			continue;
		
		$req = $DB->prepare("SELECT COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `type` = ? GROUP BY `uploaded_at` ORDER BY `uploaded_at` DESC;");
		$req->execute([$team->getParticipants()[$i], "PHOTO_CONSENT"]);
		$d = $req->fetch();
		$can_validate &= $d["version"] > 0;
		
		$req = $DB->prepare("SELECT COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `type` = ? GROUP BY `uploaded_at` ORDER BY `uploaded_at` DESC;");
		$req->execute([$team->getParticipants()[$i], "SANITARY_PLUG"]);
		$d = $req->fetch();
		$can_validate &= $d["version"] > 0;
		
		$birth_date = $DB->query("SELECT `birth_date` FROM `users` WHERE `id` = " . $team->getParticipants()[$i] . ";")->fetch()["birth_date"];
		if ($birth_date > strval($YEAR - 18) . substr($tournament->getStartDate(), 4)) {
			$req = $DB->prepare("SELECT COUNT(`type`) AS `version` FROM `documents` WHERE `user` = ? AND `type` = ? GROUP BY `uploaded_at` ORDER BY `uploaded_at` DESC;");
			$req->execute([$team->getParticipants()[$i], "PARENTAL_CONSENT"]);
			$d = $req->fetch();
			$can_validate &= $d["version"] > 0;
		}
	}
	
	return $can_validate;
}

require_once "server_files/views/mon_equipe.php";