<?php

namespace Objectiv\Plugins\Checkout\Compatibility\Plugins;

use Objectiv\Plugins\Checkout\Compatibility\CompatibilityAbstract;

class Fattureincloud extends CompatibilityAbstract {
	public function is_available(): bool {
		return function_exists( 'billing_fields_woofc' );
	}

	public function run_immediately() {
		add_filter( 'woocommerce_update_order_review_fragments', [ $this, 'update_checkout_fragments' ], 1000 );
	}

	public function run() {
		remove_filter( 'woocommerce_billing_fields', 'billing_fields_woofc', 10 );
		add_action( 'cfw_checkout_payment_method_tab', [ $this, 'output_fields' ], 21 );
	}

	public function get_fields_wrapped() {
		return '<div id="fattureincloud-fields">' . $this->get_fields() . '</div>';
	}

	public function output_fields() {
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $this->get_fields_wrapped(); // output is already sanitized through woocommerce_form_field
	}

	public function get_fields() {
		ob_start();

		$fields = billing_fields_woofc( [] );

		foreach ( $fields as $key => $field ) {
			/**
			 * Filters whether to hide optional fiscal code field generated by Fatture in Cloud plugin
			 *
			 * @since 2.0.0
			 *
			 * @param bool $hide True hide, false show
			 */
			if ( 'billing_cod_fisc' === $key && ! $field['required'] && apply_filters( 'cfw_hide_optional_fiscal_code', true ) ) {
				continue;
			}

			woocommerce_form_field( $key, $field );
		}

		return ob_get_clean();
	}

	public function update_checkout_fragments( $fragments ) {
		$fragments['#fattureincloud-fields'] = $this->get_fields_wrapped();

		return $fragments;
	}

	public function remove_scripts( array $scripts ): array {
		$scripts['woo_fic_cf'] = 'woo_fic_cf';

		return $scripts;
	}
}
