<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Middleware\AuthMiddleware;
use App\Services\ApiService;
use App\Services\AuthService;

/**
 * Login / logout controller.
 */
final class AuthController
{
    private AuthService $auth;
    private AuthMiddleware $middleware;

    public function __construct(?AuthService $auth = null)
    {
        $api = ApiService::instance();
        $this->auth = $auth ?? new AuthService($api);
        $this->middleware = new AuthMiddleware($this->auth);
    }

    public function showLoginForm(): void
    {
        $this->middleware->requireGuest();

        $error = $this->auth->lastError();
        $action = function_exists('app_path') ? app_path('/admin/login/') : '/admin/login/';

        require dirname(__DIR__) . '/views/auth/login.php';
    }

    public function login(): void
    {
        $this->middleware->requireGuest();

        // Accept "email" field only (Karvi Partner API request body).
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');

        $result = $this->auth->login($email, $password);

        if ($result->success) {
            redirect('/admin/dashboard/');
        }

        $error = $result->message;
        $action = function_exists('app_path') ? app_path('/admin/login/') : '/admin/login/';

        require dirname(__DIR__) . '/views/auth/login.php';
    }

    public function logout(): void
    {
        $this->auth->logout();
        redirect('/admin/login/');
    }
}
