<?php

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 ?? 'unused-media-finder' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Unused Media Finder requires an active license. Activate your license to scan for and remove unused media files.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'unused-media-finder';
}

$scan_nonce   = wp_create_nonce( 'wpps_umf_scan' );
$delete_nonce = wp_create_nonce( 'wpps_umf_delete' );
$ajax_url     = admin_url( 'admin-ajax.php' );

?>
<div class="wp-powersuite-module-settings wpps-umf-settings">
	<p class="description">
		<?php esc_html_e( 'Find media files not used in posts, pages, or as featured images. Delete them to reclaim storage space. The scanner checks post content for wp-image-{id} and featured image meta. Files used only in widgets, theme options, or custom fields may appear unused.', 'wp-powersuite' ); ?>
	</p>

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

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

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

	<div class="wpps-umf-results" style="display: none;">
		<div class="wpps-umf-summary"></div>
		<div class="tablenav top">
			<div class="alignleft actions bulkactions">
				<select class="wpps-umf-bulk-select" aria-label="<?php esc_attr_e( 'Bulk actions', 'wp-powersuite' ); ?>">
					<option value=""><?php esc_html_e( 'Bulk actions', 'wp-powersuite' ); ?></option>
					<option value="delete"><?php esc_html_e( 'Delete', 'wp-powersuite' ); ?></option>
				</select>
				<button type="button" class="button wpps-umf-bulk-apply" data-nonce="<?php echo esc_attr( $delete_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>"><?php esc_html_e( 'Apply', 'wp-powersuite' ); ?></button>
			</div>
			<div class="alignleft actions">
				<button type="button" class="button-link wpps-umf-select-all-btn"><?php esc_html_e( 'Select All', 'wp-powersuite' ); ?></button>
			</div>
			<div class="alignright">
				<button type="button" class="button button-secondary wpps-umf-delete-all" data-nonce="<?php echo esc_attr( $delete_nonce ); ?>" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>"><?php esc_html_e( 'Delete All Unused', 'wp-powersuite' ); ?></button>
			</div>
			<br class="clear">
		</div>
		<div class="wpps-umf-table-wrap">
			<table class="wp-list-table widefat fixed striped wpps-umf-table">
				<thead>
					<tr>
						<th scope="col" class="manage-column column-cb check-column">
							<label class="screen-reader-text" for="cb-select-all-1"><?php esc_html_e( 'Select All', 'wp-powersuite' ); ?></label>
							<input type="checkbox" id="cb-select-all-1" class="wpps-umf-select-all" aria-label="<?php esc_attr_e( 'Select All', 'wp-powersuite' ); ?>">
						</th>
						<th scope="col" class="column-preview"><?php esc_html_e( 'Preview', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-title column-primary"><?php esc_html_e( 'Title', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-size"><?php esc_html_e( 'Size', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-actions"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></th>
					</tr>
				</thead>
				<tbody class="wpps-umf-tbody"></tbody>
				<tfoot>
					<tr>
						<th scope="col" class="manage-column column-cb check-column">
							<input type="checkbox" class="wpps-umf-select-all wpps-umf-select-all-foot" aria-label="<?php esc_attr_e( 'Select All', 'wp-powersuite' ); ?>">
						</th>
						<th scope="col" class="column-preview"><?php esc_html_e( 'Preview', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-title column-primary"><?php esc_html_e( 'Title', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-size"><?php esc_html_e( 'Size', 'wp-powersuite' ); ?></th>
						<th scope="col" class="column-actions"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></th>
					</tr>
				</tfoot>
			</table>
		</div>
	</div>

	<div class="wpps-umf-info-box">
		<p>
			<strong><?php esc_html_e( 'Warning', 'wp-powersuite' ); ?></strong><br>
			<?php esc_html_e( 'Deletion is permanent. The file, all thumbnails, and the attachment record are removed. Always backup your site before bulk deletion. Files used in widgets, theme options, ACF fields, or page builder backgrounds might appear unused but are in use.', 'wp-powersuite' ); ?>
		</p>
	</div>
</div>



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

	var scanBtn = container.querySelector('.wpps-umf-scan');
	var loading = container.querySelector('.wpps-umf-loading');
	var results = container.querySelector('.wpps-umf-results');
	var summary = container.querySelector('.wpps-umf-summary');
	var tbody = container.querySelector('.wpps-umf-tbody');
	var selectAllBtn = container.querySelector('.wpps-umf-select-all-btn');
	var bulkSelect = container.querySelector('.wpps-umf-bulk-select');
	var bulkApplyBtn = container.querySelector('.wpps-umf-bulk-apply');
	var deleteAllBtn = container.querySelector('.wpps-umf-delete-all');
	var afterDelete = container.querySelector('.wpps-umf-after-delete');
	var successMsg = container.querySelector('.wpps-umf-success');
	var failMsg = container.querySelector('.wpps-umf-fail');

	var state = { unused: [], scanId: '', scanning: false };

	function clearChildren(el) {
		while (el.firstChild) {
			el.removeChild(el.firstChild);
		}
	}

	function formatSize(bytes) {
		if (bytes === 0) return '0 B';
		var k = 1024;
		var sizes = ['B', 'KB', 'MB', 'GB'];
		var i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
	}

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

	function updateSelectedCount() {
		var cbs = container.querySelectorAll('.wpps-umf-cb:checked');
		var allCbs = container.querySelectorAll('.wpps-umf-cb');
		var allChecked = allCbs.length > 0 && allCbs.length === cbs.length;
		container.querySelectorAll('.wpps-umf-select-all').forEach(function(cb) { if (cb) cb.checked = allChecked; });
		if (selectAllBtn) selectAllBtn.textContent = allChecked ? '<?php echo esc_js( __( 'Deselect All', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Select All', 'wp-powersuite' ) ); ?>';
	}

	function createDeleteControl(tagName, itemId) {
		var el = document.createElement(tagName);
		el.className = 'wpps-umf-delete-one';
		el.setAttribute('data-id', String(itemId));
		el.setAttribute('data-nonce', '<?php echo esc_js( $delete_nonce ); ?>');
		el.setAttribute('data-ajax-url', '<?php echo esc_js( $ajax_url ); ?>');
		if (tagName === 'a') {
			el.href = '#';
		} else {
			el.type = 'button';
		}
		el.textContent = '<?php echo esc_js( __( 'Delete', 'wp-powersuite' ) ); ?>';
		return el;
	}

	function createPreviewCell(item) {
		var td = document.createElement('td');
		td.className = 'column-preview';
		var isImage = (item.mime || '').indexOf('image/') === 0;
		if (isImage) {
			var img = document.createElement('img');
			img.src = item.thumbnail || '';
			img.alt = '';
			img.className = 'wpps-umf-preview';
			td.appendChild(img);
		} else {
			var wrap = document.createElement('div');
			wrap.className = 'wpps-umf-preview-icon';
			var icon = document.createElement('img');
			icon.src = item.thumbnail || '';
			icon.alt = '';
			wrap.appendChild(icon);
			td.appendChild(wrap);
		}
		return td;
	}

	function createUnusedRow(item) {
		var tr = document.createElement('tr');
		tr.dataset.id = String(item.id);

		var th = document.createElement('th');
		th.scope = 'row';
		th.className = 'check-column';
		var cb = document.createElement('input');
		cb.type = 'checkbox';
		cb.className = 'wpps-umf-cb';
		cb.value = String(item.id);
		th.appendChild(cb);
		tr.appendChild(th);

		tr.appendChild(createPreviewCell(item));

		var titleTd = document.createElement('td');
		titleTd.className = 'column-title column-primary';
		titleTd.setAttribute('data-colname', '<?php echo esc_attr( __( 'Title', 'wp-powersuite' ) ); ?>');
		var titleStrong = document.createElement('strong');
		titleStrong.className = 'row-title';
		titleStrong.textContent = item.title || 'Untitled';
		titleTd.appendChild(titleStrong);
		var rowActions = document.createElement('div');
		rowActions.className = 'row-actions';
		var deleteSpan = document.createElement('span');
		deleteSpan.className = 'delete';
		deleteSpan.appendChild(createDeleteControl('button', item.id));
		rowActions.appendChild(deleteSpan);
		titleTd.appendChild(rowActions);
		tr.appendChild(titleTd);

		var sizeTd = document.createElement('td');
		sizeTd.className = 'column-size';
		sizeTd.setAttribute('data-colname', '<?php echo esc_attr( __( 'Size', 'wp-powersuite' ) ); ?>');
		sizeTd.textContent = formatSize(item.size);
		tr.appendChild(sizeTd);

		var actionsTd = document.createElement('td');
		actionsTd.className = 'column-actions';
		actionsTd.setAttribute('data-colname', '<?php echo esc_attr( __( 'Actions', 'wp-powersuite' ) ); ?>');
		actionsTd.appendChild(createDeleteControl('a', item.id));
		tr.appendChild(actionsTd);

		return tr;
	}

	function renderTable() {
		clearChildren(tbody);
		var totalSize = 0;
		state.unused.forEach(function(item) {
			totalSize += item.size || 0;
			tbody.appendChild(createUnusedRow(item));
		});
		summary.textContent = state.unused.length + ' <?php echo esc_js( __( 'unused file(s) found', 'wp-powersuite' ) ); ?> — ' + formatSize(totalSize) + ' <?php echo esc_js( __( 'total', 'wp-powersuite' ) ); ?>';
		updateSelectedCount();
	}

	function doScanBatch(continueScan) {
		var nonce = scanBtn.getAttribute('data-nonce');
		var url = scanBtn.getAttribute('data-ajax-url');
		if (!continueScan) {
			state.unused = [];
			state.scanId = '';
			results.style.display = 'none';
			afterDelete.style.display = 'none';
			clearChildren(tbody);
		}
		showLoading(true, continueScan ? '<?php echo esc_js( __( 'Scanning more…', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Scanning...', 'wp-powersuite' ) ); ?>');
		var formData = new FormData();
		formData.append('action', 'wpps_umf_scan');
		formData.append('nonce', nonce);
		if (continueScan && state.scanId) {
			formData.append('continue', '1');
			formData.append('scan_id', state.scanId);
		}
		fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (!data.success || !data.data) {
					showLoading(false);
					state.scanning = false;
					scanBtn.disabled = false;
					alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Scan failed.', 'wp-powersuite' ) ); ?>');
					return;
				}
				if (data.data.scan_id) {
					state.scanId = data.data.scan_id;
				}
				if (data.data.unused && data.data.unused.length) {
					data.data.unused.forEach(function(item) { state.unused.push(item); });
					renderTable();
					results.style.display = 'block';
				}
				if (!data.data.done) {
					doScanBatch(true);
					return;
				}
				showLoading(false);
				state.scanning = false;
				scanBtn.disabled = false;
				if (state.unused.length === 0) {
					alert('<?php echo esc_js( __( 'No unused media found.', 'wp-powersuite' ) ); ?>');
				} else {
					renderTable();
					results.style.display = 'block';
				}
			})
			.catch(function() {
				showLoading(false);
				state.scanning = false;
				scanBtn.disabled = false;
				alert('<?php echo esc_js( __( 'Request failed.', 'wp-powersuite' ) ); ?>');
			});
	}

	function doScan() {
		if (state.scanning) return;
		state.scanning = true;
		scanBtn.disabled = true;
		doScanBatch(false);
	}

	function removeRowsByIds(ids) {
		ids.forEach(function(id) {
			var row = container.querySelector('.wpps-umf-tbody tr[data-id="' + id + '"]');
			if (row) row.remove();
		});
		state.unused = state.unused.filter(function(item) { return ids.indexOf(item.id) === -1; });
		if (state.unused.length === 0) {
			results.style.display = 'none';
		} else {
			var totalSize = state.unused.reduce(function(a, b) { return a + (b.size || 0); }, 0);
			summary.textContent = state.unused.length + ' <?php echo esc_js( __( 'unused file(s) remaining', 'wp-powersuite' ) ); ?> — ' + formatSize(totalSize) + ' <?php echo esc_js( __( 'total', 'wp-powersuite' ) ); ?>';
		}
		updateSelectedCount();
	}

	function doDeleteOne(btn) {
		var id = parseInt(btn.getAttribute('data-id'), 10);
		if (!window.confirm('<?php echo esc_js( __( 'Permanently delete this file?', 'wp-powersuite' ) ); ?>')) return;
		var nonce = btn.getAttribute('data-nonce');
		var url = btn.getAttribute('data-ajax-url');
		showLoading(true, '<?php echo esc_js( __( 'Deleting...', 'wp-powersuite' ) ); ?>');
		var formData = new FormData();
		formData.append('action', 'wpps_umf_delete');
		formData.append('nonce', nonce);
		if (state.scanId) {
			formData.append('scan_id', state.scanId);
		}
		formData.append('ids[]', id);
		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) {
					removeRowsByIds(data.data.deleted || []);
					if (data.data.failed && data.data.failed.length) {
						afterDelete.style.display = 'block';
						failMsg.textContent = data.data.failed[0].message || '<?php echo esc_js( __( 'Deletion failed.', 'wp-powersuite' ) ); ?>';
					} else {
						afterDelete.style.display = 'block';
						successMsg.textContent = '<?php echo esc_js( __( 'File deleted.', 'wp-powersuite' ) ); ?>';
						failMsg.textContent = '';
					}
				} else {
					alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Deletion failed.', 'wp-powersuite' ) ); ?>');
				}
			})
			.catch(function() {
				showLoading(false);
				alert('<?php echo esc_js( __( 'Request failed.', 'wp-powersuite' ) ); ?>');
			});
	}

	function doDeleteSelected() {
		var ids = [];
		container.querySelectorAll('.wpps-umf-cb:checked').forEach(function(cb) {
			ids.push(parseInt(cb.value, 10));
		});
		if (ids.length === 0) {
			alert('<?php echo esc_js( __( 'Select at least one file to delete.', 'wp-powersuite' ) ); ?>');
			return;
		}
		if (!window.confirm(ids.length + ' <?php echo esc_js( __( 'file(s) will be permanently deleted. This cannot be undone. Continue?', 'wp-powersuite' ) ); ?>')) return;
		doDelete(ids);
	}

	function doDeleteAll() {
		if (state.unused.length === 0) return;
		var warn = '<?php echo esc_js( __( 'You are about to permanently delete ALL unused files found in this scan. The scanner checks featured images and post content only — files used in widgets, theme options, menus, page builders, or custom fields may still appear unused. Always back up your site first.', 'wp-powersuite' ) ); ?>';
		if (!window.confirm(warn)) return;
		if (!window.confirm(state.unused.length + ' <?php echo esc_js( __( 'file(s) will be permanently deleted. This cannot be undone. Continue?', 'wp-powersuite' ) ); ?>')) return;
		doDelete(state.unused.map(function(i) { return i.id; }));
	}

	function doDelete(ids) {
		var nonce = (bulkApplyBtn || deleteAllBtn).getAttribute('data-nonce');
		var url = (bulkApplyBtn || deleteAllBtn).getAttribute('data-ajax-url');
		showLoading(true, '<?php echo esc_js( __( 'Deleting...', 'wp-powersuite' ) ); ?>');
		var formData = new FormData();
		formData.append('action', 'wpps_umf_delete');
		formData.append('nonce', nonce);
		if (state.scanId) {
			formData.append('scan_id', state.scanId);
		}
		ids.forEach(function(id) { formData.append('ids[]', id); });
		fetch(url, { method: 'POST', body: formData, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				showLoading(false);
				afterDelete.style.display = 'block';
				successMsg.textContent = '';
				failMsg.textContent = '';
				if (data.success && data.data) {
					var d = data.data;
					if (d.deleted && d.deleted.length) {
						removeRowsByIds(d.deleted);
						successMsg.textContent = d.total_deleted + ' <?php echo esc_js( __( 'file(s) deleted.', 'wp-powersuite' ) ); ?>';
					}
					if (d.failed && d.failed.length) {
						failMsg.textContent = '<?php echo esc_js( __( 'Failed:', 'wp-powersuite' ) ); ?> ' + d.failed.map(function(f) { return f.message || ''; }).join('; ');
					}
				} else {
					failMsg.textContent = (data.data && data.data.message) ? data.data.message : '<?php echo esc_js( __( 'Deletion failed.', 'wp-powersuite' ) ); ?>';
				}
			})
			.catch(function() {
				showLoading(false);
				afterDelete.style.display = 'block';
				failMsg.textContent = '<?php echo esc_js( __( 'Request failed.', 'wp-powersuite' ) ); ?>';
			});
	}

	container.addEventListener('change', function(e) {
		if (e.target.classList.contains('wpps-umf-cb')) {
			updateSelectedCount();
			return;
		}
		if (e.target.classList.contains('wpps-umf-select-all')) {
			container.querySelectorAll('.wpps-umf-cb').forEach(function(c) { c.checked = e.target.checked; });
			updateSelectedCount();
		}
	});

	container.addEventListener('click', function(e) {
		var deleteBtn = e.target.closest('.wpps-umf-delete-one');
		if (deleteBtn) {
			e.preventDefault();
			doDeleteOne(deleteBtn);
		}
	});

	if (selectAllBtn) {
		selectAllBtn.addEventListener('click', function() {
			var allCbs = container.querySelectorAll('.wpps-umf-cb');
			var allChecked = allCbs.length > 0 && container.querySelectorAll('.wpps-umf-cb:checked').length === allCbs.length;
			allCbs.forEach(function(c) { c.checked = !allChecked; });
			container.querySelectorAll('.wpps-umf-select-all').forEach(function(cb) { if (cb) cb.checked = !allChecked; });
			updateSelectedCount();
		});
	}
	if (scanBtn) scanBtn.addEventListener('click', doScan);
	if (bulkApplyBtn) bulkApplyBtn.addEventListener('click', function() {
		if (bulkSelect && bulkSelect.value === 'delete') doDeleteSelected();
	});
	if (deleteAllBtn) deleteAllBtn.addEventListener('click', doDeleteAll);
})();
</script>
