<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Models\Tenant;
use App\Models\User;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class LoginController extends Controller
{
    public function middleware(): array
    {
        return [];
    }

    public function index(): void
    {
        if (Session::check()) {
            redirect('/Home');
        }
        $this->view->setLayout('blank');
        $this->render('login/index', [
            'csrf'    => Tool::generateCsrf(),
            'msg'     => Session::flash('login_msg'),
            'error'   => Session::flash('login_error'),
            'tenants' => Tenant::activeForLogin(),
        ]);
    }

    public function authenticate(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            redirect('/Login');
        }
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('login_error', 'Session expired. Please try again.');
            redirect('/Login');
        }

        $tenantId = (int) ($_POST['tenant_id'] ?? 0);
        $username = trim((string) ($_POST['username'] ?? ''));
        $password = (string) ($_POST['password'] ?? '');

        if ($tenantId <= 0 || $username === '' || $password === '') {
            Session::flash('login_error', 'Company, username, and password are required.');
            redirect('/Login');
        }

        $tenant = Tenant::findById($tenantId);
        if (!$tenant || $tenant['status'] !== 'active') {
            Session::flash('login_error', 'Company is not available.');
            redirect('/Login');
        }

        $user = User::verify($tenantId, $username, $password);
        if (!$user) {
            Session::flash('login_error', 'Wrong username or password.');
            redirect('/Login');
        }

        Session::login($user, []);
        redirect('/Home');
    }
}
