<?php

namespace App\Services\Support;

use Config\Database;

/**
 * Wraps sensitive writes with a before/after diff record in audit_logs.
 * Distinct from ActivityLogger (behavioral trail) — this is the compliance/
 * dispute-resolution trail. See 05-saas-architecture.md §10.
 *
 * Usage from a Service method:
 *   $this->audit->record($user->id, 'subscription', 'plan_change', $agencyId, $oldPlan, $newPlan);
 */
class AuditService
{
    public function record(
        ?int $userId,
        string $module,
        string $action,
        ?int $recordId,
        ?array $oldValue,
        ?array $newValue
    ): void {
        Database::connect()->table('audit_logs')->insert([
            'user_id'    => $userId,
            'module'     => $module,
            'action'     => $action,
            'record_id'  => $recordId,
            'old_value'  => $oldValue !== null ? json_encode($oldValue) : null,
            'new_value'  => $newValue !== null ? json_encode($newValue) : null,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
