<?php
/**
 * File Path: includes/helpers/class-mbs-book-defaults.php
 *
 * Book Creation Defaults
 *
 * Applies stored default values to new MBS book posts at the moment
 * WordPress creates the auto-draft, so the editor renders with values
 * pre-populated without any user action required.
 *
 * @package My_Book_Showroom
 * @since   1.2.0
 */

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

/**
 * Class MBS_Book_Defaults
 *
 * Self-registering service. Instantiated in MBS_Plugin::load_core_services().
 * Owns all logic for applying saved default field values to new MBS book
 * posts before the editor renders.
 *
 * @since 1.2.0
 */
class MBS_Book_Defaults {

	/**
	 * Register WordPress hooks.
	 *
	 * @since 1.2.0
	 */
	public function __construct() {
		add_action( 'wp_insert_post', array( $this, 'apply_default_author' ), 10, 3 );
	}

	/**
	 * Pre-assign the default author taxonomy term on new book auto-drafts.
	 *
	 * Fires on wp_insert_post. Guards ensure this only runs once, for genuinely
	 * new MBS book posts created via the WordPress admin Add New screen. The
	 * auto-draft status is exclusive to that flow — programmatic inserts always
	 * set an explicit status and are never affected by this method.
	 *
	 * @param int     $post_id The post ID.
	 * @param WP_Post $post    The post object.
	 * @param bool    $update  True if updating an existing post, false on insert.
	 * @return void
	 * @since 1.2.0
	 */
	public function apply_default_author( int $post_id, WP_Post $post, bool $update ): void {
		if ( $update ) {
			return;
		}
		if ( MBS_POST_TYPE !== $post->post_type ) {
			return;
		}
		if ( 'auto-draft' !== $post->post_status ) {
			return;
		}

		$term_id = (int) get_option( 'mbs_setting_default_author_term', 0 );
		if ( $term_id <= 0 ) {
			return;
		}

		$term = get_term( $term_id, MBS_TAX_AUTHOR );
		if ( ! $term || is_wp_error( $term ) ) {
			return;
		}

		$existing = wp_get_object_terms( $post_id, MBS_TAX_AUTHOR, array( 'fields' => 'ids' ) );
		if ( ! empty( $existing ) && ! is_wp_error( $existing ) ) {
			return;
		}

		wp_set_object_terms( $post_id, $term_id, MBS_TAX_AUTHOR );
	}
}
