<?php
/**
 * Product Settings Handler
 *
 * Adds custom product-level configuration fields in the WooCommerce product editor.
 *
 * @package MOMCS_Sync\Includes\Common\Handlers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

use MOMCS_Sync\Includes\Common\Utils\Asin_Helper;
use MOMCS_Sync\Includes\Common\Utils\Utils;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

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

/**
 * Class Product_Settings_Handler
 */
class Product_Settings_Handler {

	/**
	 * Initialise hooks.
	 */
	public function init(): void {
		// Add new tab in the product data meta box.
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'register_tab' ), 10 );

		// Render the panel for the tab.
		add_action( 'woocommerce_product_data_panels', array( $this, 'render_panel' ) );

		// Save the custom fields.
		add_action( 'woocommerce_admin_process_product_object', array( $this, 'save_fields' ) );

		// Enqueue JS for the meta-box when editing products.
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

		// Ajax handler for on-demand sync.
		add_action( 'wp_ajax_momcs_amz_product_sync_now', array( $this, 'sync_now_ajax' ) );
	}

	/**
	 * Register new tab.
	 *
	 * @param array $tabs Existing Woo tabs.
	 * @return array Modified tabs.
	 */
	public function register_tab( array $tabs ): array {
		$tabs['momcs_sync'] = array(
			'label'    => esc_html__( 'miniOrange Multi-Channel Sync Settings', 'multi-channel-for-woocommerce' ),
			'target'   => 'momcs_sync_product_data',
			'class'    => array(),
			'priority' => 4,
		);
		return $tabs;
	}

	/**
	 * Render custom panel HTML.
	 *
	 * @param string $hook The current admin page.
	 */
	public function enqueue_assets( $hook ): void {
		// Only load on product edit/create screens.
		if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || 'product' !== $screen->post_type ) {
			return;
		}

		wp_enqueue_script(
			'momcs-sync-product-settings',
			MOMCS_PLUGIN_URL . 'assets/js/product-settings.js',
			array( 'jquery' ),
			defined( 'MOMCS_VERSION' ) ? MOMCS_VERSION : '1.0.0',
			true
		);

		wp_localize_script(
			'momcs-sync-product-settings',
			'momcsAmazonProductSettings',
			array(
				'strings' => array(
					'syncing'  => esc_html__( 'Syncing…', 'multi-channel-for-woocommerce' ),
					'success'  => esc_html__( 'Sync queued!', 'multi-channel-for-woocommerce' ),
					'sync_now' => esc_html__( 'Sync to Amazon Now', 'multi-channel-for-woocommerce' ),
				),
			)
		);
	}

	/**
	 * Render custom panel HTML.
	 */
	public function render_panel(): void {
		echo '<div id="momcs_sync_product_data" class="panel woocommerce_options_panel hidden">';

		// Ensure no WooCommerce Admin notices break layout.
		if ( class_exists( '\\WooCommerce\\Admin\\Filters\\Notifications' ) ) {
			\WooCommerce\Admin\Filters\Notifications::maybe_remove_notifications();
		}

		// Group 1 – ASIN & Amazon SKU.
		echo '<div class="options_group">';

		// Plan-aware ASIN rendering.
		if ( Utils::is_premium_plan() ) {
			$this->render_premium_asin_fields();
		} else {
			$this->render_standard_asin_field();
		}
		woocommerce_wp_text_input(
			array(
				'id'    => '_momcs_amz_sku',
				'label' => esc_html__( 'Amazon SKU', 'multi-channel-for-woocommerce' ),
			)
		);
		echo '</div>';

		// Group 2 – Brand, Product Type, Condition.
		echo '<div class="options_group">';
		woocommerce_wp_text_input(
			array(
				'id'    => '_momcs_amz_brand',
				'label' => esc_html__( 'Brand', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'    => '_momcs_amz_product_type',
				'label' => esc_html__( 'Product Type', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_select(
			array(
				'id'      => '_momcs_amz_condition',
				'label'   => esc_html__( 'Condition', 'multi-channel-for-woocommerce' ),
				'options' => array(
					''                        => esc_html__( 'Choose&hellip;', 'multi-channel-for-woocommerce' ),
					'club_club'               => esc_html__( 'Club', 'multi-channel-for-woocommerce' ),
					'collectible_acceptable'  => esc_html__( 'Collectible - Acceptable', 'multi-channel-for-woocommerce' ),
					'collectible_good'        => esc_html__( 'Collectible - Good', 'multi-channel-for-woocommerce' ),
					'collectible_like_new'    => esc_html__( 'Collectible - Like New', 'multi-channel-for-woocommerce' ),
					'collectible_very_good'   => esc_html__( 'Collectible - Very Good', 'multi-channel-for-woocommerce' ),
					'new_new'                 => esc_html__( 'New', 'multi-channel-for-woocommerce' ),
					'new_oem'                 => esc_html__( 'New - OEM', 'multi-channel-for-woocommerce' ),
					'new_open_box'            => esc_html__( 'New - Open Box', 'multi-channel-for-woocommerce' ),
					'refurbished_refurbished' => esc_html__( 'Refurbished', 'multi-channel-for-woocommerce' ),
					'used_acceptable'         => esc_html__( 'Used - Acceptable', 'multi-channel-for-woocommerce' ),
					'used_good'               => esc_html__( 'Used - Good', 'multi-channel-for-woocommerce' ),
					'used_like_new'           => esc_html__( 'Used - Like New', 'multi-channel-for-woocommerce' ),
					'used_very_good'          => esc_html__( 'Used - Very Good', 'multi-channel-for-woocommerce' ),
				),
			)
		);
		echo '</div>';

		// Group 3 – ID Type & ID Value.
		echo '<div class="options_group">';
		woocommerce_wp_select(
			array(
				'id'      => '_momcs_amz_id_type',
				'label'   => esc_html__( 'Product ID Type', 'multi-channel-for-woocommerce' ),
				'options' => array(
					''     => esc_html__( 'Choose&hellip;', 'multi-channel-for-woocommerce' ),
					'UPC'  => 'UPC',
					'EAN'  => 'EAN',
					'ISBN' => 'ISBN',
					'GTIN' => 'GTIN',
				),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'    => '_momcs_amz_id_value',
				'label' => esc_html__( 'Product ID Value', 'multi-channel-for-woocommerce' ),
			)
		);
		echo '</div>';

		// Group 4 – Bullet Points.
		echo '<div class="options_group">';
		echo '<h3 style="margin: 12px">' . esc_html__( 'Amazon Bullet Points', 'multi-channel-for-woocommerce' ) . '</h3>';
		woocommerce_wp_text_input(
			array(
				'id'          => '_momcs_amz_bullet_point_1',
				'label'       => esc_html__( 'Bullet Point 1', 'multi-channel-for-woocommerce' ),
				'description' => esc_html__( 'First key feature or benefit of the product.', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'          => '_momcs_amz_bullet_point_2',
				'label'       => esc_html__( 'Bullet Point 2', 'multi-channel-for-woocommerce' ),
				'description' => esc_html__( 'Second key feature or benefit of the product.', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'          => '_momcs_amz_bullet_point_3',
				'label'       => esc_html__( 'Bullet Point 3', 'multi-channel-for-woocommerce' ),
				'description' => esc_html__( 'Third key feature or benefit of the product.', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'          => '_momcs_amz_bullet_point_4',
				'label'       => esc_html__( 'Bullet Point 4', 'multi-channel-for-woocommerce' ),
				'description' => esc_html__( 'Fourth key feature or benefit of the product.', 'multi-channel-for-woocommerce' ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'          => '_momcs_amz_bullet_point_5',
				'label'       => esc_html__( 'Bullet Point 5', 'multi-channel-for-woocommerce' ),
				'description' => esc_html__( 'Fifth key feature or benefit of the product.', 'multi-channel-for-woocommerce' ),
			)
		);
		echo '</div>';
		echo '</div>';
	}

	/**
	 * Save custom fields.
	 *
	 * @param \WC_Product $product Product object.
	 */
	public function save_fields( \WC_Product $product ): void {
		if ( ! isset( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ), 'woocommerce_save_data' ) || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Handle ASIN saving (plan-aware).
		if ( Utils::is_premium_plan() ) {
			$this->save_premium_asin_fields( $product );
		} else {
			$this->save_standard_asin_field( $product );
		}

		// Handle non-ASIN fields.
		$map_text = array(
			'_momcs_amz_sku',
			'_momcs_amz_brand',
			'_momcs_amz_product_type',
			'_momcs_amz_id_value',
			'_momcs_amz_bullet_point_1',
			'_momcs_amz_bullet_point_2',
			'_momcs_amz_bullet_point_3',
			'_momcs_amz_bullet_point_4',
			'_momcs_amz_bullet_point_5',
		);

		$product->update_meta_data( '_momcs_amz_condition', sanitize_text_field( wp_unslash( $_POST['_momcs_amz_condition'] ?? '' ) ) );
		$product->update_meta_data( '_momcs_amz_id_type', sanitize_text_field( wp_unslash( $_POST['_momcs_amz_id_type'] ?? '' ) ) );

		foreach ( $map_text as $key ) {
			$value = isset( $_POST[ $key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) : '';
			$product->update_meta_data( $key, $value );
		}

		$fc = isset( $_POST['_momcs_amz_fulfillment_channel'] ) ? sanitize_text_field( wp_unslash( $_POST['_momcs_amz_fulfillment_channel'] ) ) : 'FBM';
		$product->update_meta_data( '_momcs_amz_fulfillment_channel', $fc );
	}

	/**
	 * Ajax: sync now.
	 */
	public function sync_now_ajax(): void {
		check_ajax_referer( 'momcs_amz_product_sync_now', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'multi-channel-for-woocommerce' ) ) );
		}
		$product_id = absint( $_POST['product_id'] ?? 0 );
		if ( ! $product_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid product ID.', 'multi-channel-for-woocommerce' ) ) );
		}
		wp_send_json_success();
	}

	/**
	 * Render standard plan ASIN field.
	 */
	private function render_standard_asin_field(): void {
		woocommerce_wp_text_input(
			array(
				'id'    => '_momcs_amz_asin',
				'label' => esc_html__( 'ASIN', 'multi-channel-for-woocommerce' ),
			)
		);
	}

	/**
	 * Render premium plan marketplace-specific ASIN fields.
	 */
	private function render_premium_asin_fields(): void {
		global $post;
		
		if ( ! $post ) {
			return;
		}

		// Check if premium ASIN helper exists.
		if ( ! class_exists( '\\MOMCS_Sync\\Includes\\Plans\\Premium\\Utils\\Asin_Helper' ) ) {
			$this->render_standard_asin_field();
			return;
		}

		$premium_asin_helper = '\\MOMCS_Sync\\Includes\\Plans\\Premium\\Utils\\Asin_Helper';
		$marketplace_display_helper = '\\MOMCS_Sync\\Includes\\Plans\\Premium\\Utils\\Marketplace_Display_Helper';

		// Get configured marketplaces.
		$configured_marketplaces = $premium_asin_helper::get_configured_marketplaces();

		if ( empty( $configured_marketplaces ) ) {
			echo '<p>' . esc_html__( 'No Amazon channels configured. Please configure Amazon channels first.', 'multi-channel-for-woocommerce' ) . '</p>';
			return;
		}

		echo '<h4>' . esc_html__( 'Amazon ASINs by Marketplace', 'multi-channel-for-woocommerce' ) . '</h4>';
		echo '<table class="momcs-asin-marketplace-table" style="width: 100%; border-collapse: collapse;">';
		echo '<thead>';
		echo '<tr style="background: #f7f7f7;">';
		echo '<th style="padding: 8px 12px; text-align: left; font-weight: 600;">' . esc_html__( 'Marketplace', 'multi-channel-for-woocommerce' ) . '</th>';
		echo '<th style="padding: 8px 12px; text-align: left; font-weight: 600;">' . esc_html__( 'ASIN', 'multi-channel-for-woocommerce' ) . '</th>';
		echo '</tr>';
		echo '</thead>';
		echo '<tbody>';

		foreach ( $configured_marketplaces as $marketplace_id => $channel_info ) {
			$marketplace_info = $marketplace_display_helper::get_marketplace_info( $marketplace_id );
			$display_name = $marketplace_info['name'] ?? $marketplace_id;
			$flag_code = $marketplace_info['flag'] ?? '';
			
			// Get existing ASIN for this marketplace.
			$existing_asin = $premium_asin_helper::get_product_asin( $post->ID, $marketplace_id );
			
			echo '<tr>';
			echo '<td style="padding: 8px 12px; border-bottom: 1px solid #eee;">';
			if ( ! empty( $flag_code ) ) {
				echo '<span class="momcs-mp-flag momcs-flag-' . esc_attr( $flag_code ) . '" style="display: inline-block; width: 16px; height: 12px; margin-right: 6px; background-size: contain; background-repeat: no-repeat; background-position: center; border-radius: 2px; box-shadow: 0 0 1px rgba(0,0,0,0.2); vertical-align: middle;"></span>';
			}
			echo esc_html( $display_name );
			echo '</td>';
			echo '<td style="padding: 8px 12px; border-bottom: 1px solid #eee;">';
			echo '<input type="text" name="_momcs_amz_asin_' . esc_attr( $marketplace_id ) . '" ';
			echo 'value="' . esc_attr( $existing_asin ) . '" ';
			echo 'placeholder="' . esc_attr__( 'Enter ASIN manually or use bulk sync', 'multi-channel-for-woocommerce' ) . '" ';
			echo 'style="width: 100%; padding: 4px 8px;" />';
			echo '</td>';
			echo '</tr>';
		}

		echo '</tbody>';
		echo '</table>';
		echo '<p class="description">' . esc_html__( 'You can manually enter ASINs or use the bulk ASIN sync feature.', 'multi-channel-for-woocommerce' ) . '</p>';
	}

	/**
	 * Save standard plan ASIN field.
	 *
	 * @param \WC_Product $product Product object.
	 */
	private function save_standard_asin_field( \WC_Product $product ): void {
		$asin = isset( $_POST['_momcs_amz_asin'] ) ? sanitize_text_field( wp_unslash( $_POST['_momcs_amz_asin'] ) ) : '';
		Asin_Helper::set_product_asin( $product->get_id(), $asin );
	}

	/**
	 * Save premium plan marketplace-specific ASIN fields.
	 *
	 * @param \WC_Product $product Product object.
	 */
	private function save_premium_asin_fields( \WC_Product $product ): void {
		// Check if premium ASIN helper exists.
		if ( ! class_exists( '\\MOMCS_Sync\\Includes\\Plans\\Premium\\Utils\\Asin_Helper' ) ) {
			$this->save_standard_asin_field( $product );
			return;
		}

		$premium_asin_helper = '\\MOMCS_Sync\\Includes\\Plans\\Premium\\Utils\\Asin_Helper';

		// Get configured marketplaces.
		$configured_marketplaces = $premium_asin_helper::get_configured_marketplaces();

		foreach ( $configured_marketplaces as $marketplace_id => $channel_info ) {
			$field_name = '_momcs_amz_asin_' . $marketplace_id;
			$asin = isset( $_POST[ $field_name ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field_name ] ) ) : '';
			
			if ( ! empty( $asin ) ) {
				$premium_asin_helper::set_product_asin( $product->get_id(), $asin, $marketplace_id );
			} else {
				// Remove ASIN if empty.
				$premium_asin_helper::delete_product_asin( $product->get_id(), $marketplace_id );
			}
		}
	}
}
