<?php

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

$status_colors = array(
	'mapped'      => '#15803d',
	'transformed' => '#2563eb',
	'dropped'     => '#b45309',
	'deferred'    => '#6b7280',
);
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Migrate from AIOSEO', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:880px;">
		<?php esc_html_e( 'Copies every per-page SEO setting from All in One SEO into AIEO\'s own store so nothing is lost when you remove AIOSEO. It is READ-ONLY on AIOSEO — it never changes or deletes AIOSEO data, so rolling back is just reactivating AIOSEO. The import is idempotent (safe to re-run) and resumable. Review the field mapping below and run it BEFORE you flip the engine on.', 'ai-eshop-optimizer' ); ?>
	</p>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Source', 'ai-eshop-optimizer' ); ?></h3>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'AIOSEO data', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<?php if ( $available ) : ?>
						<span style="color:#15803d;font-weight:600;">✓</span>
						<?php
						echo esc_html( sprintf(
							
							__( '%1$d posts/products + %2$d terms found', 'ai-eshop-optimizer' ),
							(int) $counts['posts'],
							(int) $counts['terms']
						) );
						?>
					<?php else : ?>
						<span style="color:#6b7280;">—</span> <?php esc_html_e( 'No AIOSEO data detected (wp_aioseo_posts absent).', 'ai-eshop-optimizer' ); ?>
					<?php endif; ?>
				</td>
			</tr>
			<?php if ( ! empty( $last ) && ! empty( $last['finished_at'] ) ) : ?>
				<tr>
					<th><?php esc_html_e( 'Last import', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<?php
						echo esc_html( sprintf(
							
							__( '%1$d posts + %2$d terms imported, %3$d FAQ/HowTo stripped — %4$s ago', 'ai-eshop-optimizer' ),
							(int) ( $last['posts_imported'] ?? 0 ),
							(int) ( $last['terms_imported'] ?? 0 ),
							(int) ( $last['stripped'] ?? 0 ),
							human_time_diff( (int) $last['finished_at'] )
						) );
						?>
					</td>
				</tr>
			<?php endif; ?>
		</table>
		<p>
			<button type="button" class="button button-primary" id="aieo-seo-import-run" <?php disabled( ! $available ); ?>><?php esc_html_e( 'Import AIOSEO data', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-import-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Field mapping (no silent drops)', 'ai-eshop-optimizer' ); ?></h3>
		<table class="widefat striped">
			<thead><tr>
				<th><?php esc_html_e( 'AIOSEO field', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Status', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Notes', 'ai-eshop-optimizer' ); ?></th>
			</tr></thead>
			<tbody>
			<?php foreach ( $report as $field => $info ) : ?>
				<?php $color = isset( $status_colors[ $info['status'] ] ) ? $status_colors[ $info['status'] ] : '#444'; ?>
				<tr>
					<td><code><?php echo esc_html( $field ); ?></code></td>
					<td><strong style="color:<?php echo esc_attr( $color ); ?>;"><?php echo esc_html( ucfirst( $info['status'] ) ); ?></strong></td>
					<td><?php echo esc_html( $info['detail'] ); ?></td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<p class="description"><?php esc_html_e( 'After importing, verify a sample of products/posts, then enable the engine (SEO → General) and deactivate AIOSEO. Keep AIOSEO installed-but-inactive for one recrawl cycle as a rollback.', 'ai-eshop-optimizer' ); ?></p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Pre-cutover verify — head parity', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:900px;">
			<?php esc_html_e( 'Compares the head AIEO WOULD emit against the LIVE head (your current SEO plugin) over a sample of products, categories and pages — flagging any title / canonical / robots drift and confirming each canonical equals its permalink (the primary-category trap). Run + review this BEFORE enabling the engine and deactivating AIOSEO.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p>
			<button type="button" class="button button-primary" id="aieo-seo-verify-run"><?php esc_html_e( 'Run verification', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-verify-status" style="margin-left:10px;"></span>
		</p>
		<div id="aieo-seo-verify-results"></div>
	</div>
</div>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var btn = document.getElementById('aieo-seo-import-run');
	if (!btn) { return; }
	var st = document.getElementById('aieo-seo-import-status');
	btn.addEventListener('click', function(){
		btn.disabled = true;
		var phase = 'posts', after = 0, posts = 0, terms = 0, stripped = 0, guard = 0;
		st.style.color = '#6b7280';
		function step(){
			if (++guard > 100000) { st.style.color = '#b91c1c'; st.textContent = 'Stopped.'; btn.disabled = false; return; }
			var fd = new FormData();
			fd.set('action', 'aieo_seo_import_run');
			fd.set('nonce', nonce);
			fd.set('phase', phase);
			fd.set('after_id', after);
			fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					if (!j || !j.success) { st.style.color = '#b91c1c'; st.textContent = (j && j.data && j.data.message) || 'Import failed.'; btn.disabled = false; return; }
					var d = j.data;
					if ('terms' === phase) { terms += (d.imported | 0); } else { posts += (d.imported | 0); }
					stripped += (d.stripped | 0);
					after = Number( d.last_id ) || 0; // Number() not |0 — ids are bigint (|0 wraps >2^31)
					st.textContent = <?php echo wp_json_encode( __( 'Importing…', 'ai-eshop-optimizer' ) ); ?> + ' ' + posts + ' posts / ' + terms + ' terms';
					if (d.done) {
						if ('posts' === phase) { phase = 'terms'; after = 0; step(); return; } if ('terms' === phase) { phase = 'options'; after = 0; step(); return; }
						st.style.color = '#15803d';
						st.textContent = <?php echo wp_json_encode( __( 'Done:', 'ai-eshop-optimizer' ) ); ?> + ' ' + posts + ' posts + ' + terms + ' terms + settings (' + stripped + ' FAQ/HowTo stripped)';
						btn.disabled = false;
						return;
					}
					step();
				})
				.catch(function(){ st.style.color = '#b91c1c'; st.textContent = 'Network error.'; btn.disabled = false; });
		}
		step();
	});

	var vbtn = document.getElementById('aieo-seo-verify-run');
	if (vbtn) {
		var vst = document.getElementById('aieo-seo-verify-status');
		var vout = document.getElementById('aieo-seo-verify-results');
		function esc(x){ return String(x==null?'':x).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
		function cell(ok, aieo, live){ var c = ok?'#15803d':'#b91c1c'; return '<td><span style="color:'+c+';font-weight:700;">'+(ok?'✓':'✗')+'</span> '+esc(aieo)+(ok?'':'<br><small style="color:#b91c1c;">live: '+esc(live)+'</small>')+'</td>'; }
		vbtn.addEventListener('click', function(){
			vbtn.disabled = true; vst.style.color = '#6b7280';
			vst.textContent = <?php echo wp_json_encode( __( 'Fetching + comparing a sample…', 'ai-eshop-optimizer' ) ); ?>;
			vout.innerHTML = '';
			var fd = new FormData(); fd.set('action','aieo_seo_verify_parity'); fd.set('nonce', nonce);
			fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					vbtn.disabled = false;
					if (!j || !j.success) { vst.style.color = '#b91c1c'; vst.textContent = (j&&j.data&&j.data.message)||'Failed.'; return; }
					var s = j.data.summary || {}, rows = j.data.rows || [];
					vst.style.color = ((s.mismatches|0)===0 && (s.canon_drift|0)===0) ? '#15803d' : '#b45309';
					vst.textContent = (s.checked|0) + ' checked · ' + (s.mismatches|0) + ' title/canonical mismatch · ' + (s.canon_drift|0) + ' canonical≠permalink';
					var h = '<table class="widefat striped" style="margin-top:10px;"><thead><tr><th>Object</th><th>Title</th><th>Canonical</th><th>Robots</th><th>Schema</th></tr></thead><tbody>';
					rows.forEach(function(r){
						h += '<tr><td><strong>'+esc(r.object)+'</strong>'+(r.fetch_ok?'':' <small style="color:#b45309;">(live fetch failed)</small>')+(r.canon_self_ok?'':' <small style="color:#b91c1c;">canonical≠permalink</small>')+'<br><small>'+esc(r.url)+'</small></td>';
						h += cell(r.title_ok, r.title_aieo, r.title_live);
						h += cell(r.canon_ok, r.canon_aieo, r.canon_live);
						h += cell(r.robots_ok, r.robots_aieo, r.robots_live);
						h += '<td>'+esc(r.schema_aieo)+((r.schema_live && r.schema_live!==r.schema_aieo)?'<br><small>live: '+esc(r.schema_live)+'</small>':'')+'</td></tr>';
					});
					vout.innerHTML = h + '</tbody></table>';
				})
				.catch(function(){ vbtn.disabled = false; vst.style.color = '#b91c1c'; vst.textContent = 'Network error.'; });
		});
	}
})();
</script>
