<?php 
/**
 * AI Auto Tool - Image 404 Scanner & Fixer
 * Scan, report and fix 404 images in posts
 * 
 * Features:
 * - Auto scan via cron
 * - Manual scan
 * - Report 404 images
 * - Fix by removing 404 images
 * - Progress tracking
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutotool_Image404Scanner extends rendersetting {
    public $active = false;
    public $active_option_name = 'Aiautotool_Image404Scanner_active';
    private $options;
    private $table_name;
    private $table_name_thumbs;
    private $table_name_alt;
    private $table_name_format;
    
    // Scan settings
    private $batch_size = 10; // Process 10 posts per batch
    private $scan_in_progress = false;

    function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'aiautotool_image404_report';
        $this->table_name_thumbs = $wpdb->prefix . 'aiautotool_missing_thumbs';
        $this->table_name_alt = $wpdb->prefix . 'aiautotool_missing_alt';
        $this->table_name_format = $wpdb->prefix . 'aiautotool_image_format';
    	 $this->active = get_option($this->active_option_name, false);
    	
        // Create tables on activation
        $this->create_report_table();
        $this->create_thumbs_table();
        $this->create_alt_table();
        $this->create_format_table();
    	
        if ($this->active == 'true') {
            $this->init();
        }
        
        // AJAX handlers
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
        add_action('wp_ajax_aiautotool_scan_images_manual', array($this, 'ajax_scan_images_manual'));
        add_action('wp_ajax_aiautotool_scan_comprehensive', array($this, 'ajax_scan_comprehensive'));
        add_action('wp_ajax_aiautotool_fix_404_images', array($this, 'ajax_fix_404_images'));
        add_action('wp_ajax_aiautotool_generate_thumbnails_ai', array($this, 'ajax_generate_thumbnails_ai'));
        add_action('wp_ajax_aiautotool_fix_missing_alt', array($this, 'ajax_fix_missing_alt'));
        add_action('wp_ajax_aiautotool_clear_report', array($this, 'ajax_clear_report'));
        add_action('wp_ajax_aiautotool_get_scan_progress', array($this, 'ajax_get_scan_progress'));
        add_action('wp_ajax_aiautotool_download_remote_images', array($this, 'ajax_download_remote_images'));
        add_action('wp_ajax_aiautotool_download_remote_from_post', array($this, 'ajax_download_remote_from_post'));
    }

    /**
     * Create database table for 404 image reports
     */
    private function create_report_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            post_title text NOT NULL,
            image_url text NOT NULL,
            image_type varchar(50) NOT NULL,
            error_message text,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            fixed_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY status (status)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Create table for missing thumbnails tracking
     */
    private function create_thumbs_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_thumbs} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            post_title text NOT NULL,
            post_type varchar(50) NOT NULL,
            status varchar(20) DEFAULT 'pending',
            ai_generated tinyint(1) DEFAULT 0,
            thumbnail_id bigint(20) DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            generated_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY status (status)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Create table for missing alt text tracking
     */
    private function create_alt_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_alt} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            post_title text NOT NULL,
            image_url text NOT NULL,
            attachment_id bigint(20) DEFAULT NULL,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            fixed_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY status (status)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Create table for image format issues
     */
    private function create_format_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_format} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            post_title text NOT NULL,
            image_url text NOT NULL,
            issue_type varchar(50) NOT NULL,
            current_format varchar(10) NOT NULL,
            current_size varchar(50) NOT NULL,
            recommended_action text,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            fixed_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY status (status),
            KEY issue_type (issue_type)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Update active option callback
     */
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active);
            
            // Clear cron on deactivation
            if ($active !== 'true') {
                wp_clear_scheduled_hook('aiautotool_cron_scan_404_images');
        }

            echo $active;
        }
        wp_die();
    }

    /**
     * Initialize plugin
     */
    public function init() {
        $this->options = get_option('aiautotool_image404_options', array());
        add_action('admin_init', array($this, 'init_page'));
        
        // Setup cron if enabled
        if (!wp_next_scheduled('aiautotool_cron_scan_404_images')) {
            wp_schedule_event(time(), 'daily', 'aiautotool_cron_scan_404_images');
        }
        add_action('aiautotool_cron_scan_404_images', array($this, 'cron_scan_404_images'));
        
        // Auto download remote images on save post (if enabled)
        if (isset($this->options['enable_remote_download']) && $this->options['enable_remote_download'] == 1) {
            add_action('save_post', array($this, 'auto_download_on_save_post'), 10, 3);
        }
        
        // Add metabox for manual download in post editor
        add_action('add_meta_boxes', array($this, 'add_remote_download_metabox'));
        
        // Enqueue scripts for post editor
        add_action('admin_enqueue_scripts', array($this, 'enqueue_post_editor_scripts'));
    }

    /**
     * Render feature box
     */
    public function render_feature() {
        require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            "<i class=\"fa-solid fa-image\"></i> " . esc_html__('Image 404 Scanner & Fixer', 'ai-auto-tool'),
            esc_html__('Automatically scan and fix 404 images in your posts. Find broken images and remove them to improve site quality.', 'ai-auto-tool'),
            "https://doc.aiautotool.com/features/image-404-scanner",
            $this->active_option_name,
            $this->active,
            plugins_url('../../images/logo.svg', __FILE__)
        );

        echo $autoToolBox->generateHTML();
    }

    /**
     * Render tab setting
     */
    public function render_tab_setting() {
        if ($this->active == 'true') {
            echo '<button href="#tab-image404-setting" class="nav-tab sotab"><i class="fa-solid fa-image"></i> ' . esc_html__('Image 404 Scanner', 'ai-auto-tool') . '</button>';
        }
    }

    /**
     * Render settings page
     */
    public function render_setting() {
        global $wpdb;
        
        $auto_scan = isset($this->options['auto_scan']) ? $this->options['auto_scan'] : 1;
        $scan_interval = isset($this->options['scan_interval']) ? $this->options['scan_interval'] : 'daily';
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        
        // Get statistics for all issue types
        $total_errors = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status='pending'");
        $total_fixed = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status='fixed'");
        $total_posts_with_errors = $wpdb->get_var("SELECT COUNT(DISTINCT post_id) FROM {$this->table_name} WHERE status='pending'");
        
        // Missing thumbnails
        $missing_thumbs = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_thumbs} WHERE status='pending'");
        $generated_thumbs = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_thumbs} WHERE status='generated'");
        
        // Missing alt text
        $missing_alt = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_alt} WHERE status='pending'");
        $fixed_alt = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_alt} WHERE status='fixed'");
        
        // Format issues
        $format_issues = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_format} WHERE status='pending'");
        
        // Get recent errors
        $recent_errors = $wpdb->get_results(
            "SELECT * FROM {$this->table_name} 
            WHERE status='pending' 
            ORDER BY created_at DESC 
            LIMIT 50"
        );
        
        ?>
        <div id="tab-image404-setting" class="tab-content" style="display:none;">
            <h2><i class="fa-solid fa-image"></i> <?php esc_html_e('Image 404 Scanner & Fixer', 'ai-auto-tool'); ?></h2>
            
            <!-- Statistics -->
            <div class="aiautotool-stats-box" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h3><?php esc_html_e('Image Issues Statistics', 'ai-auto-tool'); ?></h3>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                    <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #dc3545;">
                        <div style="font-size: 28px; font-weight: bold; color: #dc3545;"><?php echo esc_html($total_errors); ?></div>
                        <div style="color: #6c757d; margin-top: 5px; font-size: 13px;"><?php esc_html_e('404 Images', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #ff9800;">
                        <div style="font-size: 28px; font-weight: bold; color: #ff9800;"><?php echo esc_html($missing_thumbs); ?></div>
                        <div style="color: #6c757d; margin-top: 5px; font-size: 13px;"><?php esc_html_e('No Thumbnail', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #9c27b0;">
                        <div style="font-size: 28px; font-weight: bold; color: #9c27b0;"><?php echo esc_html($missing_alt); ?></div>
                        <div style="color: #6c757d; margin-top: 5px; font-size: 13px;"><?php esc_html_e('Missing Alt', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #2196f3;">
                        <div style="font-size: 28px; font-weight: bold; color: #2196f3;"><?php echo esc_html($format_issues); ?></div>
                        <div style="color: #6c757d; margin-top: 5px; font-size: 13px;"><?php esc_html_e('Format Issues', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #28a745;">
                        <div style="font-size: 28px; font-weight: bold; color: #28a745;"><?php echo esc_html($total_fixed); ?></div>
                        <div style="color: #6c757d; margin-top: 5px; font-size: 13px;"><?php esc_html_e('Fixed', 'ai-auto-tool'); ?></div>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="aiautotool-actions" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h3><?php esc_html_e('Quick Actions', 'ai-auto-tool'); ?></h3>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Comprehensive Scan checks: 404 images, missing thumbnails, missing alt text, and image formats in one scan.', 'ai-auto-tool'); ?>
                </p>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-top: 15px;">
                    <button type="button" id="aiautotool-scan-comprehensive" class="button button-primary" style="padding: 12px 20px; font-weight: 600;">
                        <i class="fa-solid fa-magnifying-glass-chart"></i> <?php esc_html_e('Comprehensive Scan', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="aiautotool-generate-thumbs-ai" class="button" style="padding: 12px 20px; background: #ff9800; color: white; border-color: #ff9800;" <?php echo $missing_thumbs == 0 ? 'disabled' : ''; ?>>
                        <i class="fa-solid fa-wand-magic-sparkles"></i> <?php esc_html_e('Generate AI Thumbnails', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="aiautotool-fix-all" class="button" style="padding: 12px 20px; background: #dc3545; color: white; border-color: #dc3545;" <?php echo $total_errors == 0 ? 'disabled' : ''; ?>>
                        <i class="fa-solid fa-wrench"></i> <?php esc_html_e('Fix 404 Images', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="aiautotool-fix-missing-alt" class="button" style="padding: 12px 20px; background: #9c27b0; color: white; border-color: #9c27b0;" <?php echo $missing_alt == 0 ? 'disabled' : ''; ?>>
                        <i class="fa-solid fa-tags"></i> <?php esc_html_e('Fix Missing Alt', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="aiautotool-download-remote" class="button button-secondary" style="padding: 12px 20px;">
                        <i class="fa-solid fa-download"></i> <?php esc_html_e('Download Remote', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="aiautotool-clear-report" class="button" style="padding: 12px 20px;">
                        <i class="fa-solid fa-trash"></i> <?php esc_html_e('Clear All Reports', 'ai-auto-tool'); ?>
                    </button>
                </div>
                <div id="aiautotool-progress" style="display: none; margin-top: 15px;">
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 6px;">
                        <!-- Progress Bar -->
                        <div id="aiautotool-progress-text" style="margin-bottom: 10px; font-weight: bold;"></div>
                        <div style="background: #e9ecef; height: 20px; border-radius: 10px; overflow: hidden; margin-bottom: 15px;">
                            <div id="aiautotool-progress-bar" style="background: linear-gradient(90deg, #007bff, #0056b3); height: 100%; width: 0%; transition: width 0.5s;"></div>
                        </div>
                        
                        <!-- Current Post -->
                        <div id="aiautotool-current-post" style="margin-bottom: 15px; padding: 10px; background: white; border-radius: 4px; border-left: 3px solid #007bff; display: none;">
                            <strong style="color: #007bff;">
                                <i class="fa-solid fa-file-lines"></i> <?php esc_html_e('Currently scanning:', 'ai-auto-tool'); ?>
                            </strong>
                            <div id="aiautotool-current-post-title" style="margin-top: 5px; color: #333;"></div>
                        </div>
                        
                        <!-- TODO List -->
                        <div id="aiautotool-todo-list" style="background: white; padding: 10px; border-radius: 4px;">
                            <strong style="display: block; margin-bottom: 10px; color: #333;">
                                <i class="fa-solid fa-list-check"></i> <?php esc_html_e('Tasks:', 'ai-auto-tool'); ?>
                            </strong>
                            <ul id="aiautotool-todos" style="list-style: none; margin: 0; padding: 0;"></ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Settings Form -->
            <form method="post" action="options.php" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h3><?php esc_html_e('Settings', 'ai-auto-tool'); ?></h3>
                
                <p class="ft-note">
                    <i class="fa-solid fa-lightbulb"></i>
                    <?php esc_html_e('Enable automatic scanning to periodically check for 404 images.', 'ai-auto-tool'); ?>
                </p>
                
					<label class="nut-switch">
                    <input type="checkbox" name="aiautotool_image404_options[auto_scan]" value="1" <?php checked($auto_scan, 1); ?> />
                    <span class="slider"></span>
                </label>
                <label><?php esc_html_e('Enable Auto Scan', 'ai-auto-tool'); ?></label>
                
                <p class="ft-note" style="margin-top: 20px;">
                    <i class="fa-solid fa-download"></i>
                    <?php esc_html_e('Download remote images to your server', 'ai-auto-tool'); ?>
                </p>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('When enabled, external images will be downloaded to your WordPress media library and replaced in posts. This improves loading speed and prevents broken images.', 'ai-auto-tool'); ?>
                </p>
                <label class="nut-switch">
                    <input type="checkbox" name="aiautotool_image404_options[enable_remote_download]" value="1" <?php checked(isset($this->options['enable_remote_download']) ? $this->options['enable_remote_download'] : 0, 1); ?> />
                    <span class="slider"></span>
                </label>
                <label><?php esc_html_e('Enable Remote Image Download', 'ai-auto-tool'); ?></label>
                
                <p class="ft-note" style="margin-top: 20px;">
                    <i class="fa-solid fa-clock"></i>
                    <?php esc_html_e('Scan interval (how often to check for 404 images)', 'ai-auto-tool'); ?>
                </p>
                <select name="aiautotool_image404_options[scan_interval]" class="ft-input-big">
                    <option value="hourly" <?php selected($scan_interval, 'hourly'); ?>><?php esc_html_e('Hourly', 'ai-auto-tool'); ?></option>
                    <option value="twicedaily" <?php selected($scan_interval, 'twicedaily'); ?>><?php esc_html_e('Twice Daily', 'ai-auto-tool'); ?></option>
                    <option value="daily" <?php selected($scan_interval, 'daily'); ?>><?php esc_html_e('Daily', 'ai-auto-tool'); ?></option>
                    <option value="weekly" <?php selected($scan_interval, 'weekly'); ?>><?php esc_html_e('Weekly', 'ai-auto-tool'); ?></option>
                </select>

                <p class="ft-note" style="margin-top: 20px;">
                    <i class="fa-solid fa-file-alt"></i>
                    <?php esc_html_e('Post types to scan', 'ai-auto-tool'); ?>
                </p>
					<?php 
                $available_post_types = get_post_types(array('public' => true), 'objects');
                foreach ($available_post_types as $post_type) {
                    $checked = in_array($post_type->name, $post_types) ? 'checked' : '';
                                    ?>
                                    <p>
                                    <label class="nut-switch">
                            <input type="checkbox" name="aiautotool_image404_options[post_types][]" value="<?php echo esc_attr($post_type->name); ?>" <?php echo $checked; ?> />
                            <span class="slider"></span>
                        </label>
                        <label><?php echo esc_html($post_type->label); ?></label>
									</p>
                                    <?php
                                }
                ?>

                <?php
                settings_fields('aiautotool_image404_options_group');
                do_settings_sections('aiautotool-image404');
                submit_button(__('Save Settings', 'ai-auto-tool'), 'ft-submit');
                 ?>
    		 </form>

            <!-- Report Table -->
            <?php if (!empty($recent_errors)): ?>
            <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h3><?php esc_html_e('Recent 404 Images', 'ai-auto-tool'); ?></h3>
                <div style="overflow-x: auto;">
                    <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                        <thead>
                            <tr>
                                <th style="width: 50px;"><?php esc_html_e('ID', 'ai-auto-tool'); ?></th>
                                <th><?php esc_html_e('Post', 'ai-auto-tool'); ?></th>
                                <th><?php esc_html_e('Image URL', 'ai-auto-tool'); ?></th>
                                <th><?php esc_html_e('Type', 'ai-auto-tool'); ?></th>
                                <th><?php esc_html_e('Error', 'ai-auto-tool'); ?></th>
                                <th><?php esc_html_e('Date', 'ai-auto-tool'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_errors as $error): ?>
                            <tr>
                                <td><?php echo esc_html($error->id); ?></td>
                                <td>
                                    <a href="<?php echo get_edit_post_link($error->post_id); ?>" target="_blank">
                                        <?php echo esc_html($error->post_title); ?>
                                    </a>
                                </td>
                                <td style="word-break: break-all; max-width: 300px;">
                                    <code><?php echo esc_html(substr($error->image_url, 0, 80)) . (strlen($error->image_url) > 80 ? '...' : ''); ?></code>
                                </td>
                                <td>
                                    <span class="badge" style="background: #6c757d; color: white; padding: 3px 8px; border-radius: 3px; font-size: 11px;">
                                        <?php echo esc_html($error->image_type); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html($error->error_message); ?></td>
                                <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($error->created_at))); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
    		</div>
            </div>
            <?php endif; ?>
        </div>

        <script>
        jQuery(document).ready(function($) {
            var progressInterval = null;
            
            // Function to update TODO list UI
            function updateTodoList(todos) {
                var $list = $('#aiautotool-todos');
                $list.empty();
                
                if (todos && todos.length > 0) {
                    $.each(todos, function(index, todo) {
                        var icon = '';
                        var color = '';
                        var textDecoration = '';
                        
                        if (todo.status === 'completed') {
                            icon = '<i class="fa-solid fa-check-circle" style="color: #28a745;"></i>';
                            color = '#28a745';
                            textDecoration = 'line-through';
                        } else if (todo.status === 'in_progress') {
                            icon = '<i class="fa-solid fa-spinner fa-spin" style="color: #007bff;"></i>';
                            color = '#007bff';
                        } else {
                            icon = '<i class="fa-regular fa-circle" style="color: #6c757d;"></i>';
                            color = '#6c757d';
                        }
                        
                        var $li = $('<li>').css({
                            'padding': '8px 0',
                            'border-bottom': '1px solid #e9ecef',
                            'color': color,
                            'text-decoration': textDecoration
                        }).html(icon + ' <span style="margin-left: 8px;">' + todo.task + '</span>');
                        
                        $list.append($li);
                    });
                }
            }
            
            // Function to poll progress
            function pollProgress() {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_get_scan_progress',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success && response.data) {
                            var data = response.data;
                            
                            // Update progress bar
                            $('#aiautotool-progress-bar').css('width', data.progress + '%');
                            
                            // Update progress text
                            var progressText = data.message || '<?php esc_html_e('Scanning...', 'ai-auto-tool'); ?>';
                            progressText += ' (' + data.posts_scanned + '/' + data.total_posts + ')';
                            if (data.errors_found > 0) {
                                progressText += ' - ' + data.errors_found + ' <?php esc_html_e('errors found', 'ai-auto-tool'); ?>';
                            }
                            $('#aiautotool-progress-text').text(progressText);
                            
                            // Update current post
                            if (data.current_post_title && data.current_post_title !== '') {
                                $('#aiautotool-current-post').show();
                                $('#aiautotool-current-post-title').text(data.current_post_title);
                            } else {
                                $('#aiautotool-current-post').hide();
                            }
                            
                            // Update TODO list
                            if (data.todo_list) {
                                updateTodoList(data.todo_list);
                            }
                            
                            // Check if completed
                            if (data.progress >= 100 || data.status === 'completed') {
                                clearInterval(progressInterval);
                                setTimeout(function() {
                                    location.reload();
                                }, 2000);
                            }
                        } else if (response.data && response.data.status === 'idle') {
                            // Scan not started or completed
                            clearInterval(progressInterval);
                        }
                    }
                });
            }
            
            // Comprehensive scan button
            $('#aiautotool-scan-comprehensive').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Scanning...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress').show();
                $('#aiautotool-progress-text').text('<?php esc_html_e('Initializing scan...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress-bar').css('width', '0%');
                $('#aiautotool-current-post').hide();
                
                // Start polling progress every 500ms
                progressInterval = setInterval(pollProgress, 500);
                
                // Start comprehensive scan
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_scan_comprehensive',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        clearInterval(progressInterval);
                        
                        if (response.success) {
                            $('#aiautotool-progress-bar').css('width', '100%');
                            $('#aiautotool-progress-text').text(response.data.message);
                            setTimeout(function() {
                                location.reload();
                            }, 2000);
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                            $('#aiautotool-progress').hide();
                        }
                    },
                    error: function() {
                        clearInterval(progressInterval);
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                        $('#aiautotool-progress').hide();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Fix all button
            $('#aiautotool-fix-all').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!confirm('<?php esc_html_e('Are you sure you want to fix all 404 images? This will remove them from posts.', 'ai-auto-tool'); ?>')) {
                    return false;
                }
                
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Fixing...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress').show();
                $('#aiautotool-progress-text').text('<?php esc_html_e('Fixing 404 images...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress-bar').css('width', '0%');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_fix_404_images',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#aiautotool-progress-bar').css('width', '100%');
                            $('#aiautotool-progress-text').text(response.data.message);
                            setTimeout(function() {
                                location.reload();
                            }, 2000);
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                            $('#aiautotool-progress').hide();
                        }
                    },
                    error: function() {
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                        $('#aiautotool-progress').hide();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Download remote images button
            $('#aiautotool-download-remote').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!confirm('<?php esc_html_e('Download all external images to your server? This may take a while depending on the number of images.', 'ai-auto-tool'); ?>')) {
                    return false;
                }
                
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Downloading...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress').show();
                $('#aiautotool-progress-text').text('<?php esc_html_e('Initializing download...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress-bar').css('width', '0%');
                $('#aiautotool-current-post').hide();
                
                // Start polling progress every 500ms
                progressInterval = setInterval(pollProgress, 500);
                
                // Start download
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_download_remote_images',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        clearInterval(progressInterval);
                        
                        if (response.success) {
                            $('#aiautotool-progress-bar').css('width', '100%');
                            $('#aiautotool-progress-text').text(response.data.message);
                            setTimeout(function() {
                                location.reload();
                            }, 2000);
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                            $('#aiautotool-progress').hide();
                        }
                    },
                    error: function() {
                        clearInterval(progressInterval);
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                        $('#aiautotool-progress').hide();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Generate AI thumbnails button
            $('#aiautotool-generate-thumbs-ai').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!confirm('<?php esc_html_e('Generate AI thumbnails for all posts without featured images? This uses Pollinations AI (free).', 'ai-auto-tool'); ?>')) {
                    return false;
                }
                
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Generating...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress').show();
                $('#aiautotool-progress-text').text('<?php esc_html_e('Generating AI thumbnails...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress-bar').css('width', '0%');
                $('#aiautotool-current-post').hide();
                
                progressInterval = setInterval(pollProgress, 500);
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_generate_thumbnails_ai',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        clearInterval(progressInterval);
                        if (response.success) {
                            $('#aiautotool-progress-bar').css('width', '100%');
                            $('#aiautotool-progress-text').text(response.data.message);
                            setTimeout(function() { location.reload(); }, 2000);
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                            $('#aiautotool-progress').hide();
                        }
                    },
                    error: function() {
                        clearInterval(progressInterval);
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                        $('#aiautotool-progress').hide();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Fix missing alt text button
            $('#aiautotool-fix-missing-alt').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!confirm('<?php esc_html_e('Add alt text to all images? Alt text will be set to post title.', 'ai-auto-tool'); ?>')) {
                    return false;
                }
                
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Fixing...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress').show();
                $('#aiautotool-progress-text').text('<?php esc_html_e('Adding alt text...', 'ai-auto-tool'); ?>');
                $('#aiautotool-progress-bar').css('width', '50%');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_fix_missing_alt',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#aiautotool-progress-bar').css('width', '100%');
                            $('#aiautotool-progress-text').text(response.data.message);
                            setTimeout(function() { location.reload(); }, 2000);
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                            $('#aiautotool-progress').hide();
                        }
                    },
                    error: function() {
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                        $('#aiautotool-progress').hide();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Clear report button
            $('#aiautotool-clear-report').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!confirm('<?php esc_html_e('Clear all reports (404, thumbnails, alt text, formats)?', 'ai-auto-tool'); ?>')) {
                    return false;
                }
                
                var $btn = $(this);
                var originalText = $btn.html();
                
                $btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Clearing...', 'ai-auto-tool'); ?>');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aiautotool_clear_report',
                        security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.data.message || '<?php esc_html_e('An error occurred', 'ai-auto-tool'); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php esc_html_e('Request failed', 'ai-auto-tool'); ?>');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(originalText);
                    }
                });
            });
        });
        </script>
        <?php
    }

    /**
     * Initialize settings page
     */
    public function init_page() {
        register_setting(
            'aiautotool_image404_options_group',
            'aiautotool_image404_options',
            array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_options')
            )
        );

        add_settings_section(
            'aiautotool_image404_section',
            '',
            array($this, 'section_info'),
            'aiautotool-image404'
        );
    }

    /**
     * Sanitize options
     */
    public function sanitize_options($input) {
        $new_input = array();
        
        if (isset($input['auto_scan'])) {
            $new_input['auto_scan'] = 1;
        } else {
            $new_input['auto_scan'] = 0;
        }
        
        if (isset($input['enable_remote_download'])) {
            $new_input['enable_remote_download'] = 1;
        } else {
            $new_input['enable_remote_download'] = 0;
        }
        
        if (isset($input['scan_interval'])) {
            $new_input['scan_interval'] = sanitize_text_field($input['scan_interval']);
        }
        
        if (isset($input['post_types']) && is_array($input['post_types'])) {
            $new_input['post_types'] = array_map('sanitize_text_field', $input['post_types']);
        } else {
            $new_input['post_types'] = array('post');
        }
        
        return $new_input;
    }

    /**
     * Section info
     */
    public function section_info() {
        // Empty - description is in render_setting
    }

    /**
     * AJAX: Manual scan
     */
    public function ajax_scan_images_manual() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->scan_all_posts();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Scan completed! Found %d 404 images in %d posts.', 'ai-auto-tool'),
                    $result['errors_found'],
                    $result['posts_scanned']
                )
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }

    /**
     * AJAX: Fix 404 images
     */
    public function ajax_fix_404_images() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->fix_all_404_images();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Fixed %d images in %d posts successfully!', 'ai-auto-tool'),
                    $result['fixed_count'],
                    $result['posts_fixed']
                )
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }

    /**
     * AJAX: Clear report
     */
    public function ajax_clear_report() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        global $wpdb;
        $wpdb->query("TRUNCATE TABLE {$this->table_name}");
        $wpdb->query("TRUNCATE TABLE {$this->table_name_thumbs}");
        $wpdb->query("TRUNCATE TABLE {$this->table_name_alt}");
        $wpdb->query("TRUNCATE TABLE {$this->table_name_format}");
        
        wp_send_json_success(array('message' => __('All reports cleared successfully!', 'ai-auto-tool')));
    }

    /**
     * AJAX: Get scan progress
     */
    public function ajax_get_scan_progress() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $progress = get_transient('aiautotool_scan_progress');
        
        if ($progress === false) {
            wp_send_json_success(array(
                'progress' => 0,
                'status' => 'idle'
            ));
        } else {
            wp_send_json_success($progress);
        }
    }

    /**
     * Cron: Scan for 404 images
     */
    public function cron_scan_404_images() {
        // Ensure textdomain is loaded (important for cron jobs)
        // Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
        if (!is_textdomain_loaded('ai-auto-tool')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        $this->scan_all_posts();
    }

    /**
     * Scan all posts for 404 images
     */
    private function scan_all_posts() {
        global $wpdb;
        
        set_time_limit(0);
        
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        
        // Get all published posts
        $args = array(
            'post_type' => $post_types,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids'
        );
        
        $post_ids = get_posts($args);
        $total_posts = count($post_ids);
        $posts_scanned = 0;
        $errors_found = 0;
        
        // Initialize TODO list
        $todo_list = array(
            array('task' => __('Clear old reports', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan featured images', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan content images', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'),
        );
        
        // Clear old pending reports
        $todo_list[0]['status'] = 'in_progress';
        $this->update_progress(0, $total_posts, 0, 0, __('Clearing old reports...', 'ai-auto-tool'), '', $todo_list);
        $wpdb->query("DELETE FROM {$this->table_name} WHERE status='pending'");
        $todo_list[0]['status'] = 'completed';
        
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool');
            
            // Update task status
            if ($posts_scanned === 0) {
                $todo_list[1]['status'] = 'in_progress';
            }
            if ($posts_scanned > 0 && $posts_scanned < $total_posts / 2) {
                $todo_list[2]['status'] = 'in_progress';
            }
            
            // Update progress with current post info
            $this->update_progress(
                $posts_scanned,
                $total_posts,
                $errors_found,
                $post_id,
                __('Scanning post...', 'ai-auto-tool'),
                $current_post_title,
                $todo_list
            );
            
            $post_errors = $this->scan_post_images($post_id);
            $errors_found += $post_errors;
            $posts_scanned++;
        }
        
        // Mark scanning tasks as completed
        $todo_list[1]['status'] = 'completed';
        $todo_list[2]['status'] = 'completed';
        $todo_list[3]['status'] = 'in_progress';
        
        $this->update_progress(
            $posts_scanned,
            $total_posts,
            $errors_found,
            0,
            __('Generating final report...', 'ai-auto-tool'),
            '',
            $todo_list
        );
        
        // Final update
        $todo_list[3]['status'] = 'completed';
        $this->update_progress(
            $posts_scanned,
            $total_posts,
            $errors_found,
            0,
            __('Scan completed!', 'ai-auto-tool'),
            '',
            $todo_list
        );
        
        // Keep final progress for 10 seconds before clearing
        sleep(2);
        delete_transient('aiautotool_scan_progress');
        
        return array(
            'success' => true,
            'posts_scanned' => $posts_scanned,
            'errors_found' => $errors_found
        );
    }
    
    /**
     * Update scan progress
     * 
     * @param int $scanned Number of posts scanned
     * @param int $total Total posts to scan
     * @param int $errors Errors found so far
     * @param int $current_post_id Current post being scanned
     * @param string $message Status message
     * @param string $current_post_title Current post title
     * @param array $todo_list TODO list with statuses
     */
    private function update_progress($scanned, $total, $errors, $current_post_id, $message, $current_post_title, $todo_list) {
        $progress = array(
            'progress' => $total > 0 ? round(($scanned / $total) * 100) : 0,
            'status' => 'scanning',
            'posts_scanned' => $scanned,
            'total_posts' => $total,
            'errors_found' => $errors,
            'current_post_id' => $current_post_id,
            'current_post_title' => $current_post_title,
            'message' => $message,
            'todo_list' => $todo_list,
            'timestamp' => time()
        );
        set_transient('aiautotool_scan_progress', $progress, 300);
    }

    /**
     * Scan single post for 404 images
     */
    private function scan_post_images($post_id) {
        global $wpdb;

        $post = get_post($post_id);
        if (!$post) {
            return 0;
        }
        
        $errors_found = 0;
        
        // Check featured image
        if (has_post_thumbnail($post_id)) {
                $thumbnail_id = get_post_thumbnail_id($post_id);
            $thumbnail_url = wp_get_attachment_url($thumbnail_id);
            
            if (!$this->check_image_exists($thumbnail_url)) {
                $this->add_404_report($post_id, $post->post_title, $thumbnail_url, 'featured_image', 'Featured image not found (404)');
                $errors_found++;
            }
        }
        
        // Check images in content
        $content = $post->post_content;
        $pattern = '/<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>/i';
        $matches = array();
        
        if (preg_match_all($pattern, $content, $matches)) {
            if (isset($matches[1])) {
                foreach ($matches[1] as $image_url) {
                    // Clean URL
                    $image_url = html_entity_decode($image_url);
                    
                    if (!$this->check_image_exists($image_url)) {
                        $this->add_404_report($post_id, $post->post_title, $image_url, 'content_image', 'Image in content not found (404)');
                        $errors_found++;
                    }
                }
            }
        }
        
        return $errors_found;
    }

    /**
     * Check if image exists
     */
    private function check_image_exists($url) {
        if (empty($url)) {
            return false;
        }
        
        // Parse URL
        $url_parts = parse_url($url);
        if (!$url_parts) {
            return false;
        }
        
        // Check if it's a local image
        $home_url = parse_url(home_url());
        
        if (isset($url_parts['host']) && $url_parts['host'] === $home_url['host']) {
            // Local image - check file system
            $upload_dir = wp_upload_dir();
            $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
            
            return file_exists($file_path);
        } else {
            // External image - check HTTP status
            $response = wp_remote_head($url, array(
                'timeout' => 5,
                'redirection' => 5,
                'sslverify' => false
            ));
            
            if (is_wp_error($response)) {
                return false;
            }
            
            $status_code = wp_remote_retrieve_response_code($response);
            return ($status_code >= 200 && $status_code < 400);
        }
    }

    /**
     * Add 404 report to database
     */
    private function add_404_report($post_id, $post_title, $image_url, $image_type, $error_message) {
            global $wpdb;
        
        $wpdb->insert(
            $this->table_name,
            array(
                'post_id' => $post_id,
                'post_title' => $post_title,
                'image_url' => $image_url,
                'image_type' => $image_type,
                'error_message' => $error_message,
                'status' => 'pending',
                'created_at' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
        );
    }

    /**
     * Fix all 404 images
     */
    private function fix_all_404_images() {
        global $wpdb;
        
        set_time_limit(0);
        
        // Get all pending errors
        $errors = $wpdb->get_results(
            "SELECT * FROM {$this->table_name} WHERE status='pending' ORDER BY post_id"
        );
        
        if (empty($errors)) {
            return array(
                'success' => false,
                'message' => __('No 404 images to fix', 'ai-auto-tool')
            );
        }
        
        $posts_fixed = array();
        $fixed_count = 0;
        
        foreach ($errors as $error) {
            $result = $this->fix_single_image($error);
            
            if ($result) {
                $fixed_count++;
                $posts_fixed[$error->post_id] = true;
                
                // Update status
                $wpdb->update(
                    $this->table_name,
                    array(
                        'status' => 'fixed',
                        'fixed_at' => current_time('mysql')
                    ),
                    array('id' => $error->id),
                    array('%s', '%s'),
                    array('%d')
                );
            }
        }
        
        return array(
            'success' => true,
            'fixed_count' => $fixed_count,
            'posts_fixed' => count($posts_fixed)
        );
    }

    /**
     * Fix single image
     */
    private function fix_single_image($error) {
        $post = get_post($error->post_id);
        if (!$post) {
            return false;
        }
        
        if ($error->image_type === 'featured_image') {
            // Remove featured image
            delete_post_thumbnail($error->post_id);
            return true;
        } elseif ($error->image_type === 'content_image') {
            // Remove image from content
            $content = $post->post_content;
            
            // Find and remove the img tag
            $pattern = '/<img[^>]*\bsrc=["\']' . preg_quote($error->image_url, '/') . '["\'][^>]*>/i';
            $new_content = preg_replace($pattern, '', $content);
            
            // Also remove any wrapping <a> tags that might be empty now
            $new_content = preg_replace('/<a[^>]*>\s*<\/a>/i', '', $new_content);
            
            // Update post
            wp_update_post(array(
                'ID' => $error->post_id,
                'post_content' => $new_content
            ));
            
                    return true;
                }
        
        return false;
    }
    
    /**
     * AJAX: Download remote images
     * 
     * Scans posts for external images and downloads them to media library
     */
    public function ajax_download_remote_images() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->download_all_remote_images();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Downloaded %d remote images from %d posts successfully!', 'ai-auto-tool'),
                    $result['downloaded_count'],
                    $result['posts_processed']
                )
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }
    
    /**
     * Download all remote images from posts
     * 
     * Scans all posts for external images and downloads them to WordPress media library.
     * Updates post content with new local URLs.
     * 
     * @return array Result with success status and statistics
     */
    private function download_all_remote_images() {
        global $wpdb;
        
        set_time_limit(0);
        
        // Check if feature is enabled
        if (!isset($this->options['enable_remote_download']) || $this->options['enable_remote_download'] != 1) {
            return array(
                'success' => false,
                'message' => __('Remote image download is not enabled. Please enable it in settings.', 'ai-auto-tool')
            );
        }
        
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        
        // Get all published posts
                            $args = array(
            'post_type' => $post_types,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids'
        );
        
        $post_ids = get_posts($args);
        $total_posts = count($post_ids);
        $posts_processed = 0;
        $downloaded_count = 0;
        
        // Initialize TODO list for download
        $todo_list = array(
            array('task' => __('Scan for remote images', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Download remote images', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Update post content', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'),
        );
        
        $todo_list[0]['status'] = 'in_progress';
        
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool');
            
            // Update task status
            if ($posts_processed === 0) {
                $todo_list[1]['status'] = 'in_progress';
            }
            if ($posts_processed > $total_posts / 2) {
                $todo_list[2]['status'] = 'in_progress';
            }
            
            // Update progress
            $this->update_progress(
                $posts_processed,
                $total_posts,
                $downloaded_count,
                $post_id,
                __('Processing post...', 'ai-auto-tool'),
                $current_post_title,
                $todo_list
            );
            
            $downloaded = $this->download_remote_images_from_post($post_id);
            $downloaded_count += $downloaded;
            $posts_processed++;
        }
        
        // Mark tasks as completed
        $todo_list[0]['status'] = 'completed';
        $todo_list[1]['status'] = 'completed';
        $todo_list[2]['status'] = 'completed';
        $todo_list[3]['status'] = 'in_progress';
        
        $this->update_progress(
            $posts_processed,
            $total_posts,
            $downloaded_count,
            0,
            __('Download completed!', 'ai-auto-tool'),
            '',
            $todo_list
        );
        
        $todo_list[3]['status'] = 'completed';
        
        sleep(2);
        delete_transient('aiautotool_scan_progress');
        
        return array(
            'success' => true,
            'posts_processed' => $posts_processed,
            'downloaded_count' => $downloaded_count
        );
    }
    
    /**
     * Download remote images from a single post
     * 
     * @param int $post_id Post ID to process
     * @return int Number of images downloaded
     */
    private function download_remote_images_from_post($post_id) {
        $post = get_post($post_id);
        if (!$post) {
            return 0;
        }
        
        $downloaded_count = 0;
        $content = $post->post_content;
        $home_url = parse_url(home_url());
        
        // Find all images in content
        $pattern = '/<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>/i';
        $matches = array();
        
        if (preg_match_all($pattern, $content, $matches)) {
            if (isset($matches[0]) && isset($matches[1])) {
                $full_tags = $matches[0];
                $image_urls = $matches[1];
                
                foreach ($image_urls as $index => $image_url) {
                    $image_url = html_entity_decode($image_url);
                    $url_parts = parse_url($image_url);
                    
                    // Check if it's an external image
                    if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) {
                        // This is an external image, download it
                        $new_attachment_id = $this->download_remote_image($image_url, $post_id);
                        
                        if ($new_attachment_id) {
                            // Get new local URL
                            $new_url = wp_get_attachment_url($new_attachment_id);
                            
                            if ($new_url) {
                                // Replace old URL with new URL in content
                                $content = str_replace($image_url, $new_url, $content);
                                $downloaded_count++;
                            }
                        }
                    }
                }
                
                // Update post content if any images were downloaded
                if ($downloaded_count > 0) {
                    wp_update_post(array(
                        'ID' => $post_id,
                        'post_content' => $content
                    ));
                }
            }
        }
        
        return $downloaded_count;
    }
    
    /**
     * Download a single remote image to media library
     * 
     * @param string $image_url Remote image URL
     * @param int $post_id Post ID to attach image to
     * @return int|false Attachment ID on success, false on failure
     */
    private function download_remote_image($image_url, $post_id) {
        // Validate URL
        if (!filter_var($image_url, FILTER_VALIDATE_URL)) {
            return false;
        }

        // Check if image exists
        $response = wp_remote_head($image_url, array(
            'timeout' => 10,
            'redirection' => 5,
            'sslverify' => false
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
                return false;
            }
        
        // Check content type
        $content_type = wp_remote_retrieve_header($response, 'content-type');
        if (strpos($content_type, 'image/') === false) {
                return false;
            }
            
        // Download image
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        
        $tmp = download_url($image_url);
        
        if (is_wp_error($tmp)) {
                return false;
            }
            
        // Get file info
        $file_array = array();
        $file_array['name'] = basename($image_url);
        $file_array['tmp_name'] = $tmp;
        
        // Check for file extension
        $ext = pathinfo($file_array['name'], PATHINFO_EXTENSION);
        if (!$ext) {
            // Try to get extension from content type
            $ext = $this->get_extension_from_content_type($content_type);
            if ($ext) {
                $file_array['name'] = 'image-' . time() . '.' . $ext;
            }
        }
        
        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, $post_id);
        
        // Check for upload errors
        if (is_wp_error($attachment_id)) {
                    @unlink($tmp);
                    return false;
                }

        return $attachment_id;
    }
    
    /**
     * Get file extension from content type
     * 
     * @param string $content_type Content type header
     * @return string|false File extension or false
     */
    private function get_extension_from_content_type($content_type) {
        $type_map = array(
            'image/jpeg' => 'jpg',
            'image/jpg' => 'jpg',
            'image/png' => 'png',
            'image/gif' => 'gif',
            'image/webp' => 'webp',
            'image/svg+xml' => 'svg',
            'image/bmp' => 'bmp',
        );
        
        $content_type = strtolower(trim($content_type));
        
        return isset($type_map[$content_type]) ? $type_map[$content_type] : false;
    }
    
    /**
     * Auto download remote images when saving/publishing post
     * 
     * Triggered by save_post hook when enable_remote_download is enabled.
     * Prevents infinite loops and only runs on actual post saves.
     * 
     * @param int $post_id Post ID
     * @param WP_Post $post Post object
     * @param bool $update Whether this is an update
     */
    public function auto_download_on_save_post($post_id, $post, $update) {
        // Avoid infinite loops
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Only for allowed post types
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        if (!in_array($post->post_type, $post_types)) {
            return;
        }
        
        // Only on publish or update
        if ($post->post_status !== 'publish') {
            return;
        }
        
        // Check if there are remote images
        if (!$this->has_remote_images($post->post_content)) {
            return;
        }
        
        // Remove this hook temporarily to prevent infinite loop
        remove_action('save_post', array($this, 'auto_download_on_save_post'), 10);
        
        // Download remote images
        $this->download_remote_images_from_post($post_id);
        
        // Re-add the hook
        add_action('save_post', array($this, 'auto_download_on_save_post'), 10, 3);
        
        // Set admin notice
        set_transient('aiautotool_remote_download_notice_' . $post_id, true, 30);
    }
    
    /**
     * Check if content has remote images
     * 
     * @param string $content Post content
     * @return bool True if has remote images
     */
    private function has_remote_images($content) {
        $pattern = '/<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>/i';
        $matches = array();
        
        if (preg_match_all($pattern, $content, $matches)) {
            if (isset($matches[1])) {
                $home_url = parse_url(home_url());
                
                foreach ($matches[1] as $image_url) {
                    $image_url = html_entity_decode($image_url);
                    $url_parts = parse_url($image_url);
                    
                    // Check if external
                    if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) {
                        return true;
                    }
                }
            }
        }
        
                return false;
            }

    /**
     * Add metabox to post editor for manual remote image download
     */
    public function add_remote_download_metabox() {
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        
        foreach ($post_types as $post_type) {
            add_meta_box(
                'aiautotool_remote_download',
                '<span class="dashicons dashicons-download"></span> ' . __('Remote Images', 'ai-auto-tool'),
                array($this, 'render_remote_download_metabox'),
                $post_type,
                'side',
                'default'
            );
        }
    }
    
    /**
     * Render metabox content
     * 
     * @param WP_Post $post Current post object
     */
    public function render_remote_download_metabox($post) {
        // Check if feature is enabled
        $is_enabled = isset($this->options['enable_remote_download']) && $this->options['enable_remote_download'] == 1;
        
        // Count remote images
        $remote_count = $this->count_remote_images($post->post_content);
        
        wp_nonce_field('aiautotool_download_remote_nonce', 'aiautotool_download_remote_nonce');
        ?>
        <div class="aiautotool-remote-download-metabox">
            <?php if (!$is_enabled): ?>
                <p style="color: #d63638;">
                    <span class="dashicons dashicons-warning"></span>
                    <?php esc_html_e('Remote image download is disabled.', 'ai-auto-tool'); ?>
                </p>
                <p>
                    <a href="<?php echo admin_url('admin.php?page=ai_auto_tool#tab-image404-setting'); ?>">
                        <?php esc_html_e('Enable in settings', 'ai-auto-tool'); ?> →
                    </a>
                </p>
            <?php else: ?>
                <div style="margin-bottom: 15px;">
                    <p style="margin: 0 0 10px;">
                        <strong><?php esc_html_e('Auto Download:', 'ai-auto-tool'); ?></strong>
                        <span style="color: #2271b1;">
                            <span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('Enabled', 'ai-auto-tool'); ?>
                        </span>
                    </p>
                    <p style="margin: 0; font-size: 12px; color: #666;">
                        <?php esc_html_e('Remote images will be downloaded automatically when you save or publish this post.', 'ai-auto-tool'); ?>
                    </p>
                </div>
            <?php endif; ?>
            
            <div style="border-top: 1px solid #ddd; padding-top: 15px; margin-top: 15px;">
                <p style="margin: 0 0 10px;">
                    <strong><?php esc_html_e('Remote Images Found:', 'ai-auto-tool'); ?></strong>
                    <span id="aiautotool-remote-count" style="font-size: 18px; color: <?php echo $remote_count > 0 ? '#d63638' : '#2271b1'; ?>;">
                        <?php echo $remote_count; ?>
                    </span>
                </p>
                
                <?php if ($remote_count > 0): ?>
                    <button type="button" 
                            id="aiautotool-download-remote-btn" 
                            class="button button-primary button-large" 
                            style="width: 100%; margin-top: 10px;"
                            <?php echo !$is_enabled ? 'disabled' : ''; ?>>
                        <span class="dashicons dashicons-download"></span>
                        <?php esc_html_e('Download Now', 'ai-auto-tool'); ?>
                    </button>
                    
                    <div id="aiautotool-download-status" style="margin-top: 10px; display: none;">
                        <div style="background: #f0f0f1; padding: 10px; border-radius: 4px;">
                            <p id="aiautotool-download-message" style="margin: 0; font-size: 12px;"></p>
                            <div style="background: #fff; height: 10px; border-radius: 5px; margin-top: 5px; overflow: hidden;">
                                <div id="aiautotool-download-progress" style="background: #2271b1; height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <p style="margin: 10px 0 0; padding: 10px; background: #d1f0d1; border-radius: 4px; font-size: 12px;">
                        <span class="dashicons dashicons-yes-alt" style="color: #0a7d0a;"></span>
                        <?php esc_html_e('All images are hosted locally!', 'ai-auto-tool'); ?>
                    </p>
                <?php endif; ?>
            </div>
            
            <?php
            // Show notice if images were just downloaded
            if (get_transient('aiautotool_remote_download_notice_' . $post->ID)): 
                delete_transient('aiautotool_remote_download_notice_' . $post->ID);
            ?>
                <div style="margin-top: 15px; padding: 10px; background: #d1f0d1; border-left: 3px solid #0a7d0a; border-radius: 4px;">
                    <p style="margin: 0; font-size: 12px; color: #0a7d0a;">
                        <span class="dashicons dashicons-yes"></span>
                        <?php esc_html_e('Remote images were downloaded automatically on save!', 'ai-auto-tool'); ?>
                    </p>
                </div>
            <?php endif; ?>
        </div>
        
        <style>
            .aiautotool-remote-download-metabox .dashicons {
                vertical-align: middle;
                margin-right: 3px;
            }
        </style>
        <?php
    }
    
    /**
     * Count remote images in content
     * 
     * @param string $content Post content
     * @return int Number of remote images
     */
    private function count_remote_images($content) {
        $count = 0;
        $pattern = '/<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>/i';
        $matches = array();
        
        if (preg_match_all($pattern, $content, $matches)) {
            if (isset($matches[1])) {
                $home_url = parse_url(home_url());
                
                foreach ($matches[1] as $image_url) {
                    $image_url = html_entity_decode($image_url);
                    $url_parts = parse_url($image_url);
                    
                    // Check if external
                    if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) {
                        $count++;
                    }
                }
            }
        }
        
        return $count;
    }
    
    /**
     * Enqueue scripts for post editor
     */
    public function enqueue_post_editor_scripts($hook) {
        // Only on post edit pages
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }
        
        // Inline script for metabox functionality
        wp_add_inline_script('jquery', '
            jQuery(document).ready(function($) {
                $("#aiautotool-download-remote-btn").on("click", function(e) {
                    e.preventDefault();
                    
                    var $btn = $(this);
                    var $status = $("#aiautotool-download-status");
                    var $message = $("#aiautotool-download-message");
                    var $progress = $("#aiautotool-download-progress");
                    var $count = $("#aiautotool-remote-count");
                    
                    // Get post ID
                    var postId = $("#post_ID").val();
                    if (!postId) {
                        alert("' . esc_js(__('Please save the post first.', 'ai-auto-tool')) . '");
                        return;
                    }
                    
                    // Disable button
                    $btn.prop("disabled", true).text("' . esc_js(__('Downloading...', 'ai-auto-tool')) . '");
                    $status.show();
                    $message.text("' . esc_js(__('Starting download...', 'ai-auto-tool')) . '");
                    $progress.css("width", "10%");
                    
                    // AJAX request
                    $.ajax({
                        url: ajaxurl,
                        type: "POST",
                        data: {
                            action: "aiautotool_download_remote_from_post",
                            post_id: postId,
                            security: $("#aiautotool_download_remote_nonce").val()
                        },
                        success: function(response) {
                            if (response.success) {
                                $progress.css("width", "100%");
                                $message.text(response.data.message);
                                $count.text(response.data.remaining || 0);
                                
                                // Reload editor content after 2 seconds
                                setTimeout(function() {
                                    location.reload();
                                }, 2000);
                            } else {
                                $message.text(response.data.message || "' . esc_js(__('An error occurred', 'ai-auto-tool')) . '");
                                $btn.prop("disabled", false).html(\'<span class="dashicons dashicons-download"></span> ' . esc_js(__('Download Now', 'ai-auto-tool')) . '\');
                            }
                        },
                        error: function() {
                            $message.text("' . esc_js(__('Request failed', 'ai-auto-tool')) . '");
                            $btn.prop("disabled", false).html(\'<span class="dashicons dashicons-download"></span> ' . esc_js(__('Download Now', 'ai-auto-tool')) . '\');
                        }
                    });
                });
            });
        ');
    }
    
    /**
     * AJAX handler for manual download from post editor
     */
    public function ajax_download_remote_from_post() {
        check_ajax_referer('aiautotool_download_remote_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        
        if (!$post_id) {
            wp_send_json_error(array('message' => __('Invalid post ID', 'ai-auto-tool')));
        }
        
        // Check if feature is enabled
        if (!isset($this->options['enable_remote_download']) || $this->options['enable_remote_download'] != 1) {
            wp_send_json_error(array('message' => __('Remote image download is not enabled.', 'ai-auto-tool')));
        }
        
        // Download images
        $downloaded = $this->download_remote_images_from_post($post_id);
        
        // Get updated post content to count remaining
        $post = get_post($post_id);
        $remaining = $this->count_remote_images($post->post_content);
        
        if ($downloaded > 0) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Successfully downloaded %d remote images!', 'ai-auto-tool'),
                    $downloaded
                ),
                'downloaded' => $downloaded,
                'remaining' => $remaining
            ));
        } elseif ($downloaded === 0 && $remaining === 0) {
            wp_send_json_success(array(
                'message' => __('No remote images found or all images are already local.', 'ai-auto-tool'),
                'downloaded' => 0,
                'remaining' => 0
            ));
        } else {
            wp_send_json_error(array(
                'message' => __('Failed to download images. Please check the image URLs.', 'ai-auto-tool'),
                'remaining' => $remaining
            ));
        }
    }
    
    /**
     * AJAX: Comprehensive scan (all image issues in one scan)
     */
    public function ajax_scan_comprehensive() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->comprehensive_scan();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Comprehensive scan completed! Found: %d 404 images, %d missing thumbnails, %d missing alt texts, %d format issues', 'ai-auto-tool'),
                    $result['404_count'],
                    $result['missing_thumbs'],
                    $result['missing_alt'],
                    $result['format_issues']
                ),
                'results' => $result
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }
    
    /**
     * Comprehensive scan - all image checks
     */
    private function comprehensive_scan() {
        global $wpdb;
        set_time_limit(0);
        
        $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
        $args = array(
            'post_type' => $post_types,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids'
        );
        
        $post_ids = get_posts($args);
        $total_posts = count($post_ids);
        $posts_scanned = 0;
        
        $counts = array(
            '404_count' => 0,
            'missing_thumbs' => 0,
            'missing_alt' => 0,
            'format_issues' => 0
        );
        
        // Initialize TODO list
        $todo_list = array(
            array('task' => __('Clear old reports', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan 404 images', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan missing thumbnails', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan missing alt text', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Scan image formats', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'),
        );
        
        // Clear old reports
        $todo_list[0]['status'] = 'in_progress';
        $this->update_progress(0, $total_posts, 0, 0, __('Clearing old reports...', 'ai-auto-tool'), '', $todo_list);
        $wpdb->query("DELETE FROM {$this->table_name} WHERE status='pending'");
        $wpdb->query("DELETE FROM {$this->table_name_thumbs} WHERE status='pending'");
        $wpdb->query("DELETE FROM {$this->table_name_alt} WHERE status='pending'");
        $wpdb->query("DELETE FROM {$this->table_name_format} WHERE status='pending'");
        $todo_list[0]['status'] = 'completed';
        
        // Scan all posts
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool');
            
            // Update task statuses based on progress
            if ($posts_scanned === 0) $todo_list[1]['status'] = 'in_progress';
            if ($posts_scanned >= $total_posts * 0.2) {
                $todo_list[1]['status'] = 'completed';
                $todo_list[2]['status'] = 'in_progress';
            }
            if ($posts_scanned >= $total_posts * 0.4) {
                $todo_list[2]['status'] = 'completed';
                $todo_list[3]['status'] = 'in_progress';
            }
            if ($posts_scanned >= $total_posts * 0.6) {
                $todo_list[3]['status'] = 'completed';
                $todo_list[4]['status'] = 'in_progress';
            }
            if ($posts_scanned >= $total_posts * 0.8) {
                $todo_list[4]['status'] = 'completed';
            }
            
            $this->update_progress($posts_scanned, $total_posts, 0, $post_id, __('Comprehensive scanning...', 'ai-auto-tool'), $current_post_title, $todo_list);
            
            // 1. Scan 404 images
            $counts['404_count'] += $this->scan_post_images($post_id);
            
            // 2. Check missing thumbnail
            if (!has_post_thumbnail($post_id)) {
                $wpdb->insert($this->table_name_thumbs, array(
                    'post_id' => $post_id,
                    'post_title' => $post->post_title,
                    'post_type' => $post->post_type,
                    'status' => 'pending',
                    'created_at' => current_time('mysql')
                ), array('%d', '%s', '%s', '%s', '%s'));
                $counts['missing_thumbs']++;
            }
            
            // 3. Check missing alt text
            $counts['missing_alt'] += $this->check_missing_alt($post_id, $post);
            
            // 4. Check image formats
            $counts['format_issues'] += $this->check_image_formats($post_id, $post);
            
            $posts_scanned++;
        }
        
        // Final report
        $todo_list[5]['status'] = 'in_progress';
        $this->update_progress($posts_scanned, $total_posts, 0, 0, __('Generating report...', 'ai-auto-tool'), '', $todo_list);
        $todo_list[5]['status'] = 'completed';
        
        sleep(1);
        delete_transient('aiautotool_scan_progress');
        
        return array_merge(array('success' => true), $counts);
    }
    
    /**
     * Check missing alt text
     */
    private function check_missing_alt($post_id, $post) {
        global $wpdb;
        $count = 0;
        $pattern = '/<img[^>]*>/i';
        
        if (preg_match_all($pattern, $post->post_content, $matches)) {
            foreach ($matches[0] as $img_tag) {
                if (!preg_match('/alt=["\'][^"\']*["\']/', $img_tag) || preg_match('/alt=["\']\s*["\']/', $img_tag)) {
                    preg_match('/src=["\']([^"\']+)["\']/', $img_tag, $src_match);
                    if (isset($src_match[1])) {
                        $wpdb->insert($this->table_name_alt, array(
                            'post_id' => $post_id,
                            'post_title' => $post->post_title,
                            'image_url' => $src_match[1],
                            'status' => 'pending',
                            'created_at' => current_time('mysql')
                        ), array('%d', '%s', '%s', '%s', '%s'));
                        $count++;
                    }
                }
            }
        }
        return $count;
    }
    
    /**
     * Check image formats and sizes
     */
    private function check_image_formats($post_id, $post) {
        global $wpdb;
        $count = 0;
        $pattern = '/<img[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>/i';
        
        if (preg_match_all($pattern, $post->post_content, $matches)) {
            foreach ($matches[1] as $image_url) {
                $image_url = html_entity_decode($image_url);
                $info = $this->get_image_info($image_url);
                
                if ($info && isset($info['issue'])) {
                    $wpdb->insert($this->table_name_format, array(
                        'post_id' => $post_id,
                        'post_title' => $post->post_title,
                        'image_url' => $image_url,
                        'issue_type' => $info['issue'],
                        'current_format' => $info['format'],
                        'current_size' => $info['size'],
                        'recommended_action' => $info['recommendation'],
                        'status' => 'pending',
                        'created_at' => current_time('mysql')
                    ), array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'));
                    $count++;
                }
            }
        }
        return $count;
    }
    
    /**
     * Get image info for format checking
     */
    private function get_image_info($url) {
        $home_url = parse_url(home_url());
        $url_parts = parse_url($url);
        
        if (!isset($url_parts['host'])) return null;
        
        // Only check local images
        if ($url_parts['host'] !== $home_url['host']) {
            return null;
        }
        
        $upload_dir = wp_upload_dir();
        $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
        
        if (!file_exists($file_path)) return null;
        
        $size = @getimagesize($file_path);
        if (!$size) return null;
        
        $width = $size[0];
        $height = $size[1];
        $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
        $filesize = filesize($file_path);
        
        $issue = null;
        $recommendation = '';
        
        // Check too small
        if ($width < 300 || $height < 300) {
            $issue = 'too_small';
            $recommendation = __('Image too small for thumbnail. Minimum 300x300px recommended.', 'ai-auto-tool');
        }
        // Check too large
        elseif ($filesize > 5 * 1024 * 1024) {
            $issue = 'too_large';
            $recommendation = __('Image file size over 5MB. Consider optimization.', 'ai-auto-tool');
        }
        // Check wrong format
        elseif (!in_array($ext, array('jpg', 'jpeg', 'png', 'webp', 'gif'))) {
            $issue = 'unsupported_format';
            $recommendation = __('Unsupported format. Convert to JPG, PNG, or WebP.', 'ai-auto-tool');
        }
        
        if ($issue) {
            return array(
                'issue' => $issue,
                'format' => $ext,
                'size' => $width . 'x' . $height . ' (' . size_format($filesize) . ')',
                'recommendation' => $recommendation
            );
        }
        
        return null;
    }
    
    /**
     * AJAX: Generate thumbnails using AI
     */
    public function ajax_generate_thumbnails_ai() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->generate_all_thumbnails_ai();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Generated %d thumbnails for %d posts using AI!', 'ai-auto-tool'),
                    $result['generated_count'],
                    $result['posts_processed']
                )
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }
    
    /**
     * Generate thumbnails for all posts without featured image
     */
    private function generate_all_thumbnails_ai() {
        global $wpdb;
        set_time_limit(0);
        
        // Get posts without thumbnails
        $posts_without_thumbs = $wpdb->get_results(
            "SELECT post_id, post_title FROM {$this->table_name_thumbs} WHERE status='pending'"
        );
        
        if (empty($posts_without_thumbs)) {
            return array('success' => false, 'message' => __('No posts without thumbnails', 'ai-auto-tool'));
        }
        
        $total = count($posts_without_thumbs);
        $generated = 0;
        $processed = 0;
        
        $todo_list = array(
            array('task' => __('Generate AI thumbnails', 'ai-auto-tool'), 'status' => 'in_progress'),
            array('task' => __('Upload to Media Library', 'ai-auto-tool'), 'status' => 'pending'),
            array('task' => __('Set as featured image', 'ai-auto-tool'), 'status' => 'pending'),
        );
        
        foreach ($posts_without_thumbs as $item) {
            $this->update_progress($processed, $total, $generated, $item->post_id, __('Generating thumbnail...', 'ai-auto-tool'), $item->post_title, $todo_list);
            
            if ($processed === 0) $todo_list[1]['status'] = 'in_progress';
            if ($processed > $total / 2) $todo_list[2]['status'] = 'in_progress';
            
            $attachment_id = $this->generate_thumbnail_ai($item->post_id, $item->post_title);
            
            if ($attachment_id) {
                set_post_thumbnail($item->post_id, $attachment_id);
                $wpdb->update($this->table_name_thumbs, 
                    array('status' => 'generated', 'ai_generated' => 1, 'thumbnail_id' => $attachment_id, 'generated_at' => current_time('mysql')),
                    array('post_id' => $item->post_id),
                    array('%s', '%d', '%d', '%s'),
                    array('%d')
                );
                $generated++;
            }
            $processed++;
        }
        
        $todo_list[1]['status'] = 'completed';
        $todo_list[2]['status'] = 'completed';
        
        sleep(1);
        delete_transient('aiautotool_scan_progress');
        
        return array('success' => true, 'posts_processed' => $processed, 'generated_count' => $generated);
    }
    
    /**
     * Generate AI thumbnail using Pollinations API with AI-enhanced prompt
     * 
     * Uses Gemini/Bard AI to create optimized image prompt, then generates
     * high-quality thumbnail using Pollinations.ai
     * 
     * @param int $post_id Post ID
     * @param string $title Post title
     * @return int|false Attachment ID on success, false on failure
     */
    private function generate_thumbnail_ai($post_id, $title) {
        $post = get_post($post_id);
        if (!$post) return false;
        
        // Get post content excerpt
        $content_excerpt = wp_trim_words(strip_tags($post->post_content), 50);
        
        // Use AI to generate optimized image prompt
        $image_prompt = $this->generate_image_prompt_with_ai($title, $content_excerpt);
        
        // Fallback to simple prompt if AI fails
        if (empty($image_prompt)) {
            $image_prompt = $title . ', professional illustration, high quality, detailed, modern design';
        }
        
        // Clean and encode prompt for Pollinations API
        $encoded_prompt = urlencode($image_prompt);
        
        // Pollinations API URL with optimal parameters
        $api_url = "https://image.pollinations.ai/prompt/{$encoded_prompt}?width=1200&height=630&nologo=true&enhance=true&model=flux";
        
        // Download image with retry mechanism
        $max_retries = 2;
        $image_data = false;
        
        for ($i = 0; $i < $max_retries; $i++) {
            $response = wp_remote_get($api_url, array(
                'timeout' => 30,
                'sslverify' => false,
                'headers' => array(
                    'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . home_url()
                )
            ));
            
            if (!is_wp_error($response)) {
                $image_data = wp_remote_retrieve_body($response);
                if (!empty($image_data) && strlen($image_data) > 1000) {
                    break; // Success
                }
            }
            
            // Wait before retry
            if ($i < $max_retries - 1) {
                sleep(2);
            }
        }
        
        if (empty($image_data)) return false;
        
        // Save to uploads directory
        $upload_dir = wp_upload_dir();
        $safe_title = sanitize_file_name(substr($title, 0, 50));
        $filename = $safe_title . '_ai_thumb_' . time() . '.png';
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        file_put_contents($file_path, $image_data);
        
        if (!file_exists($file_path)) return false;
        
        // Verify it's a valid image
        $image_size = @getimagesize($file_path);
        if ($image_size === false) {
            @unlink($file_path);
            return false;
        }
        
        // Create WordPress attachment
        $filetype = wp_check_filetype($filename);
        $attachment = array(
            'guid' => $upload_dir['url'] . '/' . $filename,
            'post_mime_type' => $filetype['type'],
            'post_title' => $title,
            'post_content' => 'AI-generated thumbnail: ' . $image_prompt,
            'post_excerpt' => 'Generated by Pollinations AI',
            'post_status' => 'inherit'
        );
        
        $attachment_id = wp_insert_attachment($attachment, $file_path, $post_id);
        
        if ($attachment_id) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path);
            wp_update_attachment_metadata($attachment_id, $attach_data);
            
            // Set alt text
            update_post_meta($attachment_id, '_wp_attachment_image_alt', $title);
            
            // Store the prompt used
            update_post_meta($attachment_id, '_ai_image_prompt', $image_prompt);
            update_post_meta($attachment_id, '_ai_generated', 1);
            
            return $attachment_id;
        }
        
        return false;
    }
    
    /**
     * Generate optimized image prompt using AI
     * 
     * Uses Gemini/Bard to create detailed, optimized prompt for image generation
     * 
     * @param string $title Post title
     * @param string $content Post content excerpt
     * @return string AI-generated image prompt
     */
    private function generate_image_prompt_with_ai($title, $content) {
        try {
            // Initialize Bard/Gemini content generator
            if (!class_exists('BardGenContent')) {
                require_once(plugin_dir_path(dirname(__FILE__)) . 'lib/bard.php');
            }
            
            $bardGenContent = new BardGenContent();
            
            // Create instruction for AI to generate image prompt
            $instruction = "Create a concise, visual description for a thumbnail image based on this article. 
Article Title: {$title}
Article Excerpt: {$content}

Generate a detailed image prompt (max 100 words) that describes:
- Main subject/theme
- Visual style (professional, modern, clean)
- Colors and mood
- Composition

Output ONLY the image prompt, no explanations. Make it suitable for AI image generation.";
            
            // Call AI to generate prompt
            $ai_response = $bardGenContent->bardcontentRaw($instruction, 'English');
            
            if (!empty($ai_response) && is_string($ai_response)) {
                // Clean up response
                $prompt = trim(strip_tags($ai_response));
                $prompt = preg_replace('/\s+/', ' ', $prompt);
                
                // Limit length
                if (strlen($prompt) > 300) {
                    $prompt = substr($prompt, 0, 300);
                }
                
                // Add quality enhancers
                $prompt .= ', professional, high quality, detailed';
                
                return $prompt;
            }
        } catch (Exception $e) {
            // Log error but continue with fallback
        }
        
        // Fallback: Simple prompt from title
        return $title . ', professional article thumbnail, modern design, clean, high quality';
    }
    
    /**
     * AJAX: Fix missing alt text
     */
    public function ajax_fix_missing_alt() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $result = $this->fix_all_missing_alt();
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(
                    __('Added alt text to %d images in %d posts!', 'ai-auto-tool'),
                    $result['fixed_count'],
                    $result['posts_fixed']
                )
            ));
        } else {
            wp_send_json_error(array('message' => $result['message']));
        }
    }
    
    /**
     * Fix all missing alt text using AI
     * 
     * Generates unique, SEO-friendly alt text for each image using AI
     * - Max 70 characters
     * - Includes relevant keywords from post
     * - Each image gets unique alt text
     */
    private function fix_all_missing_alt() {
        global $wpdb;
        
        set_time_limit(0);
        
        $items = $wpdb->get_results("SELECT * FROM {$this->table_name_alt} WHERE status='pending'");
        if (empty($items)) {
            return array('success' => false, 'message' => __('No images with missing alt text', 'ai-auto-tool'));
        }
        
        $fixed = 0;
        $posts_data = array();
        $used_alts = array(); // Track used alt texts to ensure uniqueness
        
        // Group by post to process efficiently
        foreach ($items as $item) {
            if (!isset($posts_data[$item->post_id])) {
                $posts_data[$item->post_id] = array(
                    'post' => get_post($item->post_id),
                    'images' => array(),
                    'image_count' => 0
                );
            }
            $posts_data[$item->post_id]['images'][] = $item;
            $posts_data[$item->post_id]['image_count']++;
        }
        
        // Process each post
        foreach ($posts_data as $post_id => $data) {
            $post = $data['post'];
            if (!$post) continue;
            
            $content = $post->post_content;
            $updated = false;
            
            // Process each image in this post
            foreach ($data['images'] as $index => $item) {
                // Generate unique AI alt text for this specific image
                $alt_text = $this->generate_alt_text_with_ai(
                    $post->post_title,
                    $item->image_url,
                    $index + 1, // Image number in post
                    $data['image_count'], // Total images in post
                    $used_alts // Previously used alt texts
                );
                
                // Ensure uniqueness
                $original_alt = $alt_text;
                $counter = 1;
                while (in_array($alt_text, $used_alts)) {
                    $alt_text = $original_alt . ' ' . $counter;
                    $counter++;
                    
                    // Trim if too long
                    if (strlen($alt_text) > 70) {
                        $alt_text = substr($original_alt, 0, 65) . ' ' . $counter;
                    }
                }
                
                // Add to used alts
                $used_alts[] = $alt_text;
                
                // Replace in content - match the specific img tag
                $pattern = '/<img([^>]*src=["\']' . preg_quote($item->image_url, '/') . '["\'][^>]*)>/i';
                
                if (preg_match($pattern, $content, $matches)) {
                    $img_tag = $matches[0];
                    
                    // Check if already has alt
                    if (preg_match('/alt=["\'][^"\']*["\']/', $img_tag)) {
                        // Has alt but empty, replace it
                        $new_tag = preg_replace('/alt=["\']\s*["\']/', 'alt="' . esc_attr($alt_text) . '"', $img_tag);
                    } else {
                        // No alt attribute, add it
                        $new_tag = str_replace('<img', '<img alt="' . esc_attr($alt_text) . '"', $img_tag);
                    }
                    
                    $content = str_replace($img_tag, $new_tag, $content);
                    $updated = true;
                    
                    // Update database
                    $wpdb->update(
                        $this->table_name_alt,
                        array('status' => 'fixed', 'fixed_at' => current_time('mysql')),
                        array('id' => $item->id),
                        array('%s', '%s'),
                        array('%d')
                    );
                    
                    $fixed++;
                }
            }
            
            // Update post content if any changes made
            if ($updated) {
                wp_update_post(array(
                    'ID' => $post->ID,
                    'post_content' => $content
                ));
            }
        }
        
        return array('success' => true, 'fixed_count' => $fixed, 'posts_fixed' => count($posts_data));
    }
    
    /**
     * Generate unique alt text using AI
     * 
     * Creates SEO-friendly, descriptive alt text for images:
     * - Max 70 characters
     * - Includes post keywords
     * - Unique for each image
     * - Context-aware
     * 
     * @param string $post_title Post title
     * @param string $image_url Image URL (for context)
     * @param int $image_number Position of image in post (1-based)
     * @param int $total_images Total images in post
     * @param array $used_alts Already used alt texts
     * @return string Generated alt text
     */
    private function generate_alt_text_with_ai($post_title, $image_url, $image_number, $total_images, $used_alts = array()) {
        try {
            // Initialize Bard/Gemini
            if (!class_exists('BardGenContent')) {
                require_once(plugin_dir_path(dirname(__FILE__)) . 'lib/bard.php');
            }
            
            $bardGenContent = new BardGenContent();
            
            // Get image filename for context
            $image_filename = basename($image_url);
            $image_name = pathinfo($image_filename, PATHINFO_FILENAME);
            
            // Create instruction for AI
            $instruction = "Generate a unique, SEO-friendly alt text for an image.

Article Title: {$post_title}
Image Position: Image {$image_number} of {$total_images} in the article
Image Filename: {$image_name}

Requirements:
- Maximum 70 characters (strict limit)
- Include relevant keywords from the article title
- Describe what the image likely shows (based on context)
- Be specific and descriptive
- SEO-optimized
- Natural language

Output ONLY the alt text, nothing else. No quotes, no explanations.";
            
            // Call AI
            $ai_response = $bardGenContent->bardcontentRaw($instruction, 'English');
            
            if (!empty($ai_response) && is_string($ai_response)) {
                // Clean response
                $alt_text = trim(strip_tags($ai_response));
                $alt_text = str_replace(array('"', "'", "\n", "\r"), '', $alt_text);
                $alt_text = preg_replace('/\s+/', ' ', $alt_text);
                
                // Ensure max 70 characters
                if (strlen($alt_text) > 70) {
                    $alt_text = substr($alt_text, 0, 67) . '...';
                }
                
                // Remove common AI response prefixes
                $prefixes_to_remove = array(
                    'Alt text: ',
                    'Image alt text: ',
                    'Alt: ',
                    'Description: ',
                );
                
                foreach ($prefixes_to_remove as $prefix) {
                    if (stripos($alt_text, $prefix) === 0) {
                        $alt_text = trim(substr($alt_text, strlen($prefix)));
                    }
                }
                
                // Final length check
                if (strlen($alt_text) > 70) {
                    $alt_text = substr($alt_text, 0, 67) . '...';
                }
                
                // Ensure it's not empty and not duplicate
                if (!empty($alt_text) && strlen($alt_text) > 5 && !in_array($alt_text, $used_alts)) {
                    return $alt_text;
                }
            }
        } catch (Exception $e) {
        }
        
        // Fallback: Create descriptive alt from post title + position
        $fallback_alt = $post_title;
        
        // Add context based on position
        if ($total_images > 1) {
            if ($image_number == 1) {
                $fallback_alt .= ' - featured image';
            } elseif ($image_number == $total_images) {
                $fallback_alt .= ' - conclusion';
            } else {
                $fallback_alt .= ' - figure ' . $image_number;
            }
        }
        
        // Trim to 70 characters
        if (strlen($fallback_alt) > 70) {
            $fallback_alt = substr($fallback_alt, 0, 67) . '...';
        }
        
        return $fallback_alt;
    }
}
