<?php
/**
 * License page functionality.
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_License
 */
class Foodord_License
{
	/**
	 * Get all possible slugs for the License page.
	 *
	 * @return string[]
	 */
	private function get_page_slugs(): array
	{
		$slugs = function_exists('foodord_get_settings_page_slugs')
			? foodord_get_settings_page_slugs('license')
			: array('foodord-theme-settings-license', 'foodord-license');

		// In standalone mode, the top-level FoodOrd menu renders the License page.
		if (!(defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE) && function_exists('foodord_get_admin_parent_slug')) {
			$parent_slug = (string) foodord_get_admin_parent_slug();
			if ('' !== $parent_slug) {
				$slugs[] = $parent_slug;
			}
		}

		$slugs = array_values(array_unique(array_filter($slugs)));
		return $slugs;
	}

	/**
	 * Retrieve the current License settings page slug.
	 */
	private function get_current_page_slug(): string
	{
		return function_exists('foodord_get_settings_page_slug')
			? foodord_get_settings_page_slug('license')
			: 'foodord-license';
	}

	/**
	 * Build the admin URL pointing to the License settings page.
	 */
	private function get_license_page_url(): string
	{
		return function_exists('foodord_get_admin_page_url')
			? foodord_get_admin_page_url('license')
			: admin_url('admin.php?page=' . $this->get_current_page_slug());
	}

	/**
	 * Retrieve pricing plans shown when no valid license is active.
	 *
	 * @return array<int,array<string,mixed>>
	 */
	private function get_pricing_plans(): array
	{
		$features = array(
			'toppings' => __('Toppings Management', 'foodord'),
			'time_picker' => __('Time Picker', 'foodord'),
			'pre_ordering' => __('Pre-ordering', 'foodord'),
			'timed_products' => __('Timed Products', 'foodord'),
			'delivery_availability' => __('Delivery Availability', 'foodord'),
			'time_to_deliver' => __('Time To Deliver / Date', 'foodord'),
			'desktop_application' => __('Desktop Application', 'foodord'),
			'waiter_application' => __('Waiter Application', 'foodord'),
			'kitchen_display_system' => __('Kitchen Display System', 'foodord'),
			'point_of_sale' => __('Point of Sale', 'foodord'),
			'foodord_theme' => __('FoodOrd Theme', 'foodord'),
			'tipping' => __('Tipping', 'foodord'),
			'stampcard_program' => __('Stampcard Program', 'foodord'),
			'pricing_rules' => __('Pricing Rules', 'foodord'),
		);

		$paid_features = array_keys($features);

		return array(
			array(
				'id' => 'pro',
				'title' => __('Pro', 'foodord'),
				'description' => __('Professional features to manage daily orders easily.', 'foodord'),
				'price' => '$19',
				'period' => __('/month', 'foodord'),
				'button_label' => __('Try now', 'foodord'),
				'button_url' => 'https://foodord.lemonsqueezy.com/checkout/buy/0201d5cf-7b4f-4a09-8d0f-3785918744fe',
				'note' => __('No contract, cancel anytime', 'foodord'),
				'features' => $features,
				'included' => $paid_features,
			),
			array(
				'id' => 'plus',
				'title' => __('Plus', 'foodord'),
				'description' => __('Unlock everything with a yearly license.', 'foodord'),
				'price' => '$199',
				'period' => __('/year', 'foodord'),
				'button_label' => __('Try now', 'foodord'),
				'button_url' => 'https://foodord.lemonsqueezy.com/checkout/buy/134bd811-fb7b-4e43-a5b0-a8d868ab0adf',
				'note' => __('No contract, cancel anytime', 'foodord'),
				'features' => $features,
				'included' => $paid_features,
			),
		);
	}

	/**
	 * Render pricing table shown for stores without an active license.
	 */
	private function render_pricing_table(): void
	{
		$plans = $this->get_pricing_plans();
		$initial_feature_count = 3;
		?>
		<section class="foodord-license-pricing" aria-labelledby="foodord-license-pricing-title">
			<div class="foodord-license-pricing__header">
				<p class="foodord-license-pricing__eyebrow"><?php echo esc_html__('FoodOrd Plans', 'foodord'); ?></p>
				<h2 id="foodord-license-pricing-title" class="foodord-license-pricing__title">
					<?php echo esc_html__('Flexible pricing as per your needs', 'foodord'); ?>
				</h2>
				<p class="foodord-license-pricing__description">
					<?php echo esc_html__('Choose exactly what you need with clear, per-module pricing.', 'foodord'); ?>
				</p>
			</div>

			<div class="foodord-license-pricing__grid">
				<?php foreach ($plans as $plan): ?>
					<?php
					$plan_id = isset($plan['id']) ? sanitize_html_class((string) $plan['id']) : '';
					$features = isset($plan['features']) && is_array($plan['features']) ? $plan['features'] : array();
					$included = isset($plan['included']) && is_array($plan['included']) ? $plan['included'] : array();
					$visible_features = array_slice($features, 0, $initial_feature_count, true);
					$hidden_features = array_slice($features, $initial_feature_count, null, true);
					$extra_id = 'foodord-license-pricing-extra-' . $plan_id;
					?>
					<article class="foodord-license-pricing-card foodord-license-pricing-card--<?php echo esc_attr($plan_id); ?>">
						<div class="foodord-license-pricing-card__body">
							<h3 class="foodord-license-pricing-card__title"><?php echo esc_html((string) $plan['title']); ?></h3>
							<p class="foodord-license-pricing-card__text"><?php echo esc_html((string) $plan['description']); ?></p>

							<div class="foodord-license-pricing-card__price">
								<span class="foodord-license-pricing-card__amount"><?php echo esc_html((string) $plan['price']); ?></span>
								<?php if (!empty($plan['period'])): ?>
									<span class="foodord-license-pricing-card__period"><?php echo esc_html((string) $plan['period']); ?></span>
								<?php endif; ?>
							</div>

							<div class="foodord-license-pricing-card__action">
								<a class="foodord-license-pricing-card__button" href="<?php echo esc_url((string) $plan['button_url']); ?>" target="_blank" rel="noopener noreferrer">
									<?php echo esc_html((string) $plan['button_label']); ?>
								</a>
								<p class="foodord-license-pricing-card__note"><?php echo esc_html((string) $plan['note']); ?></p>
							</div>

							<ul class="foodord-license-pricing-features">
								<?php foreach ($visible_features as $feature_key => $feature_label): ?>
									<?php $is_included = in_array((string) $feature_key, $included, true); ?>
									<li class="foodord-license-pricing-feature <?php echo esc_attr($is_included ? 'is-included' : 'is-excluded'); ?>">
										<span class="foodord-license-pricing-feature__icon" aria-hidden="true"></span>
										<span><?php echo esc_html((string) $feature_label); ?></span>
									</li>
								<?php endforeach; ?>
							</ul>

							<?php if (!empty($hidden_features)): ?>
								<div id="<?php echo esc_attr($extra_id); ?>" class="foodord-license-pricing-extra" hidden>
									<ul class="foodord-license-pricing-features">
										<?php foreach ($hidden_features as $feature_key => $feature_label): ?>
											<?php $is_included = in_array((string) $feature_key, $included, true); ?>
											<li class="foodord-license-pricing-feature <?php echo esc_attr($is_included ? 'is-included' : 'is-excluded'); ?>">
												<span class="foodord-license-pricing-feature__icon" aria-hidden="true"></span>
												<span><?php echo esc_html((string) $feature_label); ?></span>
											</li>
										<?php endforeach; ?>
									</ul>
								</div>

								<button type="button" class="foodord-license-pricing-toggle" aria-expanded="false" aria-controls="<?php echo esc_attr($extra_id); ?>" data-collapsed-label="<?php echo esc_attr__('See features', 'foodord'); ?>" data-expanded-label="<?php echo esc_attr__('Hide features', 'foodord'); ?>">
									<span class="foodord-license-pricing-toggle__label"><?php echo esc_html__('See features', 'foodord'); ?></span>
									<span class="foodord-license-pricing-toggle__icon" aria-hidden="true"></span>
								</button>
							<?php endif; ?>
						</div>
					</article>
				<?php endforeach; ?>
			</div>

			<aside class="foodord-license-enterprise">
				<div class="foodord-license-enterprise__content">
					<span class="foodord-license-enterprise__eyebrow"><?php echo esc_html__('Tailored Solution', 'foodord'); ?></span>
					<h3 class="foodord-license-enterprise__title"><?php echo esc_html__('Custom Pricing for Enterprises', 'foodord'); ?></h3>
					<p class="foodord-license-enterprise__text">
						<?php echo esc_html__('We offer specialized solutions for agencies and high-volume licensing. Contact our team to explore bulk discounts and partnership opportunities.', 'foodord'); ?>
					</p>
				</div>
				<a class="foodord-license-enterprise__button" href="<?php echo esc_url('https://www.foodord.com/contact-us/'); ?>" target="_blank" rel="noopener noreferrer">
					<span><?php echo esc_html__('Contact Us', 'foodord'); ?></span>
					<span class="foodord-license-enterprise__button-icon" aria-hidden="true"></span>
				</a>
			</aside>
		</section>
		<?php
	}

	/**
	 * Constructor
	 */
	public function __construct()
	{
		add_action('admin_init', array($this, 'register_settings'));
		add_action('admin_post_foodord_save_license', array($this, 'handle_license_save'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
	}

	/**
	 * Register license settings
	 */
	public function register_settings()
	{
		register_setting(
			'foodord_license_settings',
			'foodord_license_key',
			array(
				'type' => 'string',
				'sanitize_callback' => array($this, 'sanitize_license_key'),
				'default' => '',
			)
		);

		register_setting(
			'foodord_license_settings',
			'foodord_license_status',
			array(
				'type' => 'string',
				'sanitize_callback' => array($this, 'sanitize_license_status'),
				'default' => 'inactive',
			)
		);

		if (!$this->has_license_service_constants()) {
			register_setting(
				'foodord_license_settings',
				'foodord_license_service_endpoint',
				array(
					'type' => 'string',
					'sanitize_callback' => array($this, 'sanitize_license_service_endpoint'),
					'default' => 'https://foodord.com/wp-json/foodord-cloud/v1/license/verify',
				)
			);

			register_setting(
				'foodord_license_settings',
				'foodord_license_service_key',
				array(
					'type' => 'string',
					'sanitize_callback' => array($this, 'sanitize_license_service_key'),
					'default' => '',
				)
			);
		}
	}

	/**
	 * Enqueue admin scripts
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_scripts($hook)
	{
		foreach ($this->get_page_slugs() as $slug) {
			if ('' === $slug || false === strpos((string) $hook, $slug)) {
				continue;
			}

			wp_enqueue_style(
				'foodord-license-page',
				plugin_dir_url(__FILE__) . 'css/foodord-license-page.css',
				array(),
				FOODORD_VERSION
			);

			wp_enqueue_style(
				'foodord-admin-faq',
				plugin_dir_url(__FILE__) . 'css/foodord-admin-faq.css',
				array('foodord-license-page'),
				FOODORD_VERSION
			);

			wp_enqueue_script(
				'foodord-license',
				plugin_dir_url(__FILE__) . 'js/foodord-license.js',
				array('jquery'),
				FOODORD_VERSION,
				true
			);
			break;
		}
	}

	/**
	 * Sanitize license key
	 *
	 * @param string $value License key value.
	 * @return string
	 */
	public function sanitize_license_key($value)
	{
		return sanitize_text_field(trim($value));
	}

	/**
	 * Sanitize license status.
	 *
	 * @param mixed $value License status value.
	 * @return string
	 */
	public function sanitize_license_status($value): string
	{
		$status = sanitize_key((string) $value);
		return in_array($status, array('active', 'inactive'), true) ? $status : 'inactive';
	}

	/**
	 * Handle license save
	 */
	public function handle_license_save()
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('Insufficient permissions', 'foodord'));
		}

		check_admin_referer('foodord_license_settings_nonce');

		$license_key = isset($_POST['foodord_license_key']) ? sanitize_text_field(wp_unslash($_POST['foodord_license_key'])) : '';
		$using_constants = $this->has_license_service_constants();

		if (class_exists('Foodord_Live_Orders_Quota')) {
			Foodord_Live_Orders_Quota::clear_status_cache();
		}

		if (!$using_constants) {
			$endpoint = isset($_POST['foodord_license_service_endpoint']) ? esc_url_raw(wp_unslash($_POST['foodord_license_service_endpoint'])) : '';
			$endpoint = '' !== $endpoint ? untrailingslashit($endpoint) : '';
			$api_key = isset($_POST['foodord_license_service_key']) ? wp_kses(wp_unslash($_POST['foodord_license_service_key']), array()) : '';

			update_option('foodord_license_service_endpoint', $endpoint);
			update_option('foodord_license_service_key', $api_key);
		}

		if (empty($license_key)) {
			update_option('foodord_license_status', 'inactive');
			update_option('foodord_license_key', '');
			delete_option('foodord_license_details');
			set_transient('foodord_license_removed', true, 45);
			delete_transient('foodord_license_error');
			wp_safe_redirect($this->get_license_page_url());
			exit;
		}

		$license_key = str_replace(array(' ', '\r', '\n', '\t'), '', $license_key);

		// Validate license key format (Purchase code: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
		if (!preg_match('/^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/i', $license_key)) {
			set_transient('foodord_license_invalid_format', true, 45);
			delete_transient('foodord_license_error');
			wp_safe_redirect($this->get_license_page_url());
			exit;
		}

		$validation = $this->validate_license_with_service($license_key);

		if (is_wp_error($validation)) {
			update_option('foodord_license_status', 'inactive');
			update_option('foodord_license_key', $license_key);
			delete_option('foodord_license_details');
			set_transient('foodord_license_error', wp_strip_all_tags($validation->get_error_message()), 45);
			wp_safe_redirect($this->get_license_page_url());
			exit;
		}

		$resolved_status = 'inactive';
		if (
			isset($validation['license']) &&
			is_array($validation['license']) &&
			isset($validation['license']['status']) &&
			'active' === strtolower((string) $validation['license']['status'])
		) {
			$resolved_status = 'active';
		}

		update_option('foodord_license_key', $license_key);
		update_option('foodord_license_status', $resolved_status);
		update_option('foodord_license_details', $validation);
		set_transient('foodord_license_saved', true, 45);
		delete_transient('foodord_license_error');

		wp_safe_redirect($this->get_license_page_url());
		exit;
	}

	/**
	 * Render the License settings page.
	 */
	public function render_license_page()
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'foodord'));
		}

		$license_key = get_option('foodord_license_key', '');

		if (!empty($license_key) && function_exists('foodord_sync_license_status')) {
			foodord_sync_license_status(true);
		}

		$license_status = get_option('foodord_license_status', 'inactive');
		$service_config = $this->get_license_service_config();
		$license_details = get_option('foodord_license_details', array());
		$has_active_license = !empty($license_details) && 'active' === $license_status;
		$using_constants = $this->has_license_service_constants();
		?>
		<div class="wrap foodord-settings-wrap foodord-license-page-root">
			<h1 class="wp-heading-inline"><?php echo esc_html__('FoodOrd License Management', 'foodord'); ?></h1>
			<p class="foodord-license-intro-text"><?php echo esc_html__('Level up your ordering experience.', 'foodord'); ?>
			</p>

			<?php
			if (function_exists('foodord_admin_render_horizontal_menu')) {
				foodord_admin_render_horizontal_menu();
			}
			?>

			<div class="foodord-license-page">


				<section class="foodord-license-features">
					<div class="foodord-license-feature-card">
						<span class="foodord-license-feature-icon">💻</span>
						<h3 class="foodord-license-feature-title"><?php echo esc_html__('Desktop Application', 'foodord'); ?>
						</h3>
						<p class="foodord-license-feature-text">
							<?php echo esc_html__('Get instant order notifications and automatic printer output with our dedicated app for Windows and Mac.', 'foodord'); ?>
						</p>
					</div>
					<div class="foodord-license-feature-card">
						<span class="foodord-license-feature-icon">🚀</span>
						<h3 class="foodord-license-feature-title"><?php echo esc_html__('FoodOrd Pro Features', 'foodord'); ?>
						</h3>
						<p class="foodord-license-feature-text">
							<?php echo esc_html__('Power up with loyalty programs, advanced pricing rules, and tipping systems.', 'foodord'); ?>
						</p>
					</div>
					<div class="foodord-license-feature-card">
						<span class="foodord-license-feature-icon">🛠️</span>
						<h3 class="foodord-license-feature-title"><?php echo esc_html__('Priority Support', 'foodord'); ?></h3>
						<p class="foodord-license-feature-text">
							<?php echo esc_html__('Get access to dedicated fast technical support and regular feature updates for active license holders.', 'foodord'); ?>
						</p>
					</div>
				</section>

				<main class="foodord-license-main-card">
					<h2 class="foodord-license-main-title"><?php echo esc_html__('Activate Your License', 'foodord'); ?></h2>

					<?php
					// Check for transient messages.
					if (get_transient('foodord_license_saved')) {
						delete_transient('foodord_license_saved');
						echo '<div class="notice notice-success is-dismissible"><p class="foodord-license-notice-text">' . esc_html__('License key activated successfully.', 'foodord') . '</p></div>';
					}
					if (get_transient('foodord_license_removed')) {
						delete_transient('foodord_license_removed');
						echo '<div class="notice notice-info is-dismissible"><p class="foodord-license-notice-text">' . esc_html__('License key removed.', 'foodord') . '</p></div>';
					}
					if (get_transient('foodord_license_invalid_format')) {
						delete_transient('foodord_license_invalid_format');
						echo '<div class="notice notice-error is-dismissible"><p class="foodord-license-notice-text">' . esc_html__('Invalid license format. Please enter your purchase code.', 'foodord') . '</p></div>';
					}
					$error_message = get_transient('foodord_license_error');
					if ($error_message) {
						delete_transient('foodord_license_error');
						echo '<div class="notice notice-error is-dismissible"><p class="foodord-license-notice-text">' . esc_html($error_message) . '</p></div>';
					}
					?>

					<form class="foodord-license-form" method="post"
						action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
						<input type="hidden" name="action" value="foodord_save_license" class="foodord-license-action-field">
						<?php
						$nonce_field = wp_nonce_field('foodord_license_settings_nonce', '_wpnonce', true, false);
						$nonce_field = str_replace('<input type="hidden"', '<input class="foodord-license-hidden-field" type="hidden"', $nonce_field);
						$allowed_nonce_tags = array(
							'input' => array(
								'type' => true,
								'name' => true,
								'value' => true,
								'id' => true,
								'class' => true,
							),
						);
						echo wp_kses($nonce_field, $allowed_nonce_tags);
						?>

						<div class="foodord-license-form-group">
							<div class="foodord-license-input-wrapper">
								<div class="foodord-license-input-control">
									<input type="text" id="foodord_license_key" name="foodord_license_key"
										value="<?php echo esc_attr($license_key); ?>" class="foodord-license-input"
										placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" maxlength="36" required>
									<button type="button" class="foodord-license-copy"
										data-foodord-license-copy
										data-copy-label="<?php echo esc_attr__('Copy to clipboard', 'foodord'); ?>"
										data-copied-label="<?php echo esc_attr__('Copied', 'foodord'); ?>"
										aria-label="<?php echo esc_attr__('Copy to clipboard', 'foodord'); ?>"
										title="<?php echo esc_attr__('Copy to clipboard', 'foodord'); ?>">
										<span class="foodord-license-copy__icon" aria-hidden="true"></span>
										<span class="foodord-license-copy__feedback" aria-hidden="true"><?php echo esc_html__('Copied', 'foodord'); ?></span>
									</button>
								</div>
								<button type="submit" class="foodord-license-submit">
									<?php echo esc_html__('Activate', 'foodord'); ?>
								</button>
							</div>
							<p class="foodord-license-help">
								<?php echo esc_html__('You can find your license key as "Purchase Code" in the file you received from FoodOrd.', 'foodord'); ?>
							</p>
						</div>
					</form>

					<?php if ($has_active_license): ?>
						<div class="foodord-license-details">
							<h4 class="foodord-license-details-title"><?php echo esc_html__('License Information', 'foodord'); ?></h4>
							<ul class="foodord-license-details-list">
								<li>
									<span><?php echo esc_html__( 'Status', 'foodord' ); ?></span>
									<div class="foodord-license-status-check">
										<i class="foodord-status-dot is-active"></i>
										<strong><?php echo esc_html__( 'Active', 'foodord' ); ?></strong>
									</div>
								</li>
								<?php if (isset($license_details['license']['domain'])): ?>
									<li>
										<span><?php echo esc_html__('Licensed Domain', 'foodord'); ?></span>
										<strong><?php echo esc_html($license_details['license']['domain']); ?></strong>
									</li>
								<?php endif; ?>
								<li>
									<span><?php echo esc_html__('License Type', 'foodord'); ?></span>
									<strong>
										<?php
										$license_type = isset($license_details['license']['type']) ? strtolower((string) $license_details['license']['type']) : 'lifetime';
										if ( 'subscription' === $license_type ) {
											echo esc_html__( 'Subscription', 'foodord' );
										} else {
											echo esc_html__( 'Lifetime', 'foodord' );
										}
										?>
									</strong>
								</li>
								<?php if (isset($license_details['license']['billingStatus']) && '' !== (string) $license_details['license']['billingStatus']): ?>
									<li>
										<span><?php echo esc_html__('Billing Status', 'foodord'); ?></span>
										<strong><?php echo esc_html(ucwords(str_replace('_', ' ', (string) $license_details['license']['billingStatus']))); ?></strong>
									</li>
								<?php endif; ?>
								<?php if (isset($license_details['license']['expiresAt']) && '' !== (string) $license_details['license']['expiresAt']): ?>
									<li>
										<span><?php echo esc_html__('Access Until', 'foodord'); ?></span>
										<strong>
											<?php
											$expires_at = (string) $license_details['license']['expiresAt'];
											echo esc_html(
												mysql2date(
													get_option('date_format') . ' ' . get_option('time_format'),
													$expires_at
												)
											);
											?>
										</strong>
									</li>
								<?php endif; ?>
								<?php if (isset($license_details['license']['daysRemaining']) && '' !== (string) $license_details['license']['daysRemaining']): ?>
									<li>
										<span><?php echo esc_html__('Remaining Days', 'foodord'); ?></span>
										<strong><?php echo esc_html((string) $license_details['license']['daysRemaining']); ?></strong>
									</li>
								<?php endif; ?>
							</ul>
							<?php if (isset($license_details['license']['notice']) && '' !== (string) $license_details['license']['notice']): ?>
								<div class="notice notice-warning inline">
									<p class="foodord-license-notice-text"><?php echo esc_html((string) $license_details['license']['notice']); ?></p>
								</div>
							<?php endif; ?>
						</div>
					<?php elseif (!empty($license_key)): ?>
						<div class="foodord-license-details">
							<h4 class="foodord-license-details-title"><?php echo esc_html__('License Information', 'foodord'); ?></h4>
							<ul class="foodord-license-details-list">
								<li>
									<span><?php echo esc_html__( 'Status', 'foodord' ); ?></span>
									<div class="foodord-license-status-check">
										<i class="foodord-status-dot is-inactive"></i>
										<strong><?php echo esc_html__( 'Verification Pending / Inactive', 'foodord' ); ?></strong>
									</div>
								</li>
							</ul>
						</div>
					<?php endif; ?>

					<?php if (!$using_constants): ?>
						<div class="foodord-license-service-config">
							<p class="foodord-license-service-label">
								<?php echo esc_html__('Service Configuration (Advanced)', 'foodord'); ?>
							</p>
							<div class="foodord-license-service-items">
								<div class="foodord-license-service-item">
									<strong
										class="foodord-license-service-item-title"><?php echo esc_html__('Endpoint:', 'foodord'); ?></strong>
									<code
										class="foodord-license-service-code"><?php echo esc_html($service_config['endpoint']); ?></code>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</main>

				<?php if (!$has_active_license): ?>
					<?php $this->render_pricing_table(); ?>
				<?php endif; ?>

				<footer class="foodord-license-footer">
					<p class="foodord-license-footer-text">
						<?php echo esc_html__('Having trouble?', 'foodord'); ?>
						<a href="https://foodord.com/support"
							target="_blank"><?php echo esc_html__('Create a Support Ticket', 'foodord'); ?></a>
					</p>
				</footer>
				<?php
				if (function_exists('foodord_admin_render_faq_section')) {
					foodord_admin_render_faq_section('license');
				}
				?>
			</div>
			<?php
	}

	/**
	 * Validate license using the remote FoodOrd license service.
	 *
	 * @param string $license_key License key.
	 * @return array|\WP_Error
	 */
	private function validate_license_with_service($license_key)
	{
		$config = $this->get_license_service_config();

		if (empty($config['endpoint'])) {
			return new \WP_Error('foodord_license_missing_config', esc_html__('Please configure the license service endpoint before validating the license.', 'foodord'));
		}

		$domain = $this->normalize_domain(wp_parse_url(home_url(), PHP_URL_HOST));
		$request_map = array(
			'purchaseCode' => $license_key,
			'domain' => $domain,
			'siteUrl' => home_url(),
		);

		$args = array(
			'timeout' => 20,
			'headers' => array(
				'content-type' => 'application/json',
				'accept' => 'application/json',
			),
			'body' => wp_json_encode($request_map),
			'method' => 'POST',
		);

		if (!empty($config['api_key'])) {
			$args['headers']['x-foodord-license-key'] = $config['api_key'];
		}

		$response = wp_remote_request($config['endpoint'], $args);

		if (is_wp_error($response)) {
			return new \WP_Error('foodord_license_request_failed', esc_html__('Unable to reach the FoodOrd license service. Please try again.', 'foodord'));
		}

		$status_code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if (null === $data) {
			return new \WP_Error('foodord_license_bad_response', esc_html__('License service returned an unexpected response.', 'foodord'));
		}

		if ($status_code >= 400) {
			$reason = isset($data['reason']) ? (string) $data['reason'] : '';
			$message = isset($data['message']) ? (string) $data['message'] : esc_html__('License validation failed.', 'foodord');

			return new \WP_Error('foodord_license_invalid', $this->format_license_error_reason($reason, $message));
		}

		$is_valid = isset($data['valid']) ? (bool) $data['valid'] : false;

		if (!$is_valid) {
			$reason = isset($data['reason']) ? (string) $data['reason'] : '';
			$message = isset($data['message']) ? (string) $data['message'] : esc_html__('License could not be validated.', 'foodord');

			return new \WP_Error('foodord_license_invalid', $this->format_license_error_reason($reason, $message));
		}

		$details = array();

		if (isset($data['license']) && is_array($data['license'])) {
			$details = $data['license'];
		}

		if (!isset($details['purchaseCode']) || '' === $details['purchaseCode']) {
			$details['purchaseCode'] = $license_key;
		}

		if (isset($details['domain'])) {
			$details['domain'] = $this->normalize_domain($details['domain']);
		}

		if (empty($details['domain'])) {
			$details['domain'] = $domain;
		}

		if (isset($details['status'])) {
			$details['status'] = (string) $details['status'];
		}

		return array(
			'license' => $details,
		);
	}

	/**
	 * Normalize the domain value for comparisons.
	 *
	 * @param string $value Raw domain.
	 * @return string
	 */
	private function normalize_domain($value)
	{
		$value = (string) $value;
		$value = trim($value);

		if ('' === $value) {
			return '';
		}

		$host = wp_parse_url($value, PHP_URL_HOST);

		if (false === $host || null === $host) {
			$host = $value;
		}

		$host = strtolower(trim($host));

		if (0 === strpos($host, 'www.')) {
			$host = substr($host, 4);
		}

		return $host;
	}

	/**
	 * Retrieve license service configuration.
	 *
	 * @return array
	 */
	private function get_license_service_config()
	{
		$default_endpoint = 'https://foodord.com/wp-json/foodord-cloud/v1/license/verify';

		if ($this->has_license_service_constants()) {
			return array(
				'endpoint' => defined('FOODORD_LICENSE_SERVICE_ENDPOINT') ? untrailingslashit((string) FOODORD_LICENSE_SERVICE_ENDPOINT) : '',
				'api_key' => defined('FOODORD_LICENSE_SERVICE_KEY') ? (string) FOODORD_LICENSE_SERVICE_KEY : '',
			);
		}

		return array(
			'endpoint' => untrailingslashit(get_option('foodord_license_service_endpoint', $default_endpoint)),
			'api_key' => get_option('foodord_license_service_key', ''),
		);
	}

	/**
	 * Sanitize license service endpoint URL.
	 *
	 * @param string $value Raw value.
	 * @return string
	 */
	public function sanitize_license_service_endpoint($value)
	{
		$value = trim((string) $value);

		if ('' === $value) {
			return '';
		}

		$sanitized = esc_url_raw($value);

		if (empty($sanitized)) {
			return '';
		}

		return untrailingslashit($sanitized);
	}

	/**
	 * Sanitize license service API key.
	 *
	 * @param string $value Raw value.
	 * @return string
	 */
	public function sanitize_license_service_key($value)
	{
		$value = trim((string) $value);

		if ('' === $value) {
			return '';
		}

		return wp_kses($value, array());
	}

	/**
	 * Determine whether license service config constants are defined.
	 *
	 * @return bool
	 */
	private function has_license_service_constants()
	{
		$endpoint = defined('FOODORD_LICENSE_SERVICE_ENDPOINT') ? trim((string) FOODORD_LICENSE_SERVICE_ENDPOINT) : '';

		return '' !== $endpoint;
	}

	/**
	 * Convert remote error reason to a friendly message.
	 *
	 * @param string $reason   Raw reason string.
	 * @param string $fallback Fallback message.
	 * @return string
	 */
	private function format_license_error_reason($reason, $fallback)
	{
		$reason = is_string($reason) ? strtolower(trim($reason)) : '';

		$messages = array(
			'missing_code' => esc_html__('License code is required.', 'foodord'),
			'not_found' => esc_html__('No valid license was found for this code.', 'foodord'),
			'domain_mismatch' => esc_html__('This license is not registered for the current domain.', 'foodord'),
			'invalid_status' => esc_html__('The license is not active.', 'foodord'),
			'payment_required' => esc_html__('The subscription payment is required before this license can be used.', 'foodord'),
			'invalid_expiry' => esc_html__('The subscription expiry date is invalid. Please contact support.', 'foodord'),
			'internal_error' => esc_html__('License validation service is temporarily unavailable. Please try again later.', 'foodord'),
		);

		if ('' !== $reason && isset($messages[$reason])) {
			return $messages[$reason];
		}

		return $fallback;
	}
}
