<?php
/**
 * Buy Now extension — single-product page rendering.
 *
 * Renders the Buy Now button on the classic single-product page: a submit
 * button inside the native add-to-cart form. WooCommerce validates variation +
 * quantity; the redirect engine sends the shopper to checkout on submit.
 *
 * @package Brandy\WooCommerce\BuyNow
 */

namespace Brandy\WooCommerce\BuyNow;

use Brandy\Traits\SingletonTrait;

defined( 'ABSPATH' ) || exit;

class ClassicRenderer {

	use SingletonTrait;

	protected function __construct() {
		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'render_single' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'register_style' ) );
	}

	/**
	 * Single-product page: submit button inside the native form.cart.
	 */
	public function render_single() {
		global $product;

		if ( ! $product instanceof \WC_Product || ! $product->is_purchasable() ) {
			return;
		}
		if ( ! $product->is_type( 'simple' ) && ! $product->is_type( 'variable' ) ) {
			return;
		}

		$this->enqueue_style();

		// The button carries the native `add-to-cart` id itself (the simple
		// add-to-cart template puts the id only on its own submit button, so a
		// separate button would submit no product). `formaction` adds the
		// buy-now marker only when THIS button is clicked, leaving the theme's
		// normal Add to cart button untouched. WooCommerce validates variation
		// and quantity from the surrounding form as usual.
		//
		// The `single_add_to_cart_button` class opts the button into WooCommerce's
		// variation handling: on variable products, variations.js disables it
		// (and blocks the click with a "select options" prompt) until a valid,
		// purchasable variation is chosen — exact parity with Add to cart. On
		// simple products there is no variations form, so the class is inert.
		$buy_now_action = add_query_arg( 'brandy_buy_now', '1', get_permalink( $product->get_id() ) );

		printf(
			'<button type="submit" name="add-to-cart" value="%1$d" formaction="%2$s" class="wp-element-button single_add_to_cart_button brandy-buy-now-button">%3$s</button>',
			absint( $product->get_id() ),
			esc_url( $buy_now_action ),
			esc_html( Settings::label() )
		);
	}

	/**
	 * Register the button stylesheet (enqueued on demand when the button renders).
	 */
	public function register_style() {
		wp_register_style(
			'brandy-buy-now',
			BRANDY_TEMPLATE_URL . '/inc/WooCommerce/BuyNow/buy-now.css',
			array(),
			BRANDY_SCRIPT_VERSION
		);
	}

	private function enqueue_style() {
		if ( ! wp_style_is( 'brandy-buy-now', 'enqueued' ) ) {
			wp_enqueue_style( 'brandy-buy-now' );
		}
	}
}
