<?php
    const MESSAGE = 'Hallo %%NAME%%,<br/><br/>das Passwort für deinen 4Creative-Account wurde soeben über die Funktion "Passwort vergessen" geändert.<br/><br/>Solltest du diese Änderung nicht selbst durchgeführt haben, wende dich bitte umgehend per E-Mail (info@4creative.net) oder Discord (@ikeytan) an uns.';
    const TOKEN_INVALID = 'Dieser Link zur Passwortzurücksetzung ist nicht gültig. Bitte klicke oder kopiere den Link aus der E-Mail, die du erhalten hast.';
    const TOKEN_EXPIRED = 'Dein Link zur Passwortzurücksetzung ist abgelaufen. Klicke <a href="index.php?page=forgot">hier</a>, um eine neue Anfrage zu senden.';

    function displayTokenError($message)
    {
        $HTML = new HTML();
        $HTML->importHTML("error.html");
        $HTML->ReplaceLayoutInhalt('%%MESSAGE%%', $message);
        $HTML->build();
        echo $HTML->ausgabe();
        exit();
    }

    function displayPage($err)
    {
        if (!isset($_GET['token']) || !preg_match('/^[a-z0-9A-Z]{32}$/', $_GET['token'])) {
            displayTokenError(TOKEN_INVALID);
        }

        $HTML = new HTML();
        $HTML->setHTMLTitle("");
        $HTML->importHTML("reset-password.html");
        $HTML->ReplaceLayoutInhalt('%%MESSAGE%%', $err);
        $HTML->ReplaceLayoutInhalt('%%RESET_TOKEN%%', htmlspecialchars($_GET['token']));
        $HTML->build();
        echo $HTML->ausgabe();
        exit();
    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        include_once 'app/FormValidator.php';
        $validator = new FormValidator(array(
            'password' => array('required' => true, 'regex' => '/^.{1,1000}$/'),
            'passwordRepeat' => array('required' => true, 'regex' => '/^.{1,1000}$/'),
            'resetToken' => array('required' => true, 'regex' => '/^[a-zA-Z0-9]{32}$/')
        ));

        if ($validator->isValid($_POST)) {
            if ($_POST['password'] !== $_POST['passwordRepeat']) {
                displayPage('Du musst in beiden Feldern das gleiche Passwort eingeben');
            }

            if (strlen($_POST['password']) < $RUNTIME['PASSWORD_MIN_LENGTH']) {
                displayPage('Dein Passwort muss mindestens '.$RUNTIME['PASSWORD_MIN_LENGTH'].' Zeichen lang sein.');
            }

            $getReq = $RUNTIME['PDO']->prepare('SELECT UserAccounts.PrincipalID AS UUID,FirstName,LastName,Email,Token,RequestTime FROM PasswordResetTokens JOIN UserAccounts ON UserAccounts.PrincipalID = PasswordResetTokens.PrincipalID WHERE Token = ?');
            $getReq->execute([$_POST['resetToken']]);
            if ($getReq->rowCount() == 0) {
                displayTokenError(TOKEN_INVALID);
            }

            $res = $getReq->fetch();

            if (!hash_equals($res['Token'], $_POST['resetToken'])) {
                displayTokenError(TOKEN_INVALID);
            }

            $uuid = $res['UUID'];
            $name = $res['FirstName'].' '.$res['LastName'];
            $getToken = $RUNTIME['PDO']->prepare('DELETE FROM PasswordResetTokens WHERE PrincipalID = ? AND Token = ?');
            $getToken->execute([$uuid, $_POST['resetToken']]);
            if ($getToken->rowCount() == 0) {
                displayTokenError(TOKEN_INVALID);
            }

            if (time() - $res['RequestTime'] > 86400) {
                displayTokenError(TOKEN_EXPIRED);
            }

            $salt = bin2hex(random_bytes(16));
            $hash = md5(md5(trim($_POST['password'])).':'.$salt);
            $statement = $RUNTIME['PDO']->prepare('UPDATE auth SET passwordHash = :PasswordHash, passwordSalt = :PasswordSalt WHERE UUID = :PrincipalID');
            $statement->execute(['PasswordHash' => $hash, 'PasswordSalt' => $salt, 'PrincipalID' => $uuid]);

            session_unset();
            $_SESSION['loginMessage'] = 'Du kannst dich jetzt mit deinem neuen Passwort einloggen!';
            $_SESSION['loginMessageColor'] = 'darkgreen';

            require_once 'app/utils.php';
            sendMail($res['Email'], str_replace('%%NAME%%', $name, MESSAGE), 'Passwort für '.$name.' zurückgesetzt', 'Passwort geändert', 'Das Passwort für deinen 4Creative-Account wurde soeben zurückgesetzt');

            header('Location: index.php?page=login');
            exit();
        }
    }

    displayPage('');