<?php
/**
 * ProQyz Migration Admin Page
 * 
 * Provides UI for database migration from v1 to v2.
 * 
 * Features:
 * - One-click migration start
 * - Real-time progress bar
 * - Pause/Resume capability
 * - Error log viewing
 * - Rollback functionality
 * - Migration verification
 * 
 * @package ST_ProQyz
 * @since   2.1.0
 */

defined( 'ABSPATH' ) || exit;

class ST_ProQyz_Migration_Admin {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Load migration class for AJAX handlers
		// This is required because AJAX requests bypass page rendering
		require_once ST_ABSPATH . 'includes/admin/classes/class-st-proqyz-migration.php';
		
		// NOTE: Menu is now registered at root level by ST_Admin_Menus class
		// NOTE: Scripts are now enqueued directly in the migration page (page-migration-v2.php)
		//       This prevents 404 errors when ProQyz library switches from v1 to v2
		
		// Register AJAX handlers only (scripts handled elsewhere)
		add_action( 'wp_ajax_proqyz_create_tables', array( $this, 'ajax_create_tables' ) );
		add_action( 'wp_ajax_proqyz_clear_tables', array( $this, 'ajax_clear_tables' ) );
		add_action( 'wp_ajax_proqyz_init_migration', array( $this, 'ajax_init_migration' ) );
		add_action( 'wp_ajax_proqyz_process_batch', array( $this, 'ajax_process_batch' ) );
		add_action( 'wp_ajax_proqyz_rollback_migration', array( $this, 'ajax_rollback' ) );
		add_action( 'wp_ajax_proqyz_verify_migration', array( $this, 'ajax_verify' ) );
		add_action( 'wp_ajax_proqyz_reset_migration', array( $this, 'ajax_reset' ) );
		add_action( 'wp_ajax_proqyz_test_connection', array( $this, 'ajax_test_connection' ) ); // Test endpoint
		
		// Debug: Log that hooks are registered
		if ( defined('WP_DEBUG') && WP_DEBUG ) {
			error_log('ProQyz Migration Admin: Constructor called, AJAX handlers registered');
		}
	}

	/**
	 * AJAX: Test connection (for debugging)
	 */
	public function ajax_test_connection() {
		// Simple test without nonce for debugging
		global $wpdb, $table_proqyz_progress_submissions;
		
		wp_send_json_success( array( 
			'message' => 'AJAX Connection successful!',
			'timestamp' => time(),
			'wpdb_prefix' => $wpdb->prefix,
			'submissions_table' => $table_proqyz_progress_submissions,
			'tables_defined' => !empty($table_proqyz_progress_submissions) ? 'yes' : 'no',
			'constant_defined' => defined('ST_PROQYZ_SLUG') ? ST_PROQYZ_SLUG : 'not defined'
		) );
	}

	/**
	 * AJAX: Create new v2 tables
	 */
	public function ajax_create_tables() {
		try {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			global $wpdb, $table_proqyz_progress_submissions, $table_proqyz_progress_submissions_meta;

			// Create submissions table
			$charset_collate = $wpdb->get_charset_collate();
			
			$sql_submissions = "CREATE TABLE IF NOT EXISTS {$table_proqyz_progress_submissions} (
				ID bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				user_id bigint(20) UNSIGNED NOT NULL,
				quiz_category varchar(191) NOT NULL DEFAULT '',
				session_type varchar(191) NOT NULL DEFAULT '',
				session_category varchar(191) NOT NULL DEFAULT '',
				course_category varchar(191) DEFAULT NULL,
				course_id varchar(100) DEFAULT NULL,
				topic_id varchar(100) DEFAULT NULL,
				lesson_id varchar(100) DEFAULT NULL,
				api_id varchar(100) NOT NULL,
				session_status tinyint(3) UNSIGNED NOT NULL DEFAULT 0,
				review tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
				status tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
				date_created bigint(20) UNSIGNED NOT NULL,
				date_modified bigint(20) UNSIGNED DEFAULT NULL,
				PRIMARY KEY (ID),
				KEY idx_user (user_id) USING BTREE,
				KEY idx_quiz_cat (quiz_category) USING BTREE,
				KEY idx_session_type (session_type, session_category) USING BTREE,
				KEY idx_session_cat (session_category) USING BTREE,
				KEY idx_date (date_created) USING BTREE,
				KEY idx_status (status, session_status) USING BTREE,
				KEY idx_user_session (user_id, session_type, session_category) USING BTREE,
				KEY idx_course_lesson (course_id, lesson_id, user_id) USING BTREE,
				KEY idx_api_user (api_id, user_id, status) USING BTREE,
				KEY idx_user_date (user_id, date_created) USING BTREE
			) ENGINE=InnoDB {$charset_collate};";

			$sql_meta = "CREATE TABLE IF NOT EXISTS {$table_proqyz_progress_submissions_meta} (
				meta_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				submission_id bigint(20) UNSIGNED NOT NULL,
				meta_key varchar(191) NOT NULL,
				meta_value longtext,
				created_at bigint(20) UNSIGNED NOT NULL,
				PRIMARY KEY (meta_id),
				KEY idx_submission (submission_id) USING BTREE,
				KEY idx_meta_key (meta_key) USING BTREE,
				KEY idx_submission_key (submission_id, meta_key) USING BTREE
			) ENGINE=InnoDB {$charset_collate};";

			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
			
			dbDelta( $sql_submissions );
			dbDelta( $sql_meta );

			// Verify tables were created
			$submissions_created = $wpdb->get_var("SHOW TABLES LIKE '{$table_proqyz_progress_submissions}'") === $table_proqyz_progress_submissions;
			$meta_created = $wpdb->get_var("SHOW TABLES LIKE '{$table_proqyz_progress_submissions_meta}'") === $table_proqyz_progress_submissions_meta;

			if ( $submissions_created && $meta_created ) {
				wp_send_json_success( array(
					'message' => 'New tables created successfully! You can now start migration.',
					'tables_created' => array(
						'submissions' => $table_proqyz_progress_submissions,
						'meta' => $table_proqyz_progress_submissions_meta
					)
				) );
			} else {
				wp_send_json_error( array(
					'message' => 'Table creation failed. Check database permissions.',
					'submissions_created' => $submissions_created,
					'meta_created' => $meta_created
				) );
			}

		} catch ( Exception $e ) {
			wp_send_json_error( array( 
				'message' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		}
	}

	/**
	 * AJAX: Clear new v2 tables
	 */
	public function ajax_clear_tables() {
		try {
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce. Please refresh the page and try again.' ) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$result = $migration->clear_new_tables();

			wp_send_json_success( $result );

		} catch ( Exception $e ) {
			wp_send_json_error( array( 
				'message' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		} catch ( Error $e ) {
			wp_send_json_error( array( 
				'message' => 'PHP Error: ' . $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		}
	}

	/**
	 * Add admin menu page (DEPRECATED - Now handled by ST_Admin_Menus)
	 * 
	 * This method is kept for backward compatibility but is no longer used.
	 * The menu is now registered at root level by ST_Admin_Menus class.
	 */
	public function add_admin_page() {
		// Check if constant is defined to avoid errors
		if ( ! defined('ST_PROQYZ_SLUG') ) {
			return;
		}
		
		add_submenu_page(
			ST_PROQYZ_SLUG, // Parent slug (st-proqyz menu)
			'Database Migration',
			'DB Migration',
			'manage_options',
			'proqyz-migration',
			array( $this, 'render_admin_page' )
		);
	}

	/**
	 * Enqueue admin scripts and styles
	 */
	public function enqueue_scripts( $hook ) {
		// Check for both old submenu page and new root-level menu page
		if ( strpos( $hook, 'proqyz-migrate' ) === false && strpos( $hook, 'proqyz-migration' ) === false ) {
			return;
		}

		// Get plugin file path - fallback if constant not defined
		$plugin_file = defined('ST_PROQYZ_PLUGIN_FILE') 
			? ST_PROQYZ_PLUGIN_FILE 
			: ST_ABSPATH . 'libs/proqyz/proqyz.php';

		wp_enqueue_style(
			'proqyz-migration-admin',
			plugin_dir_url( $plugin_file ) . 'includes/admin/css/migration-admin.css',
			array(),
			'2.1.0'
		);

		wp_enqueue_script(
			'proqyz-migration-admin',
			plugin_dir_url( $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 (e.g., :10005)
		if ( isset( $_SERVER['HTTP_HOST'] ) ) {
			$current_host = $_SERVER['HTTP_HOST']; // Includes port if present
			$ajax_host = parse_url( $ajax_url, PHP_URL_HOST );
			
			// If current host has port but ajax URL doesn't, fix it
			if ( $current_host !== $ajax_host && strpos( $current_host, ':' ) !== false ) {
				$ajax_url = str_replace( $ajax_host, $current_host, $ajax_url );
			}
		}

		wp_localize_script(
			'proqyz-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,
				)
			)
		);
	}

	/**
	 * Render admin page
	 */
	public function render_admin_page() {
		$migration = new ST_ProQyz_Migration();
		$status = $migration->get_migration_status();
		$logs = $migration->get_logs();
		
		global $st_db_version_key;
		$db_version = get_option( $st_db_version_key, '1.0' );
		$migration_required = defined('ST_MIGRATION_REQUIRED') ? ST_MIGRATION_REQUIRED : false;
		$plugin_disabled = defined('ST_PLUGIN_DISABLED') ? ST_PLUGIN_DISABLED : false;

		?>
		<div class="wrap proqyz-migration-admin">
			<h1>ProQyz Database Migration</h1>
			
		<?php 
		$plugin_version = defined('ST_VERSION') ? ST_VERSION : '2.0.5.2';
		$plugin_needs_update = version_compare($plugin_version, '2.1.0', '<');
		?>

		<?php if ( $migration_required ) : ?>
			<div class="notice notice-warning" style="border-left: 4px solid #ffb900; background: #fff8e5;">
				<h2 style="margin-top: 1em; color: #856404;">⚠️ Database Migration Recommended (Step 1 of 2)</h2>
				<p style="font-size: 14px;">
					<strong>Current Database Version:</strong> <?php echo esc_html( $db_version ); ?><br>
					<strong>Optimized Database Version:</strong> <?php echo esc_html( ST_DB_VERSION ); ?> (available)
				</p>
				<p style="font-size: 14px; color: #856404;">
					<strong>⚠️ Important:</strong> 
					Future plugin updates require migration to v2. You won't receive new features until you migrate.
				</p>
				<p style="font-size: 14px; color: #856404;">
					<strong>⚠️ Performance:</strong> 
					Your current database may be slow (especially with 4GB+ data). Migration provides <strong>99% faster performance</strong>.
				</p>
				<p style="font-size: 13px; color: #666;">
					<strong>Process:</strong> Step 1: Migrate database (below) → Step 2: Update plugin (WordPress Updates) → Enjoy v2!
				</p>
			</div>
		<?php elseif ( !$migration_required && $plugin_needs_update ) : ?>
			<div class="notice notice-info" style="border-left: 4px solid #00a0d2;">
				<h2 style="margin-top: 1em; color: #00648c;">✓ Step 1 Complete - Step 2 Required</h2>
				<p style="font-size: 14px;">
					<strong style="color: #2e7d32;">✓ Database Migration Complete!</strong> Your database is on v2 (optimized).<br>
					<strong style="color: #00648c;">→ Next Step:</strong> Update plugin to v2.1.0+ to unlock v2 features.
				</p>
				<p style="font-size: 14px;">
					<strong>Current Plugin:</strong> v<?php echo esc_html( $plugin_version ); ?><br>
					<strong>Required Plugin:</strong> v2.1.0+ (available in v2 update channel)
				</p>
				<p>
					<a href="<?php echo esc_url(admin_url('update-core.php')); ?>" 
					   class="button button-primary button-large" 
					   style="margin-right: 10px;">
						🔄 Check for Plugin Updates
					</a>
				</p>
				<p style="font-size: 13px; color: #666;">
					After updating, all shortcodes will use the optimized v2 architecture (99% faster performance).
				</p>
			</div>
		<?php else : ?>
			<div class="notice notice-success">
				<p>
					<strong>✓ Database Version:</strong> <?php echo esc_html( $db_version ); ?> (up to date)<br>
					<strong>✓ Plugin Version:</strong> v<?php echo esc_html( $plugin_version ); ?> (v2 compatible)
				</p>
				<p>Your database and plugin are fully updated. You're receiving v2 updates with all latest features and optimizations!</p>
			</div>
		<?php endif; ?>

		<?php if ( defined('WP_DEBUG') && WP_DEBUG ) : ?>
			<div class="notice notice-warning">
				<p><strong>Debug Info:</strong></p>
				<ul>
					<li>Current Host: <?php echo esc_html( $_SERVER['HTTP_HOST'] ?? 'unknown' ); ?></li>
					<li>AJAX URL: <code><?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?></code></li>
					<li>DB Version: <?php echo esc_html( $db_version ); ?></li>
					<li>Required DB Version: <?php echo esc_html( ST_DB_VERSION ); ?></li>
					<li>ST_MIGRATION_REQUIRED: <?php echo $migration_required ? 'true' : 'false'; ?></li>
					<li>ST_MIGRATION_COMPLETED: <?php echo defined('ST_MIGRATION_COMPLETED') && ST_MIGRATION_COMPLETED ? 'true' : 'false'; ?></li>
					<li>Update URL: <code><?php echo esc_url( ST_UPDATE_URL ); ?></code></li>
					<li>Update Channel: <?php echo $migration_required ? 'v1 (security fixes only)' : 'v2 (latest features)'; ?></li>
				</ul>
			</div>
		<?php endif; ?>

			<!-- Migration Status Card -->
			<div class="migration-card">
				<h2>Migration Status</h2>
				
				<div class="migration-stats">
					<div class="stat-item">
						<span class="stat-label">Status:</span>
						<span class="stat-value status-<?php echo esc_attr( $status['status'] ); ?>">
							<?php echo esc_html( ucfirst( str_replace( '_', ' ', $status['status'] ) ) ); ?>
						</span>
					</div>
					
					<div class="stat-item">
						<span class="stat-label">Total Records:</span>
						<span class="stat-value"><?php echo number_format( $status['total_records'] ); ?></span>
					</div>
					
					<div class="stat-item">
						<span class="stat-label">Processed:</span>
						<span class="stat-value"><?php echo number_format( $status['processed'] ); ?></span>
					</div>
					
					<div class="stat-item">
						<span class="stat-label">Errors:</span>
						<span class="stat-value"><?php echo number_format( $status['errors'] ); ?></span>
					</div>
					
					<div class="stat-item">
						<span class="stat-label">Progress:</span>
						<span class="stat-value"><?php echo number_format( $status['percentage'], 2 ); ?>%</span>
					</div>
				</div>

				<!-- Progress Bar -->
				<div class="progress-bar-container">
					<div class="progress-bar" style="width: <?php echo esc_attr( $status['percentage'] ); ?>%">
						<span class="progress-text"><?php echo number_format( $status['percentage'], 2 ); ?>%</span>
					</div>
				</div>

				<!-- Action Buttons -->
				<div class="migration-actions">
					<!-- Test Connection Button (Debug) -->
					<button type="button" class="button button-secondary" id="btn-test-connection" style="background: #f0f0f1;">
						🔧 Test AJAX Connection
					</button>
					
					<?php if ( $status['status'] === 'not_started' || $status['status'] === 'initialized' ) : ?>
						<button type="button" class="button button-primary button-large" id="btn-init-migration">
							Initialize Migration
						</button>
					<?php endif; ?>

					<?php if ( $status['status'] === 'initialized' || $status['status'] === 'paused' ) : ?>
						<button type="button" class="button button-primary button-large" id="btn-process-batch">
							<?php echo $status['status'] === 'paused' ? 'Resume' : 'Start'; ?> Migration
						</button>
						<button type="button" class="button button-secondary" id="btn-auto-migrate">
							Auto-Complete All Batches
						</button>
					<?php endif; ?>

					<?php if ( $status['status'] !== 'not_started' && $status['status'] !== 'completed' ) : ?>
						<button type="button" class="button button-secondary" id="btn-reset-migration">
							Reset Migration
						</button>
					<?php endif; ?>

					<?php if ( $status['processed'] > 0 ) : ?>
						<button type="button" class="button button-secondary" id="btn-verify-migration">
							Verify Migration
						</button>
						<button type="button" class="button button-danger" id="btn-rollback">
							Rollback Migration
						</button>
					<?php endif; ?>
				</div>

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

			<!-- Update Channel Info -->
			<?php if ( $migration_required ) : ?>
			<div class="migration-card" style="background: #fff8e5; border-left: 4px solid #ffb900;">
				<h2 style="color: #856404;">📢 Update Channel Information</h2>
				<p style="font-size: 14px;">
					<strong>Current Update Channel:</strong> <code>v1 (Security Fixes Only)</code>
				</p>
				<p style="font-size: 13px; color: #666;">
					Your site is receiving security updates but <strong>no new features</strong> until you migrate to v2.
				</p>
				<p style="font-size: 13px; color: #666;">
					<strong>After Migration:</strong> You'll switch to <code>v2/latest</code> update channel and receive all new features and optimizations.
				</p>
			</div>
			<?php else : ?>
			<div class="migration-card" style="background: #e7f5e8; border-left: 4px solid #46b450;">
				<h2 style="color: #2e7d32;">✅ Update Channel Active</h2>
				<p style="font-size: 14px;">
					<strong>Current Update Channel:</strong> <code>v2/latest (All Features)</code>
				</p>
				<p style="font-size: 13px; color: #2e7d32;">
					You're receiving all the latest features, optimizations, and security updates!
				</p>
			</div>
			<?php endif; ?>

			<!-- Information Card -->
			<div class="migration-card">
				<h2>Performance Improvements</h2>
				<ul class="performance-list">
					<li><strong>99.98% reduction</strong> in row size (2MB → 350 bytes)</li>
					<li><strong>Lazy loading</strong> of meta data - fetched only when needed</li>
					<li><strong>Integer timestamps</strong> for faster date filtering</li>
					<li><strong>Optimized composite indexes</strong> for multi-column queries</li>
					<li><strong>InnoDB engine</strong> for ACID compliance and better concurrency</li>
					<li><strong>Access to v2 updates</strong> - New features and optimizations</li>
				</ul>
			</div>

			<!-- Error Logs -->
			<?php if ( !empty( $logs ) ) : ?>
				<div class="migration-card">
					<h2>Error Logs (<?php echo count( $logs ); ?>)</h2>
					<div class="error-logs">
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th>Record ID</th>
									<th>Error Message</th>
									<th>Time</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( array_slice( $logs, -50 ) as $log ) : ?>
									<tr>
										<td><?php echo esc_html( $log['record_id'] ); ?></td>
										<td><?php echo esc_html( $log['error'] ); ?></td>
										<td><?php echo esc_html( $log['time'] ); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				</div>
			<?php endif; ?>

			<!-- Technical Details -->
			<div class="migration-card">
				<h2>Technical Details</h2>
				<details>
					<summary>Click to view migration specifications</summary>
					<table class="widefat">
						<tr>
							<th>Batch Size:</th>
							<td>100 records per batch</td>
						</tr>
						<tr>
							<th>Old Table:</th>
							<td><code>wp_st_proqyz_quiz_progress</code></td>
						</tr>
						<tr>
							<th>New Index Table:</th>
							<td><code>wp_st_proqyz_progress_submissions</code></td>
						</tr>
						<tr>
							<th>New Meta Table:</th>
							<td><code>wp_st_proqyz_progress_submissions_meta</code></td>
						</tr>
						<tr>
							<th>Migration Mode:</th>
							<td>Non-destructive (old data preserved)</td>
						</tr>
						<tr>
							<th>Rollback Support:</th>
							<td>Yes (with ID mapping)</td>
						</tr>
						<tr style="background: <?php echo $migration_required ? '#fff8e5' : '#e7f5e8'; ?>;">
							<th>Update Channel:</th>
							<td>
								<strong><?php echo $migration_required ? 'v1/latest (Limited)' : 'v2/latest (Full)'; ?></strong><br>
								<small><?php echo esc_url( ST_UPDATE_URL ); ?></small>
							</td>
						</tr>
					</table>
				</details>
			</div>
		</div>

		<style>
			.proqyz-migration-admin .migration-card {
				background: white;
				padding: 20px;
				margin: 20px 0;
				border: 1px solid #ccd0d4;
				box-shadow: 0 1px 1px rgba(0,0,0,.04);
			}
			.migration-stats {
				display: grid;
				grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
				gap: 15px;
				margin: 20px 0;
			}
			.stat-item {
				padding: 15px;
				background: #f9f9f9;
				border-radius: 4px;
			}
			.stat-label {
				display: block;
				font-size: 12px;
				color: #666;
				margin-bottom: 5px;
			}
			.stat-value {
				display: block;
				font-size: 24px;
				font-weight: bold;
				color: #1e1e1e;
			}
			.stat-value.status-completed {
				color: #46b450;
			}
			.stat-value.status-running {
				color: #00a0d2;
			}
			.stat-value.status-paused {
				color: #ffb900;
			}
			.progress-bar-container {
				width: 100%;
				height: 40px;
				background: #f0f0f0;
				border-radius: 4px;
				overflow: hidden;
				margin: 20px 0;
			}
			.progress-bar {
				height: 100%;
				background: linear-gradient(90deg, #00a0d2, #0073aa);
				transition: width 0.3s ease;
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 40px;
			}
			.progress-text {
				color: white;
				font-weight: bold;
				font-size: 14px;
			}
			.migration-actions {
				display: flex;
				gap: 10px;
				flex-wrap: wrap;
				margin: 20px 0;
			}
			.button-danger {
				background: #dc3232;
				border-color: #dc3232;
				color: white;
			}
			.button-danger:hover {
				background: #c62828;
				border-color: #c62828;
			}
			.migration-messages {
				margin: 20px 0;
			}
			.performance-list li {
				margin: 10px 0;
				padding-left: 20px;
			}
			.error-logs {
				max-height: 400px;
				overflow-y: auto;
			}
		</style>
		<?php
	}

	/**
	 * AJAX: Initialize migration
	 */
	public function ajax_init_migration() {
		// Enhanced error handling
		try {
			// Check nonce with better error handling
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 
					'message' => 'Invalid nonce. Please refresh the page and try again.',
					'nonce_received' => isset($_POST['nonce']) ? 'yes' : 'no'
				) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$result = $migration->init_migration();

			wp_send_json_success( $result );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 
				'message' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		} catch ( Error $e ) {
			wp_send_json_error( array( 
				'message' => 'PHP Error: ' . $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		}
	}

	/**
	 * AJAX: Process single batch
	 */
	public function ajax_process_batch() {
		// Enhanced error handling
		try {
			// Check nonce with better error handling
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 
					'message' => 'Invalid nonce. Please refresh the page and try again.'
				) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$result = $migration->process_batch();

			// Update DB version if completed
			if ( isset( $result['is_complete'] ) && $result['is_complete'] ) {
				global $ST_OPTION_st_proqyz__db_version, $st_db_version_key;
				
				// Update ProQyz-specific DB version
				update_option( $ST_OPTION_st_proqyz__db_version, '2.0' );
				
				// Update main Spacetree DB version (unlocks plugin)
				update_option( $st_db_version_key, ST_DB_VERSION );
				
				// Fire action for other plugins/features
				do_action( 'proqyz_migration_completed', $result );
			}

			wp_send_json_success( $result );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 
				'message' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		} catch ( Error $e ) {
			wp_send_json_error( array( 
				'message' => 'PHP Error: ' . $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		}
	}

	/**
	 * AJAX: Rollback migration
	 */
	public function ajax_rollback() {
		// Enhanced error handling
		try {
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 
					'message' => 'Invalid nonce. Please refresh the page and try again.'
				) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$result = $migration->rollback();

			wp_send_json_success( $result );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 
				'message' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		} catch ( Error $e ) {
			wp_send_json_error( array( 
				'message' => 'PHP Error: ' . $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine()
			) );
		}
	}

	/**
	 * AJAX: Verify migration
	 */
	public function ajax_verify() {
		try {
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce. Please refresh the page and try again.' ) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$result = $migration->verify_migration();

			wp_send_json_success( $result );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}

	/**
	 * AJAX: Reset migration
	 */
	public function ajax_reset() {
		try {
			$nonce_check = isset($_POST['nonce']) ? wp_verify_nonce( $_POST['nonce'], 'proqyz_migration_nonce' ) : false;
			
			if ( ! $nonce_check ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce. Please refresh the page and try again.' ) );
				return;
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized - Administrator access required' ) );
				return;
			}

			$migration = new ST_ProQyz_Migration();
			$migration->reset_migration();

			wp_send_json_success( array( 'message' => 'Migration reset successfully. You can now restart the migration process.' ) );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}
}

// Don't instantiate here - let the main class handle it

