<?php

if (!isset($_SESSION["user_id"]))
	require_once "server_files/403.php";

/** @var User $user */
$user = $_SESSION["user"];

$has_error = false;
$error_message = null;

if (isset($_POST["update_account"])) {
    $my_account = new MyAccount($_POST);
    try {
    	$my_account->makeVerifications();
    	$my_account->updateAccount();
	}
	catch (AssertionError $e) {
    	$has_error = true;
    	$error_message = $e->getMessage();
	}
}

if (isset($_POST["update_password"])) {
	$new_password = new NewPassword($_POST);
	try {
		$new_password->makeVerifications();
		$new_password->updatePassword();
	}
	catch (AssertionError $e) {
		$has_error = true;
		$error_message = $e->getMessage();
	}
}

if (isset($_POST["send_document"])) {
    $send_document = new SendDocument();
    try {
        $send_document->makeVerifications();
        $send_document->sendDocument();
    }
    catch (AssertionError $e) {
        $has_error = true;
        $error_message = $e->getMessage();
    }
}

class MyAccount
{
	public $email;
	public $surname;
	public $first_name;
	public $school;
	public $city;
	public $country;
	public $class;
	public $description;
	public $receive_animath_mails;
	/** @var User */
	private $user;

	public function __construct($data)
	{
		foreach ($data as $key => $value)
			$this->$key = htmlspecialchars($value);

		$this->user = $_SESSION["user"];

		$keys = ["email", "surname", "first_name", "school", "class", "description"];

		if ($this->user->getRole() == Role::PARTICIPANT)
			$this->class = SchoolClass::fromName($this->class);

		foreach ($keys as $key)
			$this->$key = $this->$key != null && $this->$key != "" ? $this->$key : $this->user->$key;

		$this->receive_animath_mails = $this->receive_animath_mails == "on";
	}

	public function makeVerifications()
	{
		ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide.");
		$this->email = strtolower($this->email);
		ensure($this->email == $this->user->getEmail() || !userExists($this->email), "Un compte existe déjà avec cette adresse e-mail.");
		$this->receive_animath_mails = $this->receive_animath_mails != false;
	}

	public function updateAccount()
	{
		$this->user->setSurname($this->surname);
		$this->user->setFirstName($this->first_name);
		$this->user->setSchool($this->school);
		$this->user->setCity($this->city);
		$this->user->setCountry($this->country);
		$this->user->setClass($this->class);
		$this->user->setDescription($this->description);
		$this->user->setReceiveAnimathMails($this->receive_animath_mails);

		if ($this->email != $this->user->getEmail()) {
			$this->user->setEmail($this->email);
			$this->user->setConfirmEmailToken(genRandomPhrase(64));

			Mailer::sendChangeEmailAddressMail($this->user);
		}
	}
}

class NewPassword
{
	private $user;
	private $old_password;
	private $new_password;
	private $confirm_password;

	public function __construct($data)
	{
		foreach ($data as $key => $value)
			$this->$key = htmlspecialchars($value);

		$this->user = $_SESSION["user"];
	}

	public function makeVerifications()
	{
		ensure($this->user->checkPassword($this->old_password), "L'ancien mot de passe est incorrect.");
		ensure(strlen($this->new_password) >= 8, "Le mot de passe doit comporter au moins 8 caractères.");
		ensure($this->new_password == $this->confirm_password, "Les deux mots de passe sont différents.");
	}

	public function updatePassword()
	{
		$this->user->setPassword($this->new_password);

		Mailer::sendChangePasswordMail($this->user);
	}
}

class SendDocument
{
    private $file;

    public function __construct()
    {
        $this->file = $_FILES["document"];
    }

    public function makeVerifications()
    {
        global $LOCAL_PATH;

        ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo.");
        ensure(!$this->file["error"], "Une erreur est survenue.");
        $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]);
        ensure($mime_type == "application/pdf" || $mime_type == "image/png" || $mime_type == "image/jpeg", "Le fichier doit être au format PDF.");
        ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenu dans l'envoi du fichier. Veuillez vérifier que le fichier pèse moins de 2 Mo. Merci de compresser votre fichier si tel n'est pas le cas. En cas de problème, merci de contacter l'administrateur du serveur.");
    }

    public function sendDocument()
    {
        global $LOCAL_PATH, $DB;

        do
            $id = genRandomPhrase(64);
        while (file_exists("$LOCAL_PATH/files/$id"));

        if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id"))
            throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier.");

        $req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `problem`)
                VALUES (?, ?, ?, ?);");
        $req->execute([$id, $_SESSION["user_id"], $_SESSION["team"]->getId(), $_SESSION["team"]->getProblem()]);
    }
}

$documents = $user->getAllDocuments();

require_once "server_files/views/mon_compte.php";