<?php
/**
 * Name: Tracking Codes Manager
 * Description: Easy setup for Google Analytics, Meta Pixel, Google Tag Manager, and other tracking codes with position control for header, footer, or body placement
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * WhereToFind: {
 *   "location": "Page Source",
 *   "url": "/",
 *   "instructions": "View page source (Ctrl+U / Cmd+U) to see tracking codes in <head>",
 *   "newTab": true
 * }
 * Added: 2025-07-20
 * Tags: tracking, analytics, google, meta, facebook, pixel, gtag, ga4
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardTrackingCodesManager {

    public function __construct() {
        add_action('wp_head', [$this, 'add_head_codes'], 1);
        add_action('wp_body_open', [$this, 'add_body_codes']);
        add_action('wp_footer', [$this, 'add_footer_codes']);
    }

    public function add_head_codes() {
        $settings = get_option('switchboard_tracking-codes-manager_settings', []);

        // Google Analytics 4
        if (!empty($settings['ga4_id'])) {
            $ga4_id = esc_attr($settings['ga4_id']);
            echo "\n<!-- Google Analytics 4 -->\n";
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped -- External tracking scripts require raw output
            echo "<script async src=\"https://www.googletagmanager.com/gtag/js?id={$ga4_id}\"></script>\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "<script>\n";
            echo "window.dataLayer = window.dataLayer || [];\n";
            echo "function gtag(){dataLayer.push(arguments);}\n";
            echo "gtag('js', new Date());\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "gtag('config', '{$ga4_id}');\n";
            echo "</script>\n";
        }

        // Google Tag Manager
        if (!empty($settings['gtm_id'])) {
            $gtm_id = esc_attr($settings['gtm_id']);
            echo "\n<!-- Google Tag Manager -->\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n";
            echo "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n";
            echo "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n";
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- External tracking scripts
            echo "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "})(window,document,'script','dataLayer','{$gtm_id}');</script>\n";
        }

        // Meta Pixel (Facebook Pixel)
        if (!empty($settings['meta_pixel_id'])) {
            $pixel_id = esc_attr($settings['meta_pixel_id']);
            echo "\n<!-- Meta Pixel Code -->\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "<script>\n";
            echo "!function(f,b,e,v,n,t,s)\n";
            echo "{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\n";
            echo "n.callMethod.apply(n,arguments):n.queue.push(arguments)};\n";
            echo "if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\n";
            echo "n.queue=[];t=b.createElement(e);t.async=!0;\n";
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- External tracking scripts
            echo "t.src=v;s=b.getElementsByTagName(e)[0];\n";
            echo "s.parentNode.insertBefore(t,s)}(window, document,'script',\n";
            echo "'https://connect.facebook.net/en_US/fbevents.js');\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "fbq('init', '{$pixel_id}');\n";
            echo "fbq('track', 'PageView');\n";
            echo "</script>\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- User-configured tracking code requires raw output
            echo "<noscript><img height=\"1\" width=\"1\" style=\"display:none\"\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- User-configured tracking code requires raw output
            echo "src=\"https://www.facebook.com/tr?id={$pixel_id}&ev=PageView&noscript=1\"\n";
            echo "/></noscript>\n";
        }

        // Google Ads Conversion
        if (!empty($settings['google_ads_id'])) {
            $ads_id = esc_attr($settings['google_ads_id']);
            echo "\n<!-- Google Ads -->\n";
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped -- External tracking scripts require raw output
            echo "<script async src=\"https://www.googletagmanager.com/gtag/js?id={$ads_id}\"></script>\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "<script>\n";
            echo "window.dataLayer = window.dataLayer || [];\n";
            echo "function gtag(){dataLayer.push(arguments);}\n";
            echo "gtag('js', new Date());\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "gtag('config', '{$ads_id}');\n";
            echo "</script>\n";
        }
    }

    public function add_body_codes() {
        $settings = get_option('switchboard_tracking-codes-manager_settings', []);

        // Google Tag Manager (noscript)
        if (!empty($settings['gtm_id'])) {
            $gtm_id = esc_attr($settings['gtm_id']);
            echo "\n<!-- Google Tag Manager (noscript) -->\n";
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Tracking code output
            echo "<noscript><iframe src=\"https://www.googletagmanager.com/ns.html?id={$gtm_id}\"\n";
            echo "height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>\n";
        }
    }

    public function add_footer_codes() {
        // Reserved for future use
    }

    /**
     * Render settings panel
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $ga4_id = isset($settings['ga4_id']) ? $settings['ga4_id'] : '';
        $gtm_id = isset($settings['gtm_id']) ? $settings['gtm_id'] : '';
        $meta_pixel_id = isset($settings['meta_pixel_id']) ? $settings['meta_pixel_id'] : '';
        $google_ads_id = isset($settings['google_ads_id']) ? $settings['google_ads_id'] : '';
        ?>
        <input type="hidden" name="module" value="tracking-codes-manager">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">Quick Setup Tracking Codes</h4>
            <p class="sb-sp-description" style="margin: 0;">Just paste your tracking IDs - we'll handle the rest! All tracking codes are automatically inserted in the correct location in your site's HTML.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Tracking Services</h3>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_ga4_id" class="sb-sp-label">
                    <span style="display: inline-flex; align-items: center; gap: 8px;">
                        <span class="dashicons dashicons-chart-line" style="font-size: 18px; color: #3b82f6;"></span>
                        <strong><?php esc_html_e('Google Analytics 4 (GA4)', 'wpswitchboard'); ?></strong>
                    </span>
                </label>
                <p class="sb-sp-description"><?php esc_html_e('Your GA4 Measurement ID (starts with G-)', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_ga4_id" id="setting_ga4_id" value="<?php echo esc_attr($ga4_id); ?>" placeholder="G-XXXXXXXXXX" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_gtm_id" class="sb-sp-label">
                    <span style="display: inline-flex; align-items: center; gap: 8px;">
                        <span class="dashicons dashicons-tag" style="font-size: 18px; color: #3b82f6;"></span>
                        <strong><?php esc_html_e('Google Tag Manager', 'wpswitchboard'); ?></strong>
                    </span>
                </label>
                <p class="sb-sp-description"><?php esc_html_e('Your GTM Container ID (starts with GTM-)', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_gtm_id" id="setting_gtm_id" value="<?php echo esc_attr($gtm_id); ?>" placeholder="GTM-XXXXXXX" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_meta_pixel_id" class="sb-sp-label">
                    <span style="display: inline-flex; align-items: center; gap: 8px;">
                        <span class="dashicons dashicons-facebook" style="font-size: 18px; color: #1877f2;"></span>
                        <strong><?php esc_html_e('Meta Pixel (Facebook)', 'wpswitchboard'); ?></strong>
                    </span>
                </label>
                <p class="sb-sp-description"><?php esc_html_e('Your Meta Pixel ID (15-16 digit number)', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_meta_pixel_id" id="setting_meta_pixel_id" value="<?php echo esc_attr($meta_pixel_id); ?>" placeholder="1234567890123456" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_google_ads_id" class="sb-sp-label">
                    <span style="display: inline-flex; align-items: center; gap: 8px;">
                        <span class="dashicons dashicons-money-alt" style="font-size: 18px; color: #3b82f6;"></span>
                        <strong><?php esc_html_e('Google Ads Conversion', 'wpswitchboard'); ?></strong>
                    </span>
                </label>
                <p class="sb-sp-description"><?php esc_html_e('Your Google Ads Conversion ID (starts with AW-)', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_google_ads_id" id="setting_google_ads_id" value="<?php echo esc_attr($google_ads_id); ?>" placeholder="AW-XXXXXXXXXX" class="sb-sp-input">
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Need Custom Code?</h4>
            <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('Use the "Header & Footer Code" module for custom tracking scripts or other code snippets.', 'wpswitchboard'); ?></p>
        </div>
        <?php


    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_tracking-codes-manager_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardTrackingCodesManager();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
