<?php
/**
 * AYSA Cleanup Project Data Page
 * 
 * This page allows administrators to delete all AYSA data for a specific project:
 * - SuggestedKeywords
 * - Associations
 * - WordPress Meta Fields
 * - GeneratedSeoTitles
 * 
 * WARNING: This is a destructive operation!
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Get project ID from multiple sources
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$project_id = 0;

// 1. Try from URL parameter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reviewed callback inventory: this read-only/core lifecycle request is authenticated by WordPress or an enclosing guard and performs no unapproved write.
if (isset($_GET['project_id']) && intval(wp_unslash($_GET['project_id'])) > 0) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.Security.NonceVerification.Recommended -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $project_id = intval(wp_unslash($_GET['project_id']));
}

// 2. Try from WordPress option
if ($project_id === 0) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $project_id = intval(get_option('aysa_current_project_id', 0));
}

// 3. Try from cookie
if ($project_id === 0 && isset($_COOKIE['project_id'])) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $project_id = intval($_COOKIE['project_id']);
}

// 4. Try from aysa_project_id option
if ($project_id === 0) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $project_id = intval(get_option('aysa_project_id', 0));
}

// If still no project ID, we'll let JavaScript try to get it from localStorage

?>
<div class="wrap aysa-cleanup-page">
    <h1>🗑️ AYSA Cleanup - Project <span id="page-project-id"><?php echo esc_html($project_id > 0 ? $project_id : 'Not Set'); ?></span></h1>
    
    <div id="project-id-selector" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
        <label for="cleanup-project-id" style="font-weight: bold; display: block; margin-bottom: 8px;">Project ID:</label>
        <input type="number" id="cleanup-project-id" value="<?php echo esc_attr($project_id); ?>" min="1" style="width: 150px; padding: 5px; font-size: 14px;" />
        <button type="button" id="load-project-id-btn" class="button" style="margin-left: 10px;">Load from Browser</button>
        <p style="margin: 10px 0 0 0; color: #666; font-size: 12px;">
            <strong>Current:</strong> <span id="current-project-id-display"><?php echo esc_html($project_id > 0 ? $project_id : 'Not set - will be loaded from browser'); ?></span>
        </p>
    </div>
    
    <div class="notice notice-warning">
        <p><strong>⚠️ WARNING:</strong> This script will permanently delete:</p>
        <ul style="margin-left: 20px;">
            <li>All SuggestedKeywords for the selected Project ID</li>
            <li>All Associations for the selected Project ID</li>
            <li>All AYSA meta fields from WordPress (Pages, Posts, Products)</li>
            <li>All GeneratedSeoTitles for the selected Project ID</li>
            <li>All Content Strategies (proposals) for the selected Project ID</li>
            <li>All local keyword/monitoring rows, local refresh status, locks and queued background jobs for the selected Project ID</li>
            <li>Google integration session for the selected project (disconnect) and browser project cache (localStorage/cookie)</li>
        </ul>
        <p><strong>This action cannot be undone!</strong></p>
    </div>
    
    <div id="cleanup-controls">
        <p>
            <button type="button" class="button button-primary button-large" id="start-cleanup-btn">
                🗑️ DELETE ALL DATA FOR SELECTED PROJECT
            </button>
        </p>
    </div>
    
    <div id="cleanup-progress" style="display: none; margin-top: 20px;">
        <h2>⏳ Cleanup in Progress...</h2>
        <div style="background: #f0f0f0; border-radius: 4px; padding: 10px; margin: 20px 0;">
            <div id="cleanup-progress-bar" style="background: #2271b1; height: 30px; width: 0%; border-radius: 4px; transition: width 0.3s; text-align: center; line-height: 30px; color: white; font-weight: bold;">0%</div>
        </div>
        <div id="cleanup-status" style="margin: 10px 0;">
            <strong>⏳ Initializing...</strong>
        </div>
        <div id="cleanup-details" style="color: #666; margin: 10px 0;"></div>
    </div>
    
    <div id="cleanup-result" style="display: none; margin-top: 20px;"></div>
</div>

<script>
jQuery(document).ready(function($) {
    // Get project ID from multiple sources
    function getProjectId() {
        // 1. Try from input field
        var inputId = parseInt($('#cleanup-project-id').val(), 10);
        if (inputId > 0) {
            return inputId;
        }
        
        // 2. Try from localStorage
        try {
            var storedId = localStorage.getItem('aysa_project_id');
            if (storedId && parseInt(storedId, 10) > 0) {
                return parseInt(storedId, 10);
            }
        } catch (e) {}
        
        // 3. Try from aysaParams (if available)
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id && parseInt(aysaParams.project_id, 10) > 0) {
            return parseInt(aysaParams.project_id, 10);
        }
        
        // 4. Try from PHP (if set)
        var phpProjectId = <?php echo esc_js($project_id); ?>;
        if (phpProjectId > 0) {
            return phpProjectId;
        }
        
        return 0;
    }
    
    // Update project ID display
    function updateProjectIdDisplay() {
        var projectId = getProjectId();
        if (projectId > 0) {
            $('#current-project-id-display').text(projectId);
            $('#cleanup-project-id').val(projectId);
            $('#page-project-id').text(projectId);
        } else {
            $('#current-project-id-display').text('Not set - please enter Project ID');
            $('#page-project-id').text('Not Set');
        }
    }
    
    // Load project ID from browser on page load
    updateProjectIdDisplay();
    
    // Load button handler
    $('#load-project-id-btn').on('click', function() {
        updateProjectIdDisplay();
    });
    
    // Update display when input changes
    $('#cleanup-project-id').on('change blur', function() {
        var projectId = parseInt($(this).val(), 10);
        if (projectId > 0) {
            $('#current-project-id-display').text(projectId);
            $('#page-project-id').text(projectId);
        } else {
            $('#current-project-id-display').text('Not set - please enter Project ID');
            $('#page-project-id').text('Not Set');
        }
    });
    
    var currentStep = 0;
    var totalSteps = 7;
    var results = {
        suggested_keywords: { deleted: 0, errors: [] },
        associations: { deleted: 0, errors: [] },
        wordpress_meta: { deleted: 0, errors: [] },
        generated_titles: { deleted: 0, errors: [] },
        content_strategies: { deleted: 0, errors: [] },
        local_project_data: { deleted: 0, errors: [] },
        google_disconnect: { deleted: 0, errors: [] }
    };
    
    $('#start-cleanup-btn').on('click', function() {
        var projectId = getProjectId();
        
        if (projectId <= 0) {
            alert('❌ ERROR: Please enter a valid Project ID!');
            $('#cleanup-project-id').focus();
            return;
        }
        
        if (!confirm('⚠️ Are you absolutely sure?\n\nThis will DELETE ALL data for Project ID ' + projectId + '!\n\nThis action cannot be undone!')) {
            return;
        }
        
        var $btn = $(this);
        var $progress = $('#cleanup-progress');
        var $result = $('#cleanup-result');
        var $status = $('#cleanup-status');
        var $details = $('#cleanup-details');
        var $progressBar = $('#cleanup-progress-bar');
        
        $btn.prop('disabled', true).text('⏳ Processing...');
        $('#cleanup-controls').hide();
        $progress.show();
        $result.hide();
        $progressBar.css('width', '0%').text('0%');
        $status.html('<strong>⏳ Starting cleanup...</strong>');
        $details.text('');
        
        // Reset results
        results = {
            suggested_keywords: { deleted: 0, errors: [] },
            associations: { deleted: 0, errors: [] },
            wordpress_meta: { deleted: 0, errors: [] },
            generated_titles: { deleted: 0, errors: [] },
            content_strategies: { deleted: 0, errors: [] },
            local_project_data: { deleted: 0, errors: [] },
            google_disconnect: { deleted: 0, errors: [] }
        };
        currentStep = 0;
        
        // Start cleanup process
        startCleanup();
    });
    
    function startCleanup() {
        // Step 1: Delete SuggestedKeywords
        deleteSuggestedKeywords();
    }
    
    function updateProgress(step, total, message, details) {
        var percentage = Math.round((step / total) * 100);
        $('#cleanup-progress-bar').css('width', percentage + '%').text(percentage + '%');
        $('#cleanup-status').html('<strong>' + message + '</strong>');
        if (details) {
            $('#cleanup-details').text(details);
        }
    }
    
    function deleteSuggestedKeywords() {
        var projectId = getProjectId();
        currentStep = 1;
        updateProgress(1, totalSteps, '⏳ Step 1/7: Deleting SuggestedKeywords...', '');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_suggested_keywords',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 600000, // 10 minutes
            success: function(response) {
                console.log('[CLEANUP] SuggestedKeywords response:', response);
                if (response.success && response.data) {
                    // Ensure we preserve the deleted count
                    if (typeof response.data.deleted !== 'undefined') {
                        results.suggested_keywords.deleted = parseInt(response.data.deleted) || 0;
                    }
                    if (response.data.errors && Array.isArray(response.data.errors)) {
                        results.suggested_keywords.errors = response.data.errors;
                    }
                    updateProgress(1, totalSteps, '✅ Step 1/7: SuggestedKeywords deleted', 'Deleted: ' + results.suggested_keywords.deleted);
                    deleteAssociations();
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.suggested_keywords.errors.push(errorMsg);
                    updateProgress(1, totalSteps, '⚠️ Step 1/7: SuggestedKeywords - Some errors', 'Errors: ' + results.suggested_keywords.errors.length);
                    deleteAssociations(); // Continue anyway
                }
            },
            error: function(xhr, status, error) {
                results.suggested_keywords.errors.push('AJAX error: ' + error);
                updateProgress(1, totalSteps, '❌ Step 1/7: SuggestedKeywords - Error', 'Error: ' + error);
                deleteAssociations(); // Continue anyway
            }
        });
    }
    
    function deleteAssociations() {
        var projectId = getProjectId();
        currentStep = 2;
        updateProgress(2, totalSteps, '⏳ Step 2/7: Fetching Associations...', '');
        
        // First, get all association IDs
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_get_associations',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 60000, // 1 minute
            success: function(response) {
                console.log('[CLEANUP] Get Associations response:', response);
                if (response.success && response.data && response.data.ids) {
                    var associationIds = response.data.ids;
                    var total = associationIds.length;
                    
                    if (total === 0) {
                        updateProgress(2, totalSteps, '✅ Step 2/7: No Associations to delete', '');
                        deleteWordPressMeta();
                        return;
                    }
                    
                    // Process in batches of 10
                    var batchSize = 10;
                    var currentBatch = 0;
                    var totalBatches = Math.ceil(total / batchSize);
                    
                    updateProgress(2, totalSteps, '⏳ Step 2/7: Deleting Associations...', '0/' + total);
                    
                    function processNextBatch() {
                        if (currentBatch >= totalBatches) {
                            // All batches processed
                            updateProgress(2, totalSteps, '✅ Step 2/7: Associations deleted', 'Deleted: ' + results.associations.deleted + '/' + total);
                            deleteWordPressMeta();
                            return;
                        }
                        
                        var start = currentBatch * batchSize;
                        var end = Math.min(start + batchSize, total);
                        var batchIds = associationIds.slice(start, end);
                        
                        updateProgress(2, totalSteps, '⏳ Step 2/7: Deleting Associations...', 
                            'Batch ' + (currentBatch + 1) + '/' + totalBatches + ' (' + results.associations.deleted + '/' + total + ' deleted)');
                        
                        $.ajax({
                            url: ajaxurl,
                            method: 'POST',
                            data: {
                                action: 'aysa_cleanup_associations_batch',
                                project_id: projectId,
                                association_ids: batchIds,
                                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
                            },
                            timeout: 120000, // 2 minutes per batch
                            success: function(batchResponse) {
                                console.log('[CLEANUP] Batch ' + (currentBatch + 1) + ' response:', batchResponse);
                                if (batchResponse.success && batchResponse.data) {
                                    if (typeof batchResponse.data.deleted !== 'undefined') {
                                        results.associations.deleted += parseInt(batchResponse.data.deleted) || 0;
                                    }
                                    if (batchResponse.data.errors && Array.isArray(batchResponse.data.errors)) {
                                        results.associations.errors = results.associations.errors.concat(batchResponse.data.errors);
                                    }
                                } else {
                                    var errorMsg = 'Unknown error';
                                    if (batchResponse.data) {
                                        if (batchResponse.data.message) {
                                            errorMsg = batchResponse.data.message;
                                        } else if (typeof batchResponse.data === 'string') {
                                            errorMsg = batchResponse.data;
                                        }
                                    }
                                    results.associations.errors.push('Batch ' + (currentBatch + 1) + ': ' + errorMsg);
                                }
                                
                                currentBatch++;
                                // Small delay before next batch
                                setTimeout(processNextBatch, 100);
                            },
                            error: function(xhr, status, error) {
                                var errorMsg = error;
                                if (xhr.responseJSON) {
                                    if (xhr.responseJSON.data && xhr.responseJSON.data.message) {
                                        errorMsg = xhr.responseJSON.data.message;
                                    } else if (xhr.responseJSON.message) {
                                        errorMsg = xhr.responseJSON.message;
                                    }
                                }
                                results.associations.errors.push('Batch ' + (currentBatch + 1) + ' error: ' + errorMsg);
                                currentBatch++;
                                // Continue with next batch even on error
                                setTimeout(processNextBatch, 100);
                            }
                        });
                    }
                    
                    // Start processing batches
                    processNextBatch();
                    
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.associations.errors.push(errorMsg);
                    updateProgress(2, totalSteps, '⚠️ Step 2/7: Associations - Error fetching list', 'Errors: ' + results.associations.errors.length);
                    deleteWordPressMeta(); // Continue anyway
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = error;
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMsg = xhr.responseJSON.data.message;
                    } else if (xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                }
                results.associations.errors.push('AJAX error fetching associations: ' + errorMsg);
                updateProgress(2, totalSteps, '❌ Step 2/7: Associations - Error', 'Error: ' + errorMsg);
                deleteWordPressMeta(); // Continue anyway
            }
        });
    }
    
    function deleteWordPressMeta() {
        var projectId = getProjectId();
        currentStep = 3;
        updateProgress(3, totalSteps, '⏳ Step 3/7: Deleting WordPress Meta Fields...', '');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_wordpress_meta',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 60000, // 1 minute
            success: function(response) {
                console.log('[CLEANUP] WordPress Meta response:', response);
                if (response.success && response.data) {
                    // Ensure we preserve the deleted count
                    if (typeof response.data.deleted !== 'undefined') {
                        results.wordpress_meta.deleted = parseInt(response.data.deleted) || 0;
                    }
                    if (response.data.errors && Array.isArray(response.data.errors)) {
                        results.wordpress_meta.errors = response.data.errors;
                    }
                    var details = 'Deleted: ' + results.wordpress_meta.deleted;
                    if (response.data.breakdown) {
                        var breakdown = [];
                        if (response.data.breakdown.postmeta > 0) breakdown.push('Posts: ' + response.data.breakdown.postmeta);
                        if (response.data.breakdown.termmeta > 0) breakdown.push('Terms: ' + response.data.breakdown.termmeta);
                        if (response.data.breakdown.commentmeta > 0) breakdown.push('Comments: ' + response.data.breakdown.commentmeta);
                        if (response.data.breakdown.usermeta > 0) breakdown.push('Users: ' + response.data.breakdown.usermeta);
                        if (breakdown.length > 0) {
                            details += ' (' + breakdown.join(', ') + ')';
                        }
                    }
                    updateProgress(3, totalSteps, '✅ Step 3/7: WordPress Meta deleted', details);
                    deleteGeneratedTitles();
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.wordpress_meta.errors.push(errorMsg);
                    updateProgress(3, totalSteps, '⚠️ Step 3/7: WordPress Meta - Some errors', 'Errors: ' + results.wordpress_meta.errors.length);
                    deleteGeneratedTitles(); // Continue anyway
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = error;
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    errorMsg = xhr.responseJSON.data.message;
                }
                results.wordpress_meta.errors.push('AJAX error: ' + errorMsg);
                updateProgress(3, totalSteps, '❌ Step 3/7: WordPress Meta - Error', 'Error: ' + errorMsg);
                deleteGeneratedTitles(); // Continue anyway
            }
        });
    }
    
    function deleteGeneratedTitles() {
        var projectId = getProjectId();
        currentStep = 4;
        updateProgress(4, totalSteps, '⏳ Step 4/7: Deleting GeneratedSeoTitles...', '');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_generated_titles',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 600000, // 10 minutes
            success: function(response) {
                console.log('[CLEANUP] GeneratedTitles response:', response);
                if (response.success && response.data) {
                    // Ensure we preserve the deleted count
                    if (typeof response.data.deleted !== 'undefined') {
                        results.generated_titles.deleted = parseInt(response.data.deleted) || 0;
                    }
                    if (response.data.errors && Array.isArray(response.data.errors)) {
                        results.generated_titles.errors = response.data.errors;
                    }
                    updateProgress(4, totalSteps, '✅ Step 4/7: GeneratedSeoTitles deleted', 'Deleted: ' + results.generated_titles.deleted);
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.generated_titles.errors.push(errorMsg);
                    updateProgress(4, totalSteps, '⚠️ Step 4/7: GeneratedSeoTitles - Some errors', 'Errors: ' + results.generated_titles.errors.length);
                }
                deleteContentStrategies();
            },
            error: function(xhr, status, error) {
                results.generated_titles.errors.push('AJAX error: ' + error);
                updateProgress(4, totalSteps, '❌ Step 4/7: GeneratedSeoTitles - Error', 'Error: ' + error);
                deleteContentStrategies(); // Continue anyway
            }
        });
    }
    
    function deleteContentStrategies() {
        var projectId = getProjectId();
        currentStep = 5;
        updateProgress(5, totalSteps, '⏳ Step 5/7: Deleting Content Strategies...', '');
        
        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_content_strategies',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 60000, // 1 minute
            success: function(response) {
                console.log('[CLEANUP] ContentStrategies response:', response);
                if (response.success && response.data) {
                    // Ensure we preserve the deleted count
                    if (typeof response.data.deleted !== 'undefined') {
                        results.content_strategies.deleted = parseInt(response.data.deleted) || 0;
                    }
                    if (response.data.errors && Array.isArray(response.data.errors)) {
                        results.content_strategies.errors = response.data.errors;
                    }
                    updateProgress(5, totalSteps, '✅ Step 5/7: Content Strategies deleted', 'Deleted: ' + results.content_strategies.deleted);
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.content_strategies.errors.push(errorMsg);
                    updateProgress(5, totalSteps, '⚠️ Step 5/7: Content Strategies - Some errors', 'Errors: ' + results.content_strategies.errors.length);
                }
                cleanupLocalProjectData();
            },
            error: function(xhr, status, error) {
                var errorMsg = error;
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    errorMsg = xhr.responseJSON.data.message;
                }
                results.content_strategies.errors.push('AJAX error: ' + errorMsg);
                updateProgress(5, totalSteps, '❌ Step 5/7: Content Strategies - Error', 'Error: ' + errorMsg);
                cleanupLocalProjectData(); // Continue anyway
            }
        });
    }

    function cleanupLocalProjectData() {
        var projectId = getProjectId();
        currentStep = 6;
        updateProgress(6, totalSteps, '⏳ Step 6/7: Cleaning local project data/caches...', '');

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_cleanup_local_project_data',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa-cleanup')); ?>'
            },
            timeout: 120000,
            success: function(response) {
                if (response.success && response.data) {
                    if (typeof response.data.deleted !== 'undefined') {
                        results.local_project_data.deleted = parseInt(response.data.deleted) || 0;
                    }
                    if (response.data.errors && Array.isArray(response.data.errors)) {
                        results.local_project_data.errors = response.data.errors;
                    }
                    updateProgress(6, totalSteps, '✅ Step 6/7: Local project cleanup done', 'Deleted: ' + results.local_project_data.deleted);
                } else {
                    var errorMsg = 'Unknown error';
                    if (response.data) {
                        if (response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }
                    }
                    results.local_project_data.errors.push(errorMsg);
                    updateProgress(6, totalSteps, '⚠️ Step 6/7: Local project cleanup - Some errors', 'Errors: ' + results.local_project_data.errors.length);
                }
                disconnectGoogleIntegration();
            },
            error: function(xhr, status, error) {
                var errorMsg = error;
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    errorMsg = xhr.responseJSON.data.message;
                }
                results.local_project_data.errors.push('AJAX error: ' + errorMsg);
                updateProgress(6, totalSteps, '❌ Step 6/7: Local project cleanup - Error', 'Error: ' + errorMsg);
                disconnectGoogleIntegration();
            }
        });
    }

    function disconnectGoogleIntegration() {
        var projectId = getProjectId();
        currentStep = 7;
        updateProgress(7, totalSteps, '⏳ Step 7/7: Disconnecting Google + clearing browser project cache...', '');

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_google_disconnect',
                project_id: projectId,
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa_google_oauth_nonce')); ?>'
            },
            timeout: 60000,
            success: function(response) {
                if (!response || response.success !== true) {
                    var errorMsg = 'Google disconnect unavailable';
                    if (response && response.data) {
                        errorMsg = (typeof response.data === 'string') ? response.data : (response.data.message || errorMsg);
                    }
                    results.google_disconnect.errors.push(errorMsg);
                    updateProgress(7, totalSteps, '⚠️ Step 7/7: Google disconnect - Some errors', errorMsg);
                } else {
                    results.google_disconnect.deleted = 1;
                    updateProgress(7, totalSteps, '✅ Step 7/7: Google disconnected', 'Project browser cache cleared.');
                }
                clearBrowserProjectCache();
                showFinalResults();
            },
            error: function(xhr, status, error) {
                var errorMsg = error || 'Unknown error';
                if (xhr.responseJSON && xhr.responseJSON.data) {
                    errorMsg = (typeof xhr.responseJSON.data === 'string') ? xhr.responseJSON.data : (xhr.responseJSON.data.message || errorMsg);
                }
                results.google_disconnect.errors.push(errorMsg);
                updateProgress(7, totalSteps, '⚠️ Step 7/7: Google disconnect failed', errorMsg);
                clearBrowserProjectCache();
                showFinalResults();
            }
        });
    }

    function clearBrowserProjectCache() {
        try { localStorage.removeItem('aysa_project_id'); } catch (e) {}
        try { localStorage.removeItem('project_id'); } catch (e) {}
        try { sessionStorage.removeItem('aysa_project_id'); } catch (e) {}
        try { sessionStorage.removeItem('project_id'); } catch (e) {}
        try {
            document.cookie = 'project_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';
            document.cookie = 'project_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/wp-admin';
        } catch (e) {}
    }
    
    function showFinalResults() {
        updateProgress(7, 7, '✅ Cleanup Completed!', '');
        
        var html = '<h2>📊 Cleanup Summary</h2>';
        html += '<table class="widefat" style="margin-top: 20px;">';
        html += '<thead><tr><th>Category</th><th>Deleted</th><th>Errors</th></tr></thead>';
        html += '<tbody>';
        html += '<tr><td><strong>SuggestedKeywords</strong></td><td>' + results.suggested_keywords.deleted + '</td><td>' + results.suggested_keywords.errors.length + '</td></tr>';
        html += '<tr><td><strong>Associations</strong></td><td>' + results.associations.deleted + '</td><td>' + results.associations.errors.length + '</td></tr>';
        html += '<tr><td><strong>WordPress Meta</strong></td><td>' + results.wordpress_meta.deleted + '</td><td>' + results.wordpress_meta.errors.length + '</td></tr>';
        html += '<tr><td><strong>GeneratedSeoTitles</strong></td><td>' + results.generated_titles.deleted + '</td><td>' + results.generated_titles.errors.length + '</td></tr>';
        html += '<tr><td><strong>Content Strategies</strong></td><td>' + results.content_strategies.deleted + '</td><td>' + results.content_strategies.errors.length + '</td></tr>';
        html += '<tr><td><strong>Local Project Data</strong></td><td>' + results.local_project_data.deleted + '</td><td>' + results.local_project_data.errors.length + '</td></tr>';
        html += '<tr><td><strong>Google Disconnect + Browser Cache Reset</strong></td><td>' + results.google_disconnect.deleted + '</td><td>' + results.google_disconnect.errors.length + '</td></tr>';
        html += '</tbody></table>';
        
        // Show errors if any
        var totalErrors = 0;
        var errorsHtml = '';
        for (var category in results) {
            if (results[category].errors && results[category].errors.length > 0) {
                totalErrors += results[category].errors.length;
                errorsHtml += '<div class="notice notice-error"><p><strong>' + category.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()) + ':</strong></p><ul>';
                results[category].errors.slice(0, 10).forEach(function(err) {
                    errorsHtml += '<li>' + err + '</li>';
                });
                if (results[category].errors.length > 10) {
                    errorsHtml += '<li><em>... and ' + (results[category].errors.length - 10) + ' more errors</em></li>';
                }
                errorsHtml += '</ul></div>';
            }
        }
        
        if (totalErrors > 0) {
            html += '<h2>⚠️ Errors (' + totalErrors + ')</h2>';
            html += errorsHtml;
        }
        
        html += '<div class="notice notice-success"><p><strong>✅ Cleanup completed!</strong></p></div>';
        
        $('#cleanup-result').html(html).show();
        $('#start-cleanup-btn').prop('disabled', false).text('🗑️ DELETE ALL DATA FOR SELECTED PROJECT');
    }
});
</script>
