<?php
/**
 * Template: Subscription (native, full parity)
 *
 * Mirrors the Cloud Subscription view: plan header with status pill, a metrics
 * row, an Active Features table, this month's session usage bar, and the
 * billing/upgrade (or Lifetime Deal) cards. Every value is derived server-side
 * from the account plan (FeatureService), real session counts and the real
 * website count — nothing is invented. When the API returns nothing, a neutral
 * loading state is shown instead of fabricated numbers.
 *
 * @var array $data get-subscription response:
 *   { plan, planName, subscriptionStatus, accountEmail, domain, websiteCount,
 *     isLtd, isLtdAgency, limits:{sessions|null,domains|null}, usage:{sessions},
 *     features:{legalDocsCount,scanFrequency,whiteLabel,abTesting,apiAccess,consentAnalytics} }
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Subscription', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

if ( empty( $data ) || ! is_array( $data ) ) :
	include __DIR__ . '/partials/loading-state.php';
	return;
endif;

// Safe extraction with documented defaults.
$plan_name     = isset( $data['planName'] ) ? sanitize_text_field( (string) $data['planName'] ) : __( 'Free', 'biscotti-cmp' );
$sub_status    = isset( $data['subscriptionStatus'] ) ? strtolower( sanitize_text_field( (string) $data['subscriptionStatus'] ) ) : '';
$account_email = isset( $data['accountEmail'] ) ? sanitize_text_field( (string) $data['accountEmail'] ) : '';
$domain        = isset( $data['domain'] ) ? sanitize_text_field( (string) $data['domain'] ) : '';
$website_count = isset( $data['websiteCount'] ) ? absint( $data['websiteCount'] ) : 0;
$is_ltd        = ! empty( $data['isLtd'] );
$is_ltd_agency = ! empty( $data['isLtdAgency'] );

$limits        = isset( $data['limits'] ) && is_array( $data['limits'] ) ? $data['limits'] : array();
$usage         = isset( $data['usage'] ) && is_array( $data['usage'] ) ? $data['usage'] : array();
$features      = isset( $data['features'] ) && is_array( $data['features'] ) ? $data['features'] : array();

// null limit means unlimited.
$session_limit = array_key_exists( 'sessions', $limits ) ? $limits['sessions'] : null;
$domain_limit  = array_key_exists( 'domains', $limits ) ? $limits['domains'] : null;
$sessions_used = isset( $usage['sessions'] ) ? absint( $usage['sessions'] ) : 0;

$is_unlimited  = ( null === $session_limit );
$usage_percent = ( ! $is_unlimited && $session_limit > 0 )
	? min( 100, (int) round( ( $sessions_used / $session_limit ) * 100 ) )
	: 0;

$unlimited_glyph = '∞';
$sessions_display = $is_unlimited ? $unlimited_glyph : number_format_i18n( absint( $session_limit ) );
$domains_display  = ( null === $domain_limit ) ? $unlimited_glyph : number_format_i18n( absint( $domain_limit ) );

$legal_docs_count = isset( $features['legalDocsCount'] ) ? absint( $features['legalDocsCount'] ) : 0;
$scan_freq        = isset( $features['scanFrequency'] ) ? (string) $features['scanFrequency'] : 'monthly';
$has_white_label  = ! empty( $features['whiteLabel'] );
$has_ab_testing   = ! empty( $features['abTesting'] );
$has_api          = ! empty( $features['apiAccess'] );
$has_consent_an   = ! empty( $features['consentAnalytics'] );

$freq_labels = array(
	'realtime'  => __( 'Realtime', 'biscotti-cmp' ),
	'hourly'    => __( 'Hourly', 'biscotti-cmp' ),
	'daily'     => __( 'Daily', 'biscotti-cmp' ),
	'weekly'    => __( 'Weekly', 'biscotti-cmp' ),
	'monthly'   => __( 'Monthly', 'biscotti-cmp' ),
	'quarterly' => __( 'Quarterly', 'biscotti-cmp' ),
	'manual'    => __( 'Manual', 'biscotti-cmp' ),
);
$freq_label = isset( $freq_labels[ $scan_freq ] ) ? $freq_labels[ $scan_freq ] : ucfirst( $scan_freq );

$yes = '✓';
$no  = '—';
?>

<div class="biscotti-page biscotti-page-subscription">

	<!-- Header -->
	<div class="biscotti-sub-header">
		<h2>
			💎 <?php esc_html_e( 'Subscription', 'biscotti-cmp' ); ?>
			<span class="biscotti-plan-badge"><?php echo esc_html( $plan_name ); ?></span>
		</h2>
		<p>
			<?php if ( '' !== $account_email ) : ?>
				<span class="biscotti-sub-email"><?php echo esc_html( $account_email ); ?></span>
			<?php endif; ?>
			<?php
			if ( 'active' === $sub_status ) :
				?>
				<span class="biscotti-pill biscotti-pill-green"><?php echo esc_html( $yes . ' ' . __( 'Active', 'biscotti-cmp' ) ); ?></span>
			<?php elseif ( 'trialing' === $sub_status || 'trial' === $sub_status ) : ?>
				<span class="biscotti-pill biscotti-pill-blue"><?php esc_html_e( 'Trial', 'biscotti-cmp' ); ?></span>
			<?php elseif ( '' !== $sub_status ) : ?>
				<span class="biscotti-pill biscotti-pill-gray"><?php echo esc_html( ucfirst( $sub_status ) ); ?></span>
			<?php endif; ?>
		</p>
	</div>

	<!-- Metrics -->
	<div class="biscotti-stats-grid">
		<?php
		Biscotti_Template_Renderer::stat_card( __( 'Sessions / month', 'biscotti-cmp' ), $sessions_display, 'dashicons-chart-bar' );
		Biscotti_Template_Renderer::stat_card( __( 'Domains', 'biscotti-cmp' ), number_format_i18n( $website_count ) . ' / ' . $domains_display, 'dashicons-admin-site' );
		Biscotti_Template_Renderer::stat_card( __( 'Scan Frequency', 'biscotti-cmp' ), $freq_label, 'dashicons-search' );
		?>
	</div>

	<!-- Active Features -->
	<div class="biscotti-card">
		<h3>📋 <?php esc_html_e( 'Active Features', 'biscotti-cmp' ); ?></h3>
		<table class="widefat biscotti-data-table biscotti-features-table">
			<tbody>
				<tr><td><?php esc_html_e( 'Sessions per month', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $sessions_display ); ?></td></tr>
				<tr><td><?php esc_html_e( 'Domains', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $domains_display ); ?></td></tr>
				<tr><td><?php esc_html_e( 'Scan frequency', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $freq_label ); ?></td></tr>
				<tr><td><?php esc_html_e( 'White label', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $has_white_label ? $yes : $no ); ?></td></tr>
				<tr><td><?php esc_html_e( 'A/B testing', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $has_ab_testing ? $yes : $no ); ?></td></tr>
				<tr><td><?php esc_html_e( 'API access', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $has_api ? $yes : $no ); ?></td></tr>
				<tr><td><?php esc_html_e( 'Consent analytics', 'biscotti-cmp' ); ?></td><td class="biscotti-feature-val"><?php echo esc_html( $has_consent_an ? $yes : $no ); ?></td></tr>
			</tbody>
		</table>
	</div>

	<!-- Session Usage -->
	<div class="biscotti-card">
		<h3><?php esc_html_e( 'Session Usage (this month)', 'biscotti-cmp' ); ?></h3>
		<?php if ( $is_unlimited ) : ?>
			<p>
				<?php
				printf(
					/* translators: %s: number of sessions used this month */
					esc_html__( '%s sessions used this month. Your plan includes unlimited sessions.', 'biscotti-cmp' ),
					'<strong>' . esc_html( number_format_i18n( $sessions_used ) ) . '</strong>'
				);
				?>
			</p>
		<?php else : ?>
			<p>
				<?php
				printf(
					/* translators: 1: sessions used, 2: session limit */
					esc_html__( '%1$s of %2$s sessions used this month.', 'biscotti-cmp' ),
					'<strong>' . esc_html( number_format_i18n( $sessions_used ) ) . '</strong>',
					'<strong>' . esc_html( number_format_i18n( absint( $session_limit ) ) ) . '</strong>'
				);
				?>
			</p>
			<div class="biscotti-usage-bar" role="progressbar"
				aria-valuenow="<?php echo esc_attr( $usage_percent ); ?>"
				aria-valuemin="0" aria-valuemax="100">
				<div class="biscotti-usage-fill<?php echo $usage_percent >= 90 ? ' is-high' : ''; ?>" style="width:<?php echo esc_attr( $usage_percent ); ?>%;"></div>
			</div>
			<p class="description"><?php echo esc_html( $usage_percent ); ?>%</p>
			<?php if ( $usage_percent >= 90 ) : ?>
				<p class="biscotti-badge biscotti-badge-warning" style="display:inline-block;">
					<?php esc_html_e( 'You are close to your monthly session limit. Consider upgrading your plan.', 'biscotti-cmp' ); ?>
				</p>
			<?php endif; ?>
		<?php endif; ?>
	</div>

	<!-- Billing / Upgrade / Lifetime Deal -->
	<div class="biscotti-two-col">
		<?php if ( $is_ltd ) : ?>
			<div class="biscotti-card biscotti-ltd-card">
				<h3><?php echo esc_html( $yes . ' ' . __( 'Lifetime Deal', 'biscotti-cmp' ) ); ?></h3>
				<p class="description"><?php esc_html_e( 'Upgrade, downgrade, and cancellation are not available for Lifetime Deal plans.', 'biscotti-cmp' ); ?></p>
			</div>
			<?php if ( $is_ltd_agency ) : ?>
				<div class="biscotti-card">
					<h3>📦 <?php esc_html_e( 'Extra Sessions', 'biscotti-cmp' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Purchase additional session packs from your billing dashboard.', 'biscotti-cmp' ); ?></p>
					<a href="https://app.biscotti-cmp.com/dashboard/settings/billing" target="_blank" rel="noopener" class="button"><?php esc_html_e( 'Manage Billing', 'biscotti-cmp' ); ?> &rarr;</a>
				</div>
			<?php endif; ?>
		<?php else : ?>
			<div class="biscotti-card">
				<h3>💳 <?php esc_html_e( 'Billing & Invoices', 'biscotti-cmp' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Change your plan, update payment details, and download invoices in your Biscotti Dashboard. Payments are processed securely by our payment provider.', 'biscotti-cmp' ); ?></p>
				<a href="https://app.biscotti-cmp.com/billing" target="_blank" rel="noopener" class="button button-primary"><?php esc_html_e( 'Manage Billing & Invoices', 'biscotti-cmp' ); ?> &rarr;</a>
			</div>
			<div class="biscotti-card">
				<h3>⬆️ <?php esc_html_e( 'Upgrade', 'biscotti-cmp' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Need more sessions, domains, or features? Compare plans and upgrade anytime.', 'biscotti-cmp' ); ?></p>
				<a href="https://biscotti-cmp.com/pricing" target="_blank" rel="noopener" class="button"><?php esc_html_e( 'Compare Plans', 'biscotti-cmp' ); ?> &rarr;</a>
			</div>
		<?php endif; ?>
	</div>

	<?php if ( '' !== $domain ) : ?>
		<p class="description"><?php esc_html_e( 'Connected domain:', 'biscotti-cmp' ); ?> <code><?php echo esc_html( $domain ); ?></code></p>
	<?php endif; ?>

</div>
