<?php
/**
 * POST handler for “Set active translation”
 * Compatible with schemas WITH or WITHOUT root_post_id
 */

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

add_action(
	'admin_post_awxct_set_active',
	static function () {

		if ( ! current_user_can( 'edit_pages' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'anywarex-clone-translate' ) );
		}

		check_admin_referer( 'awxct_set_active', '_wpnonce_awxct' );

		// IDs (unslash + absint).
		$original_id = isset( $_POST['original_post_id'] )
			? absint( wp_unslash( (string) $_POST['original_post_id'] ) )
			: 0;

		$row_id = isset( $_POST['active_translation_id'] )
			? absint( wp_unslash( (string) $_POST['active_translation_id'] ) )
			: 0;

		// Language code (unslash + sanitize + strict normalize + length limit).
		// Keep only characters we expect for locales: a-z, 0-9, '_' and '-'.
		$language_code = isset( $_POST['language_code'] )
			? sanitize_text_field( wp_unslash( (string) $_POST['language_code'] ) )
			: '';
		$language_code = strtolower( trim( $language_code ) );
		$language_code = preg_replace( '/[^a-z0-9_-]/', '', $language_code );
		$language_code = substr( $language_code, 0, 32 );

		if ( ! $original_id || ! $row_id ) {
			wp_safe_redirect( admin_url( 'admin.php?page=anywarex-clone-translate-mapping' ) );
			exit;
		}

		global $wpdb;

		// Fixed plugin table name (not user input).
		$table = $wpdb->prefix . 'awxct_translations';

		// Normalize language code (tolerant input; case-insensitive, "_" and "-" equal).
		$language_code = str_replace( '_', '-', $language_code );

		// 1) Deactivate all entries for this original + language.
		// IMPORTANT: always use original_post_id for mapping. root_post_id is clone history only.
		$tbl_sql = esc_sql( $table );
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE `" . $tbl_sql . "` SET is_active = 0 WHERE original_post_id = %d AND LOWER(REPLACE(language_code, '_', '-')) = %s",
				$original_id,
				$language_code
			)
		);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared

		// 2) Activate the selected row (by id).
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->update(
			$table,
			array( 'is_active' => 1 ),
			array( 'id' => $row_id ),
			array( '%d' ),
			array( '%d' )
		);

		// Back to the mapping page (preserve filters).
		$back = add_query_arg(
			array(
				'page'          => 'anywarex-clone-translate-mapping',
				'original_id'   => $original_id,
				'language_code' => $language_code,
			),
			admin_url( 'admin.php' )
		);

		wp_safe_redirect( $back );
		exit;
	}
);
