<?php
/**
 * Onboarding Wizard for Empty Sites
 *
 * Provides a modal wizard that collects initial site information when
 * a user starts a trial on a fresh WordPress site with no content.
 *
 * @package Simple_AI_Auto_Post
 * @since 2.7.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Render the onboarding wizard modal HTML.
 *
 * This should be called on pages where the trial start button appears.
 * The modal is hidden by default and shown via JavaScript when needed.
 */
function saiap_render_onboarding_wizard_modal() {
	$site_name = get_bloginfo( 'name' );
	if ( empty( $site_name ) || 'WordPress' === $site_name ) {
		$site_name = '';
	}

	// Determine if this is a new trial start or editing existing data.
	$is_new_trial = function_exists( 'saiap_can_start_trial' ) && saiap_can_start_trial();
	?>
	<div id="saiap-onboarding-wizard-modal" class="saiap-wizard-modal" style="display: none;" aria-hidden="true">
		<div class="saiap-wizard-modal__backdrop"></div>
		<div class="saiap-wizard-modal__container" role="dialog" aria-modal="true" aria-labelledby="saiap-wizard-title">
			<div class="saiap-wizard-modal__content">
				<button type="button" class="saiap-wizard-modal__back" aria-label="<?php esc_attr_e( 'Go back', 'clearpost-simple-ai-auto-post' ); ?>">
					<span class="dashicons dashicons-arrow-left-alt2"></span>
					<?php esc_html_e( 'Back', 'clearpost-simple-ai-auto-post' ); ?>
				</button>

				<div class="saiap-wizard__header">
					<h2 id="saiap-wizard-title" class="saiap-wizard__title">
						<?php esc_html_e( 'Tell us about your site', 'clearpost-simple-ai-auto-post' ); ?>
					</h2>
					<p class="saiap-wizard__subtitle">
						<?php esc_html_e( 'Help us create content that matches your vision. This takes about 2 minutes.', 'clearpost-simple-ai-auto-post' ); ?>
					</p>
				</div>

				<form id="saiap-onboarding-wizard-form" class="saiap-wizard__form">
					<?php wp_nonce_field( 'saiap_trial_nonce', 'saiap_wizard_nonce' ); ?>

					<!-- Section: Publishing Preference -->
					<div class="saiap-wizard__section">
						<h3 class="saiap-wizard__section-title">
							<?php esc_html_e( 'Publishing preference', 'clearpost-simple-ai-auto-post' ); ?>
							<span class="saiap-wizard__required">*</span>
						</h3>

						<div class="saiap-wizard__field">
							<label class="saiap-wizard__radio-option">
								<input
									type="radio"
									name="review_before_publish"
									value="draft"
									required
								/>
								<span class="saiap-wizard__radio-label">
									<strong><?php esc_html_e( 'Save as drafts for my review', 'clearpost-simple-ai-auto-post' ); ?></strong>
									<span class="saiap-wizard__radio-help">
										<?php esc_html_e( 'Posts land in your WordPress admin as drafts. You click Publish when ready.', 'clearpost-simple-ai-auto-post' ); ?>
									</span>
								</span>
							</label>

							<label class="saiap-wizard__radio-option">
								<input
									type="radio"
									name="review_before_publish"
									value="publish"
									required
								/>
								<span class="saiap-wizard__radio-label">
									<strong><?php esc_html_e( 'Auto-publish to my site', 'clearpost-simple-ai-auto-post' ); ?></strong>
									<span class="saiap-wizard__radio-help">
										<?php esc_html_e( 'Posts go live automatically on their scheduled date.', 'clearpost-simple-ai-auto-post' ); ?>
									</span>
								</span>
							</label>

							<p class="saiap-wizard__help-text">
								<?php esc_html_e( 'You can change this anytime in Settings.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
						</div>
					</div>

					<!-- Section 1: Site Basics -->
					<div class="saiap-wizard__section">
						<h3 class="saiap-wizard__section-title">
							<?php esc_html_e( 'Site Basics', 'clearpost-simple-ai-auto-post' ); ?>
						</h3>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-site-name" class="saiap-wizard__label">
								<?php esc_html_e( 'Site Name', 'clearpost-simple-ai-auto-post' ); ?>
							</label>
							<input
								type="text"
								id="saiap-wizard-site-name"
								name="site_name"
								class="saiap-wizard__input"
								value="<?php echo esc_attr( $site_name ); ?>"
								placeholder="<?php esc_attr_e( 'e.g., TechStartup Blog', 'clearpost-simple-ai-auto-post' ); ?>"
							/>
						</div>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-site-description" class="saiap-wizard__label">
								<?php esc_html_e( "What's your site about?", 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__required">*</span>
							</label>
							<textarea
								id="saiap-wizard-site-description"
								name="site_description"
								class="saiap-wizard__textarea"
								rows="3"
								required
								placeholder="<?php esc_attr_e( 'Describe your site in 2-3 sentences. What do you want to be known for?', 'clearpost-simple-ai-auto-post' ); ?>"
							></textarea>
						</div>
					</div>

					<!-- Section 2: Niche & Audience -->
					<div class="saiap-wizard__section">
						<h3 class="saiap-wizard__section-title">
							<?php esc_html_e( 'Niche & Audience', 'clearpost-simple-ai-auto-post' ); ?>
						</h3>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-niche" class="saiap-wizard__label">
								<?php esc_html_e( 'Niche / Industry', 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__required">*</span>
							</label>
							<input
								type="text"
								id="saiap-wizard-niche"
								name="niche"
								class="saiap-wizard__input"
								required
								placeholder="<?php esc_attr_e( 'e.g., sustainable fashion, B2B SaaS, personal finance', 'clearpost-simple-ai-auto-post' ); ?>"
							/>
						</div>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-target-audience" class="saiap-wizard__label">
								<?php esc_html_e( 'Target Audience', 'clearpost-simple-ai-auto-post' ); ?>
							</label>
							<textarea
								id="saiap-wizard-target-audience"
								name="target_audience"
								class="saiap-wizard__textarea"
								rows="2"
								placeholder="<?php esc_attr_e( 'e.g., small business owners looking to improve their online presence', 'clearpost-simple-ai-auto-post' ); ?>"
							></textarea>
						</div>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-locations" class="saiap-wizard__label">
								<?php esc_html_e( 'Locations', 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__optional"><?php esc_html_e( '(for local SEO)', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
							<p class="saiap-wizard__field-description">
								<?php esc_html_e( 'Enter cities or areas you serve. We\'ll create location-targeted content for each.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
							<div class="saiap-wizard__tags-input" id="saiap-wizard-locations-container">
								<div class="saiap-wizard__tags-list" id="saiap-wizard-locations-list"></div>
								<input
									type="text"
									id="saiap-wizard-locations-input"
									class="saiap-wizard__tags-text-input"
									placeholder="<?php esc_attr_e( 'Type a city and press Enter...', 'clearpost-simple-ai-auto-post' ); ?>"
								/>
							</div>
							<input type="hidden" id="saiap-wizard-locations" name="locations" value="" />
						</div>
					</div>

					<!-- Section 3: Content Direction -->
					<div class="saiap-wizard__section">
						<h3 class="saiap-wizard__section-title">
							<?php esc_html_e( 'Content Direction', 'clearpost-simple-ai-auto-post' ); ?>
						</h3>

						<div class="saiap-wizard__field">
							<label for="saiap-wizard-seed-topics" class="saiap-wizard__label">
								<?php esc_html_e( 'Seed Topics', 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__required">*</span>
								<span class="saiap-wizard__hint"><?php esc_html_e( '(minimum 3)', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
							<p class="saiap-wizard__field-description">
								<?php esc_html_e( 'Enter topics you want to write about. Press Enter or comma to add each topic.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
							<div class="saiap-wizard__tags-input" id="saiap-wizard-seed-topics-container">
								<div class="saiap-wizard__tags-list" id="saiap-wizard-seed-topics-list"></div>
								<input
									type="text"
									id="saiap-wizard-seed-topics-input"
									class="saiap-wizard__tags-text-input"
									placeholder="<?php esc_attr_e( 'Type a topic and press Enter...', 'clearpost-simple-ai-auto-post' ); ?>"
								/>
							</div>
							<input type="hidden" id="saiap-wizard-seed-topics" name="seed_topics" value="" />
						</div>

						<div class="saiap-wizard__field">
							<label class="saiap-wizard__label">
								<?php esc_html_e( 'Competitor URLs', 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__optional"><?php esc_html_e( '(optional)', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
							<p class="saiap-wizard__field-description">
								<?php esc_html_e( 'Add URLs of sites you admire or compete with. We\'ll use them for inspiration.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
							<div id="saiap-wizard-competitor-urls" class="saiap-wizard__repeater">
								<div class="saiap-wizard__repeater-item">
									<input
										type="url"
										name="competitor_urls[]"
										class="saiap-wizard__input saiap-wizard__repeater-input"
										placeholder="<?php esc_attr_e( 'https://example.com', 'clearpost-simple-ai-auto-post' ); ?>"
									/>
									<button type="button" class="saiap-wizard__repeater-remove" aria-label="<?php esc_attr_e( 'Remove', 'clearpost-simple-ai-auto-post' ); ?>" style="display: none;">
										<span class="dashicons dashicons-no-alt"></span>
									</button>
								</div>
							</div>
							<button type="button" id="saiap-wizard-add-competitor" class="saiap-wizard__add-btn">
								<span class="dashicons dashicons-plus-alt2"></span>
								<?php esc_html_e( 'Add another URL', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>

						<div class="saiap-wizard__field">
							<label class="saiap-wizard__label">
								<?php esc_html_e( 'Example Posts', 'clearpost-simple-ai-auto-post' ); ?>
								<span class="saiap-wizard__optional"><?php esc_html_e( '(optional)', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
							<p class="saiap-wizard__field-description">
								<?php esc_html_e( 'Paste URLs of blog posts you like — we\'ll match the style.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
							<div id="saiap-wizard-example-posts" class="saiap-wizard__repeater">
								<div class="saiap-wizard__repeater-item">
									<input
										type="url"
										name="example_posts[]"
										class="saiap-wizard__input saiap-wizard__repeater-input"
										placeholder="<?php esc_attr_e( 'https://yourblog.com/best-post', 'clearpost-simple-ai-auto-post' ); ?>"
									/>
									<button type="button" class="saiap-wizard__repeater-remove" aria-label="<?php esc_attr_e( 'Remove', 'clearpost-simple-ai-auto-post' ); ?>" style="display: none;">
										<span class="dashicons dashicons-no-alt"></span>
									</button>
								</div>
							</div>
							<button type="button" id="saiap-wizard-add-example-post" class="saiap-wizard__add-btn">
								<span class="dashicons dashicons-plus-alt2"></span>
								<?php esc_html_e( 'Add another URL', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>
					</div>

					<!-- Submit -->
					<div class="saiap-wizard__actions">
						<button type="submit" id="saiap-wizard-submit" class="button button-primary button-hero">
							<?php
							if ( $is_new_trial ) {
								esc_html_e( 'Start My Trial', 'clearpost-simple-ai-auto-post' );
							} else {
								esc_html_e( 'Save', 'clearpost-simple-ai-auto-post' );
							}
							?>
						</button>
						<?php if ( $is_new_trial ) : ?>
						<p class="saiap-wizard__footnote">
							<?php esc_html_e( 'No credit card required. Cancel anytime.', 'clearpost-simple-ai-auto-post' ); ?>
						</p>
						<?php endif; ?>
					</div>
				</form>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Check if the wizard might be needed for this user.
 *
 * Returns true if:
 * - User can start a trial (hasn't started one yet), OR
 * - User has an active trial and hasn't completed wizard yet
 *
 * @return bool
 */
function saiap_wizard_might_be_needed() {
	// Can start a trial - wizard may be needed.
	if ( function_exists( 'saiap_can_start_trial' ) && saiap_can_start_trial() ) {
		return true;
	}

	// Premium users need wizard for editing business info or initial setup.
	if ( function_exists( 'saiap_get_user_scenario' ) ) {
		$scenario = saiap_get_user_scenario();
		if ( 'active_trial' === $scenario || 'paid' === $scenario ) {
			// Premium users always need wizard available for editing.
			return true;
		}
	}

	return false;
}

/**
 * Enqueue wizard assets on pages where trial button appears.
 *
 * @param string $hook_suffix The current admin page hook suffix.
 */
function saiap_enqueue_wizard_assets( $hook_suffix ) {
	// Load on plugin pages or Dashboard (where ClearPost widget appears).
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$is_plugin_page = isset( $_GET['page'] ) && 'saiap' === sanitize_text_field( wp_unslash( $_GET['page'] ) );
	$is_dashboard   = 'index.php' === $hook_suffix;

	if ( ! is_admin() || ( ! $is_plugin_page && ! $is_dashboard ) ) {
		return;
	}

	// Load wizard assets if the wizard might be needed.
	if ( ! saiap_wizard_might_be_needed() ) {
		return;
	}

	wp_enqueue_style(
		'saiap-onboarding-wizard',
		plugins_url( '../assets/css/onboarding-wizard.css', __FILE__ ),
		array(),
		defined( 'SAIAP_VERSION' ) ? SAIAP_VERSION : '1.0.0'
	);

	wp_enqueue_script(
		'saiap-onboarding-wizard',
		plugins_url( '../assets/js/onboarding-wizard.js', __FILE__ ),
		array( 'jquery' ),
		defined( 'SAIAP_VERSION' ) ? SAIAP_VERSION : '1.0.0',
		true
	);

	// Determine if this is a new trial start for JS strings.
	$is_new_trial_for_js = function_exists( 'saiap_can_start_trial' ) && saiap_can_start_trial();

	wp_localize_script(
		'saiap-onboarding-wizard',
		'saiapWizard',
		array(
			'ajaxurl'    => admin_url( 'admin-ajax.php' ),
			'nonce'      => wp_create_nonce( 'saiap_trial_nonce' ),
			'adminEmail' => get_option( 'admin_email', '' ),
			'isNewTrial' => $is_new_trial_for_js,
			'strings'    => array(
				'submitting'       => $is_new_trial_for_js
					? __( 'Starting trial...', 'clearpost-simple-ai-auto-post' )
					: __( 'Saving...', 'clearpost-simple-ai-auto-post' ),
				'error'            => __( 'Something went wrong. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'minTopics'        => __( 'Please add at least 3 seed topics.', 'clearpost-simple-ai-auto-post' ),
				'invalidUrl'       => __( 'Please enter a valid URL.', 'clearpost-simple-ai-auto-post' ),
				'duplicateTopic'   => __( 'This topic has already been added.', 'clearpost-simple-ai-auto-post' ),
				'choosePublishing' => __( 'Please choose a publishing preference.', 'clearpost-simple-ai-auto-post' ),
			),
			'redirectUrl' => admin_url( 'admin.php?page=saiap&tab=dashboard&trial_started=1&gsc_prompt=1' ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_wizard_assets' );

/**
 * Output wizard modal HTML in admin footer.
 */
function saiap_output_wizard_modal() {
	// Only output on plugin pages or Dashboard (where ClearPost widget appears).
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$is_plugin_page = isset( $_GET['page'] ) && 'saiap' === sanitize_text_field( wp_unslash( $_GET['page'] ) );
	$screen         = get_current_screen();
	$is_dashboard   = $screen && 'dashboard' === $screen->id;

	if ( ! is_admin() || ( ! $is_plugin_page && ! $is_dashboard ) ) {
		return;
	}

	// Only output if wizard might be needed.
	if ( ! saiap_wizard_might_be_needed() ) {
		return;
	}

	saiap_render_onboarding_wizard_modal();
}
add_action( 'admin_footer', 'saiap_output_wizard_modal' );
