<?php
/**
 * Unified Mapping Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers/template-mapping
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers\Template_Mapping;

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

/**
 * Controller class for handling unified mapping functionality.
 * Thin static endpoints that delegate to Mapping_Handler.
 */
class Unified_Mapping_Controller {
	/**
	 * Handle saving the unified mapping.
	 *
	 * Expects POST params:
	 * - marketplace: string (required)
	 * - channel_id: string (required - UUID for multi-channel support)
	 * - category_mapping: JSON string
	 * - field_mapping: JSON string
	 * - selected_category: string
	 * - mapping_data: JSON string
	 * - new_attributes: JSON string (optional)
	 *
	 * @return void
	 */
	public static function handle_save_unified_mapping(): void {
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_save_unified_mapping_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		$marketplace       = sanitize_text_field( wp_unslash( $_POST['marketplace'] ?? '' ) );
		$channel_id        = sanitize_text_field( wp_unslash( $_POST['channel_id'] ?? '' ) );
		$category_mapping  = sanitize_text_field( wp_unslash( $_POST['category_mapping'] ?? '' ) );
		$field_mapping     = sanitize_text_field( wp_unslash( $_POST['field_mapping'] ?? '' ) );
		$selected_category = sanitize_text_field( wp_unslash( $_POST['selected_category'] ?? '' ) );
		$mapping_data      = sanitize_text_field( wp_unslash( $_POST['mapping_data'] ?? '' ) );
		$new_attributes    = sanitize_text_field( wp_unslash( $_POST['new_attributes'] ?? '' ) );

		if ( empty( $channel_id ) ) {
			wp_send_json_error( array( 'message' => 'Channel ID is required.' ) );
			exit;
		}

		try {
			$handler = new \MOMCS_Sync\Includes\Common\Handlers\Mapping_Handler();

			if ( '' !== $new_attributes ) {
				$handler->create_new_woocommerce_attributes_from_json( $new_attributes );
			}

			$saved_template_uuid = $handler->save_unified_mapping( $marketplace, $category_mapping, $field_mapping, $selected_category, $mapping_data, $channel_id );
			$response            = array( 'message' => 'All mapping configurations saved successfully.' );
			if ( ! empty( $saved_template_uuid ) ) {
				$response['template_uuid'] = $saved_template_uuid;
			}
			wp_send_json_success( $response );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}

	/**
	 * Handle getting the unified mapping.
	 *
	 * Expects POST params:
	 * - marketplace: string (required)
	 * - channel_id: string (required - UUID for multi-channel support)
	 * - template_uuid: string (optional, for specific template)
	 * - wc_category: string (optional, for category pair lookup)
	 * - amazon_category: string (optional, for category pair lookup)
	 *
	 * @return void
	 */
	public static function handle_get_unified_mapping(): void {
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_get_unified_mapping_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		$marketplace   = sanitize_text_field( wp_unslash( $_POST['marketplace'] ?? '' ) );
		$channel_id    = sanitize_text_field( wp_unslash( $_POST['channel_id'] ?? '' ) );
		$template_uuid = sanitize_text_field( wp_unslash( $_POST['template_uuid'] ?? '' ) );
		$wc_category   = sanitize_text_field( wp_unslash( $_POST['wc_category'] ?? '' ) );
		$amz_category  = sanitize_text_field( wp_unslash( $_POST['amazon_category'] ?? '' ) );

		if ( empty( $channel_id ) ) {
			wp_send_json_error( array( 'message' => 'Channel ID is required.' ) );
			exit;
		}

		try {
			$handler = new \MOMCS_Sync\Includes\Common\Handlers\Mapping_Handler();
			$allow_multiple = (bool) apply_filters( 'momcs_allow_multiple_templates', false );
			if ( $template_uuid && $allow_multiple ) {
				$data = $handler->get_unified_mapping_by_uuid( $template_uuid );
			} elseif ( $wc_category && $amz_category ) {
				$data = $handler->get_unified_mapping_by_pair( $marketplace, $wc_category, $amz_category, $channel_id );
			} else {
				$data = $handler->get_unified_mapping( $marketplace, $channel_id );
			}
			wp_send_json_success( $data );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}

	/**
	 * Handle validating parent category mapping for potential conflicts.
	 *
	 * Expects POST params:
	 * - marketplace: string (required)
	 * - channel_id: string (required - UUID for multi-channel support)
	 * - wc_category: string (required)
	 * - amazon_category: string (required)
	 *
	 * @return void
	 */
	public static function handle_validate_parent_mapping(): void {
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_validate_parent_mapping_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		$marketplace     = sanitize_text_field( wp_unslash( $_POST['marketplace'] ?? '' ) );
		$channel_id      = sanitize_text_field( wp_unslash( $_POST['channel_id'] ?? '' ) );
		$wc_category     = sanitize_text_field( wp_unslash( $_POST['wc_category'] ?? '' ) );
		$amazon_category = sanitize_text_field( wp_unslash( $_POST['amazon_category'] ?? '' ) );

		if ( empty( $channel_id ) ) {
			wp_send_json_error( array( 'message' => 'Channel ID is required.' ) );
			exit;
		}

		try {
			$handler = new \MOMCS_Sync\Includes\Common\Handlers\Mapping_Handler();
			$validation = $handler->validate_parent_category_mapping( $marketplace, $wc_category, $amazon_category, $channel_id );
			wp_send_json_success( $validation );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}
}
