<?php
/**
 * Allergy Info Tweaks handler.
 *
 * @package FoodOrd
 */

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

/**
 * Handles the Allergy Info settings block inside Tweaks page.
 */
class Foodord_Allergy_Info
{
	/**
	 * Option key for stored content.
	 */
	private const OPTION_KEY = 'foodord_allergy_info_content';

	/**
	 * Option key for enable toggle.
	 */
	private const OPTION_ENABLE_KEY = 'foodord_allergy_info_enabled';

	/**
	 * Legacy option key kept for backward compatibility.
	 */
	private const LEGACY_OPTION_KEY = 'foodord_alllergy_info_content';

	/**
	 * Marks whether modal markup has been rendered.
	 *
	 * @var bool
	 */
	private static $modal_rendered = false;

	/**
	 * Process form submissions for Allergy Info section.
	 */
	public function handle_form_submission()
	{
		if (!isset($_POST['foodord_tweaks_submit'])) {
			return;
		}

		if (!current_user_can('manage_options')) {
			return;
		}

		if (!isset($_POST['foodord_tweaks_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['foodord_tweaks_nonce'])), 'foodord_tweaks_save')) {
			return;
		}

		$sanitized = '';
		if (isset($_POST[self::OPTION_KEY])) {
			$sanitized = wp_kses_post(wp_unslash($_POST[self::OPTION_KEY]));
		} elseif (isset($_POST[self::LEGACY_OPTION_KEY])) {
			$sanitized = wp_kses_post(wp_unslash($_POST[self::LEGACY_OPTION_KEY]));
		}

		update_option(self::OPTION_KEY, $sanitized);
		if (self::LEGACY_OPTION_KEY !== self::OPTION_KEY) {
			delete_option(self::LEGACY_OPTION_KEY);
		}

		$enabled = isset($_POST[self::OPTION_ENABLE_KEY]) ? 'yes' : 'no';
		update_option(self::OPTION_ENABLE_KEY, $enabled);
	}

	/**
	 * Render the Allergy Info editor section.
	 */
	public function render_section()
	{
		$content = $this->get_editor_content();
		$editor_id = self::OPTION_KEY;
		$editor_settings = array(
			'textarea_name' => self::OPTION_KEY,
			'textarea_rows' => 8,
			'editor_height' => 220,
			'quicktags' => false,
			'media_buttons' => false,
			'tinymce' => array(
				'plugins' => 'lists link paste wordpress',
				'toolbar1' => 'formatselect bold italic underline | bullist numlist | link unlink | removeformat',
				'toolbar2' => '',
				'toolbar3' => '',
				'toolbar4' => '',
				'menubar' => false,
				'wp_autoresize_on' => false,
			),
		);
		if (function_exists('wp_enqueue_editor')) {
			wp_enqueue_editor();
		}
		?>
		<div class="wrc-allergy-info-container">
			<div class="wrc-allergy-info-header">
				<div class="wrc-section-heading">
					<h2 class="wrc-section-title"><?php echo esc_html__('Allergy Info', 'foodord'); ?></h2>
					<span
						class="wrc-card-sub"><?php echo esc_html__('Configure the modal copy displayed when customers open the Allergy Info popup.', 'foodord'); ?></span>
				</div>
				<div class="wrc-toggle-row">
					<label class="foodord-toggle-switch" for="<?php echo esc_attr(self::OPTION_ENABLE_KEY); ?>">
						<input type="checkbox" id="<?php echo esc_attr(self::OPTION_ENABLE_KEY); ?>"
							name="<?php echo esc_attr(self::OPTION_ENABLE_KEY); ?>" value="yes"
							aria-label="<?php echo esc_attr__('Enable Allergy Info modal', 'foodord'); ?>" <?php checked('yes', get_option(self::OPTION_ENABLE_KEY, 'no')); ?> />
						<span class="foodord-toggle-slider"></span>
					</label>
				</div>
			</div>
			<div class="wrc-allergy-info-content">
				<div class="wrc-form wrc-form--single">
					<div class="wrc-field">
						<label class="screen-reader-text" for="<?php echo esc_attr($editor_id); ?>">
							<?php echo esc_html__('Allergy Info modal text', 'foodord'); ?>
						</label>
						<div class="wrc-control">
							<?php
							wp_editor($content, $editor_id, $editor_settings);
							?>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Initialize frontend hooks.
	 */
	public function init_frontend()
	{
		// AJAX endpoint for product-specific allergens - must be registered regardless of is_admin.
		// AJAX requests go through admin-ajax.php where is_admin() returns true.
		add_action('wp_ajax_foodord_get_product_allergens', array($this, 'ajax_get_product_allergens'));
		add_action('wp_ajax_nopriv_foodord_get_product_allergens', array($this, 'ajax_get_product_allergens'));

		if (is_admin()) {
			return;
		}

		add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
		add_action('wp_footer', array($this, 'render_modal_markup'));
	}

	/**
	 * Enqueue frontend assets when content exists or product allergens may be used.
	 */
	public function enqueue_assets()
	{
		// Always enqueue if global allergy info is enabled, or if we're on a page that might have products.
		// Product-specific allergens can exist even without global allergy info.
		$has_global_content = self::has_content() && self::is_enabled();

		// For simplicity, always enqueue on frontend - the script is lightweight.
		wp_enqueue_script(
			'foodord-allergy-info',
			FOODORD_URL . 'public/js/foodord-allergy-info.js',
			array(),
			FOODORD_VERSION,
			true
		);

		wp_localize_script(
			'foodord-allergy-info',
			'foodordAllergyInfo',
			array(
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('foodord_allergy_info'),
				'hasGlobalContent' => $has_global_content,
				'globalTitle' => esc_html__('Allergy Info', 'foodord'),
				'productTitle' => esc_html__('Allergen Information', 'foodord'),
				'containsLabel' => esc_html__('Contains:', 'foodord'),
				'notContainLabel' => esc_html__('Does Not Contain:', 'foodord'),
				'mayContainLabel' => esc_html__('May Contain (Shared Equipment):', 'foodord'),
			)
		);
	}

	/**
	 * Output the modal markup in the footer.
	 */
	public function render_modal_markup()
	{
		if (self::$modal_rendered) {
			return;
		}

		self::$modal_rendered = true;

		$global_content = self::get_content();
		$has_global = self::is_enabled() && '' !== $global_content;

		$modal_id = 'foodord-allergy-info-modal';
		$title_id = 'foodord-allergy-info-title';
		$close_label = esc_html__('Close Allergy Info', 'foodord');
		$heading = esc_html__('Allergy Info', 'foodord');
		$icon_url = FOODORD_URL . 'public/images/foodord-allergy-info.svg';
		?>
		<div class="foodord-allergy-info-modal" id="<?php echo esc_attr($modal_id); ?>" role="dialog" aria-modal="true"
			aria-hidden="true" aria-labelledby="<?php echo esc_attr($title_id); ?>">
			<div class="foodord-allergy-info-modal__backdrop" data-allergy-close="true"></div>
			<div class="foodord-allergy-info-modal__dialog" role="document">
				<div class="foodord-allergy-info-modal__header">
					<h2 class="foodord-allergy-info-modal__title" id="<?php echo esc_attr($title_id); ?>">
						<?php echo esc_html($heading); ?>
					</h2>
					<button type="button" class="foodord-allergy-info-modal__close"
						aria-label="<?php echo esc_attr($close_label); ?>" data-allergy-close="true"></button>
				</div>
				<div class="foodord-allergy-info-modal__content">
					<div class="foodord-allergy-info-modal__icon" aria-hidden="true">
						<img src="<?php echo esc_url($icon_url); ?>" alt="" />
					</div>
					<div class="foodord-allergy-info-modal__global-content" <?php echo $has_global ? '' : esc_attr('hidden'); ?>>
						<?php echo wp_kses_post($global_content); ?>
					</div>
					<div class="foodord-allergy-info-modal__product-content" hidden></div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Retrieve saved content for frontend usage.
	 *
	 * @return string
	 */
	public static function get_content(): string
	{
		$content = get_option(self::OPTION_KEY, '');
		if ('' === $content) {
			$content = get_option(self::LEGACY_OPTION_KEY, '');
			if ('' !== $content) {
				update_option(self::OPTION_KEY, $content);
				delete_option(self::LEGACY_OPTION_KEY);
			}
		}
		if (!is_string($content)) {
			return '';
		}

		$content = trim($content);
		if ('' === $content) {
			return '';
		}

		return wp_kses_post($content);
	}

	/**
	 * Whether Allergy Info modal is enabled.
	 *
	 * @return bool
	 */
	public static function is_enabled(): bool
	{
		return 'yes' === get_option(self::OPTION_ENABLE_KEY, 'no');
	}

	/**
	 * Determine whether content is available for display.
	 *
	 * @return bool
	 */
	public static function has_content(): bool
	{
		$content = self::get_content();
		if ('' === $content) {
			return false;
		}

		return '' !== trim(wp_strip_all_tags($content));
	}

	/**
	 * Retrieve raw content for editor population.
	 *
	 * @return string
	 */
	private function get_editor_content(): string
	{
		$content = get_option(self::OPTION_KEY, '');
		if ('' === $content) {
			$content = get_option(self::LEGACY_OPTION_KEY, '');
		}
		return is_string($content) ? $content : '';
	}

	/**
	 * AJAX handler for fetching product-specific allergens.
	 */
	public function ajax_get_product_allergens()
	{
		$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
		if (!wp_verify_nonce($nonce, 'foodord_allergy_info')) {
			wp_send_json_error(array('message' => 'Invalid nonce'), 403);
		}

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
		if ($product_id < 1) {
			wp_send_json_error(array('message' => 'Invalid product ID'), 400);
		}

		if (!class_exists('Foodord_Product_Data_Allergens')) {
			wp_send_json_error(array('message' => 'Allergens class not available'), 500);
		}

		$allergens = Foodord_Product_Data_Allergens::get_product_allergens($product_id);
		$html = Foodord_Product_Data_Allergens::get_product_allergens_html($product_id);

		wp_send_json_success(
			array(
				'allergens' => $allergens,
				'html' => $html,
			)
		);
	}
}
