<?php
/**
 * Product Type Schema 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 product type schema requests.
 */
class Product_Type_Schema_Controller {

	/**
	 * Handle getting the product type schema.
	 *
	 * @return void
	 */
	public static function handle_get_product_type_schema(): void {
		// Capability or nonce verification.
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_get_product_type_schema_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		// Get parameters.
		$product_type   = isset( $_POST['product_type'] ) ? sanitize_text_field( wp_unslash( $_POST['product_type'] ) ) : '';
		$marketplace_id = isset( $_POST['marketplace_id'] ) ? sanitize_text_field( wp_unslash( $_POST['marketplace_id'] ) ) : '';
		$channel_id     = isset( $_POST['channel_id'] ) ? sanitize_text_field( wp_unslash( $_POST['channel_id'] ) ) : '';

		if ( '' === $product_type || '' === $marketplace_id || '' === $channel_id ) {
			wp_send_json_error( array( 'message' => 'Missing required parameters.' ) );
			exit;
		}

		$handler = new \MOMCS_Sync\Includes\Common\Handlers\Product_Type_Schema_Handler();
		$result  = $handler->fetch_schema_and_fields( $channel_id, $product_type, $marketplace_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			exit;
		}

		wp_send_json_success( $result );
	}
}
