<?php
/**
 * Checkout Override Class
 * Handles custom checkout template loading and field management
 * 
 * @package Checkoutify_Lite
 * @since 1.0.0
 */

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

/**
 * Checkout Override Class
 * Manages custom checkout templates, field modifications, and checkout functionality
 */
class CKFYLT25_Checkout_Override {

    /**
     * Constructor - Initialize checkout override hooks
     */
    public function __construct() {
        add_action( 'template_redirect', array( $this, 'force_load_custom_checkout_template' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'manage_checkout_scripts_styles' ), 99 );
        add_filter( 'woocommerce_checkout_fields', array( $this, 'ckfylt25_disable_billing_fields' ), 9999 );
        add_filter( 'woocommerce_checkout_fields', array( $this, 'ckfylt25_disable_order_notes' ), 9999 );
        
        // Ensure billing fields load correctly
        add_action( 'woocommerce_checkout_billing', array( $this, 'ensure_billing_fields_display' ), 5 );
        add_action( 'woocommerce_checkout_before_customer_details', array( $this, 'before_customer_details' ), 5 );
        add_action( 'woocommerce_checkout_after_customer_details', array( $this, 'after_customer_details' ), 5 );
        
        // Make render function globally available
        add_action( 'init', array( $this, 'make_render_function_global' ) );
        
        // Ensure WooCommerce is initialized before rendering fields
        add_action( 'woocommerce_before_checkout_form', array( $this, 'ensure_woocommerce_initialized' ), 5 );
        
        // Compatibility with other checkout plugins
        add_action( 'init', array( $this, 'handle_checkout_conflicts' ), 1 );
        
        // Ensure disabled fields don't interfere with validation
        add_filter( 'woocommerce_checkout_fields', array( $this, 'ensure_disabled_fields_validation' ), 10000 );
        
        // Clean disabled field values during processing
        add_action( 'woocommerce_checkout_process', array( $this, 'clean_disabled_fields_values' ) );
        
        // Relax address requirement for shipping calculations when key billing fields are disabled
        add_filter( 'woocommerce_shipping_cost_requires_address', array( $this, 'relax_shipping_address_requirement' ), 10, 2 );
        
        // Optionally mark shipping address as not required when cart is virtual-only
        add_filter( 'woocommerce_cart_needs_shipping_address', array( $this, 'maybe_disable_shipping_address_requirement' ), 10 );
        
        // When allowing checkout without address, mark the entire cart as not needing shipping to bypass address and method requirements
        add_filter( 'woocommerce_cart_needs_shipping', array( $this, 'maybe_disable_cart_needs_shipping' ), 999 );
        
        // Prefer shipping address as destination when billing fields are disabled (prevents relying on hidden billing address)
        add_filter( 'woocommerce_ship_to_destination', array( $this, 'prefer_shipping_address_destination' ), 10 );
        
        // When billing fields are disabled, default "Ship to a different address" to checked so shipping fields are visible
        add_filter( 'woocommerce_ship_to_different_address_checked', array( $this, 'force_ship_to_different_address_checked' ), 10 );

        // Apply base-location fallback for shipping packages when allowing checkout without address
        add_filter( 'woocommerce_shipping_packages', array( $this, 'maybe_apply_base_location_destination' ), 10 );
    }

    /**
     * Disable billing fields based on admin settings
     * 
     * @param array $fields WooCommerce checkout fields
     * @return array Modified checkout fields
     */
    public function ckfylt25_disable_billing_fields( $fields ) {
        // Ensure fields exist
        if ( ! isset( $fields['billing'] ) || ! is_array( $fields['billing'] ) ) {
            return $fields;
        }
        
        // Only disable fields if specific fields are configured to be disabled
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', [] );
        
        // If no disabled fields or option is not configured, return original fields unchanged
        if ( empty( $disabled_fields ) || ! is_array( $disabled_fields ) || $disabled_fields === false ) {
            return $fields;
        }
        
        // Only disable specific fields that are in the list
        foreach ( $disabled_fields as $field_key ) {
            if ( isset( $fields['billing'][ $field_key ] ) ) {
                // Mark as not required
                $fields['billing'][ $field_key ]['required'] = false;
                
                // Add CSS class to hide
                if ( ! isset( $fields['billing'][ $field_key ]['class'] ) ) {
                    $fields['billing'][ $field_key ]['class'] = [];
                }
                // Use CSS class consistent with assets to hide disabled fields
                $fields['billing'][ $field_key ]['class'][] = 'ckfylt25-hidden-field';
                
                // Set default empty value
                $fields['billing'][ $field_key ]['default'] = '';
                
                // Also set field as optional in validation
                $fields['billing'][ $field_key ]['validate'] = [];
            }
        }
        
        return $fields;
    }

    /**
     * Disable order notes if configured
     * 
     * @param array $fields WooCommerce checkout fields
     * @return array Modified checkout fields
     */
    public function ckfylt25_disable_order_notes( $fields ) {
        $order_notes_disabled = get_option( 'ckfylt25_order_notes_disabled', false );
        
        if ( $order_notes_disabled && isset( $fields['order'] ) && isset( $fields['order']['order_comments'] ) ) {
            unset( $fields['order']['order_comments'] );
        }
        
        return $fields;
    }

    /**
     * Asegurar que los campos deshabilitados no interfieran con la validación
     */
    public function ensure_disabled_fields_validation( $fields ) {
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', [] );
        
        if ( ! empty( $disabled_fields ) && is_array( $disabled_fields ) ) {
            foreach ( $disabled_fields as $field_key ) {
                if ( isset( $fields['billing'][ $field_key ] ) ) {
                    // Asegurar que el campo no sea requerido
                    $fields['billing'][ $field_key ]['required'] = false;
                    
                    // Limpiar reglas de validación
                    $fields['billing'][ $field_key ]['validate'] = [];
                    
                    // Establecer valor por defecto vacío
                    $fields['billing'][ $field_key ]['default'] = '';
                    
                    // Asegurar que el campo esté oculto
                    if ( ! isset( $fields['billing'][ $field_key ]['class'] ) ) {
                        $fields['billing'][ $field_key ]['class'] = [];
                    }
                    // Use CSS class consistent with assets to hide disabled fields
                    $fields['billing'][ $field_key ]['class'][] = 'ckfylt25-hidden-field';
                }
            }
        }
        
        return $fields;
    }

    /**
     * Renderizar campos de facturación manualmente
     */
    public function render_billing_fields() {
        // Forzar la inicialización de WooCommerce si no está disponible
        if (!function_exists('WC')) {
            return;
        }
        
        // Asegurar que WooCommerce esté inicializado
        if (!WC()->checkout()) {
            return;
        }
        
        // Obtener los campos de facturación
        $checkout = WC()->checkout();
        $fields = $checkout->get_checkout_fields('billing');
        
        if (!empty($fields)) {
            foreach ($fields as $key => $field) {
                woocommerce_form_field($key, $field);
            }
        }
    }


    /**
     * Asegurar que WooCommerce esté inicializado
     */
    public function ensure_woocommerce_initialized() {
        // Forzar la inicialización de WooCommerce
        if (function_exists('WC') && !WC()->checkout()) {
            WC()->init();
        }
    }



    public function force_load_custom_checkout_template() {
        if ( is_page( wc_get_page_id( 'checkout' ) ) && ! is_wc_endpoint_url() && ! is_ajax() ) {
            $selected_template_id = get_option( 'ckfylt25_selected_template', 'minimalista' );
            $template_path = CKFYLT25_PLUGIN_DIR . 'templates/' . $selected_template_id . '/template.php';

            if ( file_exists( $template_path ) ) {
                ?>
                <!DOCTYPE html>
                <html <?php language_attributes(); ?>>
                <head>
                    <meta charset="<?php bloginfo( 'charset' ); ?>">
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                    <?php wp_head(); ?>
                </head>
                <body <?php body_class(); ?>>
                    
                    <?php if ( get_option('ckfylt25_header_footer_enabled', true) ) {
                        $this->render_global_header();
                    } else {
                        // Use theme header when plugin header is disabled
                        get_header();
                    } ?>

                    <div class="ckfylt25-global-checkout-container">
                        <?php include $template_path; ?>
                    </div>

                    <?php if ( get_option('ckfylt25_header_footer_enabled', true) ) {
                        $this->render_global_footer();
                        wp_footer();
                    } else {
                        // Use theme footer when plugin footer is disabled
                        // Don't call wp_footer() here as it's already included in get_footer()
                        get_footer();
                    } ?>
                </body>
                </html>
                <?php
                exit();
            }
        }
    }

    // Compatibility bridge for legacy hook name
    public function ckfylt25_force_load_custom_checkout_template() {
        return $this->force_load_custom_checkout_template();
    }

    public function render_global_header() {
        $logo_id = get_option('ckfylt25_header_logo_id');
        $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'medium') : '';
        $header_style = get_option('ckfylt25_header_style', 'header-style-classic');
        $steps_style = get_option('ckfylt25_steps_style', 'steps-style-bold');
        $header_classes = "ckfylt25-global-header " . esc_attr($header_style) . " " . esc_attr($steps_style);
        ?>
        <header class="<?php echo esc_attr($header_classes); ?>">
            <div class="ckfylt25-header-content">
                <div class="ckfylt25-header-logo">
                    <?php if ( $logo_url ) : ?>
                        <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $logo_url ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>"></a>
                    <?php else : ?>
                        <a href="<?php echo esc_url( home_url( '/' ) ); ?>" class="ckfylt25-site-title-link"><?php bloginfo( 'name' ); ?></a>
                    <?php endif; ?>
                </div>
                <nav class="ckfylt25-header-breadcrumb">
                    <ol>
                        <li><a href="<?php echo esc_url( wc_get_cart_url() ); ?>">Cart</a></li>
                        <li class="is-active" aria-current="step">Information</li>
                        <li>Finish</li>
                    </ol>
                </nav>
            </div>
        </header>
        <?php
    }

    public function render_global_footer() {
        $refund_url = get_option('ckfylt25_footer_refund_url');
        $privacy_url = get_option('ckfylt25_footer_privacy_url');
        $terms_url = get_option('ckfylt25_footer_terms_url');

        if ( empty($refund_url) && empty($privacy_url) && empty($terms_url ) ) {
            return;
        }

        $header_style = get_option('ckfylt25_header_style', 'header-style-classic');
        $footer_classes = "ckfylt25-global-footer " . esc_attr($header_style);
        ?>
        <footer class="<?php echo esc_attr($footer_classes); ?>">
            <div class="ckfylt25-footer-content">
                <nav class="ckfylt25-footer-nav">
                    <ul>
                        <?php if ( ! empty( $refund_url ) ) : ?>
                            <li><a href="<?php echo esc_url( $refund_url ); ?>">Refund policy</a></li>
                        <?php endif; ?>
                        <?php if ( ! empty( $privacy_url ) ) : ?>
                            <li><a href="<?php echo esc_url( $privacy_url ); ?>">Privacy policy</a></li>
                        <?php endif; ?>
                        <?php if ( ! empty( $terms_url ) ) : ?>
                            <li><a href="<?php echo esc_url( $terms_url ); ?>">Terms of service</a></li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </footer>
        <?php
    }

    public function manage_checkout_scripts_styles() {
        if ( ! is_checkout() || is_wc_endpoint_url() || is_ajax() ) return;
        
        // Desactivado para cumplir las directrices de WordPress.org. Puede reactivarse si se detecta un conflicto de tema específico.
        // $parent_theme_handle = get_template();
        // $child_theme_handle = get_stylesheet();
        // wp_dequeue_style( $parent_theme_handle );
        // wp_dequeue_script( $parent_theme_handle );
        // if ( $parent_theme_handle !== $child_theme_handle ) {
        //     wp_dequeue_style( $child_theme_handle );
        //     wp_dequeue_script( $child_theme_handle );
        // }
        
        // Removed external Google Fonts enqueue to comply with WordPress.org guidelines.
        // Use system font stack via local CSS instead.
        
        // Enqueue checkout override styles
        wp_enqueue_style( 'ckfylt25-checkout-override', CKFYLT25_PLUGIN_URL . 'assets/css/checkout-override.css', [], '1.0.0' );
        
        // Se carga el archivo CSS principal para Header, Footer y otros estilos.
        wp_enqueue_style( 'ckfylt25-global-styles', CKFYLT25_PLUGIN_URL . 'assets/css/global-checkout-styles.css', [], '1.2.0' );
        
        // No cargar JavaScript para express checkout (Google Pay, Apple Pay, etc.)

        $selected_template_id = get_option( 'ckfylt25_selected_template', 'minimalista' );
        $template_url = CKFYLT25_PLUGIN_URL . 'templates/' . $selected_template_id . '/';
        $template_dir = CKFYLT25_PLUGIN_DIR . 'templates/' . $selected_template_id . '/';
        if ( file_exists( $template_dir . 'style.css' ) ) {
            wp_enqueue_style( 'ckfylt25-template-style', $template_url . 'style.css', ['ckfylt25-global-styles'], filemtime( $template_dir . 'style.css' ) );
        }
        if ( file_exists( $template_dir . 'script.js' ) ) {
            wp_enqueue_script( 'ckfylt25-template-script', $template_url . 'script.js', [ 'jquery', 'wc-checkout', 'wp-i18n' ], filemtime( $template_dir . 'script.js' ), true );
            // Enable script translations for template script
            if ( function_exists( 'wp_set_script_translations' ) ) {
                wp_set_script_translations( 'ckfylt25-template-script', 'checkoutify-lite', CKFYLT25_PLUGIN_DIR . 'languages' );
            }
        }
        
        // Enqueue common template JavaScript
        wp_enqueue_script( 'ckfylt25-minimalista-template', CKFYLT25_PLUGIN_URL . 'assets/js/minimalista-template.js', array( 'jquery', 'wc-checkout', 'wp-i18n' ), '1.0.0', true );
        if ( function_exists( 'wp_set_script_translations' ) ) {
            wp_set_script_translations( 'ckfylt25-minimalista-template', 'checkoutify-lite', CKFYLT25_PLUGIN_DIR . 'languages' );
        }

        // Provide currency info to the template script (before it runs)
        $currency_data = array(
            'code' => get_woocommerce_currency(),
            'symbol' => html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ),
            'decimal_separator' => wc_get_price_decimal_separator(),
            'thousand_separator' => wc_get_price_thousand_separator(),
            'decimals' => wc_get_price_decimals(),
            'position' => get_option( 'woocommerce_currency_pos', 'left' ),
        );
        wp_add_inline_script( 'ckfylt25-minimalista-template', 'window.ckfylt25Currency = ' . wp_json_encode( $currency_data ) . ';', 'before' );

        // Enqueue checkout conflict fix script
        wp_enqueue_script( 'ckfylt25-checkout-conflict-fix', CKFYLT25_PLUGIN_URL . 'assets/js/checkout-conflict-fix.js', array( 'jquery', 'wc-checkout', 'wp-i18n' ), '1.0.0', true );
        if ( function_exists( 'wp_set_script_translations' ) ) {
            wp_set_script_translations( 'ckfylt25-checkout-conflict-fix', 'checkoutify-lite', CKFYLT25_PLUGIN_DIR . 'languages' );
        }

        // Localize script with minimal template params under a unique namespace to avoid clobbering WooCommerce's wc_checkout_params
        wp_localize_script( 'ckfylt25-minimalista-template', 'ckfylt25_checkout_params', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'apply_coupon_nonce' => wp_create_nonce( 'apply-coupon' ),
            'remove_coupon_nonce' => wp_create_nonce( 'remove-coupon' ),
            'update_order_review_nonce' => wp_create_nonce( 'update-order-review' )
        ) );

        // Provide checkout config to client to align validations
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', array() );
        $checkout_config_js = 'window.ckfylt25CheckoutConfig = ' . wp_json_encode( array(
            'allowWithoutAddress' => (bool) $allow_without_address,
            'disabledBillingFields' => is_array( $disabled_fields ) ? array_values( $disabled_fields ) : array(),
        ) ) . ';';
        // Attach before scripts so they can read it
        wp_add_inline_script( 'ckfylt25-checkout-conflict-fix', $checkout_config_js, 'before' );
        wp_add_inline_script( 'ckfylt25-minimalista-template', $checkout_config_js, 'before' );
        if ( file_exists( $template_dir . 'script.js' ) ) {
            wp_add_inline_script( 'ckfylt25-template-script', $checkout_config_js, 'before' );
        }
    }
    
    public function ensure_billing_fields_display() {
        // Asegurar que los campos de facturación se muestren
        if ( ! WC()->checkout()->get_checkout_fields( 'billing' ) ) {
            // Si no hay campos de facturación, forzar su creación
            WC()->checkout()->get_checkout_fields();
        }
    }
    
    public function before_customer_details() {
        // Asegurar que el contenedor de campos esté presente
        echo '<div class="ckfylt25-billing-fields-wrapper">';
    }
    
    public function after_customer_details() {
        echo '</div>';
    }
    
    public function handle_checkout_conflicts() {
        // Detectar y manejar conflictos con otros plugins de checkout
        if ( defined( 'CFW_VERSION' ) ) {
            // CheckoutWC está activo, desactivar temporalmente para nuestro template
            remove_action( 'template_redirect', 'cfw_template_redirect', 10 );
        }
        
        // Asegurar que WooCommerce cargue sus campos de facturación
        if ( ! has_action( 'woocommerce_checkout_billing', array( WC()->checkout(), 'checkout_form_billing' ) ) ) {
            add_action( 'woocommerce_checkout_billing', array( WC()->checkout(), 'checkout_form_billing' ), 10 );
        }
    }
    
    /**
     * Detectar si hay métodos de pago express disponibles
     */
    public function has_express_payment_methods() {
        if ( ! WC()->cart->needs_payment() ) {
            return false;
        }
        
        $available_gateways = WC()->payment_gateways()->get_available_payment_gateways();
        $express_methods = array();
        
        foreach ( $available_gateways as $gateway_id => $gateway ) {
            // Detectar métodos de pago express conocidos
            if ( $this->is_express_payment_method( $gateway_id, $gateway ) ) {
                $express_methods[] = $gateway_id;
            }
        }
        
        return ! empty( $express_methods );
    }
    
    /**
     * Verificar si un método de pago es de tipo express
     */
    private function is_express_payment_method( $gateway_id, $gateway ) {
        // PayPal Express
        if ( strpos( $gateway_id, 'paypal' ) !== false && 
             ( strpos( $gateway_id, 'express' ) !== false || $gateway_id === 'ppcp-gateway' ) ) {
            return true;
        }
        
        // Stripe Express (Google Pay, Apple Pay)
        if ( strpos( $gateway_id, 'stripe' ) !== false && 
             ( method_exists( $gateway, 'is_express_payment' ) || 
               isset( $gateway->supports ) && in_array( 'express_payment', $gateway->supports ) ) ) {
            return true;
        }
        
        // Amazon Pay
        if ( strpos( $gateway_id, 'amazon' ) !== false ) {
            return true;
        }
        
        // Apple Pay específico
        if ( strpos( $gateway_id, 'apple' ) !== false || strpos( $gateway_id, 'applepay' ) !== false ) {
            return true;
        }
        
        // Google Pay específico
        if ( strpos( $gateway_id, 'google' ) !== false || strpos( $gateway_id, 'googlepay' ) !== false ) {
            return true;
        }
        
        // Verificar si el gateway tiene configuración de express checkout
        if ( method_exists( $gateway, 'is_express_payment_enabled' ) && $gateway->is_express_payment_enabled() ) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Renderizar la sección de métodos de pago express
     */
    public function render_express_checkout_section() {
        if ( ! $this->has_express_payment_methods() ) {
            return;
        }
        
        ?>
        <div class="ckfylt25-express-checkout-section">
            <h3 class="ckfylt25-express-checkout-title">Express Checkout</h3>
            <div class="ckfylt25-express-payment-methods">
                <?php
                // Hook específico para métodos de pago express en checkout
                do_action( 'woocommerce_review_order_before_payment' );
                
                // También intentar renderizar métodos express específicos
                $this->render_express_payment_buttons();
                
                // Verificar si hay hooks de express payment de WooCommerce Blocks
                if ( function_exists( 'wc_get_container' ) ) {
                    try {
                        $express_payment_registry = wc_get_container()->get( 'Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry' );
                        if ( method_exists( $express_payment_registry, 'get_all_active_payment_methods' ) ) {
                            // Renderizar métodos express de blocks si están disponibles
                            echo '<div class="wc-block-checkout__express-payment-container">';
                            do_action( 'woocommerce_blocks_checkout_express_payment' );
                            echo '</div>';
                        }
                    } catch ( Exception $e ) {
                        // Continuar silenciosamente si no hay blocks disponibles
                    }
                }
                ?>
            </div>
        </div>
        <div class="ckfylt25-express-checkout-separator">
            <span><?php esc_html_e( 'OR', 'checkoutify-lite' ); ?></span>
        </div>
        <?php
    }
    
    /**
     * Renderizar botones de pago express específicos
     */
    private function render_express_payment_buttons() {
        $available_gateways = WC()->payment_gateways()->get_available_payment_gateways();
        
        foreach ( $available_gateways as $gateway_id => $gateway ) {
            if ( ! $this->is_express_payment_method( $gateway_id, $gateway ) ) {
                continue;
            }
            
            // Para PayPal Express
            if ( strpos( $gateway_id, 'paypal' ) !== false ) {
                $this->render_paypal_express_button( $gateway );
            }
            
            // Para métodos Stripe Express
            if ( strpos( $gateway_id, 'stripe' ) !== false ) {
                $this->render_stripe_express_buttons( $gateway );
            }
            
            // Para Amazon Pay
            if ( strpos( $gateway_id, 'amazon' ) !== false ) {
                $this->render_amazon_pay_button( $gateway );
            }
        }
    }
    
    /**
     * Renderizar botón de PayPal Express
     */
    private function render_paypal_express_button( $gateway ) {
        if ( method_exists( $gateway, 'checkout_express_button' ) ) {
            $gateway->checkout_express_button();
        } elseif ( method_exists( $gateway, 'express_checkout_button' ) ) {
            $gateway->express_checkout_button();
        } else {
            ?>
            <button type="button" class="ckfylt25-express-paypal-button" onclick="window.location.href='<?php echo esc_url( $gateway->get_return_url() ); ?>'">
                <?php esc_html_e( 'Pay with PayPal', 'checkoutify-lite' ); ?>
            </button>
            <?php
        }
    }
    
    /**
     * Renderizar botones de Stripe Express (Google Pay, Apple Pay)
     */
    private function render_stripe_express_buttons( $gateway ) {
        if ( method_exists( $gateway, 'display_express_checkout_button' ) ) {
            $gateway->display_express_checkout_button();
        } elseif ( method_exists( $gateway, 'payment_request_button' ) ) {
            $gateway->payment_request_button();
        } else {
            ?>
            <button type="button" class="ckfylt25-express-stripe-button" onclick="document.querySelector('#place_order').click();">
                <?php esc_html_e( 'Pay with Stripe', 'checkoutify-lite' ); ?>
            </button>
            <?php
        }
    }

    /**
     * Renderizar botón de Amazon Pay
     */
    private function render_amazon_pay_button( $gateway ) {
        if ( method_exists( $gateway, 'checkout_button' ) ) {
            $gateway->checkout_button();
        } else {
            ?>
            <button type="button" class="ckfylt25-express-amazon-button">
                <?php esc_html_e( 'Pay with Amazon', 'checkoutify-lite' ); ?>
            </button>
            <?php
        }
    }

    /**
     * Limpiar valores de campos deshabilitados durante el procesamiento del checkout
     */
    public function clean_disabled_fields_values() {
        // Verify nonce for security
        if ( ! isset( $_POST['woocommerce-process-checkout-nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ), 'woocommerce-process_checkout' ) ) {
            return;
        }
        
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', [] );
        
        if ( ! empty( $disabled_fields ) && is_array( $disabled_fields ) ) {
            foreach ( $disabled_fields as $field_key ) {
                // Support both full keys (e.g., billing_company) and short keys (e.g., company)
                $post_key = $field_key;
                if ( strpos( $post_key, 'billing_' ) !== 0 ) {
                    $post_key = 'billing_' . $post_key;
                }
                if ( isset( $_POST[ $post_key ] ) ) {
                    $_POST[ $post_key ] = '';
                }
            }
        }
    }

    public function relax_shipping_address_requirement( $needs_address, $package ) {
        // Respect admin setting: allow checkout without address unconditionally
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        if ( $allow_without_address ) {
            return false; // shipping cost does not require address when option is enabled
        }
        return $needs_address;
    }

    public function maybe_disable_shipping_address_requirement( $needs_address ) {
        // Respect admin setting: allow checkout without address unconditionally
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        if ( $allow_without_address ) {
            return false; // no shipping address needed when option is enabled
        }
        // Only disable shipping address requirement if cart is virtual-only
        if ( function_exists( 'WC' ) && WC()->cart ) {
            $only_virtual = true;
            foreach ( WC()->cart->get_cart() as $item ) {
                if ( isset( $item['data'] ) && is_object( $item['data'] ) && method_exists( $item['data'], 'is_virtual' ) ) {
                    if ( ! $item['data']->is_virtual() ) {
                        $only_virtual = false;
                        break;
                    }
                } else {
                    $only_virtual = false;
                    break;
                }
            }
            if ( $only_virtual ) {
                return false; // no shipping address needed if all products are virtual
            }
        }
        return $needs_address;
    }

    public function prefer_shipping_address_destination( $destination ) {
        // If billing fields are disabled, prefer shipping address for shipping calculations
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', [] );
        if ( ! empty( $disabled_fields ) && is_array( $disabled_fields ) ) {
            return 'shipping';
        }
        
        // Also prefer shipping destination when cart needs shipping
        if ( function_exists( 'WC' ) && WC()->cart && WC()->cart->needs_shipping() ) {
            return 'shipping';
        }
        return $destination;
    }

    public function force_ship_to_different_address_checked( $checked ) {
        // If billing fields are disabled or allowing checkout without address is enabled, show shipping form
        $disabled_fields = get_option( 'ckfylt25_disabled_billing_fields', [] );
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        if ( $allow_without_address || ( ! empty( $disabled_fields ) && is_array( $disabled_fields ) ) ) {
            return true;
        }
        return $checked;
    }

    public function maybe_apply_base_location_destination( $packages ) {
        // When allowing checkout without address, apply store base location as fallback for destination
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        if ( ! $allow_without_address ) {
            return $packages;
        }
        $base = wc_get_base_location();
        $base_country = isset( $base['country'] ) ? $base['country'] : '';
        $base_state   = isset( $base['state'] ) ? $base['state'] : '';
        $base_postcode = get_option( 'woocommerce_store_postcode' );
        $base_city     = get_option( 'woocommerce_store_city' );
        foreach ( $packages as &$package ) {
            if ( ! isset( $package['destination'] ) || ! is_array( $package['destination'] ) ) {
                $package['destination'] = array();
            }
            if ( empty( $package['destination']['country'] ) ) {
                $package['destination']['country'] = $base_country;
            }
            if ( empty( $package['destination']['state'] ) ) {
                $package['destination']['state'] = $base_state;
            }
            if ( empty( $package['destination']['postcode'] ) ) {
                $package['destination']['postcode'] = $base_postcode;
            }
            if ( empty( $package['destination']['city'] ) ) {
                $package['destination']['city'] = $base_city;
            }
        }
        return $packages;
    }

    /**
     * When allowing checkout without address, tell Woo that the cart does not need shipping.
     * This bypasses address validation and shipping method requirements.
     */
    public function maybe_disable_cart_needs_shipping( $needs_shipping ) {
        $allow_without_address = get_option( 'ckfylt25_allow_checkout_without_address', false );
        if ( $allow_without_address ) {
            // Do NOT globally disable shipping. Only disable when the cart is virtual-only.
            if ( function_exists( 'WC' ) && WC()->cart ) {
                $only_virtual = true;
                foreach ( WC()->cart->get_cart() as $item ) {
                    if ( isset( $item['data'] ) && is_object( $item['data'] ) && method_exists( $item['data'], 'is_virtual' ) ) {
                        if ( ! $item['data']->is_virtual() ) {
                            $only_virtual = false;
                            break;
                        }
                    } else {
                        $only_virtual = false;
                        break;
                    }
                }
                if ( $only_virtual ) {
                    return false; // no shipping needed if all products are virtual
                }
            }
            // For physical products, keep shipping enabled so methods are visible
            return $needs_shipping;
        }
        return $needs_shipping;
    }
}
