<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

final class AuditService
{
    // Safe flexible logger: never breaks the app
    public static function log($entityType = null, $entityId = null, $action = null, $message = null, $userId = null, $meta = null): void
    {
        try {
            $db = Database::getInstance();

            $actorId = null;
            if (is_int($userId)) $actorId = $userId;
            elseif (is_string($userId) && ctype_digit($userId)) $actorId = (int)$userId;
            elseif (is_array($userId)) {
                if (isset($userId['id']) && (is_int($userId['id']) || (is_string($userId['id']) && ctype_digit($userId['id'])))) $actorId = (int)$userId['id'];
            } elseif (is_object($userId) && isset($userId->id) && (is_int($userId->id) || (is_string($userId->id) && ctype_digit($userId->id)))) {
                $actorId = (int)$userId->id;
            } elseif (function_exists('auth_id') && auth_id()) {
                $actorId = (int)auth_id();
            }

            $actorEmail = null;
            if ($actorId) {
                $st = $db->prepare("SELECT email FROM users WHERE id=:id LIMIT 1");
                $st->execute([':id'=>$actorId]);
                $actorEmail = (string)($st->fetchColumn() ?: '');
            }

            $metaJson = null;
            if (is_array($meta) || is_object($meta)) $metaJson = json_encode($meta, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            elseif (is_string($meta) && $meta !== '') $metaJson = $meta;

            $st = $db->prepare("
              INSERT INTO audit_logs(actor_user_id, actor_email, action, entity_type, entity_id, message, ip_address, user_agent, meta_json)
              VALUES(:uid,:email,:action,:etype,:eid,:msg,:ip,:ua,:meta)
            ");
            $st->execute([
                ':uid'   => $actorId ?: null,
                ':email' => $actorEmail ?: null,
                ':action'=> ($action===null?null:(string)$action),
                ':etype' => ($entityType===null?null:(string)$entityType),
                ':eid'   => ($entityId===null?null:(string)$entityId),
                ':msg'   => ($message===null?null:(string)$message),
                ':ip'    => ($_SERVER['REMOTE_ADDR'] ?? null),
                ':ua'    => ($_SERVER['HTTP_USER_AGENT'] ?? null),
                ':meta'  => $metaJson,
            ]);
        } catch (\Throwable $e) {
            // never break app
        }
    }
}
