<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'broken-link-checker' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Broken Link Checker requires an active license. Activate your license to scan content for dead links.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'broken-link-checker';
}

$settings             = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$post_types_available = get_post_types( [ 'public' => true ], 'objects' );
$post_types_selected  = $settings['post_types'] ?? [ 'post', 'page' ];
if ( ! is_array( $post_types_selected ) ) {
	$post_types_selected = [ 'post', 'page' ];
}

$ajax_nonce = wp_create_nonce( 'wp_powersuite_ajax' );
?>

<div class="wp-powersuite-module-settings wpps-blc-settings">
	<p class="description">
		<?php esc_html_e( 'Scan published content for broken internal and external links. Checks post content, images, Gutenberg block URLs, and Elementor data when present. Large sites are scanned in batches automatically.', 'wppowersuite-lite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>" data-ajax-nonce="<?php echo esc_attr( $ajax_nonce ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<h4 style="margin-top: 0;"><?php esc_html_e( 'Post Types to Scan', 'wppowersuite-lite' ); ?></h4>
		<p class="description" style="margin-bottom: 12px;">
			<?php esc_html_e( 'Select which content types to include in the scan.', 'wppowersuite-lite' ); ?>
		</p>
		<div class="wpps-blc-post-types" style="display: flex; flex-wrap: wrap; gap: 12px 24px; margin-bottom: 20px;">
			<?php foreach ( $post_types_available as $pt ) : ?>
				<label style="display: flex; align-items: center; gap: 6px;">
					<input
						type="checkbox"
						name="post_types[]"
						value="<?php echo esc_attr( $pt->name ); ?>"
						class="wp-powersuite-advanced-setting"
						data-setting-key="post_types"
						<?php checked( in_array( $pt->name, $post_types_selected, true ) ); ?>
					/>
					<?php echo esc_html( $pt->label ); ?>
				</label>
			<?php endforeach; ?>
		</div>

		<hr style="margin: 20px 0;" />

		<h4><?php esc_html_e( 'Scan', 'wppowersuite-lite' ); ?></h4>
		<p class="description" style="margin-bottom: 12px;">
			<?php esc_html_e( 'Internal links are verified via WordPress when possible. External links use HEAD with GET fallback. Results include broken, redirect, and inconclusive links.', 'wppowersuite-lite' ); ?>
		</p>
		<p style="margin-bottom: 12px;">
			<button type="button" class="button button-primary wpps-blc-scan" id="wpps-blc-scan-btn">
				<span class="dashicons dashicons-search" style="vertical-align: middle; margin-right: 4px;"></span>
				<?php esc_html_e( 'Start Scan', 'wppowersuite-lite' ); ?>
			</button>
			<button type="button" class="button wpps-blc-cancel" id="wpps-blc-cancel-btn" style="display: none; margin-left: 8px;">
				<?php esc_html_e( 'Cancel Scan', 'wppowersuite-lite' ); ?>
			</button>
		</p>

		<div class="wpps-blc-progress" style="display: none; margin-top: 16px;" aria-live="polite" aria-atomic="true">
			<div style="background: #f0f0f1; border-radius: 4px; height: 8px; overflow: hidden;">
				<div class="wpps-blc-progress-bar" style="width: 0%; background: #2271b1; height: 100%; transition: width 0.3s;"></div>
			</div>
			<p class="description wpps-blc-progress-text" style="margin: 8px 0 0;"><?php esc_html_e( 'Scanning...', 'wppowersuite-lite' ); ?></p>
		</div>

		<div class="wpps-blc-results" style="margin-top: 20px; display: none;"></div>
	</form>
</div>

<?php
$blc_i18n = [
	'scanning'          => __( 'Scanning...', 'wppowersuite-lite' ),
	'scanningProgress'  => __( 'Scanning posts… %1$s%% complete (%2$s of %3$s)', 'wppowersuite-lite' ),
	'checkingLinks'     => __( 'Checking links… %1$s%% complete (%2$s URLs remaining)', 'wppowersuite-lite' ),
	'finalizing'        => __( 'Finalizing results…', 'wppowersuite-lite' ),
	'startScan'         => __( 'Start Scan', 'wppowersuite-lite' ),
	'scanFailed'        => __( 'Scan failed. Please try again.', 'wppowersuite-lite' ),
	'scanResults'       => __( 'Scan Results', 'wppowersuite-lite' ),
	'postsScanned'      => __( 'Posts Scanned', 'wppowersuite-lite' ),
	'uniqueUrlsChecked' => __( 'Unique URLs Checked', 'wppowersuite-lite' ),
	'brokenLinks'       => __( 'Broken Links', 'wppowersuite-lite' ),
	'redirectLinks'     => __( 'Redirects', 'wppowersuite-lite' ),
	'inconclusiveLinks' => __( 'Inconclusive', 'wppowersuite-lite' ),
	'excellent'         => __( 'Excellent!', 'wppowersuite-lite' ),
	'noBrokenLinks'     => __( 'No broken links found.', 'wppowersuite-lite' ),
	'brokenLinksFound'  => __( 'Found %d broken link(s). Click the post title to edit.', 'wppowersuite-lite' ),
	'postPage'          => __( 'Post/Page', 'wppowersuite-lite' ),
	'brokenUrl'         => __( 'URL', 'wppowersuite-lite' ),
	'type'              => __( 'Type', 'wppowersuite-lite' ),
	'error'             => __( 'Status', 'wppowersuite-lite' ),
	'copy'              => __( 'Copy', 'wppowersuite-lite' ),
	'copied'            => __( 'Copied!', 'wppowersuite-lite' ),
	'exportCsv'         => __( 'Export CSV', 'wppowersuite-lite' ),
];
ob_start();
?>
(function() {
	'use strict';
	var container = document.querySelector('.wpps-blc-settings');
	if (!container || container.getAttribute('data-wpps-blc-bound') === '1') {
		return;
	}
	container.setAttribute('data-wpps-blc-bound', '1');

	var form = container.querySelector('form');
	var btn = container.querySelector('.wpps-blc-scan');
	var cancelBtn = container.querySelector('.wpps-blc-cancel');
	var progress = container.querySelector('.wpps-blc-progress');
	var progressBar = container.querySelector('.wpps-blc-progress-bar');
	var progressText = container.querySelector('.wpps-blc-progress-text');
	var results = container.querySelector('.wpps-blc-results');
	if (!btn || !results) {
		return;
	}
	if (form) {
		form.addEventListener('submit', function(e) { e.preventDefault(); });
	}

	var i18n = <?php echo wp_json_encode( $blc_i18n ); ?>;
	var nonce = (window.wpPowerSuite && window.wpPowerSuite.nonce) || (form && form.getAttribute('data-ajax-nonce')) || '';
	var endpoint = (window.wpPowerSuite && window.wpPowerSuite.ajaxUrl) || window.ajaxurl || '';
	var scanActive = false;
	var currentScanId = '';
	var aggregated = { broken_links: [], redirect_links: [], inconclusive_links: [], total_urls: 0, total_posts: 0, posts_scanned: 0, scan_time: 0 };

	function escHtml(s) {
		var el = document.createElement('div');
		el.textContent = s || '';
		return el.innerHTML;
	}

	function getPostTypes() {
		var types = [];
		if (!form) {
			return ['post', 'page'];
		}
		form.querySelectorAll('input[name="post_types[]"]:checked').forEach(function(input) {
			if (input.value) {
				types.push(input.value);
			}
		});
		return types.length ? types : ['post', 'page'];
	}

	function showError(message) {
		results.innerHTML = '<div class="notice notice-error"><p>' + escHtml(message) + '</p></div>';
		results.style.display = '';
	}

	function finishScanUi() {
		scanActive = false;
		currentScanId = '';
		btn.disabled = false;
		btn.innerHTML = '<span class="dashicons dashicons-search" style="vertical-align: middle; margin-right: 4px;"></span>' + escHtml(i18n.startScan);
		if (cancelBtn) {
			cancelBtn.style.display = 'none';
		}
		if (progress) {
			progress.style.display = 'none';
		}
	}

	function startScan() {
		aggregated = { broken_links: [], redirect_links: [], inconclusive_links: [], total_urls: 0, total_posts: 0, posts_scanned: 0, scan_time: 0 };
		scanActive = true;
		currentScanId = '';
		btn.disabled = true;
		btn.innerHTML = '<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; vertical-align: middle; margin-right: 4px;"></span>' + escHtml(i18n.scanning);
		if (cancelBtn) {
			cancelBtn.style.display = '';
		}
		if (progress) {
			progress.style.display = '';
		}
		if (progressBar) {
			progressBar.style.width = '0%';
		}
		if (progressText) {
			progressText.textContent = i18n.scanning;
		}
		results.style.display = 'none';
		results.innerHTML = '';
		runBatch('start', '');
	}

	function runBatch(action, scanId) {
		if (!scanActive && action !== 'start') {
			return;
		}
		if (!endpoint) {
			showError(i18n.scanFailed);
			finishScanUi();
			return;
		}
		var body = new URLSearchParams();
		body.append('action', 'wp_powersuite_scan_broken_links');
		body.append('nonce', nonce);
		body.append('scan_action', action);
		body.append('scan_id', scanId || '');
		if (action === 'start') {
			getPostTypes().forEach(function(type) {
				body.append('post_types[]', type);
			});
		}
		fetch(endpoint, { method: 'POST', body: body, credentials: 'same-origin' })
			.then(function(response) { return response.json(); })
			.then(function(r) {
				if (!scanActive && action === 'start') {
					return;
				}
				if (r && r.success && r.data) {
					aggregated.broken_links = r.data.broken_links || [];
					aggregated.redirect_links = r.data.redirect_links || [];
					aggregated.inconclusive_links = r.data.inconclusive_links || [];
					aggregated.total_urls = r.data.total_urls || 0;
					aggregated.total_posts = r.data.total_posts || aggregated.total_posts;
					aggregated.posts_scanned = r.data.posts_scanned || 0;
					aggregated.scan_time = r.data.scan_time || 0;
					if (r.data.has_more && scanActive) {
						currentScanId = r.data.scan_id || scanId;
						runBatch('continue', currentScanId);
						return;
					}
					results.innerHTML = '<div class="notice notice-success"><p><strong>' + escHtml(i18n.excellent) + '</strong> ' +
						escHtml(aggregated.broken_links.length ? i18n.brokenLinksFound.replace('%d', String(aggregated.broken_links.length)) : i18n.noBrokenLinks) +
						'</p><p>' + escHtml(i18n.postsScanned) + ': ' + aggregated.posts_scanned + ' · ' +
						escHtml(i18n.uniqueUrlsChecked) + ': ' + aggregated.total_urls + ' · ' +
						escHtml(i18n.brokenLinks) + ': ' + aggregated.broken_links.length + '</p></div>';
					results.style.display = '';
				} else {
					showError(r && r.data && r.data.message ? r.data.message : i18n.scanFailed);
				}
				finishScanUi();
			})
			.catch(function() {
				showError(i18n.scanFailed);
				finishScanUi();
			});
	}

	btn.addEventListener('click', startScan);
	if (cancelBtn) {
		cancelBtn.addEventListener('click', function() {
			scanActive = false;
			if (currentScanId && endpoint) {
				var body = new URLSearchParams();
				body.append('action', 'wp_powersuite_scan_broken_links');
				body.append('nonce', nonce);
				body.append('scan_action', 'cancel');
				body.append('scan_id', currentScanId);
				fetch(endpoint, { method: 'POST', body: body, credentials: 'same-origin' });
			}
			finishScanUi();
		});
	}
})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-broken-link-checker-admin-php-script-1', (string) ob_get_clean() ); ?>

