<?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' ),
			__( 'License Settings', 'teknotok-ai-translator' ),
			'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;
		}

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

		if ( 'activate' === $action ) {
			check_admin_referer( 'teknotok_ait_license_nonce' );
			$key = sanitize_text_field( wp_unslash( $_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' ), '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' ), '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' ), '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();
		}
		$quota_status = $this->plugin->license->get_quota_status();
		if ( is_wp_error( $quota_status ) ) {
			$quota_status = $is_pro ? $license : $free_usage;
		}
		$server_warning = is_array( $quota_status ) ? ( $quota_status['server_warning'] ?? '' ) : '';

		$website_url = 'https://soft.teknotok.com/';
		$premium_url = 'https://soft.teknotok.com/teknotok-translator-pro/';
		$contact_email = 'teknotok@teknotok.com';
		$status_label = $is_pro ? __( 'Pro active', 'teknotok-ai-translator' ) : ( 'expired' === $status ? __( 'Expired', 'teknotok-ai-translator' ) : __( 'Free active', 'teknotok-ai-translator' ) );
		$status_class = $is_pro ? 'is-active' : ( 'expired' === $status ? 'is-warning' : 'is-free' );
		$license_heading = $is_pro ? __( 'Pro license is active', 'teknotok-ai-translator' ) : ( 'expired' === $status ? __( 'License expired', 'teknotok-ai-translator' ) : __( 'Free tier is active', 'teknotok-ai-translator' ) );
		$license_summary = $is_pro
			? __( 'Your site can use all target languages and the Pro yearly word quota. Saved translations stay local and do not use words again unless source content changes.', 'teknotok-ai-translator' )
			: ( 'expired' === $status
				? __( 'Saved translations remain available, but new premium background translations are paused until the license is renewed or replaced.', 'teknotok-ai-translator' )
				: __( 'Use the free word quota to test translation, or enter a Pro key for all languages and 1000,000 AI translated words per year.', 'teknotok-ai-translator' )
			);
		$masked_key = '';
		if ( ! empty( $key ) ) {
			$masked_key = substr( $key, 0, 8 ) . '...' . substr( $key, -4 );
		}
		?>
		<div class="wrap teknotok-ait-wrap">
			<h1><?php esc_html_e( 'License Settings', 'teknotok-ai-translator' ); ?></h1>
			<?php settings_errors(); ?>
			<?php if ( ! empty( $server_warning ) ) : ?>
				<div class="notice notice-warning teknotok-license-notice">
					<p>
						<strong><?php esc_html_e( 'License server update needed:', 'teknotok-ai-translator' ); ?></strong>
						<?php echo esc_html( $server_warning ); ?>
					</p>
				</div>
			<?php endif; ?>

			<div class="teknotok-license-layout">
				<div class="teknotok-license-main teknotok-ait-card">
					<div class="teknotok-license-header">
						<div>
							<span class="teknotok-license-status <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
							<h2><?php echo esc_html( $license_heading ); ?></h2>
							<p><?php echo esc_html( $license_summary ); ?></p>
						</div>
						<?php if ( ! $is_pro ) : ?>
							<a class="button button-primary" href="<?php echo esc_url( $premium_url ); ?>" target="_blank" rel="noopener noreferrer">
								<?php esc_html_e( 'Buy Pro', 'teknotok-ai-translator' ); ?>
							</a>
						<?php endif; ?>
					</div>

					<?php $this->render_quota_meter( $quota_status, $is_pro ? __( 'Pro yearly word usage', 'teknotok-ai-translator' ) : __( 'Free word usage', 'teknotok-ai-translator' ) ); ?>

					<form method="post" action="" class="teknotok-license-form">
						<?php wp_nonce_field( 'teknotok_ait_license_nonce' ); ?>

						<div class="teknotok-license-field">
							<label for="license_key"><?php esc_html_e( 'License key', 'teknotok-ai-translator' ); ?></label>
							<?php if ( $is_pro ) : ?>
								<input type="text" id="license_key" value="<?php echo esc_attr( $masked_key ); ?>" class="regular-text" disabled />
								<p class="description"><?php esc_html_e( 'Your active key is hidden for safety. Refresh status to sync quota and renewal details.', 'teknotok-ai-translator' ); ?></p>
							<?php else : ?>
								<input type="text" name="license_key" id="license_key" value="<?php echo esc_attr( $key ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'Enter your license key here...', 'teknotok-ai-translator' ); ?>" />
								<p class="description"><?php esc_html_e( 'Paste your TeknoTok license key to unlock Pro translation quota and premium updates.', 'teknotok-ai-translator' ); ?></p>
							<?php endif; ?>
						</div>

						<?php if ( $is_pro && ! empty( $expires ) ) : ?>
							<div class="teknotok-license-meta">
								<span><?php esc_html_e( 'License expiry', 'teknotok-ai-translator' ); ?></span>
								<strong><?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $expires ) ) ); ?></strong>
							</div>
						<?php endif; ?>

						<div class="teknotok-license-actions">
							<?php if ( $is_pro ) : ?>
								<button type="submit" name="teknotok_ait_license_action" value="check" class="button button-primary"><?php esc_html_e( 'Refresh License Status', 'teknotok-ai-translator' ); ?></button>
								<button type="submit" name="teknotok_ait_license_action" value="deactivate" class="button button-link-delete"><?php esc_html_e( 'Deactivate Pro License', 'teknotok-ai-translator' ); ?></button>
							<?php else : ?>
								<button type="submit" name="teknotok_ait_license_action" value="activate" class="button button-primary"><?php esc_html_e( 'Activate Pro License', 'teknotok-ai-translator' ); ?></button>
							<?php endif; ?>
						</div>
					</form>
				</div>

				<div class="teknotok-license-side teknotok-ait-card">
					<h2><?php esc_html_e( 'Need help?', 'teknotok-ai-translator' ); ?></h2>
					<p><?php esc_html_e( 'Use these links for purchases, support, documentation, or custom WordPress and AI projects.', 'teknotok-ai-translator' ); ?></p>
					<div class="teknotok-license-links">
						<?php if ( ! $is_pro ) : ?>
							<a class="button button-primary" href="<?php echo esc_url( $premium_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Buy Pro License', 'teknotok-ai-translator' ); ?></a>
						<?php endif; ?>
						<a class="button button-secondary" href="<?php echo esc_url( $website_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Visit Website', 'teknotok-ai-translator' ); ?></a>
						<a class="button button-secondary" href="<?php echo esc_url( 'mailto:' . $contact_email ); ?>"><?php esc_html_e( 'Email Support', 'teknotok-ai-translator' ); ?></a>
					</div>
					<div class="teknotok-license-note">
						<strong><?php esc_html_e( 'Pro includes', 'teknotok-ai-translator' ); ?></strong>
						<span><?php esc_html_e( 'All languages, premium updates, and 1000,000 AI translated words per year for one website.', 'teknotok-ai-translator' ); ?></span>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render a quota usage meter.
	 *
	 * @param array  $quota Quota data.
	 * @param string $title Meter title.
	 * @return void
	 */
	private function render_quota_meter( $quota, $title ) {
		if ( ! is_array( $quota ) ) {
			return;
		}

		$limit = (int) ( $quota['words_limit'] ?? ( $quota['limit'] ?? 0 ) );
		$used  = (int) ( $quota['words_used'] ?? ( $quota['word_count'] ?? 0 ) );

		if ( $limit <= 0 ) {
			return;
		}

		$remaining = max( 0, (int) ( $quota['words_remaining'] ?? ( $limit - $used ) ) );
		$percentage = min( 100, round( ( $used / $limit ) * 100 ) );
		$bar_color = $percentage >= 100 ? '#ef4444' : ( $percentage > 80 ? '#f59e0b' : '#3b82f6' );
		$period_end = $quota['quota_period_end'] ?? '';
		$user_message = $quota['user_message'] ?? '';
		?>
		<div class="teknotok-quota-stats">
			<div class="teknotok-quota-head">
				<h3><?php echo esc_html( $title ); ?></h3>
				<strong><?php printf( esc_html__( '%1$s / %2$s words', 'teknotok-ai-translator' ), esc_html( number_format_i18n( $used ) ), esc_html( number_format_i18n( $limit ) ) ); ?></strong>
			</div>
			<div class="teknotok-quota-track">
				<div class="teknotok-quota-bar" style="width: <?php echo esc_attr( $percentage ); ?>%; background: <?php echo esc_attr( $bar_color ); ?>;"></div>
			</div>
			<div class="teknotok-quota-foot">
				<?php if ( $remaining <= 0 ) : ?>
					<div class="teknotok-quota-warning">
						<?php echo esc_html( $user_message ? $user_message : __( 'Your AI translation word quota is finished. Existing translations still work, but new translations are paused until your quota renews or you add more words.', 'teknotok-ai-translator' ) ); ?>
					</div>
				<?php else : ?>
					<div>
						<?php printf( esc_html__( '%s words remaining.', 'teknotok-ai-translator' ), esc_html( number_format_i18n( $remaining ) ) ); ?>
						<?php if ( ! empty( $period_end ) ) : ?>
							<?php printf( esc_html__( 'Renews on %s.', 'teknotok-ai-translator' ), esc_html( date_i18n( get_option( 'date_format' ), strtotime( $period_end ) ) ) ); ?>
						<?php else : ?>
							<?php esc_html_e( 'Finished translations stay saved locally and do not use words again unless the source content changes.', 'teknotok-ai-translator' ); ?>
						<?php endif; ?>
					</div>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}
}
