<?php
include 'renderer.php';

class Register extends Renderer {
    protected array $formFields = [
        ['label' => 'Gewünscher Benutzername', 'type' => 'text', 'size' => 50, 'name' => 'username', 'combine_with_next_line' => false],
        ['label' => 'Vollständiger Name', 'type' => 'text', 'size' => 50, 'name' => 'fullname', 'combine_with_next_line' => false],
        ['label' => 'Email-Adresse', 'type' => 'email', 'size' => 50, 'name' => 'email', 'combine_with_next_line' => false],
        ['label' => 'Gewünschtes Paßwort', 'type' => 'password', 'size' => 50, 'name' => 'password', 'combine_with_next_line' => false],
        ['label' => 'Paßwort wiederholen', 'type' => 'password', 'size' => 50, 'name' => 'password2', 'combine_with_next_line' => false],
        ['label' => 'Ich stimme der Speicherung meiner Daten zu.', 'type' => 'checkbox', 'size' => 50, 'name' => 'accept', 'combine_with_next_line' => false,
         'value' => 1],
    ];
    protected string $formSendButtonLabel = 'Zugang beantragen';
    protected string $templateName = 'renderer';
    
    protected function formAction(): void {
        error_log('DEBUG Register::formAction aufgerufen');
        if (!$this->formCheckFields()) {
            error_log('DEBUG Register::formCheckFields fehlgeschlagen: ' . print_r($this->errors, true));
            // Bei Validierungsfehlern: nichts speichern, keine Mail, Fehler im Formular anzeigen
            return;
        }
        error_log('DEBUG Register::formCheckFields ok, schreibe in DB');
        $this->writeToDb();
        error_log('DEBUG Register::writeToDb erledigt, sende Mail');
        $this->sendEmail();
        error_log('DEBUG Register::sendEmail beendet, Errors: ' . print_r($this->errors, true));
        if (count($this->errors) === 0) {
            $this->templateName = 'register_successful';
        }
    }
    
    protected function formCheckFields(): bool {
        $username = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_ADD_SLASHES));
        $user = mysqli_query($this->dbConnection, 'SELECT * FROM user WHERE `username` = lower("' . $username . '")');
        if ($user->num_rows !== 0) {
            $this->errors[] = 'Der Benutzername existiert bereits.';
        }
        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.';
        }
        if (!filter_var(
                strtolower(trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL))),
                FILTER_VALIDATE_EMAIL
            )) {
            $this->errors['email'] = 'Die Email-Adresse ist inkorrekt';
        }
        if (strlen(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING)) < 8) {
            $this->errors['password'] = 'Das gewählte Paßwort ist zu kurz (Minimum: 8 Zeichen).';
        } 
        if (filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING) !== filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_STRING)) {
            $this->errors['password2'] = 'Die Paßwörter stimmen nicht überein.';
        }
        if (filter_input(INPUT_POST, 'accept', FILTER_SANITIZE_NUMBER_INT) !== '1') {
            $this->errors['accept'] = 'Sie müssen der Speicherung Ihrer Daten zustimmen.';
        }
        return (count($this->errors) === 0);
    }
    
    protected function writeToDb(): void {
        $salt = $this->generateRandomString();
        $encryptedName = $this->encode(trim(filter_input(INPUT_POST, 'fullname', FILTER_SANITIZE_STRING)), $salt);
        $email = strtolower(trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL)));
        $encryptedEmail = $this->encode($email, $salt);
        $query = sprintf("INSERT INTO ffajs.`user` (username, password, realname, email, active, save_data_accepted, salt, color_id) "
                . "VALUES('%s', '%s', '%s', '%s', 0, %d, '%s', COALESCE((SELECT c.id 
                            FROM color c 
                            left join `user` u
                            on u.color_id = c.id 
                            where u.id is null
                            order by rand()
                            limit 1), 1))",
                strtolower(trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING))),
                password_hash(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING), PASSWORD_DEFAULT),
                $encryptedName,
                $encryptedEmail,
                filter_input(INPUT_POST, 'accept', FILTER_SANITIZE_NUMBER_INT) ?: 0,
                $salt);
        mysqli_query($this->dbConnection, $query);
    }
    
    protected function sendEmail(): void {
        $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('foerderverein-ajs@gmx.de', 'Förderverein der Steffi-Jones-Schule');
        $message = 'Ein neuer Antrag auf Benutzerzugang wurde gestellt';
        $this->sendMail($mail, 'Zugang zu internem Bereich beantragt', $message, '');
    }
}
