<?php
require_once __DIR__ . '/../config/db.php';

class AuditLog
{
    public static function log($userId, string $action, $details = null): void
    {
        $uid = $userId !== null ? (int)$userId : null;

        $detailsText = null;
        if (is_array($details) || is_object($details)) {
            $detailsText = json_encode($details, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        } elseif (is_string($details)) {
            $trim = trim($details);
            $detailsText = ($trim === '') ? null : $trim;
        }

        $stmt = db()->prepare("
            INSERT INTO audit_logs (user_id, action, details, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->execute([$uid, $action, $detailsText]);
    }

    public static function recent(int $limit = 200): array
    {
        $limit = max(1, min($limit, 1000));
        $stmt = db()->query("
            SELECT a.*, u.full_name, u.email
            FROM audit_logs a
            LEFT JOIN users u ON u.id = a.user_id
            ORDER BY a.created_at DESC, a.id DESC
            LIMIT {$limit}
        ");
        return $stmt->fetchAll();
    }
}
