<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

include_once SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/settings-pages-header-template.php';

$features_dir           = trailingslashit( SFTCY_WORDAI_PLUGIN_DIR ) . 'features/';
$basic_features_file    = $features_dir . 'basic-features.json';
$pro_features_file      = $features_dir . 'pro-features.json';
$comparison_ui_file     = $features_dir . 'feature-comparison-ui.json';
$basic_features_payload = file_exists( $basic_features_file ) ? json_decode( file_get_contents( $basic_features_file ), true ) : array();
$pro_features_payload   = file_exists( $pro_features_file ) ? json_decode( file_get_contents( $pro_features_file ), true ) : array();
$comparison_ui_payload  = file_exists( $comparison_ui_file ) ? json_decode( file_get_contents( $comparison_ui_file ), true ) : array();
$upgrade_url            = class_exists( 'SftcyWordaiFeatures' ) ? SftcyWordaiFeatures::wordai_get_upgrade_url() : 'https://softcoy.com/products/wordai-pro/checkout';

$hero_items   = ! empty( $comparison_ui_payload['uiSections']['hero'] ) && is_array( $comparison_ui_payload['uiSections']['hero'] ) ? $comparison_ui_payload['uiSections']['hero'] : array();
$table_rows   = ! empty( $comparison_ui_payload['uiSections']['comparison_table'] ) && is_array( $comparison_ui_payload['uiSections']['comparison_table'] ) ? $comparison_ui_payload['uiSections']['comparison_table'] : array();
$notice_cards = ! empty( $comparison_ui_payload['uiSections']['limited_features_cards'] ) && is_array( $comparison_ui_payload['uiSections']['limited_features_cards'] ) ? $comparison_ui_payload['uiSections']['limited_features_cards'] : array();
$cta_copy     = ! empty( $comparison_ui_payload['uiSections']['cta'] ) && is_array( $comparison_ui_payload['uiSections']['cta'] ) ? $comparison_ui_payload['uiSections']['cta'] : array();

$feature_labels = array();
foreach ( array( $basic_features_payload, $pro_features_payload ) as $payload ) {
	if ( empty( $payload['modules'] ) || ! is_array( $payload['modules'] ) ) {
		continue;
	}

	foreach ( $payload['modules'] as $module ) {
		if ( ! empty( $module['label'] ) && ! empty( $module['key'] ) ) {
			$feature_labels[ sanitize_key( (string) $module['key'] ) ] = sanitize_text_field( $module['label'] );
		}

		if ( empty( $module['features'] ) || ! is_array( $module['features'] ) ) {
			continue;
		}

		foreach ( $module['features'] as $feature_entry ) {
			if ( is_array( $feature_entry ) ) {
				$feature_key   = ! empty( $feature_entry['key'] ) ? sanitize_key( (string) $feature_entry['key'] ) : '';
				$feature_label = ! empty( $feature_entry['label'] ) ? sanitize_text_field( $feature_entry['label'] ) : '';
			} else {
				$feature_key   = sanitize_key( (string) $feature_entry );
				$feature_label = '';
			}

			if ( '' === $feature_key ) {
				continue;
			}

			if ( '' === $feature_label ) {
				$feature_label = ucwords( str_replace( array( '_', '-' ), ' ', $feature_key ) );
			}

			if ( ! isset( $feature_labels[ $feature_key ] ) || ( is_array( $feature_entry ) && '' !== $feature_label ) ) {
				$feature_labels[ $feature_key ] = $feature_label;
			}
		}
	}
}

$feature_flag_registry = class_exists( 'SftcyWordaiFeatures' ) ? SftcyWordaiFeatures::wordai_get_feature_flags_registry() : array( 'features' => array() );
$feature_flag_map      = ! empty( $feature_flag_registry['features'] ) && is_array( $feature_flag_registry['features'] ) ? $feature_flag_registry['features'] : array();

$resolve_feature_status = static function( $feature_key, $tier ) use ( $feature_flag_map ) {
	$feature_key = sanitize_key( str_replace( '-', '_', (string) $feature_key ) );
	$tier        = sanitize_key( (string) $tier );

	if ( empty( $feature_flag_map[ $feature_key ] ) || ! is_array( $feature_flag_map[ $feature_key ] ) ) {
		return array(
			'status' => 'basic' === $tier ? 'pro_only' : 'full',
			'limits' => array(),
		);
	}

	$feature_map = $feature_flag_map[ $feature_key ];

	return array(
		'status' => isset( $feature_map[ $tier ] ) ? sanitize_key( $feature_map[ $tier ] ) : ( 'basic' === $tier ? 'pro_only' : 'full' ),
		'limits' => ! empty( $feature_map['limits'][ $tier ] ) && is_array( $feature_map['limits'][ $tier ] ) ? $feature_map['limits'][ $tier ] : array(),
	);
};

$render_status_badge = static function( $status, $limits = array() ) {
	$status = sanitize_key( (string) $status );

	if ( 'full' === $status ) {
		return '<span class="wordai-license-status-badge is-full">' . esc_html__( 'Full access', 'wordai' ) . '</span>';
	}

	if ( 'limited' === $status ) {
		return '<span class="wordai-license-status-badge is-limited">' . esc_html__( 'Limited access', 'wordai' ) . '</span>';
	}

	return '<span class="wordai-license-status-badge is-pro">' . esc_html__( 'Pro only', 'wordai' ) . '</span>';
};

$feature_icon_map = array(
	'unlock_more_targets'            => 'fa-solid fa-layer-group',
	'unlock_more_ai'                 => 'fa-solid fa-brain',
	'unlock_agent'                   => 'fa-solid fa-comments',
	'prompt_assistant'               => 'fa-solid fa-wand-magic-sparkles',
	'image_generation'               => 'fa-solid fa-image',
	'auto_insert_images'             => 'fa-solid fa-photo-film',
	'contents_embedding'             => 'fa-solid fa-database',
	'chat_analytics'                 => 'fa-solid fa-chart-line',
	'chat_lead_capture'              => 'fa-solid fa-address-card',
	'chat_handoff'                   => 'fa-solid fa-headset',
	'seo_scan'                       => 'fa-solid fa-magnifying-glass',
	'scheduled_seo_scans'            => 'fa-solid fa-calendar-check',
	'advanced_seo_content_controls'  => 'fa-solid fa-arrow-trend-up',
	'search_console'                 => 'fa-brands fa-google',
);

$render_feature_card_icon = static function( $key ) use ( $feature_icon_map ) {
	$key        = sanitize_key( (string) $key );
	$icon_class = isset( $feature_icon_map[ $key ] ) ? $feature_icon_map[ $key ] : 'fa-solid fa-sparkles';

	return '<span class="wordai-free-go-pro-card-icon" aria-hidden="true"><i class="' . esc_attr( $icon_class ) . '"></i></span>';
};
?>

<div class="wrap wordai-license-shell wordai-license-shell-free">
	<div class="wordai-license-hero-card">
		<div class="wordai-license-hero-copy">
			<div class="wordai-license-eyebrow"><?php esc_html_e( 'Get Pro', 'wordai' ); ?></div>
			<h2 class="wordai-license-page-header">
				<i class="fa-solid fa-bolt"></i>
				<?php esc_html_e( 'Upgrade WordAI to Pro', 'wordai' ); ?>
			</h2>
			<p class="wordai-license-hero-text">
				<?php esc_html_e( 'Turn WordAI into a complete AI publishing, SEO, image, and website assistant workspace. Pro unlocks full generation workflows, advanced SEO automation, richer image controls, larger AI Agent knowledge bases, Search Console insights, and priority in-plugin support from the same WordPress dashboard.', 'wordai' ); ?>
			</p>
			<div class="wordai-license-hero-actions">
				<a class="button button-primary button-large wordai-buy-pro-focus" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener"><i class="fa-solid fa-cart-shopping" aria-hidden="true"></i><?php echo esc_html( ! empty( $cta_copy['primaryLabel'] ) ? $cta_copy['primaryLabel'] : __( 'Buy WordAI Pro', 'wordai' ) ); ?></a>
				<a class="button button-secondary button-large" href="<?php echo esc_url( admin_url( 'admin.php?page=sc-wordai-support' ) ); ?>"><?php esc_html_e( 'In-Plugin Support', 'wordai' ); ?></a>
				<a class="button button-secondary button-large" href="https://softcoy.com/support" target="_blank" rel="noopener"><?php esc_html_e( 'SOFTCOY Support', 'wordai' ); ?></a>
			</div>
		</div>

		<div class="wordai-license-summary-grid">
			<div class="wordai-license-summary-card">
				<strong><?php esc_html_e( 'Higher content and image capacity', 'wordai' ); ?></strong>
				<span><?php esc_html_e( 'Create more complete posts, pages, product content, SEO metadata, and image workflows for real publishing campaigns.', 'wordai' ); ?></span>
			</div>
			<div class="wordai-license-summary-card">
				<strong><?php esc_html_e( 'Advanced SEO and search insights', 'wordai' ); ?></strong>
				<span><?php esc_html_e( 'Use AI SEO Scan, AI Auto Fix, content-decay opportunities, Search Console reports, and Pro content guidance to improve search visibility faster.', 'wordai' ); ?></span>
			</div>
			<div class="wordai-license-summary-card">
				<strong><?php esc_html_e( 'AI Agent for leads and support', 'wordai' ); ?></strong>
				<span><?php esc_html_e( 'Build a stronger front-end assistant with embedded site knowledge, visitor lead capture, analytics, handoff options, and clean Pro branding.', 'wordai' ); ?></span>
			</div>
		</div>
	</div>

	<div class="wordai-license-flow-grid">
		<div class="wordai-license-flow-card">
			<h3><?php esc_html_e( 'How the upgrade path works', 'wordai' ); ?></h3>
			<ol class="wordai-license-step-list">
				<li>
					<strong><?php esc_html_e( 'Enter the WordAI Pro license key', 'wordai' ); ?></strong>
					<span><?php esc_html_e( 'Use the key from your purchase email or customer account. The upgrade validates it first before attempting any package replacement.', 'wordai' ); ?></span>
				</li>
				<li>
					<strong><?php esc_html_e( 'Run Upgrade to Pro from this page', 'wordai' ); ?></strong>
					<span><?php esc_html_e( 'If the license is active and the site is within the allowed activation limit, the free plugin is replaced automatically from inside wp-admin.', 'wordai' ); ?></span>
				</li>
				<li>
					<strong><?php esc_html_e( 'Continue with Pro features and support', 'wordai' ); ?></strong>
					<span><?php esc_html_e( 'After activation, premium updates, licensed access, and the in-plugin support workflow continue from the Pro plugin admin screens.', 'wordai' ); ?></span>
				</li>
			</ol>
		</div>

		<div class="wordai-license-form-card">
			<div class="sc-wordai-license-message-settings-info" role="status" aria-live="polite"></div>

			<form id="scWordAILicenseKey" method="post" data-primary-action="upgrade">
				<div class="wordai-license-form-head">
					<h3><?php esc_html_e( 'License key upgrade', 'wordai' ); ?></h3>
					<p><?php esc_html_e( 'Paste your valid Pro key and start the upgrade. If anything blocks the request, you will see the exact message on this page.', 'wordai' ); ?></p>
				</div>

				<div class="wordai-license-field-block">
					<label for="wordaiProLicenseKey"><?php esc_html_e( 'WordAI Pro License Key', 'wordai' ); ?></label>
					<div class="wordai-license-input-shell">
						<span class="wordai-license-input-icon"><i class="fa-solid fa-key"></i></span>
						<input type="text" id="wordaiProLicenseKey" value="" name="wordai-pro-license-key" class="wordai-pro-license-key" placeholder="<?php esc_attr_e( 'Paste your license key here', 'wordai' ); ?>" autocomplete="off" />
					</div>
					<small><?php esc_html_e( 'The upgrade flow validates the key, checks the current site allowance, and only continues when the license can be used on this installation.', 'wordai' ); ?></small>
				</div>

				<div class="wordai-license-form-actions">
					<button type="button" class="button button-primary button-large sc-wordai-upgrade-to-pro-btn">
						<i class="fa-solid fa-arrow-up-right-dots"></i>
						<?php esc_html_e( 'Upgrade to Pro', 'wordai' ); ?>
					</button>
				</div>
			</form>

			<div class="wordai-license-support-panel">
				<div class="wordai-license-support-copy">
					<strong><?php esc_html_e( 'Need help with a license, site activation, or upgrade issue?', 'wordai' ); ?></strong>
					<span><?php esc_html_e( 'Open support if the key is rejected, if the site limit needs review, or if you want help finishing the Pro conversion safely.', 'wordai' ); ?></span>
				</div>
				<div class="wordai-license-support-links">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=sc-wordai-support' ) ); ?>"><?php esc_html_e( 'In-Plugin Support', 'wordai' ); ?></a>
					<a href="https://softcoy.com/support" target="_blank" rel="noopener"><?php esc_html_e( 'SOFTCOY Support', 'wordai' ); ?></a>
				</div>
			</div>
		</div>
	</div>

	<?php if ( ! empty( $hero_items ) ) : ?>
		<div class="wordai-free-go-pro-grid wordai-license-feature-grid">
			<?php foreach ( $hero_items as $hero_item ) : ?>
				<div class="wordai-free-go-pro-card">
					<?php echo $render_feature_card_icon( $hero_item['key'] ?? '' ); ?>
					<h3><?php echo esc_html( isset( $hero_item['title'] ) ? $hero_item['title'] : '' ); ?></h3>
					<p><?php echo esc_html( isset( $hero_item['description'] ) ? $hero_item['description'] : '' ); ?></p>
				</div>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>

	<div id="wordai-free-feature-comparison" class="wordai-free-go-pro-table wordai-license-comparison-table">
		<h2><?php esc_html_e( 'WordAI Free vs WordAI Pro', 'wordai' ); ?></h2>
		<table>
			<thead>
				<tr>
					<th><?php esc_html_e( 'Feature', 'wordai' ); ?></th>
					<th><?php esc_html_e( 'WordAI Free', 'wordai' ); ?></th>
					<th><?php esc_html_e( 'WordAI Pro', 'wordai' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $table_rows as $row_group ) : ?>
					<tr class="wordai-free-go-pro-group-row">
						<td colspan="3"><?php echo esc_html( isset( $row_group['group'] ) ? $row_group['group'] : '' ); ?></td>
					</tr>
					<?php foreach ( (array) ( $row_group['rows'] ?? array() ) as $feature_key ) : ?>
						<?php
						$basic_status  = $resolve_feature_status( $feature_key, 'basic' );
						$pro_status    = $resolve_feature_status( $feature_key, 'pro' );
						$feature_index = sanitize_key( (string) $feature_key );
						$feature_label = isset( $feature_labels[ $feature_index ] ) ? $feature_labels[ $feature_index ] : ucwords( str_replace( array( '-', '_' ), ' ', (string) $feature_key ) );
						?>
						<tr>
							<td><?php echo esc_html( $feature_label ); ?></td>
							<td><?php echo $render_status_badge( $basic_status['status'], $basic_status['limits'] ); ?></td>
							<td><?php echo $render_status_badge( $pro_status['status'], $pro_status['limits'] ); ?></td>
						</tr>
					<?php endforeach; ?>
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>

	<?php if ( ! empty( $notice_cards ) ) : ?>
		<div class="wordai-free-go-pro-limits-grid">
			<?php foreach ( $notice_cards as $card ) : ?>
				<div class="wordai-free-go-pro-card">
					<?php echo $render_feature_card_icon( $card['featureKey'] ?? '' ); ?>
					<h3><?php echo esc_html( isset( $card['title'] ) ? $card['title'] : '' ); ?></h3>
					<p><?php echo esc_html( isset( $card['description'] ) ? $card['description'] : '' ); ?></p>
				</div>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>

	<div class="wordai-free-go-pro-cta">
		<div>
			<h2><?php echo esc_html( ! empty( $cta_copy['title'] ) ? $cta_copy['title'] : __( 'Unlock WordAI Pro', 'wordai' ) ); ?></h2>
			<p><?php echo esc_html( ! empty( $cta_copy['description'] ) ? $cta_copy['description'] : __( 'Unlock higher limits, premium AI controls, richer media workflows, and licensed support from the same plugin admin experience.', 'wordai' ) ); ?></p>
		</div>
		<div class="wordai-free-upgrade-actions">
			<a class="button button-primary button-large wordai-buy-pro-focus" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener"><i class="fa-solid fa-cart-shopping" aria-hidden="true"></i><?php echo esc_html( ! empty( $cta_copy['primaryLabel'] ) ? $cta_copy['primaryLabel'] : __( 'Buy WordAI Pro', 'wordai' ) ); ?></a>
		</div>
	</div>
</div>
