<?php

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

$orgas_response = $DB->query("SELECT `id`, `surname`, `first_name` FROM `users` WHERE (`role` = 'ORGANIZER' OR `role` = 'ADMIN') AND `year` = '$YEAR';");

$has_error = false;
$error_message = null;

if (isset($_POST["submitted"])) {
    $tournament = new NewTournament($_POST);
    try {
    	$tournament->makeVerifications();
    	$tournament->register();
	}
	catch (AssertionError $e) {
    	$has_error = true;
    	$error_message = $e->getMessage();
	}
}

class NewTournament {
	public $name;
	public $organizers;
	public $size;
	public $place;
	public $price;
	public $date_start;
	public $date_end;
	public $date_inscription;
	public $time_inscription;
	public $date_solutions;
	public $time_solutions;
	public $date_syntheses;
	public $time_syntheses;
	public $description;
	public $final;
	public $tournament;

	public function __construct($data)
	{
		foreach ($data as $key => $value)
			$this->$key = ($key == "organizers" ? $value : htmlspecialchars($value));
	}

	public function makeVerifications()
	{
		global $FINAL;

		ensure($this->name != null && $this->name != "", "Le nom est invalide.");
		ensure(!tournamentExists($this->name), "Un tournoi existe déjà avec ce nom.");
		ensure(sizeof($this->organizers) > 0, "Aucun organisateur n'a été choisi.");

		$orgas = [];
		foreach ($this->organizers as $orga_id) {
			$orga = User::fromId($orga_id);
			ensure($orga != null, "Un organisateur spécifié n'existe pas.");
			ensure($orga->getRole() == Role::ORGANIZER || $orga->getRole() == Role::ADMIN, "Une personne indiquée ne peut pas organiser de tournoi.");
			$orgas[] = $orga;
		}
		$this->organizers = $orgas;

		ensure(preg_match("#[0-9]*#", $this->size), "Le nombre d'équipes indiqué n'est pas un nombre valide.");
		$this->size = intval($this->size);
		ensure($this->size >= 3 && $this->size <= 15, "Un tournoi doit avoir au moins 3 et au plus 15 équipes.");

		ensure(preg_match("#[0-9]*#", $this->price), "Le tarif pour les participants n'est pas un entier valide.");
		$this->price = intval($this->price);
		ensure($this->price >= 0, "Le TFJM² ne va pas payer les élèves pour venir.");
		ensure($this->price <= 50, "Soyons raisonnable sur le prix.");

		ensure(dateWellFormed($this->date_start), "La date de début n'est pas valide.");
		ensure(dateWellFormed($this->date_end), "La date de fin n'est pas valide.");
		ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date de clôture des inscriptions n'est pas valide.");
		ensure(dateWellFormed($this->date_solutions . " " . $this->time_solutions), "La date limite de remise des solutions n'est pas valide.");
		ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse n'est pas valide.");

		$this->final = $this->final ? 1 : 0;

		ensure(!$this->final || $FINAL == NULL, "Une finale nationale est déjà enregistrée.");
	}

	public function register()
	{
		global $DB, $YEAR;

		$req = $DB->prepare("INSERT INTO `tournaments` (`name`, `size`, `place`, `price`, `description`, 
                           `date_start`, `date_end`, `date_inscription`, `date_solutions`, `date_syntheses`, `final`, `year`)
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
		$req->execute([$this->name, $this->size, $this->place, $this->price, $this->description, $this->date_start, $this->date_end,
			"$this->date_inscription $this->time_inscription", "$this->date_solutions $this->time_solutions", "$this->date_syntheses $this->time_syntheses", $this->final ? 1 : 0, $YEAR]);

		$this->tournament = Tournament::fromName($this->name);

		/** @var User $organizer */
		foreach ($this->organizers as $organizer) {
			$this->tournament->addOrganizer($organizer);
			Mailer::sendAddOrganizerForTournamentMail($organizer, $this->tournament);
		}
	}
}

require_once "server_files/views/ajouter_tournoi.php";