<?php
/**
 * Utility to get a standard tax rate for a country.
 *
 * @package     EDD\Pro\Taxes\VAT
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.5.0
 */

namespace EDD\Pro\Taxes\VAT;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\Utils\RemoteRequest;
use EDD\Utils\Transient;

/**
 * Standard Rate.
 *
 * @since 3.5.0
 */
class StandardRate {

	/**
	 * The country to get the standard rate for.
	 *
	 * @var string
	 */
	private $country;

	/**
	 * StandardRate constructor.
	 *
	 * @param string $country The country to get the standard rate for.
	 */
	public function __construct( string $country ) {
		$this->country = $country;
	}

	/**
	 * The endpoint for the VAT rates.
	 *
	 * @var string
	 */
	private $endpoint = 'https://services.easydigitaldownloads.com/vat-rates';

	/**
	 * Get the standard tax rate for a country.
	 *
	 * @since 3.5.0
	 * @return float|false
	 */
	public function get() {
		if ( empty( $this->country ) ) {
			return false;
		}

		$transient = new Transient( 'edd_vat_rates' );
		$value     = $transient->get();
		if ( $value ) {
			return $this->get_standard_rate( $value );
		}

		$vat_lookup = new RemoteRequest( $this->endpoint );
		if ( 200 !== $vat_lookup->code ) {
			return false;
		}

		$body = json_decode( $vat_lookup->body, true );
		if ( empty( $body ) || ! is_array( $body ) ) {
			return false;
		}

		$transient->set( $body );

		return $this->get_standard_rate( $body );
	}

	/**
	 * Gets the standard rate for a country from the body array.
	 *
	 * @since 3.5.0
	 * @param array $body The body array from the VAT rates endpoint.
	 * @return float|false
	 */
	private function get_standard_rate( $body ) {
		$countries = wp_list_pluck( $body, 'country_code' );
		if ( empty( $countries ) || ! in_array( strtoupper( $this->country ), $countries, true ) ) {
			return false;
		}

		$key = array_search( strtoupper( $this->country ), $countries, true );
		if ( false !== $key && isset( $body[ $key ]['standard']['rate'] ) ) {
			return floatval( $body[ $key ]['standard']['rate'] );
		}

		return false;
	}
}
