<?php

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;
/**
 * Code Snippet Admin Interface
 *
 * Admin UI for managing code snippets. Uses WordPress WP_List_Table.
 *
 * @package CodeSnippet
 * @since 1.0.0
 */

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

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'code-snippet';
}

$module_class = 'CodeSnippet\\Module';
if ( ! class_exists( $module_class ) ) {
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Code Snippet module class not found.', 'wppowersuite-lite' ) . '</p></div>';
	return;
}

$module = null;
if ( class_exists( 'WP_PowerSuite\\Core\\ModuleManager' ) ) {
	$module_manager = \WP_PowerSuite\Core\ModuleManager::getInstance();
	$module        = $module_manager->getModule( 'code-snippet' );
}
if ( ! $module ) {
	$module = new $module_class();
}

// Bulk action success notice
$cs_done = isset( $_GET['cs_done'] ) ? sanitize_text_field( wp_unslash( $_GET['cs_done'] ) ) : '';
if ( $cs_done !== '' ) {
	$parts = explode( '_', $cs_done, 2 );
	$num   = isset( $parts[0] ) ? absint( $parts[0] ) : 0;
	$act   = isset( $parts[1] ) ? $parts[1] : '';
	$labels = [
		'activate'   => __( 'activated', 'wppowersuite-lite' ),
		'deactivate' => __( 'deactivated', 'wppowersuite-lite' ),
		'delete'     => __( 'deleted', 'wppowersuite-lite' ),
		'export'     => __( 'exported', 'wppowersuite-lite' ),
	];
	$label = $labels[ $act ] ?? $act;
	if ( $num > 0 ) {
		/* translators: 1: number, 2: string, 1: number, 2: string. */
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( _n( '%1$d snippet %2$s.', '%1$d snippets %2$s.', $num, 'wppowersuite-lite' ), $num, $label ) ) . '</p></div>';
	}
}

$cs_skipped = isset( $_GET['cs_skipped'] ) ? absint( $_GET['cs_skipped'] ) : 0;
if ( $cs_skipped > 0 ) {
	/* translators: 1: number, 2: number. */
	echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( sprintf( _n( '%d snippet could not be activated (PHP errors, PRO-only features, or validation failed).', '%d snippets could not be activated (PHP errors, PRO-only features, or validation failed).', $cs_skipped, 'wppowersuite-lite' ), $cs_skipped ) ) . '</p></div>';
}

$cs_error = isset( $_GET['cs_error'] ) ? sanitize_text_field( wp_unslash( $_GET['cs_error'] ) ) : '';
if ( $cs_error !== '' ) {
	echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $cs_error ) . '</p></div>';
}

$cs_imported = isset( $_GET['cs_imported'] ) ? absint( $_GET['cs_imported'] ) : 0;
if ( $cs_imported > 0 ) {
	echo '<div class="notice notice-success is-dismissible"><p>' . esc_html(
		sprintf(
			/* translators: %d: number of imported snippets. */
			_n( 'Imported %d snippet.', 'Imported %d snippets.', $cs_imported, 'wppowersuite-lite' ),
			$cs_imported
		)
	) . '</p></div>';
}

$cs_import_skipped = isset( $_GET['cs_import_skipped'] ) ? absint( $_GET['cs_import_skipped'] ) : 0;
if ( $cs_import_skipped > 0 ) {
	echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html(
		sprintf(
			/* translators: %d: number of skipped snippets. */
			_n( '%d snippet was skipped.', '%d snippets were skipped.', $cs_import_skipped, 'wppowersuite-lite' ),
			$cs_import_skipped
		)
	) . '</p></div>';
}

$cs_import_error = isset( $_GET['cs_import_error'] ) ? sanitize_text_field( wp_unslash( $_GET['cs_import_error'] ) ) : '';
if ( $cs_import_error !== '' ) {
	echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( $cs_import_error ) . '</p></div>';
}

require_once __DIR__ . '/class-code-snippet-list-table.php';
?>
<div class="wrap wpps-cs-wrap">
	<hr class="wp-header-end">
	<?php
	\WP_PowerSuite\Admin\PageHero::render_for_module(
		[
			'icon'    => 'dashicons-editor-code',
			'title'   => __( 'Code Snippets', 'wppowersuite-lite' ),
			'tagline' => __( 'Add custom HTML, CSS, JavaScript, or PHP snippets with auto-insert in header, body, or footer, or use shortcodes', 'wppowersuite-lite' ),
			'actions' => [
				[
					'label'     => __( 'Settings', 'wppowersuite-lite' ),
					'url'       => admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ),
					'icon'      => 'dashicons-admin-generic',
					'icon_only' => true,
				],
				[
					'label'     => __( 'Error Logs', 'wppowersuite-lite' ),
					'url'       => admin_url( 'admin.php?page=powersuite-code-snippet&view=logs' ),
					'icon'      => 'dashicons-media-text',
					'icon_only' => true,
				],
				[
					'label'     => __( 'Safe Mode', 'wppowersuite-lite' ),
					'title'     => __( 'Disable all snippets temporarily', 'wppowersuite-lite' ),
					'url'       => admin_url( 'admin.php?page=powersuite-code-snippet&wpps-cs-safe-mode=1' ),
					'icon'      => 'dashicons-shield',
					'icon_only' => true,
				],
				[
					'label'     => __( 'Export JSON', 'wppowersuite-lite' ),
					'url'       => \CodeSnippet\ImportExport::exportUrl(),
					'icon'      => 'dashicons-download',
					'icon_only' => true,
				],
				[
					'label'     => __( 'Import', 'wppowersuite-lite' ),
					'type'      => 'button',
					'icon'      => 'dashicons-upload',
					'icon_only' => true,
					'id'        => 'wpps-cs-import-toggle',
					'class'     => 'wpps-cs-import-toggle',
				],
				[
					'label'     => __( 'Add Snippet', 'wppowersuite-lite' ),
					'url'       => admin_url( 'admin.php?page=powersuite-code-snippet&action=add' ),
					'icon'      => 'dashicons-plus-alt2',
					'icon_only' => true,
					'class'     => 'wpps-page-hero__action--primary',
				],
			],
		]
	);
	?>

	<?php
		$module_enabled = OptionStoreModuleSettingsRepository::isModuleEnabled( 'code-snippet'  );
	if ( \CodeSnippet\Module::isSafeMode() ) :
		?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Safe Mode is active.', 'wppowersuite-lite' ); ?></strong>
				<?php esc_html_e( 'Snippets are disabled for your admin session only. Other visitors are unaffected. Remove the safe mode parameter from the URL to re-enable snippets for yourself.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet' ) ); ?>"><?php esc_html_e( 'Disable Safe Mode', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	<?php endif; ?>
	<?php if ( \CodeSnippet\Module::getSetting( 'global_safe_mode', false ) ) : ?>
		<div class="notice notice-error">
			<p>
				<strong><?php esc_html_e( 'Global Safe Mode is enabled.', 'wppowersuite-lite' ); ?></strong>
				<?php esc_html_e( 'All snippets are disabled site-wide.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ) ); ?>"><?php esc_html_e( 'Disable in settings', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	<?php endif; ?>
	<?php if ( ! $module_enabled ) :
		?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Code Snippet module is disabled.', 'wppowersuite-lite' ); ?></strong>
				<?php esc_html_e( 'Snippets will not run on your site until you enable this module in PowerSuite settings.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite' ) ); ?>"><?php esc_html_e( 'Enable module', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<div class="wpps-cs-import-panel" id="wpps-cs-import-panel" <?php echo ( $cs_import_error !== '' || $cs_imported > 0 ) ? '' : 'hidden'; ?>>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
			<input type="hidden" name="action" value="wpps_cs_import">
			<?php wp_nonce_field( 'wpps_cs_import' ); ?>
			<h2><?php esc_html_e( 'Import snippets', 'wppowersuite-lite' ); ?></h2>
			<p class="description"><?php esc_html_e( 'Upload a .json export from WP PowerSuite, WPCode, or Code Snippets, or paste the JSON below. Each snippet is re-validated on import.', 'wppowersuite-lite' ); ?></p>
			<p>
				<input type="file" name="import_file" accept=".json,application/json">
			</p>
			<textarea name="import_json" class="large-text code" rows="8" placeholder='{"schema":1,"source":"wp-powersuite-code-snippet","snippets":[ ... ]}'></textarea>
			<p>
				<label><input type="checkbox" name="import_inactive" value="1" checked> <?php esc_html_e( 'Import as inactive (recommended)', 'wppowersuite-lite' ); ?></label>
			</p>
			<p>
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Import', 'wppowersuite-lite' ); ?></button>
			</p>
		</form>
	</div>

	<div id="wpps-cs-list-app">
		<?php Code_Snippet_List_Table::renderAppInner( $module ); ?>
	</div>
	<div id="wpps-cs-toast" class="wpps-cs-toast" role="status" aria-live="polite" aria-atomic="true" aria-hidden="true">
		<span id="wpps-cs-toast-message"></span>
	</div>
	<?php ob_start(); ?>
	(function() {
		var ajaxurl = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
		var nonce = <?php echo wp_json_encode( wp_create_nonce( 'wpps_cs_nonce' ) ); ?>;
		var wrap = document.querySelector('.wpps-cs-wrap');
		var panel = document.getElementById('wpps-cs-import-panel');
		var activeText = <?php echo wp_json_encode( __( 'Active', 'wppowersuite-lite' ) ); ?>;
		var inactiveText = <?php echo wp_json_encode( __( 'Inactive', 'wppowersuite-lite' ) ); ?>;
		var activateText = <?php echo wp_json_encode( __( 'Activate', 'wppowersuite-lite' ) ); ?>;
		var deactivateText = <?php echo wp_json_encode( __( 'Deactivate', 'wppowersuite-lite' ) ); ?>;
		var deleteConfirm = <?php echo wp_json_encode( __( 'Delete this snippet? This cannot be undone.', 'wppowersuite-lite' ) ); ?>;
		var deleteOk = <?php echo wp_json_encode( __( 'Snippet deleted.', 'wppowersuite-lite' ) ); ?>;
		var deleteFail = <?php echo wp_json_encode( __( 'Could not delete snippet.', 'wppowersuite-lite' ) ); ?>;
		var requestFail = <?php echo wp_json_encode( __( 'Request failed.', 'wppowersuite-lite' ) ); ?>;
		var FILTER_KEYS = ['status', 's', 'snippet_type', 'snippet_location', 'snippet_device', 'orderby', 'order', 'paged'];
		var toastTimeout = null;

		function listApp() {
			return document.getElementById('wpps-cs-list-app');
		}

		function emptyParams() {
			return { status: 'all', s: '', snippet_type: '', snippet_location: '', snippet_device: '', orderby: '', order: '', paged: '' };
		}

		function paramsFromUrl(href) {
			var p = emptyParams();
			try {
				var u = new URL(href, window.location.origin);
				FILTER_KEYS.forEach(function(k) {
					if (u.searchParams.has(k)) p[k] = String(u.searchParams.get(k) || '');
				});
			} catch (e) {}
			return p;
		}

		function paramsFromForm() {
			var p = emptyParams();
			var form = document.getElementById('wpps-cs-list-form');
			if (!form) return paramsFromUrl(window.location.href);
			var fd = new FormData(form);
			FILTER_KEYS.forEach(function(k) {
				if (fd.has(k)) p[k] = String(fd.get(k));
			});
			return p;
		}

		function refreshList(params, push) {
			var app = listApp();
			if (!app || app.dataset.loading === '1') return;
			app.dataset.loading = '1';
			app.classList.add('is-loading');
			var body = new URLSearchParams();
			body.set('action', 'wpps_cs_list_snippets');
			body.set('nonce', nonce);
			FILTER_KEYS.forEach(function(k) {
				if (params[k] != null && params[k] !== '') body.set(k, params[k]);
			});
			var xhr = new XMLHttpRequest();
			xhr.open('POST', ajaxurl);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr.onload = function() {
				app.dataset.loading = '';
				app.classList.remove('is-loading');
				try {
					var r = JSON.parse(xhr.responseText);
					if (r.success && r.data && typeof r.data.html === 'string') {
						app.innerHTML = r.data.html;
						if (push && r.data.url && r.data.url !== window.location.href) {
							history.pushState({ wppsCsList: true }, '', r.data.url);
						}
					}
				} catch (e) {}
			};
			xhr.onerror = function() {
				app.dataset.loading = '';
				app.classList.remove('is-loading');
			};
			xhr.send(body.toString());
		}

		function postForm(action, extra) {
			return new Promise(function(resolve, reject) {
				var body = new URLSearchParams();
				body.set('action', action);
				body.set('nonce', nonce);
				Object.keys(extra || {}).forEach(function(k) { body.set(k, extra[k]); });
				var xhr = new XMLHttpRequest();
				xhr.open('POST', ajaxurl);
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xhr.onload = function() {
					try { resolve(JSON.parse(xhr.responseText)); }
					catch (e) { reject(e); }
				};
				xhr.onerror = function() { reject(new Error('network')); };
				xhr.send(body.toString());
			});
		}

		function showToast(msg, type) {
			var toast = document.getElementById('wpps-cs-toast');
			var toastMsg = document.getElementById('wpps-cs-toast-message');
			if (!toast || !toastMsg || !msg) return;
			clearTimeout(toastTimeout);
			toast.className = 'wpps-cs-toast wpps-cs-toast-' + (type === 'error' ? 'error' : 'success');
			toastMsg.textContent = msg;
			toast.setAttribute('aria-hidden', 'false');
			toast.classList.add('is-visible');
			toastTimeout = setTimeout(function() {
				toast.classList.remove('is-visible');
				toast.setAttribute('aria-hidden', 'true');
			}, 2800);
		}

		function currentStatusFilter() {
			try {
				return new URL(window.location.href).searchParams.get('status') || 'all';
			} catch (e) {
				return 'all';
			}
		}

		function updateViewCounts(counts) {
			if (!counts) return;
			document.querySelectorAll('#wpps-cs-list-app .subsubsub a').forEach(function(a) {
				var status = 'all';
				try {
					status = new URL(a.href, window.location.origin).searchParams.get('status') || 'all';
				} catch (e) {}
				var span = a.querySelector('.count');
				if (span && counts[status] != null) {
					span.textContent = '(' + counts[status] + ')';
				}
			});
		}

		function setRowActive(row, active) {
			if (!row) return;
			var toggle = row.querySelector('.wpps-cs-status-toggle');
			var cb = row.querySelector('.wpps-cs-status-switch');
			var label = row.querySelector('.wpps-cs-status-label');
			if (cb) cb.checked = !!active;
			if (label) label.textContent = active ? activeText : inactiveText;
			if (toggle) toggle.setAttribute('title', active ? deactivateText : activateText);
			var actionWrap = row.querySelector('.row-actions .activate, .row-actions .deactivate');
			if (actionWrap) {
				actionWrap.className = active ? 'deactivate' : 'activate';
				var a = actionWrap.querySelector('a');
				if (a) {
					a.textContent = active ? deactivateText : activateText;
					a.classList.toggle('submitdelete', !!active);
					var href = a.getAttribute('href') || '';
					a.setAttribute('href', active
						? href.replace('action=activate', 'action=deactivate')
						: href.replace('action=deactivate', 'action=activate'));
				}
			}
		}

		function removeRowIfFilteredOut(row, active) {
			var filter = currentStatusFilter();
			if ((filter === 'active' && !active) || (filter === 'inactive' && active)) {
				row.classList.add('wpps-cs-row-leaving');
				window.setTimeout(function() {
					if (row.parentNode) row.remove();
					var tbody = document.querySelector('#wpps-cs-list-app .wp-list-table tbody');
					if (tbody && !tbody.querySelector('tr')) {
						refreshList(paramsFromUrl(window.location.href), false);
					}
				}, 200);
			}
		}

		function requestToggle(id, row, cb) {
			var toggle = row ? row.querySelector('.wpps-cs-status-toggle') : null;
			if (toggle && toggle.classList.contains('is-busy')) {
				if (cb) {
					cb.checked = !cb.checked;
					setRowActive(row, cb.checked);
				}
				return;
			}
			if (toggle) toggle.classList.add('is-busy');
			postForm('wpps_cs_toggle_snippet', { id: id }).then(function(r) {
				if (toggle) toggle.classList.remove('is-busy');
				if (r.success && r.data) {
					setRowActive(row, !!r.data.active);
					updateViewCounts(r.data.counts);
					removeRowIfFilteredOut(row, !!r.data.active);
					showToast(r.data.message || (r.data.active ? activeText : inactiveText), 'success');
				} else {
					if (cb) {
						cb.checked = !cb.checked;
						setRowActive(row, cb.checked);
					}
					showToast((r.data && r.data.message) ? r.data.message : requestFail, 'error');
				}
			}).catch(function() {
				if (toggle) toggle.classList.remove('is-busy');
				if (cb) {
					cb.checked = !cb.checked;
					setRowActive(row, cb.checked);
				}
				showToast(requestFail, 'error');
			});
		}

		if (history.replaceState) {
			history.replaceState({ wppsCsList: true }, '', window.location.href);
		}

		if (wrap) {
			wrap.addEventListener('click', function(e) {
				var importBtn = e.target.closest('.wpps-cs-import-toggle');
				if (importBtn) {
					if (!panel) return;
					panel.hidden = !panel.hidden;
					if (!panel.hidden) {
						var field = panel.querySelector('textarea[name="import_json"]');
						if (field) field.focus();
					}
					return;
				}

				var viewLink = e.target.closest('#wpps-cs-list-app .subsubsub a');
				if (viewLink) {
					e.preventDefault();
					refreshList(paramsFromUrl(viewLink.href), true);
					return;
				}

				var sortLink = e.target.closest('#wpps-cs-list-app .wp-list-table thead a');
				if (sortLink) {
					e.preventDefault();
					refreshList(paramsFromUrl(sortLink.href), true);
					return;
				}

				var pageLink = e.target.closest('#wpps-cs-list-app .tablenav-pages a');
				if (pageLink) {
					e.preventDefault();
					refreshList(paramsFromUrl(pageLink.href), true);
					return;
				}

				var del = e.target.closest('.wpps-cs-delete-link');
				if (del) {
					e.preventDefault();
					if (!confirm(deleteConfirm)) return;
					var delId = del.getAttribute('data-id');
					postForm('wpps_cs_delete_snippet', { id: delId }).then(function(r) {
						if (r.success) {
							showToast((r.data && r.data.message) ? r.data.message : deleteOk, 'success');
							refreshList(paramsFromUrl(window.location.href), false);
						} else {
							showToast((r.data && r.data.message) ? r.data.message : deleteFail, 'error');
						}
					}).catch(function() { showToast(requestFail, 'error'); });
					return;
				}

				var rowToggle = e.target.closest('.row-actions a');
				if (rowToggle && rowToggle.href) {
					var href = rowToggle.getAttribute('href') || '';
					if (href.indexOf('action=activate') !== -1 || href.indexOf('action=deactivate') !== -1) {
						e.preventDefault();
						var match = href.match(/[?&]id=(\d+)/);
						var toggleId = match ? match[1] : '';
						if (!toggleId) return;
						requestToggle(toggleId, rowToggle.closest('tr'), null);
					}
				}
			});

			wrap.addEventListener('change', function(e) {
				var cb = e.target.closest('.wpps-cs-status-switch');
				if (cb && cb.type === 'checkbox') {
					var row = cb.closest('tr');
					var label = cb.closest('.wpps-cs-status-toggle') && cb.closest('.wpps-cs-status-toggle').querySelector('.wpps-cs-status-label');
					if (label) label.textContent = cb.checked ? activeText : inactiveText;
					requestToggle(cb.getAttribute('data-id'), row, cb);
					return;
				}

				var filterSelect = e.target.closest('#wpps-cs-list-form select[name="snippet_type"], #wpps-cs-list-form select[name="snippet_location"], #wpps-cs-list-form select[name="snippet_device"]');
				if (filterSelect) {
					refreshList(paramsFromForm(), true);
				}
			});

			wrap.addEventListener('submit', function(e) {
				var form = e.target.closest('#wpps-cs-list-form');
				if (!form) return;
				var submitter = e.submitter;
				var submitId = submitter ? submitter.id : '';
				var submitName = submitter ? submitter.name : '';
				if (submitId === 'doaction' || submitId === 'doaction2') {
					return;
				}
				if (submitName === 'filter_action' || submitId === 'search-submit' || submitId === 'wpps-cs-filter-submit' || !submitter) {
					e.preventDefault();
					refreshList(paramsFromForm(), true);
				}
			});
		}

		window.addEventListener('popstate', function(e) {
			if (!e.state || !e.state.wppsCsList) return;
			refreshList(paramsFromUrl(window.location.href), false);
		});
	})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-code-snippet-admin-php-script-1', (string) ob_get_clean() ); ?>
</div>

