<?php
if (!defined('ABSPATH')) exit;

/**
 * Lightweight error reporting to WebAbility's self-hosted GlitchTip
 * (Sentry-API compatible). No SDK — a single minimal "store" POST.
 *
 * Privacy: sends ONLY diagnostic context — site host, plugin/WP/PHP version,
 * a failure type and (truncated) error message. NEVER the statement content,
 * user data, nonces, or credentials. Disable with:
 *   define('WEBABILITY_ACWG_DISABLE_REPORTING', true);
 * or: add_filter('webability_acwg_error_reporting_enabled', '__return_false');
 */

if (!defined('WEBABILITY_ACWG_GLITCHTIP_DSN')) {
    define('WEBABILITY_ACWG_GLITCHTIP_DSN', 'https://2bde226c8cb2470d8afc0c92ba219d20@glitchtip-d6xoleppxxckdnfnq8xxlvxg.server.techywebsolutions.com/4');
}

function webability_acwg_reporting_enabled() {
    if (defined('WEBABILITY_ACWG_DISABLE_REPORTING') && WEBABILITY_ACWG_DISABLE_REPORTING) {
        return false;
    }
    return (bool) apply_filters('webability_acwg_error_reporting_enabled', true);
}

function webability_acwg_parse_dsn($dsn) {
    $p = wp_parse_url($dsn);
    if (empty($p['host']) || empty($p['user']) || empty($p['path'])) {
        return false;
    }
    $scheme  = isset($p['scheme']) ? $p['scheme'] : 'https';
    $port    = isset($p['port']) ? ':' . $p['port'] : '';
    $project = ltrim($p['path'], '/');
    return array(
        'key'       => $p['user'],
        'project'   => $project,
        'store'     => "$scheme://{$p['host']}$port/api/$project/store/",
        'host'      => "$scheme://{$p['host']}$port",
    );
}

/**
 * The DSN's public key + store URL, for handing to the browser so client-side
 * failures (the common case: stale nonce, WAF block) report directly.
 */
function webability_acwg_reporter_config() {
    $dsn = webability_acwg_parse_dsn(WEBABILITY_ACWG_GLITCHTIP_DSN);
    if (!$dsn || !webability_acwg_reporting_enabled()) {
        return array('enabled' => false);
    }
    return array(
        'enabled' => true,
        'url'     => $dsn['store'] . '?sentry_key=' . rawurlencode($dsn['key']),
        'release' => defined('WEBABILITY_WIDGET_VERSION') ? WEBABILITY_WIDGET_VERSION : 'unknown',
    );
}

/**
 * Report a diagnostic event server-side (non-blocking, 2s cap — never delays
 * the admin response).
 *
 * @param string $message Short, low-cardinality summary (becomes the issue title).
 * @param string $level   error|warning|info
 * @param array  $extra   Extra context. Caller must NOT include PII.
 */
function webability_acwg_report($message, $level = 'error', $extra = array()) {
    if (!webability_acwg_reporting_enabled()) {
        return;
    }
    $dsn = webability_acwg_parse_dsn(WEBABILITY_ACWG_GLITCHTIP_DSN);
    if (!$dsn) {
        return;
    }

    $version = defined('WEBABILITY_WIDGET_VERSION') ? WEBABILITY_WIDGET_VERSION : 'unknown';
    $host    = wp_parse_url(home_url(), PHP_URL_HOST);

    $event = array(
        'event_id'    => str_replace('-', '', wp_generate_uuid4()),
        'timestamp'   => gmdate('Y-m-d\TH:i:s\Z'),
        'platform'    => 'php',
        'level'       => $level,
        'logger'      => 'webability-wp-plugin',
        'release'     => $version,
        'server_name' => $host,
        'message'     => $message,
        'tags'        => array(
            'plugin_version' => $version,
            'wp_version'     => get_bloginfo('version'),
            'php_version'    => PHP_VERSION,
            'site_host'      => $host,
        ),
        'extra'       => $extra,
    );

    $auth = 'Sentry sentry_version=7, sentry_client=webability-wp/' . $version . ', sentry_key=' . $dsn['key'];

    wp_remote_post($dsn['store'], array(
        'timeout'  => 2,
        'blocking' => false,
        'headers'  => array(
            'Content-Type'   => 'application/json',
            'X-Sentry-Auth'  => $auth,
        ),
        'body'     => wp_json_encode($event),
    ));
}
