<?php
/**
 * Amazon Field 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\Field_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 field mapping view.
 */
class Amazon_Field_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 Field_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 Field_Mapping_Controller();
	}

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

		// Get marketplace ID from region.
		$marketplace_id = '';
		if ( $amazon_channel && isset( $amazon_channel['region'] ) ) {
			$marketplace_id = $this->category_service->get_marketplace_id_by_region( $amazon_channel['region'] );
		}

		// Get Amazon product types.
		$product_types = $this->category_service->get_amazon_product_types();

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

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

		wp_localize_script(
			'momcs-field-mapping',
			'momcsAmazonFieldMapping',
			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_field_mapping_nonce' ),
					'saveMapping' => wp_create_nonce( 'momcs_sync_save_field_mapping_nonce' ),
				),
				'marketplaceId' => esc_js( $marketplace_id ),
				'channelUuid'   => esc_js( $amazon_channel['uuid'] ?? '' ),
				'wc_attributes' => $wc_attributes,
				'strings'       => array(
					'noRequiredFields'       => esc_html__( 'No required fields found for this product type.', 'multi-channel-for-woocommerce' ),
					'failedFetchFields'      => esc_html__( 'Failed to load required fields for this product type.', 'multi-channel-for-woocommerce' ),
					'errorFetchFields'       => esc_html__( 'An error occurred while fetching required fields.', 'multi-channel-for-woocommerce' ),
					'selectFieldPlaceholder' => esc_html__( '-- Select Field --', 'multi-channel-for-woocommerce' ),
					'saving'                 => esc_html__( 'Saving...', 'multi-channel-for-woocommerce' ),
					'saved'                  => esc_html__( 'Field mappings saved', 'multi-channel-for-woocommerce' ),
					'failedSave'             => esc_html__( 'Failed to save field mappings', 'multi-channel-for-woocommerce' ),
				),
			)
		);

		?>
		<div class="momcs-field-mapping-container">
			<h2><?php esc_html_e( 'Map Amazon Fields to WooCommerce Fields', 'multi-channel-for-woocommerce' ); ?></h2>
			
			<div class="momcs-field-mapping-description">
				<p><?php esc_html_e( 'Map Amazon required fields to your WooCommerce product fields. This mapping will be used when syncing products to Amazon.', 'multi-channel-for-woocommerce' ); ?></p>
			</div>
			
			<div class="momcs-field-mapping-form">
				<div class="momcs-field-mapping-product-type-container">
					<label for="momcs-field-mapping-product-type">
						<?php esc_html_e( 'Select Amazon Product Type:', 'multi-channel-for-woocommerce' ); ?>
					</label>
					<select id="momcs-field-mapping-product-type" class="momcs-field-mapping-product-type">
						<option value=""><?php esc_html_e( '-- Select Product Type --', 'multi-channel-for-woocommerce' ); ?></option>
						<?php foreach ( $product_types as $type_id => $type_name ) : ?>
							<option value="<?php echo esc_attr( $type_id ); ?>"><?php echo esc_html( $type_name ); ?></option>
						<?php endforeach; ?>
					</select>
				</div>
				
				<div id="momcs-field-mapping-fields-container" style="display: none;">
					<div class="momcs-loading-message">
						<span class="spinner is-active"></span>
						<?php esc_html_e( 'Loading required fields...', 'multi-channel-for-woocommerce' ); ?>
					</div>
					
					<table class="momcs-field-mapping-table" style="display: none;">
						<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>
								<th><?php esc_html_e( 'Field Type', 'multi-channel-for-woocommerce' ); ?></th>
								<th><?php esc_html_e( 'Description', 'multi-channel-for-woocommerce' ); ?></th>
							</tr>
						</thead>
						<tbody id="momcs-field-mapping-rows">
							<!-- Field mapping rows will be added here dynamically -->
						</tbody>
					</table>
					
					<div class="momcs-field-mapping-actions">
						<button id="momcs-field-mapping-save" class="button button-primary" type="button" style="margin-top: 15px; display: none;">
							<?php esc_html_e( 'Save Field Mapping', 'multi-channel-for-woocommerce' ); ?>
						</button>
						<span id="momcs-field-mapping-status" class="momcs-field-mapping-status"></span>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * 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;
	}
}
