/**
 * ProQyz Migration Admin JS
 * 
 * Handles migration UI interactions and AJAX calls.
 * 
 * @since 2.1.0
 */

(function($) {
    'use strict';

    // Prevent double initialization
    if (window.MigrationAdminInitialized) {
        console.warn('ProQyz Migration Admin: Already initialized, skipping duplicate initialization');
        return;
    }
    window.MigrationAdminInitialized = true;

    const MigrationAdmin = {
        processing: false,

        init: function() {
            // Log debug info if available
            if (typeof proqyzMigration !== 'undefined' && proqyzMigration.debug) {
                console.log('ProQyz Migration Admin: Initializing...');
                // console.log('ProQyz Migration Debug Info:', proqyzMigration.debug);
            }
            this.bindEvents();
        },

        bindEvents: function() {
            // Use event delegation to handle buttons even inside collapsed accordions
            const $body = $(document.body);
            
            // Unbind first to prevent duplicate handlers
            $body.off('click', '#btn-create-tables');
            $body.off('click', '#btn-clear-tables');
            $body.off('click', '#btn-test-connection');
            $body.off('click', '#btn-init-migration');
            $body.off('click', '#btn-process-batch');
            $body.off('click', '#btn-auto-migrate');
            $body.off('click', '#btn-rollback');
            $body.off('click', '#btn-verify-migration');
            $body.off('click', '#btn-reset-migration');

            // Bind events using delegation (works for hidden elements too)
            $body.on('click', '#btn-create-tables', (e) => {
                e.preventDefault();
                console.log('ProQyz: Create Tables button clicked');
                this.createTables();
            });
            $body.on('click', '#btn-clear-tables', (e) => {
                e.preventDefault();
                console.log('ProQyz: Clear Tables button clicked');
                this.clearTables();
            });
            $body.on('click', '#btn-test-connection', (e) => {
                e.preventDefault();
                console.log('ProQyz: Test Connection button clicked');
                this.testConnection();
            });
            $body.on('click', '#btn-init-migration', (e) => {
                e.preventDefault();
                this.initMigration();
            });
            $body.on('click', '#btn-process-batch', (e) => {
                e.preventDefault();
                this.processBatch();
            });
            $body.on('click', '#btn-auto-migrate', (e) => {
                e.preventDefault();
                this.autoMigrate();
            });
            $body.on('click', '#btn-rollback', (e) => {
                e.preventDefault();
                console.log('ProQyz: Rollback button clicked');
                this.rollback();
            });
            $body.on('click', '#btn-verify-migration', (e) => {
                e.preventDefault();
                console.log('ProQyz: Verify button clicked');
                this.verify();
            });
            $body.on('click', '#btn-reset-migration', (e) => {
                e.preventDefault();
                console.log('ProQyz: Reset button clicked');
                this.reset();
            });

            if (typeof proqyzMigration !== 'undefined' && proqyzMigration.debug) {
                console.log('ProQyz Migration Admin: Events bound successfully using delegation');
            }
        },

        createTables: function() {
            if (this.processing) return;

            if (!confirm('This will create the new v2 database tables. Your existing data will not be affected. Continue?')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-create-tables').prop('disabled', true).text('Creating tables...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_create_tables'
                },
                success: (response) => {
                    console.log('Create Tables Response:', response);
                    if (response.success) {
                        this.showMessage('✅ ' + response.data.message + ' Page will reload.', 'success');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                        console.error('Create Tables Error:', response);
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Create Tables AJAX Error:', xhr, status, error);
                    this.showMessage('AJAX Error: ' + xhr.statusText + '<br>Response: ' + xhr.responseText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('🔧 Create New Tables Now');
                }
            });
        },

        clearTables: function() {
            if (this.processing) return;

            const confirmMsg = 'WARNING: This will DELETE all data from the new v2 tables:\n\n' +
                '• wp_st_proqyz_progress_submissions\n' +
                '• wp_st_proqyz_progress_submissions_meta\n\n' +
                'Your ORIGINAL data will NOT be affected.\n\n' +
                'This is useful if migration had errors (e.g., meta table is empty).\n\n' +
                'Are you sure you want to continue?';

            if (!confirm(confirmMsg)) {
                return;
            }

            // Second confirmation
            if (!confirm('Are you ABSOLUTELY SURE? This cannot be undone!')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-clear-tables').prop('disabled', true).text('Clearing tables...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_clear_tables',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    console.log('Clear Tables Response:', response);
                    if (response.success) {
                        const data = response.data;
                        const detailsMsg = data.message + '<br><br>' +
                            '<strong>Details:</strong><br>' +
                            '• Progress data cleared: ' + (data.progress_cleared ? '✓' : '✗') + '<br>' +
                            '• Error logs cleared: ' + (data.logs_cleared ? '✓' : '✗') + '<br>' +
                            '• ID mappings cleared: ' + (data.mappings_cleared ? '✓' : '✗') + '<br><br>' +
                            '<em>Page will reload in 2 seconds...</em>';
                        
                        this.showMessage(detailsMsg, 'success');
                        setTimeout(() => location.reload(), 2000);
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                        console.error('Clear Tables Error:', response);
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Clear Tables AJAX Error:', xhr, status, error);
                    this.showMessage('AJAX Error: ' + xhr.statusText + '<br>Response: ' + xhr.responseText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('🗑️ Clear New Tables & Reset Migration');
                }
            });
        },

        testConnection: function() {
            if (this.processing) return;

            this.processing = true;
            const $btn = $('#btn-test-connection').prop('disabled', true).text('Testing...');

            console.log('Testing AJAX connection...');
            console.log('AJAX URL:', proqyzMigration.ajaxurl);
            console.log('Nonce:', proqyzMigration.nonce);

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_test_connection'
                    // No nonce for basic connection test
                },
                success: (response) => {
                    console.log('Test Response:', response);
                    if (response.success) {
                        this.showMessage('✅ Connection successful! AJAX is working. Data: ' + JSON.stringify(response.data), 'success');
                    } else {
                        this.showMessage('❌ Connection failed: ' + JSON.stringify(response), 'error');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Connection Test Error:', xhr, status, error);
                    this.showMessage('❌ AJAX Error: ' + xhr.status + ' ' + xhr.statusText + '<br>Response: ' + xhr.responseText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('🔧 Test AJAX Connection');
                }
            });
        },

        showMessage: function(message, type = 'info') {
            const $messages = $('#migration-messages');
            const messageClass = type === 'success' ? 'success' : type === 'error' ? 'error' : 'info';
            
            const $msg = $('<div>', {
                class: 'migration-message ' + messageClass,
                html: message
            });

            $messages.empty().append($msg);
            
            // Scroll to message
            $('html, body').animate({
                scrollTop: $messages.offset().top - 100
            }, 500);

            // Auto-remove after 10 seconds for success messages
            if (type === 'success') {
                setTimeout(() => $msg.fadeOut(() => $msg.remove()), 10000);
            }
        },

        updateProgress: function(progress) {
            if (!progress) return;

            // Handle both init response and progress response
            const totalRecords = progress.total_records || 0;
            const processed = progress.processed || 0;
            const errors = progress.errors || 0;
            const percentage = progress.percentage || 0;
            const status = progress.status || 'unknown';

            $('.stat-value').eq(1).text(parseInt(totalRecords).toLocaleString());
            $('.stat-value').eq(2).text(parseInt(processed).toLocaleString());
            $('.stat-value').eq(3).text(parseInt(errors).toLocaleString());
            $('.stat-value').eq(4).text(parseFloat(percentage).toFixed(2) + '%');
            
            $('.progress-bar').css('width', percentage + '%');
            $('.progress-text').text(parseFloat(percentage).toFixed(2) + '%');
            
            const statusText = status.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
            $('.stat-value').eq(0)
                .text(statusText)
                .removeClass('status-not_started status-initialized status-running status-paused status-completed')
                .addClass('status-' + status);
        },

        initMigration: function() {
            if (this.processing) {
                console.warn('ProQyz Migration: Request already in progress, ignoring duplicate click');
                return;
            }

            if (!confirm('This will analyze your database and prepare for migration. Continue?')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-init-migration').prop('disabled', true).text('Initializing...');

            console.log('ProQyz Migration: Sending init_migration request...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_init_migration',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    console.log('Init Migration Response:', response);
                    if (response.success) {
                        this.showMessage(response.data.message, 'success');
                        // Don't update progress here - page will reload with fresh data
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                        console.error('Migration Error:', response);
                    }
                },
                error: (xhr, status, error) => {
                    console.error('AJAX Error:', xhr.responseText, status, error);
                    this.showMessage('AJAX Error: ' + xhr.statusText + ' - ' + error + '<br>Response: ' + xhr.responseText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('Initialize Migration');
                    console.log('ProQyz Migration: init_migration request completed');
                }
            });
        },

        processBatch: function() {
            if (this.processing) {
                console.warn('ProQyz Migration: Request already in progress, ignoring duplicate click');
                return;
            }

            this.processing = true;
            console.log('ProQyz Migration: Sending process_batch request...');
            const $btn = $('#btn-process-batch').prop('disabled', true).text('Processing...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_process_batch',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    if (response.success) {
                        if (response.data.is_complete) {
                            this.showMessage('✅ Step 1 Complete! Database migrated to v2. Next: Update plugin to v2.1.0+ to unlock features. Reloading...', 'success');
                        } else {
                            this.showMessage(response.data.message, 'success');
                        }
                        this.updateProgress(response.data.progress);

                        if (response.data.is_complete) {
                            setTimeout(() => location.reload(), 2000);
                        }
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                    }
                },
                error: (xhr) => {
                    this.showMessage('AJAX Error: ' + xhr.statusText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('Process Next Batch');
                }
            });
        },

        autoMigrate: function() {
            if (this.processing) return;

            if (!confirm('This will process ALL remaining batches automatically. This may take several minutes. Continue?')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-auto-migrate').prop('disabled', true).text('Auto-migrating...');

            this.processNextBatchAuto($btn);
        },

        processNextBatchAuto: function($btn) {
            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_process_batch',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.updateProgress(response.data.progress);
                        
                        if (response.data.is_complete) {
                            this.showMessage('🎉 Step 1 Complete! Database migrated. Next: Update plugin to v2.1.0+ from WordPress Updates. Reloading...', 'success');
                            setTimeout(() => location.reload(), 2000);
                        } else {
                            // Process next batch
                            this.showMessage(response.data.message, 'info');
                            setTimeout(() => this.processNextBatchAuto($btn), 500);
                        }
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                        this.processing = false;
                        $btn.prop('disabled', false).text('Auto-Complete All Batches');
                    }
                },
                error: (xhr) => {
                    this.showMessage('AJAX Error: ' + xhr.statusText, 'error');
                    this.processing = false;
                    $btn.prop('disabled', false).text('Auto-Complete All Batches');
                }
            });
        },

        rollback: function() {
            if (this.processing) return;

            if (!confirm('WARNING: This will delete all migrated data from the new tables and switch you back to v1 update channel (security fixes only). Continue?')) {
                return;
            }

            if (!confirm('Are you ABSOLUTELY sure? You will lose access to v2 features and updates!')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-rollback').prop('disabled', true).text('Rolling back...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_rollback_migration',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showMessage('⚠️ ' + response.data.message + ' You are now on v1 update channel. Page will reload.', 'success');
                        setTimeout(() => location.reload(), 2000);
                    } else {
                        const errorMsg = response.data && response.data.message ? response.data.message : JSON.stringify(response.data);
                        this.showMessage('Error: ' + errorMsg, 'error');
                    }
                },
                error: (xhr) => {
                    this.showMessage('AJAX Error: ' + xhr.statusText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('Rollback Migration');
                }
            });
        },

        verify: function() {
            if (this.processing) return;

            this.processing = true;
            const $btn = $('#btn-verify-migration').prop('disabled', true).text('Verifying...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_verify_migration',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    if (response.success) {
                        const data = response.data;
                        const metaCount = data.meta_count || 0;
                        const avgMetaPerRecord = data.new_table_count > 0 ? (metaCount / data.new_table_count).toFixed(2) : 0;
                        
                        const message = `
                            <strong>Verification Results:</strong><br>
                            Old Table: ${data.old_table_count.toLocaleString()} records (filtered: status=1, session_status!=3)<br>
                            New Submissions Table: ${data.new_table_count.toLocaleString()} records<br>
                            New Meta Table: ${metaCount.toLocaleString()} entries (avg ${avgMetaPerRecord} per submission)<br>
                            Mapped: ${data.mapped_records.toLocaleString()} records<br>
                            <strong>Status:</strong> ${data.message}<br><br>
                            ${metaCount === 0 && data.new_table_count > 0 ? '<span style="color: red;">⚠️ WARNING: Meta table is empty! Use "Clear New Tables" button to retry migration.</span>' : ''}
                        `;
                        this.showMessage(message, data.is_valid && metaCount > 0 ? 'success' : 'error');
                    } else {
                        this.showMessage('Error: ' + (response.data || 'Unknown error'), 'error');
                    }
                },
                error: (xhr) => {
                    this.showMessage('AJAX Error: ' + xhr.statusText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('Verify Migration');
                }
            });
        },

        reset: function() {
            if (this.processing) return;

            if (!confirm('This will reset the migration progress but keep migrated data. Continue?')) {
                return;
            }

            this.processing = true;
            const $btn = $('#btn-reset-migration').prop('disabled', true).text('Resetting...');

            $.ajax({
                url: proqyzMigration.ajaxurl,
                type: 'POST',
                data: {
                    action: 'proqyz_reset_migration',
                    nonce: proqyzMigration.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showMessage(response.data.message, 'success');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        this.showMessage('Error: ' + (response.data || 'Unknown error'), 'error');
                    }
                },
                error: (xhr) => {
                    this.showMessage('AJAX Error: ' + xhr.statusText, 'error');
                },
                complete: () => {
                    this.processing = false;
                    $btn.prop('disabled', false).text('Reset Migration');
                }
            });
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        MigrationAdmin.init();
    });

})(jQuery);

