<?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-pro' ),
			__( 'Translations Editor', 'teknotok-ai-translator-pro' ),
			'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;
		}

		if ( empty( $_POST['teknotok_ait_editor_action'] ) ) {
			return;
		}

		$action = sanitize_key( wp_unslash( $_POST['teknotok_ait_editor_action'] ) );

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

			$id = absint( $_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-pro' ), 'success' );
			}
		}

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

			$id = absint( $_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-pro' ), '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( $_GET['per_page'] ) : 25;
		if ( ! in_array( $per_page, array( 25, 50, 100 ), true ) ) {
			$per_page = 25;
		}
		$paged = isset( $_GET['paged'] ) ? max( 1, absint( $_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 ) );

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

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

		$languages = array(
			'en' => 'English',
			'es' => 'Spanish',
			'tr' => 'Turkish',
			'zh' => 'Chinese',
			'hi' => 'Hindi',
			'ar' => 'Arabic',
			'pt' => 'Portuguese',
			'bn' => 'Bengali',
			'ru' => 'Russian',
			'ja' => 'Japanese',
			'fr' => 'French',
		);

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

			<div class="teknotok-memory-stats" aria-label="<?php esc_attr_e( 'Translation memory summary', 'teknotok-ai-translator-pro' ); ?>">
				<div>
					<strong><?php echo esc_html( number_format_i18n( $total_items ) ); ?></strong>
					<span><?php esc_html_e( 'visible memory records', 'teknotok-ai-translator-pro' ); ?></span>
				</div>
				<?php foreach ( $memory_counts as $count_row ) : ?>
					<div>
						<strong><?php echo esc_html( strtoupper( $count_row->target_lang ) ); ?></strong>
						<span><?php echo esc_html( number_format_i18n( (int) $count_row->count ) ); ?></span>
					</div>
				<?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-pro' ); ?></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-pro' ); ?>" />
						<select name="per_page">
							<option value="25" <?php selected( $per_page, 25 ); ?>><?php esc_html_e( '25 per page', 'teknotok-ai-translator-pro' ); ?></option>
							<option value="50" <?php selected( $per_page, 50 ); ?>><?php esc_html_e( '50 per page', 'teknotok-ai-translator-pro' ); ?></option>
							<option value="100" <?php selected( $per_page, 100 ); ?>><?php esc_html_e( '100 per page', 'teknotok-ai-translator-pro' ); ?></option>
						</select>
						<input type="submit" class="button button-secondary" value="<?php esc_attr_e( 'Filter', 'teknotok-ai-translator-pro' ); ?>" />
					</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-pro' ); ?></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-pro' ); ?></th>
								<th><?php esc_html_e( 'Language', 'teknotok-ai-translator-pro' ); ?></th>
								<th><?php esc_html_e( 'Source Text', 'teknotok-ai-translator-pro' ); ?></th>
								<th><?php esc_html_e( 'Translation', 'teknotok-ai-translator-pro' ); ?></th>
								<th><?php esc_html_e( 'Last Used', 'teknotok-ai-translator-pro' ); ?></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-pro' ); ?>
												</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-pro' ); ?>');">
													<?php esc_html_e( 'Delete', 'teknotok-ai-translator-pro' ); ?>
												</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-pro' ),
									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
	}
}
