<?php
/**
 * Custom Fields Display Handler
 *
 * @package ShopExplorer
 * @since 1.0.0
 */

namespace SHOPEXPLORER;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Custom Fields Display class
 *
 * Handles displaying custom fields on product pages and storing them in orders
 *
 * @since 1.0.0
 */
class SHOPEX_CustomFieldsDisplay {

    /**
     * Constructor
     */
    public function __construct() {
        // Display custom fields on single product page - BEFORE add to cart button
        add_action( 'woocommerce_before_add_to_cart_button', [ $this, 'display_custom_fields' ], 10 );
        
        // Add custom fields to cart item data
        add_filter( 'woocommerce_add_cart_item_data', [ $this, 'add_custom_fields_to_cart' ], 10, 3 );
        
        // Display custom fields in cart
        add_filter( 'woocommerce_get_item_data', [ $this, 'display_custom_fields_in_cart' ], 10, 2 );
        
        // Add custom fields to order items
        add_action( 'woocommerce_checkout_create_order_line_item', [ $this, 'add_custom_fields_to_order_items' ], 10, 4 );
        
        // Display custom fields in admin order items
        add_action( 'woocommerce_after_order_itemmeta', [ $this, 'display_custom_fields_in_admin_order' ], 10, 3 );
    }

    /**
     * Get custom fields for a product
     *
     * @param int $product_id Product ID
     * @return array Custom fields
     */
    private function get_product_custom_fields( $product_id ) {
        $custom_fields = [];
        $meta_data = get_post_meta( $product_id );
        
        foreach ( $meta_data as $key => $value ) {
            // Only get custom fields that start with _custom_ but NOT _custom_field_config_
            if ( strpos( $key, '_custom_' ) === 0 && strpos( $key, '_custom_field_config_' ) !== 0 ) {
                $field_key = str_replace( '_custom_', '', $key );
                
                // Skip if the field key itself contains "field_config"
                if ( strpos( $field_key, 'field_config' ) !== false ) {
                    continue;
                }
                
                // Get field configuration
                $field_config = get_post_meta( $product_id, '_custom_field_config_' . $field_key, true );
                $is_editable = false;
                $field_type = 'text';
                
                if ( is_array( $field_config ) ) {
                    $is_editable = isset( $field_config['editable'] ) && $field_config['editable'];
                    $field_type = $field_config['type'] ?? 'text';
                }
                
                $field_value = is_array( $value ) ? $value[0] : $value;
                
                // Skip if value is an array or object
                if ( is_array( $field_value ) || is_object( $field_value ) ) {
                    continue;
                }
                
                // Skip if value is serialized string
                if ( is_string( $field_value ) && ( strpos( $field_value, 'a:' ) === 0 || strpos( $field_value, 'O:' ) === 0 ) ) {
                    continue;
                }
                
                $custom_fields[] = [
                    'key' => $field_key,
                    'value' => $field_value,
                    'label' => ucwords( str_replace( [ '_', '-' ], ' ', $field_key ) ),
                    'editable' => $is_editable,
                    'type' => $field_type,
                ];
            }
        }
        
        return $custom_fields;
    }

    /**
     * Display custom fields on single product page
     */
    public function display_custom_fields() {
        global $product;
        
        if ( ! $product ) {
            return;
        }
        
        $custom_fields = $this->get_product_custom_fields( $product->get_id() );
        
        if ( empty( $custom_fields ) ) {
            return;
        }
        
        echo '<div class="shopex-custom-fields" style="margin: 20px 0;">';
        
        foreach ( $custom_fields as $field ) {
            echo '<div class="shopex-custom-field" style="margin-bottom: 15px;">';
            echo '<label for="shopex_custom_' . esc_attr( $field['key'] ) . '" style="display: block; margin-bottom: 5px; font-weight: 600;">';
            echo esc_html( $field['label'] );
            if ( ! $field['editable'] ) {
                echo ' <span style="font-weight: normal; color: #666;">(Read-only)</span>';
            }
            echo '</label>';
            
            if ( $field['editable'] ) {
                $field_name = 'shopex_custom_' . esc_attr( $field['key'] );
                $field_id = 'shopex_custom_' . esc_attr( $field['key'] );
                $field_value = esc_attr( $field['value'] );
                
                switch ( $field['type'] ) {
                    case 'textarea':
                        echo '<textarea id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $field_name ) . '" rows="3" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">' . esc_textarea( $field_value ) . '</textarea>';
                        break;
                    case 'number':
                        echo '<input type="number" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $field_name ) . '" value="' . esc_attr( $field_value ) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" />';
                        break;
                    case 'date':
                        echo '<input type="date" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $field_name ) . '" value="' . esc_attr( $field_value ) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" />';
                        break;
                    case 'checkbox':
                        // Using Yoda conditions
                        $checked = '';
                        if ( 'yes' === $field_value || '1' === $field_value || 'true' === $field_value ) {
                            $checked = 'checked';
                        }
                        echo '<label style="display: flex; align-items: center; gap: 8px;"><input type="checkbox" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $field_name ) . '" value="yes" ' . esc_attr( $checked ) . ' /> <span>Yes</span></label>';
                        break;
                    case 'text':
                    default:
                        echo '<input type="text" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $field_name ) . '" value="' . esc_attr( $field_value ) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" />';
                        break;
                }
            } else {
                echo '<div style="padding: 8px; background: #f5f5f5; border-radius: 4px;">' . esc_html( $field['value'] ) . '</div>';
            }
            
            echo '</div>';
        }
        
        echo '</div>';
    }

    /**
     * Add custom fields to cart item data
     *
     * @param array $cart_item_data Cart item data
     * @param int   $product_id Product ID
     * @param int   $variation_id Variation ID
     * @return array Modified cart item data
     */
    public function add_custom_fields_to_cart( $cart_item_data, $product_id, $variation_id ) {
        $custom_fields = $this->get_product_custom_fields( $product_id );
        
        if ( ! empty( $custom_fields ) ) {
            foreach ( $custom_fields as $key => $field ) {
                $field_name = 'shopex_custom_' . $field['key'];
                
                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce
                if ( $field['editable'] && isset( $_POST[ $field_name ] ) ) {
                    // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                    $value = wp_unslash( $_POST[ $field_name ] );
                    
                    // Sanitize based on field type
                    switch ( $field['type'] ) {
                        case 'textarea':
                            $custom_fields[ $key ]['value'] = sanitize_textarea_field( $value );
                            break;
                        case 'number':
                            $custom_fields[ $key ]['value'] = floatval( $value );
                            break;
                        case 'checkbox':
                            // Using Yoda condition
                            if ( 'yes' === $value ) {
                                $custom_fields[ $key ]['value'] = 'yes';
                            } else {
                                $custom_fields[ $key ]['value'] = 'no';
                            }
                            break;
                        case 'date':
                        case 'text':
                        default:
                            $custom_fields[ $key ]['value'] = sanitize_text_field( $value );
                            break;
                    }
                }
            }
            
            $cart_item_data['shopex_custom_fields'] = $custom_fields;
            $cart_item_data['unique_key'] = md5( wp_json_encode( $custom_fields ) );
        }
        
        return $cart_item_data;
    }

    /**
     * Display custom fields in cart
     *
     * @param array $item_data Item data
     * @param array $cart_item Cart item
     * @return array Modified item data
     */
    public function display_custom_fields_in_cart( $item_data, $cart_item ) {
        if ( isset( $cart_item['shopex_custom_fields'] ) && ! empty( $cart_item['shopex_custom_fields'] ) ) {
            foreach ( $cart_item['shopex_custom_fields'] as $field ) {
                // Only show fields with values - using Yoda conditions
                if ( ! empty( $field['value'] ) || '0' === $field['value'] || 0 === $field['value'] ) {
                    $item_data[] = [
                        'key'   => $field['label'],
                        'value' => $field['value'],
                    ];
                }
            }
        }
        
        return $item_data;
    }

    /**
     * Add custom fields to order items
     *
     * @param \WC_Order_Item_Product $item Order item
     * @param string                 $cart_item_key Cart item key
     * @param array                  $values Cart item values
     * @param \WC_Order              $order Order object
     */
    public function add_custom_fields_to_order_items( $item, $cart_item_key, $values, $order ) {
        if ( isset( $values['shopex_custom_fields'] ) && ! empty( $values['shopex_custom_fields'] ) ) {
            foreach ( $values['shopex_custom_fields'] as $field ) {
                // Only add fields with values - using Yoda conditions
                if ( ! empty( $field['value'] ) || '0' === $field['value'] || 0 === $field['value'] ) {
                    $item->add_meta_data( $field['label'], $field['value'], true );
                }
            }
        }
    }

    /**
     * Display custom fields in admin order items
     *
     * @param int                    $item_id Order item ID
     * @param \WC_Order_Item_Product $item Order item
     * @param \WC_Product            $product Product object
     */
    public function display_custom_fields_in_admin_order( $item_id, $item, $product ) {
        $meta_data = $item->get_meta_data();
        
        if ( empty( $meta_data ) ) {
            return;
        }
        
        $custom_fields_html = '';
        
        foreach ( $meta_data as $meta ) {
            $data = $meta->get_data();
            // Check if this is a custom field (you can identify by key pattern or just show all)
            if ( ! empty( $data['value'] ) ) {
                $custom_fields_html .= '<div class="shopex-order-custom-field" style="margin: 5px 0; padding: 5px; background: #f9f9f9; border-left: 3px solid #2271b1;">';
                $custom_fields_html .= '<strong>' . esc_html( $data['key'] ) . ':</strong> ';
                $custom_fields_html .= esc_html( $data['value'] );
                $custom_fields_html .= '</div>';
            }
        }
        
        if ( ! empty( $custom_fields_html ) ) {
            echo '<div class="shopex-custom-fields-display" style="margin-top: 10px;">';
            echo '<h4 style="margin: 10px 0 5px 0; font-size: 13px;">Custom Fields:</h4>';
            // Since we've already escaped the HTML components, we can safely output it
            echo wp_kses_post( $custom_fields_html );
            echo '</div>';
        }
    }
}

// Initialize the class
new SHOPEX_CustomFieldsDisplay();