<?php

namespace FleekDash\Services\AnalyticsTracking;

/**
 * Tracking Script Generator
 *
 * Generates JavaScript tracking code for analytics
 * Extracted from AnalyticsTrackingService for better organization
 *
 * @package FleekDash\Services\AnalyticsTracking
 * @since 2.2.0
 */
class TrackingScriptGenerator
{
    /**
     * Generate complete tracking script HTML
     *
     * @param string $session_id Session identifier
     * @param array $settings Analytics settings
     * @return string HTML script tag
     */
    public function generateTrackingScript($session_id, $settings = [])
    {
        $nonce = \wp_create_nonce('fleekdash_analytics');
        $ajax_url = \admin_url('admin-ajax.php');
        $respect_dnt = !empty($settings['respect_dnt']);

        ob_start();
        ?>
        <script>
            console.log('🚀 FleekDash Analytics: Script loaded successfully!');
            console.log('📊 Session ID:', '<?php echo \esc_js($session_id); ?>');
            console.log('🔗 AJAX URL:', '<?php echo \esc_js($ajax_url); ?>');

            (function() {
                var startTime = Date.now();
                var sessionId = '<?php echo \esc_js($session_id); ?>';
                var nonce = '<?php echo \esc_js($nonce); ?>';
                var ajaxUrl = '<?php echo \esc_js($ajax_url); ?>';
                var respectDNT = <?php echo $respect_dnt ? 'true' : 'false'; ?>;

                // Client-side DNT check as extra safety
                try {
                    var dntVal = (navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack);
                    if (respectDNT && (dntVal === '1' || dntVal === 'yes')) {
                        console.log('🛑 FleekDash Analytics: DNT enabled, skipping.');
                        return;
                    }
                } catch (e) {}

                // Track page view
                function trackPageView() {
                    console.log('📈 FleekDash Analytics: Starting pageview tracking...');

                    var data = {
                        action: 'fleekdash_track_pageview',
                        nonce: nonce,
                        session_id: sessionId,
                        page_url: window.location.href,
                        page_title: document.title,
                        referrer: document.referrer,
                        user_agent: navigator.userAgent,
                        screen_width: screen.width,
                        screen_height: screen.height,
                        timestamp: Date.now()
                    };

                    console.log('📊 FleekDash Analytics: Sending data:', data);

                    fetch(ajaxUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams(data)
                    }).then(function(response) {
                        console.log('📡 FleekDash Analytics: Response received:', response.status);
                        return response.text();
                    }).then(function(data) {
                        console.log('📊 FleekDash Analytics: Response data:', data);
                        if (data === 'OK') {
                            console.log('FleekDash Analytics: Pageview tracked successfully');
                        } else {
                            console.error('❌ FleekDash Analytics: Error tracking pageview', data);
                        }
                    }).catch(function(error) {
                        console.error('🚨 FleekDash Analytics: Tracking failed', error);
                    });
                }

                // Track time on page when leaving
                function trackTimeOnPage() {
                    console.log('⏱️ FleekDash Analytics: Tracking time on page...');
                    var timeOnPage = Math.round((Date.now() - startTime) / 1000);
                    console.log('⏱️ Time on page:', timeOnPage + 's');

                    var data = {
                        action: 'fleekdash_track_pageview',
                        nonce: nonce,
                        session_id: sessionId,
                        page_url: window.location.href,
                        time_on_page: timeOnPage,
                        is_exit: true
                    };

                    navigator.sendBeacon(ajaxUrl, new URLSearchParams(data));
                }

                // Track page view on load
                console.log('🔄 FleekDash Analytics: Setting up pageview tracking...');
                if (document.readyState === 'loading') {
                    console.log('📄 FleekDash Analytics: Document loading, waiting for DOMContentLoaded...');
                    document.addEventListener('DOMContentLoaded', function() {
                        console.log('✨ FleekDash Analytics: DOM loaded, tracking pageview...');
                        trackPageView();
                    });
                } else {
                    console.log('⚡ FleekDash Analytics: Document ready, tracking pageview immediately...');
                    trackPageView();
                }

                // Track time on page before leaving
                window.addEventListener('beforeunload', trackTimeOnPage);
                window.addEventListener('pagehide', trackTimeOnPage);

                // Store interval ID for cleanup
                var heartbeatInterval = null;

                // Track time on page periodically for long sessions
                heartbeatInterval = setInterval(function() {
                    var timeOnPage = Math.round((Date.now() - startTime) / 1000);
                    if (timeOnPage > 30) { // Only track if user stayed more than 30 seconds
                        console.log('💓 FleekDash Analytics: Heartbeat - Time on page:', timeOnPage + 's');

                        var data = {
                            action: 'fleekdash_track_pageview',
                            nonce: nonce,
                            session_id: sessionId,
                            page_url: window.location.href,
                            time_on_page: timeOnPage,
                            is_heartbeat: true
                        };

                        fetch(ajaxUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: new URLSearchParams(data)
                        }).then(function(response) {
                            console.log('💓 FleekDash Analytics: Heartbeat response:', response.status);
                        }).catch(function(error) {
                            console.error('🚨 FleekDash Analytics: Heartbeat failed', error);
                        });
                    }
                }, 30000); // Every 30 seconds

                // Cleanup interval on page unload
                window.addEventListener('beforeunload', function() {
                    if (heartbeatInterval) {
                        clearInterval(heartbeatInterval);
                        heartbeatInterval = null;
                    }
                });
            })();
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * Check if tracking should be enabled based on settings
     *
     * @param array $settings Analytics settings
     * @return bool Whether tracking should be enabled
     */
    public function shouldEnableTracking($settings = [])
    {
        // Check integration manager
        try {
            if (class_exists('FleekDash\\Core\\IntegrationManager')) {
                $manager = \FleekDash\Core\IntegrationManager::getInstance();
                if (!$manager->isActive('analytics')) {
                    return false;
                }
            }
        } catch (\Throwable $e) {
            return false;
        }

        // Check DNT header
        $respect_dnt = !empty($settings['respect_dnt']);
        if ($respect_dnt && (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] === '1')) {
            return false;
        }

        // Check logged-in users setting
        $track_logged_in = !empty($settings['track_logged_in']);
        if (!$track_logged_in && \is_user_logged_in()) {
            return false;
        }

        // Check ignored roles
        if ($this->isUserRoleIgnored($settings)) {
            return false;
        }

        // Check excluded paths
        if ($this->isPathExcluded($settings)) {
            return false;
        }

        // Check excluded user agents
        if ($this->isUserAgentExcluded($settings)) {
            return false;
        }

        // Check sample rate
        if (!$this->passedSampleRate($settings)) {
            return false;
        }

        // Skip on admin pages
        if (is_admin()) {
            return false;
        }

        // Skip on login pages
        if (in_array($GLOBALS['pagenow'] ?? '', ['wp-login.php', 'wp-register.php'])) {
            return false;
        }

        return true;
    }

    /**
     * Check if current user's role is ignored
     *
     * @param array $settings Analytics settings
     * @return bool
     */
    private function isUserRoleIgnored($settings)
    {
        $ignore_roles = $settings['ignore_roles'] ?? [];

        if (is_string($ignore_roles)) {
            $ignore_roles = array_filter(array_map('trim', explode(',', $ignore_roles)));
        }

        if (empty($ignore_roles) || !\is_user_logged_in()) {
            return false;
        }

        $user = \wp_get_current_user();
        if ($user && $user->ID > 0) {
            $user_roles = $user->roles ?? [];
            foreach ($user_roles as $role) {
                if (in_array($role, $ignore_roles, true)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Check if current path is excluded
     *
     * @param array $settings Analytics settings
     * @return bool
     */
    private function isPathExcluded($settings)
    {
        $exclude_paths = $settings['exclude_paths'] ?? '';

        if (is_string($exclude_paths)) {
            $exclude_paths = preg_split('/\r\n|\r|\n/', $exclude_paths);
        }

        if (empty($exclude_paths)) {
            return false;
        }

        $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

        foreach ($exclude_paths as $pattern) {
            $pattern = trim($pattern);
            if ($pattern === '') {
                continue;
            }
            if (strpos($path, $pattern) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if current user agent is excluded
     *
     * @param array $settings Analytics settings
     * @return bool
     */
    private function isUserAgentExcluded($settings)
    {
        $excluded_user_agents = $settings['excluded_user_agents'] ?? '';

        if (is_string($excluded_user_agents)) {
            $excluded_user_agents = preg_split('/\r\n|\r|\n/', $excluded_user_agents);
        }

        if (empty($excluded_user_agents)) {
            return false;
        }

        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

        foreach ($excluded_user_agents as $needle) {
            $needle = trim($needle);
            if ($needle === '') {
                continue;
            }
            if (stripos($ua, $needle) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user passed sample rate
     *
     * @param array $settings Analytics settings
     * @return bool
     */
    private function passedSampleRate($settings)
    {
        $sample_rate = isset($settings['sample_rate'])
            ? max(0, min(1, floatval($settings['sample_rate'])))
            : 1.0;

        // Apply sample rate using a sticky cookie for consistency
        $sample_cookie = $_COOKIE['fleekdash_analytics_sampled'] ?? null;

        if ($sample_cookie === null) {
            $included = ($sample_rate >= 1) ? 1 : ((mt_rand() / mt_getrandmax()) <= $sample_rate ? 1 : 0);
            setcookie('fleekdash_analytics_sampled', (string) $included, time() + 24 * 60 * 60, '/');
            return $included === 1;
        }

        return $sample_cookie !== '0';
    }
}
