<?php
/**
 * Stepper Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers/stepper
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers\Stepper;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Handlers\Stepper_Handler;

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

/**
 * Controller class for stepper functionality.
 */
class Stepper_Controller {

	/**
	 * Handle updating the step.
	 *
	 * @return void
	 */
	public static function handle_update_step() {
		// Verify nonce and capability (allow WooCommerce managers).
		if ( ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'manage_woocommerce' ) ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_update_step_nonce' ) ) {
			wp_send_json_error( array( 'message' => Plugin_Constants::MESSAGE_SECURITY_CHECK_FAILED ) );
			exit;
		}

		// Get step and marketplace.
		$step        = isset( $_POST['step'] ) ? sanitize_text_field( wp_unslash( $_POST['step'] ) ) : 0;
		$marketplace = isset( $_POST['marketplace'] ) ? sanitize_text_field( wp_unslash( $_POST['marketplace'] ) ) : '';

		// Get channel UUID if passed.
		$channel_uuid = isset( $_POST['channel_uuid'] ) ? sanitize_text_field( wp_unslash( $_POST['channel_uuid'] ) ) : '';

		// Delegate to handler.
		try {
			( new Stepper_Handler() )->update_step( $marketplace, (int) $step, $channel_uuid );
		} catch ( \Throwable $e ) {
			wp_send_json_error( array( 'message' => Plugin_Constants::MESSAGE_FAILED_TO_UPDATE_STEP ) );
			exit;
		}

		wp_send_json_success( array( 'message' => Plugin_Constants::MESSAGE_STEP_UPDATED_SUCCESSFULLY ) );
	}
}
