<?php
/**
 * Easy Social Share Buttons to PinnerPress Migration functionality
 *
 * @link       https://pinnerpress.com
 * @since      1.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */

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

/**
 * The Easy Social Share Buttons migration functionality of the plugin.
 *
 * Handles discovery and migration of ESSB settings and hidden images.
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/includes
 */
if (!class_exists('PinnerPress_ESSB_Migration')) {
class PinnerPress_ESSB_Migration {

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.1.0
     */
    public function __construct() {
        // Register AJAX actions for migration
        add_action('wp_ajax_pinnerpress_scan_essb_data', array($this, 'scan_essb_data_ajax'));
        add_action('wp_ajax_pinnerpress_migrate_from_essb', array($this, 'migrate_from_essb_ajax'));
        add_action('wp_ajax_pinnerpress_migrate_essb_batch', array($this, 'migrate_batch_ajax'));
    }

    /**
     * Discover ESSB settings in the database.
     *
     * @since    1.1.0
     * @return   array    Array of ESSB options found
     */
    public function discover_essb_settings() {
        global $wpdb;
        $settings = array();
        
        // Get main ESSB settings (WordPress automatically unserializes)
        $essb_settings = get_option('easy-social-share-buttons3');
        if ($essb_settings) {
            $settings['easy-social-share-buttons3'] = $essb_settings;
        }
        
        // Get additional ESSB options that might contain Pinterest data
        $essb_options = array(
            'essb3_options',
            'essb_options', 
            'essb-pinterest-pro',
            'essb3_pinterest',
            'essb3_pinpro',
            'essb_cached_settings'
        );
        
        foreach ($essb_options as $option_name) {
            $option_value = get_option($option_name);
            if ($option_value) {
                $settings[$option_name] = $option_value;
            }
        }
        
        // Also search for any options containing 'essb' in the name
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
        $essb_like_options = $wpdb->get_results(
            "SELECT option_name, option_value FROM {$wpdb->options} 
             WHERE option_name LIKE '%essb%' 
             AND option_name NOT LIKE '%_transient_%'
             ORDER BY option_name"
        );
        
        foreach ($essb_like_options as $option) {
            if (!isset($settings[$option->option_name])) {
                $value = maybe_unserialize($option->option_value);
                if (is_array($value) || is_object($value)) {
                    $settings[$option->option_name] = $value;
                }
            }
        }
        
        return $settings;
    }

    /**
     * Find posts with ESSB hidden images.
     *
     * @since    1.1.0
     * @return   array    Array of posts with hidden images
     */
    public function find_hidden_images() {
        global $wpdb;
        
        // Check if essb_post_meta table exists
        $table_name = $wpdb->prefix . 'essb_post_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table existence check for migration
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
        
        if (!$table_exists) {
            return array();
        }
        
        // Look for ESSB hidden Pinterest images in custom table  
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
        $hidden_images = $wpdb->get_results($wpdb->prepare(
            "SELECT post_id, meta_key, meta_value FROM `" . esc_sql($table_name) . "` 
             WHERE meta_key = %s
             ORDER BY post_id", 
            'pinterest_hidden'
        ));
        
        return $hidden_images;
    }

    /**
     * Count posts with ESSB hidden images.
     *
     * @since    1.1.0
     * @return   int      Number of posts with hidden images
     */
    public function count_posts_with_hidden_images() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'essb_post_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table existence check for migration
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
        
        if (!$table_exists) {
            return 0;
        }
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration count query, one-time operation
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT post_id) FROM `" . esc_sql($table_name) . "` 
             WHERE meta_key = %s", 
            'pinterest_hidden'
        ));
        
        return intval($count);
    }

    /**
     * Count total hidden images across all posts.
     *
     * @since    1.1.0
     * @return   int      Total number of hidden images
     */
    public function count_total_hidden_images() {
        $hidden_images = $this->find_hidden_images();
        $total = 0;
        
        foreach ($hidden_images as $image_data) {
            // ESSB stores data as double-serialized
            $first_unserialize = maybe_unserialize($image_data->meta_value);
            
            // If the first unserialize returns a string, unserialize again
            if (is_string($first_unserialize)) {
                $images = maybe_unserialize($first_unserialize);
            } else {
                $images = $first_unserialize;
            }
            
            if (is_array($images)) {
                $total += count($images);
            }
        }
        
        return $total;
    }

    /**
     * Get ESSB Pinterest settings.
     *
     * @since    1.1.0
     * @return   array    Pinterest-related settings from ESSB
     */
    public function get_essb_pinterest_settings() {
        $pinterest_settings = array();
        
        // Get main ESSB settings (WordPress automatically unserializes)
        $essb_settings = get_option('easy-social-share-buttons3');
        
        // If not found, try alternative option names
        if (!$essb_settings) {
            $essb_settings = get_option('essb3_options');
        }
        if (!$essb_settings) {
            $essb_settings = get_option('essb_options');
        }
        
        if ($essb_settings && is_array($essb_settings)) {
            // Extract Pinterest-related settings with multiple possible keys
            $pinterest_key_mappings = array(
                // Pin button text variations - added pinsc_text for ESSB
                array('keys' => array('pinsc_text', 'pinterest_text', 'pintext', 'pin_text'), 'target' => 'pin_button_text'),
                // Min width variations - added pinsc variants
                array('keys' => array('pinsc_minwidth', 'pinterest_minwidth', 'pin_minwidth', 'pinimages_minwidth'), 'target' => 'pin_button_min_width'),
                array('keys' => array('pinsc_minwidth_mobile', 'pinterest_minwidth_mobile', 'pin_minwidth_mobile'), 'target' => 'pin_button_min_width_mobile'),
                // Position variations - added pinsc variants
                array('keys' => array('pinsc_position', 'pinterest_position', 'pin_position', 'pinimages_position'), 'target' => 'pin_button_position'),
                // Follow box variations
                array('keys' => array('pinpro_follow_box', 'pinterest_follow_box', 'pin_follow_box'), 'target' => 'follow_box_enabled'),
                array('keys' => array('pinpro_followbox_desc', 'pinterest_followbox_desc'), 'target' => 'follow_box_description'),
                array('keys' => array('pinpro_followbox_title', 'pinterest_followbox_title', 'pinterest_username'), 'target' => 'pinterest_username'),
                array('keys' => array('pinpro_followbox_url', 'pinterest_followbox_url', 'pinterest_url'), 'target' => 'pinterest_profile_url'),
                array('keys' => array('pinpro_followbox_header', 'pinterest_followbox_header', 'pinpro_header', 'follow_header'), 'target' => 'follow_box_header_image'),
                array('keys' => array('pinpro_followbox_button_bg', 'pinterest_followbox_button_bg'), 'target' => 'follow_box_button_bg_color'),
                array('keys' => array('pinpro_followbox_button_text', 'pinterest_followbox_button_text'), 'target' => 'follow_box_button_text_color'),
                // Logo/Profile image variations
                array('keys' => array('pinpro_followbox_logo', 'pinterest_followbox_logo', 'pinterest_logo', 'pinpro_logo', 'pinterest_profile_image'), 'target' => 'profile_image'),
            );
            
            // Search for each possible key
            foreach ($pinterest_key_mappings as $mapping) {
                foreach ($mapping['keys'] as $key) {
                    if (isset($essb_settings[$key]) && !empty($essb_settings[$key])) {
                        $pinterest_settings[$mapping['target']] = $essb_settings[$key];
                        break; // Found this setting, move to next mapping
                    }
                }
            }
            
            // Also check for Pinterest settings in nested arrays
            if (isset($essb_settings['pinterest']) && is_array($essb_settings['pinterest'])) {
                foreach ($essb_settings['pinterest'] as $key => $value) {
                    if (!empty($value)) {
                        // Map nested Pinterest settings
                        if ($key === 'text') $pinterest_settings['pin_button_text'] = $value;
                        if ($key === 'minwidth') $pinterest_settings['pin_button_min_width'] = $value;
                        if ($key === 'position') $pinterest_settings['pin_button_position'] = $value;
                    }
                }
            }
            
            // Check for pinsc nested settings (ESSB specific)
            if (isset($essb_settings['pinsc']) && is_array($essb_settings['pinsc'])) {
                foreach ($essb_settings['pinsc'] as $key => $value) {
                    if (!empty($value)) {
                        // Map nested pinsc settings
                        if ($key === 'text') $pinterest_settings['pin_button_text'] = $value;
                        if ($key === 'minwidth') $pinterest_settings['pin_button_min_width'] = $value;
                        if ($key === 'position') $pinterest_settings['pin_button_position'] = $value;
                    }
                }
            }
            
            // Check for pinpro nested settings
            if (isset($essb_settings['pinpro']) && is_array($essb_settings['pinpro'])) {
                foreach ($essb_settings['pinpro'] as $key => $value) {
                    if (!empty($value)) {
                        if ($key === 'follow_box') $pinterest_settings['follow_box_enabled'] = $value;
                        if ($key === 'followbox_desc') $pinterest_settings['follow_box_description'] = $value;
                        if ($key === 'followbox_title') $pinterest_settings['pinterest_username'] = $value;
                        if ($key === 'followbox_url') $pinterest_settings['pinterest_profile_url'] = $value;
                        if ($key === 'followbox_header' || $key === 'header') $pinterest_settings['follow_box_header_image'] = $value;
                        if ($key === 'followbox_logo' || $key === 'logo') $pinterest_settings['profile_image'] = $value;
                    }
                }
            }
        }
        
        // If still no settings, check all discovered options
        if (empty($pinterest_settings)) {
            $all_settings = $this->discover_essb_settings();
            foreach ($all_settings as $option_name => $option_value) {
                if (is_array($option_value)) {
                    // Search for Pinterest-related keys in any option
                    $this->extract_pinterest_from_array($option_value, $pinterest_settings);
                }
            }
        }
        
        // Force check for pinpro_followbox_header in the main easy-social-share-buttons3 option
        if (!isset($pinterest_settings['follow_box_header_image'])) {
            // Get fresh copy of the main ESSB settings to be absolutely sure
            $main_essb_settings = get_option('easy-social-share-buttons3');
            if ($main_essb_settings && is_array($main_essb_settings)) {
                if (isset($main_essb_settings['pinpro_followbox_header']) && !empty($main_essb_settings['pinpro_followbox_header'])) {
                    $pinterest_settings['follow_box_header_image'] = $main_essb_settings['pinpro_followbox_header'];
                }
            }
            
            // Also check the original essb_settings variable
            if (!isset($pinterest_settings['follow_box_header_image']) && $essb_settings && is_array($essb_settings)) {
                if (isset($essb_settings['pinpro_followbox_header']) && !empty($essb_settings['pinpro_followbox_header'])) {
                    $pinterest_settings['follow_box_header_image'] = $essb_settings['pinpro_followbox_header'];
                }
            }
            
            // Also check all discovered options for this specific key
            $all_settings = $this->discover_essb_settings();
            foreach ($all_settings as $option_name => $option_value) {
                if (is_array($option_value) && isset($option_value['pinpro_followbox_header']) && !empty($option_value['pinpro_followbox_header'])) {
                    $pinterest_settings['follow_box_header_image'] = $option_value['pinpro_followbox_header'];
                    break;
                }
            }
            
            // Last resort: search database for any option containing header-related data
            if (!isset($pinterest_settings['follow_box_header_image'])) {
                global $wpdb;
                
                // Search for the specific image URL pattern
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration search query, one-time operation
                $results = $wpdb->get_results(
                    "SELECT option_name, option_value FROM {$wpdb->options} 
                     WHERE (option_value LIKE '%pinpro_followbox_header%' 
                     OR option_value LIKE '%c2108b101a8301caeb9d12c5ff0844c5.jpg%'
                     OR option_value LIKE '%followbox_header%')
                     AND option_name LIKE '%essb%'"
                );
                
                foreach ($results as $result) {
                    $unserialized = maybe_unserialize($result->option_value);
                    if (is_array($unserialized)) {
                        // Check for header image in various possible keys
                        $possible_keys = ['pinpro_followbox_header', 'followbox_header', 'header'];
                        foreach ($possible_keys as $key) {
                            if (isset($unserialized[$key]) && !empty($unserialized[$key])) {
                                // Check if this contains a valid image URL
                                if (strpos($unserialized[$key], 'http') !== false || strpos($unserialized[$key], '/wp-content/') !== false) {
                                    $pinterest_settings['follow_box_header_image'] = $unserialized[$key];
                                    break 2; // Break out of both loops
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return $pinterest_settings;
    }
    
    /**
     * Extract Pinterest settings from an array recursively.
     *
     * @since    1.1.0
     * @param    array    $array              Array to search
     * @param    array    &$pinterest_settings Reference to Pinterest settings array
     * @param    string   $prefix             Key prefix for nested arrays
     */
    private function extract_pinterest_from_array($array, &$pinterest_settings, $prefix = '') {
        foreach ($array as $key => $value) {
            $full_key = $prefix ? $prefix . '_' . $key : $key;
            
            // Check if this key contains pinterest-related terms (including pinsc for ESSB)
            if (stripos($full_key, 'pinterest') !== false || 
                stripos($full_key, 'pin') !== false ||
                stripos($full_key, 'pinpro') !== false ||
                stripos($full_key, 'pinsc') !== false) {
                
                if (is_array($value) && !empty($value)) {
                    // Recurse into nested arrays
                    $this->extract_pinterest_from_array($value, $pinterest_settings, $full_key);
                } elseif (!empty($value) && !is_array($value)) {
                    // Store the value with a descriptive key
                    // Check specifically for pinsc_text first (ESSB specific)
                    if ((stripos($full_key, 'pinsc_text') !== false || stripos($full_key, 'text') !== false) && !isset($pinterest_settings['pin_button_text'])) {
                        $pinterest_settings['pin_button_text'] = $value;
                    } elseif (stripos($full_key, 'minwidth') !== false && !isset($pinterest_settings['pin_button_min_width'])) {
                        $pinterest_settings['pin_button_min_width'] = $value;
                    } elseif (stripos($full_key, 'position') !== false && !isset($pinterest_settings['pin_button_position'])) {
                        $pinterest_settings['pin_button_position'] = $value;
                    } elseif ((stripos($full_key, 'username') !== false || stripos($full_key, 'title') !== false) && !isset($pinterest_settings['pinterest_username'])) {
                        $pinterest_settings['pinterest_username'] = $value;
                    } elseif (stripos($full_key, 'url') !== false && stripos($full_key, 'logo') === false && stripos($full_key, 'header') === false && !isset($pinterest_settings['pinterest_profile_url'])) {
                        $pinterest_settings['pinterest_profile_url'] = $value;
                    } elseif (stripos($full_key, 'header') !== false && !isset($pinterest_settings['follow_box_header_image'])) {
                        // Check if it's a valid image URL for header/background
                        if (filter_var($value, FILTER_VALIDATE_URL) || (is_string($value) && (strpos($value, '.jpg') !== false || strpos($value, '.png') !== false || strpos($value, '.gif') !== false || strpos($value, '/wp-content/') !== false))) {
                            $pinterest_settings['follow_box_header_image'] = $value;
                        }
                    } elseif ((stripos($full_key, 'logo') !== false || (stripos($full_key, 'image') !== false && stripos($full_key, 'header') === false)) && !isset($pinterest_settings['profile_image'])) {
                        // Check if it's a valid image URL for logo/profile
                        if (filter_var($value, FILTER_VALIDATE_URL) || (is_string($value) && (strpos($value, '.jpg') !== false || strpos($value, '.png') !== false || strpos($value, '.gif') !== false || strpos($value, '/wp-content/') !== false))) {
                            $pinterest_settings['profile_image'] = $value;
                        }
                    }
                }
            }
        }
    }

    /**
     * Check if ESSB plugin is active.
     *
     * @since    1.1.0
     * @return   bool     True if ESSB is active, false otherwise
     */
    public function is_essb_active() {
        if (!function_exists('is_plugin_active')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        
        // Get all active plugins
        $active_plugins = get_option('active_plugins', array());
        
        // Check for ESSB plugin
        foreach ($active_plugins as $plugin) {
            $plugin_lower = strtolower($plugin);
            if (strpos($plugin_lower, 'easy-social-share') !== false ||
                strpos($plugin_lower, 'essb') !== false) {
                return true;
            }
        }
        
        // Also check if ESSB options exist
        if (get_option('easy-social-share-buttons3') || 
            get_option('essb3_options') ||
            get_option('essb_options')) {
            return true;
        }
        
        // Check for ESSB custom table
        global $wpdb;
        $table_name = $wpdb->prefix . 'essb_post_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table existence check for migration
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
        
        return $table_exists;
    }

    /**
     * Analyze ESSB data for migration.
     *
     * @since    1.1.0
     * @return   array    Analysis of ESSB data
     */
    public function analyze_essb_data() {
        $analysis = array(
            'settings' => $this->discover_essb_settings(),
            'pinterest_settings' => $this->get_essb_pinterest_settings(),
            'posts_with_images' => $this->count_posts_with_hidden_images(),
            'total_images' => $this->count_total_hidden_images(),
            'essb_active' => $this->is_essb_active(),
            'table_exists' => $this->check_essb_table()
        );
        
        // Add detailed settings analysis
        if (!empty($analysis['pinterest_settings'])) {
            $analysis['migration_preview'] = $this->get_migration_preview($analysis['pinterest_settings']);
        }
        
        // Add debug info about what was found
        $analysis['debug'] = array(
            'options_found' => array_keys($analysis['settings']),
            'settings_count' => count($analysis['settings']),
            'pinterest_settings_count' => count($analysis['pinterest_settings']),
            'pinterest_settings_keys' => array_keys($analysis['pinterest_settings'])
        );
        
        // Sample the main ESSB settings structure for debugging
        if (!empty($analysis['settings'])) {
            foreach ($analysis['settings'] as $key => $value) {
                if (is_array($value) && !empty($value)) {
                    // Get top-level keys to see structure
                    $analysis['debug']['option_' . $key . '_keys'] = array_keys($value);
                    
                    // Look for any Pinterest-related keys (including pinsc)
                    $pinterest_keys = array();
                    foreach ($value as $k => $v) {
                        if (stripos($k, 'pin') !== false || stripos($k, 'pinterest') !== false || stripos($k, 'pinsc') !== false) {
                            $pinterest_keys[$k] = is_array($v) ? 'array(' . count($v) . ')' : substr((string)$v, 0, 100);
                        }
                    }
                    if (!empty($pinterest_keys)) {
                        $analysis['debug']['pinterest_keys_in_' . $key] = $pinterest_keys;
                    }
                }
            }
        }
        
        return $analysis;
    }

    /**
     * Check if ESSB custom table exists.
     *
     * @since    1.1.0
     * @return   bool     True if table exists, false otherwise
     */
    private function check_essb_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'essb_post_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table existence check for migration
        return $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
    }

    /**
     * Get migration preview data.
     *
     * @since    1.1.0
     * @param    array    $settings    Pinterest settings to preview
     * @return   array                 Migration preview data
     */
    private function get_migration_preview($settings) {
        $preview = array();
        
        // Map settings for preview
        $mapping = array(
            'pin_button_text' => __('Pin Button Text', 'pinnerpress'),
            'pin_button_min_width' => __('Pin Button Min Width', 'pinnerpress'),
            'pin_button_min_width_mobile' => __('Pin Button Min Width Mobile', 'pinnerpress'),
            'pin_button_position' => __('Pin Button Position', 'pinnerpress'),
            'profile_image' => __('Profile Image (Logo)', 'pinnerpress'),
            'follow_box_enabled' => __('Follow Box Enabled', 'pinnerpress'),
            'follow_box_description' => __('Follow Box Description', 'pinnerpress'),
            'pinterest_username' => __('Pinterest Username', 'pinnerpress'),
            'pinterest_profile_url' => __('Pinterest Profile URL', 'pinnerpress'),
            'follow_box_header_image' => __('Follow Box Header Image', 'pinnerpress'),
            'follow_box_button_bg_color' => __('Follow Box Button Background', 'pinnerpress'),
            'follow_box_button_text_color' => __('Follow Box Button Text Color', 'pinnerpress')
        );
        
        foreach ($settings as $key => $value) {
            if (isset($mapping[$key]) && !empty($value)) {
                $preview[] = array(
                    'label' => $mapping[$key],
                    'value' => is_bool($value) ? ($value ? 'Yes' : 'No') : $value
                );
            }
        }
        
        return $preview;
    }

    /**
     * Migrate Pinterest settings from ESSB to PinnerPress.
     *
     * @since    1.1.0
     * @return   array    Migration results
     */
    public function migrate_pinterest_settings() {
        $results = array(
            'success' => false,
            'messages' => array()
        );
        
        // Get ESSB Pinterest settings
        $pinterest_settings = $this->get_essb_pinterest_settings();
        
        if (empty($pinterest_settings)) {
            $results['messages'][] = __('No Pinterest settings found in ESSB', 'pinnerpress');
            return $results;
        }
        
        // Migrate pin button settings
        if (isset($pinterest_settings['pin_button_text'])) {
            update_option('pinnerpress_custom_button_text', sanitize_text_field($pinterest_settings['pin_button_text']));
            $results['messages'][] = __('Pin button text migrated', 'pinnerpress');
        }
        
        if (isset($pinterest_settings['pin_button_min_width'])) {
            $min_width = intval($pinterest_settings['pin_button_min_width']);
            if ($min_width > 0) {
                update_option('pinnerpress_minimum_image_size', $min_width);
                /* translators: %d: Minimum width in pixels */
                $results['messages'][] = sprintf(__('Minimum image width set to %dpx', 'pinnerpress'), $min_width);
            }
        }
        
        // Migrate pin button position
        if (isset($pinterest_settings['pin_button_position'])) {
            $position = $this->map_pin_button_position($pinterest_settings['pin_button_position']);
            update_option('pinnerpress_pin_button_position', $position);
            /* translators: %s: Pin button position */
            $results['messages'][] = sprintf(__('Pin button position set to %s', 'pinnerpress'), $position);
        }
        
        // Migrate profile image (Logo)
        if (isset($pinterest_settings['profile_image'])) {
            update_option('pinnerpress_profile_image', esc_url_raw($pinterest_settings['profile_image']));
            $results['messages'][] = __('Profile image (Logo) migrated', 'pinnerpress');
        }
        
        // Check if follow box should be enabled
        $follow_box_enabled = false;
        if (isset($pinterest_settings['follow_box_enabled'])) {
            $follow_box_value = $pinterest_settings['follow_box_enabled'];
            // Check for various enabled values
            if ($follow_box_value === 'true' || 
                $follow_box_value === true || 
                $follow_box_value === '1' || 
                $follow_box_value === 1 || 
                $follow_box_value === 'yes' || 
                $follow_box_value === 'on' ||
                $follow_box_value === 'enabled') {
                $follow_box_enabled = true;
            }
        }
        
        // If follow box settings exist (even without explicit enabled flag), enable the follow box
        // This ensures if ESSB has follow box data configured, we enable it in PinnerPress
        if ($follow_box_enabled || 
            isset($pinterest_settings['follow_box_description']) ||
            isset($pinterest_settings['pinterest_username']) ||
            isset($pinterest_settings['pinterest_profile_url']) ||
            isset($pinterest_settings['follow_box_header_image'])) {
            
            update_option('pinnerpress_follow_box_enabled', 'yes');
            $results['messages'][] = __('Follow box enabled', 'pinnerpress');
            $follow_box_enabled = true;
        }
        
        // Migrate all follow box details and ensure follow box is enabled if any are present
        if (isset($pinterest_settings['follow_box_description'])) {
            update_option('pinnerpress_follow_box_description', sanitize_text_field($pinterest_settings['follow_box_description']));
            $results['messages'][] = __('Follow box description migrated', 'pinnerpress');
            // Ensure follow box is enabled
            update_option('pinnerpress_follow_box_enabled', 'yes');
            if (!$follow_box_enabled) {
                $results['messages'][] = __('Follow box enabled (has description)', 'pinnerpress');
            }
            $follow_box_enabled = true;
        }
        
        if (isset($pinterest_settings['pinterest_username'])) {
            update_option('pinnerpress_pinterest_display_name', sanitize_text_field($pinterest_settings['pinterest_username']));
            $results['messages'][] = __('Pinterest username migrated', 'pinnerpress');
            // Ensure follow box is enabled
            update_option('pinnerpress_follow_box_enabled', 'yes');
            if (!$follow_box_enabled) {
                $results['messages'][] = __('Follow box enabled (has username)', 'pinnerpress');
            }
            $follow_box_enabled = true;
        }
        
        if (isset($pinterest_settings['pinterest_profile_url'])) {
            $url = $this->validate_pinterest_url($pinterest_settings['pinterest_profile_url']);
            if ($url) {
                update_option('pinnerpress_pinterest_url', $url);
                $results['messages'][] = __('Pinterest profile URL migrated', 'pinnerpress');
                // Ensure follow box is enabled
                update_option('pinnerpress_follow_box_enabled', 'yes');
                if (!$follow_box_enabled) {
                    $results['messages'][] = __('Follow box enabled (has profile URL)', 'pinnerpress');
                }
                $follow_box_enabled = true;
            }
        }
        
        if (isset($pinterest_settings['follow_box_header_image']) && !empty($pinterest_settings['follow_box_header_image'])) {
            // The ESSB header image goes to PinnerPress follow box header
            $header_url = $pinterest_settings['follow_box_header_image'];
            
            // Ensure it's a valid URL
            if (filter_var($header_url, FILTER_VALIDATE_URL) || strpos($header_url, '/wp-content/') !== false) {
                update_option('pinnerpress_follow_box_header', esc_url_raw($header_url));
                /* translators: %s: Image filename */
                $results['messages'][] = sprintf(__('Follow box header/background image migrated: %s', 'pinnerpress'), basename($header_url));
                
                // Enable the follow box since we have a header image (always enable to be sure)
                update_option('pinnerpress_follow_box_enabled', 'yes');
                if (!$follow_box_enabled) {
                    $results['messages'][] = __('Follow box enabled (has header image)', 'pinnerpress');
                }
                $follow_box_enabled = true;
            }
        }
        
        if (isset($pinterest_settings['follow_box_button_bg_color'])) {
            $color = $pinterest_settings['follow_box_button_bg_color'];
            // Add # if missing for hex colors
            if (preg_match('/^[0-9A-Fa-f]{6}$/', $color)) {
                $color = '#' . $color;
            }
            update_option('pinnerpress_follow_button_bg_color', sanitize_hex_color($color));
            $results['messages'][] = __('Follow box button background color migrated', 'pinnerpress');
        }
        
        if (isset($pinterest_settings['follow_box_button_text_color'])) {
            $color = $pinterest_settings['follow_box_button_text_color'];
            // Add # if missing for hex colors
            if (preg_match('/^[0-9A-Fa-f]{6}$/', $color)) {
                $color = '#' . $color;
            }
            update_option('pinnerpress_follow_button_text_color', sanitize_hex_color($color));
            $results['messages'][] = __('Follow box button text color migrated', 'pinnerpress');
        }
        
        // Final safety check: ensure follow box is enabled if any follow box data was imported
        $follow_box_imported = false;
        
        // Check if any follow box related options were set
        if (get_option('pinnerpress_follow_box_description') ||
            get_option('pinnerpress_pinterest_display_name') ||
            get_option('pinnerpress_pinterest_url') ||
            get_option('pinnerpress_follow_box_header') ||
            get_option('pinnerpress_profile_image')) {
            $follow_box_imported = true;
        }
        
        // Force enable follow box if any related data was imported
        if ($follow_box_imported) {
            update_option('pinnerpress_follow_box_enabled', 'yes');
            if (!in_array(__('Follow box enabled', 'pinnerpress'), $results['messages']) && 
                !in_array(__('Follow box enabled (has header image)', 'pinnerpress'), $results['messages']) &&
                !in_array(__('Follow box enabled (has description)', 'pinnerpress'), $results['messages']) &&
                !in_array(__('Follow box enabled (has username)', 'pinnerpress'), $results['messages']) &&
                !in_array(__('Follow box enabled (has profile URL)', 'pinnerpress'), $results['messages'])) {
                $results['messages'][] = __('Follow box enabled (imported follow box data)', 'pinnerpress');
            }
        }
        
        $results['success'] = true;
        $results['messages'][] = __('ESSB Pinterest settings migration completed', 'pinnerpress');
        
        return $results;
    }

    /**
     * Map ESSB pin button position to PinnerPress position.
     *
     * @since    1.1.0
     * @param    string   $essb_position    ESSB position value
     * @return   string                      PinnerPress position value
     */
    private function map_pin_button_position($essb_position) {
        $position_mapping = array(
            'bottom-right' => 'bottom_right',
            'bottom-left' => 'bottom_left',
            'top-right' => 'top_right',
            'top-left' => 'top_left',
            'center' => 'top_left' // Default center to top_left
        );
        
        return isset($position_mapping[$essb_position]) ? $position_mapping[$essb_position] : 'top_left';
    }

    /**
     * Validate Pinterest URL format.
     *
     * @since    1.1.0
     * @param    string   $url    URL to validate
     * @return   string           Validated URL or false
     */
    private function validate_pinterest_url($url) {
        if (empty($url)) {
            return false;
        }
        
        // Add https if no protocol specified
        if (!preg_match('~^https?://~i', $url)) {
            $url = 'https://' . $url;
        }
        
        // Validate URL format
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return false;
        }
        
        // Check if it's a Pinterest URL
        if (stripos($url, 'pinterest.com') === false) {
            return false;
        }
        
        return esc_url_raw($url);
    }

    /**
     * Get posts that have hidden images.
     *
     * @since    1.1.0
     * @param    int    $limit   Number of posts to return
     * @param    int    $offset  Offset for pagination
     * @return   array  Array of post IDs
     */
    private function get_posts_with_hidden_images($limit = -1, $offset = 0) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'essb_post_meta';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table existence check for migration
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
        
        if (!$table_exists) {
            return array();
        }
        
        // Build query with proper preparation without variable SQL
        if ($limit > 0 && $offset > 0) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
            $post_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT post_id FROM `" . esc_sql($table_name) . "` 
                 WHERE meta_key = %s
                 AND meta_value != '' 
                 AND meta_value != 'a:0:{}'
                 ORDER BY post_id
                 LIMIT %d OFFSET %d",
                'pinterest_hidden',
                (int) $limit,
                (int) $offset
            ));
        } elseif ($limit > 0) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
            $post_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT post_id FROM `" . esc_sql($table_name) . "` 
                 WHERE meta_key = %s
                 AND meta_value != '' 
                 AND meta_value != 'a:0:{}'
                 ORDER BY post_id
                 LIMIT %d",
                'pinterest_hidden',
                (int) $limit
            ));
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
            $post_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT post_id FROM `" . esc_sql($table_name) . "` 
                 WHERE meta_key = %s
                 AND meta_value != '' 
                 AND meta_value != 'a:0:{}'
                 ORDER BY post_id",
                'pinterest_hidden'
            ));
        }
        
        return array_map('intval', $post_ids);
    }

    /**
     * Migrate hidden images for a single post.
     *
     * @since    1.1.0
     * @param    int    $post_id  The post ID
     * @return   array  Migration result
     */
    private function migrate_post_hidden_images($post_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'essb_post_meta';
        
        // Get ESSB hidden images for this post
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration query, one-time operation
        $essb_data = $wpdb->get_var($wpdb->prepare(
            "SELECT meta_value FROM `" . esc_sql($table_name) . "` 
             WHERE post_id = %d AND meta_key = %s",
            $post_id, 'pinterest_hidden'
        ));
        
        if (empty($essb_data)) {
            return array(
                'success' => false,
                'message' => 'No hidden images found',
                'images_count' => 0
            );
        }
        
        // ESSB stores data as double-serialized
        $first_unserialize = maybe_unserialize($essb_data);
        
        // If the first unserialize returns a string, unserialize again
        if (is_string($first_unserialize)) {
            $images = maybe_unserialize($first_unserialize);
        } else {
            $images = $first_unserialize;
        }
        
        if (!is_array($images) || empty($images)) {
            return array(
                'success' => false,
                'message' => 'Invalid or empty image data',
                'images_count' => 0
            );
        }
        
        // Convert to PinnerPress format
        $hidden_images = array();
        foreach ($images as $image_url) {
            if (is_string($image_url) && !empty($image_url)) {
                // Clean and validate URL
                $image_url = trim($image_url);
                if (filter_var($image_url, FILTER_VALIDATE_URL)) {
                    $hidden_images[] = array('url' => esc_url_raw($image_url));
                }
            }
        }
        
        if (empty($hidden_images)) {
            return array(
                'success' => false,
                'message' => 'No valid image URLs found',
                'images_count' => 0
            );
        }
        
        // Check for existing PinnerPress hidden images
        $existing_images = get_post_meta($post_id, '_pinnerpress_hidden_images', true);
        
        if (!empty($existing_images) && is_array($existing_images)) {
            // Merge with existing, avoiding duplicates
            $existing_urls = array_map(function($img) {
                return isset($img['url']) ? $img['url'] : '';
            }, $existing_images);
            
            foreach ($hidden_images as $new_image) {
                if (!in_array($new_image['url'], $existing_urls)) {
                    $existing_images[] = $new_image;
                }
            }
            
            $hidden_images = $existing_images;
        }
        
        // Save to PinnerPress format
        update_post_meta($post_id, '_pinnerpress_hidden_images', $hidden_images);
        
        return array(
            'success' => true,
            'message' => 'Images migrated successfully',
            'images_count' => count($hidden_images)
        );
    }

    /**
     * AJAX handler for scanning ESSB data.
     *
     * @since    1.1.0
     */
    public function scan_essb_data_ajax() {
        // Check nonce and permissions
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'pinnerpress_admin_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        $data = $this->analyze_essb_data();
        
        // Force check for the specific header image issue
        $essb_main = get_option('easy-social-share-buttons3');
        $data['debug']['raw_essb_main'] = is_array($essb_main) ? array_keys($essb_main) : 'not_array';
        
        if (is_array($essb_main) && isset($essb_main['pinpro_followbox_header'])) {
            $data['debug']['found_header_direct'] = $essb_main['pinpro_followbox_header'];
        }
        
        wp_send_json_success($data);
    }

    /**
     * AJAX handler for migrating from ESSB.
     *
     * @since    1.1.0
     */
    public function migrate_from_essb_ajax() {
        // Check nonce and permissions
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'pinnerpress_admin_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        // FORCE FIX: Direct check and force import of the known ESSB settings using CORRECT option names
        $essb_main = get_option('easy-social-share-buttons3');
        if (is_array($essb_main)) {
            // Force import the header image (correct option name: pinnerpress_header_image)
            if (isset($essb_main['pinpro_followbox_header']) && !empty($essb_main['pinpro_followbox_header'])) {
                update_option('pinnerpress_header_image', esc_url_raw($essb_main['pinpro_followbox_header']));
            }
            
            // Force import the profile image/logo
            if (isset($essb_main['pinpro_followbox_logo']) && !empty($essb_main['pinpro_followbox_logo'])) {
                update_option('pinnerpress_profile_image', esc_url_raw($essb_main['pinpro_followbox_logo']));
            }
            
            // Force import the pin button text
            if (isset($essb_main['pinsc_text']) && !empty($essb_main['pinsc_text'])) {
                update_option('pinnerpress_custom_button_text', sanitize_text_field($essb_main['pinsc_text']));
            }
            
            // Force import Pinterest URL
            if (isset($essb_main['pinpro_followbox_url']) && !empty($essb_main['pinpro_followbox_url'])) {
                update_option('pinnerpress_pinterest_url', esc_url_raw($essb_main['pinpro_followbox_url']));
            }
            
            // Force import Pinterest display name
            if (isset($essb_main['pinpro_followbox_title']) && !empty($essb_main['pinpro_followbox_title'])) {
                update_option('pinnerpress_pinterest_display_name', sanitize_text_field($essb_main['pinpro_followbox_title']));
            }
            
            // Force import account description
            if (isset($essb_main['pinpro_followbox_desc']) && !empty($essb_main['pinpro_followbox_desc'])) {
                update_option('pinnerpress_account_description', sanitize_text_field($essb_main['pinpro_followbox_desc']));
            }
            
            // Force enable follow box (correct option name: pinnerpress_follow_box_status with value 'on')
            $follow_box_keys = ['pinpro_followbox_header', 'pinpro_followbox_desc', 'pinpro_followbox_title', 'pinpro_followbox_url', 'pinpro_follow_box'];
            foreach ($follow_box_keys as $key) {
                if (isset($essb_main[$key]) && !empty($essb_main[$key])) {
                    update_option('pinnerpress_follow_box_status', 'on');
                    break;
                }
            }
        }
        
        // Initialize migration session
        $migration_id = 'essb_migration_' . time();
        set_transient('pinnerpress_migration_' . $migration_id, array(
            'started' => current_time('mysql'),
            'status' => 'starting',
            'settings_done' => false,
            'images_done' => false,
            'batch_size' => 50, // Process 50 posts at a time
            'current_batch' => 0,
            'total_posts' => 0,
            'processed_posts' => 0
        ), 3600); // 1 hour expiry
        
        $results = array(
            'success' => true,
            'migration_id' => $migration_id,
            'use_batch_processing' => true,
            'messages' => array(__('Migration initialized. Starting batch processing...', 'pinnerpress'))
        );
        
        // First migrate settings (quick operation)
        $settings_result = $this->migrate_pinterest_settings();
        $results['settings_migration'] = $settings_result;
        
        // Count total posts with hidden images for progress tracking
        $total_posts = $this->count_posts_with_hidden_images();
        
        // Update migration session with total count
        $migration_data = get_transient('pinnerpress_migration_' . $migration_id);
        $migration_data['total_posts'] = $total_posts;
        $migration_data['settings_done'] = $settings_result['success'];
        set_transient('pinnerpress_migration_' . $migration_id, $migration_data, 3600);
        
        $results['total_posts'] = $total_posts;
        $results['batch_size'] = $migration_data['batch_size'];
        
        wp_send_json_success($results);
    }

    /**
     * AJAX handler for batch processing migration.
     *
     * @since    1.1.0
     */
    public function migrate_batch_ajax() {
        // Check nonce and permissions
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'pinnerpress_admin_nonce') || !current_user_can('manage_options')) {
            wp_die('Security check failed');
        }
        
        if (!isset($_POST['migration_id'])) {
            wp_send_json_error(array('message' => __('Missing migration ID.', 'pinnerpress')));
        }
        $migration_id = sanitize_text_field(wp_unslash($_POST['migration_id']));
        $migration_data = get_transient('pinnerpress_migration_' . $migration_id);
        
        if (!$migration_data) {
            wp_send_json_error(array('message' => __('Migration session expired or not found.', 'pinnerpress')));
        }
        
        $batch_size = $migration_data['batch_size'];
        $current_batch = $migration_data['current_batch'];
        $offset = $current_batch * $batch_size;
        
        // Get posts for this batch
        $posts_with_images = $this->get_posts_with_hidden_images($batch_size, $offset);
        
        $batch_results = array(
            'migrated_posts' => 0,
            'migrated_images' => 0,
            'errors' => array(),
            'messages' => array()
        );
        
        // Process each post in the batch
        foreach ($posts_with_images as $post_id) {
            try {
                $result = $this->migrate_post_hidden_images($post_id);
                if ($result['success']) {
                    $batch_results['migrated_posts']++;
                    $batch_results['migrated_images'] += $result['images_count'];
                } else {
                    /* translators: %1$d: Post ID, %2$s: Error message */
                    $batch_results['errors'][] = sprintf(__('Post %1$d: %2$s', 'pinnerpress'), $post_id, $result['message']);
                }
            } catch (Exception $e) {
                /* translators: %1$d: Post ID, %2$s: Exception message */
                $batch_results['errors'][] = sprintf(__('Post %1$d: %2$s', 'pinnerpress'), $post_id, $e->getMessage());
            }
        }
        
        // Update migration progress
        $migration_data['current_batch']++;
        $migration_data['processed_posts'] += count($posts_with_images);
        $migration_data['status'] = 'processing';
        
        // Check if we're done
        $is_complete = $migration_data['processed_posts'] >= $migration_data['total_posts'];
        if ($is_complete) {
            $migration_data['status'] = 'completed';
            $migration_data['completed'] = current_time('mysql');
            update_option('pinnerpress_essb_migration_completed', current_time('mysql'));
        }
        
        set_transient('pinnerpress_migration_' . $migration_id, $migration_data, 3600);
        
        $response = array(
            'success' => true,
            'batch_complete' => true,
            'migration_complete' => $is_complete,
            'progress' => array(
                'processed' => $migration_data['processed_posts'],
                'total' => $migration_data['total_posts'],
                'percentage' => $migration_data['total_posts'] > 0 ? round(($migration_data['processed_posts'] / $migration_data['total_posts']) * 100, 1) : 100
            ),
            'batch_results' => $batch_results,
            'next_batch' => $is_complete ? null : $migration_data['current_batch']
        );
        
        wp_send_json_success($response);
    }
}
}