<?php

declare(strict_types=1);

namespace App\Controllers\PlatformAdmin;

use App\Core\BaseController;
use App\Core\PlatformAuth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;

final class PlatformAuthController extends BaseController
{
    public function showLoginForm(Request $request): Response
    {
        if (PlatformAuth::check()) {
            return $this->redirect('platform/companies');
        }

        return $this->view('platform/login', ['title' => 'Platform Admin'], useLayout: false);
    }

    public function login(Request $request): Response
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->withErrors($request, $validator->errors(), 'platform/login');
        }

        $data = $validator->validated();

        if (!PlatformAuth::attempt($data['email'], $data['password'])) {
            return $this->withErrors($request, ['email' => 'Incorrect email or password.'], 'platform/login');
        }

        return $this->redirect('platform/companies');
    }

    public function logout(Request $request): Response
    {
        PlatformAuth::logout();

        return $this->redirect('platform/login');
    }
}
