<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'remove-unused-themes-plugins';
}

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

$scan_nonce   = wp_create_nonce( 'wpps_ru_scan' );
$remove_nonce = wp_create_nonce( 'wpps_ru_remove' );
$ajax_url     = admin_url( 'admin-ajax.php' );

?>
<div class="wp-powersuite-module-settings wpps-ru-settings">
	<p class="description">
		<?php esc_html_e( 'Scan for inactive themes and plugins, then remove them in one go. This frees disk space and reduces security risk from unused code. Parent themes of active child themes are always protected.', 'wp-powersuite' ); ?>
	</p>

	<div class="wpps-ru-after-remove" style="display: none;">
		<div class="wpps-ru-message wpps-ru-success"></div>
		<div class="wpps-ru-message wpps-ru-fail"></div>
	</div>

	<div class="wpps-ru-actions">
		<button type="button" class="button button-secondary wpps-ru-scan" data-nonce="<?php echo esc_attr( $scan_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
			<?php esc_html_e( 'Scan for Inactive Items', 'wp-powersuite' ); ?>
		</button>
	</div>

	<div class="wpps-ru-loading" style="display: none;">
		<span class="spinner is-active"></span>
		<span class="wpps-ru-loading-text"><?php esc_html_e( 'Scanning...', 'wp-powersuite' ); ?></span>
	</div>

	<div class="wpps-ru-results" style="display: none;">
		<div class="wpps-ru-section wpps-ru-plugins">
			<h4><?php esc_html_e( 'Inactive Plugins', 'wp-powersuite' ); ?>
				<button type="button" class="button-link wpps-ru-select-all" data-target="plugins"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></button>
			</h4>
			<div class="wpps-ru-list wpps-ru-plugin-list"></div>
			<p class="description wpps-ru-none wpps-ru-none-plugins" style="display: none;"><?php esc_html_e( 'No inactive plugins.', 'wp-powersuite' ); ?></p>
		</div>
		<div class="wpps-ru-section wpps-ru-themes">
			<h4><?php esc_html_e( 'Inactive Themes', 'wp-powersuite' ); ?>
				<button type="button" class="button-link wpps-ru-select-all" data-target="themes"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></button>
			</h4>
			<div class="wpps-ru-list wpps-ru-theme-list"></div>
			<p class="description wpps-ru-none wpps-ru-none-themes" style="display: none;"><?php esc_html_e( 'No inactive themes.', 'wp-powersuite' ); ?></p>
		</div>

		<div class="wpps-ru-remove-actions" style="display: none;">
			<p class="description" style="margin-bottom: 8px;">
				<?php esc_html_e( 'Select the items you want to remove, then click Remove selected. Or use the buttons below to remove all in a category.', 'wp-powersuite' ); ?>
			</p>
			<button type="button" class="button button-primary wpps-ru-remove-selected" data-nonce="<?php echo esc_attr( $remove_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
				<?php esc_html_e( 'Remove selected', 'wp-powersuite' ); ?>
			</button>
			<span class="wpps-ru-selected-count" style="margin-left: 8px; color: #646970;"></span>
			<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #dcdcde;">
				<strong><?php esc_html_e( 'Or remove all:', 'wp-powersuite' ); ?></strong>
				<button type="button" class="button button-secondary wpps-ru-remove" data-type="plugins" data-nonce="<?php echo esc_attr( $remove_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
					<?php esc_html_e( 'All inactive plugins', 'wp-powersuite' ); ?>
				</button>
				<button type="button" class="button button-secondary wpps-ru-remove" data-type="themes" data-nonce="<?php echo esc_attr( $remove_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
					<?php esc_html_e( 'All inactive themes', 'wp-powersuite' ); ?>
				</button>
				<button type="button" class="button button-secondary wpps-ru-remove" data-type="all" data-nonce="<?php echo esc_attr( $remove_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>">
					<?php esc_html_e( 'All inactive items', 'wp-powersuite' ); ?>
				</button>
			</div>
		</div>
	</div>

	<div class="wpps-ru-info-box" style="background: #f0f6fc; border-left: 4px solid #2271b1; padding: 12px; margin: 20px 0;">
		<p style="margin: 0;">
			<strong><?php esc_html_e( 'Warning', 'wp-powersuite' ); ?></strong><br>
			<?php esc_html_e( 'Deletion cannot be undone. Make backups first. Database settings for removed items remain (orphaned). On multisite, plugins and themes active on any site in the network are protected, along with plugins required by active plugins.', 'wp-powersuite' ); ?>
		</p>
	</div>
</div>

<style>
	.wpps-ru-settings .wpps-ru-actions { margin: 16px 0; }
	.wpps-ru-settings .wpps-ru-loading { margin: 12px 0; align-items: center; display: flex; gap: 8px; }
	.wpps-ru-settings .wpps-ru-results { margin-top: 16px; }
	.wpps-ru-settings .wpps-ru-section { margin-bottom: 20px; }
	.wpps-ru-settings .wpps-ru-section h4 { margin: 0 0 8px 0; }
	.wpps-ru-settings .wpps-ru-list { max-height: 220px; overflow-y: auto; border: 1px solid #c3c4c7; border-radius: 4px; padding: 8px; background: #fff; }
	.wpps-ru-settings .wpps-ru-item { padding: 6px 8px; border-bottom: 1px solid #f0f0f1; display: flex; align-items: center; gap: 10px; }
	.wpps-ru-settings .wpps-ru-item:last-child { border-bottom: none; }
	.wpps-ru-settings .wpps-ru-item input[type="checkbox"] { flex-shrink: 0; margin: 0; }
	.wpps-ru-settings .wpps-ru-item-info { flex: 1; min-width: 0; }
	.wpps-ru-settings .wpps-ru-item-name { font-weight: 600; }
	.wpps-ru-settings .wpps-ru-item-meta { font-size: 12px; color: #646970; margin-top: 2px; }
	.wpps-ru-settings .wpps-ru-remove-actions { margin-top: 16px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
	.wpps-ru-settings .wpps-ru-after-remove { margin-top: 16px; }
	.wpps-ru-settings .wpps-ru-message { margin-bottom: 8px; padding: 10px; border-radius: 4px; }
	.wpps-ru-settings .wpps-ru-message:empty { display: none !important; }
	.wpps-ru-settings .wpps-ru-success { background: #d4edda; border: 1px solid #c3e6cb; }
	.wpps-ru-settings .wpps-ru-fail { background: #f8d7da; border: 1px solid #f5c6cb; }
</style>

<script>
(function() {
	'use strict';
	var container = document.querySelector('.wpps-ru-settings');
	if (!container) return;

	var scanBtn = container.querySelector('.wpps-ru-scan');
	var loading = container.querySelector('.wpps-ru-loading');
	var results = container.querySelector('.wpps-ru-results');
	var pluginList = container.querySelector('.wpps-ru-plugin-list');
	var themeList = container.querySelector('.wpps-ru-theme-list');
	var nonePlugins = container.querySelector('.wpps-ru-none-plugins');
	var noneThemes = container.querySelector('.wpps-ru-none-themes');
	var removeActions = container.querySelector('.wpps-ru-remove-actions');
	var removeSelectedBtn = container.querySelector('.wpps-ru-remove-selected');
	var selectedCountEl = container.querySelector('.wpps-ru-selected-count');
	var afterRemove = container.querySelector('.wpps-ru-after-remove');
	var successMsg = container.querySelector('.wpps-ru-success');
	var failMsg = container.querySelector('.wpps-ru-fail');

	var state = { plugins: [], themes: [] };

	function showLoading(show, text) {
		loading.style.display = show ? 'flex' : 'none';
		if (loading.querySelector('.wpps-ru-loading-text')) {
			loading.querySelector('.wpps-ru-loading-text').textContent = text || 'Scanning...';
		}
	}

	function updateSelectedCount() {
		var n = container.querySelectorAll('.wpps-ru-plugin-list input:checked').length + container.querySelectorAll('.wpps-ru-theme-list input:checked').length;
		if (selectedCountEl) selectedCountEl.textContent = n > 0 ? n + ' selected' : '';
		container.querySelectorAll('.wpps-ru-select-all').forEach(function(btn) {
			var target = btn.getAttribute('data-target');
			var list = target === 'plugins' ? pluginList : themeList;
			var cbs = list.querySelectorAll('.wpps-ru-cb');
			var allChecked = cbs.length > 0 && Array.prototype.every.call(cbs, function(c) { return c.checked; });
			btn.textContent = allChecked ? 'Deselect all' : 'Select all';
		});
	}

	function renderLists() {
		var pluginsSection = container.querySelector('.wpps-ru-section.wpps-ru-plugins');
		var themesSection = container.querySelector('.wpps-ru-section.wpps-ru-themes');
		pluginList.innerHTML = '';
		themeList.innerHTML = '';
		if (pluginsSection) pluginsSection.style.display = state.plugins.length ? 'block' : 'none';
		if (themesSection) themesSection.style.display = state.themes.length ? 'block' : 'none';
		nonePlugins.style.display = 'none';
		noneThemes.style.display = 'none';
		state.plugins.forEach(function(p) {
			var div = document.createElement('div');
			div.className = 'wpps-ru-item';
			div.innerHTML = '<label style="display: flex; align-items: center; gap: 10px; width: 100%; cursor: pointer;"><input type="checkbox" class="wpps-ru-cb wpps-ru-cb-plugin" data-file="' + escapeHtml(p.file) + '"><div class="wpps-ru-item-info"><span class="wpps-ru-item-name">' + escapeHtml(p.name) + '</span><div class="wpps-ru-item-meta">' + escapeHtml(p.version ? 'Version ' + p.version : '') + (p.author ? ' · ' + escapeHtml(p.author) : '') + '</div></div></label>';
			pluginList.appendChild(div);
		});
		state.themes.forEach(function(t) {
			var div = document.createElement('div');
			div.className = 'wpps-ru-item';
			div.innerHTML = '<label style="display: flex; align-items: center; gap: 10px; width: 100%; cursor: pointer;"><input type="checkbox" class="wpps-ru-cb wpps-ru-cb-theme" data-slug="' + escapeHtml(t.slug) + '"><div class="wpps-ru-item-info"><span class="wpps-ru-item-name">' + escapeHtml(t.name) + '</span><div class="wpps-ru-item-meta">' + escapeHtml(t.version ? 'Version ' + t.version : '') + (t.author ? ' · ' + escapeHtml(t.author) : '') + '</div></div></label>';
			themeList.appendChild(div);
		});
		removeActions.style.display = (state.plugins.length || state.themes.length) ? 'block' : 'none';
		updateSelectedCount();
		container.querySelectorAll('.wpps-ru-select-all').forEach(function(b) { b.textContent = 'Select all'; });
		pluginList.querySelectorAll('.wpps-ru-cb').forEach(function(cb) { cb.addEventListener('change', updateSelectedCount); });
		themeList.querySelectorAll('.wpps-ru-cb').forEach(function(cb) { cb.addEventListener('change', updateSelectedCount); });
	}

	function escapeHtml(s) {
		if (!s) return '';
		var div = document.createElement('div');
		div.textContent = s;
		return div.innerHTML;
	}

	function doScan(btn, hideAfterRemove) {
		if (hideAfterRemove === undefined) hideAfterRemove = true;
		var nonce = btn.getAttribute('data-nonce');
		var url = btn.getAttribute('data-ajax-url');
		showLoading(true, 'Scanning...');
		results.style.display = 'none';
		if (hideAfterRemove) afterRemove.style.display = 'none';
		var formData = new FormData();
		formData.append('action', 'wpps_ru_scan_inactive');
		formData.append('nonce', nonce);
		fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				showLoading(false);
				if (data.success && data.data) {
					state.plugins = data.data.inactive_plugins || [];
					state.themes = data.data.inactive_themes || [];
					renderLists();
					results.style.display = 'block';
				} else {
					alert(data.data && data.data.message ? data.data.message : 'Scan failed.');
				}
			})
			.catch(function() {
				showLoading(false);
				alert('Request failed.');
			});
	}

	function confirmRemove(type, totalPlugins, totalThemes) {
		var parts = [];
		if (type === 'all' || type === 'plugins') parts.push(totalPlugins + ' plugin(s)');
		if (type === 'all' || type === 'themes') parts.push(totalThemes + ' theme(s)');
		var count = (type === 'all' ? totalPlugins + totalThemes : (type === 'plugins' ? totalPlugins : totalThemes));
		var msg = 'You are about to permanently delete ' + parts.join(' and ') + '.\n\nThis cannot be undone. Make sure you have a backup.\n\nContinue?';
		return window.confirm(msg);
	}

	function doRemove(btn) {
		var type = btn.getAttribute('data-type');
		var nonce = btn.getAttribute('data-nonce');
		var url = btn.getAttribute('data-ajax-url');
		var totalPlugins = state.plugins.length;
		var totalThemes = state.themes.length;
		if (type === 'plugins' && totalPlugins === 0) { alert('No inactive plugins to remove.'); return; }
		if (type === 'themes' && totalThemes === 0) { alert('No inactive themes to remove.'); return; }
		if (type === 'all' && totalPlugins === 0 && totalThemes === 0) { alert('No inactive items to remove.'); return; }
		if (!confirmRemove(type, totalPlugins, totalThemes)) return;
		showLoading(true, 'Removing...');
		var formData = new FormData();
		formData.append('action', 'wpps_ru_remove_inactive');
		formData.append('nonce', nonce);
		formData.append('type', type);
		fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				showLoading(false);
				afterRemove.style.display = 'block';
				successMsg.innerHTML = '';
				failMsg.innerHTML = '';
				if (data.success && data.data) {
					var d = data.data;
					var total = d.total_deleted || 0;
					if (total > 0) {
						successMsg.textContent = 'Successfully deleted ' + total + ' item(s).';
						if (d.deleted_plugins && d.deleted_plugins.length) successMsg.innerHTML += '<br>Plugins: ' + escapeHtml(d.deleted_plugins.join(', '));
						if (d.deleted_themes && d.deleted_themes.length) successMsg.innerHTML += '<br>Themes: ' + escapeHtml(d.deleted_themes.join(', '));
					}
					if (d.failed && d.failed.length) {
						failMsg.innerHTML = 'Failed to delete:<br>' + d.failed.map(function(f) { return escapeHtml(f.name) + ': ' + escapeHtml(f.message); }).join('<br>');
					}
					results.style.display = 'block';
					doScan(scanBtn, false);
				} else {
					failMsg.textContent = (data.data && data.data.message) ? data.data.message : 'Removal failed.';
				}
			})
			.catch(function() {
				showLoading(false);
				afterRemove.style.display = 'block';
				failMsg.textContent = 'Request failed.';
			});
	}

	function doRemoveSelected() {
		var pluginFiles = [];
		var themeSlugs = [];
		container.querySelectorAll('.wpps-ru-cb-plugin:checked').forEach(function(cb) { pluginFiles.push(cb.getAttribute('data-file')); });
		container.querySelectorAll('.wpps-ru-cb-theme:checked').forEach(function(cb) { themeSlugs.push(cb.getAttribute('data-slug')); });
		if (pluginFiles.length === 0 && themeSlugs.length === 0) {
			alert('Select at least one plugin or theme to remove.');
			return;
		}
		var msg = 'Permanently delete ' + (pluginFiles.length ? pluginFiles.length + ' plugin(s)' : '') + (pluginFiles.length && themeSlugs.length ? ' and ' : '') + (themeSlugs.length ? themeSlugs.length + ' theme(s)' : '') + '? This cannot be undone.';
		if (!window.confirm(msg)) return;
		var nonce = removeSelectedBtn.getAttribute('data-nonce');
		var url = removeSelectedBtn.getAttribute('data-ajax-url');
		showLoading(true, 'Removing...');
		var formData = new FormData();
		formData.append('action', 'wpps_ru_remove_inactive');
		formData.append('nonce', nonce);
		formData.append('type', 'selected');
		pluginFiles.forEach(function(f) { formData.append('plugin_files[]', f); });
		themeSlugs.forEach(function(s) { formData.append('theme_slugs[]', s); });
		fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				showLoading(false);
				afterRemove.style.display = 'block';
				successMsg.innerHTML = '';
				failMsg.innerHTML = '';
				if (data.success && data.data) {
					var d = data.data;
					var total = d.total_deleted || 0;
					if (total > 0) {
						successMsg.textContent = 'Successfully deleted ' + total + ' item(s).';
						if (d.deleted_plugins && d.deleted_plugins.length) successMsg.innerHTML += '<br>Plugins: ' + escapeHtml(d.deleted_plugins.join(', '));
						if (d.deleted_themes && d.deleted_themes.length) successMsg.innerHTML += '<br>Themes: ' + escapeHtml(d.deleted_themes.join(', '));
					}
					if (d.failed && d.failed.length) {
						failMsg.innerHTML = 'Failed to delete:<br>' + d.failed.map(function(f) { return escapeHtml(f.name) + ': ' + escapeHtml(f.message); }).join('<br>');
					}
					results.style.display = 'block';
					doScan(scanBtn, false);
				} else {
					failMsg.textContent = (data.data && data.data.message) ? data.data.message : 'Removal failed.';
				}
			})
			.catch(function() {
				showLoading(false);
				afterRemove.style.display = 'block';
				failMsg.textContent = 'Request failed.';
			});
	}

	container.querySelectorAll('.wpps-ru-select-all').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var target = btn.getAttribute('data-target');
			var list = target === 'plugins' ? pluginList : themeList;
			var cbs = list.querySelectorAll('.wpps-ru-cb');
			var allChecked = cbs.length > 0 && Array.prototype.every.call(cbs, function(c) { return c.checked; });
			cbs.forEach(function(c) { c.checked = !allChecked; });
			updateSelectedCount();
		});
	});

	if (scanBtn) scanBtn.addEventListener('click', function() { doScan(scanBtn); });
	if (removeSelectedBtn) removeSelectedBtn.addEventListener('click', doRemoveSelected);
	container.querySelectorAll('.wpps-ru-remove').forEach(function(btn) {
		btn.addEventListener('click', function() { doRemove(btn); });
	});
})();
</script>
