<?php

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] != Role::ORGANIZER && $_SESSION["role"] != Role::ADMIN)
	require_once "server_files/403.php";

$trigram = htmlspecialchars($_GET["trigram"]);

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

if ($team === null)
	require_once "server_files/404.php";

if (isset($_POST["validate"])) {
	$team->setValidationStatus(ValidationStatus::VALIDATED);
}

if (isset($_POST["select"])) {
	$team->selectForFinal(true);
	$team->setValidationStatus(ValidationStatus::NOT_READY);
	$sols = $tournament->getAllSolutions($team->getId());
	/** @var Solution $sol */
	foreach ($sols as $sol) {
		$old_id = $sol->getFileId();
		do
			$id = genRandomPhrase(64);
		while (file_exists("$LOCAL_PATH/files/$id"));
		
		copy("$LOCAL_PATH/files/$old_id", "$LOCAL_PATH/files/$id");
		
		$req = $DB->prepare("INSERT INTO `solutions`(`file_id`, `team`, `tournament`, `problem`) VALUES (?, ?, ?, ?);");
		$req->execute([$id, $team->getId(), $FINAL->getId(), $sol->getFileId()]);
	}
}

if (isset($_POST["download_zip"])) {
	$final = isset($_POST["final"]);
	$tournament_dest = $final ? $FINAL : $tournament;

	$file_name = getZipFile(DocumentType::PARENTAL_CONSENT, $tournament_dest->getId(), $team->getId());

	header("Content-Type: application/zip");
	header("Content-Disposition: attachment; filename=\"Documents de l'équipe " . $team->getTrigram() . ".zip\"");
	header("Content-Length: " . strval(filesize($file_name)));

	readfile($file_name);

	exit();
}

$documents = $tournament->getAllDocuments($team->getId());
$documents_final = null;

if ($team->isSelectedForFinal())
	$documents_final = $FINAL->getAllDocuments($team->getId());

require_once "server_files/views/equipe.php";