<?php
/**
 * Dashboard Tab View
 *
 * Renders the main dashboard tab showing either the empty state (no channels
 * connected yet) or a list of connected channels.  The heavy lifting of data
 * retrieval is delegated to Dashboard_Handler – this class is purely
 * responsible for presentational markup.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/views/src/common/pages/dashboard
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Views\Src\Common\Pages\Dashboard;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Utils\Utils;
use MOMCS_Sync\Includes\Plans\Premium\Handlers\License_Handler;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Class Dashboard_Tab_View
 */
class Dashboard_Tab_View {

	/**
	 * List of connected channels (rows from momcs_multichannels table).
	 *
	 * @var array<int, array<string, mixed>>
	 */
	private array $channels;

	/**
	 * License status information (premium builds only).
	 *
	 * @var array{has_license: bool, is_expired: bool, status_code: string, expiry_date: ?string, is_trial: bool}|null
	 */
	private ?array $license_status = null;

	/**
	 * Constructor.
	 *
	 * @param array<int, array<string, mixed>> $channels Channels retrieved from Dashboard_Handler.
	 */
	public function __construct( array $channels ) {
		$this->channels = $channels;
		if ( Utils::is_premium_plan() && class_exists( License_Handler::class ) ) {
			$this->license_status = License_Handler::get_license_status();
		}
	}

	/**
	 * Check if license is valid (not expired and has license).
	 *
	 * @return bool True if license is valid, false otherwise.
	 */
	private function is_license_valid(): bool {
		if ( ! Utils::is_premium_plan() || null === $this->license_status ) {
			return true;
		}

		return $this->license_status['has_license'] && ! $this->license_status['is_expired'];
	}

	/**
	 * Get disabled attribute string if license is invalid.
	 *
	 * @return string 'disabled' if license is invalid, empty string otherwise.
	 */
	private function get_disabled_attr(): string {
		return $this->is_license_valid() ? '' : 'disabled';
	}

	/**
	 * Get disabled CSS class if license is invalid.
	 *
	 * @return string 'momcs-license-disabled' if license is invalid, empty string otherwise.
	 */
	private function get_disabled_class(): string {
		return $this->is_license_valid() ? '' : 'momcs-license-disabled';
	}

	/**
	 * Get disabled title/tooltip if license is invalid.
	 *
	 * @return string Tooltip message if license is invalid, empty string otherwise.
	 */
	private function get_disabled_title(): string {
		if ( $this->is_license_valid() || null === $this->license_status ) {
			return '';
		}

		return $this->license_status['has_license']
			? __( 'Your license has expired. Please renew to use this feature.', 'multi-channel-for-woocommerce' )
			: __( 'No valid license found. Please verify your license.', 'multi-channel-for-woocommerce' );
	}

	/**
	 * Render the view.
	 *
	 * @return void
	 */
	public function render(): void {
		if ( empty( $this->channels ) ) {
			$this->render_empty_state();
		} else {
			$this->render_channel_list();
		}
	}

	/**
	 * Render the empty-state UI prompting the user to connect a marketplace.
	 *
	 * @return void
	 */
	private function render_empty_state(): void {
		$plugin_url = MOMCS_PLUGIN_URL; // Trailing slash included.
		?>
		<div class="momcs-sync-dashboard">
			<br/>
			<div class="momcs-channels-wrapper-new">
				<!-- Amazon Channel -->
				<div class="momcs-channel-rect-container">
					<div class="momcs-channel-rect-content">
						<div class="momcs-channel-rect-info">
							<img src="<?php echo esc_url( $plugin_url . 'assets/images/amazon-logo.png' ); ?>"
								alt="<?php esc_attr_e( 'Amazon Logo', 'multi-channel-for-woocommerce' ); ?>"
								class="momcs-channel-rect-logo"
							>
							<div class="momcs-channel-rect-text">
								<div class="momcs-channel-rect-name"><?php esc_html_e( 'Amazon', 'multi-channel-for-woocommerce' ); ?></div>
								<p><?php esc_html_e( 'Connect your Amazon Seller Central account to sync products.', 'multi-channel-for-woocommerce' ); ?></p>
							</div>
						</div>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-dashboard&tab=connect&marketplace=amazon&step=1' ) ); ?>" class="momcs-channel-rect-connect">
							<?php esc_html_e( 'Connect', 'multi-channel-for-woocommerce' ); ?>
						</a>
					</div>
				</div>

				<!-- eBay Channel -->
				<div class="momcs-channel-rect-container">
					<div class="momcs-channel-rect-content">
						<div class="momcs-channel-rect-info">
							<img src="<?php echo esc_url( $plugin_url . 'assets/images/ebay-logo.png' ); ?>"
								alt="<?php esc_attr_e( 'eBay Logo', 'multi-channel-for-woocommerce' ); ?>"
								class="momcs-channel-rect-logo"
							>
							<div class="momcs-channel-rect-text">
								<div class="momcs-channel-rect-name"><?php esc_html_e( 'eBay', 'multi-channel-for-woocommerce' ); ?></div>
								<p><?php esc_html_e( 'Connect your eBay account to sync products.', 'multi-channel-for-woocommerce' ); ?></p>
							</div>
						</div>
						<a class="momcs-channel-rect-connect disabled">
							<?php esc_html_e( 'Coming Soon', 'multi-channel-for-woocommerce' ); ?>
						</a>
					</div>
				</div>

				<!-- Walmart Channel -->
				<div class="momcs-channel-rect-container">
					<div class="momcs-channel-rect-content">
						<div class="momcs-channel-rect-info">
							<img src="<?php echo esc_url( $plugin_url . 'assets/images/walmart-logo.png' ); ?>"
								alt="<?php esc_attr_e( 'Walmart Logo', 'multi-channel-for-woocommerce' ); ?>"
								class="momcs-channel-rect-logo"
							>
							<div class="momcs-channel-rect-text">
								<div class="momcs-channel-rect-name"><?php esc_html_e( 'Walmart', 'multi-channel-for-woocommerce' ); ?></div>
								<p><?php esc_html_e( 'Connect your Walmart Marketplace account to sync products.', 'multi-channel-for-woocommerce' ); ?></p>
							</div>
						</div>
						<a class="momcs-channel-rect-connect disabled">
							<?php esc_html_e( 'Coming Soon', 'multi-channel-for-woocommerce' ); ?>
						</a>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the list of connected channels.
	 *
	 * @return void
	 */
	private function render_channel_list(): void {
		$plugin_url       = MOMCS_PLUGIN_URL;
		$connection_stats = \MOMCS_Sync\Includes\Common\Utils\Connection_Limits::get_connection_stats();
		$disabled_class   = $this->get_disabled_class();
		$disabled_title   = $this->get_disabled_title();
		$is_valid_license = $this->is_license_valid();
		?>
		<div class="momcs-sync-dashboard">
			<br/>
			<div class="momcs-channels-wrapper-new">
				<div class="momcs-sync-card">
					<div class="momcs-sync-card-content">
						<div class="momcs-card-header">
							<h3><?php esc_html_e( 'Marketplaces', 'multi-channel-for-woocommerce' ); ?></h3>
							
							<!-- Add New Connection Button -->
							<?php
							$limit_check = \MOMCS_Sync\Includes\Common\Utils\Connection_Limits::can_add_amazon_connection();
							if ( $limit_check['can_add'] ) :
								if ( $is_valid_license ) :
									?>
									<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-dashboard&tab=connect&marketplace=amazon&step=1' ) ); ?>" 
									   class="momcs-add-connection-btn">
										<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus-icon lucide-plus" aria-hidden="true"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
										<span><?php esc_html_e( 'Add Marketplace', 'multi-channel-for-woocommerce' ); ?></span>
									</a>
								<?php else : ?>
									<span class="momcs-add-connection-btn <?php echo esc_attr( $disabled_class ); ?>"
										  title="<?php echo esc_attr( $disabled_title ); ?>"
										  style="opacity: 0.6; cursor: not-allowed; pointer-events: none;">
										<span class="dashicons dashicons-lock"></span>
										<span><?php esc_html_e( 'Add Marketplace', 'multi-channel-for-woocommerce' ); ?></span>
									</span>
								<?php endif; ?>
							<?php else : ?>
								<a href="<?php echo esc_url( Plugin_Constants::UPGRADE_PAYMENT_URL ); ?>" 
								   class="momcs-add-connection-btn momcs-upgrade-btn"
								   target="_blank"
								   title="<?php echo esc_attr( $limit_check['message'] ); ?>">
									<span class="dashicons dashicons-lock"></span>
									<span><?php esc_html_e( 'Upgrade to Add More', 'multi-channel-for-woocommerce' ); ?></span>
								</a>
							<?php endif; ?>
						</div>
						
						<div class="momcs-marketplace-list">
							<?php
							foreach ( $this->channels as $channel ) :
								$marketplace    = $channel['marketplace'];
								$logo_url       = $plugin_url . 'assets/images/' . $marketplace . '-single-logo.png';
								$current_step   = isset( $channel['current_step'] ) ? (int) $channel['current_step'] : 1;
								$setup_complete = ( $current_step >= 3 );
								?>
								<div class="momcs-marketplace-item">
									<img src="<?php echo esc_url( $logo_url ); ?>"
										alt="<?php echo esc_attr( ucfirst( $marketplace ) . ' Logo' ); ?>"
									>
									<div class="momcs-marketplace-details">
										<h4><?php echo esc_html( $channel['connection_name'] ); ?></h4>
										<?php
										$region_raw      = isset( $channel['region'] ) ? (string) $channel['region'] : '';
										$region_upper    = strtoupper( trim( $region_raw ) );
										$country_name    = \MOMCS_Sync\Includes\Common\Utils\Marketplace_IDs::get_country_name_by_marketplace_id( $region_upper );
										$country_display = $country_name ?? strtoupper( $this->map_region_to_country( $region_raw ) );
										?>
										<span class="momcs-marketplace-region"><?php echo esc_html( $country_display ); ?></span>
									</div>

									<div class="momcs-marketplace-status">
										<?php if ( $setup_complete ) : ?>
											<span class="momcs-status-connected">
												<span class="momcs-status-dot"></span>
												<?php esc_html_e( 'Connected', 'multi-channel-for-woocommerce' ); ?>
											</span>
										<?php else : ?>
											<span class="momcs-sync-status-chip warning">
												<span class="momcs-sync-status-dot"></span>
												<?php esc_html_e( 'Continue Setup', 'multi-channel-for-woocommerce' ); ?>
											</span>
										<?php endif; ?>
									</div>

									<div class="momcs-marketplace-actions" style="margin-left: 10px;">
										<?php
										if ( $setup_complete ) :
											$edit_url = admin_url( 'admin.php?page=momcs-sync-dashboard&tab=connect&marketplace=' . $marketplace . '&action=edit&uuid=' . $channel['uuid'] );
											if ( $is_valid_license ) :
												?>
												<a href="<?php echo esc_url( $edit_url ); ?>" class="button">
													<span class="dashicons dashicons-edit" style="margin-top: 0px;"></span>
													<?php esc_html_e( 'Edit', 'multi-channel-for-woocommerce' ); ?>
												</a>
											<?php else : ?>
												<span class="button <?php echo esc_attr( $disabled_class ); ?>"
													  title="<?php echo esc_attr( $disabled_title ); ?>"
													  style="opacity: 0.6; cursor: not-allowed;">
													<span class="dashicons dashicons-edit" style="margin-top: 0px;"></span>
													<?php esc_html_e( 'Edit', 'multi-channel-for-woocommerce' ); ?>
												</span>
												<?php
											endif;
										else :
											$continue_url = admin_url( 'admin.php?page=momcs-sync-dashboard&tab=connect&marketplace=' . $marketplace . '&uuid=' . $channel['uuid'] );
											if ( $is_valid_license ) :
												?>
												<a href="<?php echo esc_url( $continue_url ); ?>" class="button button-primary">
													<span class="dashicons dashicons-arrow-right-alt" style="margin-top: 0px;"></span>
													<?php esc_html_e( 'Continue', 'multi-channel-for-woocommerce' ); ?>
												</a>
											<?php else : ?>
												<span class="button button-primary <?php echo esc_attr( $disabled_class ); ?>"
													  title="<?php echo esc_attr( $disabled_title ); ?>"
													  style="opacity: 0.6; cursor: not-allowed;">
													<span class="dashicons dashicons-arrow-right-alt" style="margin-top: 0px;"></span>
													<?php esc_html_e( 'Continue', 'multi-channel-for-woocommerce' ); ?>
												</span>
												<?php
											endif;
										endif;
										?>

										<a href="#" class="button danger momcs-sync-delete-channel" data-id="<?php echo esc_attr( $channel['id'] ); ?>">
											<span class="dashicons dashicons-trash" style="margin-top: 0px;"></span>
											<?php esc_html_e( 'Delete', 'multi-channel-for-woocommerce' ); ?>
										</a>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}


	/**
	 * Map SP-API region codes to ISO-3166 country codes for display.
	 * Matches behaviour of original Dashboard_Controller::map_region_to_country.
	 *
	 * @param string $region Region identifier returned by Amazon.
	 *
	 * @return string ISO country code or the original region string if unknown.
	 */
	private function map_region_to_country( string $region ): string {
		$mapping = array(
			'atvpdkikx0der'  => 'US',
			'a2euq1wtgctbg2' => 'CA',
			'a1pa6795ukmfr9' => 'DE',
			'a1rkkupihcs9hs' => 'ES',
			'a13vqmvgh1j6vh' => 'FR',
			'apaybkwhqasin'  => 'IT',
			'a21tjrujahjze'  => 'IN',
			'a1f83g8c2aro7p' => 'UK',
			'a1vc38t7yxb528' => 'JP',
			'a39ibj37trp1c6' => 'AU',
		);

		$key = strtolower( trim( $region ) );
		return $mapping[ $key ] ?? $region;
	}
}
