<?php
/**
 * Setup Wizard — 3-step onboarding for new installs.
 *
 * Step 1: Pixel ID + Access Token
 * Step 2: Event selection
 * Step 3: Done (test connection + link to dashboard)
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined( 'ABSPATH' ) || exit;

// Nonce verification for steps.
$capiflow_step   = isset( $_GET['step'] ) ? absint( $_GET['step'] ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$capiflow_errors = array();

// ── Helper: Check if a valid (decryptable, non-empty) token is stored ────────
$capiflow_has_valid_token = false;
$capiflow_stored_token    = get_option( 'capiflow_access_token', '' );
if ( ! empty( $capiflow_stored_token ) ) {
	$capiflow_decrypted       = Encryption::decrypt( $capiflow_stored_token );
	$capiflow_has_valid_token = ! empty( $capiflow_decrypted ) && strlen( $capiflow_decrypted ) > 10;
}

/**
 * Helper: Force-redirect even if headers are already sent.
 * Outputs a self-contained redirect page (meta + JS + link fallback).
 */
function capiflow_wizard_redirect( string $url ): void {
	if ( ! headers_sent() ) {
		wp_safe_redirect( $url );
		exit;
	}
	// Full HTML page to guarantee redirect despite prior output.
	?><!DOCTYPE html><html><head>
	<meta http-equiv="refresh" content="0;url=<?php echo esc_url( $url ); ?>">
	</head><body>
	<p>Redirecting… <a href="<?php echo esc_url( $url ); ?>">Click here</a> if not redirected.</p>
	</body></html><?php
	exit;
}

// ── Handle Step POST ─────────────────────────────────────────────────────────
if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] && isset( $_POST['capiflow_wizard_nonce'] ) ) {
	if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['capiflow_wizard_nonce'] ) ), 'capiflow_wizard_step_' . $capiflow_step ) ) {
		$capiflow_errors[] = __( 'Security check failed. Please try again.', 'capiflow' );
	} else {
		if ( 1 === $capiflow_step ) {
			$capiflow_pixel_id     = sanitize_text_field( wp_unslash( $_POST['pixel_id'] ?? '' ) );
			$capiflow_access_token = sanitize_text_field( wp_unslash( $_POST['access_token'] ?? '' ) );
			$capiflow_api_version  = sanitize_text_field( wp_unslash( $_POST['graph_api_version'] ?? 'v25.0' ) );

			if ( empty( $capiflow_pixel_id ) ) {
				$capiflow_errors[] = __( 'Pixel ID is required.', 'capiflow' );
			}
			// Token is required on first setup; optional if already saved.
			if ( empty( $capiflow_access_token ) && ! $capiflow_has_valid_token ) {
				$capiflow_errors[] = __( 'Access Token is required.', 'capiflow' );
			}

			if ( empty( $capiflow_errors ) ) {
				update_option( 'capiflow_pixel_id', $capiflow_pixel_id );
				if ( ! empty( $capiflow_access_token ) ) {
					update_option( 'capiflow_access_token', Encryption::encrypt( $capiflow_access_token ) );
				}
				update_option( 'capiflow_graph_api_version', $capiflow_api_version );
				capiflow_wizard_redirect( admin_url( 'admin.php?page=capiflow-setup&step=2' ) );
			}
		} elseif ( 2 === $capiflow_step ) {
			$capiflow_event_keys = array(
				'capiflow_send_purchase',
				'capiflow_send_initiatecheckout',
				'capiflow_send_addpaymentinfo',
				'capiflow_send_addtocart',
				'capiflow_send_viewcontent',
				'capiflow_send_search',
				'capiflow_send_pageview',
			);
			foreach ( $capiflow_event_keys as $capiflow_key ) {
				if ( 'capiflow_send_purchase' === $capiflow_key ) {
					update_option( $capiflow_key, true );
					continue;
				}
				update_option( $capiflow_key, isset( $_POST[ $capiflow_key ] ) ? true : false ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
			}
			// Purchase trigger is now hardcoded (dual-hook: processing + wc-confirmed).
			// Legacy option 'capiflow_purchase_trigger' is no longer saved.

			delete_transient( 'capiflow_activation_redirect' );
			update_option( 'capiflow_wizard_complete', true );

			capiflow_wizard_redirect( admin_url( 'admin.php?page=capiflow-setup&step=3' ) );
		}
	}
}

// Re-compute after possible save above.
if ( ! $capiflow_has_valid_token && ! empty( get_option( 'capiflow_access_token', '' ) ) ) {
	$capiflow_decrypted       = Encryption::decrypt( get_option( 'capiflow_access_token', '' ) );
	$capiflow_has_valid_token = ! empty( $capiflow_decrypted ) && strlen( $capiflow_decrypted ) > 10;
}
?>
<div class="wrap capiflow-wizard-wrap" style="max-width:680px;margin:24px auto;">

	<!-- Progress bar -->
	<div style="display:flex;gap:0;margin-bottom:28px;border-radius:8px;overflow:hidden;">
		<?php
		$capiflow_steps = array(
			1 => __( '1. Pixel Setup', 'capiflow' ),
			2 => __( '2. Events', 'capiflow' ),
			3 => __( '3. Done!', 'capiflow' ),
		);
		foreach ( $capiflow_steps as $capiflow_s => $capiflow_label ) {
			$capiflow_active = $capiflow_s === $capiflow_step;
			$capiflow_done   = $capiflow_s < $capiflow_step;
			$capiflow_bg     = $capiflow_active ? '#2563eb' : ( $capiflow_done ? '#16a34a' : '#e5e7eb' );
			$capiflow_color  = ( $capiflow_active || $capiflow_done ) ? '#fff' : '#6b7280';
			echo '<div style="flex:1;padding:10px;text-align:center;background:' . esc_attr( $capiflow_bg ) . ';color:' . esc_attr( $capiflow_color ) . ';font-size:13px;font-weight:600;">'
				. ( $capiflow_done ? '✓ ' : '' )
				. esc_html( $capiflow_label ) . '</div>';
		}
		?>
	</div>

	<!-- Card -->
	<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:32px;">

		<!-- Header -->
		<div style="margin-bottom:24px;">
			<h1 style="margin:0 0 4px;font-size:22px;color:#111;">
				🚀 <?php esc_html_e( 'Welcome to CapiFlow', 'capiflow' ); ?>
			</h1>
			<p style="margin:0;color:#6b7280;font-size:14px;">
				<?php esc_html_e( 'Complete the setup in 2 minutes to start rescuing lost conversions.', 'capiflow' ); ?>
			</p>
		</div>

		<?php if ( ! empty( $capiflow_errors ) ) : ?>
		<div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:6px;padding:12px 16px;margin-bottom:20px;">
			<?php foreach ( $capiflow_errors as $capiflow_error ) : ?>
				<p style="margin:0;color:#dc2626;font-size:13px;">⚠ <?php echo esc_html( $capiflow_error ); ?></p>
			<?php endforeach; ?>
		</div>
		<?php endif; ?>

		<?php if ( 1 === $capiflow_step ) : ?>
		<!-- ── STEP 1: Pixel Credentials ── -->
		<form method="post">
			<?php wp_nonce_field( 'capiflow_wizard_step_1', 'capiflow_wizard_nonce' ); ?>

			<div style="margin-bottom:18px;">
				<label style="display:block;font-weight:600;font-size:13px;margin-bottom:6px;color:#374151;">
					<?php esc_html_e( 'Meta Pixel ID', 'capiflow' ); ?> <span style="color:#dc2626;">*</span>
				</label>
				<input type="text" name="pixel_id" value="<?php echo esc_attr( get_option( 'capiflow_pixel_id', '' ) ); ?>"
				       placeholder="e.g. 1234567890123"
				       style="width:100%;padding:10px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;" required>
				<p style="margin:4px 0 0;font-size:12px;color:#6b7280;">
					<?php esc_html_e( 'Find this in Meta Events Manager → Data Sources → your Pixel.', 'capiflow' ); ?>
				</p>
			</div>

			<div style="margin-bottom:18px;">
				<label style="display:block;font-weight:600;font-size:13px;margin-bottom:6px;color:#374151;">
					<?php esc_html_e( 'Access Token (CAPI)', 'capiflow' ); ?>
					<?php if ( ! $capiflow_has_valid_token ) : ?><span style="color:#dc2626;">*</span><?php endif; ?>
				</label>
				<textarea name="access_token" rows="3"
				          placeholder="EAA..."
				          style="width:100%;padding:10px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;font-family:monospace;resize:vertical;"
				          autocomplete="off" spellcheck="false" <?php echo $capiflow_has_valid_token ? '' : 'required'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Hardcoded safe string. ?>></textarea>
				<?php if ( $capiflow_has_valid_token ) : ?>
				<p style="margin:4px 0 0;font-size:12px;color:#16a34a;">✓ <?php esc_html_e( 'Token already configured. Leave blank to keep it, or paste a new one to replace.', 'capiflow' ); ?></p>
				<?php endif; ?>
				<p style="margin:4px 0 0;font-size:12px;color:#6b7280;">
					<?php esc_html_e( 'Generate from Meta Events Manager → Settings → Conversions API → Generate Access Token.', 'capiflow' ); ?>
				</p>
			</div>

			<div style="margin-bottom:24px;">
				<label style="display:block;font-weight:600;font-size:13px;margin-bottom:6px;color:#374151;">
					<?php esc_html_e( 'Graph API Version', 'capiflow' ); ?>
				</label>
				<select name="graph_api_version" style="padding:10px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;">
					<option value="v25.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v25.0' ); ?>>v25.0 (Recommended)</option>
					<option value="v24.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v24.0' ); ?>>v24.0</option>
					<option value="v23.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v23.0' ); ?>>v23.0</option>
					<option value="v22.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v22.0' ); ?>>v22.0</option>
					<option value="v21.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v21.0' ); ?>>v21.0</option>
					<option value="v20.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v20.0' ); ?>>v20.0</option>
					<option value="v19.0" <?php selected( get_option( 'capiflow_graph_api_version', 'v25.0' ), 'v19.0' ); ?>>v19.0</option>
				</select>
			</div>

			<button type="submit" class="button button-primary" style="padding:10px 24px;font-size:14px;">
				<?php esc_html_e( 'Continue →', 'capiflow' ); ?>
			</button>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=capiflow-dashboard' ) ); ?>" style="margin-left:12px;font-size:13px;color:#6b7280;">
				<?php esc_html_e( 'Skip for now', 'capiflow' ); ?>
			</a>
		</form>

		<?php elseif ( 2 === $capiflow_step ) : ?>
		<!-- ── STEP 2: Event Selection ── -->
		<form method="post">
			<?php wp_nonce_field( 'capiflow_wizard_step_2', 'capiflow_wizard_nonce' ); ?>

			<p style="font-size:14px;color:#374151;margin-top:0;">
				<?php esc_html_e( 'Select which events to track. All are recommended for maximum attribution.', 'capiflow' ); ?>
			</p>

			<?php
			$capiflow_events = array(
				'capiflow_send_purchase'         => array( 'label' => 'Purchase', 'badge' => 'required', 'desc' => 'Core conversion event' ),
				'capiflow_send_initiatecheckout' => array( 'label' => 'InitiateCheckout', 'badge' => 'recommended', 'desc' => 'Checkout page visit' ),
				'capiflow_send_addpaymentinfo'   => array( 'label' => 'AddPaymentInfo', 'badge' => 'recommended', 'desc' => 'Payment method selected' ),
				'capiflow_send_addtocart'        => array( 'label' => 'AddToCart', 'badge' => 'recommended', 'desc' => 'Add to cart events' ),
				'capiflow_send_viewcontent'      => array( 'label' => 'ViewContent', 'badge' => 'optional', 'desc' => 'Product page views' ),
				'capiflow_send_search'           => array( 'label' => 'Search', 'badge' => 'optional', 'desc' => 'Site search events' ),
				'capiflow_send_pageview'         => array( 'label' => 'PageView', 'badge' => 'optional', 'desc' => 'All page views' ),
			);
			$capiflow_badge_colors = array( 'required' => '#dc2626', 'recommended' => '#2563eb', 'optional' => '#6b7280' );

			foreach ( $capiflow_events as $capiflow_key => $capiflow_event ) :
				$capiflow_checked     = get_option( $capiflow_key, true );
				$capiflow_badge_color = $capiflow_badge_colors[ $capiflow_event['badge'] ];
			?>
			<label style="display:flex;align-items:center;gap:12px;padding:12px;border:1px solid #e5e7eb;border-radius:6px;margin-bottom:8px;cursor:pointer;background:<?php echo $capiflow_checked ? '#f0fdf4' : '#fff'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Hardcoded safe CSS color. ?>">
				<input type="checkbox" name="<?php echo esc_attr( $capiflow_key ); ?>" value="1" <?php checked( $capiflow_checked, true ); ?>
				       style="width:18px;height:18px;">
				<div style="flex:1;">
					<span style="font-weight:600;font-size:14px;color:#111;"><?php echo esc_html( $capiflow_event['label'] ); ?></span>
					<span style="display:inline-block;font-size:10px;font-weight:700;padding:1px 6px;border-radius:20px;background:<?php echo esc_attr( $capiflow_badge_color ); ?>;color:#fff;margin-left:6px;text-transform:uppercase;">
						<?php echo esc_html( $capiflow_event['badge'] ); ?>
					</span>
					<div style="font-size:12px;color:#6b7280;margin-top:2px;"><?php echo esc_html( $capiflow_event['desc'] ); ?></div>
				</div>
			</label>
			<?php endforeach; ?>

			<div style="margin:20px 0 24px;">
				<p style="font-size:13px;color:#6b7280;">
					<?php esc_html_e( 'Purchase event fires automatically on: Processing (online payments) and Confirmed (COD orders).', 'capiflow' ); ?>
				</p>
			</div>

			<button type="submit" class="button button-primary" style="padding:10px 24px;font-size:14px;">
				<?php esc_html_e( 'Finish Setup →', 'capiflow' ); ?>
			</button>
		</form>

		<?php elseif ( 3 === $capiflow_step ) : ?>
		<!-- ── STEP 3: Done ── -->
		<div style="text-align:center;padding:16px 0;">
			<div style="font-size:48px;margin-bottom:12px;">🎉</div>
			<h2 style="margin:0 0 8px;font-size:22px;color:#111;">
				<?php esc_html_e( "You're all set!", 'capiflow' ); ?>
			</h2>
			<p style="color:#6b7280;font-size:14px;max-width:400px;margin:0 auto 24px;">
				<?php esc_html_e( 'CapiFlow is now tracking your WooCommerce orders server-side. Place a test order to verify events in Meta Events Manager.', 'capiflow' ); ?>
			</p>

			<div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap;">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=capiflow-dashboard' ) ); ?>"
				   class="button button-primary" style="padding:10px 20px;font-size:14px;">
					<?php esc_html_e( 'Open Dashboard', 'capiflow' ); ?>
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=capiflow-settings' ) ); ?>"
				   class="button" style="padding:10px 20px;font-size:14px;">
					<?php esc_html_e( 'Settings', 'capiflow' ); ?>
				</a>
				<a href="https://www.facebook.com/events_manager2/" target="_blank" rel="noopener"
				   class="button" style="padding:10px 20px;font-size:14px;">
					<?php esc_html_e( 'Meta Events Manager ↗', 'capiflow' ); ?>
				</a>
			</div>
		</div>
		<?php endif; ?>

	</div><!-- .card -->

</div><!-- .wrap -->
