<?php

namespace Devikit\Infakt;

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

class CheckoutManager {

    /**
     * Constructor
     */
    public function __construct() {
        // Add NIP field if needed
        add_filter( 'woocommerce_checkout_fields', [ $this, 'maybe_add_nip_field' ] );
        add_action( 'woocommerce_admin_order_data_after_billing_address', [ $this, 'display_nip_in_admin' ] );
    }

    /**
     * Maybe add NIP field
     */
    public function maybe_add_nip_field( $fields ) {
        // Check if NIP field already exists from other plugins
        // Common keys: billing_nip, vat_number
        if ( isset( $fields['billing']['billing_nip'] ) || isset( $fields['billing']['vat_number'] ) ) {
            return $fields;
        }

        // Logic for Pro override (checkbox "I want invoice")
        // Hook is 'woocommerce_checkout_fields' which runs before display. 
        // We can add the field, and JS will handle visibility if Pro features are active.
        // For Free version: simple always visible or conditional?
        // User requirement: "dodała to pole nawet we free wersji". 
        // So we add it.

        $fields['billing']['billing_nip'] = [
            'label'       => __( 'NIP (VAT ID)', 'invoicing-integration-for-infakt-and-woocommerce' ),
            'placeholder' => '',
            'required'    => false, // Optional by default in Free
            'class'       => [ 'form-row-wide' ],
            'clear'       => true,
            'priority'    => 35, // After Company
        ];

        return $fields;
    }

    /**
     * Display NIP in Admin Order View
     */
    public function display_nip_in_admin( $order ) {
        if ( $order->get_meta( '_billing_nip' ) ) {
            echo '<p><strong>' . esc_html__( 'VAT:', 'invoicing-integration-for-infakt-and-woocommerce' ) . '</strong> ' . esc_html( $order->get_meta( '_billing_nip' ) ) . '</p>';
        }
    }
}

