<?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());
	}

	/**
	 * 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_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 (!$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());
		$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 table ordering, 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">
								<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="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 (!empty($license_details) && 'active' === $license_status): ?>
						<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>

				<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>
			</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;
	}
}
