<?php

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

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and hooks for injecting tracking scripts.
 *
 * @since      1.0.0
 * @package    VASP_Analytics
 * @subpackage VASP_Analytics/public
 */
class VASP_Analytics_Public {

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    string    $plugin_name  The name of the plugin.
     * @param    string    $version      The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;

        // Register tracking script enqueue hook
        add_action('wp_enqueue_scripts', [$this, 'enqueue_tracking_script']);
        // Register pixel code injection in head (for API-provided pixel code)
        add_action('wp_head', [$this, 'inject_pixel_code']);
    }

    /**
     * Enqueues the SentinelPro tracking script using WordPress standards.
     * 
     * This method enqueues the tracking script from analytics.sentinelpro.com
     * only when tracking is explicitly enabled and properly configured by the admin.
     * 
     * Security and privacy:
     * - Tracking is disabled by default
     * - Requires explicit admin configuration (enable_tracking + Property ID + Account Name)
     * - Uses WordPress wp_enqueue_script for proper script loading
     * 
     * @since 1.0.0
     */
    public function enqueue_tracking_script() {
        // Get options from the correct option name
        $options = get_option('vasp_options', []);
        
        // Check if tracking is enabled (handle different value formats: 1, '1', true)
        // Tracking is OFF by default - requires explicit admin configuration
        $enable_tracking = !empty($options['enable_tracking']) && ($options['enable_tracking'] == 1 || $options['enable_tracking'] === '1' || $options['enable_tracking'] === true);
        
        // Check if required data exists
        // No tracking will occur if not enabled or missing required configuration
        if (!$enable_tracking || empty($options['property_id']) || empty($options['account_name'])) {
            return; // No tracking if not enabled or missing required data
        }

        $property_id  = $options['property_id'];
        $account_name = $options['account_name'];

        // Try to get cached pixel code
        $pixel_option_key = "vasp_pixel_code_{$property_id}";
        $pixel_code = get_option($pixel_option_key);

        // If pixel code exists from API, we'll inject it via wp_head (see inject_pixel_code)
        // Otherwise, enqueue the fallback tracking script from SentinelPro CDN
        if (empty($pixel_code)) {
            $tracking_url = 'https://analytics.sentinelpro.com/track.js?id=' . urlencode($property_id);
            wp_enqueue_script(
                'sentinelpro-tracking',
                esc_url_raw($tracking_url),
                [],
                $this->version,
                false // Load in header, not footer
            );
        }
    }

    /**
     * Injects the SentinelPro pixel code (from API) into the site <head>.
     * 
     * This method outputs tracking script code provided by the SentinelPro API.
     * Similar to Google Analytics or Facebook Pixel implementations, this injects
     * a trusted JavaScript snippet for analytics tracking purposes only.
     * 
     * Security notes:
     * - Tracking is disabled by default and only enabled after admin configuration
     * - Requires both enable_tracking flag AND valid Property ID/Account Name
     * - Pixel code is fetched from authenticated API endpoint, not arbitrary sources
     * - Code is cached locally to reduce API calls
     * 
     * @since 1.0.0
     */
    public function inject_pixel_code() {
        // Get options from the correct option name
        $options = get_option('vasp_options', []);
        
        // Check if tracking is enabled (handle different value formats: 1, '1', true)
        // Tracking is OFF by default - requires explicit admin configuration
        $enable_tracking = !empty($options['enable_tracking']) && ($options['enable_tracking'] == 1 || $options['enable_tracking'] === '1' || $options['enable_tracking'] === true);
        
        // Check if required data exists
        // No tracking will occur if not enabled or missing required configuration
        if (!$enable_tracking || empty($options['property_id']) || empty($options['account_name'])) {
            return; // No tracking if not enabled or missing required data
        }

        $property_id  = $options['property_id'];
        $account_name = $options['account_name'];

        // Try to get cached pixel code
        $pixel_option_key = "vasp_pixel_code_{$property_id}";
        $pixel_code = get_option($pixel_option_key);

        // If not cached, request from API (only for logged-in admins to reduce frontend API calls)
        if (empty($pixel_code) && class_exists('VASP_API_Client')) {
            $api_key = class_exists('VASP_Security_Manager') ? VASP_Security_Manager::get_api_key() : '';

            // Preferred: fetch via pixelCode endpoint (raw script)
            if (method_exists('VASP_API_Client', 'request_pixel_code_raw')) {
                $fetched = VASP_API_Client::request_pixel_code_raw($account_name, $property_id, $api_key);
            } else {
                $fetched = '';
            }

            // Fallback: fetch via pixel endpoint with dimensions
            if (empty($fetched)) {
                $dimensions = get_option("vasp_dimensions_{$property_id}", []);
                if (!is_array($dimensions)) {
                    $dimensions = [];
                }
                
                // If dimensions is an associative array (with config), extract just the keys (dimension names)
                // Otherwise, if it's a simple array, use it as-is
                if (!empty($dimensions) && array_values($dimensions) !== $dimensions) {
                    // It's an associative array, extract keys
                    $dimension_names = array_keys($dimensions);
                } else {
                    // It's already a simple array of dimension names
                    $dimension_names = $dimensions;
                }
                
                if (method_exists('VASP_API_Client', 'request_pixel_code')) {
                    $fetched = VASP_API_Client::request_pixel_code($account_name, $property_id, $api_key, $dimension_names);
                }
            }

            if (!empty($fetched)) {
                $pixel_code = $fetched;
                update_option($pixel_option_key, $pixel_code);
            }
        }

        // Output the pixel code as provided by the API
        // This is similar to standard analytics pixel implementations (GA, Facebook Pixel, etc.)
        // The code is trusted as it comes from the authenticated SentinelPro API endpoint
        if (!empty($pixel_code)) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pixel code is trusted script from authenticated API endpoint, similar to standard analytics implementations
            echo $pixel_code;
        }
    }
}
