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

class AuditLog extends Model
{
    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO audit_logs (user_id, action, entity_type, entity_id, details_json, ip_address) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $data['user_id'] ?? null,
            $data['action'],
            $data['entity_type'],
            $data['entity_id'] ?? null,
            $data['details_json'] ?? null,
            $data['ip_address'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

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