<?php
/**
 * REST API: mark the first-run onboarding tour completed/skipped.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Admin\Rest;

use PRECO\Includes\Admin\Onboarding;
use PRECO\Includes\Durbin\DurbinClient;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Onboarding REST controller.
 *
 * Handles:
 *  POST /preco/v1/onboarding — mark the tour completed or skipped.
 *  POST /preco/v1/onboarding/subscribe — report the wizard subscription opt-in.
 */
class OnboardingRest {

	/**
	 * REST namespace.
	 */
	const PRECO_REST_NAMESPACE = 'preco/v1';

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register routes.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			self::PRECO_REST_NAMESPACE,
			'/onboarding',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'mark_status' ),
				'permission_callback' => array( $this, 'permission_check' ),
				'args'                => array(
					'status' => array(
						'required' => true,
						'type'     => 'string',
						'enum'     => Onboarding::DISMISS_STATUSES,
					),
				),
			)
		);

		register_rest_route(
			self::PRECO_REST_NAMESPACE,
			'/onboarding/subscribe',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'subscribe' ),
				'permission_callback' => array( $this, 'permission_check' ),
			)
		);
	}

	/**
	 * Permission check.
	 *
	 * @return bool
	 */
	public function permission_check() {
		return current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' );
	}

	/**
	 * POST /preco/v1/onboarding
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function mark_status( WP_REST_Request $request ) {
		if ( ! wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
			return new WP_REST_Response( array( 'message' => 'Invalid nonce.' ), 403 );
		}

		$status = Onboarding::mark( $request->get_param( 'status' ) );
		if ( ! $status ) {
			return new WP_REST_Response( array( 'message' => 'Invalid status.' ), 400 );
		}

		return new WP_REST_Response( array( 'status' => Onboarding::get_status() ), 200 );
	}

	/**
	 * POST /preco/v1/onboarding/subscribe
	 *
	 * Reports that the user left the "Subscribe to get Suggestions" checkbox
	 * on the onboarding intro screen checked when they moved past it.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function subscribe( WP_REST_Request $request ) {
		if ( ! wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
			return new WP_REST_Response( array( 'message' => 'Invalid nonce.' ), 403 );
		}

		DurbinClient::send( DurbinClient::WIZARD_ACTION );

		return new WP_REST_Response( array( 'sent' => true ), 200 );
	}
}
