<?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.', 'wp-powersuite' ) . '</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();
}

$status  = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : 'all';
if ( ! in_array( $status, [ 'all', 'active', 'inactive' ], true ) ) {
	$status = 'all';
}
$search = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : '';

// 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', 'wp-powersuite' ),
		'deactivate' => __( 'deactivated', 'wp-powersuite' ),
		'delete'     => __( 'deleted', 'wp-powersuite' ),
	];
	$label = $labels[ $act ] ?? $act;
	if ( $num > 0 ) {
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( _n( '%1$d snippet %2$s.', '%1$d snippets %2$s.', $num, 'wp-powersuite' ), $num, $label ) ) . '</p></div>';
	}
}

$cs_skipped = isset( $_GET['cs_skipped'] ) ? absint( $_GET['cs_skipped'] ) : 0;
if ( $cs_skipped > 0 ) {
	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, 'wp-powersuite' ), $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>';
}

require_once __DIR__ . '/class-code-snippet-list-table.php';
$list_table = new Code_Snippet_List_Table( $module, $status, $search );
$list_table->prepare_items();
$snippets    = $list_table->items;
$total_count = $module->getSnippetCounts()['all'];
?>
<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', 'wp-powersuite' ),
			'tagline'   => __( 'Add custom HTML, CSS, JavaScript, or PHP snippets with auto-insert in header, body, or footer, or use shortcodes', 'wp-powersuite' ),
			'stats'     => [
				[
					'value' => number_format_i18n( $total_count ),
					'label' => __( 'Snippets', 'wp-powersuite' ),
				],
			],
			'meta_html' => sprintf(
				'<a href="%1$s" class="button button-secondary">%2$s</a>'
				. '<a href="%3$s" class="button button-secondary">%4$s</a>'
				. '<a href="%5$s" class="button button-secondary" title="%8$s">%6$s</a>'
				. '<a href="%7$s" class="button button-primary">%9$s</a>',
				esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ) ),
				esc_html__( 'Settings', 'wp-powersuite' ),
				esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=logs' ) ),
				esc_html__( 'Error Logs', 'wp-powersuite' ),
				esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&wpps-cs-safe-mode=1' ) ),
				esc_html__( 'Safe Mode', 'wp-powersuite' ),
				esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&action=add' ) ),
				esc_attr__( 'Disable all snippets temporarily', 'wp-powersuite' ),
				esc_html__( 'Add Snippet', 'wp-powersuite' )
			),
		]
	);
	?>

	<?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.', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet' ) ); ?>"><?php esc_html_e( 'Disable Safe Mode', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'All snippets are disabled site-wide.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ) ); ?>"><?php esc_html_e( 'Disable in settings', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'Snippets will not run on your site until you enable this module in PowerSuite settings.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite' ) ); ?>"><?php esc_html_e( 'Enable module', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( $total_count === 0 ) : ?>
		<div class="wpps-cs-empty-state">
			<div class="wpps-cs-empty-icon">
				<span class="dashicons dashicons-editor-code"></span>
			</div>
			<h3 class="wpps-cs-empty-title"><?php esc_html_e( 'No code snippets yet', 'wp-powersuite' ); ?></h3>
			<p class="wpps-cs-empty-desc"><?php esc_html_e( 'Create your first snippet to add custom code to your site\'s header, footer, or anywhere via shortcode.', 'wp-powersuite' ); ?></p>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&action=add' ) ); ?>" class="wpps-cs-empty-btn">
				<span class="dashicons dashicons-plus-alt"></span>
				<?php esc_html_e( 'Add Snippet', 'wp-powersuite' ); ?>
			</a>
		</div>
	<?php else : ?>
		<?php $list_table->views(); ?>

		<form method="post" id="wpps-cs-list-form">
			<?php wp_nonce_field( 'bulk-snippets' ); ?>
			<input type="hidden" name="page" value="powersuite-code-snippet" />
			<input type="hidden" name="status" value="<?php echo esc_attr( $status ); ?>" />
			<?php $list_table->search_box( __( 'Search snippets', 'wp-powersuite' ), 'snippet' ); ?>
			<?php $list_table->display(); ?>
		</form>

		<script>
		(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 listUrl = <?php echo wp_json_encode( admin_url( 'admin.php?page=powersuite-code-snippet' ) ); ?>;
			document.getElementById('wpps-cs-list-form')?.addEventListener('change', function(e) {
				var cb = e.target.closest('.wpps-cs-status-switch');
				if (!cb || cb.type !== 'checkbox') return;
				var id = cb.getAttribute('data-id');
				var label = cb.closest('.wpps-cs-status-toggle')?.querySelector('.wpps-cs-status-label');
				var activeText = <?php echo wp_json_encode( __( 'Active', 'wp-powersuite' ) ); ?>;
				var inactiveText = <?php echo wp_json_encode( __( 'Inactive', 'wp-powersuite' ) ); ?>;
				if (label) label.textContent = cb.checked ? activeText : inactiveText;
				var xhr = new XMLHttpRequest();
				xhr.open('POST', ajaxurl);
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xhr.onload = function() {
					try {
						var r = JSON.parse(xhr.responseText);
						if (r.success && label) {
							label.textContent = r.data.active ? activeText : inactiveText;
						} else {
							cb.checked = !cb.checked;
							if (label) label.textContent = cb.checked ? activeText : inactiveText;
							if (r.data && r.data.message) alert(r.data.message);
						}
					} catch (e) {
						cb.checked = !cb.checked;
						if (label) label.textContent = cb.checked ? activeText : inactiveText;
					}
				};
				xhr.onerror = function() {
					cb.checked = !cb.checked;
					if (label) label.textContent = cb.checked ? activeText : inactiveText;
				};
				xhr.send('action=wpps_cs_toggle_snippet&nonce=' + encodeURIComponent(nonce) + '&id=' + encodeURIComponent(id));
			});
			document.querySelectorAll('.wpps-cs-delete-link').forEach(function(link) {
				link.addEventListener('click', function(e) {
					e.preventDefault();
					if (!confirm(<?php echo wp_json_encode( __( 'Delete this snippet? This cannot be undone.', 'wp-powersuite' ) ); ?>)) return;
					var id = this.getAttribute('data-id');
					var row = this.closest('tr');
					var xhr = new XMLHttpRequest();
					xhr.open('POST', ajaxurl);
					xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					xhr.onload = function() {
						try {
							var r = JSON.parse(xhr.responseText);
							if (r.success) {
								window.location.href = listUrl;
							} else {
								alert(r.data && r.data.message ? r.data.message : <?php echo wp_json_encode( __( 'Could not delete snippet.', 'wp-powersuite' ) ); ?>);
							}
						} catch (err) {
							alert(<?php echo wp_json_encode( __( 'Request failed.', 'wp-powersuite' ) ); ?>);
						}
					};
					xhr.onerror = function() { alert(<?php echo wp_json_encode( __( 'Request failed.', 'wp-powersuite' ) ); ?>); };
					xhr.send('action=wpps_cs_delete_snippet&nonce=' + encodeURIComponent(nonce) + '&id=' + encodeURIComponent(id));
				});
			});

		})();
		</script>
	<?php endif; ?>
</div>
