<?php
/**
 * Admin settings for SolarDawn Sunrise & Sunset Widget.
 *
 * @package SolarDawn_Sunrise_Sunset_Widget
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'SolarDawn_Admin' ) ) {
	/**
	 * Handles admin settings registration and rendering.
	 */
	class SolarDawn_Admin {
		/**
		 * Singleton instance.
		 *
		 * @var SolarDawn_Admin|null
		 */
		private static $instance = null;

		/**
		 * Get singleton instance.
		 *
		 * @return SolarDawn_Admin
		 */
		public static function instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Constructor.
		 */
		private function __construct() {
			add_action( 'admin_menu', array( $this, 'register_admin_menu' ) );
			add_action( 'admin_init', array( $this, 'register_settings' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
			add_action( 'wp_ajax_solardawn_sun_widget_get_states', array( $this, 'ajax_get_states' ) );
			add_action( 'wp_ajax_solardawn_sun_widget_get_cities', array( $this, 'ajax_get_cities' ) );
			add_filter( 'plugin_action_links_' . plugin_basename( SOLARDAWN_SUN_WIDGET_FILE ), array( $this, 'add_plugin_action_links' ) );
		}

		/**
		 * Register settings page.
		 *
		 * @return void
		 */
		public function register_admin_menu() {
			add_menu_page(
				__( 'SolarDawn Sun Widget', 'solardawn-sunrise-sunset-widget' ),
				__( 'SolarDawn Sun Widget', 'solardawn-sunrise-sunset-widget' ),
				'manage_options',
				'solardawn-sun-widget',
				array( $this, 'render_settings_page' ),
				'dashicons-admin-site-alt3',
				81
			);

			add_options_page(
				__( 'SolarDawn Sun Widget', 'solardawn-sunrise-sunset-widget' ),
				__( 'SolarDawn Sun Widget', 'solardawn-sunrise-sunset-widget' ),
				'manage_options',
				'solardawn-sun-widget',
				array( $this, 'render_settings_page' )
			);
		}

		/**
		 * Add a Settings shortcut on the Plugins page.
		 *
		 * @param array $links Plugin action links.
		 * @return array
		 */
		public function add_plugin_action_links( $links ) {
			$settings_link = sprintf(
				'<a href="%1$s">%2$s</a>',
				esc_url( admin_url( 'admin.php?page=solardawn-sun-widget' ) ),
				esc_html__( 'Settings', 'solardawn-sunrise-sunset-widget' )
			);

			array_unshift( $links, $settings_link );

			return $links;
		}

		/**
		 * Register plugin settings with the WordPress Settings API.
		 *
		 * @return void
		 */
		public function register_settings() {
			register_setting(
				'solardawn_sun_widget_settings_group',
				SOLARDAWN_SUN_WIDGET_OPTION,
				array(
					'type'              => 'array',
					'sanitize_callback' => array( $this, 'sanitize_settings' ),
					'default'           => solardawn_sun_widget_default_settings(),
				)
			);

			add_settings_section(
				'solardawn_sun_widget_main',
				__( 'Widget Settings', 'solardawn-sunrise-sunset-widget' ),
				'__return_false',
				'solardawn-sun-widget'
			);
		}

		/**
		 * Enqueue admin assets only on this settings page.
		 *
		 * @param string $hook_suffix Current admin page hook suffix.
		 * @return void
		 */
		public function enqueue_admin_assets( $hook_suffix ) {
			$allowed_hooks = array(
				'settings_page_solardawn-sun-widget',
				'toplevel_page_solardawn-sun-widget',
			);

			if ( ! in_array( $hook_suffix, $allowed_hooks, true ) ) {
				return;
			}

			wp_enqueue_style(
				'solardawn-sun-widget-admin',
				SOLARDAWN_SUN_WIDGET_URL . 'assets/css/admin.css',
				array(),
				SOLARDAWN_SUN_WIDGET_VERSION
			);

			wp_enqueue_script(
				'solardawn-sun-widget-admin',
				SOLARDAWN_SUN_WIDGET_URL . 'assets/js/admin.js',
				array(),
				SOLARDAWN_SUN_WIDGET_VERSION,
				true
			);

			wp_localize_script(
				'solardawn-sun-widget-admin',
				'solarDawnWidgetAdmin',
				array(
					'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
					'nonce'        => wp_create_nonce( 'solardawn_sun_widget_location' ),
					'selectedState'=> solardawn_sun_widget_get_settings()['state'],
					'selectedCity' => solardawn_sun_widget_get_settings()['city'],
					'i18n'         => array(
						'selectState' => __( 'Select a state or region', 'solardawn-sunrise-sunset-widget' ),
						'selectCity'  => __( 'Select a city', 'solardawn-sunrise-sunset-widget' ),
						'noStates'    => __( 'No states found for this country', 'solardawn-sunrise-sunset-widget' ),
						'noCities'    => __( 'No cities found for this state', 'solardawn-sunrise-sunset-widget' ),
						'loading'     => __( 'Loading...', 'solardawn-sunrise-sunset-widget' ),
					),
				)
			);
		}

		/**
		 * Render settings page.
		 *
		 * @return void
		 */
		public function render_settings_page() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$settings = solardawn_sun_widget_get_settings();
			?>
			<div class="wrap solardawn-admin-wrap">
				<h1><?php esc_html_e( 'SolarDawn Sunrise & Sunset Widget', 'solardawn-sunrise-sunset-widget' ); ?></h1>

				<div class="solardawn-admin-layout">
					<form method="post" action="options.php" class="solardawn-admin-panel">
						<?php settings_fields( 'solardawn_sun_widget_settings_group' ); ?>
						<?php do_settings_sections( 'solardawn-sun-widget' ); ?>

						<table class="form-table solardawn-settings-table" role="presentation">
							<tbody>
								<tr>
									<th scope="row">
										<label for="solardawn-title"><?php esc_html_e( 'Default Title', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<input type="text" id="solardawn-title" class="regular-text" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[title]" value="<?php echo esc_attr( $settings['title'] ); ?>">
									</td>
								</tr>

								<tr>
									<th scope="row">
										<label for="solardawn-location-mode"><?php esc_html_e( 'Location Mode', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<select id="solardawn-location-mode" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[location_mode]">
											<option value="country" <?php selected( $settings['location_mode'], 'country' ); ?>><?php esc_html_e( 'Country / state / city dropdown', 'solardawn-sunrise-sunset-widget' ); ?></option>
											<option value="manual" <?php selected( $settings['location_mode'], 'manual' ); ?>><?php esc_html_e( 'Manual latitude/longitude', 'solardawn-sunrise-sunset-widget' ); ?></option>
											<option value="detect" <?php selected( $settings['location_mode'], 'detect' ); ?>><?php esc_html_e( 'Detect visitor country by public IP', 'solardawn-sunrise-sunset-widget' ); ?></option>
										</select>
										<p class="description solardawn-privacy-note">
											<?php
											echo wp_kses_post(
												__( 'When visitor country detection is enabled, the visitor IP address is sent to ipapi.co to estimate the visitor country. No request is sent to ipapi.co when this mode is disabled. See the ipapi <a href="https://ipapi.co/terms/" target="_blank" rel="noopener">Terms of Service</a> and <a href="https://ipapi.co/privacy/" target="_blank" rel="noopener">Privacy Policy</a>.', 'solardawn-sunrise-sunset-widget' )
											);
											?>
										</p>
									</td>
								</tr>

								<tr class="solardawn-field-country">
									<th scope="row">
										<label for="solardawn-country"><?php esc_html_e( 'Country', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<?php $this->render_country_dropdown( $settings['country'] ); ?>
									</td>
								</tr>

								<tr class="solardawn-field-location">
									<th scope="row">
										<label for="solardawn-state"><?php esc_html_e( 'State / Region', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<?php $this->render_state_dropdown( $settings['country'], $settings['state'] ); ?>
									</td>
								</tr>

								<tr class="solardawn-field-location">
									<th scope="row">
										<label for="solardawn-city"><?php esc_html_e( 'City', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<?php $this->render_city_dropdown( $settings['country'], $settings['state'], $settings['city'] ); ?>
										<p class="description"><?php esc_html_e( 'Latitude, longitude, and timezone are detected from your country, state, and city selection.', 'solardawn-sunrise-sunset-widget' ); ?></p>
										<input type="hidden" id="solardawn-location-name" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[location_name]" value="<?php echo esc_attr( $settings['location_name'] ); ?>">
									</td>
								</tr>

								<tr class="solardawn-field-manual">
									<th scope="row">
										<label for="solardawn-lat"><?php esc_html_e( 'Latitude', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<input type="number" step="0.000001" min="-90" max="90" id="solardawn-lat" class="regular-text" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[lat]" value="<?php echo esc_attr( $settings['lat'] ); ?>">
									</td>
								</tr>

								<tr class="solardawn-field-manual">
									<th scope="row">
										<label for="solardawn-lon"><?php esc_html_e( 'Longitude', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<input type="number" step="0.000001" min="-180" max="180" id="solardawn-lon" class="regular-text" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[lon]" value="<?php echo esc_attr( $settings['lon'] ); ?>">
									</td>
								</tr>

								<tr class="solardawn-field-manual">
									<th scope="row">
										<label for="solardawn-timezone"><?php esc_html_e( 'Timezone', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<?php $this->render_timezone_dropdown( $settings['timezone'] ); ?>
									</td>
								</tr>

								<tr>
									<th scope="row"><?php esc_html_e( 'Display Options', 'solardawn-sunrise-sunset-widget' ); ?></th>
									<td>
										<div class="solardawn-toggle-grid">
											<?php
											$this->render_toggle( 'show_date', __( 'Show Date', 'solardawn-sunrise-sunset-widget' ), $settings['show_date'] );
											$this->render_toggle( 'show_solar_noon', __( 'Show Solar Noon', 'solardawn-sunrise-sunset-widget' ), $settings['show_solar_noon'] );
											$this->render_toggle( 'show_day_length', __( 'Show Day Length', 'solardawn-sunrise-sunset-widget' ), $settings['show_day_length'] );
											$this->render_toggle( 'show_golden_hour', __( 'Show Golden Hour', 'solardawn-sunrise-sunset-widget' ), $settings['show_golden_hour'] );
											$this->render_toggle( 'show_blue_hour', __( 'Show Blue Hour', 'solardawn-sunrise-sunset-widget' ), $settings['show_blue_hour'] );
											$this->render_toggle( 'show_twilight', __( 'Show Twilight Times', 'solardawn-sunrise-sunset-widget' ), $settings['show_twilight'] );
											?>
										</div>
									</td>
								</tr>

								<tr>
									<th scope="row">
										<label for="solardawn-theme"><?php esc_html_e( 'Widget Theme', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<select id="solardawn-theme" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[theme]">
											<option value="light" <?php selected( $settings['theme'], 'light' ); ?>><?php esc_html_e( 'Light', 'solardawn-sunrise-sunset-widget' ); ?></option>
											<option value="dark" <?php selected( $settings['theme'], 'dark' ); ?>><?php esc_html_e( 'Dark', 'solardawn-sunrise-sunset-widget' ); ?></option>
											<option value="sunrise" <?php selected( $settings['theme'], 'sunrise' ); ?>><?php esc_html_e( 'Sunrise gradient', 'solardawn-sunrise-sunset-widget' ); ?></option>
										</select>
									</td>
								</tr>

								<tr>
									<th scope="row">
										<label for="solardawn-cache-hours"><?php esc_html_e( 'Cache Duration in Hours', 'solardawn-sunrise-sunset-widget' ); ?></label>
									</th>
									<td>
										<input type="number" min="1" max="168" step="1" id="solardawn-cache-hours" class="small-text" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[cache_hours]" value="<?php echo esc_attr( $settings['cache_hours'] ); ?>">
										<p class="description"><?php esc_html_e( 'Use 1 to 168 hours. Twelve hours is recommended for most sites.', 'solardawn-sunrise-sunset-widget' ); ?></p>
									</td>
								</tr>
							</tbody>
						</table>

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

					<aside class="solardawn-admin-sidebar">
						<?php $this->render_preview_shortcode(); ?>
					</aside>
				</div>
			</div>
			<?php
		}

		/**
		 * Sanitize settings before saving.
		 *
		 * @param array $input Raw settings.
		 * @return array
		 */
		public function sanitize_settings( $input ) {
			$defaults = solardawn_sun_widget_default_settings();
			$input    = is_array( $input ) ? wp_unslash( $input ) : array();
			$clean    = $defaults;

			$clean['title'] = isset( $input['title'] ) ? sanitize_text_field( $input['title'] ) : $defaults['title'];

			$location_modes = array( 'country', 'manual', 'detect' );
			$mode           = isset( $input['location_mode'] ) ? sanitize_key( $input['location_mode'] ) : $defaults['location_mode'];
			$clean['location_mode'] = in_array( $mode, $location_modes, true ) ? $mode : $defaults['location_mode'];

			$clean['country'] = isset( $input['country'] ) ? $this->sanitize_country( $input['country'] ) : $defaults['country'];
			$clean['state']   = isset( $input['state'] ) ? sanitize_text_field( $input['state'] ) : $defaults['state'];
			$clean['city']    = isset( $input['city'] ) ? sanitize_text_field( $input['city'] ) : $defaults['city'];
			$location         = solardawn_find_location_details( $clean['country'], $clean['state'], $clean['city'] );

			$clean['country']       = $location['country'];
			$clean['state']         = $location['state'];
			$clean['city']          = $location['city'];
			$clean['location_name'] = ! empty( $location['location_name'] ) ? sanitize_text_field( $location['location_name'] ) : $clean['country'];
			$fallback_coords        = array(
				'lat'      => $location['lat'],
				'lon'      => $location['lon'],
				'timezone' => $location['timezone'],
			);

			$clean['lat']      = isset( $input['lat'] ) ? (string) $this->sanitize_coordinate( $input['lat'], -90, 90, $fallback_coords['lat'] ) : (string) $fallback_coords['lat'];
			$clean['lon']      = isset( $input['lon'] ) ? (string) $this->sanitize_coordinate( $input['lon'], -180, 180, $fallback_coords['lon'] ) : (string) $fallback_coords['lon'];
			$clean['timezone'] = isset( $input['timezone'] ) ? $this->sanitize_timezone( $input['timezone'], $fallback_coords['timezone'] ) : $fallback_coords['timezone'];

			if ( 'country' === $clean['location_mode'] ) {
				$clean['lat']      = (string) $fallback_coords['lat'];
				$clean['lon']      = (string) $fallback_coords['lon'];
				$clean['timezone'] = $fallback_coords['timezone'];
			}

			$toggles = array(
				'show_date',
				'show_solar_noon',
				'show_day_length',
				'show_golden_hour',
				'show_blue_hour',
				'show_twilight',
			);

			foreach ( $toggles as $toggle ) {
				$clean[ $toggle ] = isset( $input[ $toggle ] ) && 'yes' === $input[ $toggle ] ? 'yes' : 'no';
			}

			$themes = array( 'light', 'dark', 'sunrise' );
			$theme  = isset( $input['theme'] ) ? sanitize_key( $input['theme'] ) : $defaults['theme'];
			$clean['theme'] = in_array( $theme, $themes, true ) ? $theme : $defaults['theme'];

			$cache_hours = isset( $input['cache_hours'] ) ? absint( $input['cache_hours'] ) : $defaults['cache_hours'];
			$clean['cache_hours'] = max( 1, min( 168, $cache_hours ) );

			return $clean;
		}

		/**
		 * Render country dropdown.
		 *
		 * @param string $selected Selected country.
		 * @return void
		 */
		public function render_country_dropdown( $selected = 'Sri Lanka' ) {
			$countries = solardawn_get_location_countries();
			?>
			<select id="solardawn-country" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[country]">
				<?php foreach ( $countries as $details ) : ?>
					<option
						value="<?php echo esc_attr( $details['name'] ); ?>"
						data-lat="<?php echo esc_attr( $details['lat'] ); ?>"
						data-lon="<?php echo esc_attr( $details['lon'] ); ?>"
						data-timezone="<?php echo esc_attr( $details['timezone'] ); ?>"
						data-location-name="<?php echo esc_attr( ! empty( $details['capital'] ) ? $details['capital'] : $details['name'] ); ?>"
						<?php selected( $selected, $details['name'] ); ?>
					>
						<?php echo esc_html( $details['name'] ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php
		}

		/**
		 * Render state dropdown.
		 *
		 * @param string $country  Country name.
		 * @param string $selected Selected state.
		 * @return void
		 */
		private function render_state_dropdown( $country, $selected = '' ) {
			$states = solardawn_get_location_states( $country );
			?>
			<select id="solardawn-state" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[state]">
				<option value=""><?php esc_html_e( 'Select a state or region', 'solardawn-sunrise-sunset-widget' ); ?></option>
				<?php foreach ( $states as $state ) : ?>
					<option
						value="<?php echo esc_attr( $state['name'] ); ?>"
						data-lat="<?php echo esc_attr( $state['lat'] ); ?>"
						data-lon="<?php echo esc_attr( $state['lon'] ); ?>"
						data-timezone="<?php echo esc_attr( $state['timezone'] ); ?>"
						data-location-name="<?php echo esc_attr( $state['name'] ); ?>"
						<?php selected( $selected, $state['name'] ); ?>
					>
						<?php echo esc_html( $state['name'] ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php
		}

		/**
		 * Render city dropdown.
		 *
		 * @param string $country  Country name.
		 * @param string $state    State name.
		 * @param string $selected Selected city.
		 * @return void
		 */
		private function render_city_dropdown( $country, $state, $selected = '' ) {
			$cities = solardawn_get_location_cities( $country, $state );
			?>
			<select id="solardawn-city" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[city]">
				<option value=""><?php esc_html_e( 'Select a city', 'solardawn-sunrise-sunset-widget' ); ?></option>
				<?php foreach ( $cities as $city ) : ?>
					<option
						value="<?php echo esc_attr( $city['name'] ); ?>"
						data-lat="<?php echo esc_attr( $city['lat'] ); ?>"
						data-lon="<?php echo esc_attr( $city['lon'] ); ?>"
						data-timezone="<?php echo esc_attr( $city['timezone'] ); ?>"
						data-location-name="<?php echo esc_attr( $city['name'] ); ?>"
						<?php selected( $selected, $city['name'] ); ?>
					>
						<?php echo esc_html( $city['name'] ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php
		}

		/**
		 * Render timezone dropdown.
		 *
		 * @param string $selected Selected timezone.
		 * @return void
		 */
		private function render_timezone_dropdown( $selected = 'Asia/Colombo' ) {
			$timezones = timezone_identifiers_list();
			$selected  = $this->sanitize_timezone( $selected, 'Asia/Colombo' );
			?>
			<select id="solardawn-timezone" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[timezone]">
				<?php foreach ( $timezones as $timezone ) : ?>
					<option value="<?php echo esc_attr( $timezone ); ?>" <?php selected( $selected, $timezone ); ?>>
						<?php echo esc_html( $timezone ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php
		}

		/**
		 * Render shortcode preview box.
		 *
		 * @return void
		 */
		public function render_preview_shortcode() {
			$settings = solardawn_sun_widget_get_settings();
			?>
			<div class="solardawn-shortcode-box">
				<h2><?php esc_html_e( 'Shortcode', 'solardawn-sunrise-sunset-widget' ); ?></h2>
				<p><?php esc_html_e( 'Add the widget to posts, pages, widget areas, Gutenberg shortcode blocks, or page builders.', 'solardawn-sunrise-sunset-widget' ); ?></p>
				<code>[solardawn_sunrise_sunset]</code>
				<code>[solardawn_sunrise_sunset country="<?php echo esc_attr( $settings['country'] ); ?>"]</code>
				<code>[solardawn_sunrise_sunset country="<?php echo esc_attr( $settings['country'] ); ?>" state="<?php echo esc_attr( $settings['state'] ); ?>" city="<?php echo esc_attr( $settings['city'] ); ?>"]</code>
				<code>[solardawn_sunrise_sunset lat="<?php echo esc_attr( $settings['lat'] ); ?>" lon="<?php echo esc_attr( $settings['lon'] ); ?>" timezone="<?php echo esc_attr( $settings['timezone'] ); ?>"]</code>
			</div>
			<?php
		}

		/**
		 * Render a checkbox toggle.
		 *
		 * @param string $key     Setting key.
		 * @param string $label   Toggle label.
		 * @param string $checked Current value.
		 * @return void
		 */
		private function render_toggle( $key, $label, $checked ) {
			$field_id = 'solardawn-' . str_replace( '_', '-', $key );
			?>
			<label class="solardawn-toggle" for="<?php echo esc_attr( $field_id ); ?>">
				<input type="checkbox" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( SOLARDAWN_SUN_WIDGET_OPTION ); ?>[<?php echo esc_attr( $key ); ?>]" value="yes" <?php checked( $checked, 'yes' ); ?>>
				<span><?php echo esc_html( $label ); ?></span>
			</label>
			<?php
		}

		/**
		 * AJAX response for state options.
		 *
		 * @return void
		 */
		public function ajax_get_states() {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => __( 'Permission denied.', 'solardawn-sunrise-sunset-widget' ) ), 403 );
			}

			check_ajax_referer( 'solardawn_sun_widget_location', 'nonce' );

			$country = isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( $_POST['country'] ) ) : '';
			$details = solardawn_find_location_details( $country );

			wp_send_json_success(
				array(
					'location' => $details,
					'states'   => solardawn_get_location_states( $details['country'] ),
				)
			);
		}

		/**
		 * AJAX response for city options.
		 *
		 * @return void
		 */
		public function ajax_get_cities() {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => __( 'Permission denied.', 'solardawn-sunrise-sunset-widget' ) ), 403 );
			}

			check_ajax_referer( 'solardawn_sun_widget_location', 'nonce' );

			$country = isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( $_POST['country'] ) ) : '';
			$state   = isset( $_POST['state'] ) ? sanitize_text_field( wp_unslash( $_POST['state'] ) ) : '';
			$details = solardawn_find_location_details( $country, $state );

			wp_send_json_success(
				array(
					'location' => $details,
					'cities'   => solardawn_get_location_cities( $details['country'], $details['state'] ),
				)
			);
		}

		/**
		 * Sanitize selected country.
		 *
		 * @param string $country Country name.
		 * @return string
		 */
		private function sanitize_country( $country ) {
			$country = sanitize_text_field( (string) $country );

			foreach ( solardawn_get_location_countries() as $row ) {
				if ( isset( $row['name'] ) && strtolower( $row['name'] ) === strtolower( $country ) ) {
					return $row['name'];
				}
			}

			return 'Sri Lanka';
		}

		/**
		 * Sanitize coordinate within bounds.
		 *
		 * @param mixed $value    Coordinate value.
		 * @param float $min      Minimum.
		 * @param float $max      Maximum.
		 * @param float $fallback Fallback.
		 * @return float
		 */
		private function sanitize_coordinate( $value, $min, $max, $fallback ) {
			if ( ! is_numeric( $value ) ) {
				return (float) $fallback;
			}

			$value = round( (float) $value, 6 );

			if ( $value < $min || $value > $max ) {
				return (float) $fallback;
			}

			return $value;
		}

		/**
		 * Sanitize timezone.
		 *
		 * @param string $timezone Timezone identifier.
		 * @param string $fallback Fallback timezone.
		 * @return string
		 */
		private function sanitize_timezone( $timezone, $fallback ) {
			$timezone = sanitize_text_field( (string) $timezone );
			$fallback = sanitize_text_field( (string) $fallback );

			if ( in_array( $timezone, timezone_identifiers_list(), true ) ) {
				return $timezone;
			}

			if ( in_array( $fallback, timezone_identifiers_list(), true ) ) {
				return $fallback;
			}

			return 'UTC';
		}
	}
}
