<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\SEO;

if (! defined('ABSPATH')) exit;

final class MeasurementBridge
{
    public function boot(): void
    {
        add_action('wp_enqueue_scripts', [$this, 'assets'], 95);
        add_action('wp_ajax_nopriv_h4bs_measure', [$this, 'collect']);
        add_action('wp_ajax_h4bs_measure', [$this, 'collect']);
    }

    public function assets(): void
    {
        if (is_admin() || ! is_singular()) return;
        $postId = get_queried_object_id();
        wp_enqueue_script('h4bs-measurement', H4BS_URL . 'assets/js/measurement.js', [], H4BS_VERSION, ['in_footer' => true, 'strategy' => 'defer']);
        wp_localize_script('h4bs-measurement', 'h4bsMeasurement', [
            'endpoint' => admin_url('admin-ajax.php'),
            'postId' => $postId,
            'eventName' => sanitize_key((string) get_post_meta($postId, '_h4_seo_analytics_event', true)),
            'consentCookie' => (string) apply_filters('h4bs_measurement_consent_cookie', 'h4bs_analytics_consent'),
            'rumEnabled' => (bool) apply_filters('h4bs_first_party_rum_enabled', false),
            'nonce' => wp_create_nonce('h4bs_measure'),
        ]);
    }

    public function collect(): void
    {
        if (! apply_filters('h4bs_first_party_rum_enabled', false)) wp_send_json_error(['message'=>'disabled'], 403);
        check_ajax_referer('h4bs_measure', 'nonce');
        $cookie = sanitize_key((string) apply_filters('h4bs_measurement_consent_cookie', 'h4bs_analytics_consent'));
        $consent = $cookie !== '' && isset($_COOKIE[$cookie]) ? sanitize_text_field(wp_unslash((string) $_COOKIE[$cookie])) : '';
        if ($cookie === '' || $consent !== '1') wp_send_json_error(['message'=>'consent_required'], 403);
        $metric = sanitize_key((string) wp_unslash($_POST['metric'] ?? ''));
        if (! in_array($metric, ['lcp','cls','inp','conversion'], true)) wp_send_json_error(['message'=>'invalid_metric'], 422);
        $value = max(0, min(600000, (float) sanitize_text_field(wp_unslash($_POST['value'] ?? '0'))));
        $postId = absint(wp_unslash($_POST['post_id'] ?? '0'));
        do_action('h4bs_first_party_measurement', ['metric'=>$metric,'value'=>$value,'post_id'=>$postId,'event'=>sanitize_key((string) wp_unslash($_POST['event'] ?? ''))]);
        wp_send_json_success(['accepted'=>true]);
    }
}
