<?php
namespace TeknoTok\AiTranslator\Admin;

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

/**
 * Controller to manage the admin License Page.
 */
class LicenseController {
	/**
	 * 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' ), 20 );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
	}

	/**
	 * Register submenu.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_submenu_page(
			'teknotok-ait',
			__( 'License Settings', 'teknotok-ai-translator-pro' ),
			__( 'License Settings', 'teknotok-ai-translator-pro' ),
			'manage_options',
			'teknotok-ait-license',
			array( $this, 'render_license' )
		);
	}

	/**
	 * Handle POST requests.
	 *
	 * @return void
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

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

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

		if ( 'activate' === $action ) {
			check_admin_referer( 'teknotok_ait_license_nonce' );
			$key = sanitize_text_field( $_POST['license_key'] ?? '' );
			$result = $this->plugin->license->activate( $key );

			if ( is_wp_error( $result ) ) {
				add_settings_error( 'teknotok_ait_license', 'activation_failed', $result->get_error_message(), 'error' );
			} else {
				add_settings_error( 'teknotok_ait_license', 'activation_success', __( 'License activated successfully.', 'teknotok-ai-translator-pro' ), 'success' );
			}
		}

		if ( 'deactivate' === $action ) {
			check_admin_referer( 'teknotok_ait_license_nonce' );
			$result = $this->plugin->license->deactivate();

			if ( is_wp_error( $result ) ) {
				add_settings_error( 'teknotok_ait_license', 'deactivation_failed', $result->get_error_message(), 'error' );
			} else {
				add_settings_error( 'teknotok_ait_license', 'deactivation_success', __( 'License deactivated successfully.', 'teknotok-ai-translator-pro' ), 'success' );
			}
		}

		if ( 'check' === $action ) {
			check_admin_referer( 'teknotok_ait_license_nonce' );
			$result = $this->plugin->license->check();

			if ( is_wp_error( $result ) ) {
				add_settings_error( 'teknotok_ait_license', 'check_failed', $result->get_error_message(), 'error' );
			} else {
				add_settings_error( 'teknotok_ait_license', 'check_success', __( 'License check completed. Status active.', 'teknotok-ai-translator-pro' ), 'success' );
			}
		}
	}

	/**
	 * Render license page.
	 *
	 * @return void
	 */
	public function render_license() {
		$license = get_option( 'teknotok_ait_license_status', array() );
		$status  = $license['status'] ?? 'free';
		$key     = $license['license_key'] ?? '';
		$expires = $license['expires_at'] ?? '';
		$is_pro  = \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active();
		if ( 'active' === $status && ! $is_pro && ! empty( $expires ) && strtotime( $expires ) < time() ) {
			$status = 'expired';
		}

		$free_usage = array();
		if ( ! $is_pro ) {
			$free_usage = $this->plugin->license->get_free_usage();
		}
		?>
		<div class="wrap teknotok-ait-wrap">
			<h1><?php esc_html_e( 'License Settings', 'teknotok-ai-translator-pro' ); ?></h1>
			<?php settings_errors(); ?>

			<div class="card teknotok-ait-card" style="max-width: 600px; margin-top: 20px; padding: 24px; background: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
				<?php if ( $is_pro ) : ?>
					<h2 style="margin-top: 0; color: #1e293b;"><?php esc_html_e( 'TeknoTok AI Translator Pro Activated', 'teknotok-ai-translator-pro' ); ?></h2>
					<p style="color: #64748b; font-size: 14px;"><?php esc_html_e( 'Your Pro license is active. You have unlocked all target languages, background processing queues, and automatic plugin update checks.', 'teknotok-ai-translator-pro' ); ?></p>
				<?php elseif ( 'expired' === $status ) : ?>
					<h2 style="margin-top: 0; color: #1e293b;"><?php esc_html_e( 'TeknoTok AI Translator Pro License Expired', 'teknotok-ai-translator-pro' ); ?></h2>
					<p style="color: #64748b; font-size: 14px;"><?php esc_html_e( 'Your saved translations remain available, but new premium background translations are paused until you renew or enter an active license key.', 'teknotok-ai-translator-pro' ); ?></p>
				<?php else : ?>
					<h2 style="margin-top: 0; color: #1e293b;"><?php esc_html_e( 'TeknoTok AI Translator Free Tier Active', 'teknotok-ai-translator-pro' ); ?></h2>
					<p style="color: #64748b; font-size: 14px;"><?php printf( esc_html__( 'You are using the Free version. You can select 1 target language and translate up to 3,000 words. Visit %s to purchase a Pro license key and unlock all features (unlimited words, multiple languages, WooCommerce product translations, etc.) instantly.', 'teknotok-ai-translator-pro' ), '<a href="https://soft.teknotok.com/teknotok-translator-pro/" target="_blank" style="color: #4f46e5; text-decoration: underline; font-weight: 600;">' . esc_html__( 'our store', 'teknotok-ai-translator-pro' ) . '</a>' ); ?></p>

					<?php if ( ! is_wp_error( $free_usage ) && ! empty( $free_usage ) && isset( $free_usage['word_count'] ) ) : ?>
						<div class="free-usage-stats" style="margin-top: 20px; padding: 16px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;">
							<h3 style="margin: 0 0 10px 0; font-size: 14px; color: #334155; font-weight: 600;"><?php esc_html_e( 'Free Translation Usage (Lifetime)', 'teknotok-ai-translator-pro' ); ?></h3>
							<div style="font-size: 13px; color: #475569;">
								<div style="margin-bottom: 5px;">
									<strong><?php esc_html_e( 'Words Used:', 'teknotok-ai-translator-pro' ); ?></strong> 
									<?php printf( esc_html__( '%1$s / %2$s words', 'teknotok-ai-translator-pro' ), number_format_i18n( $free_usage['word_count'] ), number_format_i18n( $free_usage['limit'] ) ); ?>
								</div>
								<?php
								$percentage = min( 100, round( ( $free_usage['word_count'] / $free_usage['limit'] ) * 100 ) );
								$bar_color = $percentage >= 100 ? '#ef4444' : ( $percentage > 80 ? '#f59e0b' : '#3b82f6' );
								?>
								<div style="width: 100%; height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin: 8px 0;">
									<div style="width: <?php echo esc_attr( $percentage ); ?>%; height: 100%; background: <?php echo esc_attr( $bar_color ); ?>; border-radius: 4px;"></div>
								</div>
								<?php if ( $free_usage['word_count'] >= $free_usage['limit'] ) : ?>
									<div style="color: #ef4444; font-weight: 600; margin-top: 5px;">
										<?php printf( esc_html__( 'Lifetime quota exceeded! Please buy a Pro license key at %s to unlock unlimited translation.', 'teknotok-ai-translator-pro' ), '<a href="https://soft.teknotok.com/teknotok-translator-pro/" target="_blank" style="color: #ef4444; text-decoration: underline; font-weight: 700;">' . esc_html__( 'our store', 'teknotok-ai-translator-pro' ) . '</a>' ); ?>
									</div>
								<?php else : ?>
									<div style="color: #64748b; font-size: 12px; margin-top: 5px;">
										<?php esc_html_e( 'One-time free allocation. Does not reset.', 'teknotok-ai-translator-pro' ); ?>
									</div>
								<?php endif; ?>
							</div>
						</div>
					<?php endif; ?>
				<?php endif; ?>

				<form method="post" action="" style="margin-top: 20px;">
					<?php wp_nonce_field( 'teknotok_ait_license_nonce' ); ?>
					
					<table class="form-table" style="margin-top: 0;">
						<tr style="border-bottom: 1px solid #f1f5f9;">
							<th scope="row" style="width: 180px; font-weight: 600; color: #334155; padding: 15px 0;"><?php esc_html_e( 'License Status', 'teknotok-ai-translator-pro' ); ?></th>
							<td style="padding: 15px 0;">
								<?php if ( $is_pro ) : ?>
									<span class="badge badge-success" style="background: #d1fae5; color: #065f46; padding: 6px 12px; font-weight: 700; border-radius: 6px; font-size: 12px;"><?php esc_html_e( 'PRO VERSION ACTIVE', 'teknotok-ai-translator-pro' ); ?></span>
								<?php elseif ( 'expired' === $status ) : ?>
									<span class="badge badge-warning" style="background: #fef3c7; color: #92400e; padding: 6px 12px; font-weight: 700; border-radius: 6px; font-size: 12px;"><?php esc_html_e( 'LICENSE EXPIRED', 'teknotok-ai-translator-pro' ); ?></span>
								<?php else : ?>
									<span class="badge badge-info" style="background: #e0f2fe; color: #075985; padding: 6px 12px; font-weight: 700; border-radius: 6px; font-size: 12px;"><?php esc_html_e( 'FREE VERSION ACTIVE', 'teknotok-ai-translator-pro' ); ?></span>
								<?php endif; ?>
							</td>
						</tr>
						<tr style="border-bottom: 1px solid #f1f5f9;">
							<th scope="row" style="width: 180px; font-weight: 600; color: #334155; padding: 15px 0;"><label for="license_key"><?php esc_html_e( 'License Key', 'teknotok-ai-translator-pro' ); ?></label></th>
							<td style="padding: 15px 0;">
								<input type="text" name="license_key" id="license_key" value="<?php echo esc_attr( $key ); ?>" class="regular-text" style="width: 100%; max-width: 380px; padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 6px;" <?php disabled( $is_pro ); ?> placeholder="<?php esc_attr_e( 'Enter your license key here...', 'teknotok-ai-translator-pro' ); ?>" />
							</td>
						</tr>
						<?php if ( $is_pro && ! empty( $expires ) ) : ?>
							<tr style="border-bottom: none;">
								<th scope="row" style="width: 180px; font-weight: 600; color: #334155; padding: 15px 0;"><?php esc_html_e( 'Expires At', 'teknotok-ai-translator-pro' ); ?></th>
								<td style="padding: 15px 0; color: #475569; font-weight: 500;">
									<?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $expires ) ) ); ?>
								</td>
							</tr>
						<?php endif; ?>
					</table>

					<div class="submit-wrapper" style="margin-top: 24px;">
						<?php if ( $is_pro ) : ?>
							<input type="hidden" name="teknotok_ait_license_action" value="deactivate" />
							<button type="submit" class="button button-link-delete" style="color: #ef4444; background: none; border: none; font-weight: 600; cursor: pointer; padding: 0; margin-right: 20px; font-size: 14px;"><?php esc_html_e( 'Deactivate Pro License', 'teknotok-ai-translator-pro' ); ?></button>
							<button type="submit" name="teknotok_ait_license_action" value="check" class="button button-secondary" style="padding: 6px 14px; border-radius: 6px; font-weight: 500; font-size: 13px;"><?php esc_html_e( 'Refresh License Status', 'teknotok-ai-translator-pro' ); ?></button>
						<?php else : ?>
							<input type="hidden" name="teknotok_ait_license_action" value="activate" />
							<button type="submit" class="button button-primary" style="background: linear-gradient(135deg, #6366f1, #4f46e5); color: white; border: none; padding: 8px 20px; font-weight: 600; border-radius: 6px; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.2);"><?php esc_html_e( 'Activate Pro Version', 'teknotok-ai-translator-pro' ); ?></button>
						<?php endif; ?>
					</div>
				</form>
			</div>
		</div>
		<?php
	}
}
