<?php
/**
 * Marketplace Stepper View
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/views/src/common/pages/supplier/apps
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Views\Src\Common\Pages\Supplier\Apps;

// Explicitly require the interface files.
require_once dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'authorization' . DIRECTORY_SEPARATOR . 'interface-authorization-view.php';
require_once dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'attribute-mapping' . DIRECTORY_SEPARATOR . 'interface-mapping-view.php';
require_once dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'sync-settings' . DIRECTORY_SEPARATOR . 'interface-sync-settings-view.php';

use MOMCS_Sync\Views\Src\Common\Pages\Supplier\Authorization\Authorization_View_Interface;
use MOMCS_Sync\Views\Src\Common\Pages\Supplier\Attribute_Mapping\Mapping_View_Interface;
use MOMCS_Sync\Views\Src\Common\Pages\Supplier\Sync_Settings\Sync_Settings_View_Interface;

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

/**
 * Class for rendering the marketplace stepper view.
 */
class Marketplace_Stepper_View {

	/**
	 * Authorization view.
	 *
	 * @var Authorization_View_Interface
	 */
	private $authorization_view;

	/**
	 * Mapping view.
	 *
	 * @var Mapping_View_Interface
	 */
	private $mapping_view;

	/**
	 * Sync Settings view.
	 *
	 * @var Sync_Settings_View_Interface
	 */
	private $sync_settings_view;

	/**
	 * Current step.
	 *
	 * @var int
	 */
	private $current_step;

	/**
	 * Marketplace name.
	 *
	 * @var string
	 */
	private $marketplace_name;

	/**
	 * Constructor.
	 *
	 * @param Authorization_View_Interface $authorization_view Authorization view.
	 * @param Mapping_View_Interface       $mapping_view       Mapping view.
	 * @param Sync_Settings_View_Interface $sync_settings_view Sync Settings view.
	 * @param string                       $marketplace_name   Marketplace name.
	 * @param int|null                     $current_step       Optional current step override.
	 */
	public function __construct(
		Authorization_View_Interface $authorization_view,
		Mapping_View_Interface $mapping_view,
		Sync_Settings_View_Interface $sync_settings_view,
		string $marketplace_name,
		?int $current_step = null
	) {
		$this->authorization_view = $authorization_view;
		$this->mapping_view       = $mapping_view;
		$this->sync_settings_view = $sync_settings_view;
		$this->marketplace_name   = $marketplace_name;

		// Use provided step if available, otherwise determine from database.
		if ( null !== $current_step && $current_step > 0 ) {
			// Clamp provided step to the 4-step flow range.
			$this->current_step = max( 1, min( 4, (int) $current_step ) );
		} else {
			$this->current_step = $this->determine_current_step();
		}
	}

	/**
	 * Determine the current step based on saved progress.
	 *
	 * @return int Current step (1-4).
	 */
	private function determine_current_step() {
		// Initialize the model.
		$multichannels_model = new \MOMCS_Sync\Includes\Common\Models\Multichannels_Model();

		// Try to get UUID from URL parameter for multi-channel support.
		$channel_uuid = \MOMCS_Sync\Includes\Common\Utils\Utils::get_current_page_parameter_value( 'uuid', '' );
		
		$current_step = 1;
		
		if ( ! empty( $channel_uuid ) ) {
			// Get step from specific channel by UUID.
			$current_step = (int) $multichannels_model->get_current_step( $channel_uuid );
		} else {
			// Fallback to marketplace-based lookup if no UUID (legacy behavior).
			$marketplace_slug = strtolower( $this->marketplace_name );
			$current_step     = (int) $multichannels_model->get_marketplace_current_step( $marketplace_slug );
		}

		// Clamp to the 4-step flow range.
		if ( $current_step < 1 ) {
			return 1;
		}
		if ( $current_step > 4 ) {
			return 4;
		}
		return $current_step;
	}

	/**
	 * Render the stepper view.
	 *
	 * @return void
	 */
	public function render() {
		$marketplace_slug = strtolower( $this->marketplace_name );

		// Initialize the model.
		$multichannels_model = new \MOMCS_Sync\Includes\Common\Models\Multichannels_Model();

		// Get channel UUID from URL parameter (required for multi-channel support).
		// This ensures we always operate on the specific channel the user is configuring.
		$channel_uuid = \MOMCS_Sync\Includes\Common\Utils\Utils::get_current_page_parameter_value( 'uuid', '' );
		
		// Validate that the channel exists and matches the expected marketplace.
		if ( ! empty( $channel_uuid ) ) {
			$channel = $multichannels_model->get_channel_by_uuid( $channel_uuid );
			if ( ! $channel || strtolower( $channel['marketplace'] ?? '' ) !== $marketplace_slug ) {
				// UUID is invalid or doesn't match marketplace - clear it.
				$channel_uuid = '';
			}
		}

		?>
		<div class="momcs-marketplace-stepper-container">
			<div class="momcs-marketplace-stepper">
				<!-- Step 1 -->
				<div class="momcs-stepper-step <?php echo $this->current_step >= 1 ? 'active' : ''; ?> <?php echo $this->current_step > 1 ? 'completed' : ''; ?>">
					<div class="momcs-stepper-circle">
						<?php if ( $this->current_step > 1 ) : ?>
							<span class="dashicons dashicons-yes"></span>
						<?php else : ?>
							<span>1</span>
						<?php endif; ?>
					</div>
					<div class="momcs-stepper-label"><?php esc_html_e( 'Authorization', 'multi-channel-for-woocommerce' ); ?></div>
				</div>
				<div class="momcs-stepper-line <?php echo $this->current_step > 1 ? 'completed' : ''; ?>"></div>

				<!-- Step 2 -->
				<div class="momcs-stepper-step <?php echo $this->current_step >= 2 ? 'active' : ''; ?> <?php echo $this->current_step > 2 ? 'completed' : ''; ?>">
					<div class="momcs-stepper-circle">
						<?php if ( $this->current_step > 2 ) : ?>
							<span class="dashicons dashicons-yes"></span>
						<?php else : ?>
							<span>2</span>
						<?php endif; ?>
					</div>
					<div class="momcs-stepper-label"><?php esc_html_e( 'Field Mapping', 'multi-channel-for-woocommerce' ); ?></div>
				</div>
				<div class="momcs-stepper-line <?php echo $this->current_step > 2 ? 'completed' : ''; ?>"></div>

				<!-- Step 3 -->
				<div class="momcs-stepper-step <?php echo $this->current_step >= 3 ? 'active' : ''; ?> <?php echo $this->current_step > 3 ? 'completed' : ''; ?>">
					<div class="momcs-stepper-circle">
						<?php if ( $this->current_step > 3 ) : ?>
							<span class="dashicons dashicons-yes"></span>
						<?php else : ?>
							<span>3</span>
						<?php endif; ?>
					</div>
					<div class="momcs-stepper-label"><?php esc_html_e( 'Sync Configuration', 'multi-channel-for-woocommerce' ); ?></div>
				</div>
				<div class="momcs-stepper-line <?php echo $this->current_step > 3 ? 'completed' : ''; ?>"></div>

				<!-- Step 4 -->
				<div class="momcs-stepper-step <?php echo $this->current_step >= 4 ? 'active' : ''; ?> <?php echo $this->current_step > 4 ? 'completed' : ''; ?>">
					<div class="momcs-stepper-circle">
						<?php if ( $this->current_step > 4 ) : ?>
							<span class="dashicons dashicons-yes"></span>
						<?php else : ?>
							<span>4</span>
						<?php endif; ?>
					</div>
					<div class="momcs-stepper-label"><?php esc_html_e( 'Complete', 'multi-channel-for-woocommerce' ); ?></div>
				</div>
			</div>
			
			<div class="momcs-marketplace-stepper-content">
				<?php if ( 1 === $this->current_step ) : ?>
					<div class="momcs-stepper-content-step momcs-stepper-content-step-1 active">
						<?php $this->authorization_view->render(); ?>
					</div>
				<?php elseif ( 2 === $this->current_step ) : ?>
					<div class="momcs-stepper-content-step momcs-stepper-content-step-2 active">
						<?php $this->mapping_view->render(); ?>
					</div>
				<?php elseif ( 3 === $this->current_step ) : ?>
					<div class="momcs-stepper-content-step momcs-stepper-content-step-3 active">
						<?php $this->sync_settings_view->render(); ?>
					</div>
				<?php elseif ( 4 === $this->current_step ) : ?>
					<div class="momcs-stepper-content-step momcs-stepper-content-step-4 active">
						<div class="momcs-stepper-complete">
							<div class="momcs-stepper-complete-icon">
								<span class="dashicons dashicons-yes-alt"></span>
							</div>
							<h2>
							<?php
							/* translators: %s: Marketplace name */
							echo esc_html( sprintf( __( '%s Integration Complete', 'multi-channel-for-woocommerce' ), $this->marketplace_name ) );
							?>
							</h2>
							<p>
							<?php
							/* translators: %s: Marketplace name */
							echo esc_html( sprintf( __( 'Your WooCommerce store is now connected to %s. You can now start syncing your products.', 'multi-channel-for-woocommerce' ), $this->marketplace_name ) );
							?>
							</p>
							<div style="display: flex; justify-content: center; gap: 15px; margin-top: 20px;">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-dashboard' ) ); ?>" class="button button-primary">
								<?php esc_html_e( 'Go to Dashboard', 'multi-channel-for-woocommerce' ); ?>
							</a>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-products' ) ); ?>" class="button button-primary">
									<?php esc_html_e( 'Go to Products', 'multi-channel-for-woocommerce' ); ?>
								</a>
							</div>
						</div>
					</div>
				<?php endif; ?>
			</div>
			
			<div class="momcs-marketplace-stepper-navigation">				
				<?php if ( $this->current_step > 2 && $this->current_step <= 4 ) : ?>
					<button id="momcs-stepper-prev" class="button"><?php esc_html_e( 'Previous', 'multi-channel-for-woocommerce' ); ?></button>
				<?php endif; ?>

				<?php if ( $this->current_step < 4 ) : ?>
					<button id="momcs-stepper-next" class="button button-primary"
						<?php
						if ( ( ! $channel_uuid ) ) {
							echo 'disabled';
						}
						?>
					>
						<?php
						if ( 2 === $this->current_step || 3 === $this->current_step ) {
							esc_html_e( 'Save and Next', 'multi-channel-for-woocommerce' );
						} else {
							esc_html_e( 'Next', 'multi-channel-for-woocommerce' );
						}
						?>
					</button>
				<?php endif; ?>
		</div>
		</div>
				
		<?php
		// Enqueue extracted stepper script.
		wp_enqueue_script(
			'momcs-marketplace-stepper',
			MOMCS_PLUGIN_URL . 'assets/js/marketplace-stepper.js',
			array( 'jquery' ),
			defined( 'MOMCS_VERSION' ) ? MOMCS_VERSION : '1.0.0',
			true
		);

		wp_localize_script(
			'momcs-marketplace-stepper',
			'momcs_marketplaceStepperConfig',
			array(
				'currentStep' => esc_js( $this->current_step ),
				'marketplace' => esc_js( strtolower( $this->marketplace_name ) ),
				'channelUuid' => esc_js( $channel_uuid ),
				'nonces'      => array(
					'saveMapping' => wp_create_nonce( 'momcs_sync_save_unified_mapping_nonce' ),
					'updateStep'  => wp_create_nonce( 'momcs_sync_update_step_nonce' ),
					'saveSyncSettings' => ( \MOMCS_Sync\Includes\Common\Constants\Plugin_Constants::PLAN_NAME === 'premium' ) ? wp_create_nonce( 'momcs_sync_save_sync_settings_nonce' ) : '',
				),
				'strings'     => array(
					'loading'             => esc_html__( 'Loading...', 'multi-channel-for-woocommerce' ),
					'saving'              => esc_html__( 'Saving...', 'multi-channel-for-woocommerce' ),
					'validating'          => esc_html__( 'Validating...', 'multi-channel-for-woocommerce' ),
					'fixValidationErrors' => esc_html__( 'Please fix all mapping validation errors before proceeding to the next step.', 'multi-channel-for-woocommerce' ),
					'errorSaveMappings'   => esc_html__( 'Error saving mappings: ', 'multi-channel-for-woocommerce' ),
					'unknownError'        => esc_html__( 'Unknown error', 'multi-channel-for-woocommerce' ),
					'errorValidating'     => esc_html__( 'Error validating mapping data. Please check your form inputs and try again.', 'multi-channel-for-woocommerce' ),
					'saveAndNext'         => esc_html__( 'Save and Next', 'multi-channel-for-woocommerce' ),
					'next'                => esc_html__( 'Next', 'multi-channel-for-woocommerce' ),
					'errorSaveSyncSettings' => esc_html__( 'Error saving sync settings: ', 'multi-channel-for-woocommerce' ),
				),
				'premiumEnabled' => ( \MOMCS_Sync\Includes\Common\Constants\Plugin_Constants::PLAN_NAME === 'premium' ),
			)
		);

		// Provide channel UUID and nonce to the sync settings script so it can preload saved settings.
		wp_localize_script(
			'momcs-sync-settings',
			'momcs_sync_settings',
			array(
				'ajax_url'       => admin_url( 'admin-ajax.php' ),
				'nonce_get_sync' => wp_create_nonce( 'momcs_sync_get_sync_settings_nonce' ),
				'channel_uuid'   => esc_js( $channel_uuid ),
			)
		);
		?>
		<?php
	}
}
