<?php
/**
 * Category 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 category requests.
 * Thin static endpoint that delegates to the Category handler.
 */
class Category_Controller {

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

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

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

		// Delegate to handler.
		$handler    = new \MOMCS_Sync\Includes\Common\Handlers\Category_Handler();
		$categories = $handler->fetch_categories( $channel_id, $marketplace_id );

		if ( is_wp_error( $categories ) ) {
			$message = $categories->get_error_message() ? 'Failed to fetch categories.' : '';
			wp_send_json_error( array( 'message' => $message ) );
			exit;
		}

		// Return categories.
		wp_send_json_success(
			array(
				'categories' => $categories,
			)
		);
	}
}
