<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Analytics Tracker
 * Self-hosted website analytics system - tracks visitor data without external dependencies
 * 
 * @package VMO_AI_Website_Builder
 * @version 8.0.1
 */

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

class VMO_Analytics_Tracker {
    
    private static $instance = null;
    
    /**
     * Singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor - Register hooks
     */
    public function __construct() {
        // AJAX endpoint for tracking (public - no authentication needed for visitor tracking)
        add_action('wp_ajax_nopriv_vmo_track_visit', array($this, 'track_visit'));
        add_action('wp_ajax_vmo_track_visit', array($this, 'track_visit'));
        
        // AJAX endpoint for tracking page views
        add_action('wp_ajax_nopriv_vmo_track_pageview', array($this, 'track_pageview'));
        add_action('wp_ajax_vmo_track_pageview', array($this, 'track_pageview'));
        
        // AJAX endpoint for tracking events
        add_action('wp_ajax_nopriv_vmo_track_event', array($this, 'track_event'));
        add_action('wp_ajax_vmo_track_event', array($this, 'track_event'));
        
        // ✅ NEW: AJAX endpoint for tracking page exit (duration update)
        add_action('wp_ajax_nopriv_vmo_track_exit', array($this, 'track_exit'));
        add_action('wp_ajax_vmo_track_exit', array($this, 'track_exit'));
    }
    
    /**
     * Track website visit
     * Called when visitor lands on any page
     */
    public function track_visit() {
        global $wpdb;
        
        // Get tracking data from request
        $data = $this->get_tracking_data();
        
        if (!$data) {
            wp_send_json_error(['message' => 'Invalid tracking data'], 400);
        }
        
        // Get or create contact ID (visitor fingerprint)
        $contact_id = $this->get_or_create_contact_id($data);
        $contact = $this->update_contact_record($data['user_id'], $contact_id, $data);
        if (!empty($contact['contact_id'])) {
            $contact_id = (string) $contact['contact_id'];
        }

        // Check if this is a new session (last visit > 30 minutes ago)
        $is_new_session = $this->is_new_session($data['user_id'], $contact_id);

        $result = function_exists('vmo_crm_log_interaction') && vmo_crm_log_interaction($data['user_id'], $contact_id, array(
            'interaction_type' => 'website_visit',
            'subtype' => $data['page_url'],
            'subject' => $data['page_title'],
            'summary' => 'Visitor from ' . ($data['referrer'] ?: 'direct traffic'),
            'full_details' => array(
                'url' => $data['page_url'],
                'title' => $data['page_title'],
                'referrer' => $data['referrer'],
                'utm_source' => $data['utm_source'],
                'utm_medium' => $data['utm_medium'],
                'utm_campaign' => $data['utm_campaign'],
                'is_new_session' => $is_new_session,
            ),
            'metadata' => array(
                'device' => $data['device'],
                'browser' => $data['browser'],
                'os' => $data['os'],
                'screen_width' => $data['screen_width'],
                'screen_height' => $data['screen_height'],
                'language' => $data['language'],
                'timezone' => $data['timezone'],
                'ip_address' => $data['ip_address'],
                'country' => $data['country'],
                'city' => $data['city'],
                'region' => $data['region'],
            ),
        ));
        
        if ($result) {
            if (function_exists('vmo_record_attribution_event')) {
                vmo_record_attribution_event($data['user_id'], $is_new_session ? 'website_visit' : 'landing_page_view', array(
                    'visitor_id' => $contact_id,
                    'contact_id' => $contact_id,
                    'page_url' => $data['page_url'],
                    'landing_page' => $data['page_url'],
                    'referrer' => $data['referrer'],
                    'utm_source' => $data['utm_source'],
                    'utm_medium' => $data['utm_medium'],
                    'utm_campaign' => $data['utm_campaign'],
                    'utm_term' => $data['utm_term'] ?? '',
                    'utm_content' => $data['utm_content'] ?? '',
                ));
            }
            $this->sync_dashboard_kpis($data['user_id']);
            
            wp_send_json_success(array(
                'contact_id' => $contact_id,
                'is_new_session' => $is_new_session,
                'interaction_id' => $wpdb->insert_id
            ));
        } else {
            wp_send_json_error(['message' => 'Failed to track visit'], 500);
        }
    }
    
    /**
     * Track page view
     * Called when visitor navigates to a new page
     */
    public function track_pageview() {
        global $wpdb;
        
        $data = $this->get_tracking_data();
        
        if (!$data || empty($data['contact_id'])) {
            wp_send_json_error(['message' => 'Invalid tracking data'], 400);
        }
        
        $event_data = array();
        $contact = $this->update_contact_record($data['user_id'], $data['contact_id'], array_merge($data, $event_data));
        $contact_id = !empty($contact['contact_id']) ? (string) $contact['contact_id'] : $data['contact_id'];

        $result = function_exists('vmo_crm_log_interaction') && vmo_crm_log_interaction($data['user_id'], $contact_id, array(
            'interaction_type' => 'website_visit',
            'subtype' => $data['page_url'],
            'subject' => $data['page_title'],
            'full_details' => array(
                'url' => $data['page_url'],
                'title' => $data['page_title'],
                'time_on_previous_page' => $data['time_on_page'] ?? 0,
            ),
            'duration_minutes' => intval($data['time_on_page'] ?? 0) / 60,
        ));
        
        if ($result) {
            if (function_exists('vmo_record_attribution_event')) {
                vmo_record_attribution_event($data['user_id'], 'landing_page_view', array(
                    'visitor_id' => $contact_id,
                    'contact_id' => $contact_id,
                    'page_url' => $data['page_url'],
                    'landing_page' => $data['page_url'],
                    'referrer' => $data['referrer'] ?? '',
                    'utm_source' => $data['utm_source'] ?? '',
                    'utm_medium' => $data['utm_medium'] ?? '',
                    'utm_campaign' => $data['utm_campaign'] ?? '',
                ));
            }
            $this->sync_dashboard_kpis($data['user_id']);
            wp_send_json_success(['pageview_id' => $wpdb->insert_id]);
        } else {
            wp_send_json_error(['message' => 'Failed to track pageview'], 500);
        }
    }
    
    /**
     * Track custom event
     * Called for button clicks, form submissions, etc.
     */
    public function track_event() {
        global $wpdb;
        
        $data = $this->get_tracking_data();
        $event_name = sanitize_text_field($_POST['event_name'] ?? 'custom_event');
        $event_data = json_decode(wp_unslash($_POST['event_data'] ?? '{}'), true);
        if (!is_array($event_data)) {
            $event_data = array();
        }
        
        if (!$data || empty($data['contact_id'])) {
            wp_send_json_error(['message' => 'Invalid tracking data'], 400);
        }
        
        $contact = $this->update_contact_record($data['user_id'], $data['contact_id'], $data);
        $contact_id = !empty($contact['contact_id']) ? (string) $contact['contact_id'] : $data['contact_id'];

        $result = function_exists('vmo_crm_log_interaction') && vmo_crm_log_interaction($data['user_id'], $contact_id, array(
            'interaction_type' => 'automated_engagement',
            'subtype' => $event_name,
            'subject' => $event_name,
            'full_details' => $event_data,
        ));
        
        if ($result) {
            if (function_exists('vmo_record_attribution_event')) {
                $event_type = 'website_event';
                if (preg_match('/form|submit|lead|contact/i', $event_name)) $event_type = 'form_submission';
                elseif (preg_match('/signup|newsletter|email/i', $event_name)) $event_type = 'email_signup';
                elseif (preg_match('/chat/i', $event_name)) $event_type = 'live_chat';
                elseif (preg_match('/book|appointment|schedule|reservation/i', $event_name)) $event_type = 'appointment_booking';
                elseif (preg_match('/checkout|purchase|order|buy/i', $event_name)) $event_type = 'checkout';
                vmo_record_attribution_event($data['user_id'], $event_type, array_merge($event_data, array(
                    'visitor_id' => $contact_id,
                    'contact_id' => $contact_id,
                    'event_subtype' => $event_name,
                    'page_url' => $data['page_url'] ?? '',
                    'landing_page' => $data['page_url'] ?? '',
                    'referrer' => $data['referrer'] ?? '',
                    'utm_source' => $data['utm_source'] ?? '',
                    'utm_medium' => $data['utm_medium'] ?? '',
                    'utm_campaign' => $data['utm_campaign'] ?? '',
                )));
            }
            $this->sync_dashboard_kpis($data['user_id'], $event_name, $event_data);
            wp_send_json_success(['event_id' => $wpdb->insert_id]);
        } else {
            wp_send_json_error(['message' => 'Failed to track event'], 500);
        }
    }
    
    /**
     * Track page exit (duration tracking)
     * Updates the most recent visit record with session duration
     * Called via sendBeacon when user leaves the page
     */
    public function track_exit() {
        global $wpdb;
        
        // Get data from beacon request
        $site_owner_id = intval($_POST['site_owner_id'] ?? 0);
        $contact_id = sanitize_text_field($_POST['contact_id'] ?? '');
        $page_url = esc_url_raw($_POST['page_url'] ?? '');
        $duration_seconds = intval($_POST['duration_seconds'] ?? 0);
        $duration_minutes = intval($_POST['duration_minutes'] ?? 0);
        
        if (!$site_owner_id || !$contact_id || !$page_url) {
            // Silent fail for beacon requests (no response expected)
            exit;
        }
        
        // Find the most recent visit record for this contact/page (within last 5 minutes)
        $interactions_table = $wpdb->prefix . 'vmo_contact_interactions';
        
        $visit_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$interactions_table} 
             WHERE user_id = %d 
             AND contact_id = %s 
             AND interaction_type = 'website_visit' 
             AND interaction_subtype = %s 
             AND created_at >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
             ORDER BY created_at DESC 
             LIMIT 1",
            $site_owner_id,
            $contact_id,
            $page_url
        ));
        
        if ($visit_id) {
            // Get current metadata
            $current_metadata = $wpdb->get_var($wpdb->prepare(
                "SELECT metadata FROM {$interactions_table} WHERE id = %d",
                $visit_id
            ));
            
            $metadata = json_decode($current_metadata, true) ?: array();
            $metadata['duration_seconds'] = $duration_seconds;
            
            // Update the visit with duration
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update(
                $interactions_table,
                array(
                    'duration_minutes' => $duration_minutes,
                    'metadata' => json_encode($metadata)
                ),
                array('id' => $visit_id),
                array('%d', '%s'),
                array('%d')
            );
        }
        
        // Silent exit (no JSON response for beacon)
        exit;
    }
    
    /**
     * Get tracking data from POST request
     */
    private function get_tracking_data() {
        // Get site owner ID (stored in tracking script)
        $user_id = intval($_POST['site_owner_id'] ?? 0);
        
        if (!$user_id) {
            return false;
        }
        
        // Get visitor data
        $contact_id = sanitize_text_field($_POST['contact_id'] ?? '');
        $page_url = esc_url_raw($_POST['page_url'] ?? '');
        $page_title = sanitize_text_field($_POST['page_title'] ?? '');
        $referrer = esc_url_raw($_POST['referrer'] ?? '');
        
        // UTM parameters
        $utm_source = sanitize_text_field($_POST['utm_source'] ?? '');
        $utm_medium = sanitize_text_field($_POST['utm_medium'] ?? '');
        $utm_campaign = sanitize_text_field($_POST['utm_campaign'] ?? '');
        
        // Device/Browser data
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $device_data = $this->parse_user_agent($user_agent);
        
        // Screen resolution
        $screen_width = intval($_POST['screen_width'] ?? 0);
        $screen_height = intval($_POST['screen_height'] ?? 0);
        
        // Language/Timezone
        $language = sanitize_text_field($_POST['language'] ?? '');
        $timezone = sanitize_text_field($_POST['timezone'] ?? '');
        
        // Get IP and geolocation
        $ip_address = $this->get_client_ip();
        $geo_data = $this->get_geolocation($ip_address);
        
        return array(
            'user_id' => $user_id,
            'contact_id' => $contact_id,
            'page_url' => $page_url,
            'page_title' => $page_title,
            'referrer' => $referrer,
            'utm_source' => $utm_source,
            'utm_medium' => $utm_medium,
            'utm_campaign' => $utm_campaign,
            'device' => $device_data['device'],
            'browser' => $device_data['browser'],
            'os' => $device_data['os'],
            'screen_width' => $screen_width,
            'screen_height' => $screen_height,
            'language' => $language,
            'timezone' => $timezone,
            'ip_address' => $ip_address,
            'country' => $geo_data['country'] ?? '',
            'city' => $geo_data['city'] ?? '',
            'region' => $geo_data['region'] ?? '',
            'time_on_page' => intval($_POST['time_on_page'] ?? 0)
        );
    }
    
    /**
     * Get or create contact ID for visitor
     */
    private function get_or_create_contact_id($data) {
        // Use existing contact ID if provided
        if (!empty($data['contact_id'])) {
            return $data['contact_id'];
        }
        
        // Generate unique contact ID based on IP + User Agent
        $fingerprint = $data['ip_address'] . '|' . $data['browser'] . '|' . $data['os'];
        return 'visitor_' . md5($fingerprint);
    }
    
    /**
     * Check if this is a new session
     * Session = gap of more than 30 minutes since last visit
     */
    private function is_new_session($user_id, $contact_id) {
        global $wpdb;
        
        $interactions_table = $wpdb->prefix . 'vmo_contact_interactions';
        $thirty_minutes_ago = date('Y-m-d H:i:s', strtotime('-30 minutes'));
        
        $recent_visit = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$interactions_table} 
             WHERE user_id = %d AND contact_id = %s 
             AND interaction_type = 'website_visit' 
             AND created_at > %s",
            $user_id, $contact_id, $thirty_minutes_ago
        ));
        
        return ($recent_visit == 0);
    }
    
    private function extract_contact_identity($data) {
        $identity = array(
            'full_name' => sanitize_text_field($data['full_name'] ?? $data['name'] ?? $data['customer_name'] ?? $data['client_name'] ?? ''),
            'email' => sanitize_email($data['email'] ?? $data['customer_email'] ?? $data['client_email'] ?? ''),
            'phone' => sanitize_text_field($data['phone'] ?? $data['customer_phone'] ?? $data['client_phone'] ?? ''),
            'company' => sanitize_text_field($data['company'] ?? $data['organization'] ?? $data['business_name'] ?? ''),
        );

        return array_filter($identity, function($value) {
            return trim((string) $value) !== '';
        });
    }

    /**
     * Update or create a CRM contact only after the visitor identifies themselves.
     */
    private function update_contact_record($user_id, $contact_id, $data) {
        $identity = $this->extract_contact_identity($data);
        if (empty($identity)) {
            return array('contact_id' => $contact_id, 'anonymous' => true);
        }

        if (!function_exists('vmo_crm_upsert_contact')) {
            return array('contact_id' => $contact_id);
        }

        $identity['contact_id'] = sanitize_text_field($contact_id);

        return vmo_crm_upsert_contact((int) $user_id, $identity, array(
            'source' => 'website_form',
            'primary_category' => 'lead',
            'lifecycle_stage' => 'new',
            'city' => sanitize_text_field($data['city'] ?? ''),
            'state' => sanitize_text_field($data['region'] ?? ''),
            'country' => sanitize_text_field($data['country'] ?? ''),
            'tags' => array('website_lead'),
            'acquisition_details' => array(
                'source' => 'website_activity',
                'visitor_fingerprint' => sanitize_text_field($contact_id),
                'referrer' => esc_url_raw($data['referrer'] ?? ''),
                'landing_page' => esc_url_raw($data['page_url'] ?? ''),
                'utm_source' => sanitize_text_field($data['utm_source'] ?? ''),
                'utm_medium' => sanitize_text_field($data['utm_medium'] ?? ''),
                'utm_campaign' => sanitize_text_field($data['utm_campaign'] ?? ''),
                'ip_address' => sanitize_text_field($data['ip_address'] ?? ''),
                'browser' => sanitize_text_field($data['browser'] ?? ''),
                'os' => sanitize_text_field($data['os'] ?? ''),
            ),
        ));
    }

    private function sync_dashboard_kpis($user_id, $event_name = '', array $event_data = array()) {
        $user_id = intval($user_id);
        if ($user_id <= 0) {
            return;
        }

        $dashboard = $this->get_kpi_dashboard();
        if (!$dashboard) {
            return;
        }

        $analytics = $this->get_operational_analytics_summary($user_id);
        $commerce = $this->get_commerce_summary($user_id);

        $conversion_events = (int) $analytics['form_submissions']
            + (int) $analytics['phone_clicks']
            + (int) $analytics['email_clicks']
            + (int) $analytics['checkout_starts']
            + (int) $analytics['purchase_events']
            + (int) $analytics['order_created_events'];
        $conversion_rate = (int) $analytics['website_visitors'] > 0
            ? round(($conversion_events / max(1, (int) $analytics['website_visitors'])) * 100, 2)
            : 0;

        $metrics = array(
            'website_visitors' => array((int) $analytics['website_visitors'], 'Website Visitors', 'number', 'traffic'),
            'page_views' => array((int) $analytics['page_views'], 'Page Views', 'number', 'traffic'),
            'cta_clicks' => array((int) $analytics['cta_clicks'], 'CTA Clicks', 'number', 'traffic'),
            'product_views' => array((int) $analytics['product_views'], 'Product Views', 'number', 'traffic'),
            'checkout_starts' => array((int) $analytics['checkout_starts'], 'Checkout Starts', 'number', 'traffic'),
            'form_submissions' => array((int) $analytics['form_submissions'], 'Form Submissions', 'number', 'leads'),
            'phone_clicks' => array((int) $analytics['phone_clicks'], 'Phone Clicks', 'number', 'leads'),
            'email_clicks' => array((int) $analytics['email_clicks'], 'Email Clicks', 'number', 'leads'),
            'total_leads' => array($conversion_events, 'Total Leads', 'number', 'leads'),
            'new_leads_today' => array((int) $analytics['conversion_events_today'], 'New Leads Today', 'number', 'leads'),
            'new_leads_week' => array((int) $analytics['conversion_events_week'], 'New Leads This Week', 'number', 'leads'),
            'conversion_events' => array($conversion_events, 'Conversion Events', 'number', 'leads'),
            'conversion_rate' => array($conversion_rate, 'Conversion Rate', 'percentage', 'leads'),
            'orders' => array((int) $commerce['orders'], 'Orders', 'number', 'commerce'),
            'orders_30d' => array((int) $commerce['orders_30d'], 'Orders 30d', 'number', 'commerce'),
            'revenue' => array((string) $commerce['revenue'], 'Revenue', 'currency', 'commerce'),
            'revenue_30d' => array((string) $commerce['revenue_30d'], 'Revenue 30d', 'currency', 'commerce'),
            'shipping_status_events' => array((int) $analytics['shipping_status_events'], 'Shipping Events', 'number', 'commerce'),
            'seo_status_events' => array((int) $analytics['seo_status_events'], 'SEO Status Events', 'number', 'seo'),
        );

        foreach ($metrics as $metric_name => $metric) {
            $dashboard->set_kpi($user_id, $metric_name, $metric[0], array(
                'label' => $metric[1],
                'type' => $metric[2],
                'category' => $metric[3],
                'source' => 'vmo_analytics_tracker',
            ));
        }

        $dashboard->record_kpi_history($user_id, 'conversion_rate', $conversion_rate);
        if ($event_name !== '') {
            update_user_meta($user_id, 'vmo_last_website_event', array(
                'event' => sanitize_key($event_name),
                'data' => $event_data,
                'recorded_at' => current_time('mysql'),
            ));
        }
    }

    private function get_operational_analytics_summary($user_id) {
        global $wpdb;

        $table = $wpdb->prefix . 'vmo_contact_interactions';
        if (!$this->table_exists($table)) {
            return $this->empty_analytics_summary();
        }

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT
                COUNT(DISTINCT CASE WHEN interaction_type IN ('website_visit', 'page_view') THEN contact_id END) AS website_visitors,
                COUNT(CASE WHEN interaction_type IN ('website_visit', 'page_view') THEN 1 END) AS page_views,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'cta_click' THEN 1 ELSE 0 END) AS cta_clicks,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'product_view' THEN 1 ELSE 0 END) AS product_views,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'checkout_start' THEN 1 ELSE 0 END) AS checkout_starts,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'form_submit' THEN 1 ELSE 0 END) AS form_submissions,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'phone_click' THEN 1 ELSE 0 END) AS phone_clicks,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'email_click' THEN 1 ELSE 0 END) AS email_clicks,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'purchase' THEN 1 ELSE 0 END) AS purchase_events,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'order_created' THEN 1 ELSE 0 END) AS order_created_events,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'shipping_status' THEN 1 ELSE 0 END) AS shipping_status_events,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype = 'seo_status' THEN 1 ELSE 0 END) AS seo_status_events,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype IN ('form_submit', 'phone_click', 'email_click', 'checkout_start', 'purchase', 'order_created') AND created_at >= CURDATE() THEN 1 ELSE 0 END) AS conversion_events_today,
                SUM(CASE WHEN interaction_type = 'automated_engagement' AND interaction_subtype IN ('form_submit', 'phone_click', 'email_click', 'checkout_start', 'purchase', 'order_created') AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS conversion_events_week
             FROM {$table}
             WHERE user_id = %d",
            $user_id
        ), ARRAY_A);

        if (!is_array($row)) {
            return $this->empty_analytics_summary();
        }

        return array_merge($this->empty_analytics_summary(), array_map('intval', $row));
    }

    private function empty_analytics_summary() {
        return array(
            'website_visitors' => 0,
            'page_views' => 0,
            'cta_clicks' => 0,
            'product_views' => 0,
            'checkout_starts' => 0,
            'form_submissions' => 0,
            'phone_clicks' => 0,
            'email_clicks' => 0,
            'purchase_events' => 0,
            'order_created_events' => 0,
            'shipping_status_events' => 0,
            'seo_status_events' => 0,
            'conversion_events_today' => 0,
            'conversion_events_week' => 0,
        );
    }

    private function get_commerce_summary($user_id) {
        global $wpdb;

        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        if (!$this->table_exists($orders_table)) {
            return $this->get_purchase_commerce_summary($user_id);
        }

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT
                COUNT(*) AS orders,
                COALESCE(SUM(amount_total), 0) AS revenue_cents,
                SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) AS orders_30d,
                COALESCE(SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN amount_total ELSE 0 END), 0) AS revenue_30d_cents
             FROM {$orders_table}
             WHERE user_id = %d AND status IN ('paid', 'completed', 'succeeded')",
            $user_id
        ), ARRAY_A);

        if (!is_array($row)) {
            return $this->get_purchase_commerce_summary($user_id);
        }

        $orders = intval($row['orders'] ?? 0);
        if ($orders <= 0) {
            return $this->get_purchase_commerce_summary($user_id);
        }

        return array(
            'orders' => $orders,
            'orders_30d' => intval($row['orders_30d'] ?? 0),
            'revenue' => round(intval($row['revenue_cents'] ?? 0) / 100, 2),
            'revenue_30d' => round(intval($row['revenue_30d_cents'] ?? 0) / 100, 2),
        );
    }

    private function get_purchase_commerce_summary($user_id) {
        global $wpdb;

        $purchases_table = $wpdb->prefix . 'vmo_contact_purchases';
        if (!$this->table_exists($purchases_table)) {
            return array('orders' => 0, 'orders_30d' => 0, 'revenue' => 0, 'revenue_30d' => 0);
        }

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT
                COUNT(*) AS orders,
                COALESCE(SUM(amount), 0) AS revenue,
                SUM(CASE WHEN purchase_date >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) AS orders_30d,
                COALESCE(SUM(CASE WHEN purchase_date >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN amount ELSE 0 END), 0) AS revenue_30d
             FROM {$purchases_table}
             WHERE user_id = %d AND status = 'completed'",
            $user_id
        ), ARRAY_A);

        if (!is_array($row)) {
            return array('orders' => 0, 'orders_30d' => 0, 'revenue' => 0, 'revenue_30d' => 0);
        }

        return array(
            'orders' => intval($row['orders'] ?? 0),
            'orders_30d' => intval($row['orders_30d'] ?? 0),
            'revenue' => round(floatval($row['revenue'] ?? 0), 2),
            'revenue_30d' => round(floatval($row['revenue_30d'] ?? 0), 2),
        );
    }

    private function get_kpi_dashboard() {
        if (!class_exists('VMO_KPI_Dashboard')) {
            $file = plugin_dir_path(__FILE__) . 'class-vmo-kpi-dashboard.php';
            if (file_exists($file)) {
                require_once $file;
            }
        }

        return class_exists('VMO_KPI_Dashboard') ? new VMO_KPI_Dashboard() : null;
    }

    private function table_exists($table) {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) === $table;
    }
    
    /**
     * Parse user agent to extract device, browser, OS
     */
    private function parse_user_agent($user_agent) {
        $device = 'Desktop';
        $browser = 'Unknown';
        $os = 'Unknown';
        
        // Detect device type
        if (preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', $user_agent)) {
            $device = 'Tablet';
        } elseif (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|mobile|opera mini)/i', $user_agent)) {
            $device = 'Mobile';
        }
        
        // Detect browser
        if (preg_match('/MSIE|Trident/i', $user_agent)) {
            $browser = 'Internet Explorer';
        } elseif (preg_match('/Edge/i', $user_agent)) {
            $browser = 'Edge';
        } elseif (preg_match('/Chrome/i', $user_agent)) {
            $browser = 'Chrome';
        } elseif (preg_match('/Safari/i', $user_agent)) {
            $browser = 'Safari';
        } elseif (preg_match('/Firefox/i', $user_agent)) {
            $browser = 'Firefox';
        } elseif (preg_match('/Opera/i', $user_agent)) {
            $browser = 'Opera';
        }
        
        // Detect OS
        if (preg_match('/windows|win32/i', $user_agent)) {
            $os = 'Windows';
        } elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
            $os = 'macOS';
        } elseif (preg_match('/linux/i', $user_agent)) {
            $os = 'Linux';
        } elseif (preg_match('/ubuntu/i', $user_agent)) {
            $os = 'Ubuntu';
        } elseif (preg_match('/iphone/i', $user_agent)) {
            $os = 'iOS';
        } elseif (preg_match('/android/i', $user_agent)) {
            $os = 'Android';
        }
        
        return array(
            'device' => $device,
            'browser' => $browser,
            'os' => $os
        );
    }
    
    /**
     * Get client IP address
     */
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
    
    /**
     * Get geolocation from IP
     * Uses free ip-api.com service (no API key needed, 45 requests/minute limit)
     */
    private function get_geolocation($ip_address) {
        // Skip for local/private IPs
        if ($ip_address === '0.0.0.0' || $ip_address === '127.0.0.1' || strpos($ip_address, '192.168.') === 0) {
            return array('country' => 'Local', 'city' => 'Local', 'region' => 'Local');
        }
        
        // Check WordPress transient cache first (cache for 24 hours)
        $cache_key = 'vmo_geo_' . md5($ip_address);
        $cached = get_transient($cache_key);
        
        if ($cached !== false) {
            return $cached;
        }
        
        // Call free geolocation API
        $response = wp_remote_get("http://ip-api.com/json/{$ip_address}?fields=status,country,regionName,city", array(
            'timeout' => 2,
            'sslverify' => false
        ));
        
        if (is_wp_error($response)) {
            return array('country' => '', 'city' => '', 'region' => '');
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if ($body && $body['status'] === 'success') {
            $geo_data = array(
                'country' => $body['country'] ?? '',
                'city' => $body['city'] ?? '',
                'region' => $body['regionName'] ?? ''
            );
            
            // Cache for 24 hours
            set_transient($cache_key, $geo_data, 24 * HOUR_IN_SECONDS);
            
            return $geo_data;
        }
        
        return array('country' => '', 'city' => '', 'region' => '');
    }
    
    /**
     * Generate tracking JavaScript snippet
     * This will be injected into generated websites
     */
    public static function get_tracking_script($site_owner_id) {
        $ajax_url = admin_url('admin-ajax.php');
        
        return <<<JS
<!-- VMO Analytics Tracker -->
<script>
(function() {
    'use strict';
    
    // Configuration
    const VMO_TRACKER = {
        ajax_url: '{$ajax_url}',
        site_owner_id: {$site_owner_id},
        contact_id: localStorage.getItem('vmo_contact_id') || '',
        session_start: Date.now(),
        page_start: Date.now(),
        is_page_visible: true
    };
    
    // Get URL parameters
    function getUrlParam(name) {
        const params = new URLSearchParams(window.location.search);
        return params.get(name) || '';
    }
    
    // Track visit (initial page load)
    function trackVisit() {
        const data = new FormData();
        data.append('action', 'vmo_track_visit');
        data.append('site_owner_id', VMO_TRACKER.site_owner_id);
        data.append('contact_id', VMO_TRACKER.contact_id);
        data.append('page_url', window.location.href);
        data.append('page_title', document.title);
        data.append('referrer', document.referrer);
        data.append('utm_source', getUrlParam('utm_source'));
        data.append('utm_medium', getUrlParam('utm_medium'));
        data.append('utm_campaign', getUrlParam('utm_campaign'));
        data.append('screen_width', window.screen.width);
        data.append('screen_height', window.screen.height);
        data.append('language', navigator.language);
        data.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
        
        fetch(VMO_TRACKER.ajax_url, {
            method: 'POST',
            body: data
        })
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data.contact_id) {
                VMO_TRACKER.contact_id = result.data.contact_id;
                localStorage.setItem('vmo_contact_id', result.data.contact_id);
            }
        })
        .catch(error => console.log('VMO Tracker: Visit tracking failed'));
    }
    
    // ✅ NEW: Track page exit with duration (using sendBeacon for reliability)
    function trackExit() {
        if (!VMO_TRACKER.is_page_visible || !VMO_TRACKER.contact_id) {
            return; // Don't track if tab was hidden or no contact ID
        }
        
        const duration_seconds = Math.round((Date.now() - VMO_TRACKER.page_start) / 1000);
        const duration_minutes = Math.round(duration_seconds / 60);
        
        const data = new FormData();
        data.append('action', 'vmo_track_exit');
        data.append('site_owner_id', VMO_TRACKER.site_owner_id);
        data.append('contact_id', VMO_TRACKER.contact_id);
        data.append('page_url', window.location.href);
        data.append('duration_seconds', duration_seconds);
        data.append('duration_minutes', duration_minutes);
        
        // sendBeacon is more reliable during page unload
        navigator.sendBeacon(VMO_TRACKER.ajax_url, data);
    }
    
    // Track page view (when navigating between pages)
    function trackPageview() {
        const time_on_page = Math.floor((Date.now() - VMO_TRACKER.page_start) / 1000);
        VMO_TRACKER.page_start = Date.now();
        
        const data = new FormData();
        data.append('action', 'vmo_track_pageview');
        data.append('site_owner_id', VMO_TRACKER.site_owner_id);
        data.append('contact_id', VMO_TRACKER.contact_id);
        data.append('page_url', window.location.href);
        data.append('page_title', document.title);
        data.append('time_on_page', time_on_page);
        
        fetch(VMO_TRACKER.ajax_url, {
            method: 'POST',
            body: data
        })
        .catch(error => console.log('VMO Tracker: Pageview tracking failed'));
    }
    
    // Track custom event
    window.vmoTrackEvent = function(event_name, event_data) {
        const data = new FormData();
        data.append('action', 'vmo_track_event');
        data.append('site_owner_id', VMO_TRACKER.site_owner_id);
        data.append('contact_id', VMO_TRACKER.contact_id);
        data.append('event_name', event_name);
        data.append('event_data', JSON.stringify(event_data || {}));
        
        fetch(VMO_TRACKER.ajax_url, {
            method: 'POST',
            body: data
        })
        .catch(error => console.log('VMO Tracker: Event tracking failed'));
    };

    function extractContactFields(form) {
        const fields = {};
        Array.prototype.slice.call(form.elements || []).forEach(function(field) {
            if (!field || field.disabled) return;
            const type = String(field.type || '').toLowerCase();
            if (/^(password|hidden|submit|button|reset|file)$/i.test(type)) return;
            const descriptor = [field.name, field.id, field.autocomplete, field.placeholder, field.getAttribute('aria-label')]
                .filter(Boolean)
                .join(' ')
                .toLowerCase();
            const value = String(field.value || '').trim();
            if (!value) return;
            if ((type === 'email' || /(^|\b)(email|e-mail)(\b|$)/.test(descriptor)) && !fields.email) {
                fields.email = value;
            } else if ((type === 'tel' || /phone|mobile|cell|telephone/.test(descriptor)) && !fields.phone) {
                fields.phone = value;
            } else if (/company|organization|business/.test(descriptor) && !fields.company) {
                fields.company = value;
            } else if (/full.?name|contact.?name|client.?name|customer.?name|(^|\b)name(\b|$)/.test(descriptor) && !fields.name) {
                fields.name = value;
            }
        });
        return fields;
    }

    function trackElementEvent(eventName, element, extraData) {
        const payload = Object.assign({
            page_url: window.location.href,
            page_title: document.title,
            label: (element && (element.getAttribute('aria-label') || element.textContent || element.title || element.href || '') || '').trim().slice(0, 160),
            href: element && element.href ? element.href : '',
            section: element && element.closest('[data-vmo-section]') ? element.closest('[data-vmo-section]').getAttribute('data-vmo-section') : '',
            product_id: element && element.closest('[data-vmo-product-id]') ? element.closest('[data-vmo-product-id]').getAttribute('data-vmo-product-id') : ''
        }, extraData || {});
        window.vmoTrackEvent(eventName, payload);
    }

    function wireOperationalEvents() {
        document.querySelectorAll('[data-vmo-product-id]').forEach(function(productEl) {
            trackElementEvent('product_view', productEl, {
                product_id: productEl.getAttribute('data-vmo-product-id') || '',
                source: 'auto_product_impression'
            });
        });

        document.addEventListener('submit', function(e) {
            const form = e.target && e.target.closest ? e.target.closest('form') : null;
            if (!form) return;
            trackElementEvent('form_submit', form, Object.assign({
                form_id: form.id || '',
                form_name: form.getAttribute('name') || '',
                source: 'auto_form_submit'
            }, extractContactFields(form)));
        }, true);

        document.addEventListener('click', function(e) {
            const target = e.target && e.target.closest ? e.target : (e.target && e.target.parentElement ? e.target.parentElement : null);
            const clickable = target ? target.closest('a, button, [role="button"], [data-vmo-track], [data-vmo-event]') : null;
            if (!clickable) return;
            const href = clickable.href || '';
            const explicitEvent = clickable.getAttribute('data-vmo-event') || clickable.getAttribute('data-vmo-track') || '';
            const label = (clickable.textContent || clickable.getAttribute('aria-label') || '').toLowerCase();

            if (explicitEvent) {
                trackElementEvent(explicitEvent, clickable, { source: 'explicit_data_attribute' });
            }
            if (href.indexOf('tel:') === 0) {
                trackElementEvent('phone_click', clickable, { source: 'auto_phone_link' });
            } else if (href.indexOf('mailto:') === 0) {
                trackElementEvent('email_click', clickable, { source: 'auto_email_link' });
            } else if (href.indexOf('vmo_buy_product=') !== -1 || /checkout|cart|buy|order|purchase/.test(label)) {
                trackElementEvent('checkout_start', clickable, { source: 'auto_commerce_click' });
            } else if (/book|reserve|schedule|contact|get started|start|quote|call|shop|order/.test(label)) {
                trackElementEvent('cta_click', clickable, { source: 'auto_cta_click' });
            }
        }, true);
    }
    
    // ✅ NEW: Track page visibility (pause timer when tab hidden)
    document.addEventListener('visibilitychange', function() {
        VMO_TRACKER.is_page_visible = !document.hidden;
    });
    
    // Initialize tracking on page load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            trackVisit();
            wireOperationalEvents();
        });
    } else {
        trackVisit();
        wireOperationalEvents();
    }
    
    // ✅ UPDATED: Track page exit with duration
    window.addEventListener('beforeunload', trackExit);
    window.addEventListener('pagehide', trackExit);
    
    // Track clicks on links (navigation within site)
    document.addEventListener('click', function(e) {
        const link = e.target.closest('a');
        if (link && link.href && link.href.indexOf(window.location.origin) === 0) {
            trackPageview();
        }
    });
    
})();
</script>
JS;
    }
}

// Initialize tracker
VMO_Analytics_Tracker::get_instance();
