<?php
/**
 * Cloud Firewall 404 Guard
 * 
 * This file contains the 404 Guard form content for the Cloud Firewall module.
 */

namespace WPSecurityNinja\Plugin;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Ensure we have access to the main class
if (!class_exists('Wf_sn_cf')) {
    return;
}

/**
 * Render the 404 Guard form content
 * 
 * @param array $options Current options
 * @param array $ips IP data
 */
function wf_sn_cf_render_404guard_content($options, $ips) {
    ?>

<table class="form-table">
					<tbody>
						<tr>
							<td colspan="2">
								<h2><?php esc_html_e('404 Guard Settings', 'security-ninja'); ?></h2>
								<p class="description"><?php esc_html_e('Protect your website from bots that generate excessive 404 errors. This feature blocks IPs that hit too many non-existent pages in a short time period.', 'security-ninja'); ?></p>
							</td>
						</tr>

						<tr valign="top">
							<th scope="row">
								<label for="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_enabled'; ?>">
									<h3><?php esc_html_e('Enable 404 Guard', 'security-ninja'); ?></h3>
									<p class="description"><?php esc_html_e('Block IPs that generate excessive 404 errors. This helps prevent bots from scanning your site for vulnerabilities.', 'security-ninja'); ?></p>
								</label>
							</th>
							<td class="sn-cf-options">
								<?php
								\WPSecurityNinja\Plugin\Utils::create_toggle_switch(
									WF_SN_CF_OPTIONS_KEY . '_404guard_enabled',
									array(
										'saved_value' => $options['404guard_enabled'],
										'option_key'  => WF_SN_CF_OPTIONS_KEY . '[404guard_enabled]',
									)
								);
								?>
							</td>
						</tr>

						<tr valign="top">
							<th scope="row">
								<label for="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_threshold'; ?>">
									<h3><?php esc_html_e('404 Error Threshold', 'security-ninja'); ?></h3>
									<p class="description"><?php esc_html_e('Number of 404 errors allowed before an IP is blocked.', 'security-ninja'); ?></p>
								</label>
							</th>
							<td class="alignright">
								<input type="number" 
									id="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_threshold'; ?>" 
									name="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY); ?>[404guard_threshold]" 
									value="<?php echo esc_attr($options['404guard_threshold']); ?>" 
									min="5" 
									max="50" 
									class="small-text" />
								<p class="description"><?php esc_html_e('Range: 5-50 errors. Recommended: 10-20 errors', 'security-ninja'); ?></p>
							</td>
						</tr>

						<tr valign="top">
							<th scope="row">
								<label for="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_window'; ?>">
									<h3><?php esc_html_e('Time Window (seconds)', 'security-ninja'); ?></h3>
									<p class="description"><?php esc_html_e('Time period in seconds to count 404 errors.', 'security-ninja'); ?></p>
								</label>
							</th>
							<td class="alignright">
								<input type="number" 
									id="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_window'; ?>" 
									name="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY); ?>[404guard_window]" 
									value="<?php echo esc_attr($options['404guard_window']); ?>" 
									min="60" 
									max="3600" 
									class="small-text" />
								<p class="description"><?php esc_html_e('Range: 60-3600 seconds (1 min - 1 hour). Recommended: 300 seconds (5 minutes)', 'security-ninja'); ?></p>
							</td>
						</tr>

						<tr valign="top">
							<th scope="row">
								<label for="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_block_time'; ?>">
									<h3><?php esc_html_e('Block Duration (seconds)', 'security-ninja'); ?></h3>
									<p class="description"><?php esc_html_e('How long to block an IP after exceeding the threshold.', 'security-ninja'); ?></p>
								</label>
							</th>
							<td class="alignright">
								<input type="number" 
									id="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY) . '_404guard_block_time'; ?>" 
									name="<?php echo esc_attr(WF_SN_CF_OPTIONS_KEY); ?>[404guard_block_time]" 
									value="<?php echo esc_attr($options['404guard_block_time']); ?>" 
									min="300" 
									max="86400" 
									class="small-text" />
								<p class="description"><?php esc_html_e('Range: 300-86400 seconds (5 min - 24 hours). Recommended: 600 seconds (10 minutes)', 'security-ninja'); ?></p>
							</td>
						</tr>

						<tr>
							<td colspan="2">
								<div class="sncard settings-card">
									<h3><?php esc_html_e('Current Status', 'security-ninja'); ?></h3>
									<?php
														// Load 404 Guard class if not already loaded
														if (!class_exists(__NAMESPACE__ . '\SN_404_Guard')) {
															require_once WF_SN_PLUGIN_DIR . 'modules/cloud-firewall/class-sn-404-guard.php';
														}
									$is_404guard_available = Wf_sn_cf::is_404guard_available();

									if ($is_404guard_available) {
										echo '<p class="description" style="color: green;"><strong>' . esc_html__('✓ 404 Guard is active and monitoring', 'security-ninja') . '</strong></p>';
										
					
										
										// Get statistics (with error handling)
										try {
											$stats = SN_404_Guard::get_statistics();
										} catch (\Exception $e) {
											$stats = array(
												'banned_count' => 0,
												'monitored_count' => 0,
												'expiring_soon_ips' => array(),
												'recent_events_count' => 0
											);
										}
										
										echo '<div style="margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 4px;">';

										// Show banned count
										echo '<p><strong>' . esc_html__('Currently Banned:', 'security-ninja') . '</strong> ';
										if ($stats['banned_count'] > 0) {
											echo '<span style="color: #dc3545; font-weight: bold;">' . esc_html($stats['banned_count']) . '</span>';
										} else {
											echo '<span style="color: #28a745;">' . esc_html__('None', 'security-ninja') . '</span>';
										}
										echo '</p>';
										
										// Show oldest banned IPs (top 5)
										$banned_ips = SN_404_Guard::get_currently_banned_ips();
										if (!empty($banned_ips)) {
											// Sort by expiry time (oldest first - closest to expiring)
											uasort($banned_ips, function($a, $b) { return $a <=> $b; });
											$oldest_banned = array_slice($banned_ips, 0, 5, true);
											
											echo '<ul style="margin: 5px 0 10px 20px; font-size: 12px;">';
											foreach ($oldest_banned as $ip => $expiry_time) {
												$time_left = SN_404_Guard::format_time_remaining($expiry_time - time());
												echo '<li><code>' . esc_html($ip) . '</code> - ' . sprintf(esc_html__('ban expires in %s', 'security-ninja'), esc_html($time_left)) . '</li>';
											}
											echo '</ul>';
										}
										
										// Show monitored count
										echo '<p><strong>' . esc_html__('Being Monitored:', 'security-ninja') . '</strong> ';
										if ($stats['monitored_count'] > 0) {
											echo '<span style="color: #ffc107; font-weight: bold;">' . esc_html($stats['monitored_count']) . '</span>';
										} else {
											echo '<span style="color: #28a745;">' . esc_html__('None', 'security-ninja') . '</span>';
										}
										echo '</p>';
										
										// Add threshold note
										$firewall_options = Wf_sn_cf::get_options();
										$threshold = $firewall_options['404guard_threshold'];
										echo '<p style="font-size: 12px; color: #6c757d; margin: 5px 0;"><em>' . sprintf(esc_html__('Note: IPs are banned when they reach %d x 404s within the monitoring window', 'security-ninja'), $threshold) . '</em></p>';
										
										// Show recent events count
										echo '<p><strong>' . esc_html__('Events (24h):', 'security-ninja') . '</strong> ';
										if ($stats['recent_events_count'] > 0) {
											echo '<span style="color: #007cba; font-weight: bold;">' . esc_html($stats['recent_events_count']) . '</span>';
										} else {
											echo '<span style="color: #6c757d;">' . esc_html__('None', 'security-ninja') . '</span>';
										}
										echo '</p>';
										
										// Show expiring soon IPs
										if (!empty($stats['expiring_soon_ips'])) {
											echo '<p><strong>' . esc_html__('Expiring Soon (within 5 minutes):', 'security-ninja') . '</strong></p>';
											echo '<ul style="margin: 5px 0; padding-left: 20px; font-size: 12px;">';
											foreach ($stats['expiring_soon_ips'] as $ip => $seconds_remaining) {
												$time_formatted = SN_404_Guard::format_time_remaining($seconds_remaining);
												echo '<li><code>' . esc_html($ip) . '</code> - ' . esc_html($time_formatted) . '</li>';
											}
											echo '</ul>';
										}
										
										// Show oldest monitored IPs (top 5)
										if (!empty($stats['oldest_monitored_ips'])) {
											echo '<ul style="margin: 5px 0 10px 20px; font-size: 12px;">';
											foreach ($stats['oldest_monitored_ips'] as $ip => $info) {
												$time_left = $info['expiry'] ? SN_404_Guard::format_time_remaining($info['expiry'] - time()) : esc_html__('unknown', 'security-ninja');
												echo '<li><code>' . esc_html($ip) . '</code> - ' . sprintf(esc_html__('%d x 404s, monitoring window expires in %s', 'security-ninja'), intval($info['count']), esc_html($time_left)) . '</li>';
											}
											echo '</ul>';
										}
										
										echo '</div>';
									} else {
										echo '<p class="description" style="color: orange;"><strong>' . esc_html__('⚠ 404 Guard is not currently active', 'security-ninja') . '</strong></p>';
									}
									?>
									
									<h3><?php esc_html_e('Important Safety Notes', 'security-ninja'); ?></h3>
									<div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 10px; border-radius: 4px; margin: 10px 0;">
										<ul style="margin: 0; padding-left: 20px;">
											<li><?php esc_html_e('Search engines and known crawlers are automatically whitelisted', 'security-ninja'); ?></li>
											<li><?php esc_html_e('Your existing firewall whitelist is respected', 'security-ninja'); ?></li>
											<li><?php esc_html_e('Blocks are temporary and automatically expire', 'security-ninja'); ?></li>
											<li><?php esc_html_e('All blocked IPs are logged for review in the Events Logger', 'security-ninja'); ?></li>
										</ul>
									</div>
									
									<h3><?php esc_html_e('How it works', 'security-ninja'); ?></h3>
									<ul class="security-test-list">
										<li><?php esc_html_e('Monitors 404 errors in real-time', 'security-ninja'); ?></li>
										<li><?php esc_html_e('Automatically whitelists known search engines and crawlers', 'security-ninja'); ?></li>
										<li><?php esc_html_e('Respects your existing firewall whitelist', 'security-ninja'); ?></li>
										<li><?php esc_html_e('Logs all blocked IPs for review', 'security-ninja'); ?></li>
										<li><?php esc_html_e('Blocks are temporary and automatically expire', 'security-ninja'); ?></li>
									</ul>
									
								</div>
							</td>
						</tr>
					</tbody>
				</table>

<?php
}