<?php
namespace Tooto_Elementor;

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

class Discount_Table_Shortcode {

	/**
	 * Instance of this class.
	 *
	 * @var Discount_Table_Shortcode
	 */
	private static $instance = null;

	/**
	 * Get instance of this class.
	 *
	 * @return Discount_Table_Shortcode
	 */
	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		\add_shortcode( 'tooto_discount_table', array( $this, 'render_shortcode' ) );
	}

	/**
	 * Render the shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string Shortcode output.
	 */
	public function render_shortcode( $atts ) {
		$atts = \shortcode_atts(
			array(
				'product_id' => '',
			),
			$atts,
			'tooto_discount_table'
		);

		$product_id = $atts['product_id'];

		// If no product ID is provided, try to get the current global product.
		if ( empty( $product_id ) ) {
			global $product;
			if ( $product instanceof \WC_Product ) {
				$product_id = $product->get_id();
			}
		}

		if ( empty( $product_id ) ) {
			return '';
		}

		$product = \wc_get_product( $product_id );

		if ( ! $product ) {
			return '';
		}

		// Capture the output of the Discount Rules plugin's table.
		\ob_start();
		\do_action( 'advanced_woo_discount_rules_load_discount_table', $product );
		$original_html = \ob_get_clean();

		if ( empty( $original_html ) ) {
			return '';
		}

		// Parse the HTML to extract data.
		$data = $this->parse_discount_table_html( $original_html );

		if ( empty( $data ) ) {
			return ''; // Fallback or empty if parsing fails.
		}

		// Render the custom horizontal table.
		return $this->render_custom_table( $data );
	}

	/**
	 * Parse the original HTML table to extract ranges and prices.
	 *
	 * @param string $html Original HTML.
	 * @return array Extracted data.
	 */
	private function parse_discount_table_html( $html ) {
		$data = array();

		// Use DOMDocument to parse HTML.
		$dom = new \DOMDocument();
		// Suppress warnings for invalid HTML (common in partials).
		libxml_use_internal_errors( true );
		// Hack to handle UTF-8 correctly.
		$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $html );
		libxml_clear_errors();

		$xpath = new \DOMXPath( $dom );

		// Find all rows in the table body.
		$rows = $xpath->query( '//tr[contains(@class, "wdr_bulk_table_tr")]' );

		foreach ( $rows as $row ) {
			$item = array();

			// Extract Title/Range (e.g., "1 ~ 47").
			// Try .wdr_bulk_title first, then .wdr_bulk_range.
			$title_node = $xpath->query( './/*[contains(@class, "wdr_bulk_title")]', $row )->item( 0 );
			if ( $title_node ) {
				$item['range'] = trim( $title_node->textContent );
			} else {
				$range_node = $xpath->query( './/*[contains(@class, "wdr_bulk_range")]', $row )->item( 0 );
				if ( $range_node ) {
					$item['range'] = trim( $range_node->textContent );
				} else {
					$item['range'] = '';
				}
			}

			// Extract Price.
			// The user wants the discounted unit price, which is often hidden in .wdr_table_discounted_price.
			// Or sometimes visible in .wdr_table_discounted_value if it's a fixed price.
			// Logic: Look for .wdr_table_discounted_price first.
			$price_node = $xpath->query( './/*[contains(@class, "wdr_table_discounted_price")]', $row )->item( 0 );
			
			if ( $price_node && ! empty( trim( $price_node->textContent ) ) ) {
				$item['price'] = trim( $price_node->textContent );
			} else {
				// Fallback to .wdr_table_discounted_value
				$value_node = $xpath->query( './/*[contains(@class, "wdr_table_discounted_value")]', $row )->item( 0 );
				if ( $value_node ) {
					$item['price'] = trim( $value_node->textContent );
				} else {
					$item['price'] = '';
				}
			}

			if ( ! empty( $item['range'] ) && ! empty( $item['price'] ) ) {
				$data[] = $item;
			}
		}

		return $data;
	}

	/**
	 * Render the custom horizontal table HTML.
	 *
	 * @param array $data Extracted data.
	 * @return string HTML output.
	 */
	private function render_custom_table( $data ) {
		if ( empty( $data ) ) {
			return '';
		}

		ob_start();
		?>
		<div class="tooto-discount-table-wrapper">
			<div class="tooto-discount-table">
				<div class="tooto-dt-row tooto-dt-header-row">
					<div class="tooto-dt-cell tooto-dt-head">Quantity</div>
					<?php foreach ( $data as $item ) : ?>
						<div class="tooto-dt-cell tooto-dt-range"><?php echo \esc_html( $item['range'] ); ?></div>
					<?php endforeach; ?>
				</div>
				<div class="tooto-dt-row tooto-dt-price-row">
					<div class="tooto-dt-cell tooto-dt-head">Unit Price</div>
					<?php foreach ( $data as $item ) : ?>
						<div class="tooto-dt-cell tooto-dt-price"><?php echo \wp_kses_post( $item['price'] ); ?></div>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
