<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $wpdb;

/**
 * IMPORTANT:
 * We do NOT use %i to stay compatible with WP < 6.2.
 * Table identifiers are strictly validated (alnum + underscore) and then interpolated.
 * Values ALWAYS use $wpdb->prepare().
 */

/* ---------- Helpers ---------- */

/**
 * Blog-aware cache key helper.
 *
 * @param string $suffix Key suffix.
 * @return string
 */
function awxct_view_cache_key( $suffix ) {
	$blog_id = function_exists( 'get_current_blog_id' ) ? (int) get_current_blog_id() : 0;
	return 'awxct_' . $blog_id . '_langs_view_' . (string) $suffix;
}

/**
 * Return the plugin languages table (validated identifier).
 *
 * @return string
 */
function awxct_view_languages_table_name() {
	global $wpdb;

	$table = (string) ( $wpdb->prefix . 'awxct_languages' );

	// Hard safety: table identifiers are always alnum/underscore in WP.
	if ( ! preg_match( '/^[A-Za-z0-9_]+$/', $table ) ) {
		return '';
	}

	return $table;
}

/**
 * Cached helper for computed values.
 *
 * @param string   $cache_suffix Cache key suffix.
 * @param int      $ttl          Cache TTL in seconds.
 * @param callable $callback     Computes the value.
 * @return mixed
 */
function awxct_view_cached( $cache_suffix, $ttl, $callback ) {
	$key = awxct_view_cache_key( 'c_' . (string) $cache_suffix );
	$val = wp_cache_get( $key, 'awxct' );

	if ( false !== $val ) {
		return $val;
	}

	$val = is_callable( $callback ) ? call_user_func( $callback ) : null;

	wp_cache_set( $key, $val, 'awxct', (int) $ttl );
	return $val;
}

/**
 * Determine default language code from DB (cached).
 *
 * @param string $table Validated table identifier.
 * @return string|null
 */
function awxct_view_db_default_lang_code( $table ) {
	if ( '' === (string) $table ) {
		return null;
	}

	$code = awxct_view_cached(
		'default_code',
		30,
		static function () use ( $table ) {
			global $wpdb;

			$table_sql = esc_sql( $table );

			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
			return $wpdb->get_var( "SELECT LOWER(code) FROM `{$table_sql}` WHERE COALESCE(is_default,0)=1 LIMIT 1" );
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		}
	);

	$code = $code ? strtolower( (string) $code ) : null;
	return $code;
}

/**
 * Load languages list (cached).
 *
 * @param string $table Validated table identifier.
 * @return array
 */
function awxct_view_load_languages_rows( $table ) {
	if ( '' === (string) $table ) {
		return array();
	}

	$rows = awxct_view_cached(
		'rows_all',
		30,
		static function () use ( $table ) {
			global $wpdb;

			$table_sql = esc_sql( $table );

			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
			return $wpdb->get_results(
				"SELECT id,
						code,
						native_name,
						english_name,
						COALESCE(active, 0)     AS active,
						COALESCE(is_default, 0) AS is_default
					FROM `{$table_sql}`
				ORDER BY (COALESCE(NULLIF(native_name,''), NULLIF(english_name,''), code)) ASC"
			);
			// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		}
	);

	return is_array( $rows ) ? $rows : array();
}

/* ---------- Load languages (cached) ---------- */

$table = awxct_view_languages_table_name();
$rows  = awxct_view_load_languages_rows( $table );

$default_code           = awxct_view_db_default_lang_code( $table );
?>
<div class="wrap">
	<?php
	// Errors / status messages from handlers (languages-save.php).
	settings_errors( 'awxct_langs' );

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$updated = isset( $_GET['updated'] ) ? sanitize_text_field( wp_unslash( $_GET['updated'] ) ) : '';
	if ( '1' === $updated ) {
		$msg = __( 'Languages updated.', 'anywarex-clone-translate' );

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! empty( $_GET['op'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$op = sanitize_key( wp_unslash( $_GET['op'] ) );

			if ( 'insert' === $op ) {
				$msg = __( 'Language added.', 'anywarex-clone-translate' );
			} elseif ( 'update' === $op ) {
				$msg = __( 'Languages updated.', 'anywarex-clone-translate' );
			} elseif ( 'delete' === $op ) {
				$msg = __( 'Language deleted.', 'anywarex-clone-translate' );
			} elseif ( 'display_saved' === $op ) {
				$msg = __( 'Language switcher display settings saved.', 'anywarex-clone-translate' );
			}
		}

		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( ! empty( $_GET['err'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$err = sanitize_key( wp_unslash( $_GET['err'] ) );

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$code_param = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : '';

		$map = array(
			'empty_code'            => __( 'Please enter a valid language code.', 'anywarex-clone-translate' ),
			'duplicate'             => sprintf(
				/* translators: %s: The language code that already exists. */
				__( 'Language code already exists: %s', 'anywarex-clone-translate' ),
				esc_html( $code_param )
			),
			'bad_id'                => __( 'Invalid language id.', 'anywarex-clone-translate' ),
			'cannot_delete_default' => __( 'You cannot delete the default language.', 'anywarex-clone-translate' ),
			'cannot_delete_active'  => __( 'You cannot delete an active language. Disable it first.', 'anywarex-clone-translate' ),
			'default_must_be_active' => __( 'The default language must be active. Please activate it first.', 'anywarex-clone-translate' ),
		);

		$text = isset( $map[ $err ] ) ? $map[ $err ] : __( 'Unknown error.', 'anywarex-clone-translate' );

		echo '<div class="notice notice-error"><p>' . esc_html( $text ) . '</p></div>';
	}

	if ( function_exists( 'awxct_admin_header' ) ) {
		awxct_admin_header( __( 'Manage Languages', 'anywarex-clone-translate' ) );
	} else {
		echo '<h1>' . esc_html__( 'Manage Languages', 'anywarex-clone-translate' ) . '</h1>';
	}
	?>

	<!-- Language Switcher Display (Settings-API / options.php) -->
	<h2 class="title" style="margin-top:.5rem;">
		<?php esc_html_e( 'Language Switcher Display', 'anywarex-clone-translate' ); ?>
	</h2>
	<p class="description">
		<?php
		esc_html_e(
			'Configure how and where the frontend language switcher is shown (e.g. EN-US, EN, English, with or without flag).',
			'anywarex-clone-translate'
		);
		?>
	</p>

	<form action="options.php" method="post" class="awxct-plg-ct-form" style="margin-bottom:16px;">
		<?php
		settings_fields( 'anywarex-clone-translate' );
		do_settings_sections( 'anywarex-clone-translate' );
		submit_button( __( 'Save display setting', 'anywarex-clone-translate' ) );
		?>
	</form>

	<hr />

	<!-- Existing languages -->
	<h2 class="title" style="margin-top:.5rem;">
		<?php esc_html_e( 'Existing languages', 'anywarex-clone-translate' ); ?>
	</h2>

	<form method="post"
		action="<?php echo esc_url( add_query_arg( 'action', 'awxct_languages_save', admin_url( 'admin-post.php' ) ) ); ?>">
		<?php
		wp_nonce_field( 'awxct_languages_save', 'awxct_nonce' );
		?>

		<table class="widefat fixed striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Code', 'anywarex-clone-translate' ); ?></th>
					<th><?php esc_html_e( 'Native name', 'anywarex-clone-translate' ); ?></th>
					<th><?php esc_html_e( 'English name', 'anywarex-clone-translate' ); ?></th>
					<th style="width:120px;"><?php esc_html_e( 'Active', 'anywarex-clone-translate' ); ?></th>
					<th style="width:120px;"><?php esc_html_e( 'Default', 'anywarex-clone-translate' ); ?></th>
					<th style="width:120px;"><?php esc_html_e( 'Delete', 'anywarex-clone-translate' ); ?></th>
				</tr>
			</thead>
			<tbody>
			<?php if ( ! empty( $rows ) ) : ?>
				<?php foreach ( $rows as $lang ) : ?>
					<?php
					$is_default = ( isset( $lang->is_default ) && (int) $lang->is_default === 1 );
					$is_active  = ( isset( $lang->active ) && (int) $lang->active === 1 );

					// Default can only be selected when the language is active.
					$disable_default = ( ! $is_active && ! $is_default );
					$default_title   = $disable_default
						? __( 'Activate this language before setting it as default.', 'anywarex-clone-translate' )
						: '';

					$lang_code  = isset( $lang->code ) ? strtolower( (string) $lang->code ) : '';
					$is_foreign = ( $lang_code !== (string) $default_code );

					$disable_activate = false;
					$disable_title    = '';
					?>
					<tr>
						<td><code><?php echo esc_html( (string) ( $lang->code ?? '' ) ); ?></code></td>
						<td><?php echo esc_html( (string) ( $lang->native_name ?: ( $lang->english_name ?: ( $lang->code ?? '' ) ) ) ); ?></td>
						<td><?php echo esc_html( (string) ( $lang->english_name ?: '—' ) ); ?></td>
						<td>
							<input type="checkbox"
								name="awxct_lang_active[<?php echo esc_attr( (string) (int) ( $lang->id ?? 0 ) ); ?>]"
								value="1"
								<?php checked( $is_active, true ); ?>
								<?php if ( $disable_activate ) : ?>
									disabled="disabled"
									aria-disabled="true"
									title="<?php echo esc_attr( $disable_title ); ?>"
								<?php endif; ?>
							/>
						</td>
						<td>
							<input type="radio"
								name="awxct_lang_default"
								value="<?php echo esc_attr( (string) (int) ( $lang->id ?? 0 ) ); ?>"
								<?php checked( $is_default, true ); ?>
								<?php if ( $disable_default ) : ?>
									disabled="disabled"
									aria-disabled="true"
									title="<?php echo esc_attr( $default_title ); ?>"
								<?php endif; ?>
							/>
						</td>
						<td>
							<?php
							$can_delete = ( ! $is_default && ! $is_active );
							if ( $can_delete ) :
								$delete_action = add_query_arg( 'action', 'awxct_language_delete', admin_url( 'admin-post.php' ) );
								?>
								<?php
								$del_url = wp_nonce_url(
									add_query_arg(
										array(
											'action' => 'awxct_language_delete',
											'id'     => (int) $lang->id,
											'code'   => $code,
										),
										admin_url( 'admin-post.php' )
									),
									'awxct_language_delete',
									'awxct_nonce'
								);
								?>
								<a class="button button-small button-link-delete"
									href="<?php echo esc_url( $del_url ); ?>"
									onclick="return confirm('<?php echo esc_js( __( 'Delete this language?', 'anywarex-clone-translate' ) ); ?>');">
									<?php esc_html_e( 'Delete', 'anywarex-clone-translate' ); ?>
								</a>
							<?php else : ?>
								<span class="description" title="<?php echo esc_attr( __( 'Active or default languages cannot be deleted.', 'anywarex-clone-translate' ) ); ?>">—</span>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php else : ?>
				<tr>
					<td colspan="6">
						<em><?php esc_html_e( 'No languages found.', 'anywarex-clone-translate' ); ?></em>
					</td>
				</tr>
			<?php endif; ?>
			</tbody>
		</table>

		<p class="submit">
			<button type="submit" class="button button-primary">
				<?php esc_html_e( 'Save Changes', 'anywarex-clone-translate' ); ?>
			</button>
		</p>
	</form>

	<!-- Add language -->
	<h2 class="title" style="margin-top:.5rem;">
		<?php esc_html_e( 'Add language', 'anywarex-clone-translate' ); ?>
	</h2>

	<form method="post"
		action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
		class="awxct-plg-ct-form"
		style="margin-bottom:16px;">
		<?php
		wp_nonce_field( 'awxct_language_add', 'awxct_nonce' );
		?>
		<input type="hidden" name="action" value="awxct_language_add" />

		<table class="form-table" role="presentation">
			<tr>
				<th scope="row">
					<label for="awxct_lang_code"><?php esc_html_e( 'Language code', 'anywarex-clone-translate' ); ?></label>
				</th>
				<td>
					<input type="text"
						id="awxct_lang_code"
						name="code"
						class="regular-text"
						placeholder="en-us, de-de, fr-fr" />
					<p class="description">
						<?php esc_html_e( 'Use a valid locale or language code (e.g. en-us, de-de).', 'anywarex-clone-translate' ); ?>
					</p>
				</td>
			</tr>

			<tr>
				<th scope="row">
					<label for="awxct_lang_native"><?php esc_html_e( 'Native name', 'anywarex-clone-translate' ); ?></label>
				</th>
				<td>
					<input type="text"
						id="awxct_lang_native"
						name="native_name"
						class="regular-text"
						placeholder="Deutsch, Français, English" />
					<p class="description">
						<?php esc_html_e( 'Name of the language in its own language (optional).', 'anywarex-clone-translate' ); ?>
					</p>
				</td>
			</tr>

			<tr>
				<th scope="row">
					<label for="awxct_lang_english"><?php esc_html_e( 'English name', 'anywarex-clone-translate' ); ?></label>
				</th>
				<td>
					<input type="text"
						id="awxct_lang_english"
						name="english_name"
						class="regular-text"
						placeholder="German, French, English" />
					<p class="description">
						<?php esc_html_e( 'Name of the language in English (optional).', 'anywarex-clone-translate' ); ?>
					</p>
				</td>
			</tr>
		</table>

		<?php submit_button( __( 'Add language', 'anywarex-clone-translate' ) ); ?>
	</form>
</div>