<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/admin
 */
if (!class_exists('PinnerPress_Admin')) {
class PinnerPress_Admin {

    /**
     * The ID of this plugin.
     *
     * @since    0.1.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    0.1.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    0.1.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;
        
        // Register AJAX actions
        add_action('wp_ajax_pinnerpress_get_preview_button', array($this, 'get_preview_button_ajax'));
        add_action('wp_ajax_pinnerpress_dismiss_activation_notice', array($this, 'dismiss_activation_notice_ajax'));
        
        // Register the reset settings action
        add_action('admin_init', array($this, 'process_settings_reset'));
        
        // Add meta box for post-specific settings
        add_action('add_meta_boxes', array($this, 'add_pinnerpress_meta_box'));
        add_action('save_post', array($this, 'save_pinnerpress_meta_box'));
        
        // Handle settings page redirects before any output
        add_action('current_screen', array($this, 'handle_settings_redirects'));
        
        // Add admin notices
        add_action('admin_notices', array($this, 'show_activation_notice'));
        
        // Handle direct access to reset analytics page (fallback for production sites)
        add_action('admin_init', array($this, 'handle_reset_analytics_direct_access'), 5);
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    0.1.0
     */
    public function enqueue_styles() {
        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/pinnerpress-admin.css', array(), $this->version, 'all');
        
        // Add WordPress color picker styles
        wp_enqueue_style('wp-color-picker');

        // Fix Freemius modal CSS issue by manually loading the required CSS files
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reading admin navigation params for conditional enqueues
        if (
            (
                isset($_GET['page']) && !empty($_GET['page']) && // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin navigation
                strpos((string) sanitize_text_field(wp_unslash($_GET['page'])), 'plugins') !== false // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin navigation
            ) || 
            (
                isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF']) && // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for current script in admin area
                strpos((string) sanitize_text_field(wp_unslash($_SERVER['PHP_SELF'])), 'plugins.php') !== false
            )
        ) {
            
            $freemius_css_base = plugin_dir_url(dirname(__FILE__)) . 'vendor/freemius/assets/css/admin/';
            
            wp_enqueue_style(
                'freemius-dialog-boxes', 
                $freemius_css_base . 'dialog-boxes.css', 
                array(), 
                '2.12.0', 
                'all'
            );
            
            wp_enqueue_style(
                'freemius-optout', 
                $freemius_css_base . 'optout.css', 
                array(), 
                '2.12.0', 
                'all'
            );
            
            wp_enqueue_style(
                'freemius-common', 
                $freemius_css_base . 'common.css', 
                array(), 
                '2.12.0', 
                'all'
            );
        }
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    0.1.0
     */
    public function enqueue_scripts() {
        wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/pinnerpress-admin.js', array('jquery', 'wp-color-picker'), $this->version, false);
        
        // Add WordPress media scripts
        wp_enqueue_media();
        
        // Note: External CDN resources removed to comply with WordPress plugin directory requirements
        // Chart.js and Select2 functionality will be limited until local versions are added
        
        // Enqueue local scripts only
        $screen = get_current_screen();
        if ($screen && $screen->id === 'toplevel_page_pinnerpress') {
            wp_enqueue_script('chart-js', plugin_dir_url(__FILE__) . 'vendor/chart.js/chart.min.js', array(), '3.9.1', true);
            
            // Localize script to provide AJAX URL and nonce for main dashboard
            wp_localize_script('chart-js', 'pinnerpress_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
                'debug_enabled' => WP_DEBUG,
                'pluginUrl' => plugin_dir_url(__FILE__),
                'siteUrl' => site_url('/'),
                'is_premium' => pinnerpress_is_premium(),
                'is_truly_premium' => function_exists('pinnerpress_is_truly_premium') ? pinnerpress_is_truly_premium() : false
            ));
        }
        
        // Enqueue Select2 for image analytics page
        // Check both screen ID and page parameter for better compatibility
        $is_image_analytics_page = false;
        if ($screen && (
            $screen->id === 'pinnerpress_page_pinnerpress-image-analytics' || 
            strpos($screen->id, 'pinnerpress-image-analytics') !== false
        )) {
            $is_image_analytics_page = true;
        }
        
        // Also check page parameter as fallback
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only
        if (!$is_image_analytics_page && isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'pinnerpress-image-analytics') {
            $is_image_analytics_page = true;
        }
        
        if ($is_image_analytics_page) {
            // Enqueue Select2 CSS
            wp_enqueue_style('select2', plugin_dir_url(__FILE__) . 'vendor/select2/select2.min.css', array(), '4.1.0-rc.0');

            // Enqueue Select2 JS
            wp_enqueue_script('select2', plugin_dir_url(__FILE__) . 'vendor/select2/select2.min.js', array('jquery'), '4.1.0-rc.0', true);

            // Enqueue custom image analytics JS
            wp_enqueue_script('pinnerpress-image-analytics', plugin_dir_url(__FILE__) . 'js/pinnerpress-image-analytics.js', array('jquery', 'select2'), $this->version, true);

            // Localize script to provide AJAX URL and nonce
            wp_localize_script('pinnerpress-image-analytics', 'pinnerpress_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
                'debug_enabled' => WP_DEBUG,
                'pluginUrl' => plugin_dir_url(__FILE__),
                'siteUrl' => site_url('/'),
                'is_premium' => pinnerpress_is_premium(),
                'is_truly_premium' => function_exists('pinnerpress_is_truly_premium') ? pinnerpress_is_truly_premium() : false
            ));
        }

        // Enqueue assets for top images page
        $is_top_images_page = false;
        if ($screen && (
            $screen->id === 'pinnerpress_page_pinnerpress-top-images' ||
            strpos($screen->id, 'pinnerpress-top-images') !== false
        )) {
            $is_top_images_page = true;
        }

        // Also check page parameter as fallback
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only
        if (!$is_top_images_page && isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'pinnerpress-top-images') {
            $is_top_images_page = true;
        }

        if ($is_top_images_page) {
            // Enqueue Select2 CSS
            wp_enqueue_style('select2', plugin_dir_url(__FILE__) . 'vendor/select2/select2.min.css', array(), '4.1.0-rc.0');

            // Enqueue Select2 JS
            wp_enqueue_script('select2', plugin_dir_url(__FILE__) . 'vendor/select2/select2.min.js', array('jquery'), '4.1.0-rc.0', true);

            // Enqueue custom top images JS
            wp_enqueue_script('pinnerpress-top-images', plugin_dir_url(__FILE__) . 'js/pinnerpress-top-images.js', array('jquery', 'select2'), $this->version, true);

            // Localize script to provide AJAX URL and nonce
            wp_localize_script('pinnerpress-top-images', 'pinnerpress_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
                'debug_enabled' => WP_DEBUG,
                'pluginUrl' => plugin_dir_url(__FILE__),
                'siteUrl' => site_url('/'),
                'is_premium' => pinnerpress_is_premium(),
                'is_truly_premium' => function_exists('pinnerpress_is_truly_premium') ? pinnerpress_is_truly_premium() : false
            ));
        }

        // Check for post analytics page
        $is_post_analytics_page = false;
        if ($screen && (
            $screen->id === 'pinnerpress_page_pinnerpress-post-analytics' || 
            strpos($screen->id, 'pinnerpress-post-analytics') !== false
        )) {
            $is_post_analytics_page = true;
        }
        
        // Also check page parameter as fallback
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only
        if (!$is_post_analytics_page && isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'pinnerpress-post-analytics') {
            $is_post_analytics_page = true;
        }
        
        if ($is_post_analytics_page) {
            // Enqueue Chart.js for post analytics
            wp_enqueue_script('chart-js', plugin_dir_url(__FILE__) . 'vendor/chart.js/chart.min.js', array(), '3.9.1', true);
            
            // Enqueue custom post analytics JS
            wp_enqueue_script('pinnerpress-post-analytics', plugin_dir_url(__FILE__) . 'js/pinnerpress-post-analytics.js', array('jquery'), $this->version, true);
            
            // Localize script to provide AJAX URL and nonce
            wp_localize_script('pinnerpress-post-analytics', 'pinnerpress_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'admin_url' => admin_url(),
                'nonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
                'debug_enabled' => WP_DEBUG,
                'pluginUrl' => plugin_dir_url(__FILE__),
                'siteUrl' => site_url('/'),
                'is_premium' => pinnerpress_is_premium(),
                'is_truly_premium' => function_exists('pinnerpress_is_truly_premium') ? pinnerpress_is_truly_premium() : false
            ));
        }
        
        // Also enqueue Chart.js for the analytics page
        if ($screen && $screen->id === 'pinnerpress_page_pinnerpress-analytics') {
            wp_enqueue_script('chart-js', plugin_dir_url(__FILE__) . 'vendor/chart.js/chart.min.js', array(), '3.9.1', true);
        }
        
        // Check for debug parameter
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Debug flag read only
        $debug_enabled = isset($_GET['pinnerpress_debug']) && sanitize_text_field(wp_unslash($_GET['pinnerpress_debug'])) === '1';
        
        // Localize the script with data
        wp_localize_script($this->plugin_name, 'pinnerpressVars', array(
            'debug_enabled' => $debug_enabled,
            'ajaxurl' => admin_url('admin-ajax.php'),
            'pluginUrl' => esc_url(plugin_dir_url(__FILE__)),
            'siteUrl' => site_url('/'),
            'previewNonce' => wp_create_nonce('pinnerpress_preview_nonce'),
            'analyticsNonce' => wp_create_nonce('pinnerpress_analytics_nonce'),
            'confirmRemoveImage' => __('Are you sure you want to remove this hidden Pinterest image?', 'pinnerpress'),
            'hiddenPinsEnabled' => get_option('pinnerpress_enable_hidden_pins', '0') === '1',
            'isPremium' => pinnerpress_is_premium()
        ));
        
        // Enqueue Block Editor script on post edit screens
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        
        // Check for edit action in GET parameters (for script enqueuing only, not form processing)
        $action_param = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only used for script enqueuing, not form processing
        
        if (
            // Classic way to check for Gutenberg
            (function_exists('is_gutenberg_page') && is_gutenberg_page()) || 
            // Modern way to check for block editor
            ($screen && method_exists($screen, 'is_block_editor') && $screen->is_block_editor()) ||
            // Simple check for edit screens
            (is_admin() && $action_param === 'edit')
        ) {
            // Only load for premium users
            if (pinnerpress_is_premium()) {
                wp_enqueue_script(
                    $this->plugin_name . '-block-editor',
                    plugin_dir_url(__FILE__) . 'js/pinnerpress-block-editor.js',
                    array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-compose', 'wp-hooks'),
                    $this->version,
                    true
                );
            }
        }
        
        // Check for migration settings page
        $is_migration_page = false;
        if ($screen && (
            $screen->id === 'toplevel_page_pinnerpress-settings' || 
            strpos($screen->id, 'pinnerpress-settings') !== false
        )) {
            // Check if we're on the migration tab
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only
            if (isset($_GET['tab']) && sanitize_text_field(wp_unslash($_GET['tab'])) === 'migration') {
                $is_migration_page = true;
            }
        }
        
        if ($is_migration_page) {
            // Enqueue migration script
            wp_enqueue_script(
                'pinnerpress-migration', 
                plugin_dir_url(__FILE__) . 'js/pinnerpress-migration.js', 
                array('jquery'), 
                $this->version, 
                true
            );
            
            // Localize script with necessary variables
            wp_localize_script('pinnerpress-migration', 'pinnerpress_migration_vars', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('pinnerpress_admin_nonce'),
                'scanning' => __('Scanning...', 'pinnerpress'),
                'scan_button_text' => __('Scan for Hubbub Data', 'pinnerpress'),
                'scan_error' => __('Error scanning for Hubbub data.', 'pinnerpress'),
                'ajax_error' => __('AJAX request failed.', 'pinnerpress'),
                'scan_results_title' => __('Scan Results', 'pinnerpress'),
                'hubbub_active' => __('Hubbub plugin is active', 'pinnerpress'),
                'hubbub_inactive' => __('Hubbub plugin is not active', 'pinnerpress'),
                'settings_found' => __('Hubbub settings found', 'pinnerpress'),
                'pinterest_url_found' => __('Pinterest URL found', 'pinnerpress'),
                'no_pinterest_url' => __('No Pinterest username/URL found in Hubbub settings', 'pinnerpress'),
                'posts_with_images' => __('Posts with hidden images', 'pinnerpress'),
                'total_images' => __('Total hidden images', 'pinnerpress'),
                'hubbub_settings_details' => __('Hubbub Settings Details', 'pinnerpress'),
                'migration_confirm' => __('Are you sure you want to migrate from Hubbub? This will import settings and hidden images to PinnerPress.', 'pinnerpress'),
                'migration_starting' => __('Starting migration...', 'pinnerpress'),
                'migration_complete' => __('Migration completed!', 'pinnerpress'),
                'migration_failed' => __('Migration failed', 'pinnerpress'),
                'migration_error' => __('Error during migration.', 'pinnerpress'),
                'migration_results_title' => __('Migration Results', 'pinnerpress'),
                'settings_migration_success' => __('Settings migration successful', 'pinnerpress'),
                'settings_migration_failed' => __('Settings migration failed', 'pinnerpress'),
                'images_migration_success' => __('Hidden images migration successful', 'pinnerpress'),
                'images_migration_failed' => __('Hidden images migration failed', 'pinnerpress'),
                'migrated_posts' => __('Migrated posts', 'pinnerpress'),
                'migrated_images' => __('Migrated images', 'pinnerpress')
            ));
        }
    }
    
    /**
     * AJAX function to get HTML for preview button
     * 
     * @since    0.1.0
     */
    public function get_preview_button_ajax() {
        // Check nonce for security
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'pinnerpress_preview_nonce')) {
            wp_die('Security check failed');
        }
        
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        // Get parameters from POST with proper sanitization and unslashing
        $options = array(
            'position' => isset($_POST['position']) ? sanitize_text_field(wp_unslash($_POST['position'])) : 'top-left',
            'shape' => isset($_POST['shape']) ? sanitize_text_field(wp_unslash($_POST['shape'])) : 'rectangular',
            'size' => isset($_POST['size']) ? sanitize_text_field(wp_unslash($_POST['size'])) : 'medium',
            'color' => isset($_POST['color']) ? sanitize_text_field(wp_unslash($_POST['color'])) : '#E60023',
            'text_color' => isset($_POST['text_color']) ? sanitize_text_field(wp_unslash($_POST['text_color'])) : '#FFFFFF',
            'image_shadow' => isset($_POST['image_shadow']) ? sanitize_text_field(wp_unslash($_POST['image_shadow'])) : '0',
            'custom_button_text' => isset($_POST['custom_button_text']) ? sanitize_text_field(wp_unslash($_POST['custom_button_text'])) : '',
            'default_text' => __('Pin It', 'pinnerpress'),
            'button_style' => isset($_POST['button_style']) ? sanitize_text_field(wp_unslash($_POST['button_style'])) : 'default'
        );
        
        // Generate a unique ID for this button instance to help prevent duplication
        $unique_id = 'preview-' . time() . '-' . wp_rand(1000, 9999);
        $options['unique_id'] = $unique_id;
        
        // Generate button HTML
        $button_html = pinnerpress_get_pin_button_html($options, true);
        
        // Return button HTML directly without filtering since this is admin-only
        // and we control the HTML generation
        echo $button_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Admin preview HTML is generated internally
        wp_die(); // Required to terminate properly
    }
    
    /**
     * Show activation notice to configure the plugin
     * 
     * @since    0.1.0
     */
    public function show_activation_notice() {
        // Only show to users who can manage options
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check if notice has been dismissed
        if (get_option('pinnerpress_activation_notice_dismissed', '0') === '1') {
            return;
        }
        
        // Check if plugin has been configured (has Pinterest URL)
        $pinterest_url = get_option('pinnerpress_pinterest_url', '');
        if (!empty($pinterest_url)) {
            // Plugin is configured, auto-dismiss the notice
            update_option('pinnerpress_activation_notice_dismissed', '1');
            return;
        }
        
        // Show the notice
        ?>
        <div class="notice notice-info is-dismissible pinnerpress-activation-notice">
            <p>
                <strong><?php esc_html_e('PinnerPress is almost ready!', 'pinnerpress'); ?></strong>
                <?php
                printf(
                    /* translators: %1$s: Link to settings page, %2$s: Link to migration tab */
                    esc_html__('To get started, please %1$s to configure your Pinterest account and customize your settings. You can also %2$s to import settings from other Pinterest plugins.', 'pinnerpress'),
                    '<a href="' . esc_url(admin_url('admin.php?page=pinnerpress-settings&tab=general')) . '">' . esc_html__('visit the settings page', 'pinnerpress') . '</a>',
                    '<a href="' . esc_url(admin_url('admin.php?page=pinnerpress-settings&tab=migration')) . '">' . esc_html__('import settings from other plugins', 'pinnerpress') . '</a>'
                );
                ?>
            </p>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $(document).on('click', '.pinnerpress-activation-notice .notice-dismiss', function() {
                $.post(ajaxurl, {
                    action: 'pinnerpress_dismiss_activation_notice',
                    nonce: '<?php echo esc_js(wp_create_nonce('pinnerpress_dismiss_activation_notice')); ?>'
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * AJAX function to dismiss the activation notice
     * 
     * @since    0.1.0
     */
    public function dismiss_activation_notice_ajax() {
        // Check nonce for security
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'pinnerpress_dismiss_activation_notice')) {
            wp_die('Security check failed');
        }
        
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        // Save the dismissal option
        update_option('pinnerpress_activation_notice_dismissed', '1');
        
        wp_send_json_success('Activation notice dismissed');
    }
    
    /**
     * Register the administration menu for this plugin.
     *
     * @since    0.1.0
     */
    public function add_plugin_admin_menu() {
        
        // Add a top level menu item - now pointing to analytics page
        add_menu_page(
            __('PinnerPress Analytics', 'pinnerpress'), 
            __('PinnerPress', 'pinnerpress'), 
            'manage_options', 
            $this->plugin_name, 
            array($this, 'display_plugin_analytics_page'), 
            plugin_dir_url(__FILE__) . 'images/pinnerpress-icon.svg',
            30
        );
        
        // Add analytics as first submenu item (same as parent menu)
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Analytics', 'pinnerpress'), 
            __('Dashboard', 'pinnerpress'), 
            'manage_options', 
            $this->plugin_name, 
            array($this, 'display_plugin_analytics_page')
        );

        // Add post analytics submenu item as second item - show for all users
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Post Analytics', 'pinnerpress'),
            __('Post Analytics', 'pinnerpress'),
            'manage_options',
            $this->plugin_name . '-post-analytics',
            array($this, 'display_plugin_post_analytics_page')
        );

        // Add image analytics submenu item as third item - show for all users
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Image Analytics', 'pinnerpress'),
            __('Image Analytics', 'pinnerpress'),
            'manage_options',
            $this->plugin_name . '-image-analytics',
            array($this, 'display_plugin_image_analytics_page')
        );

        // Add top images submenu item - show for all users
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Top Images', 'pinnerpress'),
            __('Top Images', 'pinnerpress'),
            'manage_options',
            $this->plugin_name . '-top-images',
            array($this, 'display_plugin_top_images_page')
        );

        // Add settings submenu item
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Settings', 'pinnerpress'), 
            __('Settings', 'pinnerpress'), 
            'manage_options', 
            $this->plugin_name . '-settings', 
            array($this, 'display_plugin_settings_page')
        );
        
        // Add support submenu item
        add_submenu_page(
            $this->plugin_name,
            __('PinnerPress Support', 'pinnerpress'), 
            __('Support', 'pinnerpress'), 
            'manage_options', 
            $this->plugin_name . '-support', 
            array($this, 'display_plugin_support_page')
        );
        
        // Add debug submenu item (only for admins) - hidden from menu
        if (current_user_can('manage_options')) {
            add_submenu_page(
                null, // No parent menu - makes it hidden
                __('PinnerPress Debug', 'pinnerpress'), 
                __('Debug', 'pinnerpress'), 
                'manage_options', 
                $this->plugin_name . '-debug', 
                array($this, 'display_plugin_debug_page')
            );
        }
        
        // Register the hidden reset analytics page with a delay to ensure compatibility
        $admin_instance = $this;
        add_action('admin_menu', function() use ($admin_instance) {
            // Hidden reset page - not shown in menu
            add_submenu_page(
                null, // No parent menu - makes it hidden
                __('Reset Analytics', 'pinnerpress'),
                __('Reset Analytics', 'pinnerpress'),
                'manage_options',
                'pinnerpress-reset-analytics',
                array($admin_instance, 'display_reset_analytics_page')
            );
        }, 999); // High priority to ensure it runs after Freemius
    }
    
    /**
     * Register plugin settings
     *
     * @since    0.1.0
     */
    public function register_plugin_settings() {
        // General Tab - Pinterest Profile Settings
        register_setting('pinnerpress_settings_general', 'pinnerpress_pinterest_url', array(
            'sanitize_callback' => array($this, 'sanitize_pinterest_url')
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_pinterest_display_name', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_profile_image', array(
            'sanitize_callback' => 'esc_url_raw'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_disable_rich_pins', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_enable_hidden_pins', array(
            'sanitize_callback' => 'absint'
        ));
        
        // Follow Button Default Settings
        register_setting('pinnerpress_settings_general', 'pinnerpress_follow_button_default_text', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_follow_button_default_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_follow_button_default_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));

        // Settings Tab - Pin Button
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_pin_button_status', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_style', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_position', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_shape', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_size', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_hover_button_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_image_shadow', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_custom_button_text', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));

        // Custom CSS selectors for Pin Button (deprecated - keeping for backwards compatibility)
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_pin_button_custom_selectors_enabled', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_pin_button_custom_selectors', array(
            'sanitize_callback' => 'sanitize_textarea_field'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_pin_button_find_images_in_selectors', array(
            'sanitize_callback' => 'absint'
        ));

        // Unified Custom CSS Selectors (Filters Tab)
        register_setting('pinnerpress_settings_filters', 'pinnerpress_custom_selectors_enabled', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_custom_selectors', array(
            'sanitize_callback' => 'sanitize_textarea_field'
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_find_images_in_selectors', array(
            'sanitize_callback' => 'absint'
        ));

        // Category Filter Settings (Filters Tab)
        register_setting('pinnerpress_settings_filters', 'pinnerpress_category_filter_pin_buttons', array(
            'sanitize_callback' => array($this, 'sanitize_checkbox')
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_category_filter_image_banners', array(
            'sanitize_callback' => array($this, 'sanitize_checkbox')
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_category_filter_call_out_banners', array(
            'sanitize_callback' => array($this, 'sanitize_checkbox')
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_category_filter_follow_boxes', array(
            'sanitize_callback' => array($this, 'sanitize_checkbox')
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_excluded_categories', array(
            'sanitize_callback' => array($this, 'sanitize_category_exclusions')
        ));

        // Minimum Image Size Settings (Filters Tab)
        register_setting('pinnerpress_settings_filters', 'pinnerpress_size_filter_pin_buttons', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_size_filter_image_banners', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_minimum_image_size', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_filters', 'pinnerpress_exclude_gallery_minimum', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));

        // Category exclusions for Pin Button
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_pin_button_excluded_categories', array(
            'sanitize_callback' => array($this, 'sanitize_category_exclusions')
        ));

        // Rich Pins (part of Pin Button tab)
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_enable_rich_pins', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_rich_pins_article', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_rich_pins_recipe', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_pin_button', 'pinnerpress_rich_pins_product', array(
            'sanitize_callback' => 'absint'
        ));
        
        // Follow Box Tab
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_box_status', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_account_description', array(
            'sanitize_callback' => 'sanitize_textarea_field'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_button_bg_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_button_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_box_display_pin_click', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_box_display_page_load', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_box_allow_dismiss', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_header_image', array(
            'sanitize_callback' => 'esc_url_raw'
        ));

        // Category exclusions for Follow Box
        register_setting('pinnerpress_settings_follow_box', 'pinnerpress_follow_box_excluded_categories', array(
            'sanitize_callback' => array($this, 'sanitize_category_exclusions')
        ));

        // Image Banner Tab
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_status', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_bg_color', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_text', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_opacity', array(
            'sanitize_callback' => 'absint'
        ));

        // Custom CSS selectors for Image Banner
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_custom_selectors_enabled', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_custom_selectors', array(
            'sanitize_callback' => 'sanitize_textarea_field'
        ));
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_find_images_in_selectors', array(
            'sanitize_callback' => 'absint'
        ));

        // Category exclusions for Image Banner
        register_setting('pinnerpress_settings_banner', 'pinnerpress_banner_excluded_categories', array(
            'sanitize_callback' => array($this, 'sanitize_category_exclusions')
        ));

        // Call Out Banners Tab
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_status', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_position', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_display_posts', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_display_pages', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_style', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_bg_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_border_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_title', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_description', array(
            'sanitize_callback' => 'sanitize_textarea_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_button_text', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_button_bg_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_button_text_color', array(
            'sanitize_callback' => 'sanitize_hex_color'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_show_icon', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_logo', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));

        // Category exclusions for Call Out Banner
        register_setting('pinnerpress_settings_call_out', 'pinnerpress_call_out_excluded_categories', array(
            'sanitize_callback' => array($this, 'sanitize_category_exclusions')
        ));

        // Analytics Settings
        register_setting('pinnerpress_settings_general', 'pinnerpress_analytics_enabled', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('pinnerpress_settings_general', 'pinnerpress_analytics_ignore_logged_in', array(
            'sanitize_callback' => 'absint'
        ));
        
        // Ensure critical default values are set
        $this->ensure_critical_defaults();
    }
    
    /**
     * Ensure critical default values are set in the database
     *
     * @since    0.1.0
     */
    private function ensure_critical_defaults() {
        // Ensure critical button color defaults
        if (get_option('pinnerpress_hover_button_color') === false) {
            add_option('pinnerpress_hover_button_color', '#E60023');
        }
        
        if (get_option('pinnerpress_hover_button_text_color') === false) {
            add_option('pinnerpress_hover_button_text_color', '#FFFFFF');
        }
        
        // Ensure critical button style default
        if (get_option('pinnerpress_hover_button_style') === false) {
            add_option('pinnerpress_hover_button_style', 'default');
        }
        
        // Ensure critical button size default
        if (get_option('pinnerpress_hover_button_size') === false) {
            add_option('pinnerpress_hover_button_size', 'medium');
        }
        
        // Ensure critical button shape default
        if (get_option('pinnerpress_hover_button_shape') === false) {
            add_option('pinnerpress_hover_button_shape', 'round');
        }
    }
    
    /**
     * Handle settings page redirects before any output
     *
     * @since    0.1.0
     */
    public function handle_settings_redirects() {
        // Only handle redirects on our settings page
        if (!is_admin() || !current_user_can('manage_options')) {
            return;
        }
        
        // Get current screen
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }
        
        // Check if we're on the settings page without a tab parameter
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Check is for redirection only, not data modification
        if (isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === $this->plugin_name . '-settings' && !isset($_GET['tab'])) {
            $redirect_url = admin_url('admin.php?page=' . $this->plugin_name . '-settings&tab=general');
            wp_redirect($redirect_url);
            exit;
        }
    }
    
    /**
     * Process settings reset if the reset button was clicked
     *
     * @since    0.1.0
     */
    public function process_settings_reset() {
        // Check if this is a reset request via GET parameter
        if (isset($_GET['pinnerpress_reset_settings']) && isset($_GET['_wpnonce'])) {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'pinnerpress-reset-settings')) {
                add_settings_error(
                    'pinnerpress_messages',
                    'pinnerpress_message',
                    __('Security check failed. Settings not reset.', 'pinnerpress'),
                    'error'
                );
                return;
            }
            
            // Get which tab is being reset
            $reset_tab = isset($_GET['reset_tab']) ? sanitize_text_field(wp_unslash($_GET['reset_tab'])) : 'all';
            
            // Include the defaults file if it hasn't been included yet
            if (!function_exists('pinnerpress_reset_tab_options')) {
                require_once plugin_dir_path(dirname(__FILE__)) . 'includes/pinnerpress-default-options.php';
            }
            
            if ($reset_tab === 'all') {
                // Reset all tabs
                $tabs = array('general', 'settings', 'follow_box', 'banner', 'call_out');
                foreach ($tabs as $tab) {
                    pinnerpress_reset_tab_options($tab);
                }
            } else {
                // Reset just the specified tab
                pinnerpress_reset_tab_options($reset_tab);
            }
            
            // Add success message
            add_settings_error(
                'pinnerpress_messages',
                'pinnerpress_message',
                __('Settings have been reset to defaults.', 'pinnerpress'),
                'updated'
            );
            
            // Redirect back to the settings page to show the changes
            $redirect_url = add_query_arg(
                array(
                    'page' => $this->plugin_name . '-settings',
                    'tab' => $reset_tab,
                    'settings-updated' => 'true'
                ),
                admin_url('admin.php')
            );
            
            wp_redirect($redirect_url);
            exit;
        }
    }
    
    /**
     * Render the dashboard page for this plugin.
     * 
     * @deprecated 1.1.0 Dashboard functionality has been replaced by Analytics page
     * @since    0.1.0
     */
    public function display_plugin_dashboard_page() {
        // Display analytics page content since dashboard has been replaced
        $this->display_plugin_analytics_page();
    }
    
    /**
     * Render the settings page for this plugin.
     *
     * @since    0.1.0
     */
    public function display_plugin_settings_page() {
        include_once('partials/pinnerpress-admin-settings.php');
    }
    
    /**
     * Render the analytics page for this plugin.
     *
     * @since    0.1.0
     */
    public function display_plugin_analytics_page() {
        include_once('partials/pinnerpress-admin-analytics.php');
    }

    /**
     * Display the image analytics page.
     *
     * @since    1.1.0
     */
    public function display_plugin_image_analytics_page() {
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'pinnerpress'));
        }

        // Let the template handle analytics disabled state and upgrade notifications
        require_once plugin_dir_path(__FILE__) . 'partials/pinnerpress-admin-image-analytics.php';
    }

    /**
     * Display the image analytics page - legacy support for date range.
     * This was previously used when analytics was enabled.
     *
     * @since    1.1.0
     */
    private function display_plugin_image_analytics_page_legacy() {
        // Get default date range
        $end_date = gmdate('Y-m-d');
        $start_date = gmdate('Y-m-d', strtotime('-30 days'));

        // Include the image analytics template
        require_once plugin_dir_path(__FILE__) . 'partials/pinnerpress-admin-image-analytics.php';
    }

    /**
     * Display the top images page.
     *
     * @since    1.1.0
     */
    public function display_plugin_top_images_page() {
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'pinnerpress'));
        }

        // Let the template handle analytics disabled state
        require_once plugin_dir_path(__FILE__) . 'partials/pinnerpress-admin-top-images.php';
    }

    /**
     * Display the post analytics page.
     * 
     * @since    1.2.0
     */
    public function display_plugin_post_analytics_page() {
        // Let the template handle upgrade notifications consistently

        include_once 'partials/pinnerpress-admin-post-analytics.php';
    }

    /**
     * Render the support page for this plugin.
     *
     * @since    0.1.0
     */
    public function display_plugin_support_page() {
        include_once('partials/pinnerpress-admin-support.php');
    }

    /**
     * Display the plugin debug page.
     *
     * @since    0.5.6
     */
    public function display_plugin_debug_page() {
        include_once('partials/pinnerpress-admin-debug.php');
    }

    /**
     * Sanitize category exclusions array
     *
     * @since    0.1.0
     * @param    array     $categories    The categories array to sanitize
     * @return   array                    The sanitized categories array
     */
    public function sanitize_checkbox($value) {
        // Convert checkbox value to 1 or 0
        return ($value == 1 || $value === '1') ? 1 : 0;
    }

    public function sanitize_category_exclusions($categories) {
        if (!is_array($categories)) {
            return array();
        }

        // Ensure all values are integers and valid category IDs
        $sanitized = array();
        foreach ($categories as $cat_id) {
            $cat_id = absint($cat_id);
            if ($cat_id > 0 && term_exists($cat_id, 'category')) {
                $sanitized[] = $cat_id;
            }
        }

        return array_unique($sanitized);
    }

    /**
     * Sanitize and validate Pinterest URL
     *
     * @since    0.1.0
     * @param    string    $url    The Pinterest URL to sanitize
     * @return   string             The sanitized Pinterest URL
     */
    public function sanitize_pinterest_url($url) {
        // Handle null values
        if (is_null($url) || $url === false) {
            return '';
        }
        
        // Trim whitespace
        $url = trim($url);
        
        // If empty, return empty string
        if (empty($url)) {
            return '';
        }
        
        // Check if it's already a full Pinterest URL
        if (preg_match('~^https?://(?:www\.)?pinterest\.[a-z\.]{2,}/[\w\-\.]+/?.*$~i', $url)) {
            // Already a full Pinterest URL, just ensure https
            return preg_replace('~^http://~i', 'https://', $url);
        }
        
        // If URL doesn't contain pinterest domain, it's likely just a username
        if (strpos((string)$url, 'pinterest') === false) {
            // Add a settings error to notify user
            add_settings_error(
                'pinnerpress_pinterest_url',
                'pinterest_url_error',
                __('Invalid Pinterest URL format. Your input has been converted to a Pinterest URL.', 'pinnerpress'),
                'warning'
            );
            
            // Assume it's a username and construct the URL
            return 'https://www.pinterest.com/' . $url;
        }
        
        // Check if URL has protocol
        if (!preg_match('~^(?:f|ht)tps?://~i', $url)) {
            $url = 'https://' . $url;
        }
        
        // If URL is not in the expected format but contains pinterest domain
        // Extract username and rebuild the URL
        if (preg_match('~pinterest\.[a-z\.]{2,}/([^/?&#]+)~i', $url, $matches)) {
            if (!empty($matches[1])) {
                // Add a settings error to notify user
                add_settings_error(
                    'pinnerpress_pinterest_url',
                    'pinterest_url_modified',
                    __('Your Pinterest URL has been reformatted to ensure compatibility.', 'pinnerpress'),
                    'warning'
                );
                
                return 'https://www.pinterest.com/' . $matches[1];
            }
        }
        
        // If we can't extract or validate, add error and return with https protocol
        add_settings_error(
            'pinnerpress_pinterest_url',
            'pinterest_url_invalid',
            __('The Pinterest URL format appears to be invalid. Please enter a valid Pinterest profile URL (e.g., https://www.pinterest.com/yourusername).', 'pinnerpress'),
            'error'
        );
        
        // Force https protocol
        return preg_replace('~^(?:f|ht)tp://~i', 'https://', $url);
    }

    /**
     * Add PinnerPress meta box to post and page edit screens
     *
     * @since    0.1.0
     */
    public function add_pinnerpress_meta_box() {
        $screens = array('post', 'page');
        
        foreach ($screens as $screen) {
            add_meta_box(
                'pinnerpress_post_settings',
                __('PinnerPress Settings', 'pinnerpress'),
                array($this, 'display_pinnerpress_meta_box'),
                $screen,
                'normal',
                'high'
            );
        }
    }

    /**
     * Display the PinnerPress meta box content
     *
     * @since    0.1.0
     * @param    WP_Post    $post    The post object
     */
    public function display_pinnerpress_meta_box($post) {
        // Add nonce field for security
        wp_nonce_field('pinnerpress_meta_box_nonce', 'pinnerpress_meta_box_nonce');
        
        // Get current values
        $disable_pin_buttons = get_post_meta($post->ID, '_pinnerpress_disable_pin_buttons', true);
        $disable_image_banners = get_post_meta($post->ID, '_pinnerpress_disable_image_banners', true);
        $disable_call_out_banners = get_post_meta($post->ID, '_pinnerpress_disable_call_out_banners', true);
        $disable_follow_box = get_post_meta($post->ID, '_pinnerpress_disable_follow_box', true);
        
        // Get hidden Pinterest images
        $hidden_images = get_post_meta($post->ID, '_pinnerpress_hidden_images', true);
        if (!is_array($hidden_images)) {
            $hidden_images = array();
        }
        
        include_once('partials/pinnerpress-admin-meta-box.php');
    }

    /**
     * Save PinnerPress meta box data
     *
     * @since    0.1.0
     * @param    int    $post_id    The post ID
     */
    public function save_pinnerpress_meta_box($post_id) {
        // Check if nonce is valid
        if (!isset($_POST['pinnerpress_meta_box_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['pinnerpress_meta_box_nonce'])), 'pinnerpress_meta_box_nonce')) {
            return;
        }

        // Check if user has permission to edit the post
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Check if this is an autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Save the checkbox values
        $disable_pin_buttons = isset($_POST['pinnerpress_disable_pin_buttons']) ? '1' : '0';
        $disable_image_banners = isset($_POST['pinnerpress_disable_image_banners']) ? '1' : '0';
        $disable_call_out_banners = isset($_POST['pinnerpress_disable_call_out_banners']) ? '1' : '0';
        $disable_follow_box = isset($_POST['pinnerpress_disable_follow_box']) ? '1' : '0';

        update_post_meta($post_id, '_pinnerpress_disable_pin_buttons', $disable_pin_buttons);
        update_post_meta($post_id, '_pinnerpress_disable_image_banners', $disable_image_banners);
        update_post_meta($post_id, '_pinnerpress_disable_call_out_banners', $disable_call_out_banners);
        update_post_meta($post_id, '_pinnerpress_disable_follow_box', $disable_follow_box);
        
        // Save hidden Pinterest images
        $hidden_images = array();
        if (isset($_POST['pinnerpress_hidden_images']) && is_array($_POST['pinnerpress_hidden_images'])) {
            // Get the raw POST data
            $pinnerpress_hidden_images_raw = $_POST['pinnerpress_hidden_images']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Sanitized below after unslashing
            
            // Unslash the data first
            $pinnerpress_hidden_images_unslashed = array_map('wp_unslash', $pinnerpress_hidden_images_raw);
            
            // Sanitize the unslashed data
            foreach ($pinnerpress_hidden_images_unslashed as $image_data) {
                if (isset($image_data['url']) && !empty($image_data['url'])) {
                    // Sanitize each URL
                    $hidden_images[] = array(
                        'url' => esc_url_raw(sanitize_text_field($image_data['url']))
                    );
                }
            }
        }
        
        update_post_meta($post_id, '_pinnerpress_hidden_images', $hidden_images);
    }

    /**
     * Display the standardized upgrade notification consistently across all admin pages
     *
     * @since    0.1.0
     */
    public function display_free_version_message() {
        // Use the standardized upgrade notification
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Function returns properly escaped HTML
        echo pinnerpress_get_upgrade_notification();
    }

    /**
     * Display the reset analytics page.
     * Access via: /wp-admin/admin.php?page=pinnerpress-reset-analytics
     *
     * @since    0.5.3
     */
    public function display_reset_analytics_page() {
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'pinnerpress'));
        }
        
        // Handle form submission
        if (isset($_POST['reset_analytics']) && check_admin_referer('pinnerpress_reset_analytics')) {
            $analytics = new PinnerPress_Analytics();
            $result = $analytics->reset_analytics_data();
            
            if ($result) {
                echo '<div class="notice notice-success"><p>' . esc_html__('Analytics data has been cleared successfully.', 'pinnerpress') . '</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__('Error clearing analytics data.', 'pinnerpress') . '</p></div>';
            }
        }
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Reset Analytics Data', 'pinnerpress'); ?></h1>
            
            <div class="notice notice-warning">
                <p><strong><?php esc_html_e('Warning:', 'pinnerpress'); ?></strong> <?php esc_html_e('This will permanently delete ALL analytics data including:', 'pinnerpress'); ?></p>
                <ul style="list-style: disc; margin-left: 20px;">
                    <li><?php esc_html_e('All click event history', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Post impressions and analytics', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Image-level analytics data', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Pin button clicks', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Banner clicks', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Follow clicks', 'pinnerpress'); ?></li>
                    <li><?php esc_html_e('Call out banner clicks', 'pinnerpress'); ?></li>
                </ul>
                <p><?php esc_html_e('This action cannot be undone! All analytics data will be permanently deleted.', 'pinnerpress'); ?></p>
            </div>
            
            <form method="post" action="">
                <?php wp_nonce_field('pinnerpress_reset_analytics'); ?>
                
                <p>
                    <label>
                        <input type="checkbox" name="confirm_reset" value="1" required />
                        <?php esc_html_e('I understand that this will permanently delete ALL analytics data', 'pinnerpress'); ?>
                    </label>
                </p>
                
                <p class="submit">
                    <input type="submit" name="reset_analytics" class="button button-primary" value="<?php esc_attr_e('Clear All Analytics Data', 'pinnerpress'); ?>" onclick="return confirm('<?php esc_attr_e('Are you absolutely sure you want to delete ALL analytics data? This cannot be undone!', 'pinnerpress'); ?>');" />
                </p>
            </form>
            
            <hr />
            
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=pinnerpress-analytics')); ?>" class="button">
                    <?php esc_html_e('Back to Analytics', 'pinnerpress'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * Handle direct page access for reset analytics (fallback method)
     * This ensures the page works even if menu registration fails
     *
     * @since    0.5.3
     */
    public function handle_reset_analytics_direct_access() {
        if (!is_admin()) {
            return;
        }
        
        // Check if we're trying to access the reset analytics page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin navigation param only
        if (isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'pinnerpress-reset-analytics') {
            // Check if user has permission
            if (!current_user_can('manage_options')) {
                return;
            }
            
            // Check if the page is already registered
            global $_registered_pages;
            $hook_suffix = get_plugin_page_hookname('pinnerpress-reset-analytics', '');
            
            if (!isset($_registered_pages[$hook_suffix])) {
                // Page not registered, register it now
                $_registered_pages[$hook_suffix] = true;
                
                // Set up the hook for rendering
                add_action('load-' . $hook_suffix, function() {
                    // Any pre-load actions can go here
                });
                
                // Render the page content
                add_action('admin_page_' . $hook_suffix, array($this, 'display_reset_analytics_page'));
            }
        }
    }

} }
