<?php

namespace App\Core;

class AuditLog
{
    public static function record(
        string $actorType,
        int $actorId,
        string $actorName,
        string $entityType,
        string $entityId,
        string $action,
        ?array $before = null,
        ?array $after = null,
        string $ip = ''
    ): void {
        try {
            $db = Database::connection();
            $stmt = $db->prepare(
                "INSERT INTO audit_log (actor_type, actor_id, actor_name, entity_type, entity_id, action, before_data, after_data, ip)
                 VALUES (:actor_type, :actor_id, :actor_name, :entity_type, :entity_id, :action, :before_data, :after_data, :ip)"
            );
            $stmt->execute([
                'actor_type'  => $actorType,
                'actor_id'    => $actorId,
                'actor_name'  => $actorName,
                'entity_type' => $entityType,
                'entity_id'   => $entityId,
                'action'      => $action,
                'before_data' => $before ? json_encode($before) : null,
                'after_data'  => $after ? json_encode($after) : null,
                'ip'          => $ip ?: ($_SERVER['REMOTE_ADDR'] ?? ''),
            ]);
        } catch (\Throwable $e) {
            error_log('AuditLog failed: ' . $e->getMessage());
        }
    }
}
