<?php
/**
 * ProQyz Migration Admin Page - V2 Modern Design
 * 
 * Step-by-step accordion interface for database migration
 * 
 * @package Spacetree
 * @since   2.1.0
 */

defined( 'ABSPATH' ) || exit;

// Load migration utility class
require_once ST_ABSPATH . 'includes/admin/classes/class-st-proqyz-migration.php';

// Get migration status
$migration = new ST_ProQyz_Migration();
$status = $migration->get_migration_status();

global $wpdb, $st_db_version_key;
global $table_proqyz_progress_submissions, $table_proqyz_progress_submissions_meta;

$db_version = get_option( $st_db_version_key, '1.0' );
$migration_required = version_compare( $db_version, ST_DB_VERSION, '<' );
$plugin_version = defined('ST_VERSION') ? ST_VERSION : '2.0.5.2';
$plugin_needs_update = version_compare($plugin_version, '2.1.0', '<');

// Check if tables exist
$submissions_table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_proqyz_progress_submissions}'") === $table_proqyz_progress_submissions;
$meta_table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_proqyz_progress_submissions_meta}'") === $table_proqyz_progress_submissions_meta;
$tables_exist = $submissions_table_exists && $meta_table_exists;

// Helper function to convert PHP ini size values to bytes
function st_convert_to_bytes($value) {
	if (is_numeric($value)) {
		return (int) $value;
	}
	$value = trim($value);
	$last = strtolower($value[strlen($value) - 1]);
	$value = (int) $value;
	switch ($last) {
		case 'g':
			$value *= 1024;
		case 'm':
			$value *= 1024;
		case 'k':
			$value *= 1024;
	}
	return $value;
}

// Helper function to format bytes for display
function st_format_bytes($bytes, $precision = 2) {
	$units = array('B', 'KB', 'MB', 'GB', 'TB');
	if ($bytes == 0) return '0 B';
	$base = log($bytes, 1024);
	return round(pow(1024, $base - floor($base)), $precision) . ' ' . $units[floor($base)];
}

// Helper function to format seconds for display
function st_format_seconds($seconds) {
	if ($seconds >= 60) {
		$minutes = floor($seconds / 60);
		$remaining_seconds = $seconds % 60;
		return $minutes . ' min' . ($remaining_seconds > 0 ? ' ' . $remaining_seconds . ' sec' : '');
	}
	return $seconds . ' sec';
}

// Check PHP configuration requirements
$php_requirements = array(
	'max_execution_time' => array(
		'name' => 'max_execution_time',
		'label' => 'PHP max_execution_time',
		'required' => 120, // 2 minutes in seconds
		'current' => (int) ini_get('max_execution_time'),
		'unit' => 'seconds',
		'pass' => false
	),
	'max_input_vars' => array(
		'name' => 'max_input_vars',
		'label' => 'PHP max_input_vars',
		'required' => 5000,
		'current' => (int) ini_get('max_input_vars'),
		'unit' => '',
		'pass' => false
	),
	'memory_limit' => array(
		'name' => 'memory_limit',
		'label' => 'PHP memory_limit',
		'required' => st_convert_to_bytes('1024M'),
		'current' => st_convert_to_bytes(ini_get('memory_limit')),
		'unit' => 'bytes',
		'pass' => false
	),
	'post_max_size' => array(
		'name' => 'post_max_size',
		'label' => 'PHP post_max_size',
		'required' => st_convert_to_bytes('500M'),
		'current' => st_convert_to_bytes(ini_get('post_max_size')),
		'unit' => 'bytes',
		'pass' => false
	),
	'upload_max_filesize' => array(
		'name' => 'upload_max_filesize',
		'label' => 'PHP upload_max_filesize',
		'required' => st_convert_to_bytes('256M'),
		'current' => st_convert_to_bytes(ini_get('upload_max_filesize')),
		'unit' => 'bytes',
		'pass' => false
	)
);

// Check each requirement
foreach ($php_requirements as $key => &$req) {
	// Handle special cases: 0 means unlimited for max_execution_time, -1 means unlimited for memory_limit
	if ($req['name'] === 'max_execution_time') {
		$req['pass'] = $req['current'] == 0 || $req['current'] >= $req['required'];
	} elseif ($req['name'] === 'memory_limit') {
		$req['pass'] = $req['current'] == -1 || $req['current'] >= $req['required'];
	} else {
		$req['pass'] = $req['current'] >= $req['required'];
	}
}

// Determine if all requirements are met
$step2_complete = true;
foreach ($php_requirements as $req) {
	if (!$req['pass']) {
		$step2_complete = false;
		break;
	}
}

// Determine step completion
$step1_complete = $tables_exist;
$step3_complete = $status['status'] === 'initialized' || $status['status'] === 'paused' || $status['status'] === 'completed';
$step4_complete = $status['status'] === 'completed';
$step5_complete = $step4_complete; // Verify (optional)
$step6_complete = !$plugin_needs_update && $step4_complete; // Plugin updated

// Determine active step
$active_step = 1;
if ($step6_complete) $active_step = 6; // All done (plugin updated)
elseif ($step5_complete) $active_step = 5; // Verify (migration done, plugin needs update)
elseif ($step4_complete) $active_step = 4; // Run migration
elseif ($step3_complete) $active_step = 3; // Initialize
elseif ($step2_complete && $step1_complete) $active_step = 2; // Minimum Requirements (if Step 1 complete)
elseif ($step1_complete) $active_step = 2; // Minimum Requirements
else $active_step = 1; // Create tables

// Enqueue scripts directly from root Spacetree structure (not ProQyz library)
// This ensures scripts load correctly even when ProQyz library switches to v2
wp_enqueue_script( 'jquery' );
wp_enqueue_script(
	'st-migration-admin',
	plugin_dir_url( ST_PLUGIN_FILE ) . 'includes/admin/js/migration-admin.js',
	array( 'jquery' ),
	'2.1.0',
	true
);

// Get the correct admin-ajax.php URL (preserves port for local dev)
$ajax_url = admin_url( 'admin-ajax.php' );

// Fix for local development with ports
if ( isset( $_SERVER['HTTP_HOST'] ) ) {
	$current_host = $_SERVER['HTTP_HOST'];
	$ajax_host = parse_url( $ajax_url, PHP_URL_HOST );
	
	if ( $current_host !== $ajax_host && strpos( $current_host, ':' ) !== false ) {
		$ajax_url = str_replace( $ajax_host, $current_host, $ajax_url );
	}
}

wp_localize_script(
	'st-migration-admin',
	'proqyzMigration',
	array(
		'ajaxurl' => $ajax_url,
		'nonce' => wp_create_nonce( 'proqyz_migration_nonce' ),
		'debug' => array(
			'current_host' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'unknown',
			'ajax_url_original' => admin_url( 'admin-ajax.php' ),
			'ajax_url_fixed' => $ajax_url,
			'script_source' => 'root_spacetree_structure'
		)
	)
);

?>
<style>
.proqyz-migration-v2 {
	max-width: 900px;
	margin: 20px auto;
	padding: 0 20px;
}

.proqyz-migration-v2 h1 {
	text-align: center;
	margin-bottom: 10px;
	color: #1d2327;
}

.proqyz-migration-v2 > p {
	text-align: center;
	font-size: 14px;
	color: #646970;
	margin-top: 0;
	margin-bottom: 30px;
}

.migration-progress-bar {
	background: #e0e0e0;
	height: 12px;
	border-radius: 6px;
	margin: 30px 0;
	overflow: hidden;
	box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

.migration-progress-fill {
	background: linear-gradient(90deg, #2271b1, #135e96);
	height: 100%;
	transition: width 0.3s ease;
	box-shadow: 0 1px 3px rgba(34, 113, 177, 0.3);
}

.migration-steps {
	margin-top: 30px;
}

.migration-step {
	background: white;
	border: 2px solid #e0e0e0;
	border-radius: 14px;
	margin-bottom: 15px;
	transition: all 0.3s ease;
	overflow: hidden;
}

.migration-step.active {
	border-color: #2271b1;
	box-shadow: 0 4px 12px rgba(34, 113, 177, 0.15);
}

.migration-step.completed {
	border-color: #46b450;
}

.migration-step.locked {
	opacity: 0.6;
	background: #f9f9f9;
}

.step-header {
	padding: 20px 25px;
	cursor: pointer;
	display: flex;
	align-items: center;
	gap: 15px;
	transition: background 0.2s;
}

.migration-step.active .step-header {
	background: #f0f6fc;
}

.migration-step.completed .step-header {
	background: #f0f9f1;
}

.step-header:hover:not(.locked) {
	background: #fafafa;
}

.step-number {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: bold;
	font-size: 18px;
	flex-shrink: 0;
}

.migration-step .step-number {
	background: #e0e0e0;
	color: #666;
	border: 2px solid #ddd;
}

.migration-step.locked .step-number {
	background: #f0f0f0;
	color: #666;
	border: 2px solid #ddd;
}

.migration-step.locked .step-number:hover {
	background: #e8e8e8;
}

.migration-step.active .step-number {
	background: #2271b1;
	color: white;
}

.migration-step.completed .step-number {
	background: #46b450;
	color: white;
	position: relative;
}

.migration-step.completed .step-number::before {
	content: "✓";
	font-size: 20px;
	font-weight: bold;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.migration-step.active .step-number {
	background: #2271b1;
	color: white;
	position: relative;
}

.migration-step.active .step-number::before {
	content: "▶";
	font-size: 16px;
	font-weight: bold;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

/* Hide text content when icons are shown */
.migration-step.completed .step-number,
.migration-step.active .step-number {
	color: transparent;
}

.migration-step.completed .step-number::before,
.migration-step.active .step-number::before {
	color: white;
}

.step-title-area {
	flex: 1;
}

.step-title {
	font-size: 18px;
	font-weight: 600;
	margin: 0 0 5px 0;
	color: #1d2327;
}

.step-description {
	font-size: 13px;
	color: #646970;
	margin: 0;
}

.step-status {
	padding: 4px 12px;
	border-radius: 12px;
	font-size: 12px;
	font-weight: 600;
	text-transform: uppercase;
	letter-spacing: 0.5px;
}

.status-pending {
	background: #f0f0f1;
	color: #646970;
}

.status-active {
	background: #e5f2ff;
	color: #2271b1;
}

.status-completed {
	background: #e7f5e8;
	color: #46b450;
}

.step-content {
	padding: 0 25px;
	max-height: 0;
	overflow: hidden;
	transition: max-height 0.3s ease, padding 0.3s ease;
}

.migration-step.active .step-content {
	max-height: 2000px;
	padding: 0 25px 25px 25px;
}

.step-inner {
	padding-top: 20px;
	border-top: 1px solid #e0e0e0;
}

.step-actions {
	margin-top: 20px;
	display: flex;
	gap: 10px;
	align-items: center;
}

.migration-info-box {
	padding: 15px;
	margin: 15px 0;
	border-radius: 4px;
}

.migration-info-box.success {
	background: #f0f9f1;
	border-color: #46b450;
}

.migration-info-box.warning {
	background: #fff8e5;
	border-color: #ffb900;
}

.migration-info-box.error {
	background: #ffebee;
	border-color: #dc3232;
}

.migration-stats {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
	gap: 15px;
	margin: 15px 0;
}

.stat-card {
	background: white;
	border: 1px solid #e0e0e0;
	border-radius: 6px;
	padding: 15px;
	text-align: center;
}

.stat-value {
	font-size: 32px;
	font-weight: bold;
	color: #2271b1;
	display: block;
}

.stat-label {
	font-size: 13px;
	color: #646970;
	margin-top: 5px;
	display: block;
}

.batch-progress {
	background: #f0f0f1;
	height: 30px;
	border-radius: 4px;
	overflow: hidden;
	margin: 15px 0;
	position: relative;
}

.batch-progress-bar {
	background: linear-gradient(90deg, #46b450, #399946);
	height: 100%;
	transition: width 0.3s ease;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-weight: bold;
	font-size: 13px;
}

.migration-messages {
	margin-top: 20px;
}

.migration-message {
	padding: 12px 15px;
	border-radius: 4px;
	margin-bottom: 10px;
	border-left: 4px solid;
}

.migration-message.success {
	background: #f0f9f1;
	border-color: #46b450;
	color: #2c5a2e;
}

.migration-message.error {
	background: #ffebee;
	border-color: #dc3232;
	color: #8a2424;
}

.migration-message.info {
	background: #f0f6fc;
	border-color: #2271b1;
	color: #135e96;
}

.celebration {
	text-align: center;
	padding: 40px 20px;
}

.celebration-icon {
	font-size: 64px;
	margin-bottom: 20px;
}

.btn-icon {
	margin-right: 5px;
}

.chevron {
	transition: transform 0.3s ease;
	font-size: 20px;
	color: #646970;
}

.migration-step.active .chevron {
	transform: rotate(180deg);
}

.advanced-options {
	margin-top: 30px;
	padding-top: 25px;
	border-top: 2px solid #e0e0e0;
	background: #fafafa;
	border-radius: 8px;
	padding: 20px;
}

.advanced-options summary {
	cursor: pointer;
	font-weight: 600;
	color: #2271b1;
	padding: 15px 20px;
	border-radius: 8px;
	user-select: none;
	background: linear-gradient(135deg, #f0f6fc, #e5f2ff);
	border: 1px solid #c3d9ff;
	transition: all 0.3s ease;
	display: flex;
	align-items: center;
	gap: 10px;
	font-size: 16px;
}

.advanced-options summary:hover {
	background: linear-gradient(135deg, #e5f2ff, #d1e7ff);
	border-color: #2271b1;
	transform: translateY(-1px);
	box-shadow: 0 4px 12px rgba(34, 113, 177, 0.15);
}

.advanced-options summary::marker {
	display: none;
}

.advanced-options summary::-webkit-details-marker {
	display: none;
}

.advanced-options[open] summary {
	border-bottom-left-radius: 0;
	border-bottom-right-radius: 0;
	border-bottom: none;
}

.advanced-options details[open] {
	background: white;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.advanced-options details[open] > div {
	padding: 20px;
	border-top: 1px solid #e0e0e0;
}

.utility-actions {
	background: #f8f9fa;
	border: 1px solid #e9ecef;
	border-radius: 8px;
	padding: 20px;
	margin-bottom: 20px;
}

.utility-actions h4 {
	margin: 0 0 15px 0;
	color: #495057;
	font-size: 16px;
	display: flex;
	align-items: center;
	gap: 8px;
}

.utility-buttons {
	display: flex;
	gap: 12px;
	flex-wrap: wrap;
}

.utility-buttons .button {
	background: #ffffff;
	border: 1px solid #dee2e6;
	color: #495057;
	padding: 8px 16px;
	border-radius: 6px;
	transition: all 0.2s ease;
	font-size: 13px;
}

.utility-buttons .button:hover {
	background: #f8f9fa;
	border-color: #2271b1;
	color: #2271b1;
	transform: translateY(-1px);
	box-shadow: 0 2px 8px rgba(34, 113, 177, 0.15);
}

.danger-zone {
	background: linear-gradient(135deg, #fff8e5, #fffbf0);
	border: 2px solid #ffb900;
	border-radius: 8px;
	padding: 20px;
	margin-top: 20px;
	position: relative;
	overflow: hidden;
}

.danger-zone::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 4px;
	background: linear-gradient(90deg, #ffb900, #ff8c00);
}

.danger-zone h4 {
	margin: 0 0 12px 0;
	color: #856404;
	font-size: 16px;
	display: flex;
	align-items: center;
	gap: 8px;
	font-weight: 700;
}

.danger-zone p {
	font-size: 14px;
	margin: 0 0 15px 0;
	color: #856404;
	line-height: 1.5;
}

.danger-zone .button {
	background: linear-gradient(135deg, #dc3232, #b91c1c);
	color: white;
	border: none;
	padding: 12px 20px;
	border-radius: 6px;
	font-weight: 600;
	font-size: 14px;
	transition: all 0.3s ease;
	display: inline-flex;
	align-items: center;
	gap: 8px;
	box-shadow: 0 2px 8px rgba(220, 50, 50, 0.3);
}

.danger-zone .button:hover {
	background: linear-gradient(135deg, #b91c1c, #991b1b);
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(220, 50, 50, 0.4);
}

.danger-zone .button:active {
	transform: translateY(0);
	box-shadow: 0 2px 4px rgba(220, 50, 50, 0.3);
}

.danger-zone .disclaimer {
	font-size: 12px;
	color: #6c757d;
	margin: 12px 0 0 0;
	line-height: 1.4;
}

.rollback-zone {
	background: linear-gradient(135deg, #ffebee, #fff5f5);
	border: 2px solid #dc3232;
	border-radius: 8px;
	padding: 20px;
	margin-top: 20px;
	position: relative;
	overflow: hidden;
}

.rollback-zone::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 4px;
	background: linear-gradient(90deg, #dc3232, #b91c1c);
}

.rollback-zone h4 {
	margin: 0 0 12px 0;
	color: #8a2424;
	font-size: 16px;
	display: flex;
	align-items: center;
	gap: 8px;
	font-weight: 700;
}

.rollback-zone p {
	font-size: 14px;
	margin: 0 0 15px 0;
	color: #495057;
	line-height: 1.5;
}

.rollback-zone .button {
	background: linear-gradient(135deg, #6c757d, #495057);
	color: white;
	border: none;
	padding: 12px 20px;
	border-radius: 6px;
	font-weight: 600;
	font-size: 14px;
	transition: all 0.3s ease;
	display: inline-flex;
	align-items: center;
	gap: 8px;
	box-shadow: 0 2px 8px rgba(108, 117, 125, 0.3);
}

.rollback-zone .button:hover {
	background: linear-gradient(135deg, #495057, #343a40);
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(108, 117, 125, 0.4);
}

.rollback-zone .button:active {
	transform: translateY(0);
	box-shadow: 0 2px 4px rgba(108, 117, 125, 0.3);
}

.rollback-zone .warning {
	font-size: 12px;
	color: #dc3232;
	margin: 12px 0 0 0;
	line-height: 1.4;
	font-weight: 600;
}

.requirement-list {
	list-style: none;
	padding: 0;
	margin: 15px 0;
}

.requirement-item {
	display: flex;
	align-items: center;
	padding: 12px 15px;
	margin-bottom: 10px;
	background: white;
	border: 2px solid #e0e0e0;
	border-radius: 8px;
	transition: all 0.2s ease;
}

.requirement-item:hover {
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.requirement-item.pass {
	border-color: #46b450;
	background: #f0f9f1;
}

.requirement-item.fail {
	border-color: #dc3232;
	background: #ffebee;
}

.requirement-checkbox {
	width: 24px;
	height: 24px;
	margin-right: 15px;
	flex-shrink: 0;
	appearance: none;
	border: 2px solid #ddd;
	border-radius: 4px;
	position: relative;
	cursor: pointer;
	transition: all 0.2s ease;
}

.requirement-item.pass .requirement-checkbox {
	border-color: #46b450;
	background: #46b450;
}

.requirement-item.fail .requirement-checkbox {
	border-color: #dc3232;
	background: #dc3232;
}

.requirement-checkbox::after {
	content: '';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 6px;
	height: 12px;
	border: solid white;
	border-width: 0 2px 2px 0;
	opacity: 0;
	transition: opacity 0.2s ease;
	transform: translate(-50%, -60%) rotate(45deg);
}

.requirement-item.pass .requirement-checkbox::after {
	opacity: 1;
}

.requirement-item.fail .requirement-checkbox::after {
	content: '✕';
	color: white;
	font-size: 16px;
	font-weight: bold;
	line-height: 1;
	opacity: 1;
	transform: translate(-50%, -50%);
	border: none;
	width: auto;
	height: auto;
}

.requirement-label {
	flex: 1;
	font-size: 14px;
	font-weight: 600;
	color: #1d2327;
}

.requirement-item.pass .requirement-label {
	color: #2c5a2e;
}

.requirement-item.fail .requirement-label {
	color: #8a2424;
}

.requirement-value {
	font-size: 13px;
	color: #646970;
	margin-left: 10px;
	font-weight: normal;
}

.requirement-item.pass .requirement-value {
	color: #46b450;
}

.requirement-item.fail .requirement-value {
	color: #dc3232;
	font-weight: 600;
}

@media (max-width: 782px) {
	.proqyz-migration-v2 {
		margin: 10px auto;
		padding: 0 10px;
	}
	
	.step-header {
		flex-wrap: wrap;
	}
	
	.step-status {
		width: 100%;
		text-align: center;
		margin-top: 10px;
	}
	
	.migration-progress-bar {
		height: 10px;
	}
	
	.proqyz-migration-v2 h1 {
		font-size: 24px;
	}
	
	.proqyz-migration-v2 > p {
		font-size: 13px;
	}
}
</style>

<div class="wrap proqyz-migration-v2">
	<h1 style="margin-bottom: 10px;">
		🔄 ProQyz Database Migration
	</h1>
	<p style="font-size: 14px; color: #646970; margin-top: 0;">
		Upgrade your database to v2 for 99% faster performance
	</p>

	<!-- Overall Progress -->
	<div class="migration-progress-bar">
		<div class="migration-progress-fill" style="width: <?php 
			$overall_progress = 0;
			if ($step6_complete) $overall_progress = 100;
			elseif ($step5_complete) $overall_progress = 83;
			elseif ($step4_complete) $overall_progress = 67;
			elseif ($step3_complete) $overall_progress = 50;
			elseif ($step2_complete && $step1_complete) $overall_progress = 33;
			elseif ($step1_complete) $overall_progress = 17;
			else $overall_progress = 0;
			echo $overall_progress;
		?>%"></div>
	</div>

	<div style="text-align: center; margin-top: 15px;">
		<span style="display: inline-block; background: #f0f6fc; color: #2271b1; padding: 8px 16px; border-radius: 20px; font-size: 14px; font-weight: 600; box-shadow: 0 2px 4px rgba(34, 113, 177, 0.1);">
			<strong><?php echo $overall_progress; ?>%</strong> Complete
			<?php if ($overall_progress == 100) : ?>
				• 🎉 All done!
			<?php else : ?>
				• Step <?php echo $active_step; ?> of 6
			<?php endif; ?>
		</span>
	</div>

	<!-- Step-by-Step Accordion -->
	<div class="migration-steps">

		<!-- STEP 1: Create Database Tables -->
		<div class="migration-step <?php echo $active_step === 1 ? 'active' : ($step1_complete ? 'completed' : 'locked'); ?>" id="step-1">
			<div class="step-header" onclick="toggleStep(1)">
				<div class="step-number"><?php 
					if ($step1_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 1) echo 'C'; // Will show play icon via CSS  
					else echo '1';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Create Database Tables</h3>
					<p class="step-description">Set up the new optimized v2 database structure</p>
				</div>
				<span class="step-status <?php echo $step1_complete ? 'status-completed' : 'status-active'; ?>">
					<?php echo $step1_complete ? 'Completed' : 'Action Required'; ?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if ($step1_complete) : ?>
						<div class="migration-info-box success">
							<strong>✓ Tables Created Successfully</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								The new database tables are ready for migration:
							</p>
							<ul style="margin: 10px 0 0 20px; font-size: 13px;">
								<li><code><?php echo esc_html($table_proqyz_progress_submissions); ?></code></li>
								<li><code><?php echo esc_html($table_proqyz_progress_submissions_meta); ?></code></li>
							</ul>
						</div>
					<?php else : ?>
						<div class="migration-info-box">
							<strong>📊 What This Does</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Creates two new optimized tables that separate small indexed data from large serialized data, 
								improving query performance by up to 99%.
							</p>
						</div>

						<div class="step-actions">
							<button type="button" class="button button-primary button-large" id="btn-create-tables">
								<span class="btn-icon">🔧</span> Create Tables Now
							</button>
							<span style="font-size: 13px; color: #646970;">
								Safe operation • Your data will not be affected
							</span>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<!-- STEP 2: Minimum Requirements -->
		<div class="migration-step <?php echo $active_step === 2 ? 'active' : ($step2_complete ? 'completed' : ($step1_complete ? '' : 'locked')); ?>" id="step-2">
			<div class="step-header" onclick="toggleStep(2)">
				<div class="step-number"><?php 
					if ($step2_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 2) echo 'C'; // Will show play icon via CSS  
					else echo '2';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Minimum Requirements</h3>
					<p class="step-description">Check PHP configuration settings</p>
				</div>
				<span class="step-status <?php 
					echo !$step1_complete ? 'status-pending' : ($step2_complete ? 'status-completed' : 'status-active'); 
				?>">
					<?php 
					if (!$step1_complete) echo 'Locked';
					elseif ($step2_complete) echo 'Completed';
					else echo 'Action Required';
					?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if (!$step1_complete) : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Complete Step 1 First</strong>
							<p style="margin: 5px 0 0 0; font-size: 13px;">
								Please create the database tables before checking requirements.
							</p>
						</div>
					<?php elseif ($step2_complete) : ?>
						<div class="migration-info-box success">
							<strong>✓ All Requirements Met</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Your PHP configuration meets all minimum requirements for the migration.
							</p>
						</div>
					<?php else : ?>
						<div class="migration-info-box">
							<strong>⚙️ What This Checks</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								The migration process requires specific PHP configuration settings to run smoothly. 
								Please ensure all requirements below are met before proceeding.
							</p>
						</div>
					<?php endif; ?>

					<ul class="requirement-list">
						<?php 
						foreach ($php_requirements as $req) : 
							$status_class = $req['pass'] ? 'pass' : 'fail';
							
							// Format the current and required values for display
							if ($req['name'] === 'max_execution_time') {
								$current_display = $req['current'] == 0 ? 'Unlimited' : st_format_seconds($req['current']);
								$required_display = st_format_seconds($req['required']);
							} elseif (in_array($req['name'], array('memory_limit', 'post_max_size', 'upload_max_filesize'))) {
								$current_display = ($req['name'] === 'memory_limit' && $req['current'] == -1) ? 'Unlimited' : st_format_bytes($req['current']);
								$required_display = st_format_bytes($req['required']);
							} else {
								$current_display = number_format($req['current']);
								$required_display = number_format($req['required']);
							}
						?>
							<li class="requirement-item <?php echo $status_class; ?>">
								<input type="checkbox" class="requirement-checkbox" <?php echo $req['pass'] ? 'checked' : ''; ?> disabled>
								<span class="requirement-label">
									<?php echo esc_html($req['label']); ?>
									<span class="requirement-value">
										(Current: <strong><?php echo esc_html($current_display); ?></strong> 
										<?php if (!$req['pass']) : ?>
											• Required: <strong><?php echo esc_html($required_display); ?></strong>)
										<?php else : ?>
											✓)
										<?php endif; ?>
									</span>
								</span>
							</li>
						<?php endforeach; ?>
					</ul>

					<?php if (!$step2_complete && $step1_complete) : ?>
						<div class="migration-info-box error">
							<strong>❌ Requirements Not Met</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Please update your PHP configuration (php.ini) to meet all requirements above. 
								Contact your hosting provider if you need assistance modifying PHP settings.
							</p>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<!-- STEP 3: Initialize Migration -->
		<div class="migration-step <?php echo $active_step === 3 ? 'active' : ($step3_complete ? 'completed' : ($step2_complete && $step1_complete ? '' : 'locked')); ?>" id="step-3">
			<div class="step-header" onclick="toggleStep(3)">
				<div class="step-number"><?php 
					if ($step3_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 3) echo 'C'; // Will show play icon via CSS  
					else echo '3';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Initialize Migration</h3>
					<p class="step-description">Analyze your database and prepare for migration</p>
				</div>
				<span class="step-status <?php 
					echo (!$step1_complete || !$step2_complete) ? 'status-pending' : ($step3_complete ? 'status-completed' : 'status-active'); 
				?>">
					<?php 
					if (!$step1_complete || !$step2_complete) echo 'Locked';
					elseif ($step3_complete) echo 'Completed';
					else echo 'Ready';
					?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if (!$step1_complete || !$step2_complete) : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Complete Previous Steps First</strong>
							<p style="margin: 5px 0 0 0; font-size: 13px;">
								Please complete Steps 1 and 2 before initializing migration.
							</p>
						</div>
					<?php elseif ($step3_complete) : ?>
						<div class="migration-info-box success">
							<strong>✓ Migration Initialized</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Found <strong><?php echo number_format($status['total_records']); ?></strong> records to migrate
								(filtered: status=1, session_status≠3)
							</p>
						</div>
					<?php else : ?>
						<div class="migration-info-box">
							<strong>🔍 What This Does</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Scans your database to count how many records need to be migrated and 
								prepares the migration process. This takes about 5-10 seconds.
							</p>
						</div>

						<div class="step-actions">
							<button type="button" class="button button-primary button-large" id="btn-init-migration">
								<span class="btn-icon">🔍</span> Initialize Migration
							</button>
							<span style="font-size: 13px; color: #646970;">
								Quick analysis • No data changes yet
							</span>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<!-- STEP 4: Run Migration -->
		<div class="migration-step <?php echo $active_step === 4 ? 'active' : ($step4_complete ? 'completed' : ($step3_complete ? '' : 'locked')); ?>" id="step-4">
			<div class="step-header" onclick="toggleStep(4)">
				<div class="step-number"><?php 
					if ($step4_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 4) echo 'C'; // Will show play icon via CSS  
					else echo '4';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Run Migration</h3>
					<p class="step-description">Move your data to the new optimized tables</p>
				</div>
				<span class="step-status <?php 
					echo !$step3_complete ? 'status-pending' : ($step4_complete ? 'status-completed' : 'status-active'); 
				?>">
					<?php 
					if (!$step3_complete) echo 'Locked';
					elseif ($step4_complete) echo 'Completed';
					else echo 'Ready';
					?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if (!$step3_complete) : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Complete Step 3 First</strong>
							<p style="margin: 5px 0 0 0; font-size: 13px;">
								Please initialize the migration before running it.
							</p>
						</div>
					<?php elseif ($step4_complete) : ?>
						<div class="migration-info-box success">
							<strong>✓ Migration Completed Successfully!</strong>
							<div class="migration-stats" style="margin-top: 15px;">
								<div class="stat-card">
									<span class="stat-value"><?php echo number_format($status['processed']); ?></span>
									<span class="stat-label">Records Migrated</span>
								</div>
								<div class="stat-card">
									<span class="stat-value" style="color: <?php echo $status['errors'] > 0 ? '#dc3232' : '#46b450'; ?>">
										<?php echo number_format($status['errors']); ?>
									</span>
									<span class="stat-label">Errors</span>
								</div>
								<div class="stat-card">
									<span class="stat-value" style="color: #46b450;">100%</span>
									<span class="stat-label">Complete</span>
								</div>
							</div>
						</div>
					<?php else : ?>
						<div class="migration-info-box">
							<strong>⚡ Automatic Migration</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								The migration will process <strong><?php echo number_format($status['total_records']); ?></strong> records 
								in batches of 100. This prevents server timeouts and allows you to pause/resume if needed.
							</p>
						</div>

						<?php 
							$total_batches = $status['total_records'] > 0 ? ceil($status['total_records'] / 100) : 0;
							$current_batch = $status['batch'];
							$processed = $status['processed'];
							$percentage = $status['percentage'];
						?>
							<div class="migration-stats">
								<div class="stat-card">
									<span class="stat-value"><?php echo number_format($processed); ?></span>
									<span class="stat-label">Processed</span>
								</div>
								<div class="stat-card">
									<span class="stat-value"><?php echo number_format($status['total_records']); ?></span>
									<span class="stat-label">Total Records</span>
								</div>
								<div class="stat-card">
									<span class="stat-value"><?php echo number_format($percentage, 1); ?>%</span>
									<span class="stat-label">Progress</span>
								</div>
							</div>

							<?php if ($processed > 0) : ?>
							<!-- Batch Info Display -->
							<div class="migration-info-box" style="margin-top: 15px; text-align: center;">
								<p id="migration-batch-info" style="margin: 0; font-size: 14px; font-weight: 600; color: #2271b1;">
									Batch <strong><?php echo $current_batch; ?></strong> of <strong><?php echo $total_batches; ?></strong>
								</p>
							</div>

							<!-- Real-time Progress Bar -->
							<div class="batch-progress" id="migration-progress-bar">
								<div class="batch-progress-bar" style="width: <?php echo $percentage; ?>%">
									<?php echo number_format($percentage, 1); ?>%
								</div>
							</div>
							<?php else : ?>
							<!-- Placeholder for progress elements (will be shown when migration starts) -->
							<div class="migration-info-box" id="migration-batch-info" style="margin-top: 15px; text-align: center; display: none;">
								<p style="margin: 0; font-size: 14px; font-weight: 600; color: #2271b1;">
									Ready to start migration...
								</p>
							</div>

							<div class="batch-progress" id="migration-progress-bar" style="display: none;">
								<div class="batch-progress-bar" style="width: 0%">0%</div>
							</div>
							<?php endif; ?>

						<div class="step-actions">
							<button type="button" class="button button-primary button-large" id="btn-auto-migrate">
								<span class="btn-icon">⚡</span> Auto-Complete Migration
							</button>
							<button type="button" class="button button-secondary" id="btn-process-batch">
								<span class="btn-icon">▶️</span> Process Single Batch (100 records)
							</button>
						</div>
						
						<p style="font-size: 13px; color: #646970; margin-top: 10px;">
							💡 <strong>Recommended:</strong> Use "Auto-Complete" for fastest migration. 
							It will automatically process all batches for you.
						</p>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<!-- STEP 5: Verify Migration -->
		<div class="migration-step <?php echo $active_step === 5 ? 'active' : ($step5_complete ? 'completed' : ($step4_complete ? '' : 'locked')); ?>" id="step-5">
			<div class="step-header" onclick="toggleStep(5)">
				<div class="step-number"><?php 
					if ($step5_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 5) echo 'C'; // Will show play icon via CSS  
					else echo '5';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Verify Migration</h3>
					<p class="step-description">Confirm all data was migrated correctly</p>
				</div>
				<span class="step-status <?php 
					echo !$step4_complete ? 'status-pending' : ($step5_complete ? 'status-completed' : 'status-active'); 
				?>">
					<?php 
					if (!$step4_complete) echo 'Locked';
					elseif ($step5_complete) echo 'Completed';
					else echo 'Optional';
					?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if (!$step4_complete) : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Complete Step 4 First</strong>
							<p style="margin: 5px 0 0 0; font-size: 13px;">
								Please complete the migration before verifying.
							</p>
						</div>
					<?php else : ?>
						<div class="migration-info-box">
							<strong>🔍 What This Does</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Verifies that all records were migrated successfully by comparing counts between 
								old and new tables, and checking the meta table for extracted data.
							</p>
						</div>

						<div class="step-actions">
							<button type="button" class="button button-primary" id="btn-verify-migration">
								<span class="btn-icon">✓</span> Verify Migration
							</button>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<!-- STEP 6: Update Plugin -->
		<div class="migration-step <?php echo $active_step === 6 ? 'active' : ($step6_complete ? 'completed' : ($step4_complete ? '' : 'locked')); ?>" id="step-6">
			<div class="step-header" onclick="toggleStep(6)">
				<div class="step-number"><?php 
					if ($step6_complete) echo '✓'; // Will show checkmark via CSS
					elseif ($active_step === 6) echo 'C'; // Will show play icon via CSS  
					else echo '6';
				?></div>
				<div class="step-title-area">
					<h3 class="step-title">Update Plugin</h3>
					<p class="step-description">Switch to v2 update channel and install latest version</p>
				</div>
				<span class="step-status <?php 
					echo !$step4_complete ? 'status-pending' : ($step6_complete ? 'status-completed' : 'status-active'); 
				?>">
					<?php 
					if (!$step4_complete) echo 'Locked';
					elseif ($step6_complete) echo 'Completed';
					else echo 'Action Required';
					?>
				</span>
				<span class="chevron">▼</span>
			</div>
			<div class="step-content">
				<div class="step-inner">
					<?php if (!$step4_complete) : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Complete Step 4 First</strong>
							<p style="margin: 5px 0 0 0; font-size: 13px;">
								Please complete the migration before updating the plugin.
							</p>
						</div>
					<?php elseif ($step6_complete) : ?>
						<div class="migration-info-box success">
							<strong>✅ Plugin Updated Successfully!</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Your plugin has been updated to the latest version. All v2 features are now unlocked!
							</p>
						</div>

						<div class="migration-info-box">
							<strong>📊 Final Status</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								<strong>Database:</strong> v<?php echo esc_html(ST_DB_VERSION); ?> (✅ Migrated)<br>
								<strong>Plugin:</strong> v<?php echo esc_html($plugin_version); ?> (✅ Updated)<br>
								<strong>Update Channel:</strong> v2/latest (✅ Active)
							</p>
						</div>
					<?php else : ?>
						<div class="migration-info-box warning">
							<strong>⚠️ Plugin Update Required</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								Your database migration is complete, but you need to update the plugin to unlock the new v2 features.
								The update channel has been switched to v2/latest.
							</p>
						</div>

						<div class="migration-info-box">
							<strong>📊 Current Status</strong>
							<p style="margin: 10px 0 0 0; font-size: 13px;">
								<strong>Database:</strong> v<?php echo esc_html($db_version); ?> (✅ Migrated)<br>
								<strong>Plugin:</strong> v<?php echo esc_html($plugin_version); ?> (⚠️ Update Required)<br>
								<strong>Update Channel:</strong> v2/latest (✅ Activated)
							</p>
						</div>

						<div class="step-actions">
							<a href="<?php echo esc_url(admin_url('update-core.php')); ?>" 
							   class="button button-primary button-large">
								<span class="btn-icon">🔄</span> Update Plugin Now
							</a>
						</div>

						<p style="font-size: 13px; color: #646970; margin-top: 15px;">
							💡 <strong>Next:</strong> After updating, you'll get the full v2 experience with 99% faster performance!
						</p>
					<?php endif; ?>
				</div>
			</div>
		</div>

	</div>

	<!-- Messages Area -->
	<div id="migration-messages" class="migration-messages"></div>

	<!-- Advanced Options (at bottom) -->
	<?php if ($step4_complete) : ?>
	<div class="advanced-options">
		<details>
			<summary>
				<span style="font-size: 18px;">⚙️</span>
				<span>Advanced Options & Troubleshooting</span>
			</summary>
			<div>
				
				<!-- <div class="utility-actions">
					<h4>🔧 Utility Actions</h4>
					<div class="utility-buttons">
						<button type="button" class="button" id="btn-test-connection">
							🔗 Test AJAX Connection
						</button>
						<?php if ($status['processed'] > 0 && !$step4_complete) : ?>
						<button type="button" class="button" id="btn-reset-migration">
							🔄 Reset Migration Progress
						</button>
						<?php endif; ?>
					</div>
				</div> -->

				<!-- <?php if ($step4_complete && $submissions_table_exists && $meta_table_exists) : ?>
				<div class="danger-zone">
					<h4>⚠️ Danger Zone</h4>
					<p>
						<strong>Retry Migration:</strong> If you encountered errors during migration, 
						you can clear the new tables and retry from scratch.
					</p>
					<button type="button" class="button" id="btn-clear-tables">
						🗑️ Clear New Tables & Retry Migration
					</button>
					<p class="disclaimer">
						This will NOT affect your original data. You can safely retry migration unlimited times.
					</p>
				</div>
				<?php endif; ?> -->

				<?php if ($step4_complete) : ?>
				<div class="rollback-zone">
					<h4>🔙 Rollback Migration</h4>
					<p>
						<strong>Emergency Only:</strong> Revert to v1 database structure. 
						This will delete all migrated data and reset your database version.
					</p>
					<button type="button" class="button" id="btn-rollback">
						⚠️ Rollback to v1
					</button>
					<p class="warning">
						⚠️ Use only if you experience critical issues with v2.
					</p>
				</div>
				<?php endif; ?>

			</div>
		</details>
	</div>
	<?php endif; ?>

</div>

<script>
function toggleStep(stepNumber) {
	const step = document.getElementById('step-' + stepNumber);
	if (!step) return;
	
	// Don't toggle if locked
	if (step.classList.contains('locked')) return;
	
	// Toggle active class
	const isActive = step.classList.contains('active');
	
	// Remove active from all steps
	document.querySelectorAll('.migration-step').forEach(s => s.classList.remove('active'));
	
	// If wasn't active, make it active
	if (!isActive) {
		step.classList.add('active');
	}
}

// Auto-open active step on load
document.addEventListener('DOMContentLoaded', function() {
	const activeStep = document.querySelector('.migration-step.active');
	if (activeStep) {
		// Already has active class, just ensure it's visible
		activeStep.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
	}
});
</script>

