<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Sanitizers for settings
 */
function multiweather_sanitize_api_key( $value ) {
	return sanitize_text_field( $value );
}

function multiweather_sanitize_worldtides_key( $value ) {
	return sanitize_text_field( $value );
}

function multiweather_sanitize_cache_interval( $value ) {
	$value = (int) $value;
	if ( $value < 1 ) {
		$value = 1;
	}
	return $value;
}

function multiweather_sanitize_tides_cache_interval( $value ) {
	$value = (int) $value;
	if ( $value < 1 ) {
		$value = 1;
	}
	return $value;
}

function multiweather_sanitize_excluded_parts( $value ) {
	if ( ! is_array( $value ) ) {
		return array();
	}

	$allowed = array( 'minutely', 'alerts' );

	$value = array_map( 'sanitize_text_field', $value );
	$value = array_intersect( $value, $allowed );

	return array_values( $value );
}

// Register settings.
function multiweather_register_settings() {

	register_setting(
		'multiweather_settings_group',
		'multiweather_api_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'multiweather_sanitize_api_key',
			'default'           => '',
		)
	);

	register_setting(
		'multiweather_settings_group',
		'multiweather_cache_interval',
		array(
			'type'              => 'integer',
			'sanitize_callback' => 'multiweather_sanitize_cache_interval',
			'default'           => 180,
		)
	);

	register_setting(
		'multiweather_settings_group',
		'multiweather_excluded_parts',
		array(
			'type'              => 'array',
			'sanitize_callback' => 'multiweather_sanitize_excluded_parts',
			'default'           => array(),
		)
	);

	register_setting(
		'multiweather_settings_group',
		'multiweather_worldtides_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'multiweather_sanitize_worldtides_key',
			'default'           => '',
		)
	);

	register_setting(
		'multiweather_settings_group',
		'multiweather_tides_cache_interval',
		array(
			'type'              => 'integer',
			'sanitize_callback' => 'multiweather_sanitize_tides_cache_interval',
			'default'           => 24,
		)
	);
}
add_action( 'admin_init', 'multiweather_register_settings' );

// Create menu.
function multiweather_settings_menu() {
	add_options_page(
		'MultiWeather Settings',
		'MultiWeather',
		'manage_options',
		'multiweather-settings',
		'multiweather_settings_page_html'
	);
}
add_action( 'admin_menu', 'multiweather_settings_menu' );

// Render page.
function multiweather_settings_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$api_key        = get_option( 'multiweather_api_key', '' );
	$interval       = get_option( 'multiweather_cache_interval', 180 ); // Default 3 hours.
	$daily_call_cnt = (int) get_option( 'multiweather_daily_call_count', 0 );
	$worldtides_key = get_option( 'multiweather_worldtides_key', '' );
	$tides_cache    = get_option( 'multiweather_tides_cache_interval', 24 );

	$excluded_parts = get_option( 'multiweather_excluded_parts' );
	if ( ! is_array( $excluded_parts ) ) {
		$excluded_parts = array();
	}
	?>
	<div class="wrap">
		<h1>🌦️ MultiWeather Settings</h1>

		<form method="post" action="options.php">
			<?php settings_fields( 'multiweather_settings_group' ); ?>
			<?php do_settings_sections( 'multiweather_settings_group' ); ?>

			<table class="form-table">
				<tr valign="top">
					<th scope="row">🔑 OpenWeatherMap API Key</th>
					<td>
						<input type="text" name="multiweather_api_key"
							   value="<?php echo esc_attr( $api_key ); ?>" size="50" />
						<p class="description">
							<?php
							printf(
								/* translators: %s: OpenWeather pricing URL. */
								esc_html__( 'Don\'t have one? %s to get a v3 API key.', 'multiweather' ),
								sprintf(
									'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
									esc_url( 'https://openweathermap.org/price' ),
									esc_html__( 'Click here', 'multiweather' )
								)
							);
							?>
							<br><strong><?php esc_html_e( 'Note:', 'multiweather' ); ?></strong>
							<?php esc_html_e( 'Only v3 is supported. We do not support v2.5.', 'multiweather' ); ?>
						</p>
					</td>
				</tr>

				<?php /* WorldTides settings are available in the free version (WP.org compliant). */ ?>

				<tr valign="top">
					<th scope="row">🌊 WorldTides API Key</th>
					<td>
						<input type="text" name="multiweather_worldtides_key"
							   value="<?php echo esc_attr( $worldtides_key ); ?>" size="50" />
						<p class="description">
							<?php
							printf(
								/* translators: %s: WorldTides register URL. */
								esc_html__( 'Optional. Enter your %s API key to enable accurate tide events like high/low tide times.', 'multiweather' ),
								sprintf(
									'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
									esc_url( 'https://www.worldtides.info/register' ),
									esc_html__( 'WorldTides.net', 'multiweather' )
								)
							);
							?>
							<br><strong><?php esc_html_e( 'Tip:', 'multiweather' ); ?></strong>
							<?php esc_html_e( 'Without a key, tide info will fall back to marine modeling from Open-Meteo.', 'multiweather' ); ?>
						</p>
					</td>
				</tr>

				<tr valign="top">
					<th scope="row"><?php esc_html_e( 'WorldTides Cache Duration (Hours)', 'multiweather' ); ?></th>
					<td>
						<input type="number" name="multiweather_tides_cache_interval"
							   value="<?php echo esc_attr( $tides_cache ); ?>" min="1" />
						<p class="description">
							<?php esc_html_e( 'How long to cache WorldTides API responses (default 24 hours).', 'multiweather' ); ?>
						</p>
					</td>
				</tr>



				<tr valign="top">
					<th scope="row">⏱️ <?php esc_html_e( 'Cache Interval (in minutes)', 'multiweather' ); ?></th>
					<td>
						<input type="number" min="1" name="multiweather_cache_interval"
							   value="<?php echo esc_attr( $interval ); ?>" />
						<p class="description">
							<?php esc_html_e( 'Enter how often each weather widget should refresh. Default: 180 (3 hours). Use values like 5, 15, 123...', 'multiweather' ); ?>
						</p>
					</td>
				</tr>

				<tr valign="top">
					<th scope="row">📊 <?php esc_html_e( 'API Calls Made Today', 'multiweather' ); ?></th>
					<td>
						<input type="text" value="<?php echo esc_attr( $daily_call_cnt ); ?>" readonly />
						<p class="description">
							<?php esc_html_e( 'Estimated number of API calls made by your site today.', 'multiweather' ); ?>
						</p>
					</td>
				</tr>

				<tr valign="top">
					<th scope="row">📦 <?php esc_html_e( 'Shortcode Example', 'multiweather' ); ?></th>
					<td>
						<code>[mwpl_weather_card lat="49.635060" lon="-116.858307" label="Crawford Bay – British Columbia" card="2" units="metric"]</code>
						<p class="description">
							<?php esc_html_e( 'Copy and paste this into any post or page (replace lat, lon, and label) to insert a weather block.', 'multiweather' ); ?>
						</p>
					</td>
				</tr>

				<tr valign="top">
					<th scope="row">📦 <?php esc_html_e( 'Exclude Data From API', 'multiweather' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="multiweather_excluded_parts[]"
								   value="minutely" <?php checked( in_array( 'minutely', $excluded_parts, true ), true ); ?> />
							<?php esc_html_e( 'Minutely Data (Next 60 min rain forecast)', 'multiweather' ); ?>
						</label>
						<br>
						<label>
							<input type="checkbox" name="multiweather_excluded_parts[]"
								   value="alerts" <?php checked( in_array( 'alerts', $excluded_parts, true ), true ); ?> />
							<?php esc_html_e( 'Alerts (Severe weather warnings)', 'multiweather' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'Disable unused data to reduce API size and speed up load time.', 'multiweather' ); ?>
						</p>
					</td>
				</tr>
			</table>

			<?php submit_button(); ?>
		</form>

		<?php
		// Handle cache purge if button pressed and nonce verifies.
		if (
			isset( $_POST['multiweather_clear_cache'] ) && // phpcs:ignore WordPress.Security.NonceVerification.Missing
			check_admin_referer( 'multiweather_clear_cache_action', 'multiweather_clear_cache_nonce' )
		) {
			global $wpdb;

			// Build LIKE patterns safely.
			$mwpl_prefix_pattern  = $wpdb->esc_like( '_transient_mwpl_' ) . '%';
			$mwpl_timeout_pattern = $wpdb->esc_like( '_transient_timeout_mwpl_' ) . '%';

			// Fetch all matching option names, then delete them via delete_option()
			// so the object cache stays in sync.
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$mwpl_option_names = $wpdb->get_col(
				$wpdb->prepare(
					// $wpdb->options is a core, trusted table name.
					"SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s OR option_name LIKE %s",
					$mwpl_prefix_pattern,
					$mwpl_timeout_pattern
				)
			);


			if ( ! empty( $mwpl_option_names ) ) {
				foreach ( $mwpl_option_names as $mwpl_option_name ) {
					delete_option( $mwpl_option_name );
				}
			}

			printf(
				'<div class="notice notice-warning is-dismissible"><p>%s</p></div>',
				esc_html__( '☁️ All weather cache cleared. Each weather block will make a fresh API call immediately.', 'multiweather' )
			);
		}
		?>

		<form method="post">
			<h2>💥 <?php esc_html_e( 'Clear All Cached Weather Data', 'multiweather' ); ?></h2>
			<p>
				<strong>⚠️ <?php esc_html_e( 'Warning:', 'multiweather' ); ?></strong>
				<?php esc_html_e( 'Clicking this will purge all cached weather data. Every weather block on your site will make a fresh API call immediately.', 'multiweather' ); ?>
			</p>

			<?php wp_nonce_field( 'multiweather_clear_cache_action', 'multiweather_clear_cache_nonce' ); ?>
			<input type="submit" name="multiweather_clear_cache" value="<?php esc_attr_e( 'Clear Weather Cache', 'multiweather' ); ?>" class="button button-secondary" />
		</form>

	</div>
	<?php
}
