<?php
/**
 * Migration admin page (Woo standard UI style).
 *
 * @package PeachPay
 */

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

$nonce = wp_create_nonce( 'peachpay_convesiopay_subscription_importer' );
?>
<div class="pp-migration-actions" style="display:flex;align-items:center;gap:8px;flex-wrap:nowrap;overflow-x:auto;margin:0 0 8px;">
	<label for="pp-convesiopay-importer-dry-run" style="white-space:nowrap;">
		<input type="checkbox" id="pp-convesiopay-importer-dry-run" />
		<?php esc_html_e( 'Dry run', 'peachpay-for-woocommerce' ); ?>
	</label>
	<label for="pp-convesiopay-importer-limit-count" style="white-space:nowrap;">
		<?php esc_html_e( 'Max subscriptions (0 = all)', 'peachpay-for-woocommerce' ); ?>
		<input type="number" id="pp-convesiopay-importer-limit-count" min="0" step="1" value="0" style="width:90px;" />
	</label>
	<button type="button" class="button button-primary" id="pp-convesiopay-importer-run"><?php esc_html_e( 'Run Import', 'peachpay-for-woocommerce' ); ?></button>
	<button type="button" class="button" id="pp-convesiopay-rollback-run"><?php esc_html_e( 'Run Rollback', 'peachpay-for-woocommerce' ); ?></button>
	<button type="button" class="button" id="pp-convesiopay-importer-pause"><?php esc_html_e( 'Pause', 'peachpay-for-woocommerce' ); ?></button>
	<button type="button" class="button" id="pp-convesiopay-importer-resume"><?php esc_html_e( 'Resume', 'peachpay-for-woocommerce' ); ?></button>
	<button type="button" class="button" id="pp-convesiopay-importer-refresh"><?php esc_html_e( 'Refresh', 'peachpay-for-woocommerce' ); ?></button>
	<button type="button" class="button" id="pp-convesiopay-importer-clear-logs"><?php esc_html_e( 'Clear Logs', 'peachpay-for-woocommerce' ); ?></button>
</div>
<p id="pp-convesiopay-importer-message" class="description" style="margin:0 0 12px;"></p>

<h2 style="margin:0 0 8px;"><?php esc_html_e( 'Subscription Overview', 'peachpay-for-woocommerce' ); ?></h2>
<table class="widefat striped" style="margin:0 0 12px;">
	<tbody>
		<tr>
			<td style="width:300px;"><strong><?php esc_html_e( 'Convesiopay Subscriptions(legacy plugin)', 'peachpay-for-woocommerce' ); ?></strong></td>
			<td data-field="cpay_count">0</td>
		</tr>
		<tr>
			<td><strong><?php esc_html_e( 'PeachPay <> ConvesioPay Subscriptions (currently on PeachPay)', 'peachpay-for-woocommerce' ); ?></strong></td>
			<td data-field="peachpay_convesiopay_count">0</td>
		</tr>
		<tr>
			<td><strong><?php esc_html_e( 'Migrated subscriptions (tagged/history)', 'peachpay-for-woocommerce' ); ?></strong></td>
			<td data-field="already_migrated_count">0</td>
		</tr>
	</tbody>
</table>

<h2 style="margin:0 0 8px;"><?php esc_html_e( 'Run Status', 'peachpay-for-woocommerce' ); ?></h2>
<table class="widefat striped" style="margin:0;">
	<thead>
		<tr>
			<th><?php esc_html_e( 'Run ID', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Operation', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Status', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Dry run', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Started', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Completed', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Progress', 'peachpay-for-woocommerce' ); ?></th>
			<th><?php esc_html_e( 'Results', 'peachpay-for-woocommerce' ); ?></th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td data-field="run_id">-</td>
			<td data-field="operation">-</td>
			<td data-field="status">idle</td>
			<td data-field="dry_run">false</td>
			<td data-field="started_at">-</td>
			<td data-field="completed_at">-</td>
			<td data-field="progress_text">0 / 0</td>
			<td data-field="counters">migrated: 0, skipped: 0, failed: 0</td>
		</tr>
	</tbody>
</table>
<div style="margin-top:8px;position:relative;background:#f0f0f1;border-radius:2px;height:18px;overflow:hidden;">
	<div id="pp-convesiopay-importer-progress-bar" style="width:0%;height:18px;background:#2271b1;border-radius:2px;" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div>
	<div id="pp-convesiopay-importer-progress-label" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#1d2327;">0%</div>
</div>

<h2 style="margin:12px 0 4px;"><?php esc_html_e( 'Recent Runs', 'peachpay-for-woocommerce' ); ?> <span id="pp-convesiopay-importer-runs-count" style="font-size:13px;font-weight:400;color:#50575e;"></span></h2>
<pre id="pp-convesiopay-importer-runs" style="margin:0 0 12px;max-height:160px;overflow:auto;">No runs yet.</pre>

<h2 style="margin:0 0 4px;"><?php esc_html_e( 'Logs', 'peachpay-for-woocommerce' ); ?> <span id="pp-convesiopay-importer-logs-count" style="font-size:13px;font-weight:400;color:#50575e;"></span></h2>
<pre id="pp-convesiopay-importer-logs" style="margin:0;max-height:400px;overflow:auto;">No logs yet.</pre>

<style>
	.pp-status {
		display: inline-flex;
		align-items: center;
		gap: 6px;
		padding: 2px 8px;
		border-radius: 999px;
		font-size: 12px;
		font-weight: 600;
		line-height: 1.6;
		border: 1px solid transparent;
		white-space: nowrap;
	}

	.pp-status-running {
		color: #135e96;
		background: #e7f0f8;
		border-color: #b6d4ef;
	}

	.pp-status-completed {
		color: #0f5132;
		background: #e7f6ee;
		border-color: #b7e0c7;
	}

	.pp-status-failed {
		color: #842029;
		background: #fbeaea;
		border-color: #f2b8be;
	}

	.pp-status-paused {
		color: #8a6d1d;
		background: #fff7e6;
		border-color: #f1d48a;
	}

	.pp-status-idle {
		color: #50575e;
		background: #f0f0f1;
		border-color: #dcdcde;
	}

	.pp-bubbles {
		display: inline-flex;
		align-items: center;
		gap: 4px;
		margin-left: 2px;
	}

	.pp-bubbles .dot {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background: currentColor;
		opacity: .35;
		animation: pp-status-bounce 1.1s infinite ease-in-out;
	}

	.pp-bubbles .dot:nth-child(2) {
		animation-delay: .15s;
	}

	.pp-bubbles .dot:nth-child(3) {
		animation-delay: .3s;
	}

	@keyframes pp-status-bounce {
		0%,
		80%,
		100% {
			transform: translateY(0);
			opacity: .35;
		}
		40% {
			transform: translateY(-2px);
			opacity: 1;
		}
	}
</style>

<script>
	(function($) {
		const nonce = <?php echo json_encode( $nonce ); ?>;
		const adminPostUrl = <?php echo json_encode( admin_url( 'post.php?post=' ) ); ?>;
		const $message = $('#pp-convesiopay-importer-message');
		const $bar = $('#pp-convesiopay-importer-progress-bar');
		const $logs = $('#pp-convesiopay-importer-logs');
		const $runs = $('#pp-convesiopay-importer-runs');
		let pollTimer = null;

		function setMessage(text, type) {
			const color = type === 'error' ? '#d63638' : '#2271b1';
			$message.html('<span style="color:' + color + ';">' + text + '</span>');
		}

		function setField(field, value) {
			$('[data-field="' + field + '"]').text(value);
		}

		function escHtml(value) {
			return String(value)
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;')
				.replace(/'/g, '&#39;');
		}

		function getEditLink(id, label) {
			const numericId = Number(id || 0);
			if (!numericId) {
				return escHtml(label);
			}
			return '<a href="' + adminPostUrl + numericId + '&action=edit" target="_blank" rel="noopener noreferrer">#' + escHtml(label) + '</a>';
		}

		function formatStatus(status) {
			const normalized = (status || 'idle').toString().toLowerCase();
			if (normalized === 'running') {
				return '<span class="pp-status pp-status-running">Running <span class="pp-bubbles"><span class="dot"></span><span class="dot"></span><span class="dot"></span></span></span>';
			}
			if (normalized === 'completed') {
				return '<span class="pp-status pp-status-completed">&#10003; Completed</span>';
			}
			if (normalized === 'failed') {
				return '<span class="pp-status pp-status-failed">&#10005; Failed</span>';
			}
			if (normalized === 'paused') {
				return '<span class="pp-status pp-status-paused">&#10074;&#10074; Paused</span>';
			}
			return '<span class="pp-status pp-status-idle">Idle</span>';
		}

		function formatOverviewStatusCounts(counts, fallbackTotal) {
			const summary = counts && typeof counts === 'object' ? counts : {};
			const total = Number(summary.total !== undefined ? summary.total : (fallbackTotal || 0));
			const active = Number(summary.active || 0);
			const pending = Number(summary.pending || 0);
			const onHold = Number(summary['on-hold'] || 0);
			return total + ' (Total), ' + active + ' (Active), ' + pending + ' (Pending), ' + onHold + ' (On Hold)';
		}

		function formatMigratedHistory(overview) {
			return formatOverviewStatusCounts(
				overview.already_migrated_status_counts,
				Number(overview.already_migrated_subscriptions || 0)
			);
		}

		function getLogDetailsSuffix(item) {
			const status = String(item && item.status ? item.status : '').toLowerCase();
			const reason = String(item && item.reason ? item.reason : '').toLowerCase();
			const shouldShowDetails = status === 'migrated' || (status === 'skipped' && reason === 'dry_run');
			if (!shouldShowDetails || !item || !item.description) {
				return '';
			}
			let parsedDetails = {};
			try {
				parsedDetails = JSON.parse(String(item.description));
			} catch (e) {
				return '';
			}
			if (!parsedDetails || typeof parsedDetails !== 'object') {
				return '';
			}
			const detailsJson = JSON.stringify(parsedDetails);
			if (!detailsJson || detailsJson === '{}') {
				return '';
			}
			return ' details=' + escHtml(detailsJson);
		}

		function renderStatus(data) {
			const run = data.active_run && data.active_run.run_id ? data.active_run : (data.latest_run || {});
			const total = Number(run.total_scanned || 0);
			const processed = Number(run.processed || 0);
			const migrated = Number(run.migrated || 0);
			const skipped = Number(run.skipped || 0);
			const failed = Number(run.failed || 0);
			const status = run.status || 'idle';
			const percent = total > 0 ? Math.min(100, Math.round((processed / total) * 100)) : 0;

			setField('run_id', run.run_id || '-');
			setField('operation', run.operation || '-');
			$('[data-field="status"]').html(formatStatus(status));
			setField('dry_run', run.dry_run ? 'true' : 'false');
			setField('started_at', run.started_at || '-');
			setField('completed_at', run.completed_at || '-');
			setField('progress_text', processed + ' / ' + total);
			setField('counters', 'migrated: ' + migrated + ', skipped: ' + skipped + ', failed: ' + failed);
			$bar.css('width', percent + '%');
			$bar.attr('aria-valuenow', percent);
			$('#pp-convesiopay-importer-progress-label').text(percent + '%');

			const overview = data.overview || {};
			setField(
				'cpay_count',
				formatOverviewStatusCounts(overview.cpay_status_counts, Number(overview.cpay_subscriptions || 0))
			);
			setField(
				'peachpay_convesiopay_count',
				formatOverviewStatusCounts(overview.peachpay_convesiopay_status_counts, Number(overview.peachpay_convesiopay_subscriptions || 0))
			);
			setField(
				'already_migrated_count',
				formatMigratedHistory(overview)
			);

			if (Array.isArray(data.logs) && data.logs.length > 0) {
				const lineNumWidth = String(data.logs.length).length;
				const rows = data.logs.map(function(item, idx) {
					const lineNum = String(idx + 1).padStart(lineNumWidth, ' ');
					const subLink = getEditLink(item.subscription_id, item.subscription_id);
					const parentLink = getEditLink(item.parent_order_id, item.parent_order_id);
					const detailsSuffix = getLogDetailsSuffix(item);
					return lineNum + '  [' + escHtml(item.created_at) + '] subscription=' + subLink + ' parent-order=' + parentLink + ' status=' + escHtml(item.status) + ' reason=' + escHtml(item.reason) + detailsSuffix;
				});
				$logs.html(rows.join('\n'));
				const countLabel = status === 'running'
					? '(showing latest ' + data.logs.length + ' — live tail)'
					: '(' + data.logs.length + ' entries)';
				$('#pp-convesiopay-importer-logs-count').text(countLabel);
			} else {
				$logs.text('No logs yet.');
				$('#pp-convesiopay-importer-logs-count').text('');
			}

			if (Array.isArray(data.runs) && data.runs.length > 0) {
				const runLineNumWidth = String(data.runs.length).length;
				const runRows = data.runs.map(function(item, idx) {
					const lineNum = String(idx + 1).padStart(runLineNumWidth, ' ');
					return lineNum + '  [' + (item.started_at || '-') + '] run=' + item.run_id + ' op=' + (item.operation || 'import') + ' status=' + item.status + ' processed=' + (item.processed || 0) + '/' + (item.total_scanned || 0);
				});
				$runs.text(runRows.join('\n'));
				$('#pp-convesiopay-importer-runs-count').text('(' + data.runs.length + ' runs)');
			} else {
				$runs.text('No runs yet.');
				$('#pp-convesiopay-importer-runs-count').text('');
			}

			if (status === 'running') {
				startPolling();
			} else {
				stopPolling();
			}
		}

		function fetchStatus(forceRefresh) {
			const refresh = forceRefresh ? '1' : '0';
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_get_subscription_import_status',
				nonce: nonce,
				force_refresh: refresh
			}).done(function(response) {
				if (!response || !response.success) {
					setMessage('Unable to load run status.', 'error');
					return;
				}
				renderStatus(response.data || {});
			}).fail(function() {
				setMessage('Status request failed.', 'error');
			});
		}

		function startPolling() {
			if (pollTimer) {
				return;
			}
			pollTimer = setInterval(fetchStatus, 4000);
		}

		function stopPolling() {
			if (!pollTimer) {
				return;
			}
			clearInterval(pollTimer);
			pollTimer = null;
		}

		$('#pp-convesiopay-importer-run').on('click', function() {
			const dryRun = $('#pp-convesiopay-importer-dry-run').is(':checked') ? '1' : '0';
			const rawLimitCount = Number($('#pp-convesiopay-importer-limit-count').val());
			const limitCount = Number.isFinite(rawLimitCount) ? Math.max(0, Math.floor(rawLimitCount)) : 0;
			const scopeText = limitCount > 0 ? ('the first ' + limitCount + ' eligible subscription(s)') : 'all eligible subscriptions';
			const confirmMsg = dryRun === '1'
				? 'Run a dry-run import for ' + scopeText + '? No data will be written.'
				: 'Run the subscription import for ' + scopeText + '?\n\nThis will migrate metadata and switch payment methods. You can roll back afterwards if needed.';
			if (!window.confirm(confirmMsg)) {
				return;
			}
			setMessage('Starting import...', 'info');
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_start_subscription_import',
				nonce: nonce,
				dry_run: dryRun,
				limit_count: String(limitCount)
			}).done(function(response) {
				if (!response || !response.success) {
					const msg = response && response.data && response.data.message ? response.data.message : 'Failed to start import.';
					setMessage(msg, 'error');
					return;
				}
				setMessage('Import started. Run ID: ' + (response.data.run_id || ''), 'info');
				fetchStatus();
				startPolling();
			}).fail(function() {
				setMessage('Failed to start import.', 'error');
			});
		});

		$('#pp-convesiopay-rollback-run').on('click', function() {
			const dryRun = $('#pp-convesiopay-importer-dry-run').is(':checked') ? '1' : '0';
			const confirmMsg = dryRun === '1'
				? 'Run a dry-run rollback? No data will be written.'
				: 'Run the subscription rollback?\n\nThis will revert payment methods back to the legacy gateway for all migrated subscriptions. Subscription metadata will be preserved.';
			if (!window.confirm(confirmMsg)) {
				return;
			}
			setMessage('Starting rollback...', 'info');
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_start_subscription_rollback',
				nonce: nonce,
				dry_run: dryRun
			}).done(function(response) {
				if (!response || !response.success) {
					const msg = response && response.data && response.data.message ? response.data.message : 'Failed to start rollback.';
					setMessage(msg, 'error');
					return;
				}
				setMessage('Rollback started. Run ID: ' + (response.data.run_id || ''), 'info');
				fetchStatus();
				startPolling();
			}).fail(function() {
				setMessage('Failed to start rollback.', 'error');
			});
		});

		$('#pp-convesiopay-importer-pause').on('click', function() {
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_cancel_subscription_migration',
				nonce: nonce
			}).done(function(response) {
				if (!response || !response.success) {
					const msg = response && response.data && response.data.message ? response.data.message : 'Pause failed.';
					setMessage(msg, 'error');
					return;
				}
				setMessage('Run paused.', 'info');
				fetchStatus();
			}).fail(function() {
				setMessage('Pause request failed.', 'error');
			});
		});

		$('#pp-convesiopay-importer-resume').on('click', function() {
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_resume_subscription_migration',
				nonce: nonce
			}).done(function(response) {
				if (!response || !response.success) {
					const msg = response && response.data && response.data.message ? response.data.message : 'Resume failed.';
					setMessage(msg, 'error');
					return;
				}
				setMessage('Run resumed.', 'info');
				fetchStatus();
				startPolling();
			}).fail(function() {
				setMessage('Resume request failed.', 'error');
			});
		});

		$('#pp-convesiopay-importer-refresh').on('click', function() {
			fetchStatus(true);
		});

		$('#pp-convesiopay-importer-clear-logs').on('click', function() {
			if (!window.confirm('Clear migration logs and recent run history?')) {
				return;
			}
			$.post(ajaxurl, {
				action: 'peachpay_convesiopay_clear_subscription_migration_logs',
				nonce: nonce
			}).done(function(response) {
				if (!response || !response.success) {
					const msg = response && response.data && response.data.message ? response.data.message : 'Clear logs failed.';
					setMessage(msg, 'error');
					return;
				}
				setMessage('Migration logs and run history cleared.', 'info');
				$logs.text('No logs yet.');
				$runs.text('No runs yet.');
				fetchStatus(true);
			}).fail(function() {
				setMessage('Clear logs request failed.', 'error');
			});
		});

		fetchStatus();
	})(jQuery);
</script>
