<?php
/**
 * Interest subscription popup modal template.
 *
 * @package Subs_Sys
 */

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

$modal_id            = esc_attr( $args['modal_id'] ?? 'ss-interest-modal' );
$categories          = $args['categories'] ?? array();
$tags                = $args['tags'] ?? array();
$plans               = $args['plans'] ?? array();
$plan_source         = isset( $args['plan_source'] ) && 'content' === $args['plan_source'] ? 'content' : 'interest';
$context_categories  = array_map( 'intval', (array) ( $args['context_categories'] ?? array() ) );
$context_tags        = array_map( 'intval', (array) ( $args['context_tags'] ?? array() ) );
$current_user        = wp_get_current_user();
$is_logged_in        = $current_user->exists();
$prefill_name        = $is_logged_in ? $current_user->display_name : '';
$prefill_email       = $is_logged_in ? $current_user->user_email : '';
$hide_fields         = $is_logged_in && (bool) get_option( 'subs_modal_hide_fields_logged_in', 1 );

// Build the login-redirect URL: after login, return here with ?ss_subscribe=1 so the modal auto-reopens.
$login_page_id   = (int) get_option( 'login_page', 0 );
$login_base_url  = $login_page_id ? get_permalink( $login_page_id ) : wp_login_url();
$return_url      = add_query_arg( 'ss_subscribe', '1', get_permalink() ?: home_url( add_query_arg( array() ) ) );
$login_url       = add_query_arg( 'redirect_to', rawurlencode( $return_url ), $login_base_url );
?>
<div id="<?php echo $modal_id; ?>" class="ss-interest-modal" aria-hidden="true" role="dialog" aria-labelledby="<?php echo $modal_id; ?>-title">
	<div class="ss-interest-modal__overlay" data-ss-close-modal></div>
	<div class="ss-interest-modal__dialog">
		<div class="ss-interest-modal__header">
			<h2 id="<?php echo $modal_id; ?>-title"><?php esc_html_e( 'Subscribe to Updates', 'subscription-system' ); ?></h2>
			<button type="button" class="ss-interest-modal__close" data-ss-close-modal aria-label="<?php esc_attr_e( 'Close', 'subscription-system' ); ?>">&times;</button>
		</div>

		<?php if ( ! $is_logged_in ) : ?>
		<!-- ── GUEST PANEL (not logged in) ─────────────────────────────── -->
		<div class="ss-interest-modal__body ss-interest-guest">
			<div class="ss-interest-guest__icon" aria-hidden="true">
				<svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
					<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
					<circle cx="12" cy="7" r="4"/>
				</svg>
			</div>
			<h3 class="ss-interest-guest__heading">
				<?php esc_html_e( 'Log in to subscribe', 'subscription-system' ); ?>
			</h3>
			<p class="ss-interest-guest__desc">
				<?php esc_html_e( 'Choose the topics you care about and get notified when new content is published. Log in first to set up your subscription.', 'subscription-system' ); ?>
			</p>
		</div>
		<div class="ss-interest-modal__footer ss-interest-guest__footer">
			<button type="button" class="ss-interest-btn ss-interest-btn--ghost" data-ss-close-modal>
				<?php esc_html_e( 'Not now', 'subscription-system' ); ?>
			</button>
			<a href="<?php echo esc_url( $login_url ); ?>" class="ss-interest-btn ss-interest-btn--primary ss-interest-btn--login">
				<?php esc_html_e( 'Log in to subscribe', 'subscription-system' ); ?>
			</a>
		</div>

		<?php else : ?>
		<!-- ── SUBSCRIBE FORM (logged in) ──────────────────────────────── -->
		<form class="ss-interest-form" id="<?php echo esc_attr( $modal_id ); ?>-form" novalidate>
			<input type="hidden" name="plan_source" value="<?php echo esc_attr( $plan_source ); ?>">
			<div class="ss-interest-modal__body">
				<?php
				// True when the category/tag list was filtered to the current post's terms.
				$post_filtered = ! empty( $context_categories ) || ! empty( $context_tags );
				?>

				<?php if ( $hide_fields ) : ?>
					<p class="ss-interest-modal__intro ss-interest-modal__intro--loggedin">
						<?php
						if ( $post_filtered ) {
							printf(
								/* translators: %s: user display name */
								esc_html__( 'Hi %s! Subscribe to get notified about new content in these topics.', 'subscription-system' ),
								esc_html( $prefill_name )
							);
						} else {
							printf(
								/* translators: %s: user display name */
								esc_html__( 'Hi %s! Choose what you\'d like to follow below.', 'subscription-system' ),
								esc_html( $prefill_name )
							);
						}
						?>
					</p>
					<input type="hidden" name="subscriber_name" value="<?php echo esc_attr( $prefill_name ); ?>">
					<input type="hidden" name="subscriber_email" value="<?php echo esc_attr( $prefill_email ); ?>">
				<?php else : ?>
					<p class="ss-interest-modal__intro">
						<?php if ( $post_filtered ) : ?>
							<?php esc_html_e( 'Subscribe to get notified when new content is published in these topics.', 'subscription-system' ); ?>
						<?php else : ?>
							<?php esc_html_e( 'Choose the categories and tags you care about. We will send updates only for content that matches your interests.', 'subscription-system' ); ?>
						<?php endif; ?>
					</p>
					<div class="ss-interest-field">
						<label for="<?php echo esc_attr( $modal_id ); ?>-name"><?php esc_html_e( 'Name', 'subscription-system' ); ?></label>
						<input type="text" id="<?php echo esc_attr( $modal_id ); ?>-name" name="subscriber_name" value="<?php echo esc_attr( $prefill_name ); ?>" required>
					</div>
					<div class="ss-interest-field">
						<label for="<?php echo esc_attr( $modal_id ); ?>-email"><?php esc_html_e( 'Email', 'subscription-system' ); ?></label>
						<input type="email" id="<?php echo esc_attr( $modal_id ); ?>-email" name="subscriber_email" value="<?php echo esc_attr( $prefill_email ); ?>" required>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $categories ) ) : ?>
				<div class="ss-interest-field">
					<span class="ss-interest-field__label">
						<?php echo $post_filtered
							? esc_html__( 'Categories in this post', 'subscription-system' )
							: esc_html__( 'Select Categories', 'subscription-system' ); ?>
					</span>
					<div class="ss-interest-checkboxes" data-limit-type="categories">
						<?php foreach ( $categories as $category ) :
							// In filtered mode every listed item IS a context item → always pre-check it.
							$is_context_cat = $post_filtered || in_array( (int) $category['id'], $context_categories, true );
						?>
							<label class="ss-interest-checkbox<?php echo $is_context_cat && ! $post_filtered ? ' ss-interest-checkbox--context' : ''; ?>">
								<input type="checkbox" name="category_ids[]" value="<?php echo esc_attr( $category['id'] ); ?>"
									<?php checked( $is_context_cat ); ?>>
								<span><?php echo esc_html( $category['name'] ); ?></span>
								<?php if ( $is_context_cat && ! $post_filtered ) : ?>
									<em class="ss-context-badge"><?php esc_html_e( 'current', 'subscription-system' ); ?></em>
								<?php endif; ?>
							</label>
						<?php endforeach; ?>
					</div>
				</div>
				<?php endif; ?>

				<?php if ( ! empty( $tags ) ) : ?>
				<div class="ss-interest-field">
					<span class="ss-interest-field__label">
						<?php echo $post_filtered
							? esc_html__( 'Tags in this post', 'subscription-system' )
							: esc_html__( 'Select Tags', 'subscription-system' ); ?>
					</span>
					<div class="ss-interest-checkboxes" data-limit-type="tags">
						<?php foreach ( $tags as $tag ) :
							$is_context_tag = $post_filtered || in_array( (int) $tag['id'], $context_tags, true );
						?>
							<label class="ss-interest-checkbox<?php echo $is_context_tag && ! $post_filtered ? ' ss-interest-checkbox--context' : ''; ?>">
								<input type="checkbox" name="tag_ids[]" value="<?php echo esc_attr( $tag['id'] ); ?>"
									<?php checked( $is_context_tag ); ?>>
								<span><?php echo esc_html( $tag['name'] ); ?></span>
								<?php if ( $is_context_tag && ! $post_filtered ) : ?>
									<em class="ss-context-badge"><?php esc_html_e( 'current', 'subscription-system' ); ?></em>
								<?php endif; ?>
							</label>
						<?php endforeach; ?>
					</div>
				</div>
				<?php elseif ( ! $post_filtered ) : ?>
				<div class="ss-interest-field">
					<span class="ss-interest-field__label"><?php esc_html_e( 'Select Tags', 'subscription-system' ); ?></span>
					<div class="ss-interest-checkboxes" data-limit-type="tags">
						<p class="ss-interest-empty"><?php esc_html_e( 'No tags available yet.', 'subscription-system' ); ?></p>
					</div>
				</div>
				<?php endif; ?>

				<div class="ss-interest-field">
					<span class="ss-interest-field__label"><?php esc_html_e( 'Choose Plan', 'subscription-system' ); ?></span>
					<div class="ss-interest-plans">
						<?php if ( empty( $plans ) ) : ?>
							<p class="ss-interest-empty">
								<?php esc_html_e( 'No subscription plans are available for this content yet.', 'subscription-system' ); ?>
							</p>
						<?php else : ?>
							<?php foreach ( $plans as $index => $plan ) :
								$covered_names = $plan['covered_names'] ?? array();
								$covered_type  = $plan['covered_type'] ?? '';

								// Build the "covers" label shown under the plan name.
								if ( ! empty( $covered_names ) ) {
									if ( 'category' === $covered_type ) {
										$covers_label = sprintf(
											/* translators: comma-separated category names */
											_n( 'Category: %s', 'Categories: %s', count( $covered_names ), 'subscription-system' ),
											implode( ', ', $covered_names )
										);
									} elseif ( 'tag' === $covered_type ) {
										$covers_label = sprintf(
											/* translators: comma-separated tag names */
											_n( 'Tag: %s', 'Tags: %s', count( $covered_names ), 'subscription-system' ),
											implode( ', ', $covered_names )
										);
									} else {
										$covers_label = implode( ', ', $covered_names );
									}
								} else {
									$covers_label = '';
								}
							?>
								<label class="ss-interest-plan <?php echo $plan['is_free'] ? 'ss-interest-plan--free' : 'ss-interest-plan--paid'; ?>">
									<input type="radio"
										name="plan_id"
										value="<?php echo esc_attr( $plan['id'] ); ?>"
										<?php checked( 0 === $index ); ?>
										data-max-categories="<?php echo esc_attr( $plan['max_categories'] ); ?>"
										data-max-tags="<?php echo esc_attr( $plan['max_tags'] ); ?>"
										data-is-free="<?php echo $plan['is_free'] ? '1' : '0'; ?>">
									<span class="ss-interest-plan__content">
										<strong><?php echo esc_html( $plan['name'] ); ?></strong>
										<em class="ss-interest-plan__price"><?php echo esc_html( $plan['price_label'] ); ?></em>
										<?php if ( $covers_label ) : ?>
											<span class="ss-interest-plan__covers"><?php echo esc_html( $covers_label ); ?></span>
										<?php endif; ?>
										<?php if ( ! empty( $plan['features'] ) ) : ?>
											<small class="ss-interest-plan__desc"><?php echo esc_html( implode( ' · ', array_slice( $plan['features'], 0, 3 ) ) ); ?></small>
										<?php endif; ?>
									</span>
								</label>
							<?php endforeach; ?>
						<?php endif; ?>
					</div>
				</div>

				<div class="ss-interest-message" aria-live="polite"></div>
			</div>

			<div class="ss-interest-modal__footer">
				<button type="button" class="ss-interest-btn ss-interest-btn--secondary" data-ss-close-modal>
					<?php esc_html_e( 'Cancel', 'subscription-system' ); ?>
				</button>
				<button type="submit" class="ss-interest-btn ss-interest-btn--primary" <?php disabled( empty( $plans ) ); ?>>
					<?php esc_html_e( 'Subscribe', 'subscription-system' ); ?>
				</button>
			</div>
		</form>
		<?php endif; ?>
	</div>
</div>
