<?php

/**
 * Class RegistrationModel
 *
 * Everything registration-related happens here.
 */
class RegistrationModel
{
    /**
     * Handles the entire registration process for DEFAULT users (not for people who register with
     * 3rd party services, like facebook) and creates a new user in the database if everything is fine
     *
     * @return boolean Gives back the success status of the registration
     */
    public static function registerNewUser($admin = false)
    {
        // TODO this could be written simpler and cleaner

        if (!Session::userIsAdmin()) {
            $admin = false;
        }

        // clean the input
        $registration = new stdClass();
        $registration->user_name = strip_tags(Request::post('user_name'));
        $registration->user_email = strip_tags(Request::post('user_email'));
        $registration->user_password_new = Request::post('user_password_new');
        $registration->user_password_repeat = Request::post('user_password_repeat');

        // stop registration flow if registrationInputValidation() returns false (= anything breaks the input check rules)
        $validation_result = RegistrationModel::registrationInputValidation(Request::post('captcha'),
                                                                            $registration->user_name,
                                                                            $registration->user_password_new,
                                                                            $registration->user_password_repeat,
                                                                            $registration->user_email,
                                                                            $admin);
        if (!$validation_result) {
            return $registration;
        }

        // crypt the password with the PHP 5.5's password_hash() function, results in a 60 character hash string.
        // @see php.net/manual/en/function.password-hash.php for more, especially for potential options
        $user_password_hash = password_hash($registration->user_password_new, PASSWORD_DEFAULT);

        // check if username already exists
        if (UserModel::doesUsernameAlreadyExist($registration->user_name)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_ALREADY_TAKEN'));
            return $registration;
        }

        // check if email already exists
        if (UserModel::doesEmailAlreadyExist($registration->user_email) && !$admin) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USER_EMAIL_ALREADY_TAKEN'));
            return $registration;
        }

        // generate random hash for email verification (40 char string)
        if (!$admin) {
            $user_activation_hash = sha1(uniqid(mt_rand(), true));
        } else {
            $user_activation_hash = null;
        }

        // write user data to database
        if (!RegistrationModel::writeNewUserToDatabase($registration->user_name,
                                                       $user_password_hash,
                                                       $registration->user_email,
                                                       time(),
                                                       $user_activation_hash,
                                                       $admin)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_CREATION_FAILED'));
        }

        // get user_id of the user that has been created, to keep things clean we DON'T use lastInsertId() here
        $user_id = UserModel::getUserIdByUsername($registration->user_name);

        if (!$user_id) {
            Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR'));
            return $registration;
        }

        if ($admin) {
            UserProfileModel::createUserProfile($user_id);
            UserModel::setUserActive($user_id);
            Session::add('feedback_positive', Text::get('ADMIN_FEEDBACK_ACCOUNT_SUCCESSFULLY_CREATED'));
            return true;
        }

        // send verification email
        if (RegistrationModel::sendVerificationEmail($user_id, $registration->user_email, $user_activation_hash)) {

            // send mail to administrator
            $email = new stdClass();
            $email->address = Config::getFromDB('MarketAdminEmail');
            $email->subject = 'Ein neuer Nutzer hat sich auf '.Config::getFromDB('MarketName').' Registriert';
            $email->body = "Benutzername: ".$registration->user_name."\n"
                          ."eMail-Adresse: ".$registration->user_email;
            $mail = new Mail;
            $mail->insertEmailToSend($email);

            Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUCCESSFULLY_CREATED'));
            return true;
        }

        // if verification email sending failed: instantly delete the user
        RegistrationModel::rollbackRegistrationByUserId($user_id);
        Session::add('feedback_negative', Text::get('FEEDBACK_VERIFICATION_MAIL_SENDING_FAILED'));
        return $registration;
    }

    /**
     * Validates the registration input
     *
     * @param $captcha
     * @param $user_name
     * @param $user_password_new
     * @param $user_password_repeat
     * @param $user_email
     *
     * @return bool
     */
    public static function registrationInputValidation($captcha, $user_name, $user_password_new, $user_password_repeat, $user_email, $admin = false)
    {
        if ($admin &&
            self::validateUserName($user_name) &&
            self::validateUserPassword($user_password_new,
                                       $user_password_repeat)) {
            return true;
        }

        // perform all necessary checks
        if (!CaptchaModel::checkCaptcha($captcha) && !$admin) {
            Session::add('feedback_negative', Text::get('FEEDBACK_CAPTCHA_WRONG'));
            return false;
        }

        // if username, email and password are all correctly validated
        if ($admin) {
            return false;
        } elseif (self::validateUserName($user_name) &&
            self::validateUserEmail($user_email) &&
            self::validateUserPassword($user_password_new,
                                       $user_password_repeat)) {
            return true;
        }

        // otherwise, return false
        return false;
    }

    /**
     * Validates the username
     *
     * @param $user_name
     * @return bool
     */
    public static function validateUserName($user_name)
    {
        if (empty($user_name)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_FIELD_EMPTY'));
            return false;
        }

        // if username is too short (2), too long (64) or does not fit the pattern (aZ09)
        if (!preg_match('/^[a-zA-Z0-9]{2,64}$/', $user_name)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_DOES_NOT_FIT_PATTERN'));
            return false;
        }

        return true;
    }

    /**
     * Validates the email
     *
     * @param $user_email
     * @return bool
     */
    public static function validateUserEmail($user_email)
    {
        if (empty($user_email)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY'));
            return false;
        }

        // validate the email with PHP's internal filter
        // side-fact: Max length seems to be 254 chars
        // @see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
        if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
            return false;
        }

        return true;
    }

    /**
     * Validates the password
     *
     * @param $user_password_new
     * @param $user_password_repeat
     * @return bool
     */
    public static function validateUserPassword($user_password_new, $user_password_repeat)
    {
        if (empty($user_password_new) OR empty($user_password_repeat)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_FIELD_EMPTY'));
            return false;
        }

        if ($user_password_new !== $user_password_repeat) {
            Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_REPEAT_WRONG'));
            return false;
        }

        if (strlen($user_password_new) < 6) {
            Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_TOO_SHORT'));
            return false;
        }

        return true;
    }

    /**
     * Writes the new user's data to the database
     *
     * @param $user_name
     * @param $user_password_hash
     * @param $user_email
     * @param $user_creation_timestamp
     * @param $user_activation_hash
     *
     * @return bool
     */
    public static function writeNewUserToDatabase($user_name, $user_password_hash, $user_email, $user_creation_timestamp, $user_activation_hash, $admin = false)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        // get registration status for user approval
        switch (Config::getFromDB('MarketRegistrationStatus')) {
          case 1:
              $user_approved = 0;
              break;
          case 2:
              $user_approved = 1;
              break;
          default:
              $user_approved = 1;
              break;
        }

        if ($admin) {
            $user_approved = 1;
        }

        // write new users data into database
        $sql = "INSERT INTO ".$prefix."users
                       (user_name,
                        user_password_hash,
                        user_email,
                        user_approved,
                        user_creation_timestamp,
                        user_activation_hash)
                VALUES (:user_name,
                        :user_password_hash,
                        :user_email,
                        :user_approved,
                        :user_creation_timestamp,
                        :user_activation_hash)";
        $query = $database->prepare($sql);
        $query->execute(array(':user_name' => $user_name,
                              ':user_password_hash' => $user_password_hash,
                              ':user_email' => $user_email,
                              ':user_approved' => $user_approved,
                              ':user_creation_timestamp' => $user_creation_timestamp,
                              ':user_activation_hash' => $user_activation_hash));
        $count =  $query->rowCount();
        if ($count == 1) {
            return true;
        }

        return false;
    }

    /**
     * Deletes the user from users table. Currently used to rollback a registration when verification mail sending
     * was not successful.
     *
     * @param $user_id
     */
    public static function rollbackRegistrationByUserId($user_id)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("DELETE FROM ".$prefix."users
                                     WHERE user_id = :user_id");
        $query->execute(array(':user_id' => $user_id));
    }

    /**
     * Sends the verification email (to confirm the account).
     * The construction of the mail $body looks weird at first, but it's really just a simple string.
     *
     * @param int $user_id user's id
     * @param string $user_email user's email
     * @param string $user_activation_hash user's mail verification hash string
     *
     * @return boolean gives back true if mail has been sent, gives back false if no mail could been sent
     */
    public static function sendVerificationEmail($user_id, $user_email, $user_activation_hash)
    {
        $verificationLink = Config::getURL()
                            . Config::get('EMAIL_VERIFICATION_URL')
                            . '/' . urlencode($user_id)
                            . '/' . urlencode($user_activation_hash);
        if (Config::getFromDB('MarketRegistrationStatus') == 1) {
            $body = PA::filter(Text::get('EMAIL_REGISTRATION_APPROVE_BODY'), $verificationLink);
        } else {
            $body = PA::filter(Text::get('EMAIL_REGISTRATION_BODY'), $verificationLink);
        }

        $mail = new Mail;
        $mail_sent = $mail->sendMail($user_email, Config::getFromDB('MarketContactEmail'),
            Config::getFromDB('MarketName'), PA::filter(Text::get('EMAIL_REGISTRATION_SUBJECT'),
                                                        Config::getFromDB('MarketName')), $body
        );

        if ($mail_sent) {
            return true;
        } else {
            Session::add('feedback_negative', Text::get('FEEDBACK_VERIFICATION_MAIL_SENDING_ERROR') . $mail->getError() );
            return false;
        }
    }

    /**
     * checks the email/verification code combination and set the user's activation status to true in the database
     *
     * @param int $user_id user id
     * @param string $user_activation_verification_code verification token
     *
     * @return bool success status
     */
    public static function verifyNewUser($user_id, $user_activation_verification_code)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "UPDATE ".$prefix."users
                SET user_active = 1,
                    user_activation_hash = NULL
                WHERE user_id = :user_id
                  AND user_activation_hash = :user_activation_hash
                LIMIT 1";
        $query = $database->prepare($sql);
        $query->execute(array(':user_id' => $user_id,
                              ':user_activation_hash' => $user_activation_verification_code));

        if ($query->rowCount() == 1) {
            if (Config::getFromDB('MarketRegistrationStatus') == 1) {
                Session::add('feedback_positive', Text::get('FEEDBACK_UNAPPROVED_ACCOUNT_ACTIVATION_SUCCESSFUL'));
            } else {
                Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_SUCCESSFUL'));
            }
            return true;
        }

        Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_FAILED'));
        return false;
    }
}
