<?php
/**
 * Livada SEO — Onboarding wizard
 *
 * 4-step welcome page that fires once on first activation. Covers:
 *   1. Business basics (name + city + country + schema type)
 *   2. Modules — keep the recommended defaults or opt out
 *   3. Optional Anthropic API key
 *   4. Run the first audit + jump to the dashboard
 *
 * Each step persists immediately so a closed tab doesn't lose progress.
 * After the final step (or "Skip"), the dismissal flag is set and the
 * user is sent to the dashboard.
 *
 * @package Livada_SEO
 */

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

class Livada_SEO_Onboarding {

	/** Option used both to mark first-activation and to short-circuit subsequent loads. */
	const DONE_OPTION = 'livada_seo_onboarding_done';

	/** Transient set by the activation hook to trigger a redirect on the next admin load. */
	const REDIRECT_TRANSIENT = 'livada_seo_onboarding_redirect';

	// ── Bootstrap ─────────────────────────────────────────────────────────────

	public static function init(): void {
		add_action( 'admin_menu',  [ self::class, 'register_menu' ], 5 );
		add_action( 'admin_init',  [ self::class, 'maybe_redirect' ] );

		// Form handler for each step.
		add_action( 'admin_post_livada_seo_onboarding_step', [ self::class, 'handle_step' ] );
	}

	/**
	 * Called from the activation hook in livada-seo.php on a *new* activation
	 * (no existing settings option). Sets a transient that triggers a redirect
	 * the next time the user lands in admin.
	 */
	public static function flag_first_activation(): void {
		if ( get_option( self::DONE_OPTION ) ) {
			return;
		}
		set_transient( self::REDIRECT_TRANSIENT, 1, 60 );
	}

	public static function register_menu(): void {
		// Hidden sub-menu — accessible only via direct URL or activation redirect.
		add_submenu_page(
			null, // phpcs:ignore WordPress.Security.NonceVerification — no parent slug = hidden
			__( 'Welcome — Livada SEO', 'livada-seo' ),
			__( 'Welcome', 'livada-seo' ),
			'manage_options',
			'livada-seo-welcome',
			[ self::class, 'render_page' ]
		);
	}

	public static function maybe_redirect(): void {
		if ( wp_doing_ajax() || wp_doing_cron() ) {
			return;
		}
		if ( ! get_transient( self::REDIRECT_TRANSIENT ) ) {
			return;
		}
		// Only redirect for users who can see the page.
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		delete_transient( self::REDIRECT_TRANSIENT );

		wp_safe_redirect( admin_url( 'admin.php?page=livada-seo-welcome' ) );
		exit;
	}

	// ── Step handler ──────────────────────────────────────────────────────────

	public static function handle_step(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'livada-seo' ) );
		}

		check_admin_referer( 'livada_seo_onboarding' );

		$step = isset( $_POST['step'] ) ? (int) $_POST['step'] : 1;

		switch ( $step ) {
			case 1:
				self::save_step_1();
				$next = 2;
				break;
			case 2:
				self::save_step_2();
				$next = 3;
				break;
			case 3:
				self::save_step_3();
				$next = 4;
				break;
			case 4:
				// Final: run audit + mark done.
				if ( class_exists( 'Livada_SEO_Site_Audit' ) ) {
					Livada_SEO_Site_Audit::run_audit( true );
				}
				update_option( self::DONE_OPTION, 1, false );

				wp_safe_redirect( admin_url( 'admin.php?page=livada-seo' ) );
				exit;

			default:
				$next = 1;
		}

		// Skip button.
		if ( ! empty( $_POST['livada_skip'] ) ) {
			update_option( self::DONE_OPTION, 1, false );
			wp_safe_redirect( admin_url( 'admin.php?page=livada-seo' ) );
			exit;
		}

		wp_safe_redirect( admin_url( 'admin.php?page=livada-seo-welcome&step=' . (int) $next ) );
		exit;
	}

	private static function save_step_1(): void {
		$name    = sanitize_text_field( wp_unslash( $_POST['name']    ?? '' ) ); // phpcs:ignore
		$city    = sanitize_text_field( wp_unslash( $_POST['city']    ?? '' ) ); // phpcs:ignore
		$country = strtoupper( substr( preg_replace( '/[^A-Za-z]/', '', (string) ( $_POST['country'] ?? 'FR' ) ), 0, 2 ) ); // phpcs:ignore
		$type    = sanitize_text_field( wp_unslash( $_POST['type']    ?? 'LocalBusiness' ) ); // phpcs:ignore

		$allowed = [
			'LocalBusiness', 'Organization', 'Campground', 'LodgingBusiness',
			'Hotel', 'BedAndBreakfast', 'Resort', 'Restaurant', 'Store', 'TouristAttraction',
		];
		if ( ! in_array( $type, $allowed, true ) ) {
			$type = 'LocalBusiness';
		}

		// Persist to the legacy schema_* settings AND seed location 0 so both
		// surfaces stay in sync.
		$existing = get_option( 'livada_seo_settings', [] );
		if ( ! is_array( $existing ) ) {
			$existing = [];
		}
		$existing['schema_name']    = $name;
		$existing['schema_type']    = $type;
		$existing['schema_city']    = $city;
		$existing['schema_country'] = '' !== $country ? $country : 'FR';
		update_option( 'livada_seo_settings', $existing, false );

		if ( '' !== $name ) {
			$locations = (array) get_option( 'livada_seo_locations', [] );
			if ( empty( $locations ) ) {
				$locations[] = [
					'name'    => $name,
					'type'    => $type,
					'city'    => $city,
					'country' => $existing['schema_country'],
				];
				update_option( 'livada_seo_locations', $locations, false );
			}
		}
	}

	private static function save_step_2(): void {
		$selected = isset( $_POST['modules'] ) && is_array( $_POST['modules'] ) // phpcs:ignore
			? array_map( 'sanitize_key', wp_unslash( $_POST['modules'] ) ) // phpcs:ignore
			: [];

		$allowed = [
			'meta', 'sitemap', 'sitemap_html', 'schema', 'opengraph', 'redirects',
			'breadcrumbs', 'analysis', 'robots', 'indexnow', 'toc', 'image_seo',
			'analytics', 'geo', 'aeo', 'site_audit', 'woocommerce', 'og_image',
		];
		$selected = array_values( array_intersect( $selected, $allowed ) );

		$existing = get_option( 'livada_seo_settings', [] );
		if ( ! is_array( $existing ) ) {
			$existing = [];
		}
		$existing['modules'] = $selected;
		update_option( 'livada_seo_settings', $existing, false );
	}

	private static function save_step_3(): void {
		$key_raw = isset( $_POST['anthropic_api_key'] ) ? trim( (string) wp_unslash( $_POST['anthropic_api_key'] ) ) : ''; // phpcs:ignore

		if ( '' === $key_raw ) {
			return; // Skipped — leave existing key untouched.
		}

		$existing = get_option( 'livada_seo_settings', [] );
		if ( ! is_array( $existing ) ) {
			$existing = [];
		}

		if ( class_exists( 'Livada_SEO_Image_Bulk' ) ) {
			$existing['anthropic_api_key'] = Livada_SEO_Image_Bulk::encrypt_key_for_storage( $key_raw );
		} else {
			$existing['anthropic_api_key'] = $key_raw;
		}

		update_option( 'livada_seo_settings', $existing, false );
	}

	// ── Page render ───────────────────────────────────────────────────────────

	public static function render_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'livada-seo' ) );
		}

		$step = isset( $_GET['step'] ) ? max( 1, min( 4, (int) $_GET['step'] ) ) : 1; // phpcs:ignore

		?>
		<div class="wrap livada-seo-wrap" style="max-width:780px;">
			<h1><?php esc_html_e( 'Welcome to Livada SEO', 'livada-seo' ); ?></h1>

			<?php self::render_progress( $step ); ?>

			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<?php wp_nonce_field( 'livada_seo_onboarding' ); ?>
				<input type="hidden" name="action" value="livada_seo_onboarding_step">
				<input type="hidden" name="step"   value="<?php echo (int) $step; ?>">

				<?php
				switch ( $step ) {
					case 1: self::render_step_1(); break;
					case 2: self::render_step_2(); break;
					case 3: self::render_step_3(); break;
					case 4: self::render_step_4(); break;
				}
				?>

				<p style="margin-top:24px; display:flex; gap:8px;">
					<?php if ( $step < 4 ) : ?>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Save & continue', 'livada-seo' ); ?></button>
					<?php else : ?>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Run first audit & finish', 'livada-seo' ); ?></button>
					<?php endif; ?>
					<button type="submit" name="livada_skip" value="1" class="button-link" style="margin-left:auto; color:#646970;">
						<?php esc_html_e( 'Skip wizard', 'livada-seo' ); ?>
					</button>
				</p>
			</form>
		</div>
		<?php
	}

	private static function render_progress( int $current ): void {
		$labels = [
			1 => __( 'Business', 'livada-seo' ),
			2 => __( 'Modules', 'livada-seo' ),
			3 => __( 'AI key',   'livada-seo' ),
			4 => __( 'Audit',    'livada-seo' ),
		];

		echo '<ol class="livada-onb-steps" style="display:flex; gap:12px; list-style:none; padding:0; margin:16px 0 28px;">';
		foreach ( $labels as $i => $label ) {
			$state = $i < $current ? 'done' : ( $i === $current ? 'current' : 'pending' );
			$style = 'flex:1; padding:8px 12px; border-radius:4px; text-align:center;';
			if ( 'done' === $state ) {
				$style .= ' background:#d4f4d8; color:#00471f;';
			} elseif ( 'current' === $state ) {
				$style .= ' background:#2271b1; color:#fff; font-weight:600;';
			} else {
				$style .= ' background:#f0f0f1; color:#646970;';
			}
			echo '<li style="' . esc_attr( $style ) . '">' . (int) $i . '. ' . esc_html( $label ) . '</li>';
		}
		echo '</ol>';
	}

	private static function render_step_1(): void {
		$s    = (array) get_option( 'livada_seo_settings', [] );
		$name = (string) ( $s['schema_name']    ?? '' );
		$city = (string) ( $s['schema_city']    ?? '' );
		$ctry = (string) ( $s['schema_country'] ?? 'FR' );
		$type = (string) ( $s['schema_type']    ?? 'LocalBusiness' );
		?>
		<h2><?php esc_html_e( 'Tell Google who you are', 'livada-seo' ); ?></h2>
		<p class="description">
			<?php esc_html_e( 'These four fields power the LocalBusiness JSON-LD schema and the title templates. You can refine everything later under Schema and Locations.', 'livada-seo' ); ?>
		</p>

		<table class="form-table" role="presentation">
			<tr>
				<th><label for="livada_onb_name"><?php esc_html_e( 'Business name', 'livada-seo' ); ?> <span style="color:#d63638;">*</span></label></th>
				<td><input type="text" id="livada_onb_name" name="name" value="<?php echo esc_attr( $name ); ?>" class="regular-text" required></td>
			</tr>
			<tr>
				<th><label for="livada_onb_type"><?php esc_html_e( 'Business type', 'livada-seo' ); ?></label></th>
				<td>
					<select id="livada_onb_type" name="type">
						<option value="LocalBusiness"<?php selected( $type, 'LocalBusiness' ); ?>>Local Business (generic)</option>
						<option value="Campground"<?php selected( $type, 'Campground' ); ?>>Campground</option>
						<option value="Hotel"<?php selected( $type, 'Hotel' ); ?>>Hotel</option>
						<option value="BedAndBreakfast"<?php selected( $type, 'BedAndBreakfast' ); ?>>Bed & Breakfast</option>
						<option value="Resort"<?php selected( $type, 'Resort' ); ?>>Resort</option>
						<option value="LodgingBusiness"<?php selected( $type, 'LodgingBusiness' ); ?>>Lodging Business</option>
						<option value="Restaurant"<?php selected( $type, 'Restaurant' ); ?>>Restaurant</option>
						<option value="Store"<?php selected( $type, 'Store' ); ?>>Store</option>
						<option value="TouristAttraction"<?php selected( $type, 'TouristAttraction' ); ?>>Tourist Attraction</option>
						<option value="Organization"<?php selected( $type, 'Organization' ); ?>>Organization (non-local)</option>
					</select>
				</td>
			</tr>
			<tr>
				<th><label for="livada_onb_city"><?php esc_html_e( 'City', 'livada-seo' ); ?></label></th>
				<td><input type="text" id="livada_onb_city" name="city" value="<?php echo esc_attr( $city ); ?>" class="regular-text"></td>
			</tr>
			<tr>
				<th><label for="livada_onb_country"><?php esc_html_e( 'Country code', 'livada-seo' ); ?></label></th>
				<td><input type="text" id="livada_onb_country" name="country" value="<?php echo esc_attr( $ctry ); ?>" class="small-text" maxlength="2"></td>
			</tr>
		</table>
		<?php
	}

	private static function render_step_2(): void {
		$s        = (array) get_option( 'livada_seo_settings', [] );
		$enabled  = (array) ( $s['modules'] ?? [] );

		$tiers = [
			__( 'Recommended for everyone', 'livada-seo' ) => [
				'meta'        => __( 'Meta tags',           'livada-seo' ),
				'sitemap'     => __( 'XML sitemap',         'livada-seo' ),
				'schema'      => __( 'Schema.org JSON-LD',  'livada-seo' ),
				'opengraph'   => __( 'Open Graph + Twitter','livada-seo' ),
				'breadcrumbs' => __( 'Breadcrumbs',         'livada-seo' ),
				'analysis'    => __( 'On-page SEO score',   'livada-seo' ),
				'robots'      => __( 'robots.txt',          'livada-seo' ),
				'redirects'   => __( 'Redirect manager',    'livada-seo' ),
				'site_audit'  => __( 'Site Audit',          'livada-seo' ),
			],
			__( 'Modern (AEO + IA)', 'livada-seo' ) => [
				'aeo'         => __( 'AEO / llms.txt',      'livada-seo' ),
				'geo'         => __( 'GEO author signals',  'livada-seo' ),
				'indexnow'    => __( 'IndexNow ping',       'livada-seo' ),
				'og_image'    => __( 'OG image generator',  'livada-seo' ),
			],
			__( 'Optional', 'livada-seo' ) => [
				'sitemap_html' => __( 'HTML sitemap',           'livada-seo' ),
				'toc'          => __( 'Table of contents',     'livada-seo' ),
				'image_seo'    => __( 'Image SEO frontend',     'livada-seo' ),
				'analytics'    => __( 'Analytics injection',    'livada-seo' ),
				'woocommerce'  => __( 'WooCommerce schemas',    'livada-seo' ),
			],
		];
		?>
		<h2><?php esc_html_e( 'Pick the modules you need', 'livada-seo' ); ?></h2>
		<p class="description"><?php esc_html_e( 'Each module is independent. You can toggle any of these later under General Settings.', 'livada-seo' ); ?></p>

		<?php foreach ( $tiers as $heading => $items ) : ?>
			<h3 style="margin-top:18px;"><?php echo esc_html( $heading ); ?></h3>
			<fieldset style="display:grid; grid-template-columns:repeat(2, 1fr); gap:6px 18px;">
				<?php foreach ( $items as $key => $label ) : ?>
					<label>
						<input type="checkbox" name="modules[]" value="<?php echo esc_attr( $key ); ?>" <?php checked( in_array( $key, $enabled, true ) ); ?>>
						<?php echo esc_html( $label ); ?>
					</label>
				<?php endforeach; ?>
			</fieldset>
		<?php endforeach; ?>
		<?php
	}

	private static function render_step_3(): void {
		$has = class_exists( 'Livada_SEO_Image_Bulk' )
			? '' !== Livada_SEO_Image_Bulk::get_anthropic_key()
			: false;
		?>
		<h2><?php esc_html_e( 'Optional: connect Claude for AI suggestions', 'livada-seo' ); ?></h2>
		<p class="description">
			<?php esc_html_e( 'Paste an Anthropic API key to unlock AI alt-text generation, AI title/description/keyword suggestions, and AI rewrite. Skip this step to add the key later under General Settings.', 'livada-seo' ); ?>
		</p>

		<?php if ( $has ) : ?>
			<p style="background:#d4f4d8; padding:10px 14px; border-radius:4px;">
				<?php esc_html_e( 'A key is already stored. You can replace it here, or leave the field blank to keep it.', 'livada-seo' ); ?>
			</p>
		<?php endif; ?>

		<table class="form-table" role="presentation">
			<tr>
				<th><label for="livada_onb_key"><?php esc_html_e( 'Anthropic API key', 'livada-seo' ); ?></label></th>
				<td>
					<input type="password" id="livada_onb_key" name="anthropic_api_key" class="regular-text" autocomplete="off" placeholder="sk-ant-…">
					<p class="description">
						<?php esc_html_e( 'Stored encrypted at rest with AES-256-CBC keyed off your wp-config secrets.', 'livada-seo' ); ?>
					</p>
				</td>
			</tr>
		</table>
		<?php
	}

	private static function render_step_4(): void {
		?>
		<h2><?php esc_html_e( 'Run the first Site Audit', 'livada-seo' ); ?></h2>
		<p class="description">
			<?php esc_html_e( 'Site Audit crawls every published post and grades them against 13 SEO checks. It runs daily on a WP-Cron event after this initial pass.', 'livada-seo' ); ?>
		</p>
		<ul style="list-style:disc; margin-left:24px;">
			<li><?php esc_html_e( 'No outbound HTTP — pure DB introspection.', 'livada-seo' ); ?></li>
			<li><?php esc_html_e( 'Results cached for 6 hours so the dashboard stays cheap.', 'livada-seo' ); ?></li>
			<li><?php esc_html_e( 'Findings exported as CSV from the Site Audit page.', 'livada-seo' ); ?></li>
		</ul>
		<p>
			<?php esc_html_e( 'Click the button below to run the audit and finish setup. You\'ll land on the dashboard.', 'livada-seo' ); ?>
		</p>
		<?php
	}
}
