<?php

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Plus Addons Dynamic Tag - Product Add to Cart URL
 *
 * Provides a dynamic tag for Elementor to output the current product add to cart url.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Product_Add_To_Cart_URL extends Tag {

    /**
     * Unique dynamic tag name used internally by Elementor.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_name(): string {
		return 'plus-tag-product-add-to-cart-url';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Product Add to Cart URL', 'theplus' );
	}

    /**
     * Registers the group under which this tag will appear.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_group(): array {
		return [ 'plus-opt-woocommerce' ];
	}

    /**
     * Defines the category type (URL) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::URL_CATEGORY,
		];
	}

    /**
     * Indicates that settings panel should be shown (even if empty).
     *
     * @since 6.4.5
     * @return bool
     */
	public function is_settings_required(): bool {
		return true;
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_advanced_section() {}

	/**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {
		$this->add_control(
			'quantity',
			[
				'label'   => esc_html__( 'Quantity', 'theplus' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'default' => 1,
				'min'     => 1,
			]
		);
	}

    /**
     * Render the dynamic product Add to Cart URL on frontend.
     *
     * Gets the current product ID and prints its Add to Cart URL.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		$product_id = get_the_ID();

		if ( ! $product_id ) {
			return;
		}

		$product = wc_get_product( $product_id );

		if ( ! $product ) {
			return;
		}

		$settings = $this->get_settings();
		$quantity = ! empty( $settings['quantity'] ) ? (int) $settings['quantity'] : 1;

		if ( $product->is_type( 'variable' ) ) {
			echo esc_url( get_permalink( $product_id ) );
			return;
		}

		$add_to_cart_url = $product->add_to_cart_url();

		if ( ! $add_to_cart_url ) {
			return;
		}

		$add_to_cart_url = add_query_arg(
			'quantity',
			max( 1, $quantity ),
			$add_to_cart_url
		);

		echo esc_url( $add_to_cart_url );
	}
}
