<?php

namespace Licenzo\Services\Logging\Concerns;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Throwable;

/**
 * Trait HandlesErrors
 *
 * Handles errors silently to prevent logging from breaking application flow
 */
trait HandlesErrors
{
    /**
     * Handle error silently with logging
     *
     * @param Throwable $e
     * @param string $context
     * @return void
     */
    protected static function handleError(Throwable $e, string $context): void
    {
        // Log to WordPress error log
        $message = sprintf(
            '[Licenzo Logging] %s: %s in %s:%d',
            $context,
            $e->getMessage(),
            $e->getFile(),
            $e->getLine()
        );

        // Fire WordPress action for custom error handling
        do_action('licenzo_logging_error', $e, $context, $message);
    }

    /**
     * Execute callback with error handling
     *
     * @param callable $callback
     * @param string $context
     * @return mixed|null
     */
    protected static function safeExecute(callable $callback, string $context)
    {
        try {
            return $callback();
        } catch (Throwable $e) {
            static::handleError($e, $context);
            return null;
        }
    }
}

