<?php
/**
 * File Path: includes/admin/tabs/license/class-mbs-tab-license-render.php
 *
 * License Tab Renderer
 *
 * Owns render() for Tab 4 (License) with all six UI states.
 *
 * CSS classes introduced (all defined in mbs-admin-settings-license.css):
 *   .mbs-license-activate-btn    — margin-left:8px on Activate button
 *   .mbs-license-register-modal  — display:none; background/border/padding/margin/max-width on modal div
 *   .mbs-license-modal-heading   — margin-top:0 on modal h3
 *   .mbs-license-free-key-btn    — margin-left:8px on Get My Free Key button
 *   .mbs-license-key-result      — display:none; margin-top:12px on key result div
 *   .mbs-license-upgrade-btn     — margin-left:8px on Upgrade CTA button
 *   .mbs-license-since           — margin-left:8px; color:var(--wp-admin-color-muted) on "since {date}" text
 *   .mbs-license-sites-counter   — pill badge showing "x of N sites active" (PUB tier only)
 *   .mbs-hero-pub                — premium gold treatment for the PUB status hero
 *
 * Note: .mbs-license-register-modal uses display:none for initial state.
 * This is JS-controlled (slideDown by child-admin-license.js) — a comment
 * is present in the markup. display:none IS moved to CSS for this element
 * because it is a stable initial state, not a runtime-computed value.
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs/License
 * @since      1.0.0
 */

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

class MBS_Tab_License_Render { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Render the License tab.
	 *
	 * @return void
	 */
	public static function render(): void {
		$is_registered = mbs_is_registered();
		$is_keyless    = mbs_is_keyless(); // WO-002: no key stored on this install
		$tier          = get_option( 'mbs_license_tier', 'free' );
		$tamper_flag   = (int) get_option( 'mbs_tamper_flag', MBS_TAMPER_CLEAN );
		$last_ping_raw = (int) get_option( 'mbs_license_last_ping', 0 );

		// PLG-055: site-usage counters (stored on activation and each daily ping).
		$sites_used    = (int) get_option( 'mbs_license_sites_used',    0 );
		$sites_allowed = (int) get_option( 'mbs_license_sites_allowed', 0 );

		// Activation date: prefer the dedicated option, fall back to last_ping
		// for legacy installs where activated_at was never written. Once
		// MBS_License_Credentials::update_after_ping() backfills this on the
		// next successful ping, the fallback branch stops being hit.
		$activated_at = (int) get_option( 'mbs_license_activated_at', 0 );
		if ( ! $activated_at && $last_ping_raw > 0 ) {
			$activated_at = $last_ping_raw;
		}
		if ( $activated_at ) {
			$mbs_tz            = MBS_Timezone_Helper::resolve_current_timezone();
			$activated_display = wp_date(
				get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
				$activated_at,
				new DateTimeZone( $mbs_tz )
			);
		} else {
			$activated_display = '';
		}

		$has_tamper = $tamper_flag >= MBS_TAMPER_WARN;
		$has_stale  = $is_registered && $last_ping_raw > 0
		              && ( time() - $last_ping_raw ) > ( MBS_PING_INTERVAL + MBS_PING_GRACE );
		?>
		<div class="mbs-license-tab">

			<?php /* ── State 1: Tamper notice ──────────────────────────────── */ ?>
			<?php if ( $has_tamper ) : ?>
				<div class="notice notice-error inline">
					<p><?php esc_html_e( 'Your license has a security violation.', 'my-book-showroom' ); ?>
					<a href="<?php echo esc_url( MBS_UPGRADE_URL ); ?>" target="_blank">
						<?php esc_html_e( 'See FAQ', 'my-book-showroom' ); ?>
					</a>.</p>
				</div>
			<?php endif; ?>

			<?php /* ── State 2: Stale-ping warning ───────────────────────── */ ?>
			<?php if ( $has_stale ) : ?>
				<div class="notice notice-warning inline">
					<p><?php esc_html_e( 'License validation is overdue. PRO features may be temporarily unavailable.', 'my-book-showroom' ); ?></p>
					<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=mbs_validate_now' ), 'mbs_validate_now' ) ); ?>"
					   class="button button-small">
						<?php esc_html_e( 'Validate now →', 'my-book-showroom' ); ?>
					</a>
				</div>
			<?php endif; ?>

			<h2><?php esc_html_e( 'License', 'my-book-showroom' ); ?></h2>

			<?php /* ── Status hero: prominent tier badge — always shown ── */ ?>
			<div class="mbs-license-status-hero mbs-hero-<?php echo esc_attr( $tier ); ?><?php echo ( $is_registered && 'free' === $tier ) ? ' mbs-hero-free-registered' : ''; ?>">
				<span class="mbs-badge mbs-badge-<?php echo esc_attr( $tier ); ?> mbs-badge-large">
					<?php if ( 'pub' === $tier ) : ?>
						&#9733;&nbsp;<?php echo esc_html( strtoupper( $tier ) ); ?>
					<?php else : ?>
						<?php echo esc_html( strtoupper( $tier ) ); ?>
					<?php endif; ?>
				</span>
				<span class="mbs-license-status-label">
					<?php
					if ( 'pub' === $tier ) {
						esc_html_e( 'Publisher Active — full features on up to 3 sites', 'my-book-showroom' );
					} elseif ( 'pro' === $tier ) {
						esc_html_e( 'PRO Active — full features on 1 site', 'my-book-showroom' );
					} elseif ( $is_keyless ) {
						esc_html_e( 'FREE — register your free key to enable settings export.', 'my-book-showroom' );
					} elseif ( $is_registered ) {
						esc_html_e( 'FREE — registered. Upgrade to PRO to unlock all features.', 'my-book-showroom' );
					} else {
						esc_html_e( 'FREE — activate your key to enable settings export.', 'my-book-showroom' );
					}
					?>
				</span>
				<?php if ( $activated_display ) : ?>
					<span class="mbs-license-since"><?php echo esc_html( sprintf(
							/* translators: %s: formatted local date and time of license activation */
							__( 'since %s', 'my-book-showroom' ),
						$activated_display
					) ); ?></span>
				<?php endif; ?>
				<?php /* PLG-055: site-usage counter — PUB tier only, shown once data is available. */ ?>
				<?php if ( 'pub' === $tier && $sites_allowed > 0 ) : ?>
					<span class="mbs-license-sites-counter"><?php echo esc_html( sprintf(
							/* translators: %1$d: sites currently active, %2$d: maximum sites for this license */
							__( '%1$d of %2$d sites active', 'my-book-showroom' ),
							$sites_used,
						$sites_allowed
					) ); ?></span>
				<?php endif; ?>
			</div>

			<?php if ( $is_keyless ) : ?>
				<?php /* ── State 3: Keyless — optional registration (WO-002) ── */ ?>
				<h3><?php esc_html_e( 'Register Your Plugin (Optional)', 'my-book-showroom' ); ?></h3>
				<p><?php esc_html_e( 'Registration is free and unlocks settings import, plus keeps you in the loop on new features and important updates. We will send your free key by email.', 'my-book-showroom' ); ?>
				<a href="<?php echo esc_url( MBS_PRIVACY_URL ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Privacy policy', 'my-book-showroom' ); ?></a>.
				</p>

				<input type="email"
				       id="mbs-free-email"
				       class="regular-text"
				       placeholder="<?php esc_attr_e( 'your@email.com', 'my-book-showroom' ); ?>"
				       autocomplete="off">
				<button id="mbs-get-free-key-btn" type="button" class="button button-primary mbs-license-free-key-btn">
					<?php esc_html_e( 'Get My Free Key', 'my-book-showroom' ); ?>
				</button>
				<?php /* JS-toggled: child-admin-license.js slideDown after key received. */ ?>
				<div id="mbs-free-key-result" class="mbs-license-key-result">
					<p><?php esc_html_e( 'Your free key:', 'my-book-showroom' ); ?>
					<strong id="mbs-free-key-display"></strong></p>
					<button id="mbs-copy-free-key" type="button" class="button">
						<?php esc_html_e( 'Copy', 'my-book-showroom' ); ?>
					</button>
				</div>

				<p class="description">
					<?php esc_html_e( 'Already have a key?', 'my-book-showroom' ); ?>
					<a href="#" id="mbs-show-key-input">
						<?php esc_html_e( 'Enter it here →', 'my-book-showroom' ); ?>
					</a>
				</p>
				<?php /* JS-toggled: #mbs-show-key-input click reveals this section. */ ?>
				<div id="mbs-key-input-section" style="display:none;">
					<table class="form-table">
						<tr>
							<th scope="row">
								<label for="mbs_license_key"><?php esc_html_e( 'License Key', 'my-book-showroom' ); ?></label>
							</th>
							<td>
								<input type="text"
								       id="mbs_license_key"
								       class="regular-text"
								       placeholder="<?php esc_attr_e( 'Insert license key here', 'my-book-showroom' ); ?>"
								       autocomplete="off">
								<button id="mbs-activate-btn" type="button" class="button button-primary mbs-license-activate-btn">
									<?php esc_html_e( 'Activate License', 'my-book-showroom' ); ?>
								</button>
							</td>
						</tr>
					</table>
				</div>

			<?php elseif ( ! $is_registered ) : ?>
				<?php /* ── State 4: Key stored, not yet activated ─────────────── */ ?>
				<p><?php esc_html_e( 'Enter your license key below to activate My Book Showroom.', 'my-book-showroom' ); ?></p>

				<table class="form-table">
					<tr>
						<th scope="row">
							<label for="mbs_license_key"><?php esc_html_e( 'License Key', 'my-book-showroom' ); ?></label>
						</th>
						<td>
							<input type="text"
							       id="mbs_license_key"
							       class="regular-text"
							       placeholder="<?php esc_attr_e( 'Insert license key here', 'my-book-showroom' ); ?>"
							       autocomplete="off">
							<button id="mbs-activate-btn" type="button" class="button button-primary mbs-license-activate-btn">
								<?php esc_html_e( 'Activate License', 'my-book-showroom' ); ?>
							</button>
						</td>
					</tr>
				</table>

				<p>
					<?php esc_html_e( "Don't have a key?", 'my-book-showroom' ); ?>
					<a href="#" id="mbs-register-free">
						<?php esc_html_e( 'Register for a free key →', 'my-book-showroom' ); ?>
					</a>
					&nbsp;|&nbsp;
					<a href="<?php echo esc_url( MBS_PRIVACY_URL ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Privacy policy', 'my-book-showroom' ); ?></a>
				</p>

				<?php /* JS-toggled: child-admin-license.js slideDown on #mbs-register-free click. */ ?>
				<div id="mbs-register-modal" class="mbs-license-register-modal">
					<h3 class="mbs-license-modal-heading"><?php esc_html_e( 'Get Your Free Key', 'my-book-showroom' ); ?></h3>
					<p><?php esc_html_e( 'Enter your email address to receive a free license key.', 'my-book-showroom' ); ?></p>
					<input type="email"
					       id="mbs-free-email"
					       class="regular-text"
					       placeholder="<?php esc_attr_e( 'your@email.com', 'my-book-showroom' ); ?>"
					       autocomplete="off">
					<button id="mbs-get-free-key-btn" type="button" class="button button-primary mbs-license-free-key-btn">
						<?php esc_html_e( 'Get My Free Key', 'my-book-showroom' ); ?>
					</button>
					<?php /* JS-toggled: child-admin-license.js slideDown after key received. */ ?>
					<div id="mbs-free-key-result" class="mbs-license-key-result">
						<p><?php esc_html_e( 'Your free key:', 'my-book-showroom' ); ?>
						<strong id="mbs-free-key-display"></strong></p>
						<button id="mbs-copy-free-key" type="button" class="button">
							<?php esc_html_e( 'Copy', 'my-book-showroom' ); ?>
						</button>
					</div>
				</div>

			<?php else : ?>
				<?php /* ── States 5 + 6: Registered (key activated, any tier) ── */ ?>

				<p>
					<button id="mbs-deactivate-btn" type="button" class="button button-secondary">
						<?php esc_html_e( 'Deactivate License', 'my-book-showroom' ); ?>
					</button>

					<?php if ( 'free' === $tier ) : ?>
						<a href="<?php echo esc_url( add_query_arg( 'tier', 'pro', MBS_UPGRADE_URL ) ); ?>"
						   target="_blank"
						   class="button button-primary mbs-license-upgrade-btn">
							<?php esc_html_e( 'Upgrade to PRO — unlock all features', 'my-book-showroom' ); ?>
						</a>
					<?php elseif ( 'pro' === $tier ) : ?>
						<a href="<?php echo esc_url( add_query_arg( 'tier', 'pub', MBS_UPGRADE_URL ) ); ?>"
						   target="_blank"
						   class="button button-primary mbs-license-upgrade-btn">
							<?php esc_html_e( 'Upgrade to Publisher — run on up to 3 sites', 'my-book-showroom' ); ?>
						</a>
					<?php endif; ?>
				</p>

				<p class="description">
					<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=mbs_validate_now' ), 'mbs_validate_now' ) ); ?>">
						<?php esc_html_e( 'Validate now →', 'my-book-showroom' ); ?>
					</a>
				</p>

			<?php endif; ?>


		</div>
		<?php
	}
}
