<?php
/**
 * Admin View: Page - Status Report.
 *
 * @package CardOracle
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( 'wizard' === $active_tab ) {
	global $co_logs, $co_notices;

	$co_import_result  = null;
	$co_import_reading = isset( $_POST['co_import_reading'] ) ? absint( $_POST['co_import_reading'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing
	if ( isset( $_POST['co_import_cards_button'] ) && check_admin_referer( 'co_import_cards_nonce' ) && current_user_can( 'manage_options' ) ) {
		require_once CARD_ORACLE_DIR . 'admin/includes/class-card-oracle-card-importer.php';

		if ( isset( $_FILES['co_import_file'] ) && UPLOAD_ERR_OK === $_FILES['co_import_file']['error'] ) {
			$tmp_path  = $_FILES['co_import_file']['tmp_name']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- system temp path.
			$orig_name = isset( $_FILES['co_import_file']['name'] ) ? sanitize_file_name( $_FILES['co_import_file']['name'] ) : '';

			// fgetcsv/file_get_contents need to see the original extension; copy to a temp file with the right suffix.
			$ext      = strtolower( pathinfo( $orig_name, PATHINFO_EXTENSION ) );
			$tmp_file = wp_tempnam( 'co-import-' );
			$staged   = $tmp_file . '.' . preg_replace( '/[^a-z0-9]/i', '', $ext );
			if ( move_uploaded_file( $tmp_path, $staged ) ) {
				$importer         = new CardOracleCardImporter();
				$co_import_result = $importer->import_from_file( $staged, $co_import_reading );
				wp_delete_file( $staged );
			} else {
				$co_import_result = array(
					'inserted' => 0,
					'skipped'  => 0,
					'failed'   => 0,
					'errors'   => array( __( 'Could not stage uploaded file.', 'card-oracle' ) ),
				);
			}

			// wp_tempnam() creates the placeholder file; we staged the upload to
			// a suffixed copy, so remove the now-orphaned original.
			wp_delete_file( $tmp_file );
		} else {
			$co_import_result = array(
				'inserted' => 0,
				'skipped'  => 0,
				'failed'   => 0,
				'errors'   => array( __( 'No file was uploaded.', 'card-oracle' ) ),
			);
		}
	}

	$co_wizard_settings = get_option( 'co_wizard', array() );
	$template_defaults  = array(
		'reading_name'    => '',
		'position_total'  => '3',
		'card_total'      => '3',
		'position_prefix' => '',
		'card_prefix'     => '',
	);
	$template_state     = $template_defaults;

	if ( isset( $_POST['create_template_reading'] ) && check_admin_referer( 'co_wizard_template_nonce' ) ) {
		$template_state = array(
			'reading_name'    => isset( $_POST['co_template_reading'] ) ? sanitize_text_field( wp_unslash( $_POST['co_template_reading'] ) ) : '',
			'position_total'  => isset( $_POST['co_template_positions'] ) ? sanitize_text_field( wp_unslash( $_POST['co_template_positions'] ) ) : '',
			'card_total'      => isset( $_POST['co_template_cards'] ) ? sanitize_text_field( wp_unslash( $_POST['co_template_cards'] ) ) : '',
			'position_prefix' => isset( $_POST['co_template_position_prefix'] ) ? sanitize_text_field( wp_unslash( $_POST['co_template_position_prefix'] ) ) : '',
			'card_prefix'     => isset( $_POST['co_template_card_prefix'] ) ? sanitize_text_field( wp_unslash( $_POST['co_template_card_prefix'] ) ) : '',
		);

		$template_args = array(
			'reading_name'    => $template_state['reading_name'],
			'position_total'  => absint( $template_state['position_total'] ),
			'card_total'      => absint( $template_state['card_total'] ),
			'position_prefix' => $template_state['position_prefix'],
			'card_prefix'     => $template_state['card_prefix'],
		);

		$validation = CardOracleAdminWizard::validate_template_reading( $template_args );

		if ( is_wp_error( $validation ) ) {
			$messages = array_map( 'esc_html', $validation->get_error_messages() );
			$co_notices->add( 'wizard-template-error', implode( '<br />', $messages ), 'error' );
			$co_notices->display();
		} else {
			CardOracleAdminWizard::create_template_reading( $template_args );
			$co_notices->add_display( 'wizard_template_created', esc_html__( 'Template reading created.', 'card-oracle' ), 'info' );
			$template_state = $template_defaults;
		}
	}

	// Reading Input.
	if ( isset( $_POST['co_wizard_reading'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings['reading'] = sanitize_text_field( wp_unslash( $_POST['co_wizard_reading'] ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Positions Table.
	// If the table has been sorted then update the variable positions.
	if ( isset( $_POST['position'], $_POST['card_oracle_sort_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['card_oracle_sort_nonce'] ) ), 'co_wizard_sort_nonce' ) ) {
		$co_wizard_settings['positions'] = array_map( 'sanitize_text_field', wp_unslash( $_POST['position'] ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// The add_position button has been pressed, add the text to the array.
	if ( isset( $_POST['add_position'] ) && ! empty( $_POST['co_wizard_add_position'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		// The variable doesn't exist, initialize it.
		if ( ! isset( $co_wizard_settings['positions'] ) ) {
			$co_wizard_settings['positions'] = array();
		}

		array_push( $co_wizard_settings['positions'], sanitize_text_field( wp_unslash( $_POST['co_wizard_add_position'] ) ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Clear All Positions button pressed, reset the variable.
	if ( isset( $_POST['clear_position'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings['positions'] = array();
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Delete position button pressed, remove it from the variable and reorder the list.
	if ( isset( $_POST['delete_position'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings['positions'] = array_merge( array_diff( $co_wizard_settings['positions'], array( sanitize_text_field( wp_unslash( $_POST['delete_position'] ) ) ) ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Cards Table.
	if ( isset( $_POST['add_card'] ) && ! empty( $_POST['co_wizard_add_card'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		if ( ! isset( $co_wizard_settings['cards'] ) ) {
			$co_wizard_settings['cards'] = array();
		}

		array_push( $co_wizard_settings['cards'], sanitize_text_field( wp_unslash( $_POST['co_wizard_add_card'] ) ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Clear All Cards button pressed, reset the variable.
	if ( isset( $_POST['clear_card'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings['cards'] = array();
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Delete card button pressed, remove it from the variable and reorder the list.
	if ( isset( $_POST['delete_card'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings['cards'] = array_merge( array_diff( $co_wizard_settings['cards'], array( sanitize_text_field( wp_unslash( $_POST['delete_card'] ) ) ) ) );
		update_option( 'co_wizard', $co_wizard_settings );
	}

	// Create the Reading.
	if ( isset( $_POST['create_reading'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		if ( CardOracleAdminWizard::wizard_validate() ) {
			CardOracleAdminWizard::create_reading();

			// Show success admin notice.
			$co_notices->add_display( 'wizard_created', esc_html__( 'Reading created.', 'card-oracle' ), 'info' );

			// Clear the variables after creating Reading.
			$co_wizard_settings = array();
			update_option( 'co_wizard', $co_wizard_settings );
		}
	}

	// Clear All Cards button pressed, reset the variable.
	if ( isset( $_POST['clear_form'] ) && check_admin_referer( 'co_wizard_nonce' ) ) {
		$co_wizard_settings = array();
		update_option( 'co_wizard', $co_wizard_settings );
	}

	?>

	<div class="co-dashboard">
		<header class="co-dashboard__hero co-dashboard__hero--subtle">
			<div class="co-dashboard__hero-text">
				<span class="co-dashboard__badge"><?php esc_html_e( 'Builder', 'card-oracle' ); ?></span>
				<h1 class="co-dashboard__hero-title"><?php esc_html_e( 'Setup Wizard', 'card-oracle' ); ?></h1>
				<p class="co-dashboard__hero-description">
					<?php esc_html_e( 'Generate a complete reading in minutes by capturing the positions and cards you want to include.', 'card-oracle' ); ?>
				</p>
			</div>
			<div class="co-dashboard__hero-actions">
				<a class="button button-secondary" href="<?php echo esc_url( admin_url( 'admin.php?page=card-oracle-doc-viewer&doc=wizard-guide' ) ); ?>">
					<?php esc_html_e( 'Open Wizard Guide', 'card-oracle' ); ?>
				</a>
				<a class="button button-secondary" href="<?php echo esc_url( admin_url( 'admin.php?page=card-oracle-doc-viewer&doc=help' ) ); ?>">
					<?php esc_html_e( 'Help Documentation', 'card-oracle' ); ?>
				</a>
			</div>
		</header>

		<section class="co-dashboard__section co-dashboard__section--panel">
			<div class="co-dashboard__section-heading">
				<h2><?php esc_html_e( 'Build Your Reading', 'card-oracle' ); ?></h2>
				<p><?php esc_html_e( 'The wizard creates readings, positions, cards, and descriptions using sensible defaults. You can finalize the details of your readings later, after the scaffold is generated here.', 'card-oracle' ); ?></p>
			</div>
			<div class="co-dashboard__panel-body card-oracle-wizard">
		<div class="card-oracle-wizard-section card-oracle-template-builder">
			<form method="post" class="card-oracle-template-form">
				<?php wp_nonce_field( 'co_wizard_template_nonce' ); ?>
			<table class="card_oracle_status_table widefat striped" cellspacing="0">
				<thead>
					<tr>
						<th colspan="2">
							<h2><?php esc_html_e( 'Template Builder', 'card-oracle' ); ?></h2>
							<p><?php esc_html_e( 'Generate a skeleton reading with placeholder cards and positions. You can fine-tune the generated posts later.', 'card-oracle' ); ?></p>
						</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">
							<label for="co_template_reading"><?php esc_html_e( 'Reading name', 'card-oracle' ); ?></label>
						</th>
						<td>
								<input id="co_template_reading" class="regular-text" type="text" name="co_template_reading" value="<?php echo esc_attr( $template_state['reading_name'] ); ?>" />
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="co_template_positions"><?php esc_html_e( 'Number of positions', 'card-oracle' ); ?></label>
						</th>
						<td>
								<input id="co_template_positions" class="small-text" type="number" min="1" step="1" name="co_template_positions" value="<?php echo esc_attr( $template_state['position_total'] ); ?>" />
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="co_template_cards"><?php esc_html_e( 'Number of cards', 'card-oracle' ); ?></label>
						</th>
						<td>
								<input id="co_template_cards" class="small-text" type="number" min="1" step="1" name="co_template_cards" value="<?php echo esc_attr( $template_state['card_total'] ); ?>" />
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="co_template_position_prefix"><?php esc_html_e( 'Position prefix', 'card-oracle' ); ?></label>
						</th>
						<td>
								<input id="co_template_position_prefix" class="regular-text" type="text" name="co_template_position_prefix" value="<?php echo esc_attr( $template_state['position_prefix'] ); ?>" placeholder="<?php esc_attr_e( 'Position', 'card-oracle' ); ?>" />
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="co_template_card_prefix"><?php esc_html_e( 'Card prefix', 'card-oracle' ); ?></label>
						</th>
						<td>
								<input id="co_template_card_prefix" class="regular-text" type="text" name="co_template_card_prefix" value="<?php echo esc_attr( $template_state['card_prefix'] ); ?>" placeholder="<?php esc_attr_e( 'Card', 'card-oracle' ); ?>" />
						</td>
					</tr>
				</tbody>
				<tfoot>
					<tr>
						<td colspan="2">
								<?php submit_button( esc_attr__( 'Create Template', 'card-oracle' ), 'primary', 'create_template_reading', false ); ?>
						</td>
					</tr>
				</tfoot>
			</table>
			</form>
		</div>
		<div class="card-oracle-wizard-section card-oracle-card-importer">
			<form method="post" enctype="multipart/form-data" class="card-oracle-import-form">
				<?php wp_nonce_field( 'co_import_cards_nonce' ); ?>
				<table class="card_oracle_status_table widefat striped" cellspacing="0">
					<thead>
						<tr>
							<th colspan="2">
								<h2><?php esc_html_e( 'Bulk Card Import', 'card-oracle' ); ?></h2>
								<p><?php esc_html_e( 'Upload a JSON array or CSV file to create multiple cards at once. Each row should at minimum contain a "name" column; an optional "description" column may include HTML.', 'card-oracle' ); ?></p>
							</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<th scope="row">
								<label for="co_import_reading"><?php esc_html_e( 'Add cards to reading', 'card-oracle' ); ?></label>
							</th>
							<td>
								<?php
								echo wp_kses(
									wp_dropdown_pages(
										array(
											'echo'        => 0,
											'name'        => 'co_import_reading',
											'show_option_none' => esc_html__( 'Select a Reading:', 'card-oracle' ),
											'post_type'   => 'co_readings',
											'selected'    => $co_import_reading,
											'sort_column' => 'post_title',
										)
									),
									array(
										'select' => array(
											'name' => array(),
											'id'   => array(),
										),
										'option' => array(
											'value'    => array(),
											'selected' => array(),
										),
									)
								);
								?>
								<p class="description"><?php esc_html_e( 'Select an existing reading to attach the imported cards to. Leave on "Select a Reading:" to create unlinked cards.', 'card-oracle' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="co_import_file"><?php esc_html_e( 'File', 'card-oracle' ); ?></label>
							</th>
							<td>
								<input id="co_import_file" type="file" name="co_import_file" accept=".json,.csv,application/json,text/csv" required />
								<p class="description"><?php esc_html_e( 'Accepted formats: .json (array of card objects) or .csv (header row with name,description).', 'card-oracle' ); ?></p>
							</td>
						</tr>
						<?php if ( null !== $co_import_result ) : ?>
							<tr>
								<td colspan="2">
									<div class="notice notice-<?php echo $co_import_result['failed'] > 0 || ! empty( $co_import_result['errors'] ) ? 'warning' : 'success'; ?> inline" style="margin: 6px 0;">
										<p>
											<?php
											printf(
												/* translators: 1: inserted count, 2: skipped count, 3: failed count */
												esc_html__( 'Imported %1$d cards (%2$d skipped, %3$d failed).', 'card-oracle' ),
												(int) $co_import_result['inserted'],
												(int) $co_import_result['skipped'],
												(int) $co_import_result['failed']
											);
											?>
										</p>
										<?php if ( ! empty( $co_import_result['errors'] ) ) : ?>
											<ul style="margin-left: 1.5em;">
												<?php foreach ( $co_import_result['errors'] as $err ) : ?>
													<li><?php echo esc_html( $err ); ?></li>
												<?php endforeach; ?>
											</ul>
										<?php endif; ?>
									</div>
								</td>
							</tr>
						<?php endif; ?>
					</tbody>
					<tfoot>
						<tr>
							<td colspan="2">
								<?php submit_button( esc_attr__( 'Import Cards', 'card-oracle' ), 'primary', 'co_import_cards_button', false ); ?>
							</td>
						</tr>
					</tfoot>
				</table>
			</form>
		</div>
		<div class="card-oracle-wizard-group">
			<div class="card-oracle-wizard-group-header">
				<h2><?php esc_html_e( 'Reading Builder', 'card-oracle' ); ?></h2>
				<p><?php esc_html_e( 'Manually define your reading name, positions, and cards, then generate the complete reading structure.', 'card-oracle' ); ?></p>
			</div>
		<div class="card-oracle-wizard-section">
			<table class="card_oracle_status_table widefat striped" cellspacing="0">
				<thead>
					<th>
						<h2>
							<?php esc_html_e( 'Reading', 'card-oracle' ); ?>
							<?php echo card_oracle_tool_tip( esc_html__( 'This is the title of the reading you wish to create.', 'card-oracle' ) ); /* phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped */ ?>
						</h2>
				</th>
				</thead>
				<tbody>
					<tr>
						<td>
							<form method="post" class="card-oracle-wizard-inline">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<label class="screen-reader-text" for="co_wizard_reading"><?php esc_html_e( 'Reading name', 'card-oracle' ); ?></label>
								<input id="co_wizard_reading" class="regular-text card-oracle-wizard-input" type="text" name="co_wizard_reading" value="<?php echo isset( $co_wizard_settings['reading'] ) ? esc_html( $co_wizard_settings['reading'] ) : ''; ?>" />
								<?php submit_button( esc_attr( __( 'Save Reading', 'card-oracle' ) ), 'primary', 'save_reading', '' ); ?>
							</form>
						</td>
					</tr>
				</tbody>
				<?php if ( empty( $co_wizard_settings['reading'] ) ) : ?>
					<tfoot>
						<tr>
							<td>
								<?php echo esc_html( __( 'Save the Reading.', 'card-oracle' ) ); ?>
							</td>
						</tr>
					</tfoot>
				<?php endif; ?>
			</table>
		</div>
		<div class="card-oracle-wizard-section">
			<table class="card_oracle_wizard_table widefat striped sortable" cellspacing="0">
				<thead>
					<th width="32"><span title="Drag and Drop to move item up or down.">&udarr;</span></th>
					<th>
						<h2>
							<?php esc_html_e( 'Positions', 'card-oracle' ); ?>
							<?php echo card_oracle_tool_tip( esc_html__( 'Add all the Positions for this Reading. You can drag and drop items to change the Order.' ) ); /* phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped */ ?>
						</h2>
					</th>
					<th><?php esc_html_e( 'Order', 'card-oracle' ); ?></th>
					<th title="Delete this position."><?php esc_html_e( 'Delete?', 'card-oracle' ); ?></th>
				</thead>
				<tbody class="row_position">
			<?php if ( ! empty( $co_wizard_settings['positions'] ) ) : ?>
				<?php $count = 0; ?>
				<?php $count_positions = count( $co_wizard_settings['positions'] ); ?>
				<?php foreach ( $co_wizard_settings['positions'] as $position ) : ?>
					<?php ++$count; ?>
					<tr id="<?php echo esc_attr( $position ); ?>">
					<?php if ( $count_positions > 1 ) : ?>
						<td class="card-oracle-color-3">
							<?php if ( 1 === $count ) : ?>
								<span title="Drag and Drop to move item down.">&darr;</span>
							<?php elseif ( $count === $count_positions ) : ?>
								<span title="Drag and Drop to move item up.">&uarr;</span>
							<?php else : ?>
								<span title="Drag and Drop to move item up or down.">&udarr;</span>
							<?php endif; ?>
						</td>
						<?php else : ?>
							<td></td>
						<?php endif; ?>
						<td>
						<?php echo esc_attr( $position ); ?>
						</td>
						<td>
							<?php echo esc_attr( $count ); ?>
						</td>
						<td class="card-oracle-icon-button">
							<form action="" method="post">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<?php echo card_oracle_delete_button( __( 'Delete this position.', 'card-oracle' ), 'delete_position', $position ); /* phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped */ ?>
							</form>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php else : ?>
				<tr>
					<td colspan="4">
						<?php echo esc_html__( 'Enter the Positions for this Reading.', 'card-oracle' ); ?>
					</td>
				</tr>
			<?php endif; ?>
				</tbody>
				<tfoot>
					<tr>
						<td colspan="3">
							<form action="" method="post" class="card-oracle-wizard-inline">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<label class="screen-reader-text" for="co_wizard_add_position"><?php esc_html_e( 'Add new position', 'card-oracle' ); ?></label>
								<input id="co_wizard_add_position" class="regular-text card-oracle-wizard-input" type="text" name="co_wizard_add_position" value="" />
								<?php submit_button( esc_attr( __( 'Add Position', 'card-oracle' ) ), 'primary', 'add_position', '' ); ?>
							</form>
						</td>
						<td class="card-oracle-icon-button">
							<form action="" method="post" class="card-oracle-wizard-inline">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<?php submit_button( esc_attr( __( 'Clear All', 'card-oracle' ) ), 'delete', 'clear_position', '' ); ?>
							</form>
						</td>
					</tr>
				</tfoot>
			</table>
		</div>
		<div class="card-oracle-wizard-section">
			<table class="card_oracle_wizard_table widefat striped" cellspacing="0">
				<thead>
					<th>
						<h2>
							<?php esc_html_e( 'Cards', 'card-oracle' ); ?>
							<?php echo card_oracle_tool_tip( esc_html__( 'Add all the Cards for this Reading.' ) ); /* phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped */ ?>
						</h2>
					</th>
					<th title="<?php esc_html_e( 'Click the Trash icon to delete a card.', 'card-oracle' ); ?>"><?php esc_html_e( 'Delete?', 'card-oracle' ); ?></th>
				</thead>
				<tbody>
			<?php if ( ! empty( $co_wizard_settings['cards'] ) ) : ?>
				<?php foreach ( $co_wizard_settings['cards'] as $card ) : ?>
					<tr id="<?php echo esc_attr( $card ); ?>">
						<td>
						<?php echo esc_attr( $card ); ?>
						</td>
						<td class="card-oracle-icon-button">
							<form action="" method="post">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<?php echo card_oracle_delete_button( __( 'Delete this card.', 'card-oracle' ), 'delete_card', $card ); /* phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped */ ?>
							</form>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php else : ?>
				<tr>
					<td>
						<?php echo esc_html__( 'Enter the Cards for this Reading.', 'card-oracle' ); ?>
					</td>
				</tr>
			<?php endif; ?>
				</tbody>
				<tfoot>
					<tr>
						<td>
							<form action="" method="post" class="card-oracle-wizard-inline">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<label class="screen-reader-text" for="co_wizard_add_card"><?php esc_html_e( 'Add new card', 'card-oracle' ); ?></label>
								<input id="co_wizard_add_card" class="regular-text card-oracle-wizard-input" type="text" name="co_wizard_add_card" value="" />
								<?php submit_button( esc_attr( __( 'Add Card', 'card-oracle' ) ), 'primary', 'add_card', '' ); ?>
							</form>
						</td>
						<td class="card-oracle-icon-button">
							<form action="" method="post" class="card-oracle-wizard-inline">
								<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
								<?php submit_button( esc_attr( __( 'Clear All', 'card-oracle' ) ), 'delete', 'clear_card', '' ); ?>
							</form>
						</td>
					</tr>
				</tfoot>
			</table>
		</div>
			<form action="" class="card-oracle-wizard-actions" method="post">
				<input type="hidden" value="true" name="co_wizard_create_reading" />
				<?php wp_nonce_field( 'co_wizard_nonce' ); ?>
				<?php submit_button( esc_attr( __( 'Create Reading', 'card-oracle' ) ), 'primary', 'create_reading', '' ); ?>
				<?php submit_button( esc_attr( __( 'Clear All', 'card-oracle' ) ), 'delete', 'clear_form', '' ); ?>
			</form>
		</div>
			</div>
		</section>
	</div>

	<!-- Wizard Progress Modal -->
	<div id="co-wizard-modal" class="co-install-modal" style="display: none;">
		<div class="co-install-modal-overlay"></div>
		<div class="co-install-modal-content">
			<div class="co-install-modal-icon">
				<span class="dashicons dashicons-update-alt co-install-spinner"></span>
			</div>
			<h2 class="co-wizard-modal-title"><?php esc_html_e( 'Creating Reading', 'card-oracle' ); ?></h2>
			<p class="co-wizard-modal-message"><?php esc_html_e( 'Please wait while the reading is being created. This may take a few moments.', 'card-oracle' ); ?></p>
		</div>
	</div>

	<!-- Duplicate Warning Modal -->
	<div id="co-wizard-warning-modal" class="co-install-modal" style="display: none;">
		<div class="co-install-modal-overlay"></div>
		<div class="co-install-modal-content">
			<div class="co-install-modal-icon">
				<span class="dashicons dashicons-warning co-warning-icon"></span>
			</div>
			<h2 class="co-wizard-warning-title"><?php esc_html_e( 'Reading Already Exists', 'card-oracle' ); ?></h2>
			<p class="co-wizard-warning-message"></p>
			<div class="co-modal-buttons">
				<button type="button" id="co-wizard-warning-cancel" class="button button-secondary"><?php esc_html_e( 'Cancel', 'card-oracle' ); ?></button>
				<button type="button" id="co-wizard-warning-continue" class="button button-primary"><?php esc_html_e( 'Continue', 'card-oracle' ); ?></button>
			</div>
		</div>
	</div>

	<script>
	jQuery(document).ready(function($) {
		var pendingForm = null;
		var pendingSubmitButton = null;
		var skipDuplicateCheck = false;

		// Function to check if reading name exists
		function checkReadingExists(readingName, callback) {
			$.ajax({
				url: cardOracleWizard.ajaxUrl,
				type: 'POST',
				data: {
					action: 'card_oracle_check_reading_exists',
					nonce: cardOracleWizard.checkReadingNonce,
					reading_name: readingName
				},
				success: function(response) {
					if (response.success) {
						callback(response.data.exists, response.data.message);
					} else {
						callback(false, null);
					}
				},
				error: function() {
					callback(false, null);
				}
			});
		}

		// Function to show progress modal
		function showProgressModal(isTemplate) {
			if (isTemplate) {
				$('.co-wizard-modal-title').text('<?php echo esc_js( __( 'Creating Template', 'card-oracle' ) ); ?>');
				$('.co-wizard-modal-message').text('<?php echo esc_js( __( 'Please wait while the template reading is being created. This may take a few moments.', 'card-oracle' ) ); ?>');
			} else {
				$('.co-wizard-modal-title').text('<?php echo esc_js( __( 'Creating Reading', 'card-oracle' ) ); ?>');
				$('.co-wizard-modal-message').text('<?php echo esc_js( __( 'Please wait while the reading is being created. This may take a few moments.', 'card-oracle' ) ); ?>');
			}
			$('#co-wizard-modal').fadeIn(200);
		}

		// Function to submit form by clicking the submit button
		function submitForm($submitButton) {
			skipDuplicateCheck = true;
			$submitButton.click();
		}

		// Handle Template Builder form submission
		$('.card-oracle-template-form').on('submit', function(e) {
			var $form = $(this);
			var $submitBtn = $form.find('input[name="create_template_reading"]');
			var readingName = $('#co_template_reading').val();

			if (!readingName || readingName.trim() === '') {
				return true;
			}

			// If we're skipping the check, just show progress and continue
			if (skipDuplicateCheck) {
				skipDuplicateCheck = false;
				showProgressModal(true);
				return true;
			}

			e.preventDefault();
			pendingForm = $form;
			pendingSubmitButton = $submitBtn;

			checkReadingExists(readingName, function(exists, message) {
				if (exists) {
					$('.co-wizard-warning-message').text(message);
					$('#co-wizard-warning-modal').fadeIn(200);
				} else {
					showProgressModal(true);
					submitForm($submitBtn);
				}
			});

			return false;
		});

		// Handle Reading Builder form submission (Create Reading button)
		$('.card-oracle-wizard-actions').on('submit', function(e) {
			var $form = $(this);
			var $createBtn = $form.find('input[name="create_reading"]');

			if (!$createBtn.length || !e.originalEvent || !e.originalEvent.submitter || e.originalEvent.submitter.name !== 'create_reading') {
				return true;
			}

			var readingName = $('#co_wizard_reading').val();

			if (!readingName || readingName.trim() === '') {
				return true;
			}

			// If we're skipping the check, just show progress and continue
			if (skipDuplicateCheck) {
				skipDuplicateCheck = false;
				showProgressModal(false);
				return true;
			}

			e.preventDefault();
			pendingForm = $form;
			pendingSubmitButton = $createBtn;

			checkReadingExists(readingName, function(exists, message) {
				if (exists) {
					$('.co-wizard-warning-message').text(message);
					$('#co-wizard-warning-modal').fadeIn(200);
				} else {
					showProgressModal(false);
					submitForm($createBtn);
				}
			});

			return false;
		});

		// Handle warning modal cancel
		$('#co-wizard-warning-cancel, #co-wizard-warning-modal .co-install-modal-overlay').on('click', function() {
			$('#co-wizard-warning-modal').fadeOut(200);
			pendingForm = null;
			pendingSubmitButton = null;
		});

		// Handle warning modal continue
		$('#co-wizard-warning-continue').on('click', function() {
			$('#co-wizard-warning-modal').fadeOut(200);
			if (pendingSubmitButton) {
				var isTemplate = pendingForm && pendingForm.hasClass('card-oracle-template-form');
				showProgressModal(isTemplate);
				submitForm(pendingSubmitButton);
			}
		});
	});
	</script>

<?php } ?>
