<?php

declare(strict_types=1);

namespace App\Modules\Administration\Controllers;

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

final class InstallController extends Controller
{
    public function __construct(
        private InstallService $installService,
        private Request $request,
        View $view
    ) {
        parent::__construct($view);
    }

    public function index(): void
    {
        if ($this->installService->installed()) {
            header(
                'Location: /public/login'
            );

            exit;
        }

        $this->render(
            'install/index',
            [
                'title' => 'System Installation'
            ]
        );
    }

    public function createAdmin(): void
    {
        if ($this->installService->installed()) {
            header(
                'Location: /public/login'
            );

            exit;
        }

        $this->render(
            'install/create_admin',
            [
                'title' => 'Create Administrator'
            ]
        );
    }

    public function storeAdmin(): void
    {
        try {
            $password = (string) $this->request->input(
                'password',
                ''
            );

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

            if ($password !== $confirmation) {
                throw new \RuntimeException(
                    'Password confirmation does not match.'
                );
            }

            $this->installService->createAdministrator(
                trim(
                    (string) $this->request->input(
                        'full_name',
                        ''
                    )
                ),
                trim(
                    (string) $this->request->input(
                        'username',
                        ''
                    )
                ),
                trim(
                    (string) $this->request->input(
                        'email',
                        ''
                    )
                ),
                $password
            );

            header(
                'Location: /public/login?installed=1'
            );

            exit;

        } catch (\Throwable $exception) {

            $this->render(
                'install/create_admin',
                [
                    'title' => 'Create Administrator',
                    'error' => $exception->getMessage()
                ]
            );
        }
    }
}