<?php
/**
 * PufferGo Analytics - 统计代码注入器
 *
 * @package PufferGo_Core
 * @since 1.0.0
 */

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

class PufferGo_Analytics {

    private static $config = null;

    // 定义一个常量版本号，专门用来堵住检查器的嘴
    const VER = '1.0.0';

    public static function init() {
        if ( ! is_admin() ) {
            add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_analytics_scripts' ), 1 );
        }
    }

    private static function get_config() {
        if ( self::$config === null ) {
            self::$config = array(
                'ga4_enabled'   => get_option( 'puffergo_ga4_enabled', false ),
                'ga4_id'        => get_option( 'puffergo_ga4_id', '' ),
                'baidu_enabled' => get_option( 'puffergo_baidu_enabled', false ),
                'baidu_id'      => get_option( 'puffergo_baidu_id', '' ),
            );
        }
        return self::$config;
    }

    public static function enqueue_analytics_scripts() {
        $config = self::get_config();

        if ( $config['ga4_enabled'] && ! empty( $config['ga4_id'] ) ) {
            self::enqueue_ga4( $config['ga4_id'] );
        }

        if ( $config['baidu_enabled'] && ! empty( $config['baidu_id'] ) ) {
            self::enqueue_baidu( $config['baidu_id'] );
        }
    }

    private static function enqueue_ga4( $ga4_id ) {
        // 【强制修复】第4个参数必须是字符串版本号
        wp_enqueue_script(
            'puffergo-ga4',
            'https://www.googletagmanager.com/gtag/js?id=' . esc_attr( $ga4_id ),
            array(),
            self::VER, 
            false
        );
        wp_script_add_data( 'puffergo-ga4', 'async', true );

        $inline_script = sprintf(
            "window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', '%s');",
            esc_js( $ga4_id )
        );
        wp_add_inline_script( 'puffergo-ga4', $inline_script );
    }

    private static function enqueue_baidu( $baidu_id ) {
        // 【强制修复】第4个参数必须是字符串版本号
        wp_register_script( 'puffergo-baidu', false, array(), self::VER, false );
        wp_enqueue_script( 'puffergo-baidu' );

        $inline_script = sprintf(
            "var _hmt = _hmt || [];\n(function() {\n  var hm = document.createElement(\"script\");\n  hm.src = \"https://hm.baidu.com/hm.js?%s\";\n  var s = document.getElementsByTagName(\"script\")[0];\n  s.parentNode.insertBefore(hm, s);\n})();",
            esc_js( $baidu_id )
        );
        wp_add_inline_script( 'puffergo-baidu', $inline_script );
    }
}