<?php

namespace POPxPMPro\Providers;

use WcElectronInvoice\Providers\OrderItemAbstract;
use WcElectronInvoice\Providers\TaxOrderItemAbstract;

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

class TaxOrderItem extends TaxOrderItemAbstract {

	/**
	 * @var \MemberOrder
	 */
	protected $order_item;


	function get_name() {
		// always return an empty string
		return '';
	}

	function get_total() {
		return $this->order_item->total;
	}

	function get_total_tax() {
		return $this->order_item->tax;
	}

	function get_data() {

		$data = [
			'id'           => $this->get_id(),
			'order_id'     => $this->order_item->id,
			'name'         => $this->get_name(),
			'rate_code'    => $this->get_rate_code(),
			'rate_id'      => $this->get_rate_id(),
			'label'        => $this->get_label(),
			'rate_percent' => $this->get_rate_percent(),
			'tax_total'    => $this->get_total_tax(),
			'compound'     => '',
			'meta_data'    => array(),
			'provider'     => 'pmpro',
		];

		return $data;
	}

	public function get_rate_code() {
		$business_address   = get_option( 'pmpro_business_address', [] );
		$merchantVatCountry = $business_address['country'] ?? '';
		if ( empty( $merchantVatCountry ) ) {
			return '';
		}

		return sprintf( '%1$s-%2$s-%3$s', $merchantVatCountry, 'IVA', $this->get_id() );
	}

	public function get_rate_id() {
		return 1;
	}

	public function get_label() {
		return esc_html__( 'IVA', WC_EL_INV_TEXTDOMAIN );
	}

	/**
	 * @inheritDoc
	 */
	function get_rate_percent() {
		$tax_rate = get_pmpro_membership_order_meta( $this->order_item->id, 'pop_tax_rate', true );
		if ( empty( $tax_rate ) ) {
			// calculate on the fly
			$subtotal = floatval( $this->order_item->subtotal );
			$taxes    = floatval( $this->get_total_tax() );
			$tax_rate = number_format( $taxes / $subtotal * 100, 0 );
		}

		return $tax_rate;
	}

	function get_product_id() {
		return 0;
	}

	function get_id() {
		// PMPro doesn't have a tax id
		// so we return 1
		return 1;
	}
}
