<?php
/**
 * Admin settings for the language switcher.
 *
 * @package EffortLessMultisiteLanguageSwitcher
 */

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

/**
 * Handles network admin menu and settings page rendering.
 */
class ELMLS_Admin {

	/**
	 * Site data instance.
	 *
	 * @var ELMLS_Site_Data
	 */
	private $site_data;

	/**
	 * Flag resolver instance.
	 *
	 * @var ELMLS_Flag_Resolver
	 */
	private $flag_resolver;

	/**
	 * Constructor.
	 *
	 * @param ELMLS_Site_Data     $site_data     Site data instance.
	 * @param ELMLS_Flag_Resolver $flag_resolver Flag resolver instance.
	 */
	public function __construct( ELMLS_Site_Data $site_data, ELMLS_Flag_Resolver $flag_resolver ) {
		$this->site_data     = $site_data;
		$this->flag_resolver = $flag_resolver;
	}

	/**
	 * Adds the plugin submenu in network admin.
	 */
	public function admin_menu() {
		add_submenu_page(
			'settings.php',
			__( 'Multisite Language Switcher Settings', 'effortless-multisite-language-switcher' ),
			__( 'Language Switcher', 'effortless-multisite-language-switcher' ),
			'manage_network_options',
			'elmls-settings',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Renders the plugin settings page in network admin.
	 */
	public function render_settings_page() {
		if ( ! is_network_admin() || ! current_user_can( 'manage_network_options' ) ) {
			return;
		}

		$hidden_sites        = get_site_option( 'elmls_hidden_sites', array() );
		$hide_switcher       = get_site_option( 'elmls_hide_switcher', false );
		$switcher_position   = get_site_option( 'elmls_switcher_position', 'bottom-right' );
		$custom_flag_mapping = get_site_option( 'elmls_custom_flag_mapping', '' );
		$custom_position_x   = get_site_option( 'elmls_custom_position_x', '20' );
		$custom_position_y   = get_site_option( 'elmls_custom_position_y', '20' );
		$site_overrides      = get_site_option( 'elmls_site_overrides', array() );
		$sites               = get_sites( array( 'number' => apply_filters( 'elmls_sites_limit', 100 ) ) );
		$available_flags     = $this->flag_resolver->get_available_flag_codes();

		if ( isset( $_POST['elmls_save_settings'] ) && check_admin_referer( 'elmls_save_settings_nonce' ) ) {
			$hidden_sites        = isset( $_POST['elmls_hidden_sites'] ) ? array_map( 'intval', wp_unslash( $_POST['elmls_hidden_sites'] ) ) : array();
			$hide_switcher       = isset( $_POST['elmls_hide_switcher'] ) ? true : false;
			$switcher_position   = isset( $_POST['elmls_switcher_position'] ) ? sanitize_text_field( wp_unslash( $_POST['elmls_switcher_position'] ) ) : 'bottom-right';
			$custom_flag_mapping = isset( $_POST['elmls_custom_flag_mapping'] ) ? sanitize_textarea_field( wp_unslash( $_POST['elmls_custom_flag_mapping'] ) ) : '';
			$custom_position_x   = isset( $_POST['elmls_custom_position_x'] ) ? sanitize_text_field( wp_unslash( $_POST['elmls_custom_position_x'] ) ) : '20';
			$custom_position_y   = isset( $_POST['elmls_custom_position_y'] ) ? sanitize_text_field( wp_unslash( $_POST['elmls_custom_position_y'] ) ) : '20';

			$posted_urls    = isset( $_POST['elmls_site_override_url'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['elmls_site_override_url'] ) ) : array();
			$posted_flags   = isset( $_POST['elmls_site_override_flag'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['elmls_site_override_flag'] ) ) : array();
			$site_overrides = array();

			foreach ( $sites as $site ) {
				$blog_id       = (int) $site->blog_id;
				$override_url  = isset( $posted_urls[ $blog_id ] ) ? esc_url_raw( trim( $posted_urls[ $blog_id ] ) ) : '';
				$override_flag = isset( $posted_flags[ $blog_id ] ) ? sanitize_file_name( $posted_flags[ $blog_id ] ) : '';

				$entry = array();
				if ( ! empty( $override_url ) ) {
					$entry['url'] = $override_url;
				}
				if ( ! empty( $override_flag ) && in_array( $override_flag, $available_flags, true ) ) {
					$entry['flag'] = $override_flag;
				}
				if ( ! empty( $entry ) ) {
					$site_overrides[ $blog_id ] = $entry;
				}
			}

			update_site_option( 'elmls_hidden_sites', $hidden_sites );
			update_site_option( 'elmls_hide_switcher', $hide_switcher );
			update_site_option( 'elmls_switcher_position', $switcher_position );
			update_site_option( 'elmls_custom_flag_mapping', $custom_flag_mapping );
			update_site_option( 'elmls_custom_position_x', $custom_position_x );
			update_site_option( 'elmls_custom_position_y', $custom_position_y );
			update_site_option( 'elmls_site_overrides', $site_overrides );
			echo '<div class="updated"><p>' . esc_html__( 'Settings saved.', 'effortless-multisite-language-switcher' ) . '</p></div>';
		}

		// Collect blog IDs for batch fetch.
		$blog_ids = wp_list_pluck( $sites, 'blog_id' );
		$blog_ids = array_map( 'intval', $blog_ids );

		// Batch fetch all site data (locale and blogname).
		$site_data = $this->site_data->get_site_data( $blog_ids );

		?>
		<div class="wrap">
			<h1>EffortLess Multisite Language Switcher</h1>
			<form method="post">
				<?php wp_nonce_field( 'elmls_save_settings_nonce' ); ?>
				<table class="form-table">
					<tr valign="top">
						<th scope="row"><?php esc_html_e( 'Hide Language Switcher', 'effortless-multisite-language-switcher' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="elmls_hide_switcher" <?php checked( $hide_switcher ); ?> />
								<?php esc_html_e( 'Hide language switcher on all sites', 'effortless-multisite-language-switcher' ); ?>
							</label>
						</td>
					</tr>
					<tr valign="top">
						<th scope="row"><?php esc_html_e( 'Switcher Position', 'effortless-multisite-language-switcher' ); ?></th>
						<td>
							<select name="elmls_switcher_position" id="elmls-switcher-position">
								<option value="bottom-right" <?php selected( $switcher_position, 'bottom-right' ); ?>><?php esc_html_e( 'Bottom Right', 'effortless-multisite-language-switcher' ); ?></option>
								<option value="bottom-left" <?php selected( $switcher_position, 'bottom-left' ); ?>><?php esc_html_e( 'Bottom Left', 'effortless-multisite-language-switcher' ); ?></option>
								<option value="top-right" <?php selected( $switcher_position, 'top-right' ); ?>><?php esc_html_e( 'Top Right', 'effortless-multisite-language-switcher' ); ?></option>
								<option value="top-left" <?php selected( $switcher_position, 'top-left' ); ?>><?php esc_html_e( 'Top Left', 'effortless-multisite-language-switcher' ); ?></option>
								<option value="custom" <?php selected( $switcher_position, 'custom' ); ?>><?php esc_html_e( 'Custom (X/Y coordinates)', 'effortless-multisite-language-switcher' ); ?></option>
							</select>
							<div id="elmls-custom-position" style="margin-top: 10px; <?php echo 'custom' !== $switcher_position ? 'display: none;' : ''; ?>">
								<label><?php esc_html_e( 'X Position:', 'effortless-multisite-language-switcher' ); ?> <input type="text" name="elmls_custom_position_x" value="<?php echo esc_attr( $custom_position_x ); ?>" size="5" /> px</label>
								<label style="margin-left: 15px;"><?php esc_html_e( 'Y Position:', 'effortless-multisite-language-switcher' ); ?> <input type="text" name="elmls_custom_position_y" value="<?php echo esc_attr( $custom_position_y ); ?>" size="5" /> px</label>
								<p class="description"><?php esc_html_e( 'Enter pixel values (e.g., 20, 100) or percentages (e.g., 50%)', 'effortless-multisite-language-switcher' ); ?></p>
							</div>
						</td>
					</tr>
					<tr valign="top">
						<th scope="row"><?php esc_html_e( 'Custom Flag Mapping', 'effortless-multisite-language-switcher' ); ?></th>
						<td>
							<textarea name="elmls_custom_flag_mapping" rows="5" cols="50" class="large-text code" placeholder='{"locale_code":"flag_code","fr_FR":"fr"}'><?php echo esc_textarea( $custom_flag_mapping ); ?></textarea>
							<p class="description"><?php esc_html_e( 'Add custom locale to flag code mappings in JSON format.', 'effortless-multisite-language-switcher' ); ?> <?php echo esc_html__( 'Example:', 'effortless-multisite-language-switcher' ); ?> <code>{"fr_FR_custom":"fr","es_AR":"es"}</code></p>
						</td>
					</tr>
					<tr valign="top">
						<th scope="row"><?php esc_html_e( 'Sites', 'effortless-multisite-language-switcher' ); ?></th>
						<td>
							<table class="widefat striped" style="max-width: 900px;">
								<thead>
									<tr>
										<th><?php esc_html_e( 'Site', 'effortless-multisite-language-switcher' ); ?></th>
										<th><?php esc_html_e( 'Hide', 'effortless-multisite-language-switcher' ); ?></th>
										<th><?php esc_html_e( 'Custom flag', 'effortless-multisite-language-switcher' ); ?></th>
										<th><?php esc_html_e( 'Custom URL', 'effortless-multisite-language-switcher' ); ?></th>
									</tr>
								</thead>
								<tbody>
								<?php
								foreach ( $sites as $site ) :
									$blog_id       = (int) $site->blog_id;
									$site_info     = isset( $site_data[ $blog_id ] ) ? $site_data[ $blog_id ] : array(
										'blogname' => "Site #$blog_id",
										'locale'   => 'en_US',
									);
									$blog_name     = $site_info['blogname'];
									$locale        = $site_info['locale'];
									$hide_checked  = in_array( $blog_id, $hidden_sites, true ) ? 'checked' : '';
									$override      = isset( $site_overrides[ $blog_id ] ) ? $site_overrides[ $blog_id ] : array();
									$override_flag = ! empty( $override['flag'] ) ? $override['flag'] : '';
									$override_url  = ! empty( $override['url'] ) ? $override['url'] : '';
									?>
									<tr>
										<td><?php echo esc_html( "$blog_name ($locale)" ); ?></td>
										<td>
											<label>
												<input type="checkbox" name="elmls_hidden_sites[]" value="<?php echo esc_attr( $blog_id ); ?>" <?php echo esc_attr( $hide_checked ); ?> />
											</label>
										</td>
										<td>
											<select name="elmls_site_override_flag[<?php echo esc_attr( $blog_id ); ?>]">
												<option value=""><?php esc_html_e( '— Auto (from locale) —', 'effortless-multisite-language-switcher' ); ?></option>
												<?php foreach ( $available_flags as $flag_code ) : ?>
													<option value="<?php echo esc_attr( $flag_code ); ?>" <?php selected( $override_flag, $flag_code ); ?>><?php echo esc_html( $flag_code ); ?></option>
												<?php endforeach; ?>
											</select>
										</td>
										<td>
											<input type="url" class="regular-text" name="elmls_site_override_url[<?php echo esc_attr( $blog_id ); ?>]" value="<?php echo esc_attr( $override_url ); ?>" placeholder="https://example.com" />
										</td>
									</tr>
								<?php endforeach; ?>
								</tbody>
							</table>
							<p class="description"><?php esc_html_e( 'Custom flag overrides the auto-detected flag icon for that site. Custom URL, if set, is where that flag always links (bypassing the automatic page matching) — useful for pointing a flag to a site outside this network.', 'effortless-multisite-language-switcher' ); ?></p>
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Save Settings', 'effortless-multisite-language-switcher' ), 'primary', 'elmls_save_settings' ); ?>
			</form>
			<script>
			(function() {
				var select = document.getElementById('elmls-switcher-position');
				var customFields = document.getElementById('elmls-custom-position');
				if (select && customFields) {
					select.addEventListener('change', function() {
						customFields.style.display = ('custom' === this.value) ? 'block' : 'none';
					});
				}
			})();
			</script>
		</div>
		<?php
	}
}
