<?php
/**
 * Cloud Firewall IP Management
 *
 * @package WPSecurityNinja\Plugin
 */

namespace WPSecurityNinja\Plugin;

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

if ( ! class_exists( 'Wf_sn_cf' ) ) {
	return;
}

/**
 * Render the IP management form content.
 *
 * @param array $options Current options.
 */
function wf_sn_cf_render_ip_management_content( $options ) {
	$current_user_ip = Wf_sn_cf::get_user_ip();
	$server_host     = gethostname();
	$server_ip       = $server_host ? gethostbyname( $server_host ) : '';

	$entries = array();
	if ( class_exists( __NAMESPACE__ . '\Wf_Sn_Cf_Ip_Management' ) ) {
		$entries = Wf_Sn_Cf_Ip_Management::get_ip_management_entries( $options );
	}

	$quick_whitelist_services = array(
		'whitelist_wprocket'    => __( 'WP Rocket', 'security-ninja' ),
		'whitelist_uptimia'     => __( 'Uptimia', 'security-ninja' ),
		'whitelist_uptimerobot' => __( 'UptimeRobot', 'security-ninja' ),
		'whitelist_managewp'    => __( 'ManageWP', 'security-ninja' ),
	);
	?>

<div class="sn-cf-ip-management">

	<table class="form-table">
		<tbody>
			<tr valign="top">
				<th scope="row" colspan="2">
					<h3><?php esc_html_e( 'IP rules and blocks', 'security-ninja' ); ?></h3>
					<p class="description">
						<?php
						printf(
							/* translators: 1: current user IP, 2: server hostname, 3: server IP */
							esc_html__( 'Your IP: %1$s. Server: %2$s (%3$s).', 'security-ninja' ),
							esc_html( $current_user_ip ),
							esc_html( $server_host ),
							esc_html( $server_ip )
						);
						?>
					</p>
				</th>
			</tr>
			<tr>
				<td colspan="2">
					<div class="sn-cf-ip-toolbar sn-cf-ip-toolbar-top">
						<label class="screen-reader-text" for="sn-cf-ip-search"><?php esc_html_e( 'Search IPs', 'security-ninja' ); ?></label>
						<input type="search" id="sn-cf-ip-search" class="regular-text" placeholder="<?php esc_attr_e( 'Search IP or note…', 'security-ninja' ); ?>" />
					</div>

					<div class="sn-cf-ip-table-wrap" id="sn-cf-ip-table-wrap">
						<div class="sn-cf-ip-table-loading" id="sn-cf-ip-table-loading" hidden aria-hidden="true">
							<span class="spinner is-active" aria-hidden="true"></span>
							<span class="screen-reader-text"><?php esc_html_e( 'Updating IP list…', 'security-ninja' ); ?></span>
						</div>
						<table class="wp-list-table widefat striped sn-cf-ip-table" id="sn-cf-ip-table">
							<thead>
								<tr>
									<th scope="col" class="column-ip"><?php esc_html_e( 'IP / Range', 'security-ninja' ); ?></th>
									<th scope="col" class="column-status"><?php esc_html_e( 'Status', 'security-ninja' ); ?></th>
									<th scope="col" class="column-details"><?php esc_html_e( 'Details', 'security-ninja' ); ?></th>
									<th scope="col" class="column-actions"><?php esc_html_e( 'Actions', 'security-ninja' ); ?></th>
								</tr>
							</thead>
							<tbody id="sn-cf-ip-table-body">
								<?php if ( empty( $entries ) ) : ?>
									<tr class="sn-cf-ip-empty">
										<td colspan="4"><?php esc_html_e( 'No IP rules or blocks yet.', 'security-ninja' ); ?></td>
									</tr>
								<?php else : ?>
									<?php foreach ( $entries as $entry ) : ?>
										<?php wf_sn_cf_render_ip_table_row( $entry ); ?>
									<?php endforeach; ?>
								<?php endif; ?>
							</tbody>
						</table>
						<div class="sn-cf-ip-pagination" id="sn-cf-ip-pagination"></div>
					</div>

					<div class="sn-cf-ip-toolbar sn-cf-ip-toolbar-below">
						<div class="sn-cf-ip-toolbar-actions">
							<button type="button" class="button" id="sn-cf-add-ip-rule"><?php esc_html_e( 'Add IP rule', 'security-ninja' ); ?></button>
							<button type="button" class="button" id="sn-cf-copy-blacklisted" title="<?php esc_attr_e( 'Copies all blacklisted IPs and ranges (entire list, not only this page).', 'security-ninja' ); ?>"><?php esc_html_e( 'Copy blacklisted IPs', 'security-ninja' ); ?></button>
							<button type="button" class="button" id="sn-cf-copy-whitelisted" title="<?php esc_attr_e( 'Copies all whitelisted IPs and ranges (entire list, not only this page).', 'security-ninja' ); ?>"><?php esc_html_e( 'Copy whitelisted IPs', 'security-ninja' ); ?></button>
						</div>
					</div>
					<p class="sn-cf-ip-notice" id="sn-cf-ip-notice" role="status" aria-live="polite"></p>
				</td>
			</tr>

			<tr valign="top">
				<th scope="row" colspan="2">
					<h3><?php esc_html_e( 'Quick whitelist', 'security-ninja' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Enable trusted service IP ranges in one click.', 'security-ninja' ); ?></p>
				</th>
			</tr>
			<tr>
				<td colspan="2">
					<div class="sn-cf-quick-whitelist">
						<?php foreach ( $quick_whitelist_services as $option_key => $label ) : ?>
							<div class="sn-cf-quick-whitelist-item">
								<label for="<?php echo esc_attr( WF_SN_CF_OPTIONS_KEY . '_' . $option_key ); ?>">
									<?php echo esc_html( $label ); ?>
								</label>
								<?php
								Utils::create_toggle_switch(
									WF_SN_CF_OPTIONS_KEY . '_' . $option_key,
									array(
										'saved_value' => isset( $options[ $option_key ] ) ? $options[ $option_key ] : 0,
										'option_key'  => WF_SN_CF_OPTIONS_KEY . '[' . $option_key . ']',
									)
								);
								?>
							</div>
						<?php endforeach; ?>
					</div>
					<p class="description sn-cf-quick-whitelist-note">
						<?php esc_html_e( 'Some services make it possible to validate their crawlers automatically. We allow traffic from Baidu, Bing (MSN), Google, Yahoo, Yandex, Petal Search, and Applebot if they can be successfully validated.', 'security-ninja' ); ?>
					</p>
				</td>
			</tr>

			<tr valign="top">
				<th scope="row" colspan="2">
					<h3><?php esc_html_e( 'Test IP', 'security-ninja' ); ?></h3>
				</th>
			</tr>
			<tr>
				<td colspan="2" id="sn-firewall-test-ip">
					<input type="text" placeholder="<?php esc_attr_e( 'IP address, e.g. 203.0.113.10', 'security-ninja' ); ?>" class="regular-text" value="" id="wf-cf-ip-test" />
					<button type="button" class="button" id="wf-cf-do-test-ip"><?php esc_html_e( 'Test if IP is blocked', 'security-ninja' ); ?></button>
					<p id="wf-cf-do-test-ip-result"></p>
				</td>
			</tr>
		</tbody>
	</table>

	<input type="hidden" id="wf_sn_cf_active" name="wf_sn_cf[active]" value="<?php echo esc_attr( $options['active'] ); ?>" />
	<input type="hidden" id="wf_sn_cf_unblock_url" name="wf_sn_cf[unblock_url]" value="<?php echo esc_attr( $options['unblock_url'] ); ?>" />
	<input type="hidden" id="sn-cf-current-user-ip" value="<?php echo esc_attr( $current_user_ip ); ?>" />

	<div id="sn-cf-ip-rule-modal" class="sn-modal" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="sn-cf-ip-rule-modal-title">
		<div class="sn-modal-content sn-cf-ip-rule-modal-content">
			<button type="button" class="sn-modal-close sn-cf-ip-rule-modal-close" aria-label="<?php esc_attr_e( 'Close', 'security-ninja' ); ?>">&times;</button>
			<h3 id="sn-cf-ip-rule-modal-title"><?php esc_html_e( 'Add IP rule', 'security-ninja' ); ?></h3>
			<div class="sn-cf-ip-rule-form">
				<p id="sn-cf-ip-rule-bulk-wrap">
					<label for="sn-cf-ip-rule-textarea"><strong><?php esc_html_e( 'IP addresses or CIDR ranges', 'security-ninja' ); ?></strong></label>
					<textarea id="sn-cf-ip-rule-textarea" class="large-text" rows="8" placeholder="<?php esc_attr_e( 'One IP or CIDR per line', 'security-ninja' ); ?>"></textarea>
					<span class="description"><?php esc_html_e( 'One IP or CIDR range per line.', 'security-ninja' ); ?></span>
				</p>
				<p id="sn-cf-ip-rule-edit-wrap" style="display:none;">
					<label for="sn-cf-ip-rule-input"><strong><?php esc_html_e( 'IP or CIDR range', 'security-ninja' ); ?></strong></label>
					<input type="text" id="sn-cf-ip-rule-input" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. 203.0.113.10 or 192.0.2.0/24', 'security-ninja' ); ?>" />
				</p>
				<p id="sn-cf-ip-rule-note-wrap">
					<label for="sn-cf-ip-rule-note"><strong><?php esc_html_e( 'Note', 'security-ninja' ); ?></strong></label>
					<input type="text" id="sn-cf-ip-rule-note" class="regular-text" maxlength="150" placeholder="<?php esc_attr_e( 'Optional, e.g. Client office IP', 'security-ninja' ); ?>" />
					<span class="description"><?php esc_html_e( 'Optional label (max 150 characters). Applied to all IPs when adding multiple.', 'security-ninja' ); ?></span>
				</p>
				<fieldset class="sn-cf-ip-rule-list-type">
					<legend class="screen-reader-text"><?php esc_html_e( 'List type', 'security-ninja' ); ?></legend>
					<label>
						<input type="radio" name="sn_cf_ip_rule_list_type" value="blacklist" checked="checked" />
						<?php esc_html_e( 'Blacklist', 'security-ninja' ); ?>
					</label>
					<label>
						<input type="radio" name="sn_cf_ip_rule_list_type" value="whitelist" />
						<?php esc_html_e( 'Whitelist', 'security-ninja' ); ?>
					</label>
				</fieldset>
			</div>
			<div class="sn-cf-ip-rule-modal-actions">
				<button type="button" class="button button-primary" id="sn-cf-ip-rule-save"><?php esc_html_e( 'Save', 'security-ninja' ); ?></button>
				<button type="button" class="button" id="sn-cf-ip-rule-cancel"><?php esc_html_e( 'Cancel', 'security-ninja' ); ?></button>
			</div>
		</div>
	</div>

	<div id="sn-cf-remove-ip-modal" class="sn-modal" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="sn-cf-remove-ip-modal-title">
		<div class="sn-modal-content sn-cf-remove-ip-modal-content">
			<button type="button" class="sn-modal-close sn-cf-remove-ip-modal-close" aria-label="<?php esc_attr_e( 'Close', 'security-ninja' ); ?>">&times;</button>
			<h3 id="sn-cf-remove-ip-modal-title"><?php esc_html_e( 'Remove IP rule', 'security-ninja' ); ?></h3>
			<p id="sn-cf-remove-ip-message"></p>
			<div class="sn-cf-remove-ip-modal-actions">
				<button type="button" class="button button-primary" id="sn-cf-remove-ip-confirm"><?php esc_html_e( 'Remove', 'security-ninja' ); ?></button>
				<button type="button" class="button" id="sn-cf-remove-ip-cancel"><?php esc_html_e( 'Cancel', 'security-ninja' ); ?></button>
			</div>
		</div>
	</div>

</div>
	<?php
}

/**
 * Build details cell HTML for a table row.
 *
 * @param array $entry Entry data.
 * @return string
 */
function wf_sn_cf_ip_row_details_html( $entry ) {
	$sources = array();
	foreach ( $entry['sources'] as $src ) {
		$sources[] = Wf_Sn_Cf_Ip_Management::source_label( $src );
	}

	$lines   = array();
	$lines[] = '<span class="sn-cf-ip-detail-line"><strong>' . esc_html__( 'Source:', 'security-ninja' ) . '</strong> ' . esc_html( implode( ', ', $sources ) ) . '</span>';
	$lines[] = '<span class="sn-cf-ip-detail-line"><strong>' . esc_html__( 'Expires:', 'security-ninja' ) . '</strong> ' . esc_html( Wf_Sn_Cf_Ip_Management::format_expires_display( $entry['expires'] ) ) . '</span>';
	$lines[] = '<span class="sn-cf-ip-detail-line"><strong>' . esc_html__( 'Last visit:', 'security-ninja' ) . '</strong> ' . esc_html( Wf_Sn_Cf_Ip_Management::format_last_visit_display( $entry['last_visit'] ) ) . '</span>';
	if ( ! empty( $entry['note'] ) ) {
		$lines[] = '<span class="sn-cf-ip-detail-line"><strong>' . esc_html__( 'Note:', 'security-ninja' ) . '</strong> ' . esc_html( $entry['note'] ) . '</span>';
	}

	return '<div class="sn-cf-ip-details">' . implode( '', $lines ) . '</div>';
}

/**
 * Render a single IP table row (server-side fallback).
 *
 * @param array $entry Entry from Wf_Sn_Cf_Ip_Management::get_ip_management_entries().
 */
function wf_sn_cf_render_ip_table_row( $entry ) {
	$status_class = 'whitelisted' === $entry['status'] ? 'sn-cf-status-whitelisted' : 'sn-cf-status-blacklisted';
	$status_label = 'whitelisted' === $entry['status']
		? __( 'Whitelisted', 'security-ninja' )
		: __( 'Blacklisted', 'security-ninja' );

	$details_html = wf_sn_cf_ip_row_details_html( $entry );
	?>
	<tr class="sn-cf-ip-row"
		data-ip="<?php echo esc_attr( $entry['ip'] ); ?>"
		data-status="<?php echo esc_attr( $entry['status'] ); ?>"
		data-temporary="<?php echo ! empty( $entry['temporary'] ) ? '1' : '0'; ?>"
		data-editable="<?php echo ! empty( $entry['editable'] ) ? '1' : '0'; ?>"
		data-list-type="<?php echo esc_attr( $entry['list_type'] ); ?>">
		<td class="column-ip"><code class="sn-cf-ip-address"><?php echo esc_html( $entry['ip'] ); ?></code></td>
		<td class="column-status"><span class="sn-cf-status-badge <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span></td>
		<td class="column-details"><?php echo $details_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in helper. ?></td>
		<td class="column-actions sn-cf-ip-row-actions">
			<?php if ( ! empty( $entry['editable'] ) && ! empty( $entry['list_type'] ) ) : ?>
				<button type="button" class="button button-small sn-cf-icon-btn sn-cf-edit-ip" data-ip="<?php echo esc_attr( $entry['ip'] ); ?>" data-list-type="<?php echo esc_attr( $entry['list_type'] ); ?>" title="<?php esc_attr_e( 'Edit', 'security-ninja' ); ?>" aria-label="<?php esc_attr_e( 'Edit', 'security-ninja' ); ?>">
					<span class="dashicons dashicons-edit" aria-hidden="true"></span>
				</button>
			<?php endif; ?>
			<button type="button" class="button button-small sn-cf-icon-btn sn-cf-copy-ip" data-ip="<?php echo esc_attr( $entry['ip'] ); ?>" title="<?php esc_attr_e( 'Copy IP', 'security-ninja' ); ?>" aria-label="<?php esc_attr_e( 'Copy IP', 'security-ninja' ); ?>">
				<span class="dashicons dashicons-admin-page" aria-hidden="true"></span>
			</button>
			<?php if ( ! empty( $entry['editable'] ) && ! empty( $entry['list_type'] ) ) : ?>
				<button type="button" class="button button-small sn-cf-icon-btn sn-cf-remove-ip" data-ip="<?php echo esc_attr( $entry['ip'] ); ?>" data-list-type="<?php echo esc_attr( $entry['list_type'] ); ?>" title="<?php esc_attr_e( 'Remove', 'security-ninja' ); ?>" aria-label="<?php esc_attr_e( 'Remove', 'security-ninja' ); ?>">
					<span class="dashicons dashicons-trash" aria-hidden="true"></span>
				</button>
			<?php endif; ?>
		</td>
	</tr>
	<?php
}
