<?php

declare(strict_types=1);

namespace App\Modules\Administration\Controllers;

use App\Controllers\Controller;
use App\Modules\Administration\Services\AuthenticationService;
use System\Http\Request;
use System\View\View;

final class LoginController extends Controller
{
    public function __construct(
        private AuthenticationService $authentication,
        private Request $request,
        View $view
    ) {
        parent::__construct($view);
    }

    public function index(): void
    {
        if ($this->authentication->check()) {

            header(
                'Location: /public/dashboard'
            );

            exit;
        }

        $this->render(
            'auth/login',
            [
                'title' => 'Login',
                'installed' => $this->request->input(
                    'installed'
                )
            ]
        );
    }

    public function login(): void
    {
        $username = trim(
            (string) $this->request->input(
                'username',
                ''
            )
        );

        $password = (string) $this->request->input(
            'password',
            ''
        );

        if (
            $this->authentication->attempt(
                $username,
                $password
            )
        ) {
            header(
                'Location: /public/dashboard'
            );

            exit;
        }

        $this->render(
            'auth/login',
            [
                'title' => 'Login',
                'error' => 'Invalid username or password.'
            ]
        );
    }

    public function logout(): void
    {
        $this->authentication->logout();

        header(
            'Location: /public/login'
        );

        exit;
    }
}