<?php
defined( 'ABSPATH' ) || exit;

/**
 * Product-level settings for TukiFlow Buy Now behavior.
 */
class TFDC_Product_Settings {

	/** @var self|null */
	private static $instance = null;

	const TAB_KEY                   = 'tfdc_product_settings';
	const META_DISABLE_BUY_NOW      = '_tfdc_disable_buy_now';
	const META_DISABLE_ADD_TO_CART  = '_tfdc_disable_add_to_cart';
	const META_DEFAULT_QUANTITY     = '_tfdc_default_quantity';
	const META_BUTTON_TEXT          = '_tfdc_button_text';
	const NONCE_ACTION              = 'tfdc_save_product_settings';
	const NONCE_NAME                = 'tfdc_product_settings_nonce';

	/**
	 * Get the singleton instance.
	 *
	 * @return self
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		if ( is_admin() ) {
			add_filter( 'woocommerce_product_data_tabs', array( $this, 'register_product_tab' ), 15 );
			add_action( 'woocommerce_product_data_panels', array( $this, 'render_product_panel' ) );
			add_action( 'woocommerce_admin_process_product_object', array( $this, 'save_product_settings' ) );
		}

		add_filter( 'woocommerce_quantity_input_args', array( $this, 'filter_quantity_input_args' ), 10, 2 );
	}

	/**
	 * Get normalized product settings.
	 *
	 * @param int $product_id Product ID.
	 * @return array
	 */
	public static function get_settings( $product_id ) {
		$product_id = self::resolve_product_meta_id( $product_id );

		return array(
			'disable_buy_now'     => 'yes' === get_post_meta( $product_id, self::META_DISABLE_BUY_NOW, true ),
			'disable_add_to_cart' => 'yes' === get_post_meta( $product_id, self::META_DISABLE_ADD_TO_CART, true ),
			'default_quantity'    => max( 1, absint( get_post_meta( $product_id, self::META_DEFAULT_QUANTITY, true ) ?: 1 ) ),
			'button_text'         => sanitize_text_field( (string) get_post_meta( $product_id, self::META_BUTTON_TEXT, true ) ),
		);
	}

	/**
	 * Whether Buy Now is disabled for a product.
	 *
	 * @param int $product_id Product ID.
	 * @return bool
	 */
	public static function is_buy_now_disabled( $product_id ) {
		$settings = self::get_settings( $product_id );
		return ! empty( $settings['disable_buy_now'] );
	}

	/**
	 * Whether Add to Cart is disabled on the single product page.
	 *
	 * @param int $product_id Product ID.
	 * @return bool
	 */
	public static function is_single_add_to_cart_disabled( $product_id ) {
		$settings = self::get_settings( $product_id );
		return ! empty( $settings['disable_add_to_cart'] );
	}

	/**
	 * Get the default quantity for a product.
	 *
	 * @param int $product_id Product ID.
	 * @return int
	 */
	public static function get_default_quantity( $product_id ) {
		$settings = self::get_settings( $product_id );
		return absint( $settings['default_quantity'] );
	}

	/**
	 * Get the product-specific button text.
	 *
	 * @param int $product_id Product ID.
	 * @return string
	 */
	public static function get_button_text( $product_id ) {
		$settings = self::get_settings( $product_id );
		return $settings['button_text'];
	}

	/**
	 * Add the TukiFlow tab right after WooCommerce's General tab.
	 *
	 * @param array $tabs Existing tabs.
	 * @return array
	 */
	public function register_product_tab( $tabs ) {
		$new_tab = array(
			self::TAB_KEY => array(
				'label'    => __( 'TukiFlow', 'tukiflow-direct-checkout-woocommerce' ),
				'target'   => self::TAB_KEY . '_data',
				'class'    => array(),
				'priority' => 11,
			),
		);

		$ordered_tabs = array();

		foreach ( $tabs as $key => $tab ) {
			$ordered_tabs[ $key ] = $tab;

			if ( 'general' === $key ) {
				$ordered_tabs = array_merge( $ordered_tabs, $new_tab );
			}
		}

		if ( ! isset( $ordered_tabs[ self::TAB_KEY ] ) ) {
			$ordered_tabs = array_merge( $ordered_tabs, $new_tab );
		}

		return $ordered_tabs;
	}

	/**
	 * Render the product data panel fields.
	 */
	public function render_product_panel() {
		global $post;

		if ( ! $post instanceof WP_Post || 'product' !== $post->post_type ) {
			return;
		}

		$settings = self::get_settings( $post->ID );
		?>
		<div id="<?php echo esc_attr( self::TAB_KEY . '_data' ); ?>" class="panel woocommerce_options_panel hidden">
			<?php wp_nonce_field( self::NONCE_ACTION, self::NONCE_NAME ); ?>
			<div class="options_group">
				<?php
				woocommerce_wp_checkbox(
					array(
						'id'          => self::META_DISABLE_BUY_NOW,
						'label'       => __( 'Disable Buy Now button', 'tukiflow-direct-checkout-woocommerce' ),
						'description' => __( 'Hide the TukiFlow Buy Now button for this product.', 'tukiflow-direct-checkout-woocommerce' ),
						'desc_tip'    => true,
						'value'       => $settings['disable_buy_now'] ? 'yes' : 'no',
						'cbvalue'     => 'yes',
					)
				);

				woocommerce_wp_checkbox(
					array(
						'id'          => self::META_DISABLE_ADD_TO_CART,
						'label'       => __( 'Disable Add to Cart button', 'tukiflow-direct-checkout-woocommerce' ),
						'description' => __( 'Hide WooCommerce\'s Add to Cart button on the single product page for this product.', 'tukiflow-direct-checkout-woocommerce' ),
						'desc_tip'    => true,
						'value'       => $settings['disable_add_to_cart'] ? 'yes' : 'no',
						'cbvalue'     => 'yes',
					)
				);

				woocommerce_wp_text_input(
					array(
						'id'                => self::META_DEFAULT_QUANTITY,
						'label'             => __( 'Default quantity', 'tukiflow-direct-checkout-woocommerce' ),
						'description'       => __( 'Used as the initial quantity on the product page and when Buy Now runs without a quantity field.', 'tukiflow-direct-checkout-woocommerce' ),
						'desc_tip'          => true,
						'type'              => 'number',
						'value'             => $settings['default_quantity'],
						'custom_attributes' => array(
							'min'  => '1',
							'step' => '1',
						),
					)
				);

				woocommerce_wp_text_input(
					array(
						'id'          => self::META_BUTTON_TEXT,
						'label'       => __( 'Button text', 'tukiflow-direct-checkout-woocommerce' ),
						'description' => __( 'Overrides the global Buy Now text for this product only.', 'tukiflow-direct-checkout-woocommerce' ),
						'desc_tip'    => true,
						'value'       => $settings['button_text'],
					)
				);
				?>
			</div>
			<div class="options_group">
				<p class="form-field">
					<label><?php esc_html_e( 'Create Landing Page', 'tukiflow-direct-checkout-woocommerce' ); ?></label>
					<span class="wrap">
						<button type="button" class="button" disabled="disabled" aria-disabled="true" style="background:#6f43df;border-color:#6f43df;color:#ffffff;box-shadow:none;">
							<?php esc_html_e( 'Create Landing Page', 'tukiflow-direct-checkout-woocommerce' ); ?>
						</button>
						<span style="display:inline-block;margin-left:8px;padding:2px 8px;border-radius:999px;background:#f6f0ff;color:#6f43df;font-size:11px;font-weight:600;letter-spacing:0.02em;text-transform:uppercase;">
							<?php esc_html_e( 'Coming Soon', 'tukiflow-direct-checkout-woocommerce' ); ?>
						</span>
						<span class="description" style="display:block;margin-top:8px;">
							<?php esc_html_e( 'Create a landing page directly from the product editor and launch a faster checkout flow for this product.', 'tukiflow-direct-checkout-woocommerce' ); ?>
						</span>
					</span>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * Save product tab values.
	 *
	 * @param WC_Product $product Product object.
	 */
	public function save_product_settings( $product ) {
		if ( ! $product instanceof WC_Product ) {
			return;
		}

		if ( ! isset( $_POST[ self::NONCE_NAME ] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ self::NONCE_NAME ] ) ), self::NONCE_ACTION ) ) {
			return;
		}

		$product->update_meta_data(
			self::META_DISABLE_BUY_NOW,
			isset( $_POST[ self::META_DISABLE_BUY_NOW ] ) ? 'yes' : 'no'
		);

		$product->update_meta_data(
			self::META_DISABLE_ADD_TO_CART,
			isset( $_POST[ self::META_DISABLE_ADD_TO_CART ] ) ? 'yes' : 'no'
		);

		$default_quantity = isset( $_POST[ self::META_DEFAULT_QUANTITY ] ) ? absint( wp_unslash( $_POST[ self::META_DEFAULT_QUANTITY ] ) ) : 1;
		$product->update_meta_data( self::META_DEFAULT_QUANTITY, max( 1, $default_quantity ) );

		$button_text = isset( $_POST[ self::META_BUTTON_TEXT ] ) ? sanitize_text_field( wp_unslash( $_POST[ self::META_BUTTON_TEXT ] ) ) : '';

		if ( '' === $button_text ) {
			$product->delete_meta_data( self::META_BUTTON_TEXT );
		} else {
			$product->update_meta_data( self::META_BUTTON_TEXT, $button_text );
		}
	}

	/**
	 * Apply product-level default quantity on single product pages.
	 *
	 * @param array      $args    Quantity args.
	 * @param WC_Product $product Product object.
	 * @return array
	 */
	public function filter_quantity_input_args( $args, $product ) {
		if ( is_admin() || ! is_product() || ! $product instanceof WC_Product ) {
			return $args;
		}

		$queried_product_id = absint( get_queried_object_id() );
		if ( ! $queried_product_id || self::resolve_product_meta_id( $product->get_id() ) !== self::resolve_product_meta_id( $queried_product_id ) ) {
			return $args;
		}

		$default_quantity = self::get_default_quantity( $product->get_id() );

		if ( $default_quantity > 1 ) {
			$args['input_value'] = $default_quantity;
		}

		return $args;
	}

	/**
	 * Resolve variation IDs to their parent product for shared settings.
	 *
	 * @param int $product_id Product or variation ID.
	 * @return int
	 */
	private static function resolve_product_meta_id( $product_id ) {
		$product_id = absint( $product_id );

		if ( ! $product_id ) {
			return 0;
		}

		$product = wc_get_product( $product_id );
		if ( $product && $product->is_type( 'variation' ) ) {
			return absint( $product->get_parent_id() ) ?: $product_id;
		}

		return $product_id;
	}
}
