<?php
namespace TeknoTok\AiTranslator\Admin;

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

use TeknoTok\AiTranslator\Database\JobRepository;
use TeknoTok\AiTranslator\Database\MemoryRepository;
use TeknoTok\AiTranslator\Queue\QueueManager;

/**
 * Controller to manage the system status, diagnostics, and queue logs UI.
 */
class DiagnosticController {
	/**
	 * 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' ), 30 );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'wp_ajax_teknotok_ait_get_queue_status', array( $this, 'ajax_get_queue_status' ) );
		add_action( 'wp_ajax_teknotok_ait_run_queue_admin', array( $this, 'ajax_run_queue_admin' ) );
		add_action( 'wp_ajax_teknotok_ait_resume_queue', array( $this, 'ajax_resume_queue' ) );
		add_action( 'wp_ajax_teknotok_ait_retry_failed_jobs', array( $this, 'ajax_retry_failed_jobs' ) );
	}

	/**
	 * Register submenu.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_submenu_page(
			'teknotok-ait',
			__( 'System Status', 'teknotok-ai-translator-pro' ),
			__( 'System Status', 'teknotok-ai-translator-pro' ),
			'manage_options',
			'teknotok-ait-diagnostics',
			array( $this, 'render_diagnostics' )
		);
	}

	/**
	 * Handle admin commands for queues.
	 *
	 * @return void
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

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

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

		if ( 'clear_logs' === $action ) {
			check_admin_referer( 'teknotok_ait_diag_nonce' );
			\TeknoTok\AiTranslator\Utils\Logger::clear_logs();
			add_settings_error( 'teknotok_ait_diagnostics', 'logs_cleared', __( 'Debug log file cleared.', 'teknotok-ai-translator-pro' ), 'success' );
		}
	}

	/**
	 * AJAX endpoint to retrieve queue status counts dynamically.
	 *
	 * @return void
	 */
	public function ajax_get_queue_status() {
		// Verify nonce
		if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['nonce'] ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		$queue_counts = JobRepository::get_counts();
		$queue_counts['retryable_failed'] = JobRepository::get_retryable_failed_count();
		$queue_counts['paused'] = get_option( 'teknotok_ait_queue_paused', '0' ) === '1';
		$queue_counts['pause_reason'] = get_option( 'teknotok_ait_queue_pause_reason', '' );
		wp_send_json_success( $queue_counts );
	}

	/**
	 * AJAX endpoint to run the queue worker from the admin dashboard automatically.
	 *
	 * @return void
	 */
	public function ajax_run_queue_admin() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		if ( function_exists( 'set_time_limit' ) ) {
			@set_time_limit( 0 );
		}

		$this->plugin->queue->process_queue();

		wp_send_json_success();
	}

	/**
	 * AJAX endpoint to resume queue execution after license/quota has been fixed.
	 *
	 * @return void
	 */
	public function ajax_resume_queue() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$reset_jobs = QueueManager::resume_after_provider_limit();

		wp_send_json_success(
			array(
				'reset_jobs' => $reset_jobs,
			)
		);
	}

	/**
	 * AJAX endpoint to retry failed jobs after timeout/server issues are fixed.
	 *
	 * @return void
	 */
	public function ajax_retry_failed_jobs() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'teknotok_ait_ajax' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Permission denied', 403 );
		}

		$reset_jobs = QueueManager::retry_failed_jobs();

		wp_send_json_success(
			array(
				'reset_jobs' => $reset_jobs,
			)
		);
	}

	/**
	 * Render system status dashboard.
	 *
	 * @return void
	 */
	public function render_diagnostics() {
		global $wpdb;

		$queue_counts = JobRepository::get_counts();
		$queue_paused = get_option( 'teknotok_ait_queue_paused', '0' ) === '1';
		$queue_pause_reason = get_option( 'teknotok_ait_queue_pause_reason', '' );
		$license_status = get_option( 'teknotok_ait_license_status', array() );
		$license_label = $license_status['status'] ?? 'inactive';
		if ( 'active' === $license_label && ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			$license_label = 'expired';
		}

		// Retrieve latest 10 log entries (jobs with failures or status)
		$jobs_table = $wpdb->prefix . 'teknotok_jobs';
		$failed_jobs = $wpdb->get_results( "SELECT * FROM {$jobs_table} WHERE status = 'failed' OR retry_count > 0 ORDER BY updated_at DESC LIMIT 10" );

		?>
		<div class="wrap teknotok-ait-wrap">
			<h1><?php esc_html_e( 'System Status & Diagnostics', 'teknotok-ai-translator-pro' ); ?></h1>
			<?php settings_errors(); ?>

			<?php
			$pending = intval( $queue_counts['pending'] );
			$processing = intval( $queue_counts['processing'] );
			$completed = intval( $queue_counts['completed'] );
			$failed = intval( $queue_counts['failed'] );
			$retryable_failed = JobRepository::get_retryable_failed_count();
			$total = $pending + $processing + $completed + $failed;
			?>

			<?php if ( $pending > 0 || $processing > 0 || ( 0 === $total && isset( $_GET['setup'] ) && 'start' === $_GET['setup'] ) ) : ?>
				<div id="queue-calc-banner" class="notice notice-info" style="border-left-color: #6366f1; background: #ffffff; padding: 20px; border-radius: 12px; margin-top: 15px; margin-bottom: 20px; border: 1px solid #e2e8f0; display: flex; align-items: center; gap: 15px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);">
					<span id="queue-calc-icon" class="dashicons <?php echo $queue_paused ? 'dashicons-warning' : 'dashicons-update spin'; ?>" style="color: #6366f1; font-size: 24px; width: 24px; height: 24px; line-height: 24px; display: inline-block;"></span>
					<div style="flex: 1;">
						<strong id="queue-calc-title" style="color: #1e293b; font-size: 14px; display: block; margin-bottom: 3px;"><?php echo esc_html( $queue_paused ? __( 'Queue paused', 'teknotok-ai-translator-pro' ) : __( 'Calculating translation time...', 'teknotok-ai-translator-pro' ) ); ?></strong>
						<span id="queue-calc-desc" style="color: #64748b; font-size: 13px; display: block;"><?php echo esc_html( $queue_paused ? ( $queue_pause_reason ? $queue_pause_reason : __( 'Translation is paused until the license or quota issue is fixed.', 'teknotok-ai-translator-pro' ) ) : __( 'Please wait while the plugin calculates the total items and processes the initial translation batch. The live progress bar below will update automatically.', 'teknotok-ai-translator-pro' ) ); ?></span>
					</div>
				</div>
			<?php endif; ?>

			<div class="teknotok-ait-dashboard">
				<!-- Queue Status Widget Card -->
				<div class="teknotok-ait-card status-section" style="padding: 24px; margin-bottom: 24px;">
					<div class="card-header" style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 10px;">
						<div>
							<h2 style="margin: 0; display: inline-flex; align-items: center; gap: 10px;">
								<?php esc_html_e( 'Translation Queue Status', 'teknotok-ai-translator-pro' ); ?>
								<span id="queue-paused-badge" class="badge badge-danger" style="background: #fee2e2; color: #991b1b; padding: 4px 8px; font-weight: 700; border-radius: 4px; font-size: 11px; <?php echo $queue_paused ? '' : 'display: none;'; ?>"><?php esc_html_e( 'PAUSED', 'teknotok-ai-translator-pro' ); ?></span>
							</h2>
							<p class="subtitle" style="margin: 5px 0 0 0;"><?php esc_html_e( 'Monitor and manage the background translation jobs in real-time.', 'teknotok-ai-translator-pro' ); ?></p>
							<div id="queue-paused-message" class="notice notice-warning" style="margin: 12px 0 0 0; <?php echo $queue_paused ? '' : 'display: none;'; ?>">
								<p style="margin: 8px 0;">
									<strong><?php esc_html_e( 'Queue paused:', 'teknotok-ai-translator-pro' ); ?></strong>
									<span id="queue-paused-reason"><?php echo esc_html( $queue_pause_reason ? $queue_pause_reason : __( 'Translation provider limit reached.', 'teknotok-ai-translator-pro' ) ); ?></span>
								</p>
							</div>
						</div>
						<div class="teknotok-queue-actions">
							<button type="button" id="teknotok-retry-failed-jobs" class="button button-secondary" style="<?php echo $retryable_failed > 0 ? '' : 'display: none;'; ?>">
								<?php esc_html_e( 'Retry Failed Jobs', 'teknotok-ai-translator-pro' ); ?>
							</button>
							<button type="button" id="teknotok-resume-queue" class="button button-primary" style="<?php echo $queue_paused ? '' : 'display: none;'; ?>">
								<?php esc_html_e( 'Resume Queue', 'teknotok-ai-translator-pro' ); ?>
							</button>
						</div>
					</div>

					<?php
					$pending = intval( $queue_counts['pending'] );
					$processing = intval( $queue_counts['processing'] );
					$completed = intval( $queue_counts['completed'] );
					$failed = intval( $queue_counts['failed'] );
					$total = $pending + $processing + $completed + $failed;
					$percentage = ( $total > 0 ) ? round( ( $completed / $total ) * 100 ) : 0;
					?>

					<!-- Translation Progress Bar Widget -->
					<?php if ( $total > 0 || ( isset( $_GET['setup'] ) && 'start' === $_GET['setup'] ) ) : ?>
						<div class="teknotok-progress-container" <?php if ( $total === 0 ) echo 'style="display: none;"'; ?>>
							<div class="teknotok-progress-header">
								<span><?php esc_html_e( 'Overall Translation Progress', 'teknotok-ai-translator-pro' ); ?></span>
								<span id="queue-progress-percentage"><?php echo esc_html( $percentage ); ?>%</span>
							</div>
							<div class="teknotok-progress-track">
								<div id="queue-progress-bar" class="teknotok-progress-bar <?php echo ( $pending > 0 || $processing > 0 ) ? 'teknotok-progress-animated' : ''; ?>" style="width: <?php echo esc_attr( $percentage ); ?>%;"></div>
							</div>
						</div>
					<?php endif; ?>

					<!-- Dashboard grid of status cards -->
					<div class="teknotok-status-grid">
						<div class="teknotok-status-card status-pending">
							<div class="status-icon"><span class="dashicons dashicons-clock"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Pending', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="status-value" id="queue-count-pending"><?php echo esc_html( $queue_counts['pending'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-processing">
							<div class="status-icon"><span class="dashicons dashicons-update <?php echo ( $queue_counts['pending'] > 0 || $queue_counts['processing'] > 0 ) ? 'spin' : ''; ?>"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Processing', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="status-value" id="queue-count-processing"><?php echo esc_html( $queue_counts['processing'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-completed">
							<div class="status-icon"><span class="dashicons dashicons-yes-alt"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Completed', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="status-value" id="queue-count-completed"><?php echo esc_html( $queue_counts['completed'] ); ?></span>
							</div>
						</div>
						<div class="teknotok-status-card status-failed">
							<div class="status-icon"><span class="dashicons dashicons-warning"></span></div>
							<div class="status-info">
								<span class="status-label"><?php esc_html_e( 'Failed', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="status-value" id="queue-count-failed"><?php echo esc_html( $queue_counts['failed'] ); ?></span>
							</div>
						</div>
					</div>

					<p class="description" id="queue-resume-help" style="<?php echo $queue_paused ? '' : 'display: none;'; ?>">
						<?php esc_html_e( 'After upgrading or fixing the License Manager quota, click Resume Queue to retry quota-failed jobs.', 'teknotok-ai-translator-pro' ); ?>
					</p>
					<p class="description" id="queue-retry-help" style="<?php echo $retryable_failed > 0 ? '' : 'display: none;'; ?>">
						<?php esc_html_e( 'After fixing timeout or server issues, click Retry Failed Jobs to retry non-quota failures without touching quota/license failures.', 'teknotok-ai-translator-pro' ); ?>
					</p>
				</div>

				<div class="teknotok-dashboard-grid">
					<!-- Environment Details Card -->
					<div class="teknotok-ait-card env-section">
						<h2><span class="dashicons dashicons-admin-settings"></span> <?php esc_html_e( 'System Environment', 'teknotok-ai-translator-pro' ); ?></h2>
						<div class="env-info-list">
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'PHP Version', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value badge"><?php echo esc_html( PHP_VERSION ); ?></span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'WordPress Version', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value badge"><?php echo esc_html( $GLOBALS['wp_version'] ); ?></span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'WooCommerce Version', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value badge <?php echo class_exists( 'WooCommerce' ) ? 'badge-success' : 'badge-danger'; ?>">
									<?php echo class_exists( 'WooCommerce' ) ? esc_html( WC()->version ) : esc_html__( 'Not Installed', 'teknotok-ai-translator-pro' ); ?>
								</span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'Memory Limit', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value badge"><?php echo esc_html( WP_MEMORY_LIMIT ); ?></span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'License Key Status', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value badge <?php echo 'active' === $license_label ? 'badge-success' : 'badge-warning'; ?>">
									<?php echo esc_html( $license_label ); ?>
								</span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'Translations Cache Table', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value status-dot <?php echo ( $wpdb->get_var( "SHOW TABLES LIKE '" . $wpdb->prefix . "teknotok_translations'" ) ) ? 'dot-active' : 'dot-inactive'; ?>">
									<?php echo ( $wpdb->get_var( "SHOW TABLES LIKE '" . $wpdb->prefix . "teknotok_translations'" ) ) ? esc_html__( 'Active', 'teknotok-ai-translator-pro' ) : esc_html__( 'Missing', 'teknotok-ai-translator-pro' ); ?>
								</span>
							</div>
							<div class="env-item">
								<span class="env-label"><?php esc_html_e( 'Jobs Queue Table', 'teknotok-ai-translator-pro' ); ?></span>
								<span class="env-value status-dot <?php echo ( $wpdb->get_var( "SHOW TABLES LIKE '" . $wpdb->prefix . "teknotok_jobs'" ) ) ? 'dot-active' : 'dot-inactive'; ?>">
									<?php echo ( $wpdb->get_var( "SHOW TABLES LIKE '" . $wpdb->prefix . "teknotok_jobs'" ) ) ? esc_html__( 'Active', 'teknotok-ai-translator-pro' ) : esc_html__( 'Missing', 'teknotok-ai-translator-pro' ); ?>
								</span>
							</div>
						</div>
					</div>

					<!-- Recent Errors Card -->
					<div class="teknotok-ait-card errors-section">
						<h2><span class="dashicons dashicons-warning"></span> <?php esc_html_e( 'Recent Queue Log Errors', 'teknotok-ai-translator-pro' ); ?></h2>
						<div class="errors-container">
							<?php if ( empty( $failed_jobs ) ) : ?>
								<div class="empty-state">
									<span class="dashicons dashicons-smiley"></span>
									<p><?php esc_html_e( 'No queue errors or translation failures logged.', 'teknotok-ai-translator-pro' ); ?></p>
								</div>
							<?php else : ?>
								<div class="errors-table-scroll">
									<table class="widefat striped modern-table">
										<thead>
											<tr>
												<th>ID</th>
												<th>Type</th>
												<th>Target</th>
												<th>Error Message</th>
												<th>Logged At</th>
											</tr>
										</thead>
										<tbody>
											<?php foreach ( $failed_jobs as $job ) : ?>
												<tr>
													<td><strong>#<?php echo esc_html( $job->id ); ?></strong></td>
													<td><span class="badge badge-secondary"><?php echo esc_html( $job->object_type ); ?></span></td>
													<td><span class="badge badge-info"><?php echo esc_html( $job->target_lang ); ?></span></td>
													<td class="error-msg-col"><code><?php echo esc_html( $job->error_message ); ?></code></td>
													<td class="time-col"><?php echo esc_html( $job->updated_at ); ?></td>
												</tr>
											<?php endforeach; ?>
										</tbody>
									</table>
								</div>
							<?php endif; ?>
						</div>
					</div>
				</div>

				<!-- Debug Logs Card -->
				<div class="teknotok-ait-card logs-section" style="margin-top: 24px; padding: 24px;">
					<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
						<div>
							<h2><span class="dashicons dashicons-media-text"></span> <?php esc_html_e( 'Plugin Activity & Debug Logs', 'teknotok-ai-translator-pro' ); ?></h2>
							<p class="subtitle" style="margin: 0;"><?php esc_html_e( 'View the last 100 log lines from the background processing and API communications.', 'teknotok-ai-translator-pro' ); ?></p>
						</div>
						<form method="post" action="">
							<?php wp_nonce_field( 'teknotok_ait_diag_nonce' ); ?>
							<button type="submit" name="teknotok_ait_diag_action" value="clear_logs" class="button button-link-delete log-clear-btn" onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to clear the debug log file?', 'teknotok-ai-translator-pro' ); ?>');">
								<span class="dashicons dashicons-trash"></span> <?php esc_html_e( 'Clear Log File', 'teknotok-ai-translator-pro' ); ?>
							</button>
						</form>
					</div>
					
					<?php
					$logs = \TeknoTok\AiTranslator\Utils\Logger::read_logs( 100 );
					?>
					
					<div class="terminal-logs-container">
						<div class="terminal-header">
							<span class="terminal-dot red-dot"></span>
							<span class="terminal-dot yellow-dot"></span>
							<span class="terminal-dot green-dot"></span>
							<span class="terminal-title">teknotok-translator-debug.log</span>
						</div>
						<div class="terminal-body" id="log-terminal">
							<?php 
							if ( $logs ) {
								$log_lines = explode( "\n", $logs );
								foreach ( $log_lines as $line ) {
									if ( empty( trim( $line ) ) ) {
										continue;
									}
									
									$class = 'log-line';
									if ( false !== stripos( $line, 'error' ) || false !== stripos( $line, 'exception' ) ) {
										$class .= ' log-error';
									} elseif ( false !== stripos( $line, 'warning' ) ) {
										$class .= ' log-warning';
									} elseif ( false !== stripos( $line, 'info' ) ) {
										$class .= ' log-info';
									}
									echo '<div class="' . esc_attr( $class ) . '">' . esc_html( $line ) . '</div>';
								}
							} else {
								echo '<div class="log-empty">' . esc_html__( 'No log entries found.', 'teknotok-ai-translator-pro' ) . '</div>';
							}
							?>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
