<?php
/**
 * ERENQVP_Ajax — admin-ajax endpoints (all nonce- and capability-guarded).
 *
 * @package ErenLabs\QuickVariableProducts
 */

defined( 'ABSPATH' ) || exit;

class ERENQVP_Ajax {

	/**
	 * Register endpoints.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'wp_ajax_erenqvp_attr_terms', array( __CLASS__, 'attr_terms' ) );
		add_action( 'wp_ajax_erenqvp_create_attribute', array( __CLASS__, 'create_attribute' ) );
		add_action( 'wp_ajax_erenqvp_gen_sku', array( __CLASS__, 'gen_sku' ) );
		add_action( 'wp_ajax_erenqvp_create_product', array( __CLASS__, 'create_product' ) );
		add_action( 'wp_ajax_erenqvp_dismiss_tour', array( __CLASS__, 'dismiss_tour' ) );
	}

	/**
	 * Permanently dismiss the first-run onboarding card for the current user.
	 *
	 * @return void
	 */
	public static function dismiss_tour() {
		self::guard();
		update_user_meta( get_current_user_id(), 'erenqvp_tour_done', 1 );
		wp_send_json_success();
	}

	/**
	 * Shared guard: valid nonce + capability. Dies with a JSON error otherwise.
	 *
	 * @return void
	 */
	private static function guard() {
		if ( ! check_ajax_referer( 'erenqvp_ajax', 'nonce', false ) ) {
			wp_send_json_error( array( 'msg' => __( 'Security check failed. Reload the page.', 'quick-variable-products' ) ), 403 );
		}
		if ( ! current_user_can( ERENQVP_CAP ) ) {
			wp_send_json_error( array( 'msg' => __( 'You do not have permission to do this.', 'quick-variable-products' ) ), 403 );
		}
	}

	/**
	 * Terms of a given attribute taxonomy.
	 *
	 * @return void
	 */
	public static function attr_terms() {
		self::guard();
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in self::guard().
		$taxonomy = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
		wp_send_json_success( array( 'terms' => ERENQVP_Attributes::terms( $taxonomy ) ) );
	}

	/**
	 * Create a new global attribute from a label and return it (so the UI can use it at once).
	 *
	 * @return void
	 */
	public static function create_attribute() {
		self::guard();
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			wp_send_json_error( array( 'msg' => __( 'You do not have permission to manage product attributes.', 'quick-variable-products' ) ), 403 );
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in self::guard().
		$label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';
		$res   = ERENQVP_Attributes::create_global( $label );
		if ( is_wp_error( $res ) ) {
			wp_send_json_error( array( 'msg' => $res->get_error_message() ) );
		}
		wp_send_json_success( $res );
	}

	/**
	 * Generate a single unique SKU/barcode.
	 *
	 * @return void
	 */
	public static function gen_sku() {
		self::guard();
		wp_send_json_success( array( 'sku' => ERENQVP_Barcode::generate() ) );
	}

	/**
	 * Create the product from the matrix payload.
	 *
	 * @return void
	 */
	public static function create_product() {
		self::guard();
		// A JSON string cannot be pre-sanitized without corrupting it, so the raw body
		// is decoded first and then EVERY value is sanitized on the next line (and again,
		// field-by-field, inside ERENQVP_Product::create_product()).
		// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified in self::guard(); decoded payload sanitized immediately below via ERENQVP_Product::sanitize_create_payload().
		$raw = ( isset( $_POST['payload'] ) && is_string( $_POST['payload'] ) ) ? wp_unslash( $_POST['payload'] ) : '';
		$d   = json_decode( $raw, true );
		if ( ! is_array( $d ) ) {
			wp_send_json_error( array( 'msg' => __( 'Invalid request payload.', 'quick-variable-products' ) ) );
		}
		$d = ERENQVP_Product::sanitize_create_payload( $d ); // Sanitize the decoded input as early as possible.
		if ( ! current_user_can( 'edit_products' ) || ( 'draft' !== ( $d['status'] ?? '' ) && ! current_user_can( 'publish_products' ) ) ) {
			wp_send_json_error( array( 'msg' => __( 'You do not have permission to create or publish products.', 'quick-variable-products' ) ), 403 );
		}
		$res = ERENQVP_Product::create_product( $d );
		if ( empty( $res['ok'] ) ) {
			wp_send_json_error( array( 'msg' => $res['msg'] ?? __( 'Could not create the product.', 'quick-variable-products' ) ) );
		}
		if ( class_exists( 'ERENQVP_Admin' ) ) {
			ERENQVP_Admin::remember_prefs( $d );
		}
		// A first successful product means the user no longer needs the onboarding card.
		update_user_meta( get_current_user_id(), 'erenqvp_tour_done', 1 );

		// Count successes; at the third one, surface a single review invitation — once, ever.
		$count = (int) get_user_meta( get_current_user_id(), 'erenqvp_create_count', true ) + 1;
		update_user_meta( get_current_user_id(), 'erenqvp_create_count', $count );
		if ( $count >= 3 && ! get_user_meta( get_current_user_id(), 'erenqvp_review_ask_done', true ) ) {
			update_user_meta( get_current_user_id(), 'erenqvp_review_ask_done', 1 );
			$res['review_ask'] = true;
		}

		wp_send_json_success( $res );
	}
}
