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

if ( ! function_exists( 'awxct_validate_ident' ) ) {
	/**
	 * Validate SQL identifier (table/column names).
	 *
	 * @param string $ident Identifier.
	 * @return string Validated identifier or empty string.
	 */
	function awxct_validate_ident( $ident ): string {
		$ident = (string) $ident;
		return preg_match( '/^[A-Za-z0-9_]+$/', $ident ) ? $ident : '';
	}
}

add_action(
	'admin_post_awxct_save_mapping',
	function () {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'forbidden', 'anywarex-clone-translate' ) );
		}
		check_admin_referer( 'awxct_map_save', 'awxct_nonce' );

		global $wpdb;

		// Whitelisted table name (not user input) + validated for safe interpolation.
		$tbl_trans_raw = $wpdb->prefix . 'awxct_translations';
		$tbl_trans     = awxct_validate_ident( $tbl_trans_raw );
		$tbl_trans_sql = esc_sql( $tbl_trans );

		if ( '' === $tbl_trans ) {
			wp_die( esc_html__( 'Configuration error: invalid table identifier.', 'anywarex-clone-translate' ) );
		}

		$original_id         = isset( $_POST['original_post_id'] ) ? absint( wp_unslash( $_POST['original_post_id'] ) ) : 0;
		$translation_post_id = isset( $_POST['translation_post_id'] ) ? absint( wp_unslash( $_POST['translation_post_id'] ) ) : 0;

		// IMPORTANT: sanitize in the same expression (PluginCheck).
		$lang_code_raw = isset( $_POST['lang_code'] )
			? sanitize_key( (string) wp_unslash( $_POST['lang_code'] ) )
			: '';

		// IMPORTANT:
		// - DB should store only lowercase + '-' (e.g. en-us)
		// - comparisons must be tolerant, but storage must be normalized
		if ( function_exists( 'awxct_normalize_lang_code' ) ) {
			$lang_code = awxct_normalize_lang_code( $lang_code_raw );
		} else {
			$lang_code = strtolower( str_replace( '_', '-', trim( (string) $lang_code_raw ) ) );
		}

		if ( ! $original_id || ! $lang_code || ! $translation_post_id ) {
			add_settings_error(
				'awxct_map',
				'awxct_map_missing',
				__( 'Missing required fields.', 'anywarex-clone-translate' ),
				'error'
			);

			wp_safe_redirect(
				admin_url(
					'admin.php?page=anywarex-clone-translate-mapping&original_id=' . (int) $original_id
				)
			);
			exit;
		}

		// Insert (skip if exact mapping already exists).
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$exists_id = (int) $wpdb->get_var(
			$wpdb->prepare(
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT id FROM `{$tbl_trans_sql}` WHERE original_post_id = %d AND LOWER(REPLACE(language_code,'_','-')) = %s AND translated_post_id = %d LIMIT 1",
				$original_id,
				$lang_code,
				$translation_post_id
			)
		);

		if ( ! $exists_id ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->insert(
				$tbl_trans,
				array(
					'original_post_id'   => (int) $original_id,
					'language_code'      => (string) $lang_code,
					'translated_post_id' => (int) $translation_post_id,
					'is_active'          => 1,
				),
				array( '%d', '%s', '%d', '%d' )
			);

			// Invalidate any caches that might rely on this mapping.
			wp_cache_delete( 'awxct_mapping_' . $original_id, 'awxct' );
		}

		wp_safe_redirect(
			admin_url(
				'admin.php?page=anywarex-clone-translate-mapping&original_id=' . (int) $original_id
			)
		);
		exit;
	}
);
