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

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

$features_dir           = trailingslashit( SFTCY_WORDFORM_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( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_get_upgrade_url() : 'https://softcoy.com/products/wordform-pro/checkout';

$hero_items    = array();
$table_rows    = array();
$notice_cards  = array();
$cta_copy      = array();
$feature_labels = array();

if ( ! empty( $comparison_ui_payload['uiSections'] ) && is_array( $comparison_ui_payload['uiSections'] ) ) {
	foreach ( $comparison_ui_payload['uiSections'] as $section ) {
		$section_key = isset( $section['key'] ) ? sanitize_key( $section['key'] ) : '';
		if ( 'hero' === $section_key ) {
			$hero_items = ! empty( $section['items'] ) && is_array( $section['items'] ) ? $section['items'] : array();
		} elseif ( 'comparison_table' === $section_key ) {
			$table_rows = ! empty( $section['rows'] ) && is_array( $section['rows'] ) ? $section['rows'] : array();
		} elseif ( 'limited_features_cards' === $section_key ) {
			$notice_cards = ! empty( $section['items'] ) && is_array( $section['items'] ) ? $section['items'] : array();
		} elseif ( 'cta' === $section_key ) {
			$cta_copy = ! empty( $section['copy'] ) && is_array( $section['copy'] ) ? $section['copy'] : array();
		}
	}
}

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

		foreach ( $payload[ $section_key ] as $module ) {
			if ( ! empty( $module['features'] ) && is_array( $module['features'] ) ) {
				foreach ( $module['features'] as $feature ) {
					if ( ! empty( $feature['key'] ) && ! empty( $feature['label'] ) ) {
						$feature_labels[ sanitize_key( $feature['key'] ) ] = sanitize_text_field( $feature['label'] );
					}
				}
			}

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

$feature_flag_registry = class_exists( 'SftcyWordformFeatures' ) ? SftcyWordformFeatures::wordform_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="wordform-go-pro-status-badge is-full">' . esc_html__( 'Included', 'wordform' ) . '</span>';
	}
	if ( 'limited' === $status ) {
		$label = ! empty( $limits['label'] ) ? sanitize_text_field( $limits['label'] ) : __( 'Included with limits', 'wordform' );
		return '<span class="wordform-go-pro-status-badge is-limited">' . esc_html( $label ) . '</span>';
	}

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

<div class="wrap wordform-license-shell wordform-license-shell-free">
	<div class="wordform-license-hero-card">
		<div class="wordform-license-hero-copy">
			<div class="wordform-license-eyebrow"><?php esc_html_e( 'Get Pro', 'wordform' ); ?></div>
			<h2 class="license-page-header">
				<i class="fa-solid fa-bolt"></i>
				<?php esc_html_e( 'Upgrade WordForm to Pro', 'wordform' ); ?>
			</h2>
			<p class="wordform-license-hero-text">
				<?php esc_html_e( 'Move from the free builder into the commercial workflow without leaving wp-admin. Enter your valid Pro license key, run the upgrade, and continue managing premium fields, payment-ready forms, automations, and real-time support from the same plugin interface.', 'wordform' ); ?>
			</p>
			<div class="wordform-license-hero-actions">
				<a class="button button-primary button-large" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Buy WordForm Pro', 'wordform' ); ?></a>
				<a class="button button-secondary button-large" href="<?php echo esc_url( admin_url( 'admin.php?page=wordform-support' ) ); ?>"><?php esc_html_e( 'In-Plugin Support', 'wordform' ); ?></a>
				<a class="button button-secondary button-large" href="https://softcoy.com/support" target="_blank" rel="noopener"><?php esc_html_e( 'SOFTCOY Support', 'wordform' ); ?></a>
			</div>
		</div>

		<div class="wordform-license-summary-grid">
			<div class="wordform-license-summary-card">
				<strong><?php esc_html_e( 'Premium fields and layouts', 'wordform' ); ?></strong>
				<span><?php esc_html_e( 'Unlock richer field types, deeper validation control, premium builder elements, and cleaner production-ready form experiences.', 'wordform' ); ?></span>
			</div>
			<div class="wordform-license-summary-card">
				<strong><?php esc_html_e( 'Payments and integrations', 'wordform' ); ?></strong>
				<span><?php esc_html_e( 'Add stronger checkout flows, more automation connectors, reporting helpers, and advanced operational visibility for live sites.', 'wordform' ); ?></span>
			</div>
			<div class="wordform-license-summary-card">
				<strong><?php esc_html_e( 'Support without leaving the plugin', 'wordform' ); ?></strong>
				<span><?php esc_html_e( 'Pro keeps the support workflow close to the product, so urgent tickets and replies stay accessible inside your WordPress admin page.', 'wordform' ); ?></span>
			</div>
		</div>
	</div>

	<div class="wordform-license-flow-grid">
		<div class="wordform-license-flow-card">
			<h3><?php esc_html_e( 'How the upgrade path works', 'wordform' ); ?></h3>
			<ol class="wordform-license-step-list">
				<li>
					<strong><?php esc_html_e( 'Enter the WordForm Pro license key', 'wordform' ); ?></strong>
					<span><?php esc_html_e( 'Use the exact key from your purchase email or customer account. The upgrade will validate it against the licensing service before any package change starts.', 'wordform' ); ?></span>
				</li>
				<li>
					<strong><?php esc_html_e( 'Run Upgrade to Pro from this page', 'wordform' ); ?></strong>
					<span><?php esc_html_e( 'If the license is active and the current site is within the allowed activation limit, the free plugin is replaced with the Pro package automatically.', 'wordform' ); ?></span>
				</li>
				<li>
					<strong><?php esc_html_e( 'Continue with Pro features and support', 'wordform' ); ?></strong>
					<span><?php esc_html_e( 'After activation, premium updates, licensed support access, and the in-plugin support workflow continue from the Pro plugin admin pages.', 'wordform' ); ?></span>
				</li>
			</ol>
		</div>

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

			<form id="scWordFormLicenseKey" method="post" data-primary-action="upgrade">
				<div class="wordform-license-form-head">
					<h3><?php esc_html_e( 'License key upgrade', 'wordform' ); ?></h3>
					<p><?php esc_html_e( 'Paste your valid Pro key and start the upgrade. If anything blocks the request, this screen will show a clear message so you know what to fix next.', 'wordform' ); ?></p>
				</div>

				<div class="wordform-license-field-block">
					<label for="wordformProLicenseKey"><?php esc_html_e( 'WordForm Pro License Key', 'wordform' ); ?></label>
					<div class="wordform-license-input-shell">
						<span class="wordform-license-input-icon"><i class="fa-solid fa-key"></i></span>
						<input type="text" id="wordformProLicenseKey" value="" name="wordform-pro-license-key" class="wordform-pro-license-key" placeholder="<?php esc_attr_e( 'Paste your license key here', 'wordform' ); ?>" autocomplete="off" />
					</div>
					<small><?php esc_html_e( 'One valid key is enough. The upgrade flow will validate the license, check the current site allowance, and continue only when everything is allowed.', 'wordform' ); ?></small>
				</div>

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

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

	<?php if ( ! empty( $hero_items ) ) { ?>
		<div class="wordform-go-pro-grid wordform-license-feature-grid">
			<?php foreach ( $hero_items as $hero_item ) { ?>
				<div class="wordform-go-pro-card">
					<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 } ?>
		</div>
	<?php } ?>

	<div class="wordform-go-pro-table wordform-license-comparison-table">
		<h2><?php esc_html_e( 'WordForm Free vs WordForm Pro', 'wordform' ); ?></h2>
		<table>
			<thead>
				<tr>
					<th><?php esc_html_e( 'Feature', 'wordform' ); ?></th>
					<th><?php esc_html_e( 'WordForm Free', 'wordform' ); ?></th>
					<th><?php esc_html_e( 'WordForm Pro', 'wordform' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $table_rows as $row_group ) { ?>
					<tr class="wordform-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['items'] ?? array() ) as $feature_key ) { ?>
						<?php
						$basic_status  = $resolve_feature_status( $feature_key, 'basic' );
						$pro_status    = $resolve_feature_status( $feature_key, 'pro' );
						$feature_label = isset( $feature_labels[ sanitize_key( $feature_key ) ] ) ? $feature_labels[ sanitize_key( $feature_key ) ] : 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 } ?>
				<?php } ?>
			</tbody>
		</table>
	</div>

	<?php if ( ! empty( $notice_cards ) ) { ?>
		<div class="wordform-go-pro-limits">
			<h2><?php esc_html_e( 'Still included in Free with limits', 'wordform' ); ?></h2>
			<div class="wordform-go-pro-limits-grid">
				<?php foreach ( $notice_cards as $card ) { ?>
					<div class="wordform-go-pro-card">
						<h3><?php echo esc_html( isset( $card['title'] ) ? $card['title'] : '' ); ?></h3>
						<p><?php echo esc_html( isset( $card['description'] ) ? $card['description'] : '' ); ?></p>
					</div>
				<?php } ?>
			</div>
		</div>
	<?php } ?>

	<div class="wordform-go-pro-cta">
		<div>
			<h2><?php echo esc_html( ! empty( $cta_copy['title'] ) ? $cta_copy['title'] : __( 'Unlock WordForm Pro', 'wordform' ) ); ?></h2>
			<p><?php echo esc_html( ! empty( $cta_copy['description'] ) ? $cta_copy['description'] : __( 'Use premium fields, deeper checkout tools, licensed support, and advanced integrations from the same WordPress admin workflow.', 'wordform' ) ); ?></p>
		</div>
		<div class="wordform-go-pro-actions">
			<a class="button button-primary button-large" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener"><?php echo esc_html( ! empty( $cta_copy['primaryButtonLabel'] ) ? $cta_copy['primaryButtonLabel'] : __( 'Buy WordForm Pro', 'wordform' ) ); ?></a>
		</div>
	</div>
</div>
