<?php

namespace Devikit\Sellsy;

use Devikit\Sellsy\Admin\Settings;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * SIRET + TVA checkout / admin / address fields (PennyLane-parity UX).
 */
class VatIdField {

	/**
	 * @var bool
	 */
	private static $hooks_registered = false;

	/**
	 * @var string[]
	 */
	private $meta_keys = [
		'_billing_vat_id',
		'billing_vat_id',
		'_wc_billing/devikit-sellsy/billing_vat_id',
		'devikit-sellsy/billing_vat_id',
		'_vat_number',
		'vat_number',
		'_billing_eu_vat_number',
		'billing_eu_vat_number',
		'_billing_vat_number',
		'billing_vat_number',
		'_billing_nip',
		'billing_nip',
	];

	public function __construct() {
		if ( self::$hooks_registered ) {
			return;
		}
		self::$hooks_registered = true;

		add_filter( 'woocommerce_billing_fields', [ $this, 'add_fields_to_checkout' ], 20 );
		add_action( 'woocommerce_checkout_update_order_meta', [ $this, 'save_checkout_fields' ] );
		add_action( 'woocommerce_checkout_update_order_meta', [ $this, 'save_want_invoice_checkbox' ] );

		add_action( 'woocommerce_admin_order_data_after_billing_address', [ $this, 'display_in_admin_order' ] );
		add_filter( 'woocommerce_admin_billing_fields', [ $this, 'add_editable_fields_to_admin' ], 20, 3 );
		add_filter( 'woocommerce_admin_shipping_fields', [ $this, 'hide_blocks_fields_from_shipping_admin' ], 25, 3 );
		add_action( 'woocommerce_process_shop_order_meta', [ $this, 'save_admin_order_fields' ], 10, 2 );

		add_filter( 'woocommerce_order_formatted_billing_address', [ $this, 'add_to_formatted_address' ], 10, 2 );

		if ( ! $this->site_uses_block_checkout() ) {
			add_filter( 'woocommerce_formatted_address_replacements', [ $this, 'address_replacements' ], 10, 2 );
			add_filter( 'woocommerce_localisation_address_formats', [ $this, 'address_formats' ] );
		}

		add_filter( 'woocommerce_order_get_formatted_billing_address', [ $this, 'append_vat_to_formatted_billing_address' ], 20, 3 );
		add_filter( 'woocommerce_customer_meta_fields', [ $this, 'add_to_user_profile' ] );

		add_action( 'personal_options_update', [ $this, 'save_user_profile_fields' ] );
		add_action( 'edit_user_profile_update', [ $this, 'save_user_profile_fields' ] );
		add_action( 'load-profile.php', [ $this, 'sync_fields_before_profile_display' ] );
		add_action( 'load-user-edit.php', [ $this, 'sync_fields_before_profile_display' ] );

		add_filter( 'woocommerce_found_customer_details', [ $this, 'add_fields_to_customer_details' ], 10, 2 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_order_scripts' ] );
		add_action( 'wp_ajax_devikit_sellsy_get_customer_fields', [ $this, 'ajax_get_customer_fields' ] );
	}

	/**
	 * @return bool
	 */
	public static function is_external_vat_field_available() {
		$available = false;

		if ( self::is_plugin_active( 'woocommerce-eu-vat-number/woocommerce-eu-vat-number.php' ) ) {
			$available = true;
		}
		if ( self::is_plugin_active( 'eu-vat-for-woocommerce/eu-vat-for-woocommerce.php' ) ) {
			$available = true;
		}
		if ( self::is_plugin_active( 'woocommerce-germanized/woocommerce-germanized.php' ) ) {
			$available = true;
		}
		if ( self::is_plugin_active( 'woocommerce-germanized-pro/woocommerce-germanized-pro.php' ) ) {
			$available = true;
		}
		if ( self::is_plugin_active( 'flexible-invoices/flexible-invoices.php' ) ) {
			$available = true;
		}
		if ( self::is_plugin_active( 'flexible-invoices-woocommerce/flexible-invoices-woocommerce.php' ) ) {
			$available = true;
		}

		return (bool) apply_filters( 'devikit_sellsy_vat_id_field_available', $available );
	}

	/**
	 * @param string $plugin
	 * @return bool
	 */
	private static function is_plugin_active( $plugin ) {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		return function_exists( 'is_plugin_active' ) && is_plugin_active( $plugin );
	}

	/**
	 * @param array $fields
	 * @return array
	 */
	public function add_fields_to_checkout( $fields ) {
		$settings         = $this->get_settings();
		$display_mode     = isset( $settings['siret_display_mode'] ) ? $settings['siret_display_mode'] : 'always';
		$vat_display_mode = $this->settings_display_mode( $settings );
		$siret_required   = isset( $settings['siret_required'] ) && $settings['siret_required'] === 'yes';
		$vat_required     = isset( $settings['vat_id_required'] ) && $settings['vat_id_required'] === 'yes';
		$checkbox_label   = isset( $settings['invoice_checkbox_label'] ) ? $settings['invoice_checkbox_label'] : '';
		$add_vat          = ( $vat_display_mode !== 'hidden' ) && ! self::is_external_vat_field_available();

		if ( empty( $checkbox_label ) ) {
			$checkbox_label = __( 'I want an invoice', 'invoicing-integration-for-sellsy-and-woocommerce' );
		}

		$show_checkbox = ( $display_mode === 'checkbox' || ( $add_vat && $vat_display_mode === 'checkbox' ) );

		if ( $show_checkbox ) {
			$checkbox_field = [
				'type'     => 'checkbox',
				'label'    => $checkbox_label,
				'class'    => [ 'form-row-wide', 'sellsy-invoice-checkbox' ],
				'priority' => 29,
			];

			if ( isset( $fields['billing_company'] ) ) {
				$new_fields = [];
				foreach ( $fields as $key => $field ) {
					if ( $key === 'billing_company' ) {
						$new_fields['billing_want_invoice'] = $checkbox_field;
					}
					$new_fields[ $key ] = $field;
				}
				$fields = $new_fields;
			} else {
				$fields['billing_want_invoice'] = $checkbox_field;
			}
		}

		$siret_field = [
			'type'        => 'text',
			'label'       => __( 'SIRET', 'invoicing-integration-for-sellsy-and-woocommerce' ),
			'placeholder' => __( 'Enter SIRET number', 'invoicing-integration-for-sellsy-and-woocommerce' ),
			'required'    => $siret_required && $display_mode === 'always',
			'class'       => [ 'form-row-wide', 'sellsy-siret-field' ],
			'priority'    => 30,
			'maxlength'   => 14,
		];

		if ( $display_mode === 'checkbox' ) {
			$siret_field['class'][]  = 'sellsy-field-hidden-initially';
			$siret_field['required'] = false;
		}

		$vat_field = [];
		if ( $add_vat ) {
			$vat_field = [
				'type'        => 'text',
				'label'       => __( 'VAT Number (TVA)', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'placeholder' => __( 'e.g. FR12345678901', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'required'    => $vat_required && $vat_display_mode === 'always',
				'class'       => [ 'form-row-wide', 'sellsy-vat-field' ],
				'priority'    => 31,
			];

			if ( $vat_display_mode === 'checkbox' ) {
				$vat_field['class'][]  = 'sellsy-field-hidden-initially';
				$vat_field['required'] = false;
			}
		}

		if ( isset( $fields['billing_company'] ) ) {
			$new_fields = [];
			foreach ( $fields as $key => $field ) {
				$new_fields[ $key ] = $field;
				if ( $key === 'billing_company' ) {
					$new_fields['billing_siret'] = $siret_field;
					if ( $add_vat ) {
						$new_fields['billing_vat_id'] = $vat_field;
					}
				}
			}
			return $new_fields;
		}

		$fields['billing_siret'] = $siret_field;
		if ( $add_vat ) {
			$fields['billing_vat_id'] = $vat_field;
		}

		return $fields;
	}

	/**
	 * @param int $order_id
	 */
	public function save_checkout_fields( $order_id ) {
		if ( ! $this->is_valid_checkout_request() ) {
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		if ( ! empty( $_POST['billing_siret'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
			$order->update_meta_data( '_billing_siret', sanitize_text_field( wp_unslash( $_POST['billing_siret'] ) ) );
		}

		if ( ! self::is_external_vat_field_available() ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
			if ( ! empty( $_POST['billing_vat_id'] ) ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
				$order->update_meta_data( '_billing_vat_id', sanitize_text_field( wp_unslash( $_POST['billing_vat_id'] ) ) );
			}
		}

		$order->save();
	}

	/**
	 * @param int $order_id
	 */
	public function save_want_invoice_checkbox( $order_id ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		if ( ! $this->is_valid_checkout_request() || ! isset( $_POST['billing_want_invoice'] ) ) {
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		$order->update_meta_data( '_billing_want_invoice', sanitize_text_field( wp_unslash( $_POST['billing_want_invoice'] ) ) );
		$order->save();
	}

	/**
	 * @param \WC_Order $order
	 */
	public function display_in_admin_order( $order ) {
		$want_invoice = $order->get_meta( '_billing_want_invoice' );
		if ( $want_invoice !== '' ) {
			$status = ( $want_invoice === '1' )
				? __( 'Yes', 'invoicing-integration-for-sellsy-and-woocommerce' )
				: __( 'No', 'invoicing-integration-for-sellsy-and-woocommerce' );
			echo '<p><strong>' . esc_html__( 'I want an invoice', 'invoicing-integration-for-sellsy-and-woocommerce' ) . ':</strong> ' . esc_html( $status ) . '</p>';
		}
	}

	/**
	 * @param array           $fields
	 * @param \WC_Order|false $order
	 * @param string          $context
	 * @return array
	 */
	public function add_editable_fields_to_admin( $fields, $order = false, $context = 'edit' ) {
		unset( $context );
		unset( $fields['devikit-sellsy/billing_vat_id'] );
		unset( $fields['devikit-sellsy/billing_siret'] );

		foreach ( $fields as $key => $field ) {
			if ( ! is_array( $field ) ) {
				continue;
			}
			$field_id = isset( $field['id'] ) ? (string) $field['id'] : '';
			if (
				$field_id === '_wc_billing/devikit-sellsy/billing_vat_id'
				|| $field_id === 'devikit-sellsy/billing_vat_id'
				|| $field_id === '_wc_billing/devikit-sellsy/billing_siret'
				|| $field_id === 'devikit-sellsy/billing_siret'
			) {
				unset( $fields[ $key ] );
			}
		}

		if ( ! isset( $fields['siret'] ) ) {
			$fields['siret'] = [
				'label' => __( 'SIRET', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'show'  => true,
			];
		}

		if ( ! isset( $fields['vat_id'] ) ) {
			$fields['vat_id'] = [
				'label' => __( 'VAT Number (TVA)', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'show'  => true,
			];
		}

		if ( $order instanceof \WC_Order ) {
			$siret = preg_replace( '/\D+/', '', (string) $order->get_meta( '_billing_siret' ) );
			if ( $siret === '' ) {
				$siret = preg_replace( '/\D+/', '', (string) $order->get_meta( '_wc_billing/devikit-sellsy/billing_siret' ) );
			}
			if ( $siret !== '' ) {
				$fields['siret']['value'] = $siret;
			}

			$vat_id = $this->get_vat_id_from_order( $order );
			if ( $vat_id !== '' ) {
				$fields['vat_id']['value'] = $vat_id;
			}
		}

		return $fields;
	}

	/**
	 * @param array           $fields
	 * @param \WC_Order|false $order
	 * @param string          $context
	 * @return array
	 */
	public function hide_blocks_fields_from_shipping_admin( $fields, $order = false, $context = 'edit' ) {
		unset( $order, $context );
		unset( $fields['devikit-sellsy/billing_vat_id'], $fields['devikit-sellsy/billing_siret'] );

		foreach ( $fields as $key => $field ) {
			if ( ! is_array( $field ) ) {
				continue;
			}
			$field_id = isset( $field['id'] ) ? (string) $field['id'] : '';
			if (
				false !== strpos( $field_id, 'devikit-sellsy/billing_vat_id' )
				|| false !== strpos( $field_id, 'devikit-sellsy/billing_siret' )
			) {
				unset( $fields[ $key ] );
			}
		}

		return $fields;
	}

	/**
	 * @param int            $order_id
	 * @param \WC_Order|null $order
	 */
	public function save_admin_order_fields( $order_id, $order = null ) {
		$order_id = absint( $order_id );
		if ( ! $order_id || ! $this->is_valid_admin_order_save_request( $order_id ) ) {
			return;
		}

		if ( ! $order instanceof \WC_Order ) {
			$order = wc_get_order( $order_id );
		}
		if ( ! $order ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_admin_order_save_request().
		if ( isset( $_POST['_billing_siret'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_admin_order_save_request().
			$order->update_meta_data( '_billing_siret', sanitize_text_field( wp_unslash( $_POST['_billing_siret'] ) ) );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_admin_order_save_request().
		if ( isset( $_POST['_billing_vat_id'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_admin_order_save_request().
			$order->update_meta_data( '_billing_vat_id', sanitize_text_field( wp_unslash( $_POST['_billing_vat_id'] ) ) );
		}

		$order->save();
	}

	/**
	 * @param array     $address
	 * @param \WC_Order $order
	 * @return array
	 */
	public function add_to_formatted_address( $address, $order ) {
		if ( ! is_array( $address ) || ! $order instanceof \WC_Order ) {
			return $address;
		}

		$vat_id = $this->get_vat_id_from_order( $order );
		if ( $vat_id !== '' && ! $this->wc_will_render_blocks_vat( $order ) ) {
			$address['vat_number'] = $vat_id;
		}

		$siret = preg_replace( '/\D+/', '', (string) $order->get_meta( '_billing_siret' ) );
		if ( $siret === '' ) {
			$siret = preg_replace( '/\D+/', '', (string) $order->get_meta( '_wc_billing/devikit-sellsy/billing_siret' ) );
		}
		if ( $siret !== '' && ! $this->wc_will_render_blocks_siret( $order ) ) {
			$address['siret'] = $siret;
		}

		return $address;
	}

	/**
	 * @param array $replacements
	 * @param array $args
	 * @return array
	 */
	public function address_replacements( $replacements, $args ) {
		if ( ! is_array( $replacements ) ) {
			$replacements = [];
		}
		if ( ! is_array( $args ) ) {
			$args = [];
		}

		$replacements['{siret}'] = ! empty( $args['siret'] )
			? __( 'SIRET: ', 'invoicing-integration-for-sellsy-and-woocommerce' ) . $args['siret']
			: '';
		$replacements['{vat_number}'] = ! empty( $args['vat_number'] )
			? __( 'TVA: ', 'invoicing-integration-for-sellsy-and-woocommerce' ) . $args['vat_number']
			: '';

		return $replacements;
	}

	/**
	 * @param array $formats
	 * @return array
	 */
	public function address_formats( $formats ) {
		if ( ! is_array( $formats ) ) {
			return $formats;
		}

		foreach ( $formats as $country => $format ) {
			if ( strpos( (string) $format, '{vat_number}' ) === false ) {
				$formats[ $country ] = rtrim( (string) $format ) . "\n{siret}\n{vat_number}";
			}
		}

		return $formats;
	}

	/**
	 * @param string    $address
	 * @param array     $raw_address
	 * @param \WC_Order $order
	 * @return string
	 */
	public function append_vat_to_formatted_billing_address( $address, $raw_address = [], $order = null ) {
		unset( $raw_address );
		if ( ! $order instanceof \WC_Order ) {
			return $address;
		}

		if ( $this->wc_will_render_blocks_vat( $order ) ) {
			return $address;
		}

		$vat_id = $this->get_vat_id_from_order( $order );
		if ( $vat_id === '' ) {
			return $address;
		}

		$address_str = (string) $address;
		if ( $address_str !== '' && ( false !== strpos( $address_str, $vat_id ) || false !== stripos( $address_str, 'TVA:' ) ) ) {
			return $address;
		}

		$line = esc_html( __( 'TVA: ', 'invoicing-integration-for-sellsy-and-woocommerce' ) . $vat_id );
		if ( $address_str === '' ) {
			return $line;
		}

		$separator = ( false !== stripos( $address_str, '<br' ) ) ? '<br/>' : "\n";
		return $address_str . $separator . $line;
	}

	/**
	 * @param \WC_Order $order
	 * @return bool
	 */
	private function wc_will_render_blocks_vat( $order ) {
		if ( ! $order instanceof \WC_Order || 'store-api' !== $order->get_created_via() ) {
			return false;
		}
		if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) || self::is_external_vat_field_available() ) {
			return false;
		}
		if ( ! $this->site_uses_block_checkout() || $this->settings_display_mode() === 'hidden' ) {
			return false;
		}
		return trim( (string) $order->get_meta( '_wc_billing/devikit-sellsy/billing_vat_id' ) ) !== '';
	}

	/**
	 * @param \WC_Order $order
	 * @return bool
	 */
	private function wc_will_render_blocks_siret( $order ) {
		if ( ! $order instanceof \WC_Order || 'store-api' !== $order->get_created_via() ) {
			return false;
		}
		if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) || ! $this->site_uses_block_checkout() ) {
			return false;
		}
		return trim( (string) $order->get_meta( '_wc_billing/devikit-sellsy/billing_siret' ) ) !== '';
	}

	/**
	 * @return bool
	 */
	private function site_uses_block_checkout() {
		$page_id = function_exists( 'wc_get_page_id' ) ? wc_get_page_id( 'checkout' ) : 0;
		return $page_id && function_exists( 'has_block' ) && has_block( 'woocommerce/checkout', $page_id );
	}

	/**
	 * @param array $fields
	 * @return array
	 */
	public function add_to_user_profile( $fields ) {
		if ( isset( $fields['billing']['fields']['billing_siret'] ) ) {
			return $fields;
		}

		if ( ! isset( $fields['billing']['fields'] ) ) {
			return $fields;
		}

		$new_fields = [];
		foreach ( $fields['billing']['fields'] as $key => $field ) {
			$new_fields[ $key ] = $field;
			if ( $key === 'billing_company' ) {
				$new_fields['billing_siret'] = [
					'label'       => __( 'SIRET', 'invoicing-integration-for-sellsy-and-woocommerce' ),
					'description' => '',
				];
				$new_fields['billing_vat_id'] = [
					'label'       => __( 'VAT Number (TVA)', 'invoicing-integration-for-sellsy-and-woocommerce' ),
					'description' => '',
				];
			}
		}

		if ( ! isset( $new_fields['billing_siret'] ) ) {
			$new_fields['billing_siret'] = [
				'label'       => __( 'SIRET', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'description' => '',
			];
			$new_fields['billing_vat_id'] = [
				'label'       => __( 'VAT Number (TVA)', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'description' => '',
			];
		}

		$fields['billing']['fields'] = $new_fields;
		return $fields;
	}

	/**
	 * @param int $user_id
	 */
	public function save_user_profile_fields( $user_id ) {
		if ( ! current_user_can( 'edit_user', $user_id ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WP core verifies nonce for profile/user-edit forms.
		if ( isset( $_POST['billing_siret'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing
			$siret = sanitize_text_field( wp_unslash( $_POST['billing_siret'] ) );
			update_user_meta( $user_id, 'billing_siret', $siret );
			update_user_meta( $user_id, 'devikit-sellsy/billing_siret', $siret );
			update_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_siret', $siret );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		if ( isset( $_POST['billing_vat_id'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing
			$vat = sanitize_text_field( wp_unslash( $_POST['billing_vat_id'] ) );
			update_user_meta( $user_id, 'billing_vat_id', $vat );
			update_user_meta( $user_id, 'devikit-sellsy/billing_vat_id', $vat );
			update_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_vat_id', $vat );
		}
	}

	public function sync_fields_before_profile_display() {
		$user_id = isset( $_REQUEST['user_id'] ) ? absint( $_REQUEST['user_id'] ) : get_current_user_id();
		if ( ! $user_id ) {
			return;
		}

		$siret        = (string) get_user_meta( $user_id, 'billing_siret', true );
		$wc_siret     = (string) get_user_meta( $user_id, 'devikit-sellsy/billing_siret', true );
		$wc_siret_p   = (string) get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_siret', true );
		$latest_siret = $wc_siret_p !== '' ? $wc_siret_p : ( $wc_siret !== '' ? $wc_siret : $siret );
		if ( $siret !== $latest_siret || $wc_siret !== $latest_siret ) {
			update_user_meta( $user_id, 'billing_siret', $latest_siret );
			update_user_meta( $user_id, 'devikit-sellsy/billing_siret', $latest_siret );
			update_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_siret', $latest_siret );
		}

		$vat        = (string) get_user_meta( $user_id, 'billing_vat_id', true );
		$wc_vat     = (string) get_user_meta( $user_id, 'devikit-sellsy/billing_vat_id', true );
		$wc_vat_p   = (string) get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_vat_id', true );
		$latest_vat = $wc_vat_p !== '' ? $wc_vat_p : ( $wc_vat !== '' ? $wc_vat : $vat );
		if ( $vat !== $latest_vat || $wc_vat !== $latest_vat ) {
			update_user_meta( $user_id, 'billing_vat_id', $latest_vat );
			update_user_meta( $user_id, 'devikit-sellsy/billing_vat_id', $latest_vat );
			update_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_vat_id', $latest_vat );
		}
	}

	/**
	 * @param array $data
	 * @param int   $user_id
	 * @return array
	 */
	public function add_fields_to_customer_details( $data, $user_id ) {
		$siret = get_user_meta( $user_id, 'billing_siret', true );
		if ( empty( $siret ) ) {
			$siret = get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_siret', true );
		}
		if ( empty( $siret ) ) {
			$siret = get_user_meta( $user_id, 'devikit-sellsy/billing_siret', true );
		}
		if ( ! empty( $siret ) ) {
			$data['billing']['siret'] = esc_attr( $siret );
		}

		$vat = get_user_meta( $user_id, 'billing_vat_id', true );
		if ( empty( $vat ) ) {
			$vat = get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_vat_id', true );
		}
		if ( empty( $vat ) ) {
			$vat = get_user_meta( $user_id, 'devikit-sellsy/billing_vat_id', true );
		}
		if ( ! empty( $vat ) ) {
			$data['billing']['vat_id'] = esc_attr( $vat );
		}

		return $data;
	}

	/**
	 * @param string $hook
	 */
	public function enqueue_admin_order_scripts( $hook ) {
		$order_hooks = [ 'post.php', 'post-new.php', 'woocommerce_page_wc-orders' ];
		if ( ! in_array( $hook, $order_hooks, true ) ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || ! in_array( $screen->id, [ 'shop_order', 'woocommerce_page_wc-orders' ], true ) ) {
			return;
		}

		wp_enqueue_script(
			'devikit-sellsy-admin-order-fields',
			DEVIKIT_SELLSY_URL . 'assets/js/admin-order-fields.js',
			[ 'jquery', 'wc-admin-order-meta-boxes' ],
			DEVIKIT_SELLSY_VERSION,
			true
		);

		wp_localize_script(
			'devikit-sellsy-admin-order-fields',
			'devikit_sellsy_admin_fields',
			[
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'devikit_sellsy_admin_fields' ),
			]
		);
	}

	public function ajax_get_customer_fields() {
		check_ajax_referer( 'devikit_sellsy_admin_fields', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

		$user_id = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
		if ( ! $user_id ) {
			wp_send_json_error( 'Invalid user ID', 400 );
		}

		$siret = (string) get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_siret', true );
		if ( $siret === '' ) {
			$siret = (string) get_user_meta( $user_id, 'devikit-sellsy/billing_siret', true );
		}
		if ( $siret === '' ) {
			$siret = (string) get_user_meta( $user_id, 'billing_siret', true );
		}

		$vat = (string) get_user_meta( $user_id, '_wc_billing/devikit-sellsy/billing_vat_id', true );
		if ( $vat === '' ) {
			$vat = (string) get_user_meta( $user_id, 'devikit-sellsy/billing_vat_id', true );
		}
		if ( $vat === '' ) {
			$vat = (string) get_user_meta( $user_id, 'billing_vat_id', true );
		}

		wp_send_json_success(
			[
				'siret'  => $siret,
				'vat_id' => $vat,
			]
		);
	}

	/**
	 * @param int $order_id
	 * @return bool
	 */
	private function is_valid_admin_order_save_request( $order_id ) {
		if ( ! current_user_can( 'edit_shop_order', $order_id ) && ! current_user_can( 'edit_shop_orders' ) ) {
			return false;
		}

		if ( isset( $_POST['woocommerce_meta_nonce'] ) ) {
			return (bool) wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ),
				'woocommerce_save_data'
			);
		}

		if ( isset( $_POST['_wpnonce'] ) ) {
			return (bool) wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ),
				'update-order_' . $order_id
			);
		}

		return false;
	}

	/**
	 * @return bool
	 */
	private function is_valid_checkout_request() {
		if ( isset( $_POST['woocommerce-process-checkout-nonce'] ) ) {
			$valid = wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ),
				'woocommerce-process_checkout'
			);
			if ( $valid ) {
				return true;
			}
			return did_action( 'woocommerce_checkout_process' ) > 0
				|| did_action( 'woocommerce_before_checkout_process' ) > 0;
		}

		return ( defined( 'REST_REQUEST' ) && REST_REQUEST )
			|| did_action( 'woocommerce_store_api_checkout_update_order_from_request' ) > 0;
	}

	/**
	 * @param \WC_Order $order
	 * @return string
	 */
	public function get_vat_id_from_order( $order ) {
		foreach ( $this->meta_keys as $key ) {
			$value = trim( (string) $order->get_meta( $key ) );
			if ( $value !== '' ) {
				return strtoupper( $value );
			}
		}
		return '';
	}

	/**
	 * @return array
	 */
	private function get_settings() {
		$settings = get_option( Settings::OPTION_NAME, [] );
		return is_array( $settings ) ? $settings : [];
	}

	/**
	 * @param array|null $settings
	 * @return string
	 */
	private function settings_display_mode( $settings = null ) {
		if ( $settings === null ) {
			$settings = $this->get_settings();
		}
		$mode = isset( $settings['vat_id_display_mode'] ) ? $settings['vat_id_display_mode'] : 'always';
		return in_array( $mode, [ 'always', 'checkbox', 'hidden' ], true ) ? $mode : 'always';
	}
}
