<?php
namespace TeknoTok\AiTranslator\Admin;

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

use TeknoTok\AiTranslator\Database\MemoryRepository;

/**
 * Controller to manage the admin Translations Editor screen.
 */
class EditorController {
	/**
	 * Plugin coordinator.
	 *
	 * @var \TeknoTok\AiTranslator\Plugin
	 */
	private $plugin;

	/**
	 * Constructor.
	 *
	 * @param \TeknoTok\AiTranslator\Plugin $plugin Plugin instance.
	 */
	public function __construct( $plugin ) {
		$this->plugin = $plugin;

		add_action( 'admin_menu', array( $this, 'register_menu' ), 25 );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
	}

	/**
	 * Register submenu.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_submenu_page(
			'teknotok-ait',
			__( 'Translations Editor', 'teknotok-ai-translator' ),
			__( 'Translations Editor', 'teknotok-ai-translator' ),
			'manage_options',
			'teknotok-ait-editor',
			array( $this, 'render_editor' )
		);
	}

	/**
	 * Handle manual overrides or deletions.
	 *
	 * @return void
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$action = sanitize_key( wp_unslash( $_POST['teknotok_ait_editor_action'] ?? '' ) );
		if ( empty( $action ) ) {
			return;
		}

		if ( 'save_translation' === $action ) {
			check_admin_referer( 'teknotok_ait_editor_nonce' );

			$id = absint( wp_unslash( $_POST['translation_id'] ?? 0 ) );
			$translated = sanitize_textarea_field( wp_unslash( $_POST['translated_text'] ?? '' ) );

			if ( $id && ! empty( $translated ) ) {
				global $wpdb;
				$table = $wpdb->prefix . 'teknotok_translations';
				$wpdb->update(
					$table,
					array( 'translated_text' => $translated ),
					array( 'id' => $id ),
					array( '%s' ),
					array( '%d' )
				);
				add_settings_error( 'teknotok_ait_editor', 'saved', __( 'Translation updated successfully.', 'teknotok-ai-translator' ), 'success' );
			}
		}

		if ( 'delete_translation' === $action ) {
			check_admin_referer( 'teknotok_ait_editor_nonce' );

			$id = absint( wp_unslash( $_POST['translation_id'] ?? 0 ) );

			if ( $id ) {
				global $wpdb;
				$table = $wpdb->prefix . 'teknotok_translations';
				$wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) );
				add_settings_error( 'teknotok_ait_editor', 'deleted', __( 'Translation record deleted.', 'teknotok-ai-translator' ), 'success' );
			}
		}
	}

	/**
	 * Render translations editor interface.
	 *
	 * @return void
	 */
	public function render_editor() {
		global $wpdb;

		$search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
		$lang_filter = isset( $_GET['lang_code'] ) ? sanitize_key( wp_unslash( $_GET['lang_code'] ) ) : '';
		$per_page = isset( $_GET['per_page'] ) ? absint( wp_unslash( $_GET['per_page'] ) ) : 25;
		if ( ! in_array( $per_page, array( 25, 50, 100 ), true ) ) {
			$per_page = 25;
		}
		$paged = isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1;
		$offset = ( $paged - 1 ) * $per_page;
		$like = ! empty( $search ) ? '%' . $wpdb->esc_like( $search ) . '%' : '';
		$table = $wpdb->prefix . 'teknotok_translations';

		// Query is prepared in a single static statement to satisfy security scanners and prevent SQL injection.
		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$table}
				 WHERE source_text NOT LIKE '%%<!-- wp:%%' 
				 AND (%s = '' OR source_text LIKE %s OR translated_text LIKE %s)
				 AND (%s = '' OR target_lang = %s)
				 ORDER BY id DESC LIMIT %d OFFSET %d",
				$search,
				$like,
				$like,
				$lang_filter,
				$lang_filter,
				$per_page,
				$offset
			)
		);

		$total_items = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table}
				 WHERE source_text NOT LIKE '%%<!-- wp:%%'
				 AND (%s = '' OR source_text LIKE %s OR translated_text LIKE %s)
				 AND (%s = '' OR target_lang = %s)",
				$search,
				$like,
				$like,
				$lang_filter,
				$lang_filter
			)
		);
		$total_pages = max( 1, (int) ceil( $total_items / $per_page ) );

		$total_memory_items = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table}
				 WHERE source_text NOT LIKE '%%<!-- wp:%%'
				 AND (%s = '' OR source_text LIKE %s OR translated_text LIKE %s)",
				$search,
				$like,
				$like
			)
		);

		$memory_counts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT target_lang, COUNT(*) as count FROM {$table}
				 WHERE source_text NOT LIKE '%%<!-- wp:%%'
				 AND (%s = '' OR source_text LIKE %s OR translated_text LIKE %s)
				 GROUP BY target_lang ORDER BY target_lang ASC",
				$search,
				$like,
				$like
			)
		);

		$settings = get_option( 'teknotok_ait_settings', array() );
		$targets = $this->sort_language_codes_by_priority( $settings['target_languages'] ?? array() );

		$languages = \TeknoTok\AiTranslator\Plugin::get_supported_languages();
		$memory_counts = $this->sort_memory_counts_by_priority( $memory_counts );
		$memory_count_map = array();
		$memory_count_codes = array();
		foreach ( $memory_counts as $count_row ) {
			$count_lang = sanitize_key( $count_row->target_lang );
			$memory_count_map[ $count_lang ] = (int) $count_row->count;
			$memory_count_codes[] = $count_lang;
		}
		$stat_language_codes = array_values( array_unique( array_filter( array_merge( $targets, $memory_count_codes, array( $lang_filter ) ) ) ) );
		$stat_language_codes = $this->sort_language_codes_by_priority( $stat_language_codes );
		$base_filter_args = array(
			'page' => 'teknotok-ait-editor',
			'per_page' => $per_page,
		);
		if ( '' !== $search ) {
			$base_filter_args['s'] = $search;
		}

		?>
		<div class="wrap teknotok-ait-wrap">
			<h1><?php esc_html_e( 'Translations Memory Editor', 'teknotok-ai-translator' ); ?></h1>
			<?php settings_errors(); ?>

			<div class="teknotok-memory-stats" aria-label="<?php esc_attr_e( 'Translation memory summary', 'teknotok-ai-translator' ); ?>">
				<a class="teknotok-memory-stat-card <?php echo esc_attr( '' === $lang_filter ? 'is-active' : '' ); ?>" href="<?php echo esc_url( add_query_arg( $base_filter_args, admin_url( 'admin.php' ) ) ); ?>" aria-current="<?php echo esc_attr( '' === $lang_filter ? 'page' : 'false' ); ?>">
					<strong><?php echo esc_html( number_format_i18n( $total_memory_items ) ); ?></strong>
					<span>
						<?php
						echo esc_html(
							'' === $search
								? __( 'all memory records', 'teknotok-ai-translator' )
								: __( 'matching records', 'teknotok-ai-translator' )
						);
						?>
					</span>
				</a>
				<?php foreach ( $stat_language_codes as $target_lang ) : ?>
					<?php
					$language_args = array_merge( $base_filter_args, array( 'lang_code' => $target_lang ) );
					$is_active = $lang_filter === $target_lang;
					?>
					<a class="teknotok-memory-stat-card <?php echo esc_attr( $is_active ? 'is-active' : '' ); ?>" href="<?php echo esc_url( add_query_arg( $language_args, admin_url( 'admin.php' ) ) ); ?>" aria-current="<?php echo esc_attr( $is_active ? 'page' : 'false' ); ?>">
						<strong><?php echo esc_html( strtoupper( $target_lang ) ); ?></strong>
						<span><?php echo esc_html( number_format_i18n( $memory_count_map[ $target_lang ] ?? 0 ) ); ?></span>
					</a>
				<?php endforeach; ?>
			</div>

			<div class="teknotok-editor-toolbar">
				<form method="get" action="">
					<input type="hidden" name="page" value="teknotok-ait-editor" />
					<div class="teknotok-editor-filters">
						<select name="lang_code">
							<option value=""><?php esc_html_e( 'All Languages', 'teknotok-ai-translator' ); ?></option>
							<?php foreach ( $targets as $target_code ) : ?>
								<option value="<?php echo esc_attr( $target_code ); ?>" <?php selected( $lang_filter, $target_code ); ?>>
									<?php echo esc_html( $languages[ $target_code ] ?? $target_code ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search translations...', 'teknotok-ai-translator' ); ?>" />
						<select name="per_page">
							<option value="25" <?php selected( $per_page, 25 ); ?>><?php esc_html_e( '25 per page', 'teknotok-ai-translator' ); ?></option>
							<option value="50" <?php selected( $per_page, 50 ); ?>><?php esc_html_e( '50 per page', 'teknotok-ai-translator' ); ?></option>
							<option value="100" <?php selected( $per_page, 100 ); ?>><?php esc_html_e( '100 per page', 'teknotok-ai-translator' ); ?></option>
						</select>
						<input type="submit" class="button button-secondary" value="<?php esc_attr_e( 'Filter', 'teknotok-ai-translator' ); ?>" />
					</div>
				</form>
			</div>

			<?php if ( empty( $results ) ) : ?>
				<div class="empty-state">
					<span class="dashicons dashicons-search"></span>
					<p><?php esc_html_e( 'No translations found in memory.', 'teknotok-ai-translator' ); ?></p>
				</div>
			<?php else : ?>
				<div class="teknotok-memory-table-wrap">
					<table class="widefat striped modern-table teknotok-memory-table">
						<thead>
							<tr>
								<th><?php esc_html_e( 'ID', 'teknotok-ai-translator' ); ?></th>
								<th><?php esc_html_e( 'Language', 'teknotok-ai-translator' ); ?></th>
								<th><?php esc_html_e( 'Source Text', 'teknotok-ai-translator' ); ?></th>
								<th><?php esc_html_e( 'Translation', 'teknotok-ai-translator' ); ?></th>
								<th><?php esc_html_e( 'Last Used', 'teknotok-ai-translator' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $results as $row ) : ?>
								<tr>
									<td><strong>#<?php echo esc_html( $row->id ); ?></strong></td>
									<td><span class="badge badge-info"><?php echo esc_html( strtoupper( $row->target_lang ) ); ?></span></td>
									<td class="teknotok-memory-source"><?php echo esc_html( $row->source_text ); ?></td>
									<td class="teknotok-memory-translation">
										<form method="post" action="" class="translation-form">
											<?php wp_nonce_field( 'teknotok_ait_editor_nonce' ); ?>
											<input type="hidden" name="translation_id" value="<?php echo esc_attr( $row->id ); ?>" />
											<textarea name="translated_text"><?php echo esc_textarea( $row->translated_text ); ?></textarea>
											<div class="teknotok-memory-actions">
												<button type="submit" name="teknotok_ait_editor_action" value="save_translation" class="button button-primary">
													<?php esc_html_e( 'Save', 'teknotok-ai-translator' ); ?>
												</button>
												<button type="submit" name="teknotok_ait_editor_action" value="delete_translation" class="button button-link-delete" onclick="return confirm('<?php esc_attr_e( 'Delete this translation record from memory?', 'teknotok-ai-translator' ); ?>');">
													<?php esc_html_e( 'Delete', 'teknotok-ai-translator' ); ?>
												</button>
											</div>
										</form>
									</td>
									<td class="time-col">
										<?php
										$time_str = ! empty( $row->last_used ) ? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $row->last_used ) ) : '--';
										echo esc_html( $time_str );
										?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>

				<?php if ( $total_pages > 1 ) : ?>
					<div class="tablenav bottom teknotok-memory-pagination">
						<div class="tablenav-pages">
							<span class="displaying-num">
								<?php
								printf(
									/* translators: %s: number of items */
									esc_html__( '%s items', 'teknotok-ai-translator' ),
									esc_html( number_format_i18n( $total_items ) )
								);
								?>
							</span>
							<?php
							echo wp_kses_post(
								paginate_links(
									array(
										'base'      => add_query_arg( 'paged', '%#%' ),
										'format'    => '',
										'current'   => $paged,
										'total'     => $total_pages,
										'prev_text' => '&lsaquo;',
										'next_text' => '&rsaquo;',
									)
								)
							);
							?>
						</div>
					</div>
				<?php endif; ?>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Sort language codes by customer-facing priority.
	 *
	 * @param array $codes Language codes.
	 * @return array
	 */
	private function sort_language_codes_by_priority( $codes ) {
		return \TeknoTok\AiTranslator\Plugin::sort_language_codes_by_priority( $codes, \TeknoTok\AiTranslator\Plugin::get_supported_languages() );
	}

	/**
	 * Sort memory count rows by customer-facing language priority.
	 *
	 * @param array $memory_counts Count rows from the database.
	 * @return array
	 */
	private function sort_memory_counts_by_priority( $memory_counts ) {
		$priority = $this->get_language_priority_order();
		$indexed = array_flip( $priority );

		usort(
			$memory_counts,
			function( $left, $right ) use ( $indexed ) {
				$left_lang = sanitize_key( $left->target_lang ?? '' );
				$right_lang = sanitize_key( $right->target_lang ?? '' );
				$left_index = $indexed[ $left_lang ] ?? PHP_INT_MAX;
				$right_index = $indexed[ $right_lang ] ?? PHP_INT_MAX;

				if ( $left_index === $right_index ) {
					return strcmp( $left_lang, $right_lang );
				}

				return $left_index <=> $right_index;
			}
		);

		return $memory_counts;
	}

	/**
	 * Customer-facing language priority used in admin language controls.
	 *
	 * @return array
	 */
	private function get_language_priority_order() {
		return \TeknoTok\AiTranslator\Plugin::get_language_priority_order();
	}
}
