<?php
/**
 * File Path: templates/admin/metabox-arc.php
 *
 * Pre-Release / ARC Metabox -- HTML partial
 *
 * Loaded via mbs_get_template_part( 'admin/metabox-arc', [...] ).
 *
 * Variables injected by MBS_Metabox_Arc::render():
 *   @var int    $post_id        Current book post ID.
 *   @var bool   $is_pro         Whether a PRO/PUB license is active.
 *   @var bool   $is_pub         Whether tier is 'pub'.
 *   @var string $arc_status     Saved ARC status slug.
 *   @var int    $copy_count     Copies distributed.
 *   @var string $dist_date      Distribution date (Y-m-d or empty).
 *   @var string $close_date     ARC close date (Y-m-d or empty).
 *   @var string $target_date    Target review date (Y-m-d or empty).
 *   @var bool   $other_active   Whether another book is currently Active (FREE gate).
 *   @var string $disabled_msg   Upgrade message when $other_active is true.
 *   @var array  $reviewers           Reviewer row objects from MBS_Arc_Recipient_DAO.
 *   @var array  $urls_by_recipient   Map of recipient_id => URL array from mbs_arc_review_urls (R2-004).
 *   @var int    $reviewer_count      Count of reviewer rows.
 *   @var int    $limit          Max reviewer rows for this tier.
 *   @var string $limit_label    Human-readable limit ('5' | '25' | '').
 *   @var bool   $at_limit       Whether reviewer count has reached the tier cap.
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variables injected by mbs_get_template_part(); not global vars

wp_nonce_field( 'mbs_arc_nonce_' . $post_id, 'mbs_arc_nonce' );
?>
<?php if ( $other_active ) : ?>
<div class="mbs-arc-disabled-overlay">
	<p class="mbs-arc-disabled-msg"><?php echo wp_kses_post( $disabled_msg ); ?></p>
</div>
<div class="mbs-arc-fields mbs-arc-fields--disabled" aria-hidden="true">
<?php else : ?>
<div class="mbs-arc-fields">
<?php endif; ?>

		<!-- -- Status / Dates / Copy Count --------------------------------- -->
		<div class="mbs-arc-header-fields">
			<label class="mbs-arc-label" for="mbs_arc_status">
				<?php esc_html_e( 'ARC Status', 'my-book-showroom' ); ?>
			</label>
			<select id="mbs_arc_status" name="mbs_arc_status" class="mbs-arc-status-select">
				<option value="not_started" <?php selected( $arc_status, 'not_started' ); ?>>
					<?php esc_html_e( 'Not Started', 'my-book-showroom' ); ?>
				</option>
				<option value="active" <?php selected( $arc_status, 'active' ); ?>>
					<?php esc_html_e( 'Active', 'my-book-showroom' ); ?>
				</option>
				<option value="closed" <?php selected( $arc_status, 'closed' ); ?>>
					<?php esc_html_e( 'Closed', 'my-book-showroom' ); ?>
				</option>
			</select>

			<label class="mbs-arc-label" for="mbs_arc_copy_count">
				<?php esc_html_e( 'Copies Distributed', 'my-book-showroom' ); ?>
			</label>
			<input type="number" id="mbs_arc_copy_count" name="mbs_arc_copy_count"
			       value="<?php echo esc_attr( $copy_count ); ?>" min="0" class="small-text">

			<label class="mbs-arc-label" for="mbs_arc_distribution_date">
				<?php esc_html_e( 'Distribution Date', 'my-book-showroom' ); ?>
			</label>
			<input type="date" id="mbs_arc_distribution_date" name="mbs_arc_distribution_date"
			       value="<?php echo esc_attr( $dist_date ); ?>">

			<label class="mbs-arc-label" for="mbs_arc_close_date">
				<?php esc_html_e( 'ARC Close Date', 'my-book-showroom' ); ?>
			</label>
			<input type="date" id="mbs_arc_close_date" name="mbs_arc_close_date"
			       value="<?php echo esc_attr( $close_date ); ?>">

			<label class="mbs-arc-label" for="mbs_arc_target_review_date">
				<?php esc_html_e( 'Target Review Date', 'my-book-showroom' ); ?>
			</label>
			<input type="date" id="mbs_arc_target_review_date" name="mbs_arc_target_review_date"
			       value="<?php echo esc_attr( $target_date ); ?>">
		</div><!-- .mbs-arc-header-fields -->

		<!-- -- Reviewer Tracking -------------------------------------------- -->
		<div class="mbs-arc-reviewer-section">
			<div class="mbs-arc-reviewer-header">
				<h4 class="mbs-arc-reviewer-title">
					<?php esc_html_e( 'ARC Reviewers', 'my-book-showroom' ); ?>
					<span class="mbs-arc-count-badge">
						<?php if ( $is_pub ) : ?>
							<?php echo (int) $reviewer_count; ?> <?php esc_html_e( 'reviewers', 'my-book-showroom' ); ?>
						<?php else : ?>
							<?php echo (int) $reviewer_count; ?>/<?php echo esc_html( $limit_label ); ?> <?php esc_html_e( 'reviewers', 'my-book-showroom' ); ?>
						<?php endif; ?>
					</span>
				</h4>
			</div>

			<div class="mbs-arc-reviewer-rows" id="mbs-arc-reviewer-rows">

				<!-- Hidden template row (cloned by JS) -->
				<div class="mbs-arc-reviewer-row mbs-arc-row-template" style="display:none;" aria-hidden="true">
					<input type="hidden" name="mbs_arc_reviewers[__IDX__][id]" value="0">
					<input type="text" name="mbs_arc_reviewers[__IDX__][reviewer_name]"
					       placeholder="<?php esc_attr_e( 'Reviewer name', 'my-book-showroom' ); ?>"
					       class="widefat mbs-arc-name-field">
					<input type="text" name="mbs_arc_reviewers[__IDX__][contact_method]"
					       placeholder="<?php esc_attr_e( 'BookFunnel, Email, NetGalley URL, social handle, etc.', 'my-book-showroom' ); ?>"
					       class="widefat mbs-arc-contact-field">
					<select name="mbs_arc_reviewers[__IDX__][contact_type]" class="mbs-arc-contact-type-field">
						<option value=""><?php esc_html_e( '— Channel —', 'my-book-showroom' ); ?></option>
						<option value="bookfunnel"><?php esc_html_e( 'BookFunnel', 'my-book-showroom' ); ?></option>
						<option value="email"><?php esc_html_e( 'Email', 'my-book-showroom' ); ?></option>
						<option value="netgalley"><?php esc_html_e( 'NetGalley', 'my-book-showroom' ); ?></option>
						<option value="booksirenreads"><?php esc_html_e( 'BookSirenReads', 'my-book-showroom' ); ?></option>
						<option value="direct"><?php esc_html_e( 'Direct', 'my-book-showroom' ); ?></option>
						<option value="other"><?php esc_html_e( 'Other', 'my-book-showroom' ); ?></option>
					</select>
					<input type="date" name="mbs_arc_reviewers[__IDX__][date_sent]"
					       class="mbs-arc-date-field">
					<label class="mbs-arc-inline-label">
						<input type="checkbox" name="mbs_arc_reviewers[__IDX__][review_posted]"
						       value="1" class="mbs-arc-posted-cb">
						<?php esc_html_e( 'Review posted', 'my-book-showroom' ); ?>
					</label>
					<!-- URL sub-repeater -->
					<div class="mbs-arc-url-repeater">
						<div class="mbs-arc-url-list">
							<!-- Hidden URL row template (nested; __IDX__ resolved when reviewer row is cloned) -->
							<div class="mbs-arc-url-row mbs-arc-url-row-template" style="display:none;" aria-hidden="true">
								<input type="url" name="mbs_arc_reviewers[__IDX__][review_urls][]"
								       placeholder="<?php esc_attr_e( 'Review URL', 'my-book-showroom' ); ?>"
								       class="widefat mbs-arc-url-field" disabled>
								<button type="button" class="button button-small mbs-arc-remove-url"
								        aria-label="<?php esc_attr_e( 'Remove URL', 'my-book-showroom' ); ?>">&times;</button>
							</div>
						</div><!-- .mbs-arc-url-list -->
						<button type="button" class="button button-small mbs-arc-add-url" disabled>
							<?php esc_html_e( '+ Add Review URL', 'my-book-showroom' ); ?>
						</button>
					</div><!-- .mbs-arc-url-repeater -->
					<button type="button" class="button button-link-delete mbs-arc-remove-row">
						<?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
					</button>
				</div>

				<?php foreach ( $reviewers as $idx => $row ) : ?>
				<div class="mbs-arc-reviewer-row">
					<input type="hidden" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][id]"
					       value="<?php echo (int) $row->id; ?>">
					<input type="text" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][reviewer_name]"
					       placeholder="<?php esc_attr_e( 'Reviewer name', 'my-book-showroom' ); ?>"
					       class="widefat mbs-arc-name-field"
					       value="<?php echo esc_attr( $row->reviewer_name ); ?>">
					<input type="text" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][contact_method]"
					       placeholder="<?php esc_attr_e( 'BookFunnel, Email, NetGalley URL, social handle, etc.', 'my-book-showroom' ); ?>"
					       class="widefat mbs-arc-contact-field"
					       value="<?php echo esc_attr( $row->contact_method ); ?>">
					<select name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][contact_type]" class="mbs-arc-contact-type-field">
						<option value=""><?php esc_html_e( '— Channel —', 'my-book-showroom' ); ?></option>
						<option value="bookfunnel" <?php selected( $row->contact_type ?? '', 'bookfunnel' ); ?>><?php esc_html_e( 'BookFunnel', 'my-book-showroom' ); ?></option>
						<option value="email" <?php selected( $row->contact_type ?? '', 'email' ); ?>><?php esc_html_e( 'Email', 'my-book-showroom' ); ?></option>
						<option value="netgalley" <?php selected( $row->contact_type ?? '', 'netgalley' ); ?>><?php esc_html_e( 'NetGalley', 'my-book-showroom' ); ?></option>
						<option value="booksirenreads" <?php selected( $row->contact_type ?? '', 'booksirenreads' ); ?>><?php esc_html_e( 'BookSirenReads', 'my-book-showroom' ); ?></option>
						<option value="direct" <?php selected( $row->contact_type ?? '', 'direct' ); ?>><?php esc_html_e( 'Direct', 'my-book-showroom' ); ?></option>
						<option value="other" <?php selected( $row->contact_type ?? '', 'other' ); ?>><?php esc_html_e( 'Other', 'my-book-showroom' ); ?></option>
					</select>
					<input type="date" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][date_sent]"
					       class="mbs-arc-date-field"
					       value="<?php echo esc_attr( $row->date_sent ); ?>">
					<label class="mbs-arc-inline-label">
						<input type="checkbox" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][review_posted]"
						       value="1" class="mbs-arc-posted-cb"
						       <?php checked( $row->review_posted, 1 ); ?>>
						<?php esc_html_e( 'Review posted', 'my-book-showroom' ); ?>
					</label>
					<!-- URL sub-repeater -->
					<?php
					// R2-004: URLs come from mbs_arc_review_urls child table via $urls_by_recipient.
					// Fall back to legacy review_url for rows that pre-date migration 4.28.
					$saved_urls = $urls_by_recipient[ (int) $row->id ] ?? array();
					if ( empty( $saved_urls ) && ! empty( $row->review_url ) ) {
						$saved_urls = array( $row->review_url );
					}
					$_url_disabled = empty( $row->review_posted ) ? 'disabled' : '';
					?>
					<div class="mbs-arc-url-repeater">
						<div class="mbs-arc-url-list">
							<!-- Hidden URL row template -->
							<div class="mbs-arc-url-row mbs-arc-url-row-template" style="display:none;" aria-hidden="true">
								<input type="url" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][review_urls][]"
								       placeholder="<?php esc_attr_e( 'Review URL', 'my-book-showroom' ); ?>"
								       class="widefat mbs-arc-url-field" disabled>
								<button type="button" class="button button-small mbs-arc-remove-url"
								        aria-label="<?php esc_attr_e( 'Remove URL', 'my-book-showroom' ); ?>">&times;</button>
							</div>
							<?php foreach ( $saved_urls as $saved_url_val ) : ?>
							<div class="mbs-arc-url-row">
								<input type="url" name="mbs_arc_reviewers[<?php echo (int) $idx; ?>][review_urls][]"
								       placeholder="<?php esc_attr_e( 'Review URL', 'my-book-showroom' ); ?>"
								       class="widefat mbs-arc-url-field"
								       value="<?php echo esc_attr( $saved_url_val ); ?>"
								       <?php echo $_url_disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $_url_disabled is a pre-constructed HTML attribute ?>>
								<button type="button" class="button button-small mbs-arc-remove-url"
								        aria-label="<?php esc_attr_e( 'Remove URL', 'my-book-showroom' ); ?>">&times;</button>
							</div>
							<?php endforeach; ?>
						</div><!-- .mbs-arc-url-list -->
						<button type="button" class="button button-small mbs-arc-add-url" <?php echo $_url_disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $_url_disabled is a pre-constructed HTML attribute ?>>
							<?php esc_html_e( '+ Add Review URL', 'my-book-showroom' ); ?>
						</button>
					</div><!-- .mbs-arc-url-repeater -->
					<button type="button" class="button button-link-delete mbs-arc-remove-row">
						<?php esc_html_e( 'Remove', 'my-book-showroom' ); ?>
					</button>
				</div>
				<?php endforeach; ?>

			</div><!-- #mbs-arc-reviewer-rows -->

			<?php if ( $at_limit && ! $is_pub ) : ?>
			<p class="mbs-arc-limit-msg">
				<?php
				if ( $is_pro ) {
					printf(
						/* translators: %s: upgrade URL */
						wp_kses_post( __( '25/25 reviewers &#8212; Publisher tier offers unlimited reviewer tracking. <a href="%s" target="_blank">Upgrade to Publisher &#8594;</a>', 'my-book-showroom' ) ),
						esc_url( MBS_UPGRADE_URL )
					);
				} else {
					printf(
						/* translators: %s: upgrade URL */
						wp_kses_post( __( '5/5 reviewers &#8212; Upgrade to PRO to track up to 25 per book. <a href="%s" target="_blank">Upgrade to PRO &#8594;</a>', 'my-book-showroom' ) ),
						esc_url( MBS_UPGRADE_URL )
					);
				}
				?>
			</p>
			<?php else : ?>
			<button type="button" class="button mbs-arc-add-row" id="mbs-arc-add-row">
				<?php esc_html_e( '+ Add Reviewer', 'my-book-showroom' ); ?>
			</button>
			<?php endif; ?>

			<!-- -- Export footer (PRO / PUB only) ------------------------------ -->
			<?php if ( $is_pro || $is_pub ) : ?>
			<div class="mbs-arc-export-footer">
				<button type="button" class="button mbs-arc-export-btn"
				        data-format="xlsx"
				        data-post-id="<?php echo (int) $post_id; ?>"
				        data-nonce="<?php echo esc_attr( wp_create_nonce( 'mbs_export_arc_' . $post_id ) ); ?>">
					<?php esc_html_e( 'Export Reviewers as XLSX', 'my-book-showroom' ); ?>
				</button>
				<button type="button" class="button mbs-arc-export-btn"
				        data-format="csv"
				        data-post-id="<?php echo (int) $post_id; ?>"
				        data-nonce="<?php echo esc_attr( wp_create_nonce( 'mbs_export_arc_' . $post_id ) ); ?>">
					<?php esc_html_e( 'Export as CSV', 'my-book-showroom' ); ?>
				</button>
				<button type="button" class="button mbs-arc-export-btn"
				        data-format="json"
				        data-post-id="<?php echo (int) $post_id; ?>"
				        data-nonce="<?php echo esc_attr( wp_create_nonce( 'mbs_export_arc_' . $post_id ) ); ?>">
					<?php esc_html_e( 'Export as JSON', 'my-book-showroom' ); ?>
				</button>
			</div>
			<?php else : ?>
			<!-- MBS: XLSX/CSV/JSON export requires PRO license -->
			<?php endif; ?>

		</div><!-- .mbs-arc-reviewer-section -->


<?php if ( $is_pro && $pending_count > 0 ) : ?>
<!-- F-027-3: Pending Applications panel -->
<div class="mbs-arc-pending-section" style="margin-top:18px;border-top:1px solid #dcdcde;padding-top:14px;">
	<h4 style="margin:0 0 10px;">
		<?php echo esc_html( sprintf(
			/* translators: %d: number of pending applications */
			_n( 'Pending Application (%d)', 'Pending Applications (%d)', $pending_count, 'my-book-showroom' ),
			$pending_count
		) ); ?>
	</h4>
	<?php foreach ( $pending_applicants as $applicant ) :
		$app_id      = (int) $applicant['id'];
		$app_name    = $applicant['name'];
		$app_email   = $applicant['email'];
		$app_message = mb_strimwidth( (string) $applicant['message'], 0, 120, "\u{2026}" );
		$app_date    = $applicant['submitted_at'];
		$app_nonce   = wp_create_nonce( 'mbs_arc_applicant_action_' . $app_id );
	?>
	<div class="mbs-arc-applicant-row" id="mbs-arc-applicant-<?php echo (int) $app_id; ?>"
	     style="background:#f9f9f9;border:1px solid #e0e0e0;border-radius:4px;padding:10px 12px;margin-bottom:8px;">
		<div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:6px;">
			<div>
				<strong><?php echo esc_html( $app_name ); ?></strong>
				&nbsp;<span style="color:#555;"><?php echo esc_html( $app_email ); ?></span>
				&nbsp;<span style="color:#888;font-size:12px;">
					<?php echo esc_html__( 'Submitted:', 'my-book-showroom' ); ?> <?php echo esc_html( $app_date ); ?>
				</span>
			</div>
			<div style="display:flex;gap:6px;">
				<button type="button" class="button button-primary mbs-arc-approve-btn"
				        data-id="<?php echo (int) $app_id; ?>"
				        data-nonce="<?php echo esc_attr( $app_nonce ); ?>">
					<?php esc_html_e( 'Approve', 'my-book-showroom' ); ?>
				</button>
				<button type="button" class="button mbs-arc-reject-btn"
				        data-id="<?php echo (int) $app_id; ?>"
				        data-nonce="<?php echo esc_attr( $app_nonce ); ?>">
					<?php esc_html_e( 'Reject', 'my-book-showroom' ); ?>
				</button>
			</div>
		</div>
		<?php if ( '' !== $app_message ) : ?>
		<p style="margin:6px 0 0;color:#555;font-size:13px;"><?php echo esc_html( $app_message ); ?></p>
		<?php endif; ?>
		<div class="mbs-arc-applicant-error" style="color:#cc1818;margin-top:6px;display:none;"></div>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>
</div><!-- .mbs-arc-fields -->
