<?php

// TODO: ...
class User 
{
    private Session  $session;
    private Database $database;

    // Always initialized
    public bool    $loggedIn;

    // Initialized only if logged in 
    public string  $username;
    public string  $password;
    public int     $powerLevel;

    public function __construct(Session $session, Database $database)
    {
        $this->session  = $session;
        $this->database = $database;

        $user = $this->session->get('user');

        // Check if user session has been set
        if (!$user)
        {
            $this->loggedIn = FALSE;
            return;
        }

        // Check if username and password match
        if (!$this->authenticate($user['username'], $user['password']))
        {
            $this->loggedIn = FALSE;
            $this->logout();
            $this->session->flash('Kontodetaljer er blitt endret, vennligst logg inn igjen', 'warning');
            return;
        }

        // All is good, we should be logged in now! (hopefully)
        $this->loggedIn = TRUE;
        $this->username = $user['username'];
        $this->password = $user['password'];

        // Set powerLevel
        $sth = $this->database->conn->prepare(
            'SELECT * FROM brukertabell WHERE Navn = ? AND Passord = ?'
        );
        $sth->execute([$this->username, $this->password]);
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        $this->powerLevel = $row['NivÄ'];
    }

    // Set session if user and password match
    public function login(string $username, string $password): bool
    {
        if ($this->authenticate($username, $password))
        {
            $this->session->set('user', [
                'loggedIn' => TRUE,
                'username' => $username,
                'password' => $password
            ]);
            return TRUE;
        }
        return FALSE;
    }

    // Check if user and password match database
    private function authenticate(string $username, string $password): bool
    {
        $sth = $this->database->conn->prepare(
            'SELECT * FROM brukertabell WHERE Navn = ? AND Passord = ?'
        );
        $sth->execute([$username, $password]);
        if ($sth->rowCount())
        {
            return TRUE;
        }
        return FALSE;
    }

    public function logout(): void
    {
        $this->session->remove('user');
    }
}