<?php
/**
 * Amazon Template Mapping View
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/views/src/common/pages/supplier/attribute-mapping
 * @author     miniOrange
 */

declare(strict_types=1);

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

use MOMCS_Sync\Includes\Common\Models\Multichannels_Model;
use MOMCS_Sync\Includes\Common\Services\Amazon\Category_Service;
use MOMCS_Sync\Includes\Common\Services\Amazon\Product_Type_Service;
use MOMCS_Sync\Includes\Common\Controllers\Template_Mapping\Unified_Mapping_Controller;
use MOMCS_Sync\Includes\Common\Utils\Utils;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

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

/**
 * Class for rendering the Amazon template mapping view.
 */
class Amazon_Template_Mapping_View {

	/**
	 * Multichannels model instance.
	 *
	 * @var Multichannels_Model
	 */
	private $multichannels_model;

	/**
	 * Category service instance.
	 *
	 * @var Category_Service
	 */
	private $category_service;

	/**
	 * Product type service instance.
	 *
	 * @var Product_Type_Service
	 */
	private $product_type_service;

	/**
	 * Field mapping controller instance.
	 *
	 * @var Unified_Mapping_Controller
	 */
	private $field_mapping_controller;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->multichannels_model      = new Multichannels_Model();
		$this->category_service         = new Category_Service();
		$this->product_type_service     = new Product_Type_Service();
		$this->field_mapping_controller = new Unified_Mapping_Controller();
	}

	/**
	 * Render the template mapping view.
	 *
	 * @return void
	 */
	public function render() {
		// Get Amazon channel.
		$amazon_channel = $this->get_amazon_channel();

		// Initialize marketplace_id for use in AJAX requests.
		$marketplace_id = '';
		$language_tag   = 'en_US'; // Default fallback.
		try {
			$default_meta_service = new \MOMCS_Sync\Includes\Common\Services\Default_Meta_Service();
			if ( $amazon_channel && isset( $amazon_channel['uuid'] ) ) {
				$defaults = $default_meta_service->get_defaults( $amazon_channel['uuid'] );
				if ( ! empty( $defaults['language_tag'] ) ) {
					$language_tag = $defaults['language_tag'];
				}
				if ( ! empty( $defaults['marketplace_id'] ) ) {
					$marketplace_id = $defaults['marketplace_id'];
				}
			}
		} catch ( \Throwable $e ) {
			wp_die( esc_html( $e->getMessage() ) );
		}

		// Get Amazon product types directly using channel UUID and region.
		$amazon_categories = array();
		if ( $amazon_channel && isset( $amazon_channel['uuid'] ) && isset( $amazon_channel['region'] ) ) {
			$marketplace_id    = $amazon_channel['region']; // Use region directly as marketplace_id.
			$amazon_categories = $this->category_service->get_product_types( $amazon_channel['uuid'], $marketplace_id );
		} else {
			// Fallback to default product types if no channel available.
			$amazon_categories = $this->category_service->get_product_types();
		}

		// Get WooCommerce categories.
		$wc_categories = $this->get_wc_categories();

		// Build ID => hierarchical name map for WC categories (used to label templates).
		$wc_category_names = array();
		foreach ( $wc_categories as $parent_id => $group ) {
			foreach ( $group as $category_id => $category ) {
				$path                        = $this->build_category_path( $category_id, $wc_categories );
				$wc_category_names[ $category_id ] = implode( ' -> ', $path );
			}
		}

		// Get WooCommerce product attributes for field mapping.
		$wc_attributes = Utils::get_wc_product_attributes();

		// Enqueue styles for the template mapping page.
		wp_enqueue_style(
			'momcs-template-mapping-style',
			MOMCS_PLUGIN_URL . 'assets/css/amazon-template-mapping.css',
			array(),
			defined( 'MOMCS_VERSION' ) ? MOMCS_VERSION : '1.0.0'
		);

		wp_enqueue_script(
			'momcs-template-mapping',
			MOMCS_PLUGIN_URL . 'assets/js/amazon-template-mapping.js',
			array( 'jquery' ),
			defined( 'MOMCS_VERSION' ) ? MOMCS_VERSION : '1.0.0',
			true
		);

		wp_localize_script(
			'momcs-template-mapping',
			'momcsAmazonTemplateMapping',
			array(
				'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
				'nonces'        => array(
					'getSchema'   => wp_create_nonce( 'momcs_sync_get_product_type_schema_nonce' ),
					'getMapping'  => wp_create_nonce( 'momcs_sync_get_unified_mapping_nonce' ),
					'saveMapping' => wp_create_nonce( 'momcs_sync_save_unified_mapping_nonce' ),
					'validateParent' => wp_create_nonce( 'momcs_sync_validate_parent_mapping_nonce' ),
				),
				'tmNonces'      => array(
					'main' => wp_create_nonce( 'momcs_tm_nonce' ),
				),
				'marketplaceId' => esc_js( $marketplace_id ),
				'channelUuid'   => esc_js( $amazon_channel['uuid'] ?? '' ),
				'wcAttributes'  => $wc_attributes,
				'amazonCategoryNames' => $amazon_categories,
				'wcCategoryNames' => $wc_category_names,
				'wcCategoryHierarchy' => $wc_categories,
				'defaultMeta'   => array(
					'marketplace_id' => esc_js( $marketplace_id ),
					'language_tag'   => esc_js( $language_tag ),
				),
				'limits'        => Utils::get_plan_limits(),
				'strings'       => array(
					'errorSelectWcCat'      => esc_html__( 'Please select a WooCommerce category for all rows.', 'multi-channel-for-woocommerce' ),
					'errorSelectAmazonCat'  => esc_html__( 'Please select an Amazon category.', 'multi-channel-for-woocommerce' ),
					'noFieldsFound'         => esc_html__( 'No fields found for this category.', 'multi-channel-for-woocommerce' ),
					/* translators: %s: template field label. */
					'errorRequiredTemplate' => esc_html__( 'Template field "%s" is required when category is selected.', 'multi-channel-for-woocommerce' ),
					'upgradeTooltip'        => esc_html__( 'Available in Premium. Upgrade to enable.', 'multi-channel-for-woocommerce' ),
					'actions'               => array(
						'add'     => esc_html__( 'Add', 'multi-channel-for-woocommerce' ),
						'save'    => esc_html__( 'Save', 'multi-channel-for-woocommerce' ),
						'save_as' => esc_html__( 'Save As', 'multi-channel-for-woocommerce' ),
						'clone'   => esc_html__( 'Clone', 'multi-channel-for-woocommerce' ),
						'delete'  => esc_html__( 'Delete', 'multi-channel-for-woocommerce' ),
					),
					'placeholders'          => array(
						'chooseTemplate' => esc_html__( '-- Select Template --', 'multi-channel-for-woocommerce' ),
						'label'          => esc_html__( 'Template label', 'multi-channel-for-woocommerce' ),
					),
					'emptyStateTitle'       => esc_html__( 'No template yet', 'multi-channel-for-woocommerce' ),
					'emptyStateDescription' => esc_html__( 'Create a template to map WooCommerce categories to Amazon and configure field mappings.', 'multi-channel-for-woocommerce' ),
					'addTemplate'           => esc_html__( 'Add template', 'multi-channel-for-woocommerce' ),
					'addTemplateReset'      => esc_html__( 'Add template', 'multi-channel-for-woocommerce' ),
					'initLoading'           => esc_html__( 'Loading templates…', 'multi-channel-for-woocommerce' ),
				),
			)
		);
		?>
		<div class="momcs-template-mapping-container">
			<h2><?php esc_html_e( 'Amazon Product Mapping', 'multi-channel-for-woocommerce' ); ?></h2>

			<div class="momcs-template-mapping-description">
				<p><?php esc_html_e( 'Map your WooCommerce product categories to Amazon product categories and configure field mappings.', 'multi-channel-for-woocommerce' ); ?></p>
			</div>

			<div id="momcs-template-mapping-init-loading" class="momcs-template-mapping-init-loading" aria-live="polite">
				<span class="spinner is-active"></span>
				<span class="momcs-template-mapping-init-loading-text"><?php esc_html_e( 'Loading templates…', 'multi-channel-for-woocommerce' ); ?></span>
			</div>

			<div id="momcs-template-mapping-empty-state" class="momcs-template-mapping-empty-state" style="display: none;" hidden>
				<div class="momcs-template-mapping-empty-state-inner">
					<h3 class="momcs-template-mapping-empty-state-title"><?php esc_html_e( 'No template yet', 'multi-channel-for-woocommerce' ); ?></h3>
					<p class="momcs-template-mapping-empty-state-desc"><?php esc_html_e( 'Create a template to map WooCommerce categories to Amazon and configure field mappings.', 'multi-channel-for-woocommerce' ); ?></p>
					<button type="button" id="momcs-add-template-mapping-start" class="button button-primary">
						<?php esc_html_e( 'Add template', 'multi-channel-for-woocommerce' ); ?>
					</button>
				</div>
			</div>

			<div id="momcs-template-mapping-editor" class="momcs-template-mapping-editor" style="display: none;" hidden>
			<!-- Premium: Template selection dropdown (populated via JS) -->
			<div id="momcs-template-dropdown-container" style="display: none; margin: 12px 0;">
				<label for="momcs-template-select" style="margin-right:8px;">
					<?php esc_html_e( 'Template', 'multi-channel-for-woocommerce' ); ?>
				</label>
				<select id="momcs-template-select" style="min-width:280px;">
					<option value=""><?php esc_html_e( '-- Select Template --', 'multi-channel-for-woocommerce' ); ?></option>
				</select>
			</div>

			<div class="momcs-template-mapping-form">
				<div class="momcs-template-mapping-rows-toolbar" style="display: none; margin-bottom: 8px;">
					<button type="button" id="momcs-add-template-mapping-reset" class="button button-secondary" style="display: none;">
						<?php esc_html_e( 'Add template', 'multi-channel-for-woocommerce' ); ?>
					</button>
				</div>
				<div class="momcs-template-mapping-rows-container">
					<div class="momcs-template-mapping-header">
						<div class="momcs-template-mapping-col momcs-template-mapping-wc-col">
							<strong><?php esc_html_e( 'WooCommerce Category', 'multi-channel-for-woocommerce' ); ?></strong>
						</div>
						<div class="momcs-template-mapping-col momcs-template-mapping-amazon-col">
							<strong><?php esc_html_e( 'Amazon Category', 'multi-channel-for-woocommerce' ); ?></strong>
						</div>
					</div>

					<div id="momcs-template-mapping-rows">
						<div class="momcs-template-mapping-row">
							<div class="momcs-template-mapping-col momcs-template-mapping-wc-col">
								<select class="momcs-template-mapping-wc-category" required>
									<option value=""><?php esc_html_e( '-- Select Category --', 'multi-channel-for-woocommerce' ); ?></option>
									<?php $this->render_category_options( $wc_categories ); ?>
								</select>
							</div>
							<div class="momcs-template-mapping-col momcs-template-mapping-amazon-col">
								<select class="momcs-template-mapping-amazon-category">
									<option value=""><?php esc_html_e( '-- Select Category --', 'multi-channel-for-woocommerce' ); ?></option>
									<?php foreach ( $amazon_categories as $category_id => $category_name ) : ?>
										<option value="<?php echo esc_attr( $category_id ); ?>"><?php echo esc_html( $category_name ); ?></option>
									<?php endforeach; ?>
								</select>
							</div>
						</div>
					</div>

				<!-- Parent Category Warning Container -->
				<div id="momcs-parent-category-warning" class="momcs-warning-container" style="display: none; margin-top: 15px;">
					<div class="notice notice-warning inline">
						<p>
							<strong><?php esc_html_e( 'Parent Category Mapping', 'multi-channel-for-woocommerce' ); ?></strong><br>
							<span id="momcs-warning-message"></span>
						</p>
						<div id="momcs-child-preview" style="margin-top: 10px;"></div>
					</div>
				</div>

				<div id="momcs-required-fields-container" style="display: none; margin-top: 20px;">
					<div style="display: flex; justify-content: space-between; align-items: center;">
						<h3><?php esc_html_e( 'Template Mapping', 'multi-channel-for-woocommerce' ); ?></h3>
						<button id="momcs-template-mapping-save" class="button button-primary" type="button" style="display: none;">
							<?php esc_html_e( 'Save Mappings', 'multi-channel-for-woocommerce' ); ?>
						</button>
					</div>
					<!-- <div id="momcs-category-chips-display" class="momcs-category-chips-display"></div> -->
					<div class="momcs-loading-message">
						<span class="spinner is-active"></span>
						<?php esc_html_e( 'Loading required fields...', 'multi-channel-for-woocommerce' ); ?>
					</div>
					<div class="momcs-field-mapping-table-container" style="display: none;">
						<table class="momcs-field-mapping-table">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Amazon Field', 'multi-channel-for-woocommerce' ); ?></th>
									<th><?php esc_html_e( 'WooCommerce Field', 'multi-channel-for-woocommerce' ); ?></th>
								</tr>
							</thead>
							<tbody id="momcs-field-mapping-rows">
								<!-- Field mapping rows will be added here dynamically -->
							</tbody>
						</table>
					</div>
					<span id="momcs-template-mapping-status" class="momcs-template-mapping-status"></span>
				</div>
			</div>
			</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render category options in flattened hierarchical format.
	 *
	 * @param array $categories Categories array organized by parent.
	 * @param int   $wc_parent     Parent category ID.
	 * @param array $path       Current hierarchical path.
	 * @return void
	 */
	private function render_category_options( $categories, $wc_parent = 0, $path = array() ) {
		if ( ! isset( $categories[ $wc_parent ] ) ) {
			return;
		}

		foreach ( $categories[ $wc_parent ] as $category_id => $category ) {
			// Build current path.
			$current_path = array_merge( $path, array( $category->name ) );

			// Create hierarchical display name.
			$display_name = implode( ' -> ', $current_path );

			// Determine if current category has children.
			$has_children = isset( $categories[ $category_id ] );

			if ( $has_children ) {
				// Make parent categories selectable with visual indicator.
				$parent_label = $display_name . ' ' . esc_html__( '(Parent Category)', 'multi-channel-for-woocommerce' );
				echo '<option value="' . esc_attr( $category_id ) . '" class="momcs-parent-category" data-has-children="true">' . esc_html( $parent_label ) . '</option>';
				
				// Render child categories with indentation.
				$this->render_category_options( $categories, $category_id, $current_path );
			} else {
				// Output selectable option for leaf categories.
				echo '<option value="' . esc_attr( $category_id ) . '" class="momcs-child-category">' . esc_html( $display_name ) . '</option>';
			}
		}
	}

	/**
	 * Build hierarchical path for a specific category.
	 *
	 * @param int   $category_id Category ID.
	 * @param array $categories  All categories organized by parent.
	 * @return array Array of category names representing the path.
	 */
	private function build_category_path( $category_id, $categories ) {
		$path       = array();
		$current_id = $category_id;

		// Traverse up the hierarchy to build the path.
		while ( $current_id && 0 !== $current_id ) {
			$category_found = false;

			// Find the category in the organized array.
			foreach ( $categories as $parent_id => $parent_categories ) {
				if ( isset( $parent_categories[ $current_id ] ) ) {
					$category = $parent_categories[ $current_id ];
					array_unshift( $path, $category->name );
					$current_id     = $category->parent;
					$category_found = true;
					break;
				}
			}

			// Break if category not found to prevent infinite loop.
			if ( ! $category_found ) {
				break;
			}
		}

		return $path;
	}

	/**
	 * Get WooCommerce categories.
	 *
	 * @return array
	 */
	private function get_wc_categories() {
		$categories = array();

		// Get all product categories.
		$args = array(
			'taxonomy'     => 'product_cat',
			'orderby'      => 'name',
			'show_count'   => 0,
			'pad_counts'   => 0,
			'hierarchical' => 1,
			'hide_empty'   => 0,
		);

		$all_categories = get_categories( $args );

		// Organize categories by parent.
		foreach ( $all_categories as $cat ) {
			$categories[ $cat->parent ][ $cat->term_id ] = $cat;
		}

		return $categories;
	}

	/**
	 * Get Amazon channel by UUID from URL parameter.
	 * 
	 * Requires 'uuid' parameter in the URL. Dies with error message if:
	 * - UUID parameter is missing
	 * - Channel not found
	 * - Channel is not an Amazon channel
	 *
	 * @return array Amazon channel data.
	 */
	private function get_amazon_channel() {
		// UUID parameter is required for multi-channel support.
		$uuid = Utils::get_current_page_parameter_value( 'uuid', '' );
		
		if ( empty( $uuid ) ) {
			wp_die( esc_html__( 'Channel UUID is required. Please navigate from the dashboard.', 'multi-channel-for-woocommerce' ) );
		}
		
		// Get the specific channel by UUID.
		$channel = $this->multichannels_model->get_channel_by_uuid( $uuid );
		
		if ( ! $channel ) {
			wp_die( esc_html__( 'Channel not found.', 'multi-channel-for-woocommerce' ) );
		}
		
		if ( strtolower( $channel['marketplace'] ?? '' ) !== Plugin_Constants::AMAZON ) {
			wp_die( esc_html__( 'Invalid channel type. Expected Amazon channel.', 'multi-channel-for-woocommerce' ) );
		}
		
		return $channel;
	}
}