<?php
/**
 * Audit Logger — Records all important actions for compliance and debugging.
 * 
 * Usage:
 *   AuditLogger::log('invoice.approved', 'invoice', $invoiceId, $oldData, $newData, $decoded);
 *   AuditLogger::log('user.login', 'user', $userId, decoded: $decoded);
 */

declare(strict_types=1);

namespace App\Core;

final class AuditLogger
{
    /**
     * Log an audit event.
     *
     * @param string      $action     e.g. 'invoice.approved', 'user.created', 'company.deleted'
     * @param string|null $entityType e.g. 'invoice', 'user', 'company'
     * @param string|null $entityId   UUID of the affected entity
     * @param array|null  $oldData    Previous state (for updates/deletes)
     * @param array|null  $newData    New state (for creates/updates)
     * @param array|null  $decoded    JWT decoded payload (to extract user_id, tenant_id)
     */
    public static function log(
        string  $action,
        ?string $entityType = null,
        ?string $entityId = null,
        ?array  $oldData = null,
        ?array  $newData = null,
        ?array  $decoded = null
    ): void {
        try {
            $db = Database::getInstance();

            $tenantId  = $decoded['tenant_id'] ?? null;
            $userId    = $decoded['user_id'] ?? null;
            $ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
            $userAgent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500);

            $stmt = $db->prepare("
                INSERT INTO audit_logs (id, tenant_id, user_id, action, entity_type, entity_id, old_data, new_data, ip_address, user_agent)
                VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $tenantId,
                $userId,
                $action,
                $entityType,
                $entityId,
                $oldData ? json_encode($oldData, JSON_UNESCAPED_UNICODE) : null,
                $newData ? json_encode($newData, JSON_UNESCAPED_UNICODE) : null,
                $ipAddress,
                $userAgent,
            ]);
        } catch (\Exception $e) {
            // Audit logging should NEVER crash the main request
            error_log("[AuditLogger] Failed to log action '{$action}': " . $e->getMessage());
        }
    }
}
