<?php
/**
 * Minimal settings screen (license activation, AI toggle + privacy notice,
 * LLM API key, uninstall behavior).
 *
 * @package EmberPrice
 */

namespace EmberPrice\Admin;

use EmberPrice\Core\LicenseManager;
use EmberPrice\Core\Settings;

defined( 'ABSPATH' ) || exit;

/**
 * Renders the settings form inside AdminPage's shared shell and handles its
 * submission. The form remains server-rendered so this UI refactor does not
 * introduce a second settings persistence path.
 */
final class SettingsPage {

	private const NONCE_ACTION = 'embp_save_settings';
	private const NONCE_FIELD  = 'embp_settings_nonce';

	/**
	 * Typed settings accessor.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Constructor.
	 *
	 * @param Settings $settings Typed settings accessor.
	 */
	public function __construct( Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Registers the form submission handler. AdminPage owns the menu itself.
	 */
	public function register(): void {
		add_action( 'admin_post_' . self::NONCE_ACTION, array( $this, 'handle_save' ) );
	}

	/**
	 * Renders the settings form.
	 */
	public function render(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$delete_data = $this->settings->get_bool( 'delete_data_on_uninstall' );

		// The AI/LLM module (license activation, AI toggle, API key) is a
		// not-yet-purchasable Pro feature excluded entirely from the free
		// build (SPEC §9, L-7) -- showing this UI with nothing behind it
		// would be exactly the kind of dangling "upgrade to Pro" promise
		// wordpress.org's Trialware guidelines forbid.
		$llm_module_available = class_exists( '\\EmberPrice\\Llm\\LlmClientFactory' );

		if ( $llm_module_available ) {
			$has_key        = $this->settings->has_llm_api_key();
			$ai_enabled     = $this->settings->ai_enabled();
			$has_license    = LicenseManager::has_active_license();
			$masked_license = LicenseManager::masked_license_key();
			$is_pro         = LicenseManager::is_pro();
		}
		?>
		<div class="embp-settings-panel">
			<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'emberprice' ); ?></p></div>
			<?php endif; ?>

			<?php if ( isset( $_GET['license_error'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-error is-dismissible"><p><?php esc_html_e( 'That license key is too short to be valid.', 'emberprice' ); ?></p></div>
			<?php endif; ?>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="<?php echo esc_attr( self::NONCE_ACTION ); ?>" />
				<?php wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD ); ?>

				<table class="form-table" role="presentation">
					<?php if ( $llm_module_available ) : ?>
						<tr>
							<th scope="row"><?php esc_html_e( 'License', 'emberprice' ); ?></th>
							<td>
								<p>
									<strong><?php esc_html_e( 'Plan:', 'emberprice' ); ?></strong>
									<?php if ( $is_pro ) : ?>
										<span style="color:#007017;"><?php esc_html_e( 'Pro', 'emberprice' ); ?></span>
									<?php else : ?>
										<span><?php esc_html_e( 'Free', 'emberprice' ); ?></span>
									<?php endif; ?>
								</p>
								<input
									type="text"
									id="embp_license_key"
									name="embp_license_key"
									class="regular-text"
									autocomplete="off"
									placeholder="<?php echo esc_attr( $has_license ? (string) $masked_license : __( 'Not activated', 'emberprice' ) ); ?>"
								/>
								<p class="description">
									<?php esc_html_e( 'Enter your Pro license key and save to activate. Leave blank to keep the current one.', 'emberprice' ); ?>
								</p>
								<?php if ( $has_license ) : ?>
									<label for="embp_remove_license">
										<input type="checkbox" id="embp_remove_license" name="embp_remove_license" value="1" />
										<?php esc_html_e( 'Remove license (revert to Free)', 'emberprice' ); ?>
									</label>
								<?php endif; ?>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'AI features', 'emberprice' ); ?></th>
							<td>
								<label for="embp_ai_enabled">
									<input
										type="checkbox"
										id="embp_ai_enabled"
										name="embp_ai_enabled"
										value="1"
										<?php checked( $ai_enabled ); ?>
									/>
									<?php esc_html_e( 'Enable AI features (LLM matching, column mapping, PDF import)', 'emberprice' ); ?>
								</label>
								<p class="description">
									<?php esc_html_e( 'AI features are optional and only run if you also configure your own API key below (Anthropic or OpenAI, BYOK).', 'emberprice' ); ?>
								</p>
								<p class="description">
									<?php esc_html_e( "When used, only the supplier's own row text (product names/codes) and matching candidates already in your store's catalog (product names, SKUs) are sent -- never customer, order, or personal data.", 'emberprice' ); ?>
								</p>
								<p class="description">
									<?php esc_html_e( 'Unchecking this disables AI calls entirely, even if a key is configured.', 'emberprice' ); ?>
								</p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="embp_llm_api_key"><?php esc_html_e( 'LLM API Key', 'emberprice' ); ?></label>
							</th>
							<td>
								<input
									type="password"
									id="embp_llm_api_key"
									name="embp_llm_api_key"
									class="regular-text"
									autocomplete="off"
									placeholder="<?php echo esc_attr( $has_key ? __( '•••••••••••••••• (configured)', 'emberprice' ) : __( 'Not configured', 'emberprice' ) ); ?>"
								/>
								<p class="description">
									<?php esc_html_e( 'Stored encrypted. Leave blank to keep the current key.', 'emberprice' ); ?>
								</p>
							</td>
						</tr>
					<?php endif; ?>
					<tr>
						<th scope="row"><?php esc_html_e( 'Uninstall', 'emberprice' ); ?></th>
						<td>
							<label for="embp_delete_data_on_uninstall">
								<input
									type="checkbox"
									id="embp_delete_data_on_uninstall"
									name="embp_delete_data_on_uninstall"
									value="1"
									<?php checked( $delete_data ); ?>
								/>
								<?php esc_html_e( 'Delete all plugin data when uninstalled', 'emberprice' ); ?>
							</label>
						</td>
					</tr>
				</table>

				<?php submit_button(); ?>
			</form>
		</div>
		<?php
	}

	/**
	 * Handles the settings form submission.
	 */
	public function handle_save(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to do this.', 'emberprice' ) );
		}

		check_admin_referer( self::NONCE_ACTION, self::NONCE_FIELD );

		$this->settings->set_bool( 'delete_data_on_uninstall', ! empty( $_POST['embp_delete_data_on_uninstall'] ) );
		$this->settings->set_bool( 'ai_enabled', ! empty( $_POST['embp_ai_enabled'] ) );

		if ( ! empty( $_POST['embp_llm_api_key'] ) ) {
			$key = sanitize_text_field( wp_unslash( $_POST['embp_llm_api_key'] ) );
			$this->settings->set_llm_api_key( $key );
		}

		$redirect_args = array(
			'page'    => 'emberprice',
			'view'    => 'settings',
			'updated' => '1',
		);

		if ( ! empty( $_POST['embp_remove_license'] ) ) {
			LicenseManager::deactivate_license();
		} elseif ( ! empty( $_POST['embp_license_key'] ) ) {
			$license_key = sanitize_text_field( wp_unslash( $_POST['embp_license_key'] ) );

			if ( ! LicenseManager::activate_license( $license_key ) ) {
				unset( $redirect_args['updated'] );
				$redirect_args['license_error'] = '1';
			}
		}

		wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
		exit;
	}
}
