<?php
/**
 * Template 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 template mapping functionality.
 */
class Template_Mapping_Controller {

	/**
	 * Handle saving the template mapping.
	 *
	 * @return void
	 */
	public static function handle_save_template_mapping(): 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_save_template_mapping_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		$marketplace  = isset( $_POST['marketplace'] ) ? sanitize_text_field( wp_unslash( $_POST['marketplace'] ) ) : '';
		$channel_id   = isset( $_POST['channel_id'] ) ? sanitize_text_field( wp_unslash( $_POST['channel_id'] ) ) : '';
		$mapping_data = isset( $_POST['mapping_data'] ) ? sanitize_text_field( wp_unslash( $_POST['mapping_data'] ) ) : '';

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

		try {
			( new \MOMCS_Sync\Includes\Common\Handlers\Mapping_Handler() )
				->save_template_mapping( $marketplace, $mapping_data, $channel_id );
			wp_send_json_success( array( 'message' => 'Template mapping saved successfully.' ) );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ?? 'Failed to save template mapping data.' ) );
		}
	}

	/**
	 * Handle getting the template mapping.
	 *
	 * @return void
	 */
	public static function handle_get_template_mapping(): 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_template_mapping_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed.' ) );
			exit;
		}

		$marketplace = isset( $_POST['marketplace'] ) ? sanitize_text_field( wp_unslash( $_POST['marketplace'] ) ) : '';
		$channel_id  = isset( $_POST['channel_id'] ) ? sanitize_text_field( wp_unslash( $_POST['channel_id'] ) ) : '';

		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();
			$data    = $handler->get_template_mapping( $marketplace, $channel_id );
			wp_send_json_success( array( 'mappings' => $data ) );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'mappings' => array() ) );
		}
	}
}
