<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Services\LoginThrottleService;

final class AuthController
{
    public function login(): void
    {
        if (Session::has('user')) {
            Response::redirect('/admin/dashboard');
            return;
        }

        $error = null;

        if (Request::isPost()) {
            Csrf::verify();

            $username = trim((string) Request::post('username', ''));
            $password = (string) Request::post('password', '');

            $pdo = DB::pdo();
            $throttle = new LoginThrottleService($pdo);
            $ipAddress = (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown');

            try {
                $throttle->assertNotLocked($username, $ipAddress);

                $statement = $pdo->prepare('SELECT * FROM users WHERE username = ? AND is_active = 1 LIMIT 1');
                $statement->execute([$username]);
                $user = $statement->fetch();

                if ($user && password_verify($password, (string) ($user['password_hash'] ?? ''))) {
                    $throttle->clear($username, $ipAddress);
                    Auth::login($user);
                    audit_log('LOGIN_SUCCESS', 'users', (int) $user['id'], ['username' => $username]);
                    Response::flash('success', 'تم تسجيل الدخول بنجاح');
                    Response::redirect(Auth::pullIntendedUrl('/admin/dashboard'));
                    return;
                }

                $throttle->recordFailure($username, $ipAddress);
                audit_log('LOGIN_FAIL', 'users', null, ['username' => $username, 'ip' => $ipAddress]);
                $error = 'بيانات الدخول غير صحيحة';
            } catch (\RuntimeException $e) {
                audit_log('LOGIN_BLOCKED', 'users', null, ['username' => $username, 'ip' => $ipAddress]);
                $error = $e->getMessage();
            }
        }

        Response::view('pages/login', [
            'error' => $error,
            'company' => company_profile(DB::pdo()),
        ]);
    }

    public function logout(): void
    {
        Auth::logout();
        Response::redirect('/login');
    }
}
