<?php
/**
 * ErrorCapture - Drop-in PHP error reporter
 *
 * Include this file at the top of your application to capture
 * errors, warnings, and fatals and POST them to a remote endpoint.
 *
 * Usage: require_once 'errorcapture.php';
 */

// ── Configuration ──────────────────────────────────────────────
define('ERRORCAPTURE_ENDPOINT', 'https://your-endpoint.com/api.php');
define('ERRORCAPTURE_HASH', '');            // your project hash from the dashboard
define('ERRORCAPTURE_API_KEY', '');          // optional, sent as Bearer token
define('ERRORCAPTURE_TIMEOUT', 2);          // HTTP timeout in seconds
// ───────────────────────────────────────────────────────────────

(function () {
    $errorNames = [
        E_ERROR             => 'Fatal Error',
        E_WARNING           => 'Warning',
        E_PARSE             => 'Parse Error',
        E_NOTICE            => 'Notice',
        E_CORE_ERROR        => 'Core Error',
        E_CORE_WARNING      => 'Core Warning',
        E_COMPILE_ERROR     => 'Compile Error',
        E_COMPILE_WARNING   => 'Compile Warning',
        E_USER_ERROR        => 'User Error',
        E_USER_WARNING      => 'User Warning',
        E_USER_NOTICE       => 'User Notice',
        E_STRICT            => 'Strict',
        E_RECOVERABLE_ERROR => 'Recoverable Error',
        E_DEPRECATED        => 'Deprecated',
        E_USER_DEPRECATED   => 'User Deprecated',
    ];

    $send = function (array $payload) {
        $json = json_encode($payload);

        $headers = ['Content-Type: application/json'];
        if (ERRORCAPTURE_API_KEY !== '') {
            $headers[] = 'Authorization: Bearer ' . ERRORCAPTURE_API_KEY;
        }

        $ch = curl_init(ERRORCAPTURE_ENDPOINT);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $json,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => ERRORCAPTURE_TIMEOUT,
            CURLOPT_CONNECTTIMEOUT => ERRORCAPTURE_TIMEOUT,
        ]);
        curl_exec($ch);
        curl_close($ch);
    };

    $buildPayload = function (string $level, string $message, string $file, int $line) use ($errorNames) {
        $payload = [
            'hash'      => ERRORCAPTURE_HASH,
            'level'     => $level,
            'message'   => $message,
            'file'      => $file,
            'line'      => $line,
            'timestamp' => gmdate('c'),
            'hostname'  => gethostname(),
        ];

        // Request context (safe for dev use)
        if (php_sapi_name() !== 'cli') {
            $payload['request'] = [
                'method' => $_SERVER['REQUEST_METHOD'] ?? null,
                'url'    => ($_SERVER['REQUEST_SCHEME'] ?? 'http') . '://'
                            . ($_SERVER['HTTP_HOST'] ?? 'unknown')
                            . ($_SERVER['REQUEST_URI'] ?? ''),
                'get'    => $_GET ?: null,
                'post'   => $_POST ?: null,
            ];
        } else {
            $payload['cli'] = [
                'argv' => $_SERVER['argv'] ?? [],
            ];
        }

        return $payload;
    };

    // Capture warnings, notices, deprecations, etc.
    set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) use ($errorNames, $send, $buildPayload) {
        // Respect the error_reporting level (handles @ suppression too)
        if (!(error_reporting() & $errno)) {
            return false;
        }

        $level = $errorNames[$errno] ?? "Unknown ($errno)";
        $send($buildPayload($level, $errstr, $errfile, $errline));

        return false; // Let PHP's default handler run too
    });

    // Capture fatal errors on shutdown
    register_shutdown_function(function () use ($errorNames, $send, $buildPayload) {
        $error = error_get_last();
        if (!$error) {
            return;
        }

        $fatal = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR];
        if (!in_array($error['type'], $fatal, true)) {
            return;
        }

        $level = $errorNames[$error['type']] ?? 'Fatal Error';
        $send($buildPayload($level, $error['message'], $error['file'], $error['line']));
    });

    // Expose custom logging function
    $GLOBALS['__errorcapture_send'] = $send;
    $GLOBALS['__errorcapture_build'] = $buildPayload;
})();

/**
 * Log a custom message to ErrorCapture.
 *
 * Usage: errorcapture_log('User signed up successfully');
 */
function errorcapture_log(string $message): void
{
    $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
    $payload = ($GLOBALS['__errorcapture_build'])(
        'Custom',
        $message,
        $trace['file'] ?? '',
        (int) ($trace['line'] ?? 0)
    );
    ($GLOBALS['__errorcapture_send'])($payload);
}
