<?php
namespace App\Services;

class AuthService {
    public function __construct(private \PDO $pdo) {}

    public function findActiveUserByEmail(string $email): ?array {
        $stmt = $this->pdo->prepare("SELECT u.*, r.slug AS role_slug, r.name AS role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.email = ? AND u.is_active = 1 LIMIT 1");
        $stmt->execute([$email]);
        return $stmt->fetch() ?: null;
    }

    public function recordSuccessfulLogin(int $userId): void {
        $this->pdo->prepare("UPDATE users SET last_login_at = NOW(), last_login_ip = ?, failed_login_attempts = 0, locked_until = NULL WHERE id = ?")
            ->execute([$_SERVER['REMOTE_ADDR'] ?? '', $userId]);
    }

    public function recordFailedLogin(array $user): void {
        $attempts = ((int)($user['failed_login_attempts'] ?? 0)) + 1;
        $lockUntil = $attempts >= 5 ? date('Y-m-d H:i:s', time() + 900) : null;
        $this->pdo->prepare("UPDATE users SET failed_login_attempts = ?, locked_until = ? WHERE id = ?")
            ->execute([$attempts, $lockUntil, $user['id']]);
    }
}
