<?php
namespace Pay4All\Pro\Admin\Newsletter;

use Pay4All\Pro\Domain\Newsletter;
use Pay4All\Pro\PostTypes;

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

/**
 * Injects a « Create newsletter for this product / promo » shortcut in
 * the Publish sidebar metabox on the product + promo edit screens.
 * Clicking it lands on the new-newsletter screen with the template kind
 * + source id pre-forwarded in the URL, so MetaBoxes seeds the picker
 * + editor defaults from those hints.
 *
 * Uses `post_submitbox_misc_actions` (fires inside the Publish metabox
 * just below the Update button) so the shortcut ends up next to the
 * other primary actions rather than buried at the bottom of the
 * left-column data metabox.
 */
final class QuickCreateButton {

	public static function register() : void {
		add_action( 'post_submitbox_misc_actions', [ self::class, 'render_in_publish_box' ] );
	}

	/**
	 * @param \WP_Post $post
	 */
	public static function render_in_publish_box( $post ) : void {
		if ( ! $post instanceof \WP_Post ) { return; }
		if ( ! current_user_can( 'manage_options' ) ) { return; }

		$post_type = (string) $post->post_type;
		// Same short label for both surfaces — the context (« I'm on the
		// product edit screen ») makes the target of the shortcut
		// obvious ; a longer « for this product » was redundant.
		if ( $post_type === 'p4all_product' ) {
			self::render_button(
				Newsletter::KIND_PRODUCT,
				(int) $post->ID,
				__( 'Create a newsletter', 'pay4all-pro' )
			);
			return;
		}
		if ( $post_type === 'p4all_promo' ) {
			self::render_button(
				Newsletter::KIND_PROMO,
				(int) $post->ID,
				__( 'Create a newsletter', 'pay4all-pro' )
			);
		}
	}

	private static function render_button( string $kind, int $source_id, string $label ) : void {
		$url = add_query_arg(
			[
				'post_type'          => PostTypes::NEWSLETTER,
				'p4all_nl_template'  => $kind,
				'p4all_nl_source'    => $source_id,
			],
			admin_url( 'post-new.php' )
		);
		?>
		<div class="misc-pub-section p4all-nl-quick-create" style="padding-top:8px;">
			<a href="<?php echo esc_url( $url ); ?>" class="button" style="width:100%;text-align:center;">
				<span class="dashicons dashicons-email-alt" style="vertical-align:middle;margin-right:4px;"></span>
				<?php echo esc_html( $label ); ?>
			</a>
		</div>
		<?php
	}
}
