<?php

declare(strict_types=1);

namespace FormConnector\Features\UTM;

use FormConnector\Core\Settings\Settings;

/**
 * UTM Tracker
 * 
 * Enqueues the frontend JavaScript that captures UTM parameters
 * from URLs and stores them in cookies for form submission attribution.
 */
class UTMTracker {

    /**
     * Singleton instance
     */
    private static ?UTMTracker $instance = null;

    /**
     * Get singleton instance
     */
    public static function get_instance(): self {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Initialize the tracker
     */
    public function init(): void {
        // Only load on frontend, not admin
        if (is_admin()) {
            return;
        }

        add_action('wp_enqueue_scripts', [$this, 'maybe_enqueue_script']);
    }

    /**
     * Enqueue UTM tracking script if enabled
     */
    public function maybe_enqueue_script(): void {
        $settings = Settings::get_instance();

        // Only enqueue if UTM tracking is enabled
        if (!$settings->is_utm_enabled()) {
            if ($settings->is_logging_enabled()) {
                error_log('[FormConnector] UTM tracker script NOT enqueued — UTM tracking is disabled in settings. Raw setting value: ' . var_export($settings->get('utm_tracking_enabled'), true));
            }
            return;
        }

        $utm_settings = $settings->get_utm_settings();

        // Enqueue the UTM tracker script
        wp_enqueue_script(
            'fc-utm-tracker',
            FC_PLUGIN_URL . 'assets/js/utm-tracker.js',
            [],
            FC_VERSION,
            [
                'in_footer' => false, // Load in header to capture params early
                'strategy'  => 'defer',
            ]
        );

        // Pass configuration to the script
        wp_add_inline_script(
            'fc-utm-tracker',
            'window.fcUtmConfig = ' . wp_json_encode([
                'cookieDuration'  => (int) $utm_settings['cookie_duration'],
                'attributionMode' => $utm_settings['attribution_mode'],
                'debug'           => defined('WP_DEBUG') && WP_DEBUG,
            ]) . ';',
            'before'
        );

        if ($settings->is_logging_enabled()) {
            error_log('[FormConnector] UTM tracker script enqueued. URL: ' . FC_PLUGIN_URL . 'assets/js/utm-tracker.js v' . FC_VERSION);
        }
    }

}
