<?php

declare(strict_types=1);

namespace OnoxWhmcs;

/**
 * Structured error logging for the Onoxsoft WHMCS module.
 *
 * Writes to WHMCS module log (visible in Admin → Utilities → Logs → Module Log)
 * using the native logModuleCall() function provided by WHMCS.
 */
class ErrorHandler
{
    /**
     * Log a caught exception with contextual WHMCS server info.
     *
     * @param  string  $action  Human-readable action name (e.g. 'CreateAccount')
     * @param  array  $params  WHMCS module params (serverhostname, serviceid, …)
     * @param  \Throwable  $e  The exception
     */
    public static function log(string $action, array $params, \Throwable $e): void
    {
        $host = $params['serverhostname'] ?? 'unknown';
        $serviceId = $params['serviceid'] ?? 'n/a';

        $context = [
            'action' => $action,
            'host' => $host,
            'service_id' => $serviceId,
            'exception' => get_class($e),
            'message' => $e->getMessage(),
            'file' => basename($e->getFile()).':'.$e->getLine(),
        ];

        // logModuleCall() is a global WHMCS function available in all module contexts.
        if (function_exists('logModuleCall')) {
            logModuleCall(
                'onox',
                $action,
                json_encode(['host' => $host, 'service_id' => $serviceId]),
                'ERROR: '.$e->getMessage(),
                json_encode($context),
                [$params['serverpassword'] ?? ''] // mask API token in logs
            );
        }

        // Also write to PHP error log as a fallback
        error_log('[Onoxsoft WHMCS] '.$action.' failed: '.$e->getMessage());
    }

    /**
     * Log a successful API call (optional; useful during setup/testing).
     *
     * @param  mixed  $response  Parsed API response
     */
    public static function logSuccess(string $action, array $params, $response = null): void
    {
        if (! function_exists('logModuleCall')) {
            return;
        }

        logModuleCall(
            'onox',
            $action,
            json_encode(['host' => $params['serverhostname'] ?? '', 'service_id' => $params['serviceid'] ?? '']),
            json_encode($response),
            '',
            [$params['serverpassword'] ?? '']
        );
    }
}
