<?php

use WP_PowerSuite\Core\ModuleManager;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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 ?? 'track-404s' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( '404 Error Log requires an active license. Activate your license to log 404 hits and review error reports.', '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 ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'track-404s';
}

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

$defaults = [
	'exclude_bots'        => true,
	'track_referrer'      => true,
	'ignore_patterns'     => '.env, .git, wp-config, favicon.ico, apple-touch-icon, xmlrpc, wp-login.php, robots.txt, wp-sitemap, /feed, phpmyadmin, mysql, adminer',
	'retention_days'      => 30,
	'log_query_strings'   => false,
];
$settings = array_merge( $defaults, $settings );

$exclude_bots        = ! empty( $settings['exclude_bots'] );
$track_referrer      = ! empty( $settings['track_referrer'] );
$log_query_strings   = ! empty( $settings['log_query_strings'] );
$ignore_patterns = isset( $settings['ignore_patterns'] ) ? ( is_array( $settings['ignore_patterns'] ) ? implode( ', ', $settings['ignore_patterns'] ) : $settings['ignore_patterns'] ) : $defaults['ignore_patterns'];
$retention_days  = isset( $settings['retention_days'] ) ? max( 7, (int) $settings['retention_days'] ) : 30;

$date_format  = get_option( 'date_format', 'Y-m-d' );
$time_format  = get_option( 'time_format', 'H:i' );
$datetime_fmt = $date_format . ' ' . $time_format;

$dashboard   = [];
$export_url  = '';
$admin_nonce = '';
$ajax_url    = admin_url( 'admin-ajax.php' );
$module_instance = ModuleManager::getInstance()->getModule( 'track-404s' );
if ( $module_instance instanceof \Track404s\Module ) {
	$dashboard = $module_instance->getDashboardData(
		\Track404s\Module::DEFAULT_FILTER,
		[
			'include_top'    => false,
			'include_recent' => false,
		]
	);
	$export_url  = add_query_arg(
		[ 'action' => 'wpps_track_404s_export', 'nonce' => $dashboard['export_nonce'] ?? '', 'filter' => \Track404s\Module::DEFAULT_FILTER ],
		$ajax_url
	);
	$admin_nonce = $dashboard['admin_nonce'] ?? '';
}
?>

<div class="wp-powersuite-module-settings wpps-track-404s-modal" data-ajax-url="<?php echo esc_attr( $ajax_url ); ?>" data-admin-nonce="<?php echo esc_attr( $admin_nonce ); ?>" data-export-nonce="<?php echo esc_attr( $dashboard['export_nonce'] ?? '' ); ?>" data-datetime-fmt="<?php echo esc_attr( $datetime_fmt ); ?>">
	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_exclude_bots"><?php esc_html_e( 'Exclude Bots', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle">
							<input type="checkbox" id="<?php echo esc_attr( $module_id ); ?>_exclude_bots" name="exclude_bots" value="1" <?php checked( $exclude_bots ); ?> class="wp-powersuite-advanced-setting" data-setting-key="exclude_bots" />
							<span class="wp-powersuite-toggle__slider"></span>
						</label>
						<p class="description"><?php esc_html_e( 'Filter out crawlers and automated scanners (Googlebot, Bingbot, SEO tools, etc.) so logs focus on real visitor issues.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_track_referrer"><?php esc_html_e( 'Track Referrer', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle">
							<input type="checkbox" id="<?php echo esc_attr( $module_id ); ?>_track_referrer" name="track_referrer" value="1" <?php checked( $track_referrer ); ?> class="wp-powersuite-advanced-setting" data-setting-key="track_referrer" />
							<span class="wp-powersuite-toggle__slider"></span>
						</label>
						<p class="description"><?php esc_html_e( 'Record where visitors came from (referrer) for each 404.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_log_query_strings"><?php esc_html_e( 'Log Query Strings', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<label class="wp-powersuite-toggle">
							<input type="checkbox" id="<?php echo esc_attr( $module_id ); ?>_log_query_strings" name="log_query_strings" value="1" <?php checked( $log_query_strings ); ?> class="wp-powersuite-advanced-setting" data-setting-key="log_query_strings" />
							<span class="wp-powersuite-toggle__slider"></span>
						</label>
						<p class="description"><?php esc_html_e( 'Include URL query strings in logged paths (e.g. ?utm_source=email). Off by default to keep URLs grouped.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_ignore_patterns"><?php esc_html_e( 'Ignore Patterns', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<textarea id="<?php echo esc_attr( $module_id ); ?>_ignore_patterns" name="ignore_patterns" rows="4" class="large-text code wp-powersuite-advanced-setting" data-setting-key="ignore_patterns" placeholder="<?php esc_attr_e( '.env, .git, /test/', 'wp-powersuite' ); ?>"><?php echo esc_textarea( $ignore_patterns ); ?></textarea>
						<p class="description"><?php esc_html_e( 'Comma-separated URL patterns to skip. Any URL containing a pattern will not be logged (e.g. .env, favicon.ico, /staging/).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_retention_days"><?php esc_html_e( 'Retention Days', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="number" id="<?php echo esc_attr( $module_id ); ?>_retention_days" name="retention_days" value="<?php echo esc_attr( $retention_days ); ?>" class="small-text wp-powersuite-advanced-setting" data-setting-key="retention_days" data-wpps-min="7" data-wpps-max="99999" data-wpps-step="1" min="7" />
						<p class="description"><?php esc_html_e( 'Auto-delete logs older than this many days (minimum 7). Cleanup runs daily.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<!-- 2. Description -->
	<p class="description wpps-404-description">
		<?php esc_html_e( 'Track missing URLs, see hit counts, and spot what still needs a fix versus what 404 Redirect already handles.', 'wp-powersuite' ); ?>
	</p>

	<!-- 3. Stats -->
	<div class="wpps-404-stats">
		<div class="wpps-404-stat-card">
			<span class="wpps-404-stat-value"><?php echo esc_html( number_format_i18n( $dashboard['total_hits'] ?? 0 ) ); ?></span>
			<span class="wpps-404-stat-label"><?php esc_html_e( 'Total Hits', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-404-stat-card">
			<span class="wpps-404-stat-value"><?php echo esc_html( number_format_i18n( $dashboard['unique_urls'] ?? 0 ) ); ?></span>
			<span class="wpps-404-stat-label"><?php esc_html_e( 'Unique URLs', 'wp-powersuite' ); ?></span>
		</div>
		<div class="wpps-404-stat-card">
			<span class="wpps-404-stat-value"><?php echo esc_html( number_format_i18n( $dashboard['new_today'] ?? 0 ) ); ?></span>
			<span class="wpps-404-stat-label"><?php esc_html_e( 'New Today', 'wp-powersuite' ); ?></span>
		</div>
	</div>

	<!-- 4. View log toggle -->
	<p class="wpps-404-view-log-wrap">
		<button type="button" class="button wpps-404-view-log-btn" aria-expanded="false">
			<span class="wpps-404-view-log-text"><?php esc_html_e( 'View log', 'wp-powersuite' ); ?></span>
			<span class="wpps-404-hide-log-text" style="display: none;"><?php esc_html_e( 'Hide log', 'wp-powersuite' ); ?></span>
		</button>
	</p>

	<!-- 5. Log section (hidden until "View log" clicked) -->
	<div class="wpps-404-log-section" style="display: none;">
		<div class="wpps-404-toolbar">
			<div class="wpps-404-filter-wrap">
				<div class="wpps-404-filter-group">
					<button type="button" class="wpps-404-filter-btn active" data-filter="redirected_only"><?php esc_html_e( 'Auto-redirected', 'wp-powersuite' ); ?></button>
					<button type="button" class="wpps-404-filter-btn" data-filter="unresolved"><?php esc_html_e( 'Unresolved', 'wp-powersuite' ); ?></button>
					<button type="button" class="wpps-404-filter-btn" data-filter="all"><?php esc_html_e( 'All 404s', 'wp-powersuite' ); ?></button>
				</div>
				<p class="description wpps-404-filter-hint" id="wpps-404-filter-hint"><?php esc_html_e( 'Page URLs sent somewhere by 404 Redirect (see destination in the Auto redirect column).', 'wp-powersuite' ); ?></p>
			</div>
			<input type="search" class="wpps-404-search" placeholder="<?php esc_attr_e( 'Search URLs or referrers...', 'wp-powersuite' ); ?>" style="min-width: 200px;">
			<a href="<?php echo esc_url( $export_url ); ?>" class="button button-primary wpps-404-export-btn" target="_blank" rel="noopener">
				<span class="dashicons dashicons-download" style="vertical-align: middle; margin-right: 4px;"></span>
				<?php esc_html_e( 'Export CSV', 'wp-powersuite' ); ?>
			</a>
			<button type="button" class="button wpps-404-clear-all"><?php esc_html_e( 'Clear All', 'wp-powersuite' ); ?></button>
		</div>

		<h4 class="wpps-404-section-title"><?php esc_html_e( 'Latest 404s', 'wp-powersuite' ); ?></h4>
		<div class="wpps-404-recent-wrap">
			<table class="wpps-404-table widefat striped wpps-404-recent-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'URL', 'wp-powersuite' ); ?></th>
						<th><?php esc_html_e( 'Auto redirect', 'wp-powersuite' ); ?></th>
						<th class="num"><?php esc_html_e( 'Hits', 'wp-powersuite' ); ?></th>
						<th><?php esc_html_e( 'Last Seen', 'wp-powersuite' ); ?></th>
						<th class="wpps-404-actions-col"></th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
			<p class="wpps-404-loading" style="display: none;"><?php esc_html_e( 'Loading...', 'wp-powersuite' ); ?></p>
			<p class="wpps-404-empty" style="display: none;" data-empty-unresolved="<?php esc_attr_e( 'No unresolved page 404s. Every logged page URL was auto-redirected or nothing has been logged yet.', 'wp-powersuite' ); ?>" data-empty-redirected="<?php esc_attr_e( 'No auto-redirected page 404s yet. Enable 404 Redirect or wait for visitors to hit missing pages.', 'wp-powersuite' ); ?>" data-empty-all="<?php esc_attr_e( 'No 404s logged yet.', 'wp-powersuite' ); ?>"><?php esc_html_e( 'No 404s logged yet.', 'wp-powersuite' ); ?></p>
			<nav class="wpps-404-pagination" aria-label="<?php esc_attr_e( 'Log pagination', 'wp-powersuite' ); ?>"></nav>
		</div>

		<h4 class="wpps-404-section-title"><?php esc_html_e( 'Top 404s', 'wp-powersuite' ); ?></h4>
		<div class="wpps-404-top-wrap">
			<table class="wpps-404-table widefat striped wpps-404-top-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'URL', 'wp-powersuite' ); ?></th>
						<th><?php esc_html_e( 'Auto redirect', 'wp-powersuite' ); ?></th>
						<th class="num"><?php esc_html_e( 'Hits', 'wp-powersuite' ); ?></th>
						<th><?php esc_html_e( 'Last Seen', 'wp-powersuite' ); ?></th>
						<th class="wpps-404-actions-col"></th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
			<p class="wpps-404-top-empty" style="display: none;" data-empty-unresolved="<?php esc_attr_e( 'No unresolved page 404s in this view.', 'wp-powersuite' ); ?>" data-empty-redirected="<?php esc_attr_e( 'No auto-redirected page 404s in this view.', 'wp-powersuite' ); ?>" data-empty-all="<?php esc_attr_e( 'No 404s logged yet.', 'wp-powersuite' ); ?>"><?php esc_html_e( 'No 404s logged yet. When visitors hit missing pages, they will appear here.', 'wp-powersuite' ); ?></p>
		</div>
	</div>
</div>

<script>
(function() {
	var container = document.querySelector('.wpps-track-404s-modal');
	if (!container) return;
	var btn = container.querySelector('.wpps-404-view-log-btn');
	var section = container.querySelector('.wpps-404-log-section');
	var viewText = container.querySelector('.wpps-404-view-log-text');
	var hideText = container.querySelector('.wpps-404-hide-log-text');
	var ajaxUrl = container.dataset.ajaxUrl || '';
	var adminNonce = container.dataset.adminNonce || '';
	var exportNonce = container.dataset.exportNonce || '';
	var datetimeFmt = container.dataset.datetimeFmt || 'Y-m-d H:i';
	var filter = 'redirected_only';
	var search = '';
	var currentPage = 0;
	var totalLogs = 0;
	var limit = 50;
	var filterHint = section ? section.querySelector('#wpps-404-filter-hint') : null;
	var filterHints = {
		unresolved: <?php echo wp_json_encode( __( 'Page URLs with no auto-redirect recorded — good candidates for fixes or Redirect Manager rules.', 'wp-powersuite' ) ); ?>,
		redirected_only: <?php echo wp_json_encode( __( 'Page URLs sent somewhere by 404 Redirect (see destination in the Auto redirect column).', 'wp-powersuite' ) ); ?>,
		all: <?php echo wp_json_encode( __( 'Every logged 404, including assets like favicon, CSS, and images.', 'wp-powersuite' ) ); ?>
	};
	var emptyMessages = {
		unresolved: <?php echo wp_json_encode( __( 'No unresolved page 404s. Every logged page URL was auto-redirected or nothing has been logged yet.', 'wp-powersuite' ) ); ?>,
		redirected_only: <?php echo wp_json_encode( __( 'No auto-redirected page 404s yet. Enable 404 Redirect or wait for visitors to hit missing pages.', 'wp-powersuite' ) ); ?>,
		all: <?php echo wp_json_encode( __( 'No 404s logged yet.', 'wp-powersuite' ) ); ?>
	};

	function updateFilterHint() {
		if (filterHint) {
			filterHint.textContent = filterHints[filter] || filterHints.redirected_only;
		}
	}

	function emptyMessageFor(el) {
		if (!el) return '';
		var key = 'data-empty-' + (filter === 'redirected_only' ? 'redirected' : filter === 'all' ? 'all' : 'unresolved');
		return el.getAttribute(key) || emptyMessages[filter] || emptyMessages.redirected_only;
	}

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

	function formatDate(str) {
		if (!str) return '';
		var d = new Date(str);
		return isNaN(d.getTime()) ? str : d.toLocaleString();
	}

	function renderRedirectCell(row) {
		if (row.redirect_to) {
			return '<span class="wpps-404-redirect-target">' + esc(row.redirect_to) + '</span>';
		}
		return '<span class="wpps-404-redirect-empty">&mdash;</span>';
	}

	function renderLogRow(row) {
		return '<tr><td><code>' + esc(row.url) + '</code></td><td>' + renderRedirectCell(row) + '</td><td class="num">' + (row.hit_count || 0) + '</td><td>' + formatDate(row.last_seen) + '</td><td><button type="button" class="wpps-404-delete-btn" data-id="' + (row.id || '') + '">Delete</button></td></tr>';
	}

	function updateExportUrl() {
		var a = section.querySelector('.wpps-404-export-btn');
		if (a) a.href = ajaxUrl + '?action=wpps_track_404s_export&nonce=' + encodeURIComponent(exportNonce) + '&filter=' + encodeURIComponent(filter);
	}

	function loadStats() {
		var fd = new FormData();
		fd.append('action', 'wpps_track_404s_get_stats');
		fd.append('nonce', adminNonce);
		fd.append('filter', filter);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				if (res.success && res.data) {
					var d = res.data;
					container.querySelectorAll('.wpps-404-stat-value').forEach(function(el, i) {
						var vals = [d.total_hits, d.unique_urls, d.new_today];
						if (vals[i] !== undefined) el.textContent = Number(vals[i]).toLocaleString();
					});
					var topTbody = section.querySelector('.wpps-404-top-table tbody');
					var topEmpty = section.querySelector('.wpps-404-top-empty');
					if (topTbody && topEmpty) {
						if (!d.top_404s || d.top_404s.length === 0) {
							topTbody.innerHTML = '';
							topEmpty.textContent = emptyMessageFor(topEmpty);
							topEmpty.style.display = 'block';
						} else {
							topEmpty.style.display = 'none';
							topTbody.innerHTML = d.top_404s.map(function(row) {
								return renderLogRow(row);
							}).join('');
							topTbody.querySelectorAll('.wpps-404-delete-btn').forEach(function(b) {
								b.addEventListener('click', function() { doDelete(b.dataset.id); });
							});
						}
					}
				}
			});
	}

	function loadLogs() {
		var tbody = section.querySelector('.wpps-404-recent-table tbody');
		var loading = section.querySelector('.wpps-404-loading');
		var empty = section.querySelector('.wpps-404-empty');
		var nav = section.querySelector('.wpps-404-pagination');
		if (!tbody) return;
		loading.style.display = 'block';
		empty.style.display = 'none';
		tbody.innerHTML = '';
		var fd = new FormData();
		fd.append('action', 'wpps_track_404s_get_logs');
		fd.append('nonce', adminNonce);
		fd.append('filter', filter);
		fd.append('search', search);
		fd.append('offset', currentPage * limit);
		fd.append('orderby', 'last_seen');
		fd.append('order', 'DESC');
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				loading.style.display = 'none';
				if (res.success && res.data) {
					var logs = res.data.logs || [];
					totalLogs = res.data.total || 0;
					if (logs.length === 0 && totalLogs === 0) {
						empty.textContent = emptyMessageFor(empty);
						empty.style.display = 'block';
						nav.innerHTML = '';
					} else {
						tbody.innerHTML = logs.map(function(row) {
							return renderLogRow(row);
						}).join('');
						tbody.querySelectorAll('.wpps-404-delete-btn').forEach(function(b) {
							b.addEventListener('click', function() { doDelete(b.dataset.id); });
						});
						var start = currentPage * limit + 1;
						var end = Math.min((currentPage + 1) * limit, totalLogs);
						nav.innerHTML = '<button type="button" class="button' + (currentPage === 0 ? ' disabled' : '') + '" data-page="prev"' + (currentPage === 0 ? ' disabled' : '') + '>&laquo;</button>' +
							'<button type="button" class="button' + (end >= totalLogs ? ' disabled' : '') + '" data-page="next"' + (end >= totalLogs ? ' disabled' : '') + '>&raquo;</button>' +
							'<span class="wpps-404-page-info">' + start + ' &ndash; ' + end + ' of ' + totalLogs + '</span>';
						nav.querySelectorAll('button').forEach(function(b) {
							b.addEventListener('click', function() {
								if (b.disabled) return;
								if (b.dataset.page === 'prev') currentPage--;
								else if (b.dataset.page === 'next') currentPage++;
								loadLogs();
							});
						});
					}
				} else {
					empty.style.display = 'block';
					empty.textContent = 'Failed to load logs.';
				}
			});
	}

	function doDelete(id) {
		if (!id || !confirm('Delete this 404 entry?')) return;
		var fd = new FormData();
		fd.append('action', 'wpps_track_404s_delete');
		fd.append('nonce', adminNonce);
		fd.append('id', id);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				if (res.success) {
					loadStats();
					loadLogs();
				}
			});
	}

	function refresh() {
		updateFilterHint();
		updateExportUrl();
		loadStats();
		currentPage = 0;
		loadLogs();
	}

	section.querySelectorAll('.wpps-404-filter-btn').forEach(function(b) {
		b.addEventListener('click', function() {
			filter = b.dataset.filter || 'redirected_only';
			section.querySelectorAll('.wpps-404-filter-btn').forEach(function(x) { x.classList.remove('active'); });
			b.classList.add('active');
			refresh();
		});
	});

	var searchInput = section.querySelector('.wpps-404-search');
	var searchTimeout;
	if (searchInput) {
		searchInput.addEventListener('input', function() {
			clearTimeout(searchTimeout);
			searchTimeout = setTimeout(function() {
				search = searchInput.value.trim();
				currentPage = 0;
				loadLogs();
			}, 300);
		});
	}

	section.querySelector('.wpps-404-clear-all').addEventListener('click', function() {
		if (!confirm('Are you sure you want to delete ALL 404 logs? This cannot be undone.')) return;
		var fd = new FormData();
		fd.append('action', 'wpps_track_404s_delete_all');
		fd.append('nonce', adminNonce);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				if (res.success) {
					loadStats();
					loadLogs();
				}
			});
	});

	btn.addEventListener('click', function() {
		var isOpen = section.style.display !== 'none';
		section.style.display = isOpen ? 'none' : 'block';
		viewText.style.display = isOpen ? 'inline' : 'none';
		hideText.style.display = isOpen ? 'none' : 'inline';
		btn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
		if (!isOpen) refresh();
	});
	updateFilterHint();
})();
</script>
