<?php

class Account
{
    private static function checkTokenLifetime($creationDate) {
        $config = Kohana::$config->load('security.securityPolicy');
        $lifetime = $config['recoveryToken']['lifetime'];
        return (time() - $creationDate) > $lifetime;
    }

    public static function checkToken($token) {
        $recovery = Model_Account::getRecoveryInfoByToken($token)[0];
        $response = true;

        if ($recovery['isUsed']) {
            $response = false;
        } else {
            $date = strtotime($recovery['Date']);
            if (self::checkTokenLifetime($date)) {
                Model_Account::useRecoveryToken($recovery['Token']);
                $response = false;
            }
        }
        return $response;
    }

    public static function createRecoveryRequest($email) {
        $requestToken = sha1($email.time().Cookie::$salt);

        $UserFullName = Model_Account::createRecoveryToken($email, $requestToken);
        if (!$UserFullName) {
            throw HTTP_Exception::factory(403, 'Пользователь с таким e-mail адресом не зарегистрирован в системе!');
        }

        $subject = ASSEMBLY_SYSTEM_NAME . ": Восстановление пароля";

        $twig = Twig::factory('email/recovery');
        $twig->curl = 'https://grade.sfedu.ru/'; // URL::base('https', TRUE); TODO: fix after mmcs.sfedu.ru gets SSL-certificate
        $twig->Token = $requestToken;
        $twig->EMail = $email;
        $twig->Subject = $subject;

        SendMail::send($subject, $twig->render(), $email, $UserFullName);
    }

    // remind password
    public static function changePasswordByToken($token, $password) {
        $recovery = Model_Account::getRecoveryInfoByToken($token)[0];
        Model_Account::changePassword($recovery['AccountID'], $password);
        Model_Account::useRecoveryToken($token);
    }

    public static function doesLoginExist($login) {
        return Model_Account::checkAccountExistenceBy('login', $login);
    }

    public static function doesEmailExist($email) {
        return Model_Account::checkAccountExistenceBy('email', $email);
    }


//    // We don't change email address:\
//    public static function changeEMail($id, $newEMail) {
//        return (bool) Model_Account::changeMail($id, $newEMail);
//    }
}