<?php
/**
 * UTM Tracker + Visit Tracker
 *
 * Captures UTM parameters and tracks first-visit timestamp + visit count,
 * then saves all of it to WooCommerce order meta at checkout.
 *
 * @package InsightPress
 */

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

class InsightPress_UTM_Tracker
{
    public function __construct()
    {
        // Enqueue JS on every frontend page
        add_action('wp_enqueue_scripts', array($this, 'enqueue_utm_capture_script'));

        // Save data to order meta at checkout
        add_action('woocommerce_checkout_create_order',              array($this, 'save_utm_to_order'), 10, 2);
        add_action('woocommerce_store_api_checkout_order_processed', array($this, 'save_utm_to_order_hpos'), 10, 1);
    }

    /**
     * Enqueue inline JS to capture UTM params AND track first-visit / visit count.
     */
    public function enqueue_utm_capture_script()
    {
        wp_enqueue_script('insightpress-utm', false, array(), null, false);

        // NOWDOC — PHP does NOT parse escape sequences inside <<<'EOT'
        $inline_script = <<<'IPJS'
(function() {
    var thirtyDays = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString();

    function getCookie(name) {
        var rx = new RegExp('(?:^|; )' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^;]*)');
        var match = document.cookie.match(rx);
        return match ? decodeURIComponent(match[1]) : null;
    }

    function setCookie(name, value, expires) {
        document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; expires=' + expires + '; SameSite=Lax';
    }

    // 1. UTM Parameter Capture (30-day persistent)
    var params = new URLSearchParams(window.location.search);
    var utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
    utmKeys.forEach(function(key) {
        if (params.has(key)) {
            setCookie('insightpress_' + key, params.get(key), thirtyDays);
        }
    });

    // 2. First Visit Timestamp (set once, never overwritten)
    if (!getCookie('ip_first_visit')) {
        setCookie('ip_first_visit', Math.floor(Date.now() / 1000).toString(), thirtyDays);
    }

    // 3. Page View Count (increment on every page load)
    var views = parseInt(getCookie('ip_visit_count') || '0', 10) + 1;
    setCookie('ip_visit_count', views.toString(), thirtyDays);

    // 4. Session Count (increments once per browser session, not per page view)
    if (!sessionStorage.getItem('ip_session_counted')) {
        sessionStorage.setItem('ip_session_counted', '1');
        var sessions = parseInt(getCookie('ip_session_count') || '0', 10) + 1;
        setCookie('ip_session_count', sessions.toString(), thirtyDays);
    }
})();
IPJS;

        wp_add_inline_script('insightpress-utm', $inline_script, 'before');
    }

    /**
     * Save UTM + visit data from cookies to order meta (classic checkout).
     */
    public function save_utm_to_order($order, $data)
    {
        // UTM params
        $utm_keys = array('utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term');
        foreach ($utm_keys as $key) {
            $cookie_name = 'insightpress_' . $key;
            if (!empty($_COOKIE[$cookie_name])) {
                $order->update_meta_data('_insightpress_' . $key, sanitize_text_field(wp_unslash($_COOKIE[$cookie_name])));
            }
        }

        // Visit / time tracking
        if (!empty($_COOKIE['ip_first_visit'])) {
            $first_visit_ts   = (int) $_COOKIE['ip_first_visit'];
            $order_ts         = time();
            $days_to_purchase = max(0, (int) floor(($order_ts - $first_visit_ts) / DAY_IN_SECONDS));

            $order->update_meta_data('_insightpress_first_visit_ts',    $first_visit_ts);
            $order->update_meta_data('_insightpress_days_to_purchase',  $days_to_purchase);
        }

        if (!empty($_COOKIE['ip_visit_count'])) {
            $order->update_meta_data('_insightpress_page_views_to_purchase', (int) $_COOKIE['ip_visit_count']);
        }

        if (!empty($_COOKIE['ip_session_count'])) {
            $order->update_meta_data('_insightpress_sessions_to_purchase', (int) $_COOKIE['ip_session_count']);
        }
    }

    /**
     * Save data for HPOS / Blocks checkout.
     */
    public function save_utm_to_order_hpos($order)
    {
        $this->save_utm_to_order($order, array());
        $order->save();
    }
}
