<?php
/**
 * Premium functionality for PinnerPress
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

if (!defined('WPINC')) {
    die;
}

/**
 * Check if user has premium plan
 *
 * @since    0.1.0
 * @return   bool    True if premium, false if free
 */
function pinnerpress_is_premium() {
    if (!function_exists('pin_fs')) {
        return false;
    }

    // Check if user can use premium code (paid plan or active trial)
    return pin_fs()->can_use_premium_code();
}

/**
 * Enhanced feature detection with granular permissions
 *
 * @since    0.1.0
 * @param    string    $feature    Feature name to check
 * @return   bool                  True if feature is available
 */
function pinnerpress_is_feature_enabled($feature) {
    // Free features - always available
    $free_features = array(
        // Settings
        'general_settings',
        'pin_button_settings',
        'pin_button_customization',
        'call_out_banners',
        
        // Analytics - Limited
        'analytics_7_days',
        'analytics_chart',
        'analytics_summary',
        'analytics_top_posts',
        'post_analytics_top_25',
        'image_analytics_top_25',
        'image_analytics_stats',
    );
    
    // Premium features - require upgrade
    $premium_features = array(
        // Settings
        'follow_box',
        'image_banner',
        
        // Pinterest Profile Settings (only these two are premium)
        'disable_rich_pins',
        'enable_hidden_pins',
        
        // Analytics - Extended
        'analytics_30_days',
        'analytics_90_days',
        'analytics_custom_dates',
        'analytics_export_csv',
        'post_analytics_all_posts',
        'image_analytics_all_posts',
        
        // Chart filtering
        'analytics_hide_follow_stats',
        'analytics_hide_callout_stats',
        
        // Legacy features
        'analytics_unlimited',
        'rich_pins',
        'hidden_pins',
    );
    
    if (in_array($feature, $free_features, true)) {
        return true;
    }
    
    if (in_array($feature, $premium_features, true)) {
        return pinnerpress_is_premium();
    }
    
    // Unknown feature defaults to premium
    return pinnerpress_is_premium();
}

/**
 * Get date range limitations for free users
 */
function pinnerpress_get_max_date_range() {
    return pinnerpress_can_use_premium_features() ? 365 : 7; // 7 days for free/trial, unlimited for premium
}


/**
 * Filter analytics data based on plan limitations
 */
function pinnerpress_filter_analytics_data($data, $feature_context = '') {
    // Load the exact same analytics data for free and premium users.
    return $data;
}

/**
 * Get upgrade URL for premium features
 *
 * @since    0.1.0
 * @return   string    Upgrade URL
 */
function pinnerpress_get_upgrade_url() {
    if (!function_exists('pin_fs')) {
        return '#';
    }
    
    // Use Freemius upgrade URL for premium plans
    return pin_fs()->get_upgrade_url();
}

/**
 * Check if user is on a trial
 *
 * @since    0.6.8
 * @return   bool    True if on trial, false otherwise
 */
function pinnerpress_is_trial() {
    if (!function_exists('pin_fs')) {
        return false;
    }
    
    return pin_fs()->is_trial();
}

/**
 * Get trial expiry info
 *
 * @since    0.6.8
 * @return   array    Trial info including days left
 */
function pinnerpress_get_trial_info() {
    if (!function_exists('pin_fs')) {
        return array('is_trial' => false);
    }
    
    if (!pin_fs()->is_trial()) {
        return array('is_trial' => false);
    }
    
    $trial = pin_fs()->get_trial_plan();
    return array(
        'is_trial' => true,
        'days_left' => pin_fs()->get_trial_days_left(),
        'expires' => $trial
    );
}

/**
 * Check if user can use premium features (premium OR trial)
 *
 * @since    0.6.8
 * @return   bool    True if can use premium features
 */
function pinnerpress_can_use_premium_features() {
    if (!function_exists('pin_fs')) {
        return false;
    }

    return pin_fs()->can_use_premium_code();
}



/**
 * Display upgrade notice for locked features (now uses standardized notification)
 *
 * @since    0.1.0
 * @param    string    $feature_name    Name of the feature that's locked (legacy parameter, now ignored)
 * @return   string                     HTML for standardized upgrade notice
 */
function pinnerpress_get_upgrade_notice($feature_name = '') {
    // Use the standardized upgrade notification
    return pinnerpress_get_upgrade_notification();
}

/**
 * Filter analytics date range for free users (max 7 days)
 *
 * @since    0.1.0
 * @param    string    $start_date    Requested start date
 * @param    string    $end_date      Requested end date
 * @return   array                    Filtered date range [start_date, end_date]
 */
function pinnerpress_filter_analytics_date_range($start_date, $end_date) {
    // Check if user can use premium features (includes trial users)
    $can_use_premium = pinnerpress_can_use_premium_features();

    // Log the premium status for debugging
    $has_pin_fs = function_exists('pin_fs');
    $pin_fs_premium = $has_pin_fs ? (pin_fs()->is_premium() ? 'true' : 'false') : 'no_fs';
    $pin_fs_trial = $has_pin_fs ? (pin_fs()->is_trial() ? 'true' : 'false') : 'no_fs';


    // If user can use premium features, allow unlimited date ranges
    if ($can_use_premium) {
        return array($start_date, $end_date);
    }

    // For free users, always limit to last 7 days regardless of input
    $max_days_ago = gmdate('Y-m-d', strtotime('-7 days'));
    $today = gmdate('Y-m-d');


    // Always enforce 7-day limit for free users
    return array($max_days_ago, $today);
}

/**
 * Check if user has truly premium (paid) plan - excludes trial users
 *
 * @since    0.6.8
 * @return   bool    True if truly premium (paid), false if free or trial
 */
function pinnerpress_is_truly_premium() {
    if (!function_exists('pin_fs')) {
        return false;
    }
    
    // Only return true for paid premium plans, not trials
    return pin_fs()->is_premium() && !pin_fs()->is_trial();
}

/**
 * Get CSS classes for premium/locked elements
 *
 * @since    0.1.0
 * @param    string    $feature    Feature to check
 * @return   string               CSS classes
 */
function pinnerpress_get_premium_classes($feature) {
    $classes = array();
    
    if (!pinnerpress_is_feature_enabled($feature)) {
        $classes[] = 'pinnerpress-premium-only';
        $classes[] = 'pinnerpress-disabled';
    }
    
    return implode(' ', $classes);
}

/**
 * Wrap premium content with upgrade notice if not premium
 *
 * @since    0.1.0
 * @param    string    $content       Content to wrap
 * @param    string    $feature       Feature name
 * @param    string    $feature_label Feature label for upgrade notice
 * @return   string                   Wrapped content or upgrade notice
 */
function pinnerpress_wrap_premium_content($content, $feature, $feature_label = '') {
    if (pinnerpress_is_feature_enabled($feature)) {
        return $content;
    }
    
    // For non-premium users, show disabled content + upgrade notice
    $disabled_content = '<div class="pinnerpress-premium-disabled">' . $content . '</div>';
    $upgrade_notice = pinnerpress_get_upgrade_notice($feature_label);
    
    return $disabled_content . $upgrade_notice;
}

/**
 * Initialize Freemius pricing page
 *
 * @since    0.1.0
 */
function pinnerpress_init_freemius_pricing() {
    if (function_exists('pin_fs')) {
        // Add the pricing page to the menu
        add_action('admin_menu', function() {
            if (function_exists('pin_fs') && !pin_fs()->is_premium()) {
                // Add pricing submenu item under the main plugin menu
                add_submenu_page(
                    'pinnerpress',
                    __('Upgrade to Premium', 'pinnerpress'),
                    __('🔥 Upgrade', 'pinnerpress'),
                    'manage_options',
                    'pinnerpress-pricing',
                    function() {
                        // Redirect to Freemius pricing page
                        wp_redirect(pin_fs()->get_upgrade_url());
                        exit;
                    }
                );
            }
        }, 100);
    }
}
add_action('admin_init', 'pinnerpress_init_freemius_pricing');

/**
 * Fix Freemius asset URLs
 *
 * @since    0.1.0
 */
function pinnerpress_fix_freemius_asset_urls() {
    if (function_exists('pin_fs')) {
        // Universal asset URL fixer function
        $fix_asset_url = function($url) {
            // Handle null values
            if (is_null($url) || $url === false) {
                return '';
            }
            
            // For freemius-pricing.js, ensure it loads from the correct plugin path
            if (strpos((string)$url, 'freemius-pricing.js') !== false) {
                // Get the correct plugin URL
                $plugin_url = plugin_dir_url(dirname(__FILE__));
                return $plugin_url . 'vendor/freemius/wordpress-sdk/assets/js/pricing/freemius-pricing.js';
            }
            
            // Fix any URL that contains filesystem paths mixed with web paths
            if (strpos((string)$url, '/Users/') !== false || strpos((string)$url, 'C:\\') !== false) {
                // Extract just the vendor/freemius part and rebuild with plugin URL
                if (preg_match('#(vendor/freemius/.+)$#', $url, $matches)) {
                    $plugin_url = plugin_dir_url(dirname(__FILE__));
                    return $plugin_url . $matches[1];
                }
            }
            
            // Fix URLs that have the themes directory but should be plugin directory
            if (strpos((string)$url, '/wp-content/themes/') !== false && strpos((string)$url, 'vendor/freemius') !== false) {
                // Replace themes with the correct plugin path
                $plugin_url = plugin_dir_url(dirname(__FILE__));
                // Ensure plugin_url is not null
                if (empty($plugin_url)) {
                    $plugin_url = '';
                }
                // Extract everything after the incorrect themes path
                if (preg_match('#/wp-content/themes/[^/]+/(.*)$#', $url, $matches)) {
                    return $plugin_url . $matches[1];
                }
                // Fallback: use wp_str_replace if available, otherwise handle null safely
                if (function_exists('wp_str_replace')) {
                    $url = wp_str_replace('/wp-content/themes/', $plugin_url, $url);
                } else {
                    $url = str_replace('/wp-content/themes/', (string)$plugin_url, (string)$url);
                }
                // Clean up any double slashes
                $url = preg_replace('#/+#', '/', (string)$url);
                // Use wp_str_replace if available for protocol fix
                if (function_exists('wp_str_replace')) {
                    $url = wp_str_replace(':/', '://', $url);
                } else {
                    $url = str_replace(':/', '://', (string)$url);
                }
            }
            
            // Fix missing wordpress-sdk directory in Freemius URLs
            if (strpos((string)$url, 'vendor/freemius/assets/') !== false && strpos((string)$url, 'wordpress-sdk') === false) {
                if (function_exists('wp_str_replace')) {
                    $url = wp_str_replace('vendor/freemius/assets/', 'vendor/freemius/wordpress-sdk/assets/', $url);
                } else {
                    $url = str_replace('vendor/freemius/assets/', 'vendor/freemius/wordpress-sdk/assets/', (string)$url);
                }
            }
            
            return $url;
        };
        
        // Apply to specific Freemius asset filters
        add_filter('freemius_asset_url', $fix_asset_url, 10, 1);
        add_filter('pricing/css_path', $fix_asset_url, 10, 1);
        
        // Add a specific filter for the pricing JS path
        add_filter('freemius_pricing_js_path', function($path) {
            // Return the correct absolute file path for the pricing JS
            return dirname(__FILE__) . '/vendor/freemius/wordpress-sdk/assets/js/pricing/freemius-pricing.js';
        }, 10, 1);
        
        // Hook into WordPress asset loading to catch any remaining URLs
        add_filter('script_loader_src', function($src, $handle) use ($fix_asset_url) {
            // Handle null values
            if (is_null($src) || $src === false) {
                return '';
            }
            // Fix Freemius-related scripts
            if (strpos((string)$src, 'vendor/freemius') !== false || strpos((string)$handle, 'freemius') !== false) {
                return $fix_asset_url($src);
            }
            return $src;
        }, 10, 2);
        
        add_filter('style_loader_src', function($src, $handle) use ($fix_asset_url) {
            // Handle null values
            if (is_null($src) || $src === false) {
                return '';
            }
            // Fix Freemius-related stylesheets
            if (strpos((string)$src, 'vendor/freemius') !== false || strpos((string)$handle, 'freemius') !== false) {
                return $fix_asset_url($src);
            }
            return $src;
        }, 10, 2);
        
        // Add a general output buffer to catch and fix any remaining malformed URLs in HTML content
        add_action('wp_loaded', function() {
            // Check for admin page access with nonce verification
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only; value sanitized and used for control flow
            if (is_admin() && isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'pinnerpress-pricing') {
                ob_start(function($buffer) {
                    // Fix any remaining malformed URLs in the HTML output
                    $plugin_url = plugin_dir_url(dirname(__FILE__));
                    
                    // Pattern to match malformed URLs with filesystem paths
                    $patterns = [
                        // Fix URLs that have themes directory with absolute filesystem paths
                        '#(https?://[^/]+)/wp-content/themes/Users/[^/]+/Projects/[^/]+/pinnerpress-custom/(vendor/freemius/[^"\s\)]+)#',
                        '#(https?://[^/]+)/wp-content/themes/[^/]+/(vendor/freemius/[^"\s\)]+)#',
                        // Fix absolute filesystem paths that somehow got into URLs
                        '#/Users/[^/]+/Projects/[^/]+/pinnerpress-custom/(vendor/freemius/[^"\s\)]+)#',
                        // Fix any remaining malformed vendor/freemius paths
                        '#(https?://[^/]+)/[^"\s]*?(vendor/freemius/wordpress-sdk/assets/[^"\s\)]+)#'
                    ];
                    
                    foreach ($patterns as $pattern) {
                        $buffer = preg_replace($pattern, $plugin_url . '$2', $buffer);
                    }
                    
                    // Additional specific fix for CSS background-image URLs and JavaScript asset references
                    $buffer = preg_replace_callback(
                        '#(url\(|[\'""])((?:https?://[^/]+)?/wp-content/themes/[^/]+/vendor/freemius/[^"\s\)]+)([\'""]|\))#',
                        function($matches) use ($plugin_url) {
                            $prefix = $matches[1];
                            $suffix = $matches[3];
                            // Extract just the vendor/freemius part
                            if (preg_match('#(vendor/freemius/.+)$#', $matches[2], $vendorMatch)) {
                                return $prefix . $plugin_url . $vendorMatch[1] . $suffix;
                            }
                            return $matches[0];
                        },
                        $buffer
                    );
                    
                    // Add client-side JavaScript to fix URLs that are generated dynamically
                    $fix_script = "
                    <script type='text/javascript'>
                    (function() {
                        // Fix asset URLs that are being dynamically generated
                        var originalFetch = window.fetch;
                        var originalXMLHttpRequest = window.XMLHttpRequest.prototype.open;
                        var pluginUrl = '" . $plugin_url . "';
                        
                        // Function to fix malformed URLs
                        function fixFreemiusUrl(url) {
                            if (typeof url !== 'string') return url;
                            
                            // Fix themes path with filesystem paths
                            url = url.replace(/\/wp-content\/themes\/Users\/[^\/]+\/Projects\/[^\/]+\/pinnerpress-custom\/(vendor\/freemius\/[^\\s\\)]+)/g, pluginUrl + '$1');
                            url = url.replace(/\/wp-content\/themes\/[^\/]+\/(vendor\/freemius\/[^\\s\\)]+)/g, pluginUrl + '$1');
                            
                            return url;
                        }
                        
                        // Override fetch to fix URLs
                        window.fetch = function(url, options) {
                            url = fixFreemiusUrl(url);
                            return originalFetch.call(this, url, options);
                        };
                        
                        // Override XMLHttpRequest to fix URLs
                        window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
                            url = fixFreemiusUrl(url);
                            return originalXMLHttpRequest.call(this, method, url, async, user, password);
                        };
                        
                        // Fix any existing image src attributes
                        document.addEventListener('DOMContentLoaded', function() {
                            var images = document.querySelectorAll('img[src*=\"/wp-content/themes/\"]');
                            images.forEach(function(img) {
                                img.src = fixFreemiusUrl(img.src);
                            });
                        });
                    })();
                    </script>";
                    
                    // Add the script before the closing body tag
                    if (function_exists('wp_str_replace')) {
                        $buffer = wp_str_replace('</body>', $fix_script . '</body>', $buffer);
                    } else {
                        $buffer = str_replace('</body>', (string)$fix_script . '</body>', (string)$buffer);
                    }
                    
                    return $buffer;
                });
            }
        });
    }
}
add_action('init', 'pinnerpress_fix_freemius_asset_urls');

/**
 * Disable Freemius support forum submenu
 *
 * @since    0.1.0
 */
function pinnerpress_disable_support_forum_submenu() {
    if (function_exists('pin_fs')) {
        // Disable the support forum submenu
        pin_fs()->add_filter('support_forum_submenu', '__return_false');
        
        // Disable showing annual pricing in monthly format
        pin_fs()->add_filter('pricing/show_annual_in_monthly', '__return_false');
        
        // Also remove the submenu page entirely using WordPress hooks
        add_action('admin_menu', function() {
            remove_submenu_page('admin.php?page=pinnerpress', 'https://wordpress.org/support/plugin/pinnerpress');
        }, 999);
        
        // Add CSS to hide the support forum link if it still appears
        add_action('admin_head', function() {
            echo '<style>
                /* Hide Freemius support forum link */
                a[href="https://wordpress.org/support/plugin/pinnerpress"] {
                    display: none !important;
                }
                /* Hide the parent li if it becomes empty */
                li:has(> a[href="https://wordpress.org/support/plugin/pinnerpress"]) {
                    display: none !important;
                }
            </style>';
        });
    }
}
add_action('init', 'pinnerpress_disable_support_forum_submenu'); 