<?php
/**
 * One request gate for AJAX/REST-style handlers: nonce + capability + consistent
 * JSON error. Deliberately NOT a REST/AJAX framework — a single helper that the
 * scoping pipeline must prove still works after prefixing.
 *
 * @package Hakki\WooCore
 */

namespace ErenLabs\SmartCategories\Vendor\Hakki\WooCore\Security;

use ErenLabs\SmartCategories\Vendor\Hakki\WooCore\Core;

defined( 'ABSPATH' ) || exit;

final class Request {

	/** @var Core */
	private $core;

	public function __construct( Core $core ) {
		$this->core = $core;
	}

	/**
	 * Verify a nonce + capability for the current request. On failure, send a
	 * consistent JSON error and stop. Returns true when the caller may proceed.
	 *
	 * @param string $capability Required capability.
	 * @param string $action     Nonce action suffix (slug-scoped internally).
	 * @param string $nonce_field POST/GET field holding the nonce.
	 */
	public function verify( string $capability, string $action = 'action', string $nonce_field = '_wpnonce' ): bool {
		$nonce = isset( $_REQUEST[ $nonce_field ] )
			? sanitize_text_field( wp_unslash( $_REQUEST[ $nonce_field ] ) )
			: '';

		if ( ! wp_verify_nonce( $nonce, $this->core->nonce_action( $action ) ) ) {
			$this->fail( 'invalid_nonce', __( 'Security check failed.', 'smart-categories-for-woocommerce' ), 403 );
			return false;
		}
		if ( ! current_user_can( $capability ) ) {
			$this->fail( 'forbidden', __( 'You are not allowed to do this.', 'smart-categories-for-woocommerce' ), 403 );
			return false;
		}
		return true;
	}

	/**
	 * Create a slug-scoped nonce for output in a form/JS.
	 */
	public function create_nonce( string $action = 'action' ): string {
		return wp_create_nonce( $this->core->nonce_action( $action ) );
	}

	/**
	 * Consistent JSON error envelope.
	 */
	public function fail( string $code, string $message, int $status = 400 ): void {
		wp_send_json_error(
			array(
				'code'    => $code,
				'message' => $message,
			),
			$status
		);
	}

	/**
	 * Consistent JSON success envelope.
	 *
	 * @param mixed $data
	 */
	public function ok( $data = null ): void {
		wp_send_json_success( $data );
	}
}
