<?php
require_once __DIR__ . '/../Core.php';

class LoginHistory extends Model
{
    public function record(?int $userId, string $email, string $status, ?string $message = null): void
    {
        $stmt = $this->db->prepare('INSERT INTO login_history (user_id, email, status, message, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([$userId, $email, $status, $message, client_ip(), substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''),0,255)]);
    }

    public function recent(int $limit = 25): array
    {
        $stmt = $this->db->prepare('SELECT lh.*, u.name AS user_name FROM login_history lh LEFT JOIN users u ON u.id = lh.user_id ORDER BY lh.created_at DESC LIMIT ?');
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
