<?php


if (!defined('ABSPATH')) {
    exit;
}
?>

<div class="wrap aieo-wrap">
    <h1><?php esc_html_e('Session Schema Migration', 'ai-eshop-optimizer'); ?></h1>

    <div class="aieo-migration-status">
        <h2><?php esc_html_e('Current Status', 'ai-eshop-optimizer'); ?></h2>

        <table class="widefat">
            <tbody>
                <tr>
                    <td><strong><?php esc_html_e('Sessions Table Exists', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['sessions_table_exists'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Statics Table Exists', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['statics_table_exists'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Has product_id Column', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['has_product_id_column'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Has scroll_depth Column', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['has_scroll_depth_column'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Has Attention Analytics Columns', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['has_attention_analytics_columns'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Has Statics Summary Columns', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['has_statics_summary_columns'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <tr style="border-top: 2px solid #ddd;">
                    <td colspan="2"><strong><?php esc_html_e('Chat Embeddings Table', 'ai-eshop-optimizer'); ?></strong></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Embeddings Table Exists', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['embeddings_table_exists'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <?php if ($status['embeddings_table_exists']): ?>
                <tr>
                    <td><strong><?php esc_html_e('Has Failure Tracking Columns', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo $status['has_embeddings_failure_columns'] ? '✅ Yes' : '❌ No'; ?></td>
                </tr>
                <?php endif; ?>
                <tr style="border-top: 2px solid #ddd;">
                    <td colspan="2"><strong><?php esc_html_e('Event Statistics', 'ai-eshop-optimizer'); ?></strong></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Total Events', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo number_format($status['total_events']); ?></td>
                </tr>
                <?php if ($status['has_product_id_column']): ?>
                <tr>
                    <td><strong><?php esc_html_e('Events with product_id', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo number_format($status['events_with_product_id']); ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e('Events Needing Backfill', 'ai-eshop-optimizer'); ?></strong></td>
                    <td><?php echo number_format($status['events_needing_backfill']); ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <?php if ($status['migration_needed']): ?>
            <div class="notice notice-warning">
                <p><strong><?php esc_html_e('Migration Required', 'ai-eshop-optimizer'); ?></strong></p>
                <p><?php esc_html_e('Your session tracking tables need to be migrated to the optimized schema for better performance.', 'ai-eshop-optimizer'); ?></p>
            </div>
        <?php elseif ($status['migration_recommended']): ?>
            <div class="notice notice-info">
                <p><strong><?php esc_html_e('Migration Recommended', 'ai-eshop-optimizer'); ?></strong></p>
                <p><?php esc_html_e('Some existing data can be backfilled to take advantage of the optimized schema.', 'ai-eshop-optimizer'); ?></p>
            </div>
        <?php else: ?>
            <div class="notice notice-success">
                <p><strong><?php esc_html_e('Schema Up to Date', 'ai-eshop-optimizer'); ?></strong></p>
                <p><?php esc_html_e('Your session tracking tables are using the optimized schema.', 'ai-eshop-optimizer'); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <?php if ($status['migration_needed'] || $status['migration_recommended']): ?>
    <div class="aieo-migration-actions">
        <h2><?php esc_html_e('Run Migration', 'ai-eshop-optimizer'); ?></h2>

        <p><?php esc_html_e('This process will:', 'ai-eshop-optimizer'); ?></p>
        <ul>
            <li>✓ <?php esc_html_e('Add optimized columns (product_id, category_name, scroll_depth, click_count)', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Add attention analytics columns (event_sequence, time_on_page, visit_number, order_id, checkout_step)', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Add position tracking flags (is_first_event, is_last_event, is_only_event)', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Backfill existing data from JSON (optional - only for old 6 columns)', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Update session summary statistics', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Add performance indexes for all analytics queries', 'ai-eshop-optimizer'); ?></li>
        </ul>

        <p><strong><?php esc_html_e('Estimated time:', 'ai-eshop-optimizer'); ?></strong>
            <?php
            $estimated_minutes = ceil($status['total_events'] / 10000); 
            printf(
                
                esc_html__('%1$d minutes for %2$s events', 'ai-eshop-optimizer'),
                (int) $estimated_minutes,
                esc_html(number_format($status['total_events']))
            );
            ?>
        </p>

        <button type="button" id="aieo-start-migration" class="button button-primary button-hero">
            <?php esc_html_e('Start Migration', 'ai-eshop-optimizer'); ?>
        </button>

        <div id="aieo-migration-progress" style="display: none; margin-top: 20px;">
            <h3><?php esc_html_e('Migration Progress', 'ai-eshop-optimizer'); ?></h3>

            <div class="aieo-progress-bar-container">
                <div id="aieo-migration-progress-bar" class="aieo-progress-bar" style="width: 0%;"></div>
            </div>
            <p id="aieo-migration-status"><?php esc_html_e('Initializing...', 'ai-eshop-optimizer'); ?></p>

            <div id="aieo-migration-log" style="max-height: 400px; overflow-y: auto; background: #f5f5f5; padding: 15px; margin-top: 15px; font-family: monospace; font-size: 12px;"></div>
        </div>
    </div>
    <?php endif; ?>

    <div class="aieo-migration-info">
        <h2><?php esc_html_e('About This Migration', 'ai-eshop-optimizer'); ?></h2>

        <h3><?php esc_html_e('What gets migrated?', 'ai-eshop-optimizer'); ?></h3>
        <p><?php esc_html_e('This migration extracts frequently-queried fields from JSON storage into dedicated database columns:', 'ai-eshop-optimizer'); ?></p>

        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e('Column', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Extracted From', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Purpose', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Performance Gain', 'ai-eshop-optimizer'); ?></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><code>product_id</code></td>
                    <td><code>event_data.product_id</code></td>
                    <td><?php esc_html_e('Fast product filtering & analytics', 'ai-eshop-optimizer'); ?></td>
                    <td><strong>200-500x faster</strong></td>
                </tr>
                <tr>
                    <td><code>product_name</code></td>
                    <td><code>event_data.product_name</code></td>
                    <td><?php esc_html_e('Cached for display without JOIN', 'ai-eshop-optimizer'); ?></td>
                    <td>50x faster</td>
                </tr>
                <tr>
                    <td><code>category_id</code></td>
                    <td><code>event_data.category_id</code></td>
                    <td><?php esc_html_e('Category-level analytics', 'ai-eshop-optimizer'); ?></td>
                    <td>200x faster</td>
                </tr>
                <tr>
                    <td><code>scroll_depth</code></td>
                    <td><code>event_data.scroll_depth</code></td>
                    <td><?php esc_html_e('Engagement analysis', 'ai-eshop-optimizer'); ?></td>
                    <td>100x faster</td>
                </tr>
                <tr>
                    <td><code>click_count</code></td>
                    <td><code>event_data.click_count</code></td>
                    <td><?php esc_html_e('Interaction tracking', 'ai-eshop-optimizer'); ?></td>
                    <td>100x faster</td>
                </tr>
            </tbody>
        </table>

        <h3><?php esc_html_e('Is this safe?', 'ai-eshop-optimizer'); ?></h3>
        <p><?php esc_html_e('Yes! This migration:', 'ai-eshop-optimizer'); ?></p>
        <ul>
            <li>✓ <?php esc_html_e('Does NOT delete any existing data', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Keeps original JSON data intact', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Can be run multiple times safely', 'ai-eshop-optimizer'); ?></li>
            <li>✓ <?php esc_html_e('Works in batches to avoid timeouts', 'ai-eshop-optimizer'); ?></li>
        </ul>

        <h3><?php esc_html_e('What if something goes wrong?', 'ai-eshop-optimizer'); ?></h3>
        <p><?php esc_html_e('The migration can be safely restarted. Original data remains in the event_data column.', 'ai-eshop-optimizer'); ?></p>
    </div>
</div>

<style>
.aieo-progress-bar-container {
    width: 100%;
    height: 30px;
    background: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 3px;
    overflow: hidden;
}

.aieo-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #2271b1 0%, #3582c4 100%);
    transition: width 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
}

.aieo-migration-log div {
    margin: 5px 0;
    padding: 5px;
}

.aieo-log-success {
    color: #46b450;
}

.aieo-log-error {
    color: #dc3232;
}

.aieo-log-info {
    color: #2271b1;
}

.aieo-migration-status table {
    margin-top: 15px;
}
</style>

<script>
jQuery(document).ready(function($) {
    let migrationRunning = false;

    $('#aieo-start-migration').on('click', function() {
        if (migrationRunning) {
            return;
        }

        if (!confirm('<?php echo esc_js(__('Start schema migration? This may take a few minutes.', 'ai-eshop-optimizer')); ?>')) {
            return;
        }

        migrationRunning = true;
        $(this).prop('disabled', true);
        $('#aieo-migration-progress').show();

        runMigration();
    });

    function runMigration() {
        logMessage(<?php echo wp_json_encode(__('Starting migration...', 'ai-eshop-optimizer')); ?>, 'info');

        // Step 1: Add columns
        addColumns();
    }

    function addColumns() {
        logMessage(<?php echo wp_json_encode(__('Step 1: Adding optimized columns and indexes...', 'ai-eshop-optimizer')); ?>, 'info');
        updateProgress(10, <?php echo wp_json_encode(__('Adding columns...', 'ai-eshop-optimizer')); ?>);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_run_migration',
                nonce: '<?php echo esc_js($nonce); ?>',
                step: 'add_columns'
            },
            success: function(response) {
                if (response.success) {
                    response.data.messages.forEach(msg => logMessage(msg, 'success'));
                    if (response.data.errors.length > 0) {
                        response.data.errors.forEach(err => logMessage(err, 'error'));
                    }
                    updateProgress(30, <?php echo wp_json_encode(__('Columns added', 'ai-eshop-optimizer')); ?>);
                    // Step 2: Backfill data
                    backfillData(0);
                } else {
                    logMessage(<?php echo wp_json_encode(__('Failed to add columns: ', 'ai-eshop-optimizer')); ?> + response.data.message, 'error');
                    completeMigration(false);
                }
            },
            error: function() {
                logMessage(<?php echo wp_json_encode(__('AJAX error during column addition', 'ai-eshop-optimizer')); ?>, 'error');
                completeMigration(false);
            }
        });
    }

    function backfillData(offset) {
        logMessage(<?php echo wp_json_encode(__('Step 2: Backfilling data (offset: ', 'ai-eshop-optimizer')); ?> + offset + ')...', 'info');
        updateProgress(30 + (offset / <?php echo (int) max($status['total_events'], 1); ?> * 50), <?php echo wp_json_encode(__('Backfilling data...', 'ai-eshop-optimizer')); ?>);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_run_migration',
                nonce: '<?php echo esc_js($nonce); ?>',
                step: 'backfill_data',
                offset: offset
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    logMessage(
                        <?php echo wp_json_encode(__('Backfilled ', 'ai-eshop-optimizer')); ?> + data.rows_updated + <?php echo wp_json_encode(__(' rows (', 'ai-eshop-optimizer')); ?> +
                        data.product_rows + <?php echo wp_json_encode(__(' products, ', 'ai-eshop-optimizer')); ?> +
                        data.scroll_rows + <?php echo wp_json_encode(__(' scroll, ', 'ai-eshop-optimizer')); ?> +
                        data.click_rows + <?php echo wp_json_encode(__(' clicks). Remaining: ', 'ai-eshop-optimizer')); ?> + data.remaining,
                        'success'
                    );

                    if (data.complete) {
                        // Step 3: Update summary
                        updateSummary();
                    } else {
                        // Continue backfill
                        backfillData(offset + 10000);
                    }
                } else {
                    // Handle error from response - check both message and error fields
                    const errorMsg = response.data.message || response.data.error || <?php echo wp_json_encode(__('Unknown error', 'ai-eshop-optimizer')); ?>;
                    logMessage(<?php echo wp_json_encode(__('Backfill failed: ', 'ai-eshop-optimizer')); ?> + errorMsg, 'error');
                    completeMigration(false);
                }
            },
            error: function() {
                logMessage(<?php echo wp_json_encode(__('AJAX error during backfill', 'ai-eshop-optimizer')); ?>, 'error');
                completeMigration(false);
            }
        });
    }

    function updateSummary() {
        logMessage(<?php echo wp_json_encode(__('Step 3: Updating session summaries...', 'ai-eshop-optimizer')); ?>, 'info');
        updateProgress(85, <?php echo wp_json_encode(__('Updating summaries...', 'ai-eshop-optimizer')); ?>);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_run_migration',
                nonce: '<?php echo esc_js($nonce); ?>',
                step: 'update_summary'
            },
            success: function(response) {
                if (response.success) {
                    logMessage(response.data.message, 'success');
                    completeMigration(true);
                } else {
                    logMessage(<?php echo wp_json_encode(__('Summary update failed: ', 'ai-eshop-optimizer')); ?> + response.data.message, 'error');
                    completeMigration(false);
                }
            },
            error: function() {
                logMessage(<?php echo wp_json_encode(__('AJAX error during summary update', 'ai-eshop-optimizer')); ?>, 'error');
                completeMigration(false);
            }
        });
    }

    function completeMigration(success) {
        migrationRunning = false;

        if (success) {
            updateProgress(100, <?php echo wp_json_encode(__('Migration complete!', 'ai-eshop-optimizer')); ?>);
            logMessage(<?php echo wp_json_encode(__('✅ Migration completed successfully!', 'ai-eshop-optimizer')); ?>, 'success');
            logMessage(<?php echo wp_json_encode(__('Your session tracking is now using the optimized schema.', 'ai-eshop-optimizer')); ?>, 'success');

            setTimeout(function() {
                location.reload();
            }, 2000);
        } else {
            logMessage(<?php echo wp_json_encode(__('❌ Migration failed. Please check the log above.', 'ai-eshop-optimizer')); ?>, 'error');
            $('#aieo-start-migration').prop('disabled', false);
        }
    }

    function updateProgress(percent, message) {
        $('#aieo-migration-progress-bar').css('width', percent + '%').text(Math.round(percent) + '%');
        $('#aieo-migration-status').text(message);
    }

    function logMessage(message, type) {
        const className = 'aieo-log-' + type;
        const timestamp = new Date().toLocaleTimeString();
        const $entry = $('<div></div>')
            .addClass(className)
            .text('[' + timestamp + '] ' + message);

        $('#aieo-migration-log').append($entry);
        $('#aieo-migration-log').scrollTop($('#aieo-migration-log')[0].scrollHeight);
    }
});
</script>
