<?php
/**
 * Dashboard Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers;

use MOMCS_Sync\Views\Src\Common\Pages\Supplier\Apps\Marketplace_View_Factory;
use MOMCS_Sync\Views\Src\Common\Components\Header_View;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Utils\Utils;

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

/**
 * Controller class for the dashboard.
 */
class Dashboard_Controller {
	// No constructor or properties – thin static controller per blueprint.

	/**
	 * Register admin menu pages.
	 *
	 * @return void
	 */
	public function register_menu_pages() {
		// Main menu page.
		add_menu_page(
			__( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ),
			__( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-dashboard',
			array( $this, 'render_dashboard' ),
			MOMCS_PLUGIN_URL . 'assets/images/miniorange-menu.png'
		);

		// Dashboard submenu page.
		add_submenu_page(
			'momcs-sync-dashboard',
			__( 'Dashboard', 'multi-channel-for-woocommerce' ),
			__( 'Dashboard', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-dashboard',
			array( $this, 'render_dashboard' )
		);

		// Order Sync submenu page.
		add_submenu_page(
			'momcs-sync-dashboard',
			__( 'Order Sync', 'multi-channel-for-woocommerce' ),
			__( 'Orders', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-orders',
			array( $this, 'render_order_sync' ),
			2
		);

		// Sync Audits submenu page.
		add_submenu_page(
			'momcs-sync-dashboard',
			__( 'Sync Audits', 'multi-channel-for-woocommerce' ),
			__( 'Sync Audits', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-queue',
			array( $this, 'render_sync_queue' )
		);

		// Products submenu page.
		$products_hook = add_submenu_page(
			'momcs-sync-dashboard',
			__( 'Products', 'multi-channel-for-woocommerce' ),
			__( 'Products', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-products',
			array( $this, 'render_product_sync' )
		);

		// Account (miniOrange) submenu page.
		add_submenu_page(
			'momcs-sync-dashboard',
			__( 'Account', 'multi-channel-for-woocommerce' ),
			__( 'Account', 'multi-channel-for-woocommerce' ),
			'manage_woocommerce',
			'momcs-sync-account',
			array( $this, 'render_account_page' )
		);

		// Removed unused migrations AJAX hook registration.
	}


	/**
	 * Enqueue scripts and styles.
	 *
	 * @param string $hook The current admin page.
	 * @return void
	 */
	public function enqueue_scripts( $hook ) {
		if (
			false === strpos( $hook, 'momcs-sync' ) &&
			false === strpos( $hook, 'momcs-sync-products' ) &&
			false === strpos( $hook, 'momcs-sync-queue' )
		) {
			return;
		}

		wp_enqueue_style( 'momcs-sync-admin', MOMCS_PLUGIN_URL . 'assets/css/admin.css', array(), MOMCS_VERSION );
		wp_enqueue_script( 'momcs-sync-admin', MOMCS_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), MOMCS_VERSION, true );

		// Contact Us script is registered/enqueued via footer hook with localization.

		// Add nonce and AJAX URL to JavaScript.
		wp_localize_script(
			'momcs-sync-admin',
			'momcs_sync_params',
			array(
				'ajaxurl'   => admin_url( 'admin-ajax.php' ),
				'nonce'     => wp_create_nonce( Plugin_Constants::NONCE_MAIN ),
				'isPremium' => Utils::is_premium_plan(),
			)
		);

		// Add additional localization for admin.js functionality.
		wp_localize_script(
			'momcs-sync-admin',
			'momcsAmazonSync',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( Plugin_Constants::NONCE_MAIN ),
				'isPremium' => Utils::is_premium_plan(),
				'strings' => array(
					'no_action'           => __( 'Please select an action.', 'multi-channel-for-woocommerce' ),
					'no_products'         => __( 'Please select at least one product.', 'multi-channel-for-woocommerce' ),
					'sync_started_notice' => __( 'Sync has started. Please go to Sync Audits to view the status.', 'multi-channel-for-woocommerce' ),
				),
			)
		);

		if ( false !== strpos( $hook, 'momcs-sync-products' ) ) {
			wp_enqueue_style( 'momcs-sync-product-sync', MOMCS_PLUGIN_URL . 'assets/css/product-sync.css', array( 'momcs-sync-admin' ), MOMCS_VERSION );
			wp_enqueue_script( 'momcs-sync-product-sync', MOMCS_PLUGIN_URL . 'assets/js/product-sync.js', array( 'jquery' ), MOMCS_VERSION, true );
		}
	}

	/**
	 * Render the dashboard page.
	 *
	 * @return void
	 */
	public function render_dashboard() {
		$tab         = Utils::get_current_page_parameter_value( 'tab', 'dashboard' );
		$marketplace = Utils::get_current_page_parameter_value( 'marketplace', '' );

		?>
		<div class="wrap momcs-sync-wrap">
			<h1 class="screen-reader-text"><?php esc_html_e( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ); ?></h1>
			<?php $this->render_header( $tab ); ?>

			<div class="momcs-sync-content">
				<?php
				switch ( $tab ) {
					case 'connect':
						// Allow connect tab access for initial setup or editing.
						if ( ! empty( $marketplace ) && ( Utils::get_current_page_parameter_value( 'step', '' ) || Utils::get_current_page_parameter_value( 'uuid', '' ) || Utils::get_current_page_parameter_value( 'config_tab', '' ) ) ) {
							$this->render_connect_tab( $marketplace );
						} else {
							// Redirect to dashboard if connect tab is accessed directly.
							wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-dashboard' ) );
							exit;
						}
						break;
					case 'manage':
						$this->render_manage_tab();
						break;
					case 'products':
						$this->render_product_sync();
						break;
					default:
						$this->render_dashboard_tab();
						break;
				}
				?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the header.
	 *
	 * @param string $active_tab The active tab.
	 * @return void
	 */
	private function render_header( $active_tab ) {
		$header_view = new Header_View( $active_tab );
		$header_view->render();
	}

	/**
	 * Render the dashboard tab.
	 *
	 * @return void
	 */
	private function render_dashboard_tab() {
		// Delegated to Dashboard_Tab_View for presentation.
		$handler        = new \MOMCS_Sync\Includes\Common\Handlers\Dashboard_Handler();
		$channels       = $handler->get_all_channels();
		$dashboard_view = new \MOMCS_Sync\Views\Src\Common\Pages\Dashboard\Dashboard_Tab_View( $channels );
		$dashboard_view->render();
	}

	/**
	 * Render the connect tab.
	 *
	 * @param string $marketplace Marketplace to connect to.
	 * @return void
	 */
	private function render_connect_tab( $marketplace ) {
		// Make sure marketplace is lowercase.
		$marketplace = strtolower( $marketplace );

		// Check if there is a UUID parameter for editing.
		$uuid = Utils::get_current_page_parameter_value( 'uuid', '' );

		// Check if there's an action parameter.
		$action = Utils::get_current_page_parameter_value( 'action', '' );

		// Check if there's a step parameter.
		$step = Utils::get_current_page_parameter_value( 'step', '0' );

		// Check connection limits for Amazon when trying to add a new connection (not editing).
		if ( Plugin_Constants::AMAZON === $marketplace && empty( $uuid ) ) {
			$limit_check = \MOMCS_Sync\Includes\Common\Utils\Connection_Limits::can_add_amazon_connection();

			if ( ! $limit_check['can_add'] ) {
				// Show upgrade notice instead of connection form.
				$this->render_connection_limit_notice( $limit_check );
				return;
			}
		}

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

		// If we have a UUID, load the channel data.
		if ( ! empty( $uuid ) ) {
			$channel = $multichannels_model->get_channel_by_uuid( $uuid );

			// If channel is found.
			if ( $channel ) {

				// Load the appropriate view based on the marketplace.
				switch ( $marketplace ) {
					case Plugin_Constants::AMAZON:
						$this->render_amazon_connect_view( $channel );
						break;
					default:
						// Display the channels view.
						$this->render_marketplace_selection();
				}
				return;
			}
		} elseif ( $step > 0 ) {
			// If we have a step parameter without UUID, we're starting a NEW connection.
			// Don't update any existing channel - just render the step UI.
			// The step will be saved when the channel is created after OAuth.

			// Create a temporary channel object with the step for rendering only.
			$channel = array(
				'current_step' => $step,
			);

			// Render the appropriate view with the specified step.
			switch ( $marketplace ) {
				case Plugin_Constants::AMAZON:
					$this->render_amazon_connect_view( $channel );
					return; // Prevent duplicate rendering below.
				default:
					// Display the channels view.
					$this->render_marketplace_selection();
					return;
			}
		}

		// Standard flow without edit or step - render the appropriate view based on the marketplace.
		switch ( $marketplace ) {
			case Plugin_Constants::AMAZON:
				$this->render_amazon_connect_view();
				break;
		}
	}

	/**
	 * Render the Amazon connect view.
	 *
	 * @param array|null $channel Optional channel data for editing.
	 * @return void
	 */
	private function render_amazon_connect_view( $channel = null ) {
		$channel_uuid = Utils::get_current_page_parameter_value( 'uuid', '' );

		// Determine if channel is authorized (current_step >= 2 means auth completed).
		$is_authorized = false;
		if ( $channel && isset( $channel['current_step'] ) && (int) $channel['current_step'] >= 2 ) {
			$is_authorized = true;
		}

		// Determine active tab from URL parameter.
		$config_tab = Utils::get_current_page_parameter_value( 'config_tab', '' );

		// Backward compatibility: map old step= param to config_tab.
		if ( empty( $config_tab ) ) {
			$step = Utils::get_current_page_parameter_value( 'step', '' );
			if ( '' !== $step && (int) $step >= 2 ) {
				$config_tab = 'sync';
			}
		}

		// Default: authorized channels go to sync tab, others to authorization.
		if ( empty( $config_tab ) ) {
			$config_tab = $is_authorized ? 'sync' : 'authorization';
		}

		// Guard: can't access sync tab unless authorized.
		if ( 'sync' === $config_tab && ! $is_authorized ) {
			$config_tab = 'authorization';
		}

		// Use the factory to create the tab view.
		$tab_view = Marketplace_View_Factory::create_marketplace_tab_view(
			Plugin_Constants::AMAZON,
			$config_tab,
			$is_authorized,
			$channel_uuid
		);

		if ( $tab_view ) {
			$tab_view->render();
		}
	}

	/**
	 * Render the marketplace selection page.
	 *
	 * @return void
	 */
	private function render_marketplace_selection() {
		$view = new \MOMCS_Sync\Views\Src\Common\Pages\Supplier\Connect_Channels_View();
		$view->render();
	}

	/**
	 * Render the manage tab.
	 *
	 * @return void
	 */
	private function render_manage_tab() {
		// Delegated to Manage_Tab_View for presentation.
		$handler     = new \MOMCS_Sync\Includes\Common\Handlers\Dashboard_Handler();
		$channels    = $handler->get_all_channels();
		$manage_view = new \MOMCS_Sync\Views\Src\Common\Pages\Dashboard\Manage_Tab_View( $channels );
		$manage_view->render();
	}

	/**
	 * Render the product sync page.
	 *
	 * @return void
	 */
	public function render_product_sync() {
		$product_sync_view = new \MOMCS_Sync\Views\Src\Common\Pages\Supplier\Sync\Product_Sync_View();
		$product_sync_view->render();
	}

	/**
	 * Render the order sync page.
	 *
	 * @return void
	 */
	public function render_order_sync() {
		// Delegated to Order_Sync_View.
		$view = new \MOMCS_Sync\Views\Src\Common\Pages\Orders\Order_Sync_View();
		$view->render();
	}

	/**
	 * Render the Account page (miniOrange login/registration).
	 *
	 * @return void
	 */
	public function render_account_page() {
		$view = new \MOMCS_Sync\Views\Src\Common\Pages\Account\User_Account_View();
		$view->render();
	}

	/**
	 * Render Sync Audits page.
	 */
	public function render_sync_queue() {
		$view = new \MOMCS_Sync\Views\Src\Common\Pages\Queue\Sync_Queue_View();
		$view->render();
	}

	/**
	 * Render upgrade notice when connection limit is reached.
	 *
	 * @param array $limit_info Limit check information.
	 * @return void
	 */
	private function render_connection_limit_notice( array $limit_info ): void {
		?>
		<div class="wrap momcs-sync-wrap">
			<h1 class="screen-reader-text"><?php esc_html_e( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ); ?></h1>
			<?php $this->render_header( 'connect' ); ?>
			<div class="momcs-upgrade-notice">
				<h2><?php esc_html_e( 'Connection Limit Reached', 'multi-channel-for-woocommerce' ); ?></h2>
				<p><?php echo esc_html( $limit_info['message'] ); ?></p>
				<p>
					<strong>
						<?php
						echo esc_html(
							sprintf(
								/* translators: %1$d: current connections, %2$d: maximum allowed */
								__( 'Current: %1$d / %2$d connections', 'multi-channel-for-woocommerce' ),
								$limit_info['current_count'],
								$limit_info['max_allowed']
							)
						);
						?>
					</strong>
				</p>
				<p>
					<a href="<?php echo esc_url( Plugin_Constants::UPGRADE_PAYMENT_URL ); ?>" 
					   class="button button-primary" 
					   target="_blank">
						<?php esc_html_e( 'Upgrade to Premium', 'multi-channel-for-woocommerce' ); ?>
					</a>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-dashboard' ) ); ?>" 
					   class="button">
						<?php esc_html_e( 'Back to Dashboard', 'multi-channel-for-woocommerce' ); ?>
					</a>
				</p>
			</div>
		</div>
		<?php
	}
}
