<?php
/**
 * B2B checkout fields (SIREN, SIRET, VAT number).
 *
 * Supports both classic checkout and Checkout Blocks.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_Checkout_Fields {

    public static function init(): void {
        if ( get_option( 'gofactox_enable_b2b_fields', 'yes' ) !== 'yes' ) {
            return;
        }

        // Classic checkout fields.
        add_filter( 'woocommerce_checkout_fields', [ __CLASS__, 'add_checkout_fields' ] );
        add_action( 'woocommerce_checkout_update_order_meta', [ __CLASS__, 'save_checkout_fields' ] );

        // Block-based checkout (since WC 8.7). The legacy filter above does not apply to
        // the React-based checkout block; we register the same fields via the new API.
        add_action( 'woocommerce_init', [ __CLASS__, 'register_block_checkout_fields' ] );

        // Display in admin order page.
        add_action( 'woocommerce_admin_order_data_after_billing_address', [ __CLASS__, 'display_in_admin' ] );
    }

    /**
     * Register B2B fields and PO reference for the Block-based checkout.
     *
     * Each registered field is saved on the order with meta key
     * `_wc_other/{namespace}/{id}` (or `_wc_billing/...` for billing-location fields).
     * We mirror the values to our existing meta keys so the rest of the plugin
     * (XML, PDF, admin display) keeps working without changes.
     */
    public static function register_block_checkout_fields(): void {
        if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
            return;
        }

        $registrations = [
            [
                'id'       => 'gofactox/siren',
                'label'    => __( 'SIREN', 'gofactox-e-invoicing-for-woocommerce' ),
                'location' => 'address',
                'mirror'   => '_gofactox_buyer_siren',
                'attributes' => [ 'maxLength' => '9', 'autocomplete' => 'off' ],
            ],
            [
                'id'       => 'gofactox/siret',
                'label'    => __( 'SIRET', 'gofactox-e-invoicing-for-woocommerce' ),
                'location' => 'address',
                'mirror'   => '_gofactox_buyer_siret',
                'attributes' => [ 'maxLength' => '14', 'autocomplete' => 'off' ],
            ],
            [
                'id'       => 'gofactox/vat_number',
                'label'    => __( 'VAT Number', 'gofactox-e-invoicing-for-woocommerce' ),
                'location' => 'address',
                'mirror'   => '_gofactox_buyer_vat_number',
                'attributes' => [ 'autocomplete' => 'off' ],
            ],
            [
                'id'       => 'gofactox/po_reference',
                'label'    => __( 'Purchase Order Number (PO)', 'gofactox-e-invoicing-for-woocommerce' ),
                'location' => 'order',
                'mirror'   => '_gofactox_buyer_po_reference',
                'attributes' => [ 'autocomplete' => 'off' ],
            ],
        ];

        foreach ( $registrations as $field ) {
            try {
                woocommerce_register_additional_checkout_field( [
                    'id'         => $field['id'],
                    'label'      => $field['label'],
                    'location'   => $field['location'],
                    'type'       => 'text',
                    'required'   => false,
                    'attributes' => $field['attributes'],
                ] );
            } catch ( \Throwable $e ) {
                // Field may already be registered (re-init); ignore.
            }
        }

        // Mirror values to legacy meta keys after the order is created so the rest
        // of the plugin doesn't have to know about the new "_wc_other/" prefix.
        add_action( 'woocommerce_store_api_checkout_update_order_meta', [ __CLASS__, 'mirror_block_fields_to_legacy_meta' ] );
    }

    /**
     * After a Blocks-based checkout, copy the new field values to the legacy meta keys.
     */
    public static function mirror_block_fields_to_legacy_meta( \WC_Order $order ): void {
        $map = [
            // Address-located fields land on the billing address meta.
            '_wc_billing/gofactox/siren'        => '_gofactox_buyer_siren',
            '_wc_billing/gofactox/siret'        => '_gofactox_buyer_siret',
            '_wc_billing/gofactox/vat_number'   => '_gofactox_buyer_vat_number',
            // Order-located field lands on the order meta directly.
            '_wc_other/gofactox/po_reference'   => '_gofactox_buyer_po_reference',
        ];

        $changed = false;
        foreach ( $map as $source => $target ) {
            $value = (string) $order->get_meta( $source );
            if ( $value !== '' && ! $order->get_meta( $target ) ) {
                $order->update_meta_data( $target, $value );
                $changed = true;
            }
        }
        if ( $changed ) {
            $order->save();
        }
    }

    /**
     * Add B2B fields to the billing section of checkout.
     */
    public static function add_checkout_fields( array $fields ): array {
        $fields['billing']['gofactox_buyer_siren'] = [
            'type'        => 'text',
            'label'       => __( 'SIREN', 'gofactox-e-invoicing-for-woocommerce' ),
            'placeholder' => '123456789',
            'required'    => false,
            'class'       => [ 'form-row-first' ],
            'priority'    => 31,
            'maxlength'   => 9,
            'custom_attributes' => [ 'pattern' => '[0-9]{9}' ],
        ];

        $fields['billing']['gofactox_buyer_siret'] = [
            'type'        => 'text',
            'label'       => __( 'SIRET', 'gofactox-e-invoicing-for-woocommerce' ),
            'placeholder' => '12345678901234',
            'required'    => false,
            'class'       => [ 'form-row-last' ],
            'priority'    => 32,
            'maxlength'   => 14,
            'custom_attributes' => [ 'pattern' => '[0-9]{14}' ],
        ];

        $fields['billing']['gofactox_buyer_vat_number'] = [
            'type'        => 'text',
            'label'       => __( 'VAT Number', 'gofactox-e-invoicing-for-woocommerce' ),
            'placeholder' => 'FR12345678901',
            'required'    => false,
            'class'       => [ 'form-row-wide' ],
            'priority'    => 33,
        ];

        $fields['order']['gofactox_buyer_po_reference'] = [
            'type'        => 'text',
            'label'       => __( 'Purchase Order Number (PO)', 'gofactox-e-invoicing-for-woocommerce' ),
            'placeholder' => __( 'Optional, e.g. BC-2026-0042', 'gofactox-e-invoicing-for-woocommerce' ),
            'required'    => false,
            'class'       => [ 'form-row-wide' ],
            'priority'    => 25,
        ];

        return $fields;
    }

    /**
     * Save B2B fields to order meta.
     */
    public static function save_checkout_fields( int $order_id ): void {
        $order = wc_get_order( $order_id );
        if ( ! $order ) {
            return;
        }

        $fields = [
            'gofactox_buyer_siren',
            'gofactox_buyer_siret',
            'gofactox_buyer_vat_number',
            'gofactox_buyer_po_reference',
        ];

        foreach ( $fields as $field ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $value = isset( $_POST[ $field ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field ] ) ) : '';
            if ( $value ) {
                $order->update_meta_data( '_' . $field, $value );
            }
        }

        $order->save();
    }

    /**
     * Display B2B fields in admin order page.
     */
    public static function display_in_admin( \WC_Order $order ): void {
        $siren = $order->get_meta( '_gofactox_buyer_siren' );
        $siret = $order->get_meta( '_gofactox_buyer_siret' );
        $vat   = $order->get_meta( '_gofactox_buyer_vat_number' );
        $po    = $order->get_meta( '_gofactox_buyer_po_reference' );

        if ( ! $siren && ! $siret && ! $vat && ! $po ) {
            return;
        }

        echo '<div class="gofactox-b2b-fields" style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e0e0e0;">';
        echo '<h3 style="margin: 0 0 8px;">' . esc_html__( 'B2B Information', 'gofactox-e-invoicing-for-woocommerce' ) . '</h3>';

        if ( $siren ) {
            echo '<p><strong>SIREN:</strong> ' . esc_html( $siren ) . '</p>';
        }
        if ( $siret ) {
            echo '<p><strong>SIRET:</strong> ' . esc_html( $siret ) . '</p>';
        }
        if ( $vat ) {
            echo '<p><strong>' . esc_html__( 'VAT Number:', 'gofactox-e-invoicing-for-woocommerce' ) . '</strong> ' . esc_html( $vat ) . '</p>';
        }
        if ( $po ) {
            echo '<p><strong>' . esc_html__( 'PO Number:', 'gofactox-e-invoicing-for-woocommerce' ) . '</strong> ' . esc_html( $po ) . '</p>';
        }

        echo '</div>';
    }
}
