<?php
/**
 * File Path: includes/admin/class-mbs-nudge-base.php
 *
 * My Book Showroom — Abstract Nudge Notice Base
 *
 * Shared AJAX dismiss handler for milestone nudge notices (DUP-008).
 * Subclasses provide the nonce action string, milestone definitions,
 * and the DISMISSED_META_PREFIX constant used via late static binding.
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

abstract class MBS_Nudge_Base {

	/**
	 * Return the nonce action string for this nudge type.
	 *
	 * @return string Nonce action used by check_ajax_referer().
	 * @since 1.1.0
	 */
	abstract protected function get_nonce_action(): string;

	/**
	 * Return the milestone definitions for this nudge type.
	 *
	 * @return array<string, array{days: int, heading: string, body: string}>
	 * @since 1.1.0
	 */
	abstract protected static function milestones(): array;

	/**
	 * AJAX handler — verify nonce, validate milestone, store per-user dismissal.
	 *
	 * Called by subclass-registered wp_ajax_ hooks. Uses late static binding
	 * for DISMISSED_META_PREFIX (defined as a const in each subclass) and
	 * for milestones() (defined as protected static in each subclass).
	 *
	 * @return void
	 * @since  1.1.0
	 */
	public function handle_ajax_dismiss(): void {
		check_ajax_referer( $this->get_nonce_action(), 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Forbidden' ), 403 );
		}

		$milestone = sanitize_key( wp_unslash( $_POST['milestone'] ?? '' ) );
		$valid     = array_keys( static::milestones() );

		if ( ! in_array( $milestone, $valid, true ) ) {
			wp_send_json_error( array( 'message' => 'Invalid milestone' ), 400 );
		}

		update_user_meta(
			get_current_user_id(),
			static::DISMISSED_META_PREFIX . $milestone,
			'1'
		);

		wp_send_json_success();
	}
}
