<?php
include 'renderer.php';

class Setpassword extends Renderer {
    protected array $formFields = [
        ['label' => 'Benutzername', 'type' => 'text', 'size' => 50, 'name' => 'username', 'combine_with_next_line' => false],
        ['label' => '', 'type' => 'hidden', 'name' => 'code', 'combine_with_next_line' => false, 'size' => 50],
        ['label' => 'Neues Paßwort', 'type' => 'password', 'name' => 'newpassword1', 'combine_with_next_line' => false, 'size' => 50],
        ['label' => 'Paßwort wiederolen', 'type' => 'password', 'name' => 'newpassword2', 'combine_with_next_line' => false, 'size' => 50],
    ];
    protected string $formSendButtonLabel = 'Neues Paßwort setzen';
    protected array $errors = [];
    
    protected function generateContent(): void {
        $this->formFields[1]['value'] = filter_input(INPUT_GET, 'code', FILTER_SANITIZE_STRING);
    }
    
    protected function formAction(): void {
        if (!$this->formCheckFields()) {
            return;
        }
        $query = 'UPDATE user SET password="' . password_hash(filter_input(INPUT_POST, 'newpassword1', FILTER_SANITIZE_STRING), PASSWORD_DEFAULT) . '", recreate_db_hash = NULL ' .
                 'WHERE username="' . trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_ADD_SLASHES)) . '"';
        mysqli_query($this->dbConnection, $query);
        $this->templateName = 'passwordresettet';
    }
    
    protected function formCheckFields(): bool {
        $userName = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_ADD_SLASHES));
        if (!preg_match('/^([a-z0-9]{3,16})$/', $userName)) {
            $this->errors['username'] = 'Der Benutzername darf nur aus Buchstaben (ohne Umlaute) und Zahlen bestehen und muss zwischen drei und sechzen Zeichen lang sein.';
        } else {
            $query = 'SELECT id, recreate_db_hash FROM user WHERE username="' . $userName . '"';
            $dbResult = mysqli_query($this->dbConnection, $query);
            if (mysqli_num_rows($dbResult) == 0) {
                $this->errors['username'] = 'Der Benutzername ist nicht vergeben';
            } else {
                $row = mysqli_fetch_assoc($dbResult);
                if ($row['recreate_db_hash'] !== filter_input(INPUT_POST, 'code', FILTER_SANITIZE_STRING)) {
                    $this->errors[] = 'Ungültige Anfrage. Bitte beginnen Sie den Vorgan von vorne.';
                }
            }
        }
        if (strlen(filter_input(INPUT_POST, 'newpassword1', FILTER_SANITIZE_STRING)) < 8) {
            $this->errors['newpassword1'] = 'Das gewählte Paßwort ist zu kurz (Minimum: 8 Zeichen).';
        } 
        if (filter_input(INPUT_POST, 'newpassword2', FILTER_SANITIZE_STRING) !== filter_input(INPUT_POST, 'newpassword1', FILTER_SANITIZE_STRING)) {
            $this->errors['newpassword2'] = 'Die Paßwörter stimmen nicht überein.';
        }
        return (count($this->errors) === 0);
    }
}
