<?php
class AuditLog {
    public static function log(
        string  $action,
        ?string $objectType = null,
        ?int    $objectId   = null,
        ?string $details    = null
    ): void {
        $ip = $_SERVER['REMOTE_ADDR'] ?? null;
        Database::get()->prepare(
            'INSERT INTO app_audit_log
             (user_id, username, action, object_type, object_id, details, ip_address)
             VALUES (?, ?, ?, ?, ?, ?, ?)'
        )->execute([
            Auth::currentUserId(),
            Auth::currentUsername(),
            $action,
            $objectType,
            $objectId,
            $details,
            $ip,
        ]);
    }

    public static function getRecent(int $limit = 100, int $offset = 0): array {
        $stmt = Database::get()->prepare(
            'SELECT * FROM app_audit_log ORDER BY created_at DESC LIMIT ? OFFSET ?'
        );
        $stmt->execute([$limit, $offset]);
        return $stmt->fetchAll();
    }

    public static function count(): int {
        return (int)Database::get()->query('SELECT COUNT(*) FROM app_audit_log')->fetchColumn();
    }
}
