<?php

namespace WcElectronInvoice\WooCommerce\Providers;
use WcElectronInvoice\Providers\TaxProviderAbstract;

defined( 'ABSPATH' ) || die( 'Not allowed.' );

class TaxesProvider extends TaxProviderAbstract {

	function get_rates( $tax_class = '', $customer = null ) {
		return \WC_Tax::get_rates( $tax_class, $customer );
	}

	function get_base_tax_rates() {
		return \WC_Tax::get_base_tax_rates();
	}

	function get_rates_for_tax_class( $tax_class ) {
		return \WC_Tax::get_rates_for_tax_class( $tax_class );
	}

 	function get_shipping_tax_rates() {
		return \WC_Tax::get_shipping_tax_rates();
	}

	/**
	 * Get tax rate for a shipping item.
	 * Uses tax_rate_id from item taxes data when tax_class is empty.
	 * Handles plugins that don't set tax_class on shipping items (e.g. table_rate).
	 *
	 * @param mixed $item Expected to be WC_Order_Item_Shipping
	 * @return object|null
	 */
	function get_shipping_item_tax_rate($item) {
		$taxRateId = $this->get_shipping_item_tax_rate_id($item);
		if (null !== $taxRateId) {
			$taxRateObj = \WC_Tax::_get_tax_rate($taxRateId);
			if ($taxRateObj && is_array($taxRateObj)) {
				return (object) $taxRateObj;
			}
		}

		// Fallback: if no tax data found, use tax_class-based method
		if (! is_object($item) || ! method_exists($item, 'get_tax_class')) {
			return null;
		}

		$taxClass = $item->get_tax_class();
		if (! empty($taxClass) || '0' === $taxClass) {
			$taxes = \WC_Tax::get_rates_for_tax_class($taxClass);
			if (! empty($taxes)) {
				return reset($taxes);
			}
		}

		return null;
	}

	/**
	 * @inheritDoc
	 */
	function get_shipping_item_tax_rate_id($item) {
		if (! is_object($item) || ! method_exists($item, 'get_taxes')) {
			return null;
		}

		$itemTaxData = $item->get_taxes();
		if (empty($itemTaxData['total']) || ! is_array($itemTaxData['total'])) {
			return null;
		}

		$matchedRateId = null;
		foreach ($itemTaxData['total'] as $taxRateId => $taxAmount) {
			if (! is_numeric($taxRateId)) {
				continue;
			}

			$matchedRateId = (int) $taxRateId;
			if (0.0 !== (float) $taxAmount) {
				return $matchedRateId;
			}
		}

		return $matchedRateId;
	}

	/**
	 * @inheritDoc
	 */
	function is_tax_enabled() {
		return get_option( 'woocommerce_calc_taxes' );
	}

	/**
	 * @inheritDoc
	 */
	function name() {
		return 'woocommerce';
	}
}
