<?php
/**
 * Settings handling for VAT.
 *
 * @package     EDD\Pro\Admin\Settings
 * @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\Admin\Settings;

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

use EDD\EventManagement\SubscriberInterface;
use EDD\Admin\Settings\Traits\Helpers;
use EDD\Cron\Schedulers\Handler;

/**
 * Settings handling for taxes.
 *
 * @since 3.5.0
 */
class VAT implements SubscriberInterface {

	use Helpers;

	/**
	 * Get the subscribed events.
	 *
	 * @since 3.5.0
	 * @return array
	 */
	public static function get_subscribed_events() {
		return array(
			'edd_settings_sections_taxes'     => 'add_vat_section',
			'admin_notices'                   => 'admin_notices',
			'edd_settings_taxes'              => 'add_vat_settings',
			'edd_settings_gateways'           => array( 'add_invoice_settings', 50 ),
			'edd_settings_taxes-vat_sanitize' => 'sanitize_vat_settings',
		);
	}

	/**
	 * Add the VAT section to the taxes settings page.
	 *
	 * @since 3.5.0
	 * @param array $sections The sections.
	 * @return array
	 */
	public function add_vat_section( $sections ) {
		$sections['vat'] = __( 'EU VAT', 'easy-digital-downloads' );

		return $sections;
	}

	/**
	 * Display a notice if the VAT rates are scheduled to be updated.
	 *
	 * @since 3.5.0
	 * @return void
	 */
	public function admin_notices() {
		if ( ! edd_is_admin_page( 'settings', 'taxes' ) || 'vat' !== filter_input( INPUT_GET, 'section', FILTER_SANITIZE_SPECIAL_CHARS ) ) {
			return;
		}
		if ( ! \EDD\Cron\Events\SingleEvent::next_scheduled( 'edd_get_vat_rates' ) ) {
			return;
		}
		?>
		<div class="notice edd-notice notice-info">
			<p><?php esc_html_e( 'Easy Digital Downloads is checking for the latest VAT Rates in the background. These rates will be imported to your tax rates when complete.', 'easy-digital-downloads' ); ?></p>
		</div>
		<?php
	}

	/**
	 * Add VAT settings.
	 *
	 * @since 3.5.0
	 * @param array $settings The settings array.
	 * @return array
	 */
	public function add_vat_settings( $settings ) {
		$settings['vat'] = array(
			'vat_auto_rates'                      => array(
				'id'      => 'vat_auto_rates',
				'name'    => __( 'Automatic Rates', 'easy-digital-downloads' ),
				'check'   => __( 'Automatically set tax rates for EU countries.', 'easy-digital-downloads' ),
				'type'    => 'checkbox_toggle',
				'desc'    => $this->get_auto_rates_description(),
				'tooltip' => $this->get_auto_rates_tooltip(),
			),
			'edd_vat_purchase_receipt'            => array(
				'id'    => 'edd_vat_purchase_receipt',
				'name'  => __( 'Order Details', 'easy-digital-downloads' ),
				'check' => __( 'Include VAT information on the customer receipt page.', 'easy-digital-downloads' ),
				'type'  => 'checkbox_toggle',
			),
			'edd_vat_reverse_charge_base_country' => array(
				'id'    => 'edd_vat_reverse_charge_base_country',
				'name'  => __( 'Reverse Charge in Home Country?', 'easy-digital-downloads' ),
				'check' => __( 'Allow VAT reverse charge for customers with a valid VAT number who are based in your home country.', 'easy-digital-downloads' ),
				'type'  => 'checkbox_toggle',
			),
			'edd_vat_address_header'              => array(
				'id'   => 'edd_vat_address_header',
				'name' => '<h3>' . __( 'Company Information', 'easy-digital-downloads' ) . '</h3>',
				'desc' => __( 'The following information about your company will be displayed on the order details page and purchase receipt email.', 'easy-digital-downloads' ),
				'type' => 'descriptive_text',
			),
			'edd_vat_company_name'                => array(
				'id'   => 'edd_vat_company_name',
				'name' => __( 'Company Name', 'easy-digital-downloads' ),
				'desc' => __( 'Enter your company name.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_number'                      => array(
				'id'   => 'edd_vat_number',
				'name' => __( 'EU VAT Number', 'easy-digital-downloads' ),
				'desc' => __( 'Enter the registered EU VAT number of your company.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_country'             => array(
				'id'            => 'edd_vat_address_country',
				'name'          => __( 'Country of VAT registration', 'easy-digital-downloads' ),
				'desc'          => __( 'Select the country of your company\'s registered VAT address.', 'easy-digital-downloads' ),
				'type'          => 'select',
				'options'       => $this->get_eu_countries(),
				'chosen'        => true,
				'placeholder'   => __( 'Select a country', 'easy-digital-downloads' ),
				'tooltip_title' => __( 'Country setup', 'easy-digital-downloads' ),
				'tooltip_desc'  => __( 'Select the country that issued your company\'s VAT number. If you are based in Northern Ireland and have a VAT number beginning with XI then you should select "Northern Ireland". If your VAT number begins with EU then you should select "EU MOSS Number"', 'easy-digital-downloads' ),
				'std'           => edd_get_shop_country(),
				'data'          => array(
					'nonce' => wp_create_nonce( 'edd-country-field-nonce' ),
				),
			),
			'edd_uk_vat_number'                   => array(
				'id'   => 'edd_uk_vat_number',
				'name' => __( 'UK VAT Number', 'easy-digital-downloads' ),
				'desc' => __( 'Enter the registered UK VAT number of your company.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_line_1'              => array(
				'id'   => 'edd_vat_address_line_1',
				'name' => __( 'Address Line 1', 'easy-digital-downloads' ),
				'desc' => __( 'Enter line 1 of your company\'s registered VAT address.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_line_2'              => array(
				'id'   => 'edd_vat_address_line_2',
				'name' => __( 'Address Line 2', 'easy-digital-downloads' ),
				'desc' => __( 'Enter line 2 of your company\'s registered VAT address if required.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_city'                => array(
				'id'   => 'edd_vat_address_city',
				'name' => __( 'City / State', 'easy-digital-downloads' ),
				'desc' => __( 'Enter the city / state of your company\'s registered VAT address.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_code'                => array(
				'id'   => 'edd_vat_address_code',
				'name' => __( 'Postal / ZIP Code', 'easy-digital-downloads' ),
				'desc' => __( 'Enter the postal code of your company\'s registered VAT address.', 'easy-digital-downloads' ),
				'type' => 'text',
			),
			'edd_vat_address_invoice'             => array(
				'id'          => 'edd_vat_address_invoice',
				'name'        => __( 'Country', 'easy-digital-downloads' ),
				'desc'        => __( 'Select the country where your business is based. This will be used on invoices.', 'easy-digital-downloads' ),
				'type'        => 'select',
				'options'     => edd_get_country_list(),
				'chosen'      => true,
				'placeholder' => __( 'Select a country', 'easy-digital-downloads' ),
				'std'         => edd_get_shop_country(),
				'data'        => array(
					'nonce' => wp_create_nonce( 'edd-country-field-nonce' ),
				),
			),
		);

		return $settings;
	}

	/**
	 * Add invoice settings.
	 *
	 * @since 3.5.0
	 * @param array $settings The settings array.
	 * @return array
	 */
	public function add_invoice_settings( $settings ) {
		if ( ! array_key_exists( 'edd-invoices', $settings ) ) {
			return $settings;
		}

		$settings['edd-invoices']['edd_vat_show_website_address'] = array(
			'id'    => 'edd_vat_show_website_address',
			'name'  => __( 'Show Website Address', 'easy-digital-downloads' ),
			'check' => __( 'Show your website address on the invoice.', 'easy-digital-downloads' ),
			'type'  => 'checkbox_toggle',
			'class' => $this->get_requires_css_class( 'edd-invoices-disabled', array( 'inverse' ) ),
		);

		$settings['edd-invoices']['edd_vat_company_email'] = array(
			'id'    => 'edd_vat_company_email',
			'name'  => __( 'Company Email', 'easy-digital-downloads' ),
			'desc'  => __( 'Enter the email address that will appear on the invoice.', 'easy-digital-downloads' ),
			'type'  => 'text',
			'class' => $this->get_requires_css_class( 'edd-invoices-disabled', array( 'inverse' ) ),
		);

		return $settings;
	}

	/**
	 * Sanitize the VAT settings.
	 *
	 * @since 3.5.0
	 * @param array $input The input array.
	 * @return array
	 */
	public function sanitize_vat_settings( $input ) {
		if ( ! empty( $input['vat_auto_rates'] ) ) {
			\EDD\Cron\Events\SingleEvent::add(
				time() + MINUTE_IN_SECONDS,
				'edd_get_vat_rates',
			);
		}

		return $input;
	}

	/**
	 * Get the list of EU countries.
	 *
	 * @since 3.5.0
	 * @return array
	 */
	private function get_eu_countries() {
		if ( ! edd_is_admin_page( 'settings', 'taxes' ) ) {
			return array();
		}

		$countries    = array(
			'' => __( 'Select a country', 'easy-digital-downloads' ),
		);
		$eu_countries = \EDD\Pro\Taxes\VAT\Utility::get_country_list( true );
		foreach ( $eu_countries as $country_code => $country_name ) {
			$countries[ $country_code ] = $country_name;
		}

		return $countries;
	}

	/**
	 * Get the tooltip for the automatic rates setting.
	 *
	 * @since 3.5.0
	 * @return array
	 */
	private function get_auto_rates_tooltip() {
		return array(
			'title'   => __( 'Automatic Rates', 'easy-digital-downloads' ),
			'content' => implode(
				'<br />',
				array(
					__( 'This will automatically set tax rates for EU countries based on the current VAT rates.', 'easy-digital-downloads' ),
					__( 'This will not override any existing tax rates you have manually set for these countries.', 'easy-digital-downloads' ),
					__( 'This feature connects to our VAT Rate API to update rates weekly.', 'easy-digital-downloads' ),
				)
			),
		);
	}

	/**
	 * Get the description for the automatic rates setting.
	 * The weekly schedule for checking rates is managed in the EDD\Cron\Components\VATRates class.
	 *
	 * @since 3.5.0
	 * @return string
	 */
	private function get_auto_rates_description() {
		if ( ! edd_is_admin_page( 'settings', 'taxes' ) ) {
			return '';
		}

		if ( ! edd_get_option( 'vat_auto_rates', false ) ) {
			return '';
		}

		$next_weekly_check = Handler::get_scheduler()->next_scheduled( 'edd_pro_weekly_scheduled_events' );
		if ( false !== $next_weekly_check ) {
			return sprintf(
				/* translators: %1$s: date, %2$s: time. */
				__( 'The next tax rates update will be on %1$s at %2$s.', 'easy-digital-downloads' ),
				edd_date_i18n( $next_weekly_check, get_option( 'date_format' ) ),
				edd_date_i18n( $next_weekly_check, get_option( 'time_format' ) )
			);
		}
	}
}
