<?php
/**
 * File Path: includes/metaboxes/class-mbs-metabox-base.php
 *
 * My Book Showroom — Metabox Base Class
 *
 * Non-abstract base for all book-post metabox classes. Provides the
 * verify_save() guard helper that consolidates the three-check pattern
 * (autosave, nonce, capability) duplicated across every metabox save().
 *
 * Usage:
 *
 *   if ( ! $this->verify_save( $post_id, 'mbs_foo_nonce', 'mbs_foo_save' ) ) {
 *       return;
 *   }
 *
 * Extracts: DUP-008 (Session 137).
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

class MBS_Metabox_Base { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Guard a metabox save() call against autosave, bad nonces, and
	 * insufficient capability.
	 *
	 * Returns false (and the caller should return immediately) when any of:
	 *   - WordPress is performing an autosave.
	 *   - The expected nonce field is absent from $_POST.
	 *   - The nonce value fails wp_verify_nonce().
	 *   - The current user cannot edit the given post.
	 *
	 * @param int    $post_id      The post being saved.
	 * @param string $nonce_field  The $_POST key holding the nonce token.
	 * @param string $nonce_action The nonce action registered via wp_nonce_field().
	 * @return bool True when all guards pass; false when any guard fails.
	 */
	protected function verify_save( int $post_id, string $nonce_field, string $nonce_action ): bool {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return false;
		}

		if ( wp_is_post_revision( $post_id ) ) {
			return false;
		}

		if ( ! isset( $_POST[ $nonce_field ] ) ||
			 ! wp_verify_nonce(
				 sanitize_key( wp_unslash( $_POST[ $nonce_field ] ) ),
				 $nonce_action
			 )
		) {
			return false;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return false;
		}

		return true;
	}
}
