<?php
/**
 * Setup Wizard Functions
 *
 * Wizard configuration, mapping, and values handling
 *
 * @since   3.0.0
 * @package WC_Affiliate
 */

use WC_Affiliate\Models\Settings;

/**
 * Get setup wizard option value.
 *
 * @param string $page Wizard page key.
 * @param string $section Section key within the page.
 * @param string $key Field key within the section.
 * @param mixed  $default Default value if not found.
 *
 * @return mixed The option value or default.
 */
function wca_get_setup_wizard_option( string $page, string $section = '', string $key = '', $default = '' ) {
	$wizard_values = wca_get_setup_wizard_options( $page );

	if ( empty( $section ) ) {
		return $wizard_values;
	}

	if ( ! isset( $wizard_values[ $section ] ) ) {
		return $default;
	}

	if ( empty( $key ) ) {
		return $wizard_values[ $section ];
	}

	return $wizard_values[ $section ][ $key ] ?? $default;
}

/**
 * Get setup wizard values with field mapping and wizard data merging.
 *
 * @param string $page Optional specific page to get values for.
 *
 * @return array Setup wizard values with merged settings and wizard data.
 */
function wca_get_setup_wizard_options( string $page = '' ): array {
	$values         = array();
	$settings_model = new Settings();
	$field_mapping  = wca_get_setup_wizard_field_mapping();
	$pages          = wca_get_setup_wizard_pages();

	if ( ! empty( $page ) && isset( $pages[ $page ] ) ) {
		// Get values for specific page using field mapping.
		$values = wca_get_setup_wizard_mapped_options( $settings_model, $field_mapping, $page );
	} else {
		// Get all pages.
		foreach ( array_keys( $pages ) as $page_key ) {
			$values[ $page_key ] = wca_get_setup_wizard_mapped_options( $settings_model, $field_mapping, $page_key );
		}
	}

	$wizard_data = $settings_model->get_all_wizard_data();

	if ( $page ) {
		$wizard_data = $wizard_data[ $page ] ?? array();
	}

	// Merge wizard data with mapped values, prioritizing mapped values.
	$merged_data = wca_merge_setup_wizard_data( $wizard_data, $values );

	return apply_filters( 'wc_affiliate_setup_wizard_values', $merged_data, $page );
}

/**
 * Update setup wizard options with validation and field mapping.
 *
 * @param string $page Wizard page key, null for all pages.
 * @param array  $values Values to update.
 * @param array  $pages Setup wizard pages configuration.
 * @param array  $field_mapping Field mapping configuration.
 *
 * @return bool|WP_Error True on success, WP_Error on failure.
 */
function wca_update_setup_wizard_options( string $page, array $values, array $pages, array $field_mapping ) {
	$option_model = new Settings();

	if ( empty( $page ) ) {
		// Save all pages using field mapping.
		$result = wca_update_mapped_wizard_options( $option_model, $field_mapping, $values );
	} else {
		// Save single page using field mapping.
		$result = wca_update_mapped_wizard_options( $option_model, $field_mapping, array( $page => $values ) );
	}

	return apply_filters( 'wc_affiliate_update_setup_wizard_result', $result, $page, $values, $pages, $field_mapping );
}

/**
 * Get mapped values for a wizard page using field mapping
 *
 * @param Settings $settings_model Settings model instance.
 * @param array    $field_mapping Field mapping array.
 * @param string   $page Wizard page key.
 *
 * @return array Mapped values for the page in get_pages() structure
 */
function wca_get_setup_wizard_mapped_options( Settings $settings_model, array $field_mapping, string $page ): array {
	$page_config_data   = wca_get_setup_wizard_pages()[ $page ];
	$page_settings_data = $settings_model->get_option( $page, '', array() );
	$page_wizard_data   = $settings_model->get_wizard_data( $page, '', array() );
	$values             = array();
	$existing_fields    = array();

	// Initialize sections structure.
	if ( isset( $page_config_data['sections'] ) && is_array( $page_config_data['sections'] ) && count( $page_config_data['sections'] ) > 0 ) {
		foreach ( $page_config_data['sections'] as $section_id => $section ) {
			$values[ $section_id ]          = array();
			$existing_fields[ $section_id ] = $section['fields'] ?? array();
		}
	}

	// Initialize tabs structure.
	if ( isset( $page_config_data['tabs'] ) && is_array( $page_config_data['tabs'] ) && count( $page_config_data['tabs'] ) > 0 ) {
		foreach ( $page_config_data['tabs'] as $tab_id => $tab ) {
			// Inline fields.
			if ( isset( $tab['inline_fields'] ) && is_array( $tab['inline_fields'] ) && count( $tab['inline_fields'] ) > 0 ) {
				$values[ $tab_id ]          = array();
				$existing_fields[ $tab_id ] = $tab['inline_fields'];
			}

			// Tab sections.
			if ( isset( $tab['sections'] ) && is_array( $tab['sections'] ) && count( $tab['sections'] ) > 0 ) {
				foreach ( $tab['sections'] as $section_id => $section ) {
					$values[ $tab_id ][ $section_id ]          = array();
					$existing_fields[ $tab_id ][ $section_id ] = $section['fields'];
				}
			}
		}
	}

	// Filter field mappings for this wizard page.
	$page_prefix = $page . '.';
	foreach ( $field_mapping as $wizard_path => $settings_path ) {
		if ( strpos( $wizard_path, $page_prefix ) !== 0 ) {
			continue;
		}

		$settings_data_path = substr( $settings_path, strlen( $page_prefix ) );
		$wizard_data_path   = substr( $wizard_path, strlen( $page_prefix ) );

		$settings_value = wca_get_nested_value( $page_settings_data, $settings_data_path );
		$wizard_value   = wca_get_nested_value( $page_wizard_data, $wizard_data_path );
		$config_value   = wca_get_nested_value( $existing_fields, $wizard_data_path );

		$data_value = $settings_value ?? $wizard_value ?? $config_value['default'] ?? null;

		if ( is_null( $data_value ) ) {
			continue;
		}

		wca_update_nested_value( $values, $wizard_data_path, $data_value );
	}

	return $values;
}

/**
 * Update mapped wizard values to settings.
 *
 * @param Settings $option_model Settings model instance.
 * @param array    $field_mapping Field mapping configuration.
 * @param array    $wizard_values Wizard values to update.
 *
 * @return bool True on success, WP_Error on failure.
 */
function wca_update_mapped_wizard_options( Settings $option_model, array $field_mapping, array $wizard_values ): bool {
	$all_settings = $option_model->get_all_settings();
	foreach ( $wizard_values as $wizard_page => $page_values ) {
		// $page_values is structured as { section_id: { field_id: field_value } }
		foreach ( $page_values as $section_id => $section_values ) {
			foreach ( $section_values as $field_id => $field_value ) {
				// Find the mapping for this field in the flat key-value structure.
				$wizard_key = $wizard_page . '.' . $section_id . '.' . $field_id;
				if ( ! isset( $field_mapping[ $wizard_key ] ) ) {
					continue;
				}

				wca_update_nested_value( $all_settings, $field_mapping[ $wizard_key ], $field_value );
			}

			// Also save to wizard data for consistency.
			$option_model->set_wizard_data( $wizard_page, $section_id, $section_values );
		}
	}

	return $option_model->update_settings( $all_settings );
}

/**
 * Get field mapping between wizard and settings in key-value format.
 * Structure: 'wizard_page.section_id.field_id' => 'settings_page.settings_section.settings_field'
 *
 * @return array Field mapping array.
 */
function wca_get_setup_wizard_field_mapping(): array {
	$default_field_mapping = array(
		// Pages page mappings.
		'pages.dashboard_page.existing_page'               => 'basic.general.dashboard_page',

		// Configuration page mappings.
		'configuration.commission.commission_base'         => 'basic.commission.commission_base',
		'configuration.commission.commission_type'         => 'basic.commission.commission_type',
		'configuration.commission.commission_amount'       => 'basic.commission.commission_amount',
		'configuration.commission.cookie_expiry'           => 'basic.tracking.cookie_expiry_time',
		'configuration.commission.cookie_expiry_unit'      => 'basic.tracking.cookie_expiry_unit',

		// Emails page mappings.
		'emails.admin_emails.affiliate_applied_admin_enable' => 'email.admin.admin_application.admin_application_enable',
		'emails.admin_emails.payout_request_admin_enable'  => 'email.admin.admin_payout_request.admin_payout_request_enable',
		'emails.admin_emails.commission_earned_admin_enable' => 'email.admin.admin_commission.admin_commission_enable',

		'emails.affiliate_emails.affiliate_applied_enable' => 'email.affiliate.affiliate_application.affiliate_email_application_enable',
		'emails.affiliate_emails.affiliate_approved_enable' => 'email.affiliate.approval.affiliate_approved_enable',
		'emails.affiliate_emails.affiliate_rejected_enable' => 'email.affiliate.rejection.affiliate_rejected_enable',
		'emails.affiliate_emails.commission_earned_enable' => 'email.affiliate.affiliate_commission.affiliate_commission_enable',
		'emails.affiliate_emails.payout_processed_enable'  => 'email.affiliate.payout_processed.affiliate_payout_processed_enable',
	);

	return apply_filters( 'wc_affiliate_setup_wizard_field_mapping', $default_field_mapping );
}

/**
 * Get setup wizard pages configuration.
 *
 * @return array Setup wizard pages structure.
 */
function wca_get_setup_wizard_pages(): array {
	static $default_pages;
	if ( ! isset( $default_pages ) ) {
		$default_pages = array(
			'welcome'       => array(
				'id'          => 'welcome',
				'label'       => __( 'Index', 'wc-affiliate' ),
				'icon'        => 'dashicons-admin-home',
				'description' => __( 'Index to WC Affiliate! Let\'s get your affiliate program set up in just a few minutes.', 'wc-affiliate' ),
				'sections'    => array(
					'welcome' => array(
						'id'              => 'welcome',
						'backgroundImage' => WC_AFFILIATE_PLUGIN_URL . 'build/images/welcome-hero.png',
						'fields'          => array(
							'logo'                   => array(
								'id'      => 'logo',
								'src_url' => WC_AFFILIATE_PLUGIN_URL . 'build/images/logo.png',
								'alt'     => __( 'Logo', 'wc-affiliate' ),
							),
							'title'                  => array(
								'id'       => 'title',
								'label'    => __( 'Welcome to WC Affiliate', 'wc-affiliate' ),
								'type'     => 'heading',
								'tag'      => 'h1',
								'default'  => __( 'Welcome to WC Affiliate', 'wc-affiliate' ),
								'attrs'    => array(
									'headingClassName' => 'text-wca-title-gradient py-4 text-[32px] font-semibold',
								),
								'required' => true,
							),
							'description'            => array(
								'id'       => 'description',
								'label'    => __( 'Description', 'wc-affiliate' ),
								'type'     => 'paragraph',
								'default'  => __( 'We\'re thrilled to have you on board! At WC Affiliate, links aren\'t just URLs, they\'re powerful, profit-driving tools. Our platform gives you everything you need to manage, cloak, and optimize your affiliate tasks for maximum conversion', 'wc-affiliate' ),
								'attrs'    => array(
									'paragraphClassName' => 'mx-auto! mt-4 w-178.25 text-center text-base font-normal text-[#2C3033]',
								),
								'required' => true,
							),
							'platform_setup'         => wca_get_platform_setup_field(),
							'getting_started_button' => array(
								'id'     => 'learn_more_button',
								'label'  => __( 'Let\'s get Button', 'wc-affiliate' ),
								'type'   => 'button',
								'action' => 'navigate',
								'value'  => __( 'Let\'s get started!', 'wc-affiliate' ),
								'attrs'  => array(
									'data-navigate-target' => '_self',
									'data-navigate-url'    => '/pages',
									'className'            => 'group text-sm! font-normal rounded-lg px-4 py-2 transition-colors duration-300 ease-in-out flex items-center justify-center cursor-pointer bg-wca-primary hover:bg-[#551999] text-white group h-11.5 w-47 shadow-[0px_6px_27.9px_0px_#D6B2FF]',
									'variant'              => 'primary',
									'fieldContainerClassName' => 'inline-block mr-4',
								),
							),
							'skip_button'            => array(
								'id'     => 'upgrade_buttonlet re',
								'label'  => __( 'Skip Button', 'wc-affiliate' ),
								'type'   => 'button',
								'action' => 'navigate',
								'value'  => __( 'Skip', 'wc-affiliate' ),
								'attrs'  => array(
									'data-navigate-target' => '_self',
									'data-navigate-url'    => '/',
									'className'            => 'h-[48px] w-[204px] bg-[#FFCF5C] border border-[#FFCF5C] rounded-sm text-base font-medium text-[#1C1C1C] hover:bg-[#FFB400] hover:border-[#FFB400] transition-all duration-300',
									'fieldContainerClassName' => 'inline-block',
								),
							),
						),
					),
				),
			),
			'pages'         => array(
				'id'          => 'pages',
				'label'       => __( 'Affiliate Dashboard', 'wc-affiliate' ),
				'icon'        => 'dashicons-admin-page',
				'description' => __( 'Set up the affiliate dashboard page where your affiliates will manage their accounts and view performance.', 'wc-affiliate' ),
				'sections'    => array(
					'dashboard_page' => array(
						'id'     => 'dashboard_page',
						'fields' => array(
							'page_option'    => array(
								'id'       => 'page_option',
								'label'    => __( 'Select Where to Show the Affiliate Dashboard', 'wc-affiliate' ),
								'type'     => 'radio',
								'options'  => array(
									'create'   => __( 'Create new page', 'wc-affiliate' ),
									'existing' => __( 'Use existing page', 'wc-affiliate' ),
								),
								'default'  => 'create',
								'required' => true,
							),
							'existing_page'  => array(
								'id'          => 'existing_page',
								'type'        => 'select',
								'options'     => wca_get_pages_options(),
								'default'     => '',
								'conditional' => array(
									'field' => 'page_option',
									'value' => 'existing',
								),
								'description' => __( 'Select an existing page from the dropdown to host the affiliate dashboard.', 'wc-affiliate' ),
							),
							'new_page_title' => array(
								'id'          => 'new_page_title',
								'label'       => __( 'New page Title', 'wc-affiliate' ),
								'type'        => 'text',
								'default'     => __( 'Affiliate Dashboard', 'wc-affiliate' ),
								'description' => __( 'Use the default page name or change it to create a new page.', 'wc-affiliate' ),
								'conditional' => array(
									'field' => 'page_option',
									'value' => 'create',
								),
							),
							'notice'         => array(
								'id'   => 'notice',
								'type' => 'success',
								'html' => sprintf(
									'<p class="description">%s</p>',
									__( 'You can adjust these settings later in the WC Affiliate Settings page.', 'wc-affiliate' )
								),
							),
						),
					),
				),
			),
			'configuration' => array(
				'id'          => 'configuration',
				'label'       => __( 'Configuration', 'wc-affiliate' ),
				'icon'        => 'dashicons-admin-settings',
				'description' => __( 'Configure commission rates, cookie tracking, and other core affiliate program settings.', 'wc-affiliate' ),
				'sections'    => array(
					'commission' => array(
						'id'     => 'commission',
						'fields' => array(
							'commission_base'    => array(
								'id'          => 'commission_base',
								'label'       => __( 'Commission Base', 'wc-affiliate' ),
								'type'        => 'select',
								'options'     => array(
									'order_total'    => __( 'Order Total', 'wc-affiliate' ),
									'order_subtotal' => __( 'Order Subtotal', 'wc-affiliate' ),
									'product_price'  => __( 'Product Price', 'wc-affiliate' ),
								),
								'default'     => 'product_price',
								'tooltip'     => __( 'Choose how affiliate commissions will be calculated', 'wc-affiliate' ),
								'required'    => true,
								'description' => __( 'The basis on which the commission will be calculated.', 'wc-affiliate' ),
							),
							'commission_type'    => array(
								'id'          => 'commission_type',
								'label'       => __( 'Commission Type', 'wc-affiliate' ),
								'type'        => 'select',
								'options'     => array(
									'percent' => __( 'Percentage', 'wc-affiliate' ),
									'fixed'   => __( 'Fixed Amount', 'wc-affiliate' ),
								),
								'default'     => 'percent',
								'tooltip'     => __( 'Type of commission calculation', 'wc-affiliate' ),
								'required'    => true,
								'description' => __( 'Set the commission amount as a percentage or a fixed amount.', 'wc-affiliate' ),
							),
							'commission_amount'  => array(
								'id'          => 'commission_amount',
								'label'       => __( 'Commission Amount', 'wc-affiliate' ),
								'type'        => 'number',
								'default'     => 10,
								'min'         => 0,
								'step'        => 0.01,
								'tooltip'     => __( 'Commission rate or fixed amount', 'wc-affiliate' ),
								'required'    => true,
								'description' => __( 'Set the commission amount per affiliate referral.', 'wc-affiliate' ),
							),
							'cookie_expiry'      => array(
								'id'          => 'cookie_expiry_time',
								'label'       => __( 'Cookie Expiry', 'wc-affiliate' ),
								'type'        => 'number',
								'default'     => 30,
								'min'         => 1,
								'max'         => 365,
								'tooltip'     => __( 'How long to track visitors after they click an affiliate link', 'wc-affiliate' ),
								'required'    => true,
								'description' => __( ' The number of value after which the referral cookie will be considered expired.', 'wc-affiliate' ),
							),
							'cookie_expiry_unit' => array(
								'id'      => 'cookie_expiry_unit',
								'label'   => __( 'Cookie Expiry Unit', 'wc-affiliate' ),
								'type'    => 'select',
								'options' => array(
									3600    => __( 'Hours', 'wc-affiliate' ),
									86400   => __( 'Days', 'wc-affiliate' ),
									604800  => __( 'Weeks', 'wc-affiliate' ),
									2592000 => __( 'Months', 'wc-affiliate' ),
								),
								'default' => 2592000,
							),
						),
					),
				),
			),
			'emails'        => array(
				'id'          => 'emails',
				'label'       => __( 'Email Settings', 'wc-affiliate' ),
				'icon'        => 'dashicons-email',
				'description' => __( 'Configure email notifications for affiliates and administrators to keep everyone informed.', 'wc-affiliate' ),
				'sections'    => array(
					'admin_emails'     => array(
						'id'          => 'admin_emails',
						'label'       => __( 'Admin Email Notifications', 'wc-affiliate' ),
						'description' => __( 'Choose which notifications administrators should receive', 'wc-affiliate' ),
						'fields'      => array(
							'affiliate_applied_admin_enable' => array(
								'id'      => 'affiliate_applied_admin_enable',
								'label'   => __( 'New affiliate application', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Choose which notifications administrators should receive', 'wc-affiliate' ),
							),
							'payout_request_admin_enable' => array(
								'id'      => 'payout_request_admin_enable',
								'label'   => __( 'Payout request received', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Notify administrators when affiliates request payouts', 'wc-affiliate' ),
							),
							'commission_earned_admin_enable' => array(
								'id'      => 'commission_earned_admin_enable',
								'label'   => __( 'Commission earned', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Notify administrators when affiliates earn commissions', 'wc-affiliate' ),
							),
						),
					),
					'affiliate_emails' => array(
						'id'          => 'affiliate_emails',
						'label'       => __( 'Affiliate Email Notifications', 'wc-affiliate' ),
						'description' => __( 'Choose which notifications affiliates should receive', 'wc-affiliate' ),
						'fields'      => array(
							'affiliate_applied_enable'  => array(
								'id'      => 'affiliate_applied_enable',
								'label'   => __( 'Application confirmation', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Choose which notifications affiliates should receive', 'wc-affiliate' ),
							),
							'affiliate_approved_enable' => array(
								'id'      => 'affiliate_approved_enable',
								'label'   => __( 'Account approved', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Send email when affiliate application is approved', 'wc-affiliate' ),
							),
							'affiliate_rejected_enable' => array(
								'id'      => 'affiliate_rejected_enable',
								'label'   => __( 'Application rejected', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Send email when affiliate application is rejected', 'wc-affiliate' ),
							),
							'commission_earned_enable'  => array(
								'id'      => 'commission_earned_enable',
								'label'   => __( 'Commission earned', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Send email when affiliate earns commission', 'wc-affiliate' ),
							),
							'payout_processed_enable'   => array(
								'id'      => 'payout_processed_enable',
								'label'   => __( 'Payout processed', 'wc-affiliate' ),
								'type'    => 'toggle',
								'default' => 'on',
								'tooltip' => __( 'Send email when affiliate payout is processed', 'wc-affiliate' ),
							),
						),
					),
				),
			),
			'complete'      => array(
				'id'          => 'complete',
				'label'       => __( 'Complete', 'wc-affiliate' ),
				'icon'        => 'dashicons-yes',
				'description' => __( 'WC Affiliate is set up and ready to track referrals, commissions, and payouts.', 'wc-affiliate' ),
				'sections'    => array(
					'cards' => array(
						'id'    => 'cards',
						'cards' => array(
							array(
								'className'     => 'gradient-bg-one',
								'icon'          => 'pro-badge',
								'type'          => 'upgrade-to-pro',
								'title'         => __( 'Upgrade to Pro & Get Exclusive Features', 'wc-affiliate' ),
								'description'   => __( 'Here, there\'s a call to action encouraging users to upgrade to the Pro version of WC Affiliate for additional features that could help give the affiliate program a competitive edge.', 'wc-affiliate' ),
								'button'        => array(
									'label'     => __( 'Upgrade to Pro', 'wc-affiliate' ),
									'url'       => 'https://wcaffiliate.com/pricing/?utm_source=wp+repository&utm_medium=setup+wizard&utm_campaign=upgrade+to+pro',
									'className' => 'gradient-pro-button',
								),
								'is_full_width' => true,
							),
							array(
								'className'   => 'gradient-bg-two',
								'icon'        => 'documentation',
								'type'        => 'read-documentation',
								'title'       => __( 'Read Documentation', 'wc-affiliate' ),
								'description' => __( 'Learn the ins and outs of WC Affiliate and set up your affiliate program exactly how you want it', 'wc-affiliate' ),
								'button'      => array(
									'label'     => __( 'Documentation', 'wc-affiliate' ),
									'url'       => 'https://wcaffiliate.com/docs/',
									'className' => 'text-white hover:text-white focus:text-white flex items-center gap-2 w-max duration-300',
								),
							),
							array(
								'className'   => 'gradient-bg-three',
								'icon'        => 'help',
								'type'        => 'get-support',
								'title'       => __( 'We\'re here to help!', 'wc-affiliate' ),
								'description' => __( 'Got questions or need assistance? Our support team is ready to help you every step of the way. Reach out anytime', 'wc-affiliate' ),
								'button'      => array(
									'label'     => __( 'Get Support', 'wc-affiliate' ),
									'url'       => 'https://help.pluggable.io/new-ticket/',
									'className' => 'text-white hover:text-white focus:text-white flex items-center gap-2 w-max duration-300',
								),
							),
						),
					),
					'crm'   => array(
						'id'          => 'crm',
						'label'       => __( 'Subscribe to WC Affiliate Updates', 'wc-affiliate' ),
						'description' => __( 'Get exclusive tips, updates, and offers delivered to your inbox.', 'wc-affiliate' ),
						'fields'      => array(
							'crm_first_name' => array(
								'id'          => 'crm_first_name',
								'label'       => __( 'First Name', 'wc-affiliate' ),
								'type'        => 'text',
								'default'     => '',
								'placeholder' => __( 'Enter your name', 'wc-affiliate' ),
							),
							'crm_last_name'  => array(
								'id'          => 'crm_last_name',
								'label'       => __( 'Last Name', 'wc-affiliate' ),
								'type'        => 'text',
								'default'     => '',
								'placeholder' => __( 'Enter your name', 'wc-affiliate' ),
							),
							'crm_email'      => array(
								'id'          => 'crm_email',
								'label'       => __( 'Email', 'wc-affiliate' ),
								'type'        => 'email',
								'default'     => '',
								'placeholder' => __( 'Enter your email address', 'wc-affiliate' ),
							),
						),
					),
				),
			),
		);
	}

	return apply_filters( 'wc_affiliate_setup_wizard_pages', $default_pages );
}

/**
 * Merge wizard data with mapped values
 *
 * @param array $wizard_data Wizard data from backup.
 * @param array $mapped_values Mapped values from main settings.
 *
 * @return array Merged data prioritizing mapped values.
 */
function wca_merge_setup_wizard_data( array $wizard_data, array $mapped_values ): array {
	$merged = $mapped_values;

	foreach ( $wizard_data as $page_key => $page_data ) {
		if ( ! isset( $merged[ $page_key ] ) ) {
			$merged[ $page_key ] = $page_data;
			continue;
		}

		if ( ! is_array( $page_data ) ) {
			continue;
		}

		foreach ( $page_data as $section_key => $section_data ) {
			if ( ! isset( $merged[ $page_key ][ $section_key ] ) ) {
				$merged[ $page_key ][ $section_key ] = $section_data;
				continue;
			}

			if ( ! is_array( $section_data ) ) {
				continue;
			}

			foreach ( $section_data as $field_key => $field_value ) {
				// Only add from wizard data if not present in mapped values.
				if ( ! isset( $merged[ $page_key ][ $section_key ][ $field_key ] ) ) {
					$merged[ $page_key ][ $section_key ][ $field_key ] = $field_value;
				}
			}
		}
	}

	return $merged;
}

/**
 * Validate setup wizard settings values
 *
 * @param array  $values Values to validate.
 * @param string $page Wizard page key.
 *
 * @return bool|WP_Error True on success, WP_Error on failure.
 */
function wca_validate_setup_wizard_values( array $values, string $page ) {
	$pages       = wca_get_setup_wizard_pages();
	$page_config = $pages[ $page ];

	// Validate fields in sections: { section_id: { field_id: field_value } }.
	if ( isset( $page_config['sections'] ) ) {
		foreach ( $page_config['sections'] as $section_id => $section ) {
			if ( isset( $section['fields'] ) && isset( $values[ $section_id ] ) ) {
				foreach ( $section['fields'] as $field_key => $field_config ) {
					// Skip validation for conditional fields that are not visible.
					if ( isset( $field_config['conditional'] ) && ! wca_is_wizard_field_visible( $field_config, $values[ $section_id ] ) ) {
						continue;
					}

					$value            = $values[ $section_id ][ $field_key ] ?? null;
					$validation_error = wca_validate_field_value( $value, $field_config );
					if ( is_wp_error( $validation_error ) ) {
						return $validation_error;
					}
				}
			}
		}
	}

	return true;
}

/**
 * Check if setup wizard should be shown.
 *
 * Determines whether to display the setup wizard based on completion status,
 * skip status, and user capabilities. Wizard is hidden once completed, skipped,
 * or for non-admin users.
 *
 * @since 1.0.0
 *
 * @return bool True if wizard should be shown, false otherwise.
 */
function wca_should_show_setup_wizard(): bool {
	// Don't show if setup-wizard is completed.
	if ( get_option( 'wc_affiliate_wizard_completed' ) ) {
		return false;
	}

	// Don't show if setup-wizard is skipped.
	$wizard_settings = wca_get_option( 'wizard', 'skip', array() );
	if ( ! empty( $wizard_settings['skipped'] ) && true === $wizard_settings['skipped'] ) {
		return false;
	}

	return apply_filters( 'wc_affiliate_show_setup_wizard', true );
}

/**
 * Check if a wizard conditional field is visible based on its parent field value
 *
 * @param array $field_config Field configuration.
 * @param array $section_values Section values.
 *
 * @return bool
 */
/**
 * Build the platform_setup field config for the welcome wizard screen.
 *
 * Reads the currently configured platform (woocommerce|easycommerce) from
 * settings and returns a fully-populated field array with live is_installed /
 * is_active flags and all labels specific to that platform.
 *
 * @since 1.0.0
 *
 * @return array Field configuration array.
 */
function wca_get_platform_setup_field(): array {
	// Per-platform metadata — extend this map to support additional platforms.
	$platform_map = array(
		'woocommerce'  => array(
			'slug'            => 'woocommerce',
			'plugin'          => 'woocommerce/woocommerce.php',
			'icon_url'        => 'https://ps.w.org/woocommerce/assets/icon-128x128.png',
			'label'           => __( 'WooCommerce Required', 'wc-affiliate' ),
			'description'     => __( 'WC Affiliate requires WooCommerce to function. Install and activate it to get started.', 'wc-affiliate' ),
			'install_label'   => __( 'Install & Activate WooCommerce', 'wc-affiliate' ),
			'activate_label'  => __( 'Activate WooCommerce', 'wc-affiliate' ),
			'success_message' => __( 'WooCommerce is now active — you\'re all set!', 'wc-affiliate' ),
		),
		'easycommerce' => array(
			'slug'            => 'easycommerce',
			'plugin'          => 'easycommerce/easycommerce.php',
			'icon_url'        => 'https://ps.w.org/easycommerce/assets/icon-128x128.png',
			'label'           => __( 'EasyCommerce Required', 'wc-affiliate' ),
			'description'     => __( 'WC Affiliate requires EasyCommerce to function. Install and activate it to get started.', 'wc-affiliate' ),
			'install_label'   => __( 'Install & Activate EasyCommerce', 'wc-affiliate' ),
			'activate_label'  => __( 'Activate EasyCommerce', 'wc-affiliate' ),
			'success_message' => __( 'EasyCommerce is now active — you\'re all set!', 'wc-affiliate' ),
		),
	);

	$platform    = wca_get_platform();
	$meta        = $platform_map[ $platform ] ?? $platform_map['woocommerce'];
	$plugin_file = $meta['plugin'];
	$active      = (array) get_option( 'active_plugins', array() );

	return array_merge(
		array(
			'id'           => 'platform_setup',
			'type'         => 'platform_installer',
			'is_installed' => file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ),
			'is_active'    => in_array( $plugin_file, $active, true ),
		),
		$meta
	);
}

/**
 * Check if a wizard conditional field is visible based on its parent field value
 *
 * @param array $field_config Field configuration.
 * @param array $section_values Section values.
 *
 * @return bool
 */
function wca_is_wizard_field_visible( array $field_config, array $section_values ): bool {
	if ( ! isset( $field_config['conditional'] ) ) {
		return true;
	}

	$conditional    = $field_config['conditional'];
	$parent_field   = $conditional['field'];
	$required_value = $conditional['value'];

	$parent_value = $section_values[ $parent_field ] ?? null;

	return $parent_value === $required_value;
}
