<?php
include 'renderer.php';

class Login extends Renderer {
    protected array $formFields = [
        ['label' => 'Benutzername', 'type' => 'text', 'size' => 50, 'name' => 'username', 'combine_with_next_line' => false],
        ['label' => 'Paßwort', 'type' => 'password', 'size' => 50, 'name' => 'password', 'combine_with_next_line' => false],
    ];
    protected string $formSendButtonLabel = 'Einloggen';
    
    protected function formAction(): void {
        $this->userId = 0;
        $result = mysqli_query($this->dbConnection, 'SELECT * FROM user WHERE `username` = lower("' . trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_ADD_SLASHES)) . '")');
        if ($result->num_rows !== 1) {
            $this->errors[] = 'Benutzer und/oder Paßwort falsch';
            return;
        }
        $user = $result->fetch_assoc();
        if (!password_verify(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING), $user['password'])) {
            $this->errors[] = 'Benutzer und/oder Paßwort falsch';
            return;
        }
        if ($user['active'] !== '1') {
            $this->errors[] = 'Dein Zugang ist noch nicht freigeschaltet.';
            return;
        }
        $_SESSION['userid'] = $user['id'];
        header('Location: accounts', true, 301);
        die();
    }
}    
