<?php
/**
 * The admin wizard: a single page with multi-step form, live preview and publish.
 */

defined( 'ABSPATH' ) || exit;

class TSFFE_Wizard {

	const SCREEN_SLUG = 'tsffe-statement-forge';

	public static function init(): void {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	public static function register_menu(): void {
		add_menu_page(
			__( 'Tendforge Statement Forge for EAA', 'tendforge-statement-forge-for-eaa' ),
			__( 'Accessibility Statement', 'tendforge-statement-forge-for-eaa' ),
			'manage_options',
			self::SCREEN_SLUG,
			array( __CLASS__, 'render_page' ),
			'dashicons-universal-access',
			81
		);
	}

	public static function enqueue_assets( string $hook ): void {
		if ( false === strpos( $hook, self::SCREEN_SLUG ) ) {
			return;
		}

		wp_enqueue_style( 'tsffe-admin', TSFFE_PLUGIN_URL . 'assets/css/admin.css', array(), TSFFE_VERSION );
		wp_enqueue_script( 'tsffe-admin', TSFFE_PLUGIN_URL . 'assets/js/admin.js', array(), TSFFE_VERSION, true );

		// A statement page already exists -> the action is an update, so the
		// progress/result copy says "update" instead of "publish" again.
		$update = self::has_published_page();

		wp_localize_script(
			'tsffe-admin',
			'tsffeAdmin',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'tsffe_admin' ),
				'i18n'    => array(
					'saving'      => __( 'Saving…', 'tendforge-statement-forge-for-eaa' ),
					'publishing'  => $update ? __( 'Updating…', 'tendforge-statement-forge-for-eaa' ) : __( 'Publishing…', 'tendforge-statement-forge-for-eaa' ),
					'saveError'   => __( 'Something went wrong. Please try again.', 'tendforge-statement-forge-for-eaa' ),
					'published'   => $update ? __( 'Your accessibility statement page has been updated.', 'tendforge-statement-forge-for-eaa' ) : __( 'Your accessibility statement page has been published.', 'tendforge-statement-forge-for-eaa' ),
					'fixErrors'   => __( 'Please fix the highlighted fields before publishing.', 'tendforge-statement-forge-for-eaa' ),
				),
			)
		);
	}

	/**
	 * Whether a live (not trashed) statement page has been published before.
	 */
	private static function has_published_page(): bool {
		$page_id = TSFFE_Page::get_page_id();
		return $page_id > 0 && 'page' === get_post_type( $page_id ) && 'trash' !== get_post_status( $page_id );
	}

	/**
	 * Pre-fill defaults from WordPress settings.
	 *
	 * @return array<string, mixed>
	 */
	private static function prefill(): array {
		$saved = get_option( TSFFE_Page::OPTION_STATEMENT, array() );
		if ( is_array( $saved ) && ! empty( $saved ) ) {
			return array_merge( TSFFE_Data::defaults(), $saved );
		}

		$data                = TSFFE_Data::defaults();
		$data['org_name']    = get_bloginfo( 'name' );
		$data['site_name']   = get_bloginfo( 'name' );
		$data['site_url']    = home_url();
		$data['contact_email'] = get_bloginfo( 'admin_email' );
		$data['prepared_date'] = current_time( 'Y-m-d' );

		// Best-effort country guess from the WP locale (e.g. de_DE -> DE).
		$locale = get_locale();
		if ( preg_match( '/_([A-Z]{2})$/', $locale, $m ) && null !== TSFFE_Bodies::get( $m[1] ) ) {
			$data['enforcement_country'] = $m[1];
		}

		return $data;
	}

	/**
	 * The page's tabs. The free plugin ships the wizard; add-ons append their own
	 * tabs via the `tsffe_tabs` filter and render them on the matching
	 * `tsffe_render_tab_{slug}` action — so Pro features live alongside the free
	 * wizard instead of in separate sidebar submenus.
	 *
	 * @return array<string,string> slug => label
	 */
	public static function tabs(): array {
		$tabs = array(
			'wizard' => __( 'Statement wizard', 'tendforge-statement-forge-for-eaa' ),
		);

		return (array) apply_filters( 'tsffe_tabs', $tabs );
	}

	private static function current_tab(): string {
		// Read-only tab switch; no state change, nonce not required.
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'wizard'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return array_key_exists( $tab, self::tabs() ) ? $tab : 'wizard';
	}

	public static function render_page(): void {
		$tab  = self::current_tab();
		$tabs = self::tabs();
		?>
		<div class="wrap tsffe-wrap">
			<h1><?php esc_html_e( 'Tendforge Statement Forge for EAA', 'tendforge-statement-forge-for-eaa' ); ?></h1>

			<?php if ( count( $tabs ) > 1 ) : ?>
				<h2 class="nav-tab-wrapper">
					<?php
					foreach ( $tabs as $key => $label ) {
						printf(
							'<a href="%s" class="nav-tab %s">%s</a>',
							esc_url( admin_url( 'admin.php?page=' . self::SCREEN_SLUG . '&tab=' . $key ) ),
							$tab === $key ? 'nav-tab-active' : '',
							esc_html( $label )
						);
					}
					?>
				</h2>
			<?php endif; ?>

			<?php
			if ( 'wizard' === $tab ) {
				self::render_wizard_tab();
			} else {
				/**
				 * Render a tab registered by an add-on (e.g. the Pro companion)
				 * through the `tsffe_tabs` filter.
				 *
				 * @param string $tab The current tab slug.
				 */
				do_action( 'tsffe_render_tab_' . $tab, $tab );
			}
			?>
		</div>
		<?php
	}

	private static function render_wizard_tab(): void {
		$data    = self::prefill();
		$page_id = TSFFE_Page::get_page_id();
		$footer  = (bool) get_option( TSFFE_Page::OPTION_FOOTER_LINK, false );
		$answers = is_array( $data['answers'] ) ? $data['answers'] : array();

		$yn = static function ( array $answers, string $key, string $val ): string {
			return ( ( $answers[ $key ] ?? '' ) === $val ) ? 'checked' : '';
		};
		?>
			<p class="tsffe-intro">
				<?php esc_html_e( 'Generate an EU/EAA accessibility statement and a feedback route. This produces a self-declared disclosure document — it does not make your site accessible and never claims compliance.', 'tendforge-statement-forge-for-eaa' ); ?>
			</p>

			<?php if ( $page_id ) : ?>
				<div class="notice notice-success inline">
					<p>
						<?php
						printf(
							/* translators: %s: link to the published page */
							esc_html__( 'Your statement is published: %s', 'tendforge-statement-forge-for-eaa' ),
							'<a href="' . esc_url( (string) get_permalink( $page_id ) ) . '">' . esc_html__( 'view page', 'tendforge-statement-forge-for-eaa' ) . '</a>'
						);
						?>
					</p>
				</div>
			<?php endif; ?>

			<div class="tsffe-layout">
				<form id="tsffe-form" class="tsffe-form">

					<?php /* STEP 1 — who / scope */ ?>
					<fieldset class="tsffe-step" data-step="1">
						<legend><?php esc_html_e( 'Step 1 — Who and what', 'tendforge-statement-forge-for-eaa' ); ?></legend>

						<p>
							<label for="tsffe-org_name"><?php esc_html_e( 'Organisation / website owner', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="text" id="tsffe-org_name" name="org_name" value="<?php echo esc_attr( $data['org_name'] ); ?>" class="regular-text" />
							<span class="tsffe-error" data-error-for="org_name"></span>
						</p>
						<p>
							<label for="tsffe-site_url"><?php esc_html_e( 'Website address', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="url" id="tsffe-site_url" name="site_url" value="<?php echo esc_attr( $data['site_url'] ); ?>" class="regular-text" />
							<span class="tsffe-error" data-error-for="site_url"></span>
						</p>
						<p>
							<label for="tsffe-scope"><?php esc_html_e( 'Scope (optional — what this statement covers)', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="text" id="tsffe-scope" name="scope" value="<?php echo esc_attr( $data['scope'] ); ?>" class="large-text" />
						</p>
					</fieldset>

					<?php /* STEP 2 — how accessible (yes/no self assessment) */ ?>
					<fieldset class="tsffe-step" data-step="2">
						<legend><?php esc_html_e( 'Step 2 — How accessible is it?', 'tendforge-statement-forge-for-eaa' ); ?></legend>
						<p class="description"><?php esc_html_e( 'Answer honestly. Your answers determine the conformance status; the conservative default is "partially conformant".', 'tendforge-statement-forge-for-eaa' ); ?></p>

						<?php
						$questions = array(
							'tested'   => __( 'Has any accessibility testing been carried out on the site?', 'tendforge-statement-forge-for-eaa' ),
							'keyboard' => __( 'Is the site fully operable using only a keyboard?', 'tendforge-statement-forge-for-eaa' ),
							'contrast' => __( 'Does text meet the colour-contrast requirements?', 'tendforge-statement-forge-for-eaa' ),
							'alt_text' => __( 'Do meaningful images have text alternatives?', 'tendforge-statement-forge-for-eaa' ),
							'labels'   => __( 'Do forms have labels and clear instructions?', 'tendforge-statement-forge-for-eaa' ),
							'headings' => __( 'Is there a proper heading structure and landmarks?', 'tendforge-statement-forge-for-eaa' ),
						);
						foreach ( $questions as $key => $label ) :
							?>
							<div class="tsffe-question">
								<span class="tsffe-q-label"><?php echo esc_html( $label ); ?></span>
								<label><input type="radio" name="answers[<?php echo esc_attr( $key ); ?>]" value="yes" <?php echo esc_attr( $yn( $answers, $key, 'yes' ) ); ?> /> <?php esc_html_e( 'Yes', 'tendforge-statement-forge-for-eaa' ); ?></label>
								<label><input type="radio" name="answers[<?php echo esc_attr( $key ); ?>]" value="no" <?php echo esc_attr( $yn( $answers, $key, 'no' ) ); ?> /> <?php esc_html_e( 'No', 'tendforge-statement-forge-for-eaa' ); ?></label>
							</div>
						<?php endforeach; ?>

						<p>
							<label for="tsffe-assessment_method"><?php esc_html_e( 'How was this assessed?', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<select id="tsffe-assessment_method" name="assessment_method">
								<option value="self" <?php selected( $data['assessment_method'], 'self' ); ?>><?php esc_html_e( 'Self-assessment by the site owner', 'tendforge-statement-forge-for-eaa' ); ?></option>
								<option value="third-party" <?php selected( $data['assessment_method'], 'third-party' ); ?>><?php esc_html_e( 'Third-party evaluation', 'tendforge-statement-forge-for-eaa' ); ?></option>
							</select>
						</p>
						<p>
							<label for="tsffe-wcag_version"><?php esc_html_e( 'WCAG version applied', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<select id="tsffe-wcag_version" name="wcag_version">
								<option value="2.1" <?php selected( $data['wcag_version'], '2.1' ); ?>>WCAG 2.1</option>
								<option value="2.2" <?php selected( $data['wcag_version'], '2.2' ); ?>>WCAG 2.2</option>
							</select>
						</p>

						<div class="tsffe-confirm-full">
							<label>
								<input type="checkbox" id="tsffe-confirm_full" name="confirm_full" value="1" <?php checked( ! empty( $data['confirm_full'] ) ); ?> />
								<?php esc_html_e( 'I deliberately confirm the site is fully conformant. (Only tick this if every answer above is "Yes" and you are certain — most sites should leave this unticked.)', 'tendforge-statement-forge-for-eaa' ); ?>
							</label>
							<span class="tsffe-error" data-error-for="conformance"></span>
						</div>
					</fieldset>

					<?php /* STEP 3 — known limitations, three buckets */ ?>
					<fieldset class="tsffe-step" data-step="3">
						<legend><?php esc_html_e( 'Step 3 — Known limitations', 'tendforge-statement-forge-for-eaa' ); ?></legend>
						<p class="description"><?php esc_html_e( 'List any content you know is not fully accessible. One item per line.', 'tendforge-statement-forge-for-eaa' ); ?></p>

						<p>
							<label for="tsffe-non_compliance"><?php esc_html_e( 'Non-compliance with the requirements', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<textarea id="tsffe-non_compliance" name="non_compliance" rows="4" class="large-text"><?php echo esc_textarea( implode( "\n", (array) $data['non_compliance'] ) ); ?></textarea>
						</p>
						<p>
							<label for="tsffe-disproportionate_burden"><?php esc_html_e( 'Disproportionate burden', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<textarea id="tsffe-disproportionate_burden" name="disproportionate_burden" rows="4" class="large-text"><?php echo esc_textarea( implode( "\n", (array) $data['disproportionate_burden'] ) ); ?></textarea>
						</p>
						<p>
							<label for="tsffe-out_of_scope"><?php esc_html_e( 'Content outside the scope of the legislation', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<textarea id="tsffe-out_of_scope" name="out_of_scope" rows="4" class="large-text"><?php echo esc_textarea( implode( "\n", (array) $data['out_of_scope'] ) ); ?></textarea>
						</p>
						<p>
							<label for="tsffe-technologies"><?php esc_html_e( 'Technologies relied upon (optional)', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="text" id="tsffe-technologies" name="technologies" value="<?php echo esc_attr( $data['technologies'] ); ?>" class="large-text" placeholder="HTML, CSS, JavaScript, WAI-ARIA" />
						</p>
					</fieldset>

					<?php /* STEP 4 — feedback + enforcement */ ?>
					<fieldset class="tsffe-step" data-step="4">
						<legend><?php esc_html_e( 'Step 4 — Feedback and enforcement', 'tendforge-statement-forge-for-eaa' ); ?></legend>

						<p>
							<label for="tsffe-contact_email"><?php esc_html_e( 'Feedback contact email', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="email" id="tsffe-contact_email" name="contact_email" value="<?php echo esc_attr( $data['contact_email'] ); ?>" class="regular-text" />
							<span class="tsffe-error" data-error-for="contact_email"></span>
						</p>
						<p>
							<label for="tsffe-feedback_method"><?php esc_html_e( 'Other feedback routes (optional)', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<textarea id="tsffe-feedback_method" name="feedback_method" rows="2" class="large-text" placeholder="<?php esc_attr_e( 'e.g. phone number, contact form URL, postal address', 'tendforge-statement-forge-for-eaa' ); ?>"><?php echo esc_textarea( $data['feedback_method'] ); ?></textarea>
						</p>
						<p>
							<label for="tsffe-enforcement_country"><?php esc_html_e( 'EU country whose enforcement body applies', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<select id="tsffe-enforcement_country" name="enforcement_country">
								<option value=""><?php esc_html_e( '— Select a country —', 'tendforge-statement-forge-for-eaa' ); ?></option>
								<?php foreach ( TSFFE_Bodies::all() as $code => $b ) : ?>
									<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $data['enforcement_country'], $code ); ?>><?php echo esc_html( $b['country'] ); ?></option>
								<?php endforeach; ?>
							</select>
							<span class="tsffe-error" data-error-for="enforcement_country"></span>
						</p>
						<p>
							<label for="tsffe-prepared_date"><?php esc_html_e( 'Prepared date', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="date" id="tsffe-prepared_date" name="prepared_date" value="<?php echo esc_attr( $data['prepared_date'] ); ?>" />
						</p>
						<p>
							<label for="tsffe-last_reviewed_date"><?php esc_html_e( 'Last reviewed date', 'tendforge-statement-forge-for-eaa' ); ?></label>
							<input type="date" id="tsffe-last_reviewed_date" name="last_reviewed_date" value="<?php echo esc_attr( $data['last_reviewed_date'] ); ?>" />
						</p>
					</fieldset>

					<?php /* STEP 5 — review + publish */ ?>
					<fieldset class="tsffe-step" data-step="5">
						<legend><?php esc_html_e( 'Step 5 — Review and publish', 'tendforge-statement-forge-for-eaa' ); ?></legend>
						<p>
							<label>
								<input type="checkbox" id="tsffe-footer_link" name="footer_link" value="1" <?php checked( $footer ); ?> />
								<?php esc_html_e( 'Add an "Accessibility Statement" link to the site footer.', 'tendforge-statement-forge-for-eaa' ); ?>
							</label>
						</p>
						<p class="description"><?php esc_html_e( 'Publishing creates or updates a page at /accessibility-statement. The disclaimer at the foot of the statement cannot be removed.', 'tendforge-statement-forge-for-eaa' ); ?></p>
						<p id="tsffe-publish-result" class="tsffe-publish-result"></p>
					</fieldset>

					<div class="tsffe-actions">
						<button type="button" class="button" id="tsffe-prev"><?php esc_html_e( 'Previous', 'tendforge-statement-forge-for-eaa' ); ?></button>
						<button type="button" class="button button-primary" id="tsffe-next"><?php esc_html_e( 'Next', 'tendforge-statement-forge-for-eaa' ); ?></button>
						<button type="button" class="button button-primary" id="tsffe-publish"><?php self::has_published_page() ? esc_html_e( 'Update statement', 'tendforge-statement-forge-for-eaa' ) : esc_html_e( 'Publish statement', 'tendforge-statement-forge-for-eaa' ); ?></button>
						<button type="button" class="button" id="tsffe-refresh-preview"><?php esc_html_e( 'Refresh preview', 'tendforge-statement-forge-for-eaa' ); ?></button>
					</div>
				</form>

				<aside class="tsffe-preview-wrap" aria-label="<?php esc_attr_e( 'Statement preview', 'tendforge-statement-forge-for-eaa' ); ?>">
					<h2><?php esc_html_e( 'Live preview', 'tendforge-statement-forge-for-eaa' ); ?></h2>
					<div id="tsffe-preview" class="tsffe-preview"></div>
				</aside>
			</div>

			<?php
			/**
			 * Fires at the end of the Tendforge Statement Forge for EAA wizard screen, after the
			 * form and preview but inside the page wrapper. Add-ons (e.g. the Pro
			 * companion) can use this to inject extra UI. Receives the current
			 * (prefilled) statement model.
			 *
			 * @param array<string, mixed> $data Current statement model.
			 */
			do_action( 'tsffe_wizard_after_form', $data );
	}

}
