<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Models\Account;
use App\Models\CustomerUser;
use App\Models\LoginAttempt;
use App\Models\Tenant;
use App\Services\PortalAccess;

final class AuthController extends BaseController
{
    public function showLogin(Request $request): void
    {
        if (Auth::instance()->check()) {
            redirect('home');
        }
        view('auth/login', ['title' => 'Sign in', 'error' => flash('error')], 'layouts/auth');
    }

    public function login(Request $request): void
    {
        $this->verifyCsrf($request);
        $email = strtolower((string) $request->input('email', ''));
        $password = (string) ($_POST['password'] ?? '');
        $ip = request_ip();
        $max = (int) config('security.login_max_attempts', 8);
        $window = (int) config('security.login_window_minutes', 15);

        if ($email === '' || $password === '') {
            flash('error', 'Enter your email and password.');
            redirect('login');
        }
        if (LoginAttempt::tooMany($email, $ip, $max, $window)) {
            flash('error', 'Too many sign-in tries. Wait a few minutes.');
            redirect('login');
        }

        $user = CustomerUser::findByEmail($email);
        $ok = $user && $user['status'] === 'active' && password_verify($password, $user['password_hash']);
        LoginAttempt::record($email, $ip, $ok);
        if (!$ok) {
            flash('error', 'Email or password is not correct.');
            redirect('login');
        }

        $tenant = Tenant::find((int) $user['tenant_id']);
        $account = Account::find((int) $user['account_id'], (int) $user['tenant_id']);
        if (!$tenant || !$account) {
            flash('error', 'This login is not linked to a company.');
            redirect('login');
        }
        if (!PortalAccess::portalOn((int) $tenant['id'])) {
            flash('error', 'The Customer Portal is not on for this company.');
            redirect('login');
        }

        CustomerUser::markLogin((int) $user['id']);
        Auth::instance()->login($user, $tenant, $account);
        redirect('home');
    }

    public function logout(Request $request): void
    {
        Auth::instance()->logout();
        redirect('login');
    }
}
