<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Settings diagnostics use plugin-owned tables and template-scope variables.

if (! defined('ABSPATH')) exit; // Exit if accessed directly

$instant_popup_builder_db_act                 = get_option('instant_popup_builder_db_active');
$instant_popup_builder_db_debug              = get_option('instant_popup_builder_db_debug');
$instant_popup_builder_preserve_analytics    = get_option('instant_popup_builder_preserve_analytics', 'yes');
$instant_popup_builder_cleanup_options       = get_option('instant_popup_builder_cleanup_options', 'no');
// Post-publish behavior option (where to redirect after creating/updating a popup)
// Default is to go back to Popups Dashboard.
$instant_popup_builder_post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');

?>

<?php Instant_Popup_Builder_Admin::ipb_top_header(); ?>

<div class="wrap ipb-settings-wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e('Settings', 'instant-popup-builder'); ?></h1>
	<hr class="wp-header-end">

	<div class="ipb-settings-layout">
		<nav class="ipb-settings-nav" aria-label="<?php esc_attr_e('Settings sections', 'instant-popup-builder'); ?>">
			<ul class="ipb-settings-nav-list">
				<li class="ipb-nav-item active"><a href="#general" class="nav-tab nav-tab-active current" data-tab="general"><?php esc_html_e('General', 'instant-popup-builder'); ?></a></li>
				<li class="ipb-nav-item"><a href="#deactivation" class="nav-tab" data-tab="deactivation"><?php esc_html_e('Deactivation', 'instant-popup-builder'); ?></a></li>
				<li class="ipb-nav-item"><a href="#performance" class="nav-tab" data-tab="performance"><?php esc_html_e('Performance', 'instant-popup-builder'); ?></a></li>
				<li class="ipb-nav-item"><a href="#debug-system" class="nav-tab" data-tab="debug-system"><?php esc_html_e('Debug &amp; System Info', 'instant-popup-builder'); ?></a></li>
				<?php do_action('instant_popup_builder_settings_tabs'); ?>
			</ul>
		</nav>

		<div class="ipb-settings-main">
			<div class="ipb-settings-panel">
				<form action="" id="setting_popup" method="post">
					<?php wp_nonce_field('instant_popup_builder_setting_action', 'instant_popup_builder_setting'); ?>

					<!-- General Settings Tab -->
					<div id="general" class="ipb-tab-panel active">
						<header class="ipb-tab-panel-header">
							<h2 class="ipb-tab-panel-title"><?php esc_html_e('General Settings', 'instant-popup-builder'); ?></h2>
							<p class="description">
								<?php esc_html_e('Control what happens after you create or update a popup.', 'instant-popup-builder'); ?>
							</p>
						</header>

						<section class="ipb-settings-section">
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row">
											<label for="ipb_post_publish_behavior">
												<?php esc_html_e('After Publishing a Popup', 'instant-popup-builder'); ?>
											</label>
										</th>
										<td>
											<fieldset id="ipb_post_publish_behavior">
												<label class="ipb-radio-label">
													<input type="radio"
														name="ipb_post_publish_behavior"
														value="dashboard"
														<?php checked($instant_popup_builder_post_publish_behavior, 'dashboard'); ?>>
													<?php esc_html_e('Go back to Popups Dashboard', 'instant-popup-builder'); ?>
												</label>
												<br>
												<label class="ipb-radio-label">
													<input type="radio"
														name="ipb_post_publish_behavior"
														value="stay"
														<?php checked($instant_popup_builder_post_publish_behavior, 'stay'); ?>>
													<?php esc_html_e('Stay on the same page', 'instant-popup-builder'); ?>
												</label>
												<p class="description">
													<?php esc_html_e('This affects both new popups and updates made from the popup editor.', 'instant-popup-builder'); ?>
												</p>
											</fieldset>
										</td>
									</tr>
								</tbody>
							</table>
							<p class="submit">
								<?php submit_button(__('Save Changes', 'instant-popup-builder'), 'primary', 'database_deactivate', false); ?>
							</p>
						</section>
					</div>

					<!-- Deactivation Settings Tab -->
					<div id="deactivation" class="ipb-tab-panel">
						<header class="ipb-tab-panel-header">
							<h2 class="ipb-tab-panel-title"><?php esc_html_e('Deactivation Settings', 'instant-popup-builder'); ?></h2>
							<p class="description"><?php esc_html_e('Configure what happens when you deactivate the plugin.', 'instant-popup-builder'); ?></p>
						</header>

						<section class="ipb-settings-section">
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row"><label for="ipb_db_del"><?php esc_html_e('Delete All Popups', 'instant-popup-builder'); ?></label></th>
										<td>
											<label for="ipb_db_del" class="ipb-checkbox-label">
												<input type="checkbox" name="ipb_db_del" id="ipb_db_del" value="yes" <?php checked($instant_popup_builder_db_act, 'yes'); ?>>
												<?php esc_html_e('Permanently remove all popups and their data when deactivating the plugin.', 'instant-popup-builder'); ?>
											</label>
										</td>
									</tr>
									<tr>
										<th scope="row"><label for="ipb_preserve_analytics"><?php esc_html_e('Preserve Analytics', 'instant-popup-builder'); ?></label></th>
										<td>
											<label for="ipb_preserve_analytics" class="ipb-checkbox-label">
												<input type="checkbox" name="ipb_preserve_analytics" id="ipb_preserve_analytics" value="yes" <?php checked($instant_popup_builder_preserve_analytics, 'yes'); ?>>
												<?php esc_html_e('Keep view counts and analytics data for historical reporting.', 'instant-popup-builder'); ?>
											</label>
										</td>
									</tr>
									<tr>
										<th scope="row"><label for="ipb_cleanup_options"><?php esc_html_e('Clean Plugin Options', 'instant-popup-builder'); ?></label></th>
										<td>
											<label for="ipb_cleanup_options" class="ipb-checkbox-label">
												<input type="checkbox" name="ipb_cleanup_options" id="ipb_cleanup_options" value="yes" <?php checked($instant_popup_builder_cleanup_options, 'yes'); ?>>
												<?php esc_html_e('Remove all plugin settings and configurations from database.', 'instant-popup-builder'); ?>
											</label>
										</td>
									</tr>
								</tbody>
							</table>
							<p class="submit">
								<?php submit_button(__('Save Changes', 'instant-popup-builder'), 'primary', 'database_deactivate', false); ?>
							</p>
						</section>
					</div>

					<!-- Performance Tab -->
					<div id="performance" class="ipb-tab-panel">
						<header class="ipb-tab-panel-header">
							<h2 class="ipb-tab-panel-title"><?php esc_html_e('Performance', 'instant-popup-builder'); ?></h2>
							<p class="description"><?php esc_html_e('Maintenance tools and performance statistics.', 'instant-popup-builder'); ?></p>
						</header>

						<!-- Maintenance / Destructive actions - visually separated -->
						<div class="ipb-settings-maintenance notice notice-warning inline">
							<h3 class="ipb-settings-section-title"><?php esc_html_e('Repair & Re-run Activation', 'instant-popup-builder'); ?></h3>
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row"><?php esc_html_e('Re-run activation routines', 'instant-popup-builder'); ?></th>
										<td>
											<p class="description"><?php esc_html_e('This will re-apply database upgrades, ensure the subscription settings table exists, and create default subscription campaign/options if missing.', 'instant-popup-builder'); ?></p>
											<p class="ipb-button-row">
												<button type="button" id="ipb-rerun-activation" class="button button-secondary">
													<?php esc_html_e('Run Repair', 'instant-popup-builder'); ?>
												</button>
											</p>
											<div id="ipb-rerun-activation-result" class="ipb-inline-result" style="display:none;"></div>
										</td>
									</tr>
								</tbody>
							</table>

							<h3 class="ipb-settings-section-title"><?php esc_html_e('Factory Reset', 'instant-popup-builder'); ?></h3>
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row"><?php esc_html_e('Full reset to fresh install', 'instant-popup-builder'); ?></th>
										<td>
											<p class="description"><?php esc_html_e('Drops plugin database tables and deletes plugin options. Then re-runs activation to recreate schemas and defaults. This action is irreversible. Consider taking a backup first.', 'instant-popup-builder'); ?></p>
											<p class="ipb-button-row">
												<button type="button" id="ipb-factory-reset" class="button button-secondary">
													<?php esc_html_e('Factory Reset', 'instant-popup-builder'); ?>
												</button>
											</p>
											<div id="ipb-factory-reset-result" class="ipb-inline-result" style="display:none;"></div>
										</td>
									</tr>
								</tbody>
							</table>
						</div>

						<section class="ipb-settings-section ipb-settings-section-divider">
							<h3 class="ipb-settings-section-title"><?php esc_html_e('Performance Statistics', 'instant-popup-builder'); ?></h3>
							<table class="widefat striped ipb-stats-table">
								<tbody>
									<tr>
										<td class="ipb-stats-label"><?php esc_html_e('Total Popups', 'instant-popup-builder'); ?></td>
										<td class="ipb-stats-value"><?php
											global $wpdb;
											$instant_popup_builder_table_name = $wpdb->prefix . 'instant_popup_builder';
											$escaped_table_name = esc_sql($instant_popup_builder_table_name);
											$instant_popup_builder_active_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$escaped_table_name}` WHERE status = 'publish'");
											echo esc_html($instant_popup_builder_active_count);
										?></td>
									</tr>
									<tr>
										<td class="ipb-stats-label"><?php esc_html_e('Active Popups', 'instant-popup-builder'); ?></td>
										<td class="ipb-stats-value"><?php
											$instant_popup_builder_table_name = $wpdb->prefix . 'instant_popup_builder';
											$escaped_table_name = esc_sql($instant_popup_builder_table_name);
											$instant_popup_builder_active_count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `{$escaped_table_name}` WHERE class = %s", 'yes'));
											echo esc_html($instant_popup_builder_active_count);
										?></td>
									</tr>
									<tr>
										<td class="ipb-stats-label"><?php esc_html_e('Database Size', 'instant-popup-builder'); ?></td>
										<td class="ipb-stats-value" id="db-size">&mdash;</td>
									</tr>
								</tbody>
							</table>
						</section>

						<?php
						$instant_popup_builder_analytics_active = get_option('analytics_license_active') === 'yes' && class_exists('Instant_Popup_Analytics_Advanced');
						if ($instant_popup_builder_analytics_active) :
							$instant_popup_builder_dashboard_widget_enabled = get_option('instant_popup_analytics_dashboard_widget', 'yes');
						?>
						<section class="ipb-settings-section ipb-settings-section-divider">
							<h3 class="ipb-settings-section-title"><?php esc_html_e('Analytics Dashboard Widget', 'instant-popup-builder'); ?></h3>
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row"><label for="ipb_dashboard_widget"><?php esc_html_e('Enable Dashboard Widget', 'instant-popup-builder'); ?></label></th>
										<td>
											<label for="ipb_dashboard_widget" class="ipb-checkbox-label">
												<input type="checkbox" name="ipb_dashboard_widget" id="ipb_dashboard_widget" value="yes" <?php checked($instant_popup_builder_dashboard_widget_enabled, 'yes'); ?>>
												<?php esc_html_e('Show popup analytics widget on WordPress admin dashboard with key metrics.', 'instant-popup-builder'); ?>
											</label>
										</td>
									</tr>
								</tbody>
							</table>
						</section>
						<?php endif; ?>

						<p class="submit">
							<?php submit_button(__('Save Changes', 'instant-popup-builder'), 'primary', 'database_deactivate', false); ?>
						</p>
					</div>

					<!-- Debug & System Info Tab -->
					<div id="debug-system" class="ipb-tab-panel">
						<header class="ipb-tab-panel-header">
							<h2 class="ipb-tab-panel-title"><?php esc_html_e('Debug & System Info', 'instant-popup-builder'); ?></h2>
							<p class="description"><?php esc_html_e('Debug mode, system information, and log viewer.', 'instant-popup-builder'); ?></p>
						</header>

						<section class="ipb-settings-section">
							<h3 class="ipb-settings-section-title"><?php esc_html_e('Debug Settings', 'instant-popup-builder'); ?></h3>
							<table class="form-table" role="presentation">
								<tbody>
									<tr>
										<th scope="row"><label for="ipb_debug_mode"><?php esc_html_e('Enable Debug Mode', 'instant-popup-builder'); ?></label></th>
										<td>
											<label for="ipb_debug_mode" class="ipb-checkbox-label">
												<input type="checkbox" name="ipb_debug_mode" id="ipb_debug_mode" value="yes" <?php checked($instant_popup_builder_db_debug, 'yes'); ?>>
												<?php esc_html_e('Log plugin activities and errors for troubleshooting.', 'instant-popup-builder'); ?>
											</label>
										</td>
									</tr>
								</tbody>
							</table>
						</section>

						<section class="ipb-settings-section ipb-settings-section-divider ipb-settings-section-system-info">
							<div class="ipb-system-info-header">
								<h3 class="ipb-settings-section-title"><?php esc_html_e('System Information', 'instant-popup-builder'); ?></h3>
								<button type="button" class="button button-secondary button-small" id="copy-system-info"><?php esc_html_e('Copy to Clipboard', 'instant-popup-builder'); ?></button>
							</div>
							<div class="ipb-system-info-box">
								<textarea id="system-info-textarea" class="large-text code" rows="16" readonly><?php
$instant_popup_builder_system_info = "=== INSTANT POPUP BUILDER - SYSTEM INFORMATION ===\n";
$instant_popup_builder_system_info .= "Generated: " . current_time('mysql') . "\n\n";
$instant_popup_builder_system_info .= "SITE & ENVIRONMENT INFO\n";
$instant_popup_builder_system_info .= str_repeat("=", 50) . "\n";
$instant_popup_builder_system_info .= "WordPress Version: " . get_bloginfo('version') . "\n";
$instant_popup_builder_system_info .= "Site URL: " . get_bloginfo('url') . "\n";
$instant_popup_builder_system_info .= "Admin URL: " . admin_url() . "\n";
$instant_popup_builder_system_info .= "Multisite: " . (is_multisite() ? 'Yes' : 'No') . "\n";
$instant_popup_builder_system_info .= "Language: " . get_bloginfo('language') . "\n";
$instant_popup_builder_system_info .= "Timezone: " . get_option('timezone_string', 'UTC') . "\n";
$instant_popup_builder_system_info .= "Memory Limit: " . ini_get('memory_limit') . "\n";
$instant_popup_builder_system_info .= "Max Execution Time: " . ini_get('max_execution_time') . "s\n";
$instant_popup_builder_system_info .= "PHP Version: " . phpversion() . "\n";
global $wpdb;
$instant_popup_builder_mysql_version = $wpdb->get_var("SELECT VERSION()");
$instant_popup_builder_system_info .= "MySQL/MariaDB Version: " . $instant_popup_builder_mysql_version . "\n";
$instant_popup_builder_system_info .= "Web Server: " . ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '' ) . "\n";
$instant_popup_builder_system_info .= "Operating System: " . PHP_OS . "\n\n";
$instant_popup_builder_system_info .= "THEME INFO\n";
$instant_popup_builder_system_info .= str_repeat("=", 50) . "\n";
$instant_popup_builder_current_theme = wp_get_theme();
$instant_popup_builder_system_info .= "Active Theme: " . $instant_popup_builder_current_theme->get('Name') . "\n";
$instant_popup_builder_system_info .= "Theme Version: " . $instant_popup_builder_current_theme->get('Version') . "\n";
$instant_popup_builder_system_info .= "Theme Author: " . $instant_popup_builder_current_theme->get('Author') . "\n\n";
$instant_popup_builder_system_info .= "PLUGINS INFO\n";
$instant_popup_builder_system_info .= str_repeat("=", 50) . "\n";
$instant_popup_builder_active_plugins = get_option('active_plugins');
$instant_popup_builder_all_plugins = get_plugins();
foreach ($instant_popup_builder_active_plugins as $instant_popup_builder_plugin_path) {
	if (isset($instant_popup_builder_all_plugins[$instant_popup_builder_plugin_path])) {
		$instant_popup_builder_plugin = $instant_popup_builder_all_plugins[$instant_popup_builder_plugin_path];
		$instant_popup_builder_system_info .= "Plugin: " . $instant_popup_builder_plugin['Name'] . "\n";
		$instant_popup_builder_system_info .= "  Version: " . $instant_popup_builder_plugin['Version'] . "\n";
		$instant_popup_builder_system_info .= "  Author: " . $instant_popup_builder_plugin['Author'] . "\n";
		$instant_popup_builder_system_info .= "  File: " . $instant_popup_builder_plugin_path . "\n\n";
	}
}
$instant_popup_builder_system_info .= "INSTANT POPUP BUILDER INFO\n";
$instant_popup_builder_system_info .= str_repeat("=", 50) . "\n";
$instant_popup_builder_popup_table = $wpdb->prefix . 'instant_popup_builder';
$escaped_popup_table = esc_sql($instant_popup_builder_popup_table);
$instant_popup_builder_total_popups = $wpdb->get_var("SELECT COUNT(*) FROM `{$escaped_popup_table}`");
$instant_popup_builder_active_popups = $wpdb->get_var("SELECT COUNT(*) FROM `{$escaped_popup_table}` WHERE class = 'yes'");
$instant_popup_builder_published_popups = $wpdb->get_var("SELECT COUNT(*) FROM `{$escaped_popup_table}` WHERE status = 'publish'");
$instant_popup_builder_system_info .= "Total Popups: " . ($instant_popup_builder_total_popups ?? 0) . "\n";
$instant_popup_builder_system_info .= "Active Popups: " . ($instant_popup_builder_active_popups ?? 0) . "\n";
$instant_popup_builder_system_info .= "Published Popups: " . ($instant_popup_builder_published_popups ?? 0) . "\n";
$instant_popup_builder_db_size_query = $wpdb->get_var($wpdb->prepare(
	"SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'DB Size in MB' FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
	DB_NAME,
	$instant_popup_builder_popup_table
));
$instant_popup_builder_system_info .= "Database Size: " . ($instant_popup_builder_db_size_query ? $instant_popup_builder_db_size_query . ' MB' : 'N/A') . "\n\n";
$instant_popup_builder_system_info .= "WORDPRESS CONFIGURATION\n";
$instant_popup_builder_system_info .= str_repeat("=", 50) . "\n";
$instant_popup_builder_system_info .= "WP_DEBUG: " . (defined('WP_DEBUG') && WP_DEBUG ? 'true' : 'false') . "\n";
$instant_popup_builder_system_info .= "WP_DEBUG_LOG: " . (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG ? 'true' : 'false') . "\n";
$instant_popup_builder_system_info .= "WP_DEBUG_DISPLAY: " . (defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY ? 'true' : 'false') . "\n";
$instant_popup_builder_system_info .= "SCRIPT_DEBUG: " . (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? 'true' : 'false') . "\n";
$instant_popup_builder_system_info .= "WP_MEMORY_LIMIT: " . (defined('WP_MEMORY_LIMIT') ? WP_MEMORY_LIMIT : 'Not defined') . "\n";
$instant_popup_builder_system_info .= "WP_MAX_MEMORY_LIMIT: " . (defined('WP_MAX_MEMORY_LIMIT') ? WP_MAX_MEMORY_LIMIT : 'Not defined') . "\n\n";
echo esc_textarea($instant_popup_builder_system_info);
?></textarea>
							</div>
						</section>

						<?php if ($instant_popup_builder_db_debug == 'yes') : ?>
						<section class="ipb-settings-section ipb-settings-section-divider">
							<h3 class="ipb-settings-section-title"><?php esc_html_e('Debug Log', 'instant-popup-builder'); ?></h3>
							<p class="ipb-button-row">
								<button type="button" class="button button-small" id="refresh-log"><?php esc_html_e('Refresh', 'instant-popup-builder'); ?></button>
							</p>
							<div class="ipb-log-viewer">
								<?php
								if (current_user_can('manage_options')) {
									$instant_popup_builder_debug_log_path = WP_CONTENT_DIR . '/debug.log';
									if (file_exists($instant_popup_builder_debug_log_path)) {
										$instant_popup_builder_debug_content = file_get_contents($instant_popup_builder_debug_log_path);
										if (!empty($instant_popup_builder_debug_content)) {
											$safe_debug_content = (string) ( $instant_popup_builder_debug_content ?? '' );
											$instant_popup_builder_lines = explode("\n", $safe_debug_content);
											$instant_popup_builder_last_lines = array_slice($instant_popup_builder_lines, -20);
											echo '<pre class="code">' . esc_html(implode("\n", is_array($instant_popup_builder_last_lines) ? $instant_popup_builder_last_lines : [])) . '</pre>';
										} else {
											echo '<p class="description">' . esc_html__('Debug log is empty.', 'instant-popup-builder') . '</p>';
										}
									} else {
										echo '<p class="description">' . esc_html__('No debug log file found.', 'instant-popup-builder') . '</p>';
									}
								}
								?>
							</div>
						</section>
						<?php endif; ?>

						<p class="submit">
							<?php submit_button(__('Save Changes', 'instant-popup-builder'), 'primary', 'database_deactivate', false); ?>
						</p>
					</div>

					<?php do_action('instant_popup_builder_settings_content'); ?>
				</form>
			</div>
		</div>
	</div>
</div>

<script>
jQuery(document).ready(function($) {
	$('.ipb-settings-nav a[data-tab]').addClass('nav-tab');

	// Tab switching via nav links
	$('.ipb-settings-nav a[data-tab], .ipb-nav-item a[data-tab], .nav-item a[data-tab]').on('click', function(e) {
		e.preventDefault();
		var tabId = $(this).data('tab');
		$('.ipb-nav-item, .nav-item').removeClass('active');
		$(this).closest('.ipb-nav-item, .nav-item').addClass('active');
		$('.ipb-settings-nav a').removeClass('current nav-tab-active');
		$(this).addClass('current nav-tab-active');
		$('.ipb-tab-panel').removeClass('active');
		$('#' + tabId).addClass('active');
	});

	// Database size on load
	if ($('#db-size').length) {
		$('#db-size').text('Loading...');
		$.ajax({
			url: instnat_ajax_handler.ajaxurl,
			type: 'POST',
			data: {
				action: 'ipb_calculate_db_size',
				nonce: instnat_ajax_handler.ipb_admin_nonce
			},
			success: function(response) {
				if (response.success) {
					$('#db-size').text(response.data.size);
				} else {
					$('#db-size').text('N/A');
				}
			},
			error: function() {
				$('#db-size').text('N/A');
			}
		});
	}

	setInterval(function() {
		if ($('#db-size').length && $('#db-size').closest('.ipb-tab-panel').hasClass('active')) {
			$.ajax({
				url: instnat_ajax_handler.ajaxurl,
				type: 'POST',
				data: {
					action: 'ipb_calculate_db_size',
					nonce: instnat_ajax_handler.ipb_admin_nonce
				},
				success: function(response) {
					if (response.success) {
						$('#db-size').text(response.data.size);
					}
				}
			});
		}
	}, 30000);

	$('#ipb-rerun-activation').on('click', function() {
		var $btn = $(this);
		var $out = $('#ipb-rerun-activation-result');
		$btn.prop('disabled', true).text('<?php echo esc_js(__('Running...', 'instant-popup-builder')); ?>');
		$out.hide().removeClass('success error');
		$.ajax({
			url: instnat_ajax_handler.ajaxurl,
			type: 'POST',
			data: {
				action: 'ipb_rerun_activation',
				nonce: instnat_ajax_handler.ipb_admin_nonce
			},
			success: function(response) {
				if (response && response.success) {
					$out.addClass('success').html('<strong><?php echo esc_js(__('Completed:', 'instant-popup-builder')); ?></strong> ' + (response.data.results.upgrade_database ? 'yes' : 'no') + ', ' + (response.data.results.create_subscription_table ? 'yes' : 'no') + ', ' + (response.data.results.ensure_global_subscription_options ? 'yes' : 'no') + ', ' + (response.data.results.ensure_default_subscription_campaign ? 'yes' : 'no')).show();
				} else {
					$out.addClass('error').text('<?php echo esc_js(__('Failed to run repair.', 'instant-popup-builder')); ?>').show();
				}
			},
			error: function() {
				$out.addClass('error').text('<?php echo esc_js(__('AJAX error while running repair.', 'instant-popup-builder')); ?>').show();
			},
			complete: function() {
				$btn.prop('disabled', false).text('<?php echo esc_js(__('Run Repair', 'instant-popup-builder')); ?>');
			}
		});
	});

	$('#ipb-factory-reset').on('click', function() {
		if (!confirm('<?php echo esc_js(__('This will delete ALL Instant Popup Builder data (tables and options) and reinstall. This cannot be undone. Proceed?', 'instant-popup-builder')); ?>')) {
			return;
		}
		var $btn = $(this);
		var $out = $('#ipb-factory-reset-result');
		$btn.prop('disabled', true).text('<?php echo esc_js(__('Resetting...', 'instant-popup-builder')); ?>');
		$out.hide().removeClass('success error');
		$.ajax({
			url: instnat_ajax_handler.ajaxurl,
			type: 'POST',
			data: {
				action: 'ipb_factory_reset',
				nonce: instnat_ajax_handler.ipb_admin_nonce
			},
			success: function(response) {
				if (response && response.success) {
					var msg = '<strong><?php echo esc_js(__('Factory Reset Completed.', 'instant-popup-builder')); ?></strong><br>' + (response.data.dropped_tables && response.data.dropped_tables.length ? response.data.dropped_tables.join(', ') : 'none') + '<br>' + (response.data.deleted_options && response.data.deleted_options.length ? response.data.deleted_options.join(', ') : 'none');
					$out.addClass('success').html(msg).show();
				} else {
					$out.addClass('error').text('<?php echo esc_js(__('Factory reset failed.', 'instant-popup-builder')); ?>').show();
				}
			},
			error: function() {
				$out.addClass('error').text('<?php echo esc_js(__('AJAX error while performing factory reset.', 'instant-popup-builder')); ?>').show();
			},
			complete: function() {
				$btn.prop('disabled', false).text('<?php echo esc_js(__('Factory Reset', 'instant-popup-builder')); ?>');
			}
		});
	});

	$('#copy-system-info').on('click', function() {
		var textarea = document.getElementById('system-info-textarea');
		var button = $(this);
		var originalText = button.text();
		textarea.select();
		textarea.setSelectionRange(0, 99999);
		try {
			navigator.clipboard.writeText(textarea.value).then(function() {
				button.text('<?php echo esc_js(__('Copied!', 'instant-popup-builder')); ?>');
				setTimeout(function() { button.text(originalText); }, 2000);
			}).catch(function() {
				if (document.execCommand('copy')) {
					button.text('<?php echo esc_js(__('Copied!', 'instant-popup-builder')); ?>');
					setTimeout(function() { button.text(originalText); }, 2000);
				} else {
					button.text('<?php echo esc_js(__('Failed to copy', 'instant-popup-builder')); ?>');
					setTimeout(function() { button.text(originalText); }, 2000);
				}
			});
		} catch (err) {
			if (document.execCommand('copy')) {
				button.text('<?php echo esc_js(__('Copied!', 'instant-popup-builder')); ?>');
				setTimeout(function() { button.text(originalText); }, 2000);
			} else {
				button.text('<?php echo esc_js(__('Failed to copy', 'instant-popup-builder')); ?>');
				setTimeout(function() { button.text(originalText); }, 2000);
			}
		}
	});
});
</script>
