<?php
/**
 * New User Discount Code Handler
 * 
 * Provides 50% discount code for new users when they upgrade to Pro/Premium version
 * 
 * @package AI_Auto_Tool
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class AIAutoTool_NewUserDiscount {
    
    /**
     * Discount code for new users (50%)
     * You can change this code in Freemius Dashboard
     */
    const NEW_USER_DISCOUNT_CODE = 'NEWKCT50';
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Add coupon to $_GET when checkout is called
        add_action( 'admin_init', array( $this, 'add_coupon_to_request' ), 1 );
        
        // Use output buffering to modify pricing config in inline script
        add_action( 'admin_init', array( $this, 'start_output_buffering' ), 999 );
        
        // Add JavaScript to handle upgrade links
        add_action( 'admin_footer', array( $this, 'add_discount_js' ) );
        add_action( 'wp_footer', array( $this, 'add_discount_js' ) );
        
        // Display discount notice on pricing page
        add_action( 'admin_notices', array( $this, 'show_discount_notice' ) );
        
        // Use Freemius filters to add discount code
        // Must be called after 'init' hook to ensure aiautotool_premium() returns an object
        add_action( 'init', array( $this, 'register_freemius_filters' ), 20 );
        
        // Hook into pricing template to ensure coupon is passed (high priority to run early)
        add_action( 'admin_init', array( $this, 'ensure_coupon_in_pricing' ), 1 );
        
        // Hook into pricing config to ensure coupon is included
        // Note: This filter may not exist in all Freemius versions, so we also use direct $_GET manipulation
        add_filter( 'fs_pricing_query_params', array( $this, 'add_coupon_to_pricing_params' ), 10, 1 );
        
        // Filter pricing config directly (if available)
        // Since pricing.php merges $_GET into query_params, ensuring coupon is in $_GET should work
        // But we also add a filter to modify the config if needed
        add_filter( 'fs_pricing_config', array( $this, 'add_coupon_to_pricing_config' ), 10, 1 );
        
        // Inject coupon into pricing config via inline script as fallback
        add_action( 'admin_footer', array( $this, 'inject_coupon_into_pricing_config' ), 999 );
    }
    
    /**
     * Register Freemius filters
     * Called after 'init' hook to ensure aiautotool_premium() returns an object
     */
    public function register_freemius_filters() {
        // Use Freemius filters to add discount code
        if ( function_exists( 'aiautotool_premium' ) ) {
            $premium = aiautotool_premium();
            if ( $premium && is_object( $premium ) && method_exists( $premium, 'add_filter' ) ) {
                // Hook into checkout_url to add discount code
                $premium->add_filter( 'checkout_url', array( $this, 'add_discount_to_checkout_url' ), 10, 1 );
                
                // Hook into pricing_url to add discount code
                $premium->add_filter( 'pricing_url', array( $this, 'add_discount_to_pricing_url' ), 10, 1 );
            }
        }
    }
    
    /**
     * Add coupon to pricing config
     * This is called if the filter exists
     * 
     * @param array $config Pricing config array
     * @return array Modified config with coupon
     */
    public function add_coupon_to_pricing_config( $config ) {
        // Only apply if new user
        if ( ! $this->is_new_user() ) {
            return $config;
        }
        
        // Get coupon from $_GET or use default
        $coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
        
        if ( empty( $coupon ) ) {
            $coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        }
        
        // Ensure coupon is in config
        if ( ! empty( $coupon ) && ! isset( $config['coupon'] ) ) {
            $config['coupon'] = $coupon;
        }
        
        return $config;
    }
    
    /**
     * Inject coupon into pricing config via JavaScript
     */
    public function inject_coupon_into_pricing_config() {
        // Only on pricing page
        $page = isset( $_GET['page'] ) ? $_GET['page'] : '';
        if ( strpos( $page, 'pricing' ) === false ) {
            return;
        }
        
        // Only if new user
        if ( ! $this->is_new_user() ) {
            return;
        }
        
        // Get coupon
        $coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
        if ( empty( $coupon ) ) {
            $coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        }
        
        if ( empty( $coupon ) ) {
            return;
        }
        
        ?>
        <script type="text/javascript">
        (function() {
            var coupon = '<?php echo esc_js( $coupon ); ?>';
            console.log('AIAutoTool Discount: Coupon code:', coupon);
            
            // Method 1: Intercept Freemius.pricing.new() call
            if (typeof Freemius === 'undefined') {
                // Wait for Freemius to load
                var checkFreemius = setInterval(function() {
                    if (typeof Freemius !== 'undefined') {
                        clearInterval(checkFreemius);
                        interceptPricingNew();
                    }
                }, 100);
            } else {
                interceptPricingNew();
            }
            
            function interceptPricingNew() {
                // Override Freemius.pricing.new if it exists
                if (typeof Freemius !== 'undefined' && typeof Freemius.pricing !== 'undefined') {
                    var originalNew = Freemius.pricing.new;
                    Freemius.pricing.new = function(config) {
                        console.log('AIAutoTool Discount: Intercepted Freemius.pricing.new() with config:', config);
                        
                        // Add coupon to config if not present
                        if (!config.coupon && coupon) {
                            config.coupon = coupon;
                            console.log('AIAutoTool Discount: Added coupon to pricing config:', coupon);
                        } else if (config.coupon && config.coupon !== coupon) {
                            // Update coupon if different
                            config.coupon = coupon;
                            console.log('AIAutoTool Discount: Updated coupon in pricing config:', coupon);
                        }
                        
                        // Call original function
                        var result = originalNew.call(this, config);
                        
                        // Store instance for later use
                        if (result && typeof result === 'object') {
                            window.fsPricingInstance = result;
                            console.log('AIAutoTool Discount: Stored pricing instance');
                        }
                        
                        return result;
                    };
                    console.log('AIAutoTool Discount: Intercepted Freemius.pricing.new()');
                }
            }
            
            // Method 2: Modify inline script before execution
            function modifyInlineScript() {
                var scripts = document.querySelectorAll('script');
                for (var i = 0; i < scripts.length; i++) {
                    var script = scripts[i];
                    if (script.textContent && script.textContent.indexOf('Freemius.pricing.new') !== -1) {
                        try {
                            // Parse the JSON config
                            var match = script.textContent.match(/Freemius\.pricing\.new\s*\(\s*({[\s\S]*?})\s*\)/);
                            if (match && match[1]) {
                                try {
                                    var config = JSON.parse(match[1]);
                                    if (!config.coupon && coupon) {
                                        config.coupon = coupon;
                                        // Replace the config in script
                                        var newConfigStr = JSON.stringify(config);
                                        script.textContent = script.textContent.replace(
                                            /Freemius\.pricing\.new\s*\(\s*{[\s\S]*?}\s*\)/,
                                            'Freemius.pricing.new(' + newConfigStr + ')'
                                        );
                                        console.log('AIAutoTool Discount: Modified inline script with coupon');
                                    }
                                } catch(e) {
                                    console.warn('AIAutoTool Discount: Could not parse config JSON:', e);
                                }
                            }
                        } catch(e) {
                            console.error('AIAutoTool Discount: Error modifying script:', e);
                        }
                    }
                }
            }
            
            // Run immediately
            modifyInlineScript();
            
            // Also run after scripts load
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', modifyInlineScript);
            } else {
                setTimeout(modifyInlineScript, 100);
            }
            
            // Method 3: Apply coupon after pricing app loads
            function applyCouponAfterLoad() {
                // Wait for pricing wrapper to be ready
                var wrapper = document.querySelector('#fs_pricing_wrapper');
                if (!wrapper) {
                    console.log('AIAutoTool Discount: Pricing wrapper not found');
                    return;
                }
                
                var applied = false;
                var attempts = 0;
                var maxAttempts = 30;
                
                var tryApply = setInterval(function() {
                    attempts++;
                    console.log('AIAutoTool Discount: Attempt ' + attempts + ' to apply coupon');
                    
                    if (applied) {
                        clearInterval(tryApply);
                        return;
                    }
                    
                    // Method 3a: Find coupon input field and set value
                    var couponInputs = wrapper.querySelectorAll('input[type="text"][name*="coupon" i], input[type="text"][placeholder*="coupon" i], input[type="text"][placeholder*="code" i], input[type="text"][id*="coupon" i]');
                    if (couponInputs.length > 0) {
                        for (var i = 0; i < couponInputs.length; i++) {
                            var input = couponInputs[i];
                            if (input.value !== coupon) {
                                input.value = coupon;
                                // Trigger events
                                input.dispatchEvent(new Event('input', { bubbles: true }));
                                input.dispatchEvent(new Event('change', { bubbles: true }));
                                input.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true }));
                                
                                // Try to find and click apply button
                                var applyBtn = wrapper.querySelector('button[type="submit"], button:contains("Apply"), .fs-apply-coupon, button[class*="apply" i]');
                                if (applyBtn) {
                                    setTimeout(function() {
                                        applyBtn.click();
                                    }, 100);
                                }
                                
                                console.log('AIAutoTool Discount: Set coupon in input field and triggered events');
                                applied = true;
                                clearInterval(tryApply);
                                return;
                            }
                        }
                    }
                    
                    // Method 3b: Check if pricing app has loaded
                    if (typeof Freemius !== 'undefined' && typeof Freemius.pricing !== 'undefined') {
                        console.log('AIAutoTool Discount: Freemius.pricing available');
                        
                        // Try to find pricing instance in multiple ways
                        var pricingInstance = null;
                        
                        // Check wrapper
                        if (wrapper._fsPricing) {
                            pricingInstance = wrapper._fsPricing;
                            console.log('AIAutoTool Discount: Found pricing instance in wrapper._fsPricing');
                        }
                        
                        // Check window
                        if (!pricingInstance && window.fsPricingInstance) {
                            pricingInstance = window.fsPricingInstance;
                            console.log('AIAutoTool Discount: Found pricing instance in window.fsPricingInstance');
                        }
                        
                        // Check Freemius.pricing instances
                        if (!pricingInstance && Freemius.pricing.instances && Freemius.pricing.instances.length > 0) {
                            pricingInstance = Freemius.pricing.instances[0];
                            console.log('AIAutoTool Discount: Found pricing instance in Freemius.pricing.instances');
                        }
                        
                        if (pricingInstance) {
                            console.log('AIAutoTool Discount: Pricing instance found:', pricingInstance);
                            
                            // Try to apply coupon via method
                            if (typeof pricingInstance.applyCoupon === 'function') {
                                try {
                                    pricingInstance.applyCoupon(coupon);
                                    console.log('AIAutoTool Discount: Applied coupon via applyCoupon() method');
                                    applied = true;
                                    clearInterval(tryApply);
                                    return;
                                } catch(e) {
                                    console.warn('AIAutoTool Discount: Error calling applyCoupon():', e);
                                }
                            }
                            
                            // Try to set coupon in config
                            if (pricingInstance.config) {
                                pricingInstance.config.coupon = coupon;
                                console.log('AIAutoTool Discount: Set coupon in pricing instance config');
                                
                                // Try to trigger update
                                if (typeof pricingInstance.update === 'function') {
                                    pricingInstance.update();
                                }
                                if (typeof pricingInstance.render === 'function') {
                                    pricingInstance.render();
                                }
                                
                                applied = true;
                                clearInterval(tryApply);
                                return;
                            }
                            
                            // Try to call setCoupon if exists
                            if (typeof pricingInstance.setCoupon === 'function') {
                                try {
                                    pricingInstance.setCoupon(coupon);
                                    console.log('AIAutoTool Discount: Applied coupon via setCoupon() method');
                                    applied = true;
                                    clearInterval(tryApply);
                                    return;
                                } catch(e) {
                                    console.warn('AIAutoTool Discount: Error calling setCoupon():', e);
                                }
                            }
                        }
                        
                        // Method 3c: Try to find iframe and send message
                        var iframe = wrapper.querySelector('iframe');
                        if (iframe && iframe.contentWindow) {
                            try {
                                iframe.contentWindow.postMessage({
                                    type: 'apply_coupon',
                                    coupon: coupon
                                }, '*');
                                
                                iframe.contentWindow.postMessage({
                                    type: 'fs_apply_coupon',
                                    coupon: coupon
                                }, '*');
                                
                                iframe.contentWindow.postMessage({
                                    type: 'coupon',
                                    code: coupon
                                }, '*');
                                
                                console.log('AIAutoTool Discount: Sent postMessage to iframe');
                            } catch(e) {
                                console.warn('AIAutoTool Discount: Error sending postMessage:', e);
                            }
                        }
                    }
                    
                    // Method 3d: Try to find React component and update state
                    if (wrapper._reactInternalInstance || wrapper._reactInternalFiber) {
                        console.log('AIAutoTool Discount: React component found, trying to update state');
                        // This is more complex and may not work, but worth trying
                    }
                    
                    if (attempts >= maxAttempts) {
                        clearInterval(tryApply);
                        console.warn('AIAutoTool Discount: Max attempts reached, coupon may not be applied');
                        console.log('AIAutoTool Discount: Final state - wrapper:', wrapper, 'Freemius:', typeof Freemius);
                    }
                }, 500);
            }
            
            // Start applying coupon after load
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', applyCouponAfterLoad);
            } else {
                setTimeout(applyCouponAfterLoad, 1000);
            }
        })();
        </script>
        <?php
    }
    
    /**
     * Add coupon to pricing query parameters
     * 
     * @param array $params Query parameters
     * @return array Modified query parameters with coupon
     */
    public function add_coupon_to_pricing_params( $params ) {
        // Only apply if new user
        if ( ! $this->is_new_user() ) {
            return $params;
        }
        
        // Get coupon from $_GET or use default
        $coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
        
        if ( empty( $coupon ) ) {
            $coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        }
        
        // Ensure coupon is in params
        if ( ! empty( $coupon ) ) {
            $params['coupon'] = $coupon;
        }
        
        return $params;
    }
    
    /**
     * Ensure coupon is passed to pricing config
     * This runs early (priority 1) to ensure coupon is in $_GET before pricing.php template loads
     */
    public function ensure_coupon_in_pricing() {
        // Only apply on pricing page
        $page = isset( $_GET['page'] ) ? $_GET['page'] : '';
        if ( strpos( $page, 'pricing' ) === false ) {
            return;
        }
        
        // Only add if new user
        if ( ! $this->is_new_user() ) {
            return;
        }
        
        // Ensure coupon is in $_GET
        // This is critical because pricing.php merges $_GET into $query_params at line 58
        // which then gets merged into $pricing_config at line 105
        if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
            $discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
            $_GET['coupon'] = $discount_code;
            
            // Debug log
            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            }
        } else {
            // Debug log
            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            }
        }
    }
    
    /**
     * Display discount notice on pricing page
     */
    public function show_discount_notice() {
        // Only display on pricing page
        $screen = get_current_screen();
        if ( ! $screen || strpos( $screen->id, 'ai_auto_tool' ) === false ) {
            return;
        }
        
        // Check if it's pricing page
        $page = isset( $_GET['page'] ) ? $_GET['page'] : '';
        if ( strpos( $page, 'pricing' ) === false && strpos( $page, 'checkout' ) === false ) {
            return;
        }
        
        // Only display if new user
        if ( ! $this->is_new_user() ) {
            return;
        }
        
        $discount_code = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        
        if ( empty( $discount_code ) ) {
            return;
        }
        
        ?>
        <div class="notice notice-success is-dismissible aiautotool-discount-notice" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-left: 4px solid #ffc107; padding: 15px 20px; margin: 20px 0;">
            <div style="display: flex; align-items: center; color: white;">
                <div style="flex: 1;">
                    <h3 style="margin: 0 0 8px 0; color: white; font-size: 18px; font-weight: 700;">
                        🎉 <?php _e( 'Special Discount Code for New Users!', 'ai-auto-tool' ); ?>
                    </h3>
                    <p style="margin: 0; color: rgba(255, 255, 255, 0.95); font-size: 15px; line-height: 1.6;">
                        <?php 
                        printf(
                            __( 'You are applying discount code <strong style="background: rgba(255, 255, 255, 0.2); padding: 4px 8px; border-radius: 4px; font-family: monospace;">%s</strong> to get <strong>50%%</strong> off on your first purchase!', 'ai-auto-tool' ),
                            esc_html( $discount_code )
                        );
                        ?>
                    </p>
                </div>
            </div>
        </div>
        <style>
        .aiautotool-discount-notice {
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            border-radius: 8px;
        }
        .aiautotool-discount-notice .notice-dismiss {
            color: white;
        }
        .aiautotool-discount-notice .notice-dismiss:hover {
            color: #ffc107;
        }
        </style>
        <?php
    }
    
    /**
     * Add coupon to $_GET when checkout/pricing is called
     */
    public function add_coupon_to_request() {
        // Only add if new user
        if ( ! $this->is_new_user() ) {
            return;
        }
        
        // Check if on checkout or pricing page
        $page = isset( $_GET['page'] ) ? $_GET['page'] : '';
        $fs_action = isset( $_GET['fs_action'] ) ? $_GET['fs_action'] : '';
        
        // If on Freemius checkout/pricing page
        if ( strpos( $page, 'ai_auto_tool' ) !== false && 
             ( strpos( $page, 'pricing' ) !== false || strpos( $page, 'checkout' ) !== false ) ) {
            
            // Only add if coupon doesn't exist
            if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
                $discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
                $_GET['coupon'] = $discount_code;
                
                // Debug
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                }
            }
        }
        
        // Also add if fs_action exists
        if ( strpos( $fs_action, 'checkout' ) !== false || strpos( $fs_action, 'pricing' ) !== false ) {
            if ( ! isset( $_GET['coupon'] ) || empty( $_GET['coupon'] ) ) {
                $discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
                $_GET['coupon'] = $discount_code;
            }
        }
    }
    
    /**
     * Start output buffering to modify HTML
     */
    public function start_output_buffering() {
        // Only apply in admin and if new user
        if ( ! is_admin() || ! $this->is_new_user() ) {
            return;
        }
        
        ob_start( array( $this, 'modify_html_output' ) );
    }
    
    /**
     * Modify HTML output to add coupon to pricing config
     */
    public function modify_html_output( $buffer ) {
        if ( empty( $buffer ) ) {
            return $buffer;
        }
        
        // Only modify if we have a coupon
        $coupon = isset( $_GET['coupon'] ) ? sanitize_text_field( $_GET['coupon'] ) : '';
        if ( empty( $coupon ) ) {
            $coupon = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        }
        
        if ( empty( $coupon ) ) {
            return $buffer;
        }
        
        // Find and modify Freemius.pricing.new() call
        // Pattern: Freemius.pricing.new( {...config...} )
        $pattern = '/(Freemius\.pricing\.new\s*\(\s*)(\{[^}]*(?:\{[^}]*\}[^}]*)*\})(\s*\))/s';
        
        $buffer = preg_replace_callback( $pattern, function( $matches ) use ( $coupon ) {
            $before = $matches[1];
            $config_json = $matches[2];
            $after = $matches[3];
            
            try {
                // Parse JSON config
                $config = json_decode( $config_json, true );
                
                if ( is_array( $config ) && ! isset( $config['coupon'] ) ) {
                    // Add coupon to config
                    $config['coupon'] = $coupon;
                    
                    // Re-encode JSON
                    $new_config_json = json_encode( $config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
                    
                    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                    }
                    
                    return $before . $new_config_json . $after;
                } elseif ( is_array( $config ) && isset( $config['coupon'] ) ) {
                    // Coupon already exists, ensure it's correct
                    if ( $config['coupon'] !== $coupon ) {
                        $config['coupon'] = $coupon;
                        $new_config_json = json_encode( $config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
                        return $before . $new_config_json . $after;
                    }
                }
            } catch ( Exception $e ) {
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                }
            }
            
            return $matches[0];
        }, $buffer );
        
        // Also modify Freemius links (keep original functionality)
        $discount_code = $coupon;
        $patterns = array(
            // Links containing freemius.com
            '/(href=["\'])([^"\']*freemius\.com[^"\']*)(["\'])/i' => function( $matches ) use ( $discount_code ) {
                $url = $matches[2];
                // Check if coupon already exists
                if ( strpos( $url, 'coupon=' ) === false ) {
                    $separator = strpos( $url, '?' ) !== false ? '&' : '?';
                    $url = $url . $separator . 'coupon=' . urlencode( $discount_code );
                }
                return $matches[1] . $url . $matches[3];
            },
        );
        
        foreach ( $patterns as $pattern => $callback ) {
            $buffer = preg_replace_callback( $pattern, $callback, $buffer );
        }
        
        return $buffer;
    }
    
    /**
     * Check if user is a new user
     * 
     * @return bool True if new user, False otherwise
     */
    public function is_new_user() {
        if ( ! function_exists( 'aiautotool_premium' ) ) {
            return false;
        }
        
        $fs = aiautotool_premium();
        
        // New user is someone who:
        // 1. Has not registered with Freemius OR
        // 2. Does not have a valid license OR
        // 3. Has never purchased a license before
        
        // Check if registered with Freemius
        if ( ! $fs->is_registered() ) {
            return true; // Not registered = new user
        }
        
        // Check if has valid license
        if ( ! $fs->has_active_valid_license() ) {
            // Check if there's any expired or cancelled license
            $license = $fs->_get_license();
            
            // If no license = new user
            if ( ! is_object( $license ) ) {
                return true;
            }
            
            // If has license but expired and never renewed = could be new user
            // (Optional: you can skip this case if you want to apply only to those who never purchased)
            // return false; // If had license before then not a new user
        }
        
        // Check if discount code has been used before
        $discount_used = get_option( 'aiautotool_new_user_discount_used', false );
        if ( $discount_used ) {
            return false; // Already used discount
        }
        
        // Default: if no valid license = new user
        return ! $fs->has_active_valid_license();
    }
    
    /**
     * Check if URL is a Freemius checkout/pricing URL
     * 
     * @param string $url URL to check
     * @return bool True if Freemius URL, False otherwise
     */
    private function is_freemius_url( $url ) {
        if ( empty( $url ) ) {
            return false;
        }
        
        // Parse URL to get host and query
        $parsed_url = parse_url( $url );
        
        // Check if it's plugin admin pricing URL
        if ( isset( $parsed_url['query'] ) ) {
            parse_str( $parsed_url['query'], $query_params );
            // If it's plugin pricing page
            if ( isset( $query_params['page'] ) && strpos( $query_params['page'], 'ai_auto_tool' ) !== false && 
                 ( strpos( $query_params['page'], 'pricing' ) !== false || strpos( $query_params['page'], 'checkout' ) !== false ) ) {
                return true;
            }
        }
        
        // Check if URL contains page=ai_auto_tool-pricing
        if ( strpos( $url, 'page=ai_auto_tool-pricing' ) !== false || 
             strpos( $url, 'page=ai_auto_tool-checkout' ) !== false ) {
            return true;
        }
        
        if ( ! isset( $parsed_url['host'] ) ) {
            return false;
        }
        
        $host = strtolower( $parsed_url['host'] );
        
        // Check if it's Freemius domain
        $freemius_domains = array(
            'freemius.com',
            'checkout.freemius.com',
            'api.freemius.com',
            'dashboard.freemius.com'
        );
        
        foreach ( $freemius_domains as $domain ) {
            if ( strpos( $host, $domain ) !== false ) {
                return true;
            }
        }
        
        // Check if URL contains checkout or pricing path
        $path = isset( $parsed_url['path'] ) ? strtolower( $parsed_url['path'] ) : '';
        if ( strpos( $path, '/checkout' ) !== false || strpos( $path, '/pricing' ) !== false ) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Add discount code to checkout URL
     * 
     * @param string $url Original checkout URL
     * @return string Checkout URL with discount code (if new user)
     */
    public function add_discount_to_checkout_url( $url ) {
        // Only apply to this plugin
        if ( ! function_exists( 'aiautotool_premium' ) ) {
            return $url;
        }
        
        // Check if new user
        if ( ! $this->is_new_user() ) {
            return $url;
        }
        
        // Only add coupon to Freemius URLs, not internal admin URLs
        if ( ! $this->is_freemius_url( $url ) ) {
            return $url;
        }
        
        // Check if URL already has coupon (avoid duplicates)
        $parsed_url = parse_url( $url );
        if ( isset( $parsed_url['query'] ) ) {
            parse_str( $parsed_url['query'], $query_params );
            if ( isset( $query_params['coupon'] ) && ! empty( $query_params['coupon'] ) ) {
                return $url; // Already has coupon, don't add again
            }
        }
        
        // Add discount code to URL
        $discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        
        // Use WordPress function to add query parameter (safer and simpler)
        $new_url = add_query_arg( 'coupon', $discount_code, $url );
        
        // Debug (can be removed later)
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        }
        
        return $new_url;
    }
    
    /**
     * Add discount code to pricing URL
     * 
     * @param string $url Original pricing URL
     * @return string Pricing URL with discount code (if new user)
     */
    public function add_discount_to_pricing_url( $url ) {
        return $this->add_discount_to_checkout_url( $url );
    }
    
    /**
     * Mark discount code as used
     * (Call when user completes payment)
     */
    public function mark_discount_as_used() {
        update_option( 'aiautotool_new_user_discount_used', true );
    }
    
    /**
     * Reset discount status (for testing or to allow reuse)
     */
    public function reset_discount_status() {
        delete_option( 'aiautotool_new_user_discount_used' );
    }
    
    /**
     * Add JavaScript to handle upgrade links and add coupon
     */
    public function add_discount_js() {
        // Only add script if new user
        if ( ! $this->is_new_user() ) {
            return;
        }
        
        $discount_code = apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE );
        ?>
        <script type="text/javascript">
        (function() {
            var discountCode = '<?php echo esc_js( $discount_code ); ?>';
            
            // Ensure coupon is applied to Freemius pricing
            function applyCouponToFreemiusPricing() {
                // Get coupon from URL
                var urlParams = new URLSearchParams(window.location.search);
                var coupon = urlParams.get('coupon') || discountCode;
                
                if (!coupon) {
                    console.log('AIAutoTool Discount: No coupon found');
                    return;
                }
                
                console.log('AIAutoTool Discount: Attempting to apply coupon:', coupon);
                
                // Method 1: Try to find pricing instance
                var pricingWrapper = document.querySelector('#fs_pricing_wrapper');
                if (pricingWrapper) {
                    // Check if pricing instance exists
                    if (pricingWrapper._fsPricing) {
                        var pricing = pricingWrapper._fsPricing;
                        if (pricing && typeof pricing.applyCoupon === 'function') {
                            console.log('AIAutoTool Discount: Applying coupon via pricing instance');
                            pricing.applyCoupon(coupon);
                            return;
                        }
                    }
                    
                    // Method 2: Try to find iframe and send postMessage
                    var iframe = pricingWrapper.querySelector('iframe');
                    if (iframe && iframe.contentWindow) {
                        console.log('AIAutoTool Discount: Sending postMessage to iframe');
                        iframe.contentWindow.postMessage({
                            type: 'apply_coupon',
                            coupon: coupon
                        }, '*');
                        
                        // Also try Freemius message format
                        iframe.contentWindow.postMessage({
                            type: 'fs_apply_coupon',
                            coupon: coupon
                        }, '*');
                    }
                    
                    // Method 3: Try to find coupon input field and set value
                    var couponInput = pricingWrapper.querySelector('input[name="coupon"], input[type="text"][placeholder*="coupon" i], input[type="text"][placeholder*="code" i]');
                    if (couponInput) {
                        console.log('AIAutoTool Discount: Found coupon input, setting value');
                        couponInput.value = coupon;
                        // Trigger change event
                        var event = new Event('input', { bubbles: true });
                        couponInput.dispatchEvent(event);
                        // Try to find and click apply button
                        var applyBtn = pricingWrapper.querySelector('button[type="submit"], .fs-apply-coupon, button:contains("Apply")');
                        if (applyBtn) {
                            applyBtn.click();
                        }
                    }
                }
                
                // Method 4: Check if Freemius pricing has loaded
                if (typeof Freemius !== 'undefined' && typeof Freemius.pricing !== 'undefined') {
                    console.log('AIAutoTool Discount: Freemius.pricing available');
                    // Try to get pricing instance from global
                    if (window.fsPricingInstance && typeof window.fsPricingInstance.applyCoupon === 'function') {
                        console.log('AIAutoTool Discount: Applying via global instance');
                        window.fsPricingInstance.applyCoupon(coupon);
                    }
                }
            }
            
            // Function to add coupon to URL
            function addCouponToUrl(url) {
                if (!url || typeof url !== 'string') {
                    return url;
                }
                
                // Check if URL already has coupon
                if (url.indexOf('coupon=') !== -1) {
                    return url;
                }
                
                // Add coupon to Freemius URL
                if (url.indexOf('freemius.com') !== -1 || 
                    url.indexOf('checkout.freemius.com') !== -1) {
                    var separator = url.indexOf('?') !== -1 ? '&' : '?';
                    return url + separator + 'coupon=' + encodeURIComponent(discountCode);
                }
                
                // Add coupon to plugin admin pricing URL
                if (url.indexOf('page=ai_auto_tool-pricing') !== -1 || 
                    url.indexOf('page=ai_auto_tool-checkout') !== -1) {
                    var separator = url.indexOf('?') !== -1 ? '&' : '?';
                    return url + separator + 'coupon=' + encodeURIComponent(discountCode);
                }
                
                return url;
            }
            
            // Function to process all links
            function processLinks() {
                var links = document.querySelectorAll('a[href*="freemius.com"], a[href*="checkout"], a[href*="pricing"], a[href*="ai_auto_tool-pricing"], .fs-upgrade, .button-upgrade, .aiautotool_btn_upgradepro');
                
                for (var i = 0; i < links.length; i++) {
                    var link = links[i];
                    var href = link.getAttribute('href');
                    
                    if (href) {
                        var newHref = addCouponToUrl(href);
                        if (newHref !== href) {
                            link.setAttribute('href', newHref);
                        }
                    }
                }
            }
            
            // Run immediately when script loads
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    processLinks();
                    applyCouponToFreemiusPricing();
                    
                    // Handle link clicks
                    document.addEventListener('click', function(e) {
                        var target = e.target;
                        while (target && target.tagName !== 'A') {
                            target = target.parentElement;
                        }
                        
                        if (target && target.href) {
                            var newHref = addCouponToUrl(target.href);
                            if (newHref !== target.href) {
                                e.preventDefault();
                                window.location.href = newHref;
                                return false;
                            }
                        }
                    }, true);
                });
            } else {
                processLinks();
                applyCouponToFreemiusPricing();
            }
            
            // Try to apply coupon multiple times with increasing delays
            var retryCount = 0;
            var maxRetries = 10;
            var retryInterval = 500;
            
            function retryApplyCoupon() {
                if (retryCount < maxRetries) {
                    setTimeout(function() {
                        applyCouponToFreemiusPricing();
                        retryCount++;
                        retryApplyCoupon();
                    }, retryInterval);
                }
            }
            
            // Start retrying
            retryApplyCoupon();
            
            // Listen for messages from Freemius iframe
            window.addEventListener('message', function(event) {
                if (event.data) {
                    // Check for various Freemius message types
                    if (event.data.type === 'fs_pricing_loaded' || 
                        event.data.type === 'pricing_loaded' ||
                        event.data.type === 'fs_ready' ||
                        (event.data.type && event.data.type.indexOf('pricing') !== -1)) {
                        console.log('AIAutoTool Discount: Received pricing loaded message');
                        setTimeout(applyCouponToFreemiusPricing, 500);
                    }
                }
            });
            
            // Also listen for DOM changes in pricing wrapper
            if (document.querySelector('#fs_pricing_wrapper')) {
                var observer = new MutationObserver(function(mutations) {
                    applyCouponToFreemiusPricing();
                });
                
                observer.observe(document.querySelector('#fs_pricing_wrapper'), {
                    childList: true,
                    subtree: true,
                    attributes: true
                });
            }
            
            // Handle dynamically added links
            var observer = new MutationObserver(function(mutations) {
                processLinks();
            });
            
            if (document.body) {
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            } else {
                document.addEventListener('DOMContentLoaded', function() {
                    observer.observe(document.body, {
                        childList: true,
                        subtree: true
                    });
                });
            }
        })();
        </script>
        <?php
    }
    
    /**
     * Get discount code information for new users
     * 
     * @return array Discount code information
     */
    public function get_discount_info() {
        return array(
            'code' => apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE ),
            'percentage' => 50,
            'is_available' => $this->is_new_user(),
            'message' => $this->is_new_user() 
                ? sprintf( 
                    __( 'You are a new user! Use code <strong>%s</strong> to get 50%% off', 'ai-auto-tool' ),
                    apply_filters( 'aiautotool_new_user_discount_code', self::NEW_USER_DISCOUNT_CODE )
                )
                : __( 'Discount code only applies to new users', 'ai-auto-tool' )
        );
    }
}

// Khởi tạo class
if ( class_exists( 'AIAutoTool_NewUserDiscount' ) ) {
    new AIAutoTool_NewUserDiscount();
}


