<?php
/**
 * Team Surveys — submission detail with three tabs (triage / review / publish).
 *
 * Variables in scope:
 *   - $response   array  Hydrated row.
 *   - $structured array  Structured payload — actual or defaulted.
 *   - $questions  array  Survey question definitions.
 *   - $field_map  array  schema_field => post_meta key.
 *   - $tpt        string Team CPT slug.
 *   - $team_label string Current target post title.
 *   - $tab        string Active tab.
 *   - $nonces     array  [triage, review, publish]
 *
 * @package BW_AI_Schema_Pro
 * @since 2.2.0
 */

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

/** @var array  $response */
/** @var array  $structured */
/** @var array  $questions */
/** @var array  $field_map */
/** @var string $tpt */
/** @var string $team_label */
/** @var string $tab */
/** @var array  $nonces */

$id          = (int) $response['id'];
$status      = $response['status'];
$queue_url   = BW_Schema_Survey_Admin::url_queue();
$triage_url  = BW_Schema_Survey_Admin::url_detail( $id, 'triage' );
$review_url  = BW_Schema_Survey_Admin::url_detail( $id, 'review' );
$publish_url = BW_Schema_Survey_Admin::url_detail( $id, 'publish' );

// Quick lookup: question by schema_field (for the review tab).
$question_for_schema = array();
foreach ( $questions as $q ) {
	if ( ! empty( $q['schema_field'] ) ) {
		$question_for_schema[ $q['schema_field'] ] = $q;
	}
}
?>
<div class="wrap bw-schema-survey-detail">
	<h1>
		<?php
		/* translators: %d: submission ID */
		printf( esc_html__( 'Survey submission #%d', 'bw-ai-schema-pro' ), $id );
		?>
		<a href="<?php echo esc_url( $queue_url ); ?>" class="page-title-action"><?php esc_html_e( '← Back to queue', 'bw-ai-schema-pro' ); ?></a>
	</h1>

	<?php settings_errors( 'bw_schema_survey' ); ?>

	<p>
		<strong><?php esc_html_e( 'Submitted by:', 'bw-ai-schema-pro' ); ?></strong>
		<?php echo esc_html( $response['submitter_name'] ); ?>
		<?php if ( $response['submitter_email'] ) : ?>
			(<?php echo esc_html( $response['submitter_email'] ); ?>)
		<?php endif; ?>
		<br />
		<strong><?php esc_html_e( 'Status:', 'bw-ai-schema-pro' ); ?></strong> <code><?php echo esc_html( $status ); ?></code><br />
		<strong><?php esc_html_e( 'Submitted at:', 'bw-ai-schema-pro' ); ?></strong>
		<?php
		echo esc_html(
			mysql2date(
				get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
				$response['created_at']
			)
		);
		?>
	</p>

	<h2 class="nav-tab-wrapper">
		<a href="<?php echo esc_url( $triage_url ); ?>" class="nav-tab <?php echo 'triage' === $tab ? 'nav-tab-active' : ''; ?>">
			<?php esc_html_e( 'Triage', 'bw-ai-schema-pro' ); ?>
		</a>
		<a href="<?php echo esc_url( $review_url ); ?>" class="nav-tab <?php echo 'review' === $tab ? 'nav-tab-active' : ''; ?>">
			<?php esc_html_e( 'Schema review', 'bw-ai-schema-pro' ); ?>
		</a>
		<a href="<?php echo esc_url( $publish_url ); ?>" class="nav-tab <?php echo 'publish' === $tab ? 'nav-tab-active' : ''; ?>">
			<?php esc_html_e( 'Publish', 'bw-ai-schema-pro' ); ?>
		</a>
	</h2>

	<?php if ( 'triage' === $tab ) : ?>

		<form method="post">
			<?php wp_nonce_field( BW_Schema_Survey_Admin::NONCE_TRIAGE, '_bw_schema_survey_triage_nonce' ); ?>

			<h3><?php esc_html_e( 'Raw submission', 'bw-ai-schema-pro' ); ?></h3>
			<table class="widefat striped">
				<tbody>
					<?php foreach ( $questions as $q ) : ?>
						<tr>
							<th style="width: 25%;"><?php echo esc_html( $q['label'] ); ?></th>
							<td>
								<?php
								$value = isset( $response['raw_payload'][ $q['key'] ] ) ? $response['raw_payload'][ $q['key'] ] : '';
								if ( is_array( $value ) ) {
									echo '<ul>';
									foreach ( $value as $item ) {
										echo '<li>' . esc_html( (string) $item ) . '</li>';
									}
									echo '</ul>';
								} else {
									echo nl2br( esc_html( (string) $value ) );
								}
								?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<h3><?php esc_html_e( 'Link to team member', 'bw-ai-schema-pro' ); ?></h3>

			<?php if ( ! $response['target_post_id'] ) : ?>
				<p><strong><?php esc_html_e( 'This is a holding-queue submission (no team-CPT entry exists yet).', 'bw-ai-schema-pro' ); ?></strong></p>

				<p>
					<label>
						<input type="radio" name="target_action" value="graduate" checked />
						<?php esc_html_e( 'Create a new draft team member from this submission', 'bw-ai-schema-pro' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input type="radio" name="target_action" value="link" />
						<?php esc_html_e( 'Or link to an existing team member:', 'bw-ai-schema-pro' ); ?>
					</label>
					<br />
					<select name="target_post_id">
						<option value=""><?php esc_html_e( '— None —', 'bw-ai-schema-pro' ); ?></option>
						<?php
						$existing = get_posts( array(
							'post_type'        => $tpt,
							'post_status'      => array( 'publish', 'draft', 'private' ),
							'numberposts'      => 200,
							'orderby'          => 'title',
							'order'            => 'ASC',
							'fields'           => 'ids',
							'suppress_filters' => false,
						) );
						foreach ( $existing as $ex_id ) :
							?>
							<option value="<?php echo (int) $ex_id; ?>"><?php echo esc_html( get_the_title( $ex_id ) ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
			<?php else : ?>
				<p>
					<input type="hidden" name="target_action" value="link" />
					<strong><?php esc_html_e( 'Currently linked to:', 'bw-ai-schema-pro' ); ?></strong>
					<a href="<?php echo esc_url( get_edit_post_link( $response['target_post_id'] ) ); ?>">
						<?php echo esc_html( $team_label ); ?>
					</a>
				</p>
				<p>
					<label for="bw-schema-relink"><?php esc_html_e( 'Change link:', 'bw-ai-schema-pro' ); ?></label>
					<select id="bw-schema-relink" name="target_post_id">
						<option value="<?php echo (int) $response['target_post_id']; ?>"><?php echo esc_html( $team_label ); ?> (current)</option>
						<?php
						$existing = get_posts( array(
							'post_type'        => $tpt,
							'post_status'      => array( 'publish', 'draft', 'private' ),
							'numberposts'      => 200,
							'orderby'          => 'title',
							'order'            => 'ASC',
							'exclude'          => array( $response['target_post_id'] ),
							'fields'           => 'ids',
							'suppress_filters' => false,
						) );
						foreach ( $existing as $ex_id ) :
							?>
							<option value="<?php echo (int) $ex_id; ?>"><?php echo esc_html( get_the_title( $ex_id ) ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
			<?php endif; ?>

			<h3><?php esc_html_e( 'Moderator notes', 'bw-ai-schema-pro' ); ?></h3>
			<p>
				<textarea name="moderator_notes" rows="4" class="large-text"><?php echo esc_textarea( (string) $response['moderator_notes'] ); ?></textarea>
			</p>

			<p>
				<button type="submit" name="bw_schema_survey_triage_submit" value="1" class="button button-primary">
					<?php esc_html_e( 'Save and move to schema review', 'bw-ai-schema-pro' ); ?>
				</button>
				<a href="<?php echo esc_url( $review_url ); ?>" class="button"><?php esc_html_e( 'Skip — go to schema review', 'bw-ai-schema-pro' ); ?></a>
			</p>
		</form>

	<?php elseif ( 'review' === $tab ) : ?>

		<form method="post">
			<?php wp_nonce_field( BW_Schema_Survey_Admin::NONCE_REVIEW, '_bw_schema_survey_review_nonce' ); ?>

			<p>
				<?php esc_html_e( 'Compare what was submitted to how it will be structured for schema. Edit the right column. List fields can be comma-separated, one-per-line, or both — we tidy up on save.', 'bw-ai-schema-pro' ); ?>
			</p>

			<table class="widefat striped bw-schema-survey-review-table">
				<thead>
					<tr>
						<th style="width: 18%;"><?php esc_html_e( 'Field', 'bw-ai-schema-pro' ); ?></th>
						<th style="width: 38%;"><?php esc_html_e( 'From submission', 'bw-ai-schema-pro' ); ?></th>
						<th style="width: 44%;"><?php esc_html_e( 'Schema value', 'bw-ai-schema-pro' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $field_map as $schema_field => $meta_key ) : ?>
						<?php
						$q     = isset( $question_for_schema[ $schema_field ] ) ? $question_for_schema[ $schema_field ] : null;
						$label = $q ? $q['label'] : $schema_field;
						$type  = $q && ! empty( $q['structured_type'] ) ? $q['structured_type'] : 'string';
						$raw   = ( $q && isset( $response['raw_payload'][ $q['key'] ] ) ) ? $response['raw_payload'][ $q['key'] ] : '';
						$val   = isset( $structured[ $schema_field ] ) ? $structured[ $schema_field ] : '';
						$input_name = 'structured[' . $schema_field . ']';
						?>
						<tr>
							<th>
								<?php echo esc_html( $label ); ?><br />
								<small><code><?php echo esc_html( $schema_field ); ?></code></small>
							</th>
							<td>
								<?php
								if ( is_array( $raw ) ) {
									echo '<ul>';
									foreach ( $raw as $item ) {
										echo '<li>' . esc_html( (string) $item ) . '</li>';
									}
									echo '</ul>';
								} else {
									echo nl2br( esc_html( (string) $raw ) );
								}
								?>
							</td>
							<td>
								<?php if ( 'list' === $type || 'url-list' === $type ) : ?>
									<?php
									$list_value = is_array( $val ) ? implode( "\n", array_map( 'strval', $val ) ) : (string) $val;
									?>
									<textarea name="<?php echo esc_attr( $input_name ); ?>" rows="4" class="large-text"><?php echo esc_textarea( $list_value ); ?></textarea>
									<br />
									<small><?php esc_html_e( 'One item per line.', 'bw-ai-schema-pro' ); ?></small>
								<?php elseif ( 'int' === $type ) : ?>
									<input type="number" min="0" step="1" name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( '' === $val ? '' : (string) $val ); ?>" />
								<?php else : ?>
									<input type="text" name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( is_array( $val ) ? '' : (string) $val ); ?>" class="large-text" />
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<p>
				<button type="submit" name="bw_schema_survey_review_submit" value="1" class="button">
					<?php esc_html_e( 'Save draft', 'bw-ai-schema-pro' ); ?>
				</button>
				<button type="submit" name="bw_schema_survey_review_approve" value="1" class="button button-primary">
					<?php esc_html_e( 'Approve and mark ready to publish', 'bw-ai-schema-pro' ); ?>
				</button>
			</p>
		</form>

	<?php elseif ( 'publish' === $tab ) : ?>

		<?php if ( ! $response['target_post_id'] ) : ?>
			<div class="notice notice-error"><p>
				<?php esc_html_e( 'This submission is in the holding queue. Go back to Triage and either create or link to a team CPT entry first.', 'bw-ai-schema-pro' ); ?>
			</p></div>
		<?php elseif ( BW_Schema_Survey_Store::STATUS_READY !== $status && BW_Schema_Survey_Store::STATUS_PUBLISHED !== $status ) : ?>
			<div class="notice notice-warning"><p>
				<?php esc_html_e( 'Approve the schema review before publishing.', 'bw-ai-schema-pro' ); ?>
				<a href="<?php echo esc_url( $review_url ); ?>"><?php esc_html_e( 'Go to schema review →', 'bw-ai-schema-pro' ); ?></a>
			</p></div>
		<?php else : ?>
			<p>
				<?php esc_html_e( "This will write the structured values below onto the live team CPT entry's post meta. The live schema markup will reflect the change as soon as the page renders.", 'bw-ai-schema-pro' ); ?>
			</p>

			<h3><?php esc_html_e( 'What will be written', 'bw-ai-schema-pro' ); ?></h3>
			<table class="widefat striped">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Schema field', 'bw-ai-schema-pro' ); ?></th>
						<th><?php esc_html_e( 'Post meta key', 'bw-ai-schema-pro' ); ?></th>
						<th><?php esc_html_e( 'Value', 'bw-ai-schema-pro' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $field_map as $schema_field => $meta_key ) : ?>
						<?php $val = isset( $structured[ $schema_field ] ) ? $structured[ $schema_field ] : ''; ?>
						<tr>
							<td><code><?php echo esc_html( $schema_field ); ?></code></td>
							<td><code><?php echo esc_html( $meta_key ); ?></code></td>
							<td>
								<?php
								if ( is_array( $val ) ) {
									echo esc_html( implode( ', ', array_map( 'strval', $val ) ) );
								} else {
									echo esc_html( (string) $val );
								}
								?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<form method="post" style="margin-top: 1em;">
				<?php wp_nonce_field( BW_Schema_Survey_Admin::NONCE_PUBLISH, '_bw_schema_survey_publish_nonce' ); ?>
				<button type="submit" name="bw_schema_survey_publish_submit" value="1" class="button button-primary">
					<?php
					echo BW_Schema_Survey_Store::STATUS_PUBLISHED === $status
						? esc_html__( 'Re-publish to live schema', 'bw-ai-schema-pro' )
						: esc_html__( 'Publish to live schema', 'bw-ai-schema-pro' );
					?>
				</button>
			</form>
		<?php endif; ?>

	<?php endif; ?>
</div>
