<?php
include 'renderer.php';

class Newpassword extends Renderer {
    protected array $formFields = [
        ['label' => 'Email-Adresse', 'type' => 'email', 'size' => 50, 'name' => 'email', 'combine_with_next_line' => false],
    ];
    protected string $formSendButtonLabel = 'Login-Name zusenden und Paßwort-Reset anfordern';
    
    protected function formAction(): void {
        $email = trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));
        $query = 'SELECT id, realname, email, username, salt FROM user';
        $dbResult = mysqli_query($this->dbConnection, $query);
        while ($row = mysqli_fetch_assoc($dbResult)) {
            if ($email === $this->decode($row['email'], $row['salt'])) {
                $salt = $row['salt'];
                $this->sendResetEmail($row['id'], $row['username'], $this->decode($row['email'], $salt), $this->decode($row['realname'], $salt));
                break;
            }
        }
        $this->templateName = 'newpassword_done';
    }
    
    protected function sendResetEmail(int $id, string $username, string $emailAddress, string $realName) {
        $resetId = $this->generateRandomString();
        $query = 'update user set recreate_db_hash="' . $resetId . '" where id=' . $id;
        mysqli_query($this->dbConnection, $query);
        $mail = $this->initSmtpMailer();
        $mail->setFrom('foerderverein-ajs@gmx.de', 'Förderverein der Steffi-Jones-Schule');
        $mail->addReplyTo('foerderverein-ajs@gmx.de', 'Förderverein der Steffi-Jones-Schule');
        $mail->addAddress($emailAddress, $realName);
        $this->sendMail($mail, 'Passwort zurücksetzen für ' . filter_input(INPUT_SERVER, 'SERVER_NAME'), $this->getEmailBody($username, $realName, $resetId), $this->generateSignature(''));
    }
    
    protected function getEmailBody(string $username, string $realname, string $code) {
        $rawBody = file_get_contents('templates/resetaccountmailbody.html');
        return str_replace(['{{name}}', '{{username}}', '{{server}}', '{{code}}', '{{protocol}}'], 
                           [$realname, $username, filter_input(INPUT_SERVER, 'SERVER_NAME'), $code, (filter_input(INPUT_SERVER, 'HTTPS') ? 's' : '') ], $rawBody);
    }
}
