<?php

/**
 * The admin-specific functionality of the plugin.
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Extra_Product_Options_For_WooCommerce
 * @subpackage Extra_Product_Options_For_WooCommerce/includes
 */
// If this file is called directly, abort.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * EPOFW_Field_Setting class.
 */
if ( !class_exists( 'EPOFW_Field_Setting' ) ) {
    /**
     * EPOFW_Field_Setting class.
     */
    class EPOFW_Field_Setting {
        /**
         * The object of class.
         *
         * @since    1.0.0
         * @var      string $instance instance object.
         */
        protected static $instance = null;

        /**
         * Post type.
         *
         * @since 1.0.0
         * @var $post_type string Store post type.
         */
        private static $post_type = null;

        /**
         * Get current page.
         *
         * @since 1.0.0
         * @var $current_page string Store current page.
         */
        private static $current_page = null;

        /**
         * Get current tab.
         *
         * @since 1.0.0
         * @var $current_tab string Store current tab.
         */
        private static $current_tab = null;

        /**
         * Define the plugins name and versions and also call admin section.
         *
         * @since    1.0.0
         */
        public static function instance() {
            if ( is_null( self::$instance ) ) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        /**
         * Constructor.
         *
         * @since 1.0.0
         */
        public function __construct() {
            if ( !current_user_can( 'manage_options' ) ) {
                wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'extra-product-options-for-woocommerce' ) );
            }
            self::$current_page = EPOFW_Admin::epofw_current_page();
            self::$current_tab = EPOFW_Admin::epofw_current_tab();
            self::$post_type = EPOFW_DFT_POST_TYPE;
            add_action(
                'add_new_btn_prd_list',
                array($this, 'add_new_btn_prd_list_fn'),
                10,
                2
            );
        }

        /**
         * Display output.
         *
         * @since    1.0.0
         * @uses     epofw_save_method
         * @uses     epofw_add_product_option_form
         * @uses     epofw_edit_method_screen
         * @uses     epofw_delete_method
         * @uses     epofw_duplicate_method
         * @uses     epofw_list_methods_screen
         * @uses     EPOFW_Admin::epofw_updated_message()
         */
        public static function epofw_output() {
            $action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $action = ( !empty( $action ) ? sanitize_text_field( wp_unslash( $action ) ) : '' );
            $allowed_actions = array(
                'add',
                'edit',
                'delete',
                'duplicate'
            );
            $post_id_request = filter_input( INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT );
            $post_id_request = ( isset( $post_id_request ) ? sanitize_text_field( wp_unslash( $post_id_request ) ) : '' );
            $epofw_nonce = filter_input( INPUT_GET, 'epofw_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $epofw_nonce = ( isset( $epofw_nonce ) ? sanitize_text_field( wp_unslash( $epofw_nonce ) ) : '' );
            $get_epofw_add = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $get_epofw_add = ( isset( $get_epofw_add ) ? sanitize_text_field( wp_unslash( $get_epofw_add ) ) : '' );
            $get_tab = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $get_tab = ( isset( $get_tab ) ? sanitize_text_field( wp_unslash( $get_tab ) ) : '' );
            $message = filter_input( INPUT_GET, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $message = ( isset( $message ) ? sanitize_text_field( wp_unslash( $message ) ) : '' );
            if ( !empty( $action ) && in_array( $action, $allowed_actions, true ) ) {
                if ( 'add' === $action ) {
                    self::epofw_save_method();
                    self::epofw_add_product_option_form();
                } elseif ( 'edit' === $action ) {
                    if ( !empty( $epofw_nonce ) ) {
                        $getnonce = wp_verify_nonce( $epofw_nonce, 'edit_' . $post_id_request );
                        if ( isset( $getnonce ) && 1 === (int) $getnonce ) {
                            self::epofw_edit_method_screen( $post_id_request );
                        } else {
                            wp_safe_redirect( esc_url_raw( add_query_arg( array(
                                'page' => 'epofw-main',
                                'tab'  => 'extra_product_option',
                            ), admin_url( 'admin.php' ) ) ) );
                            exit;
                        }
                    } elseif ( !empty( $get_epofw_add ) ) {
                        if ( !wp_verify_nonce( $get_epofw_add, 'epofw_add' ) ) {
                            $message = 'nonce_check';
                        } else {
                            self::epofw_edit_method_screen( $post_id_request );
                        }
                    }
                } else {
                    self::epofw_list_methods_screen();
                }
            } else {
                self::epofw_list_methods_screen();
            }
        }

        /**
         * Count total Field Option.
         *
         * @since    1.0.0
         * @return int $count_method Count total Field Option ID.
         */
        public static function epofw_count_method() {
            $post_counts = wp_count_posts( self::$post_type );
            $publish = ( isset( $post_counts->publish ) ? (int) $post_counts->publish : 0 );
            $draft = ( isset( $post_counts->draft ) ? (int) $post_counts->draft : 0 );
            return $publish + $draft;
        }

        /**
         * Process option field arrays for different field types.
         *
         * @since 1.1
         *
         * @param array  $gn_value         Option data array.
         * @param array  $new_field_op_arr New Field data array.
         * @param string $field_type       Field type to determine processing logic.
         *
         * @return array
         */
        private static function epofw_option_field_arr( $gn_value, $new_field_op_arr, $field_type = '' ) {
            // Get the arrays for label, price type, price, and opt_id.
            $gn_label_value = epofw_check_array_key_exists( 'label', $gn_value );
            $gn_opt_price_type = epofw_check_array_key_exists( 'opt_price_type', $gn_value );
            $gn_opt_price = epofw_check_array_key_exists( 'opt_price', $gn_value );
            $gn_opt_id = epofw_check_array_key_exists( 'opt_id', $gn_value );
            $gn_opt_stock = epofw_check_array_key_exists( 'stock', $gn_value );
            // Validate that all required arrays exist and have the same length.
            if ( !$gn_label_value || !$gn_opt_price_type || !$gn_opt_price ) {
                return $new_field_op_arr;
            }
            $array_length = count( $gn_label_value );
            if ( count( $gn_opt_price_type ) !== $array_length || count( $gn_opt_price ) !== $array_length ) {
                return $new_field_op_arr;
            }
            // Ensure opt_id array has correct length (fill with empty strings if not present).
            if ( !$gn_opt_id || count( $gn_opt_id ) !== $array_length ) {
                $gn_opt_id = array_fill( 0, $array_length, '' );
            }
            // Ensure stock array has correct length (fill with empty strings if not present).
            if ( !$gn_opt_stock || count( $gn_opt_stock ) !== $array_length ) {
                $gn_opt_stock = array_fill( 0, $array_length, '' );
            }
            // Check if this field type needs switcher handling.
            $needs_switcher = in_array( $field_type, array('imageswitcher', 'colorswitcher'), true );
            $gn_opt_swticher = array();
            if ( $needs_switcher ) {
                // Check for opt_swticher field (the field we were missing).
                $gn_opt_swticher = epofw_check_array_key_exists( 'epofw_cs_switcher', $gn_value );
                // If switcher array doesn't exist or has different length, create default values.
                if ( !$gn_opt_swticher || count( $gn_opt_swticher ) !== $array_length ) {
                    $gn_opt_swticher = array_fill( 0, $array_length, '' );
                }
            }
            // Process each option index using for loop for better performance.
            for ($index = 0; $index < $array_length; $index++) {
                $label_value = $gn_label_value[$index];
                $price_type = $gn_opt_price_type[$index];
                $price = $gn_opt_price[$index];
                $opt_id = ( isset( $gn_opt_id[$index] ) ? $gn_opt_id[$index] : '' );
                $opt_stock = ( isset( $gn_opt_stock[$index] ) ? $gn_opt_stock[$index] : '' );
                // Only add if we have all required values.
                if ( !empty( $label_value ) && !empty( $price_type ) && !empty( $price ) ) {
                    if ( $needs_switcher ) {
                        $switcher_value = ( isset( $gn_opt_swticher[$index] ) ? $gn_opt_swticher[$index] : '' );
                        // Store in format: label||price_type||price||switcher_value||opt_id||stock.
                        $new_field_op_arr[] = $label_value . '||' . $price_type . '||' . $price . '||' . $switcher_value . '||' . $opt_id . '||' . $opt_stock;
                    } else {
                        // Store in format: label||price_type||price||opt_id||stock.
                        $new_field_op_arr[] = $label_value . '||' . $price_type . '||' . $price . '||' . $opt_id . '||' . $opt_stock;
                    }
                }
            }
            return $new_field_op_arr;
        }

        /**
         * Process individual field properties and settings.
         *
         * @since    1.0.0
         *
         * @param array  $field_data      Field data array.
         * @param string $field_id        Field ID.
         * @param string $epofw_field_key Section key.
         * @param string $field_key       Field key.
         * @param array  $new_epofw_data  Reference to the main data array.
         * @param array  $row_info        Optional row information for row-based fields.
         *
         * @return void
         */
        private static function process_field_properties(
            $field_data,
            $field_id,
            $epofw_field_key,
            $field_key,
            &$new_epofw_data,
            $row_info = null
        ) {
            // Extract field type from field data.
            $field_type = '';
            if ( isset( $field_data['field'] ) && isset( $field_data['field']['type'] ) ) {
                $field_type = $field_data['field']['type'];
            }
            // Initialize the field data structure.
            $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id] = array();
            // Add row association if provided or create default one.
            if ( $row_info && is_array( $row_info ) ) {
                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id]['row_association'] = array(
                    'row_id'   => $row_info['row_id'],
                    'group_id' => $row_info['group_id'],
                    'layout'   => $row_info['layout'],
                    'columns'  => $row_info['columns'],
                );
            } else {
                // Add default row association for fields that don't have it.
                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id]['row_association'] = array(
                    'row_id'   => 'default_row_' . $field_id,
                    'group_id' => 'default_group_' . $epofw_field_key,
                    'layout'   => 'single',
                    'columns'  => 1,
                );
            }
            foreach ( $field_data as $property_key => $property_value ) {
                if ( 'field' === $property_key ) {
                    // Process field properties (name, class, id, type, etc.).
                    if ( is_array( $property_value ) ) {
                        foreach ( $property_value as $field_property_key => $field_property_value ) {
                            if ( 'class' === $field_property_key ) {
                                unset($new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$field_property_key]);
                                $modified_class = $field_property_value;
                                $field_restriction = epofw_check_array_key_exists( 'field_restriction', $property_value );
                                if ( $field_restriction ) {
                                    $modified_class .= ' epofw_' . $field_restriction;
                                }
                                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$field_property_key] = $field_property_value;
                            } elseif ( 'name' === $field_property_key || 'id' === $field_property_key ) {
                                if ( empty( $field_property_value ) ) {
                                    $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$field_property_key] = 'epofw_' . $property_key . '_' . wp_rand();
                                } else {
                                    $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$field_property_key] = $field_property_value;
                                }
                            } else {
                                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$field_property_key] = $field_property_value;
                            }
                        }
                    }
                } elseif ( 'epofw_field_settings' === $property_key ) {
                    // Process epofw_field_settings properties (including options).
                    if ( is_array( $property_value ) ) {
                        foreach ( $property_value as $setting_key => $setting_value ) {
                            if ( 'options' === $setting_key ) {
                                $new_field_op_arr = array();
                                $new_field_op_arr_data = self::epofw_option_field_arr( $setting_value, $new_field_op_arr, $field_type );
                                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$setting_key] = $new_field_op_arr_data;
                            } else {
                                $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key][$setting_key] = $setting_value;
                            }
                        }
                    } else {
                        $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                    }
                } elseif ( 'field_container_settings' === $property_key ) {
                    // Process field_container_settings properties (including nested arrays for padding/margin).
                    if ( is_array( $property_value ) ) {
                        // Handle padding: If FREE version sends simple value, convert to array with same value for all sides.
                        if ( isset( $property_value['padding'] ) && !is_array( $property_value['padding'] ) && !empty( $property_value['padding'] ) ) {
                            // FREE version: Simple padding value - convert to array with same value for all sides.
                            $padding_value = absint( $property_value['padding'] );
                            $property_value['padding'] = array(
                                'top'    => $padding_value,
                                'right'  => $padding_value,
                                'bottom' => $padding_value,
                                'left'   => $padding_value,
                                'units'  => 'px',
                            );
                        } elseif ( isset( $property_value['padding'] ) && is_array( $property_value['padding'] ) ) {
                            // PRO version: Advanced padding - clean up the array structure.
                            if ( isset( $property_value['padding']['top'] ) || isset( $property_value['padding']['right'] ) || isset( $property_value['padding']['bottom'] ) || isset( $property_value['padding']['left'] ) ) {
                                // Advanced padding is set, keep only the advanced structure.
                                // Remove any numeric keys that might have been created by PHP's mixed array handling.
                                $property_value['padding'] = array_filter( $property_value['padding'], function ( $key ) {
                                    return in_array( $key, array(
                                        'top',
                                        'right',
                                        'bottom',
                                        'left',
                                        'units'
                                    ), true );
                                }, ARRAY_FILTER_USE_KEY );
                                // Ensure units has a default value.
                                if ( empty( $property_value['padding']['units'] ) ) {
                                    $property_value['padding']['units'] = 'px';
                                }
                            }
                        }
                        // Handle margin: If FREE version sends simple value, convert to array with same value for all sides.
                        if ( isset( $property_value['margin'] ) && !is_array( $property_value['margin'] ) && !empty( $property_value['margin'] ) ) {
                            // FREE version: Simple margin value - convert to array with same value for all sides.
                            $margin_value = absint( $property_value['margin'] );
                            $property_value['margin'] = array(
                                'top'    => $margin_value,
                                'right'  => $margin_value,
                                'bottom' => $margin_value,
                                'left'   => $margin_value,
                                'units'  => 'px',
                            );
                        } elseif ( isset( $property_value['margin'] ) && is_array( $property_value['margin'] ) ) {
                            // PRO version: Advanced margin - clean up the array structure.
                            if ( isset( $property_value['margin']['top'] ) || isset( $property_value['margin']['right'] ) || isset( $property_value['margin']['bottom'] ) || isset( $property_value['margin']['left'] ) ) {
                                // Advanced margin is set, keep only the advanced structure.
                                // Remove any numeric keys that might have been created by PHP's mixed array handling.
                                $property_value['margin'] = array_filter( $property_value['margin'], function ( $key ) {
                                    return in_array( $key, array(
                                        'top',
                                        'right',
                                        'bottom',
                                        'left',
                                        'units'
                                    ), true );
                                }, ARRAY_FILTER_USE_KEY );
                                // Ensure units has a default value.
                                if ( empty( $property_value['margin']['units'] ) ) {
                                    $property_value['margin']['units'] = 'px';
                                }
                            }
                        }
                        // Save the entire field_container_settings array.
                        $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                    } else {
                        $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                    }
                } elseif ( 'input_container_settings' === $property_key ) {
                    // Process input_container_settings properties (including nested arrays for padding/margin/width).
                    if ( is_array( $property_value ) ) {
                        // Handle padding: If FREE version sends simple value, convert to array with same value for all sides.
                        if ( isset( $property_value['padding'] ) && !is_array( $property_value['padding'] ) && !empty( $property_value['padding'] ) ) {
                            // FREE version: Simple padding value - convert to array with same value for all sides.
                            $padding_value = absint( $property_value['padding'] );
                            $property_value['padding'] = array(
                                'top'    => $padding_value,
                                'right'  => $padding_value,
                                'bottom' => $padding_value,
                                'left'   => $padding_value,
                                'units'  => 'px',
                            );
                        } elseif ( isset( $property_value['padding'] ) && is_array( $property_value['padding'] ) ) {
                            // PRO version: Advanced padding - clean up the array structure.
                            if ( isset( $property_value['padding']['top'] ) || isset( $property_value['padding']['right'] ) || isset( $property_value['padding']['bottom'] ) || isset( $property_value['padding']['left'] ) ) {
                                // Advanced padding is set, keep only the advanced structure.
                                $property_value['padding'] = array_filter( $property_value['padding'], function ( $key ) {
                                    return in_array( $key, array(
                                        'top',
                                        'right',
                                        'bottom',
                                        'left',
                                        'units'
                                    ), true );
                                }, ARRAY_FILTER_USE_KEY );
                                // Ensure units has a default value.
                                if ( empty( $property_value['padding']['units'] ) ) {
                                    $property_value['padding']['units'] = 'px';
                                }
                            }
                        }
                        // Handle margin: If FREE version sends simple value, convert to array with same value for all sides.
                        if ( isset( $property_value['margin'] ) && !is_array( $property_value['margin'] ) && !empty( $property_value['margin'] ) ) {
                            // FREE version: Simple margin value - convert to array with same value for all sides.
                            $margin_value = absint( $property_value['margin'] );
                            $property_value['margin'] = array(
                                'top'    => $margin_value,
                                'right'  => $margin_value,
                                'bottom' => $margin_value,
                                'left'   => $margin_value,
                                'units'  => 'px',
                            );
                        } elseif ( isset( $property_value['margin'] ) && is_array( $property_value['margin'] ) ) {
                            // PRO version: Advanced margin - clean up the array structure.
                            if ( isset( $property_value['margin']['top'] ) || isset( $property_value['margin']['right'] ) || isset( $property_value['margin']['bottom'] ) || isset( $property_value['margin']['left'] ) ) {
                                // Advanced margin is set, keep only the advanced structure.
                                $property_value['margin'] = array_filter( $property_value['margin'], function ( $key ) {
                                    return in_array( $key, array(
                                        'top',
                                        'right',
                                        'bottom',
                                        'left',
                                        'units'
                                    ), true );
                                }, ARRAY_FILTER_USE_KEY );
                                // Ensure units has a default value.
                                if ( empty( $property_value['margin']['units'] ) ) {
                                    $property_value['margin']['units'] = 'px';
                                }
                            }
                        }
                        // Handle width: If FREE version sends simple value, keep as is (max-width in px).
                        // If PRO version sends array, keep the array structure.
                        if ( isset( $property_value['width'] ) && is_array( $property_value['width'] ) ) {
                            // PRO version: Advanced width - clean up the array structure.
                            $property_value['width'] = array_filter( $property_value['width'], function ( $key ) {
                                return in_array( $key, array('value', 'units'), true );
                            }, ARRAY_FILTER_USE_KEY );
                            // Ensure units has a default value.
                            if ( empty( $property_value['width']['units'] ) ) {
                                $property_value['width']['units'] = 'px';
                            }
                        }
                        // Save the entire input_container_settings array.
                        $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                    } else {
                        $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                    }
                } else {
                    $new_epofw_data['general'][$epofw_field_key][$field_key][$field_id][$property_key] = $property_value;
                }
            }
        }

        /**
         * Process row groups and integrate fields with row associations.
         *
         * @since    1.0.0
         *
         * @param array  $row_groups_data Row groups data from form submission.
         * @param string $section_id      Section ID.
         * @param array  $new_epofw_data  Reference to the main data array.
         *
         * @return void
         */
        private static function process_row_groups( $row_groups_data, $section_id, &$new_epofw_data ) {
            if ( !is_array( $row_groups_data ) ) {
                return;
            }
            foreach ( $row_groups_data as $group_id => $group_data ) {
                if ( !is_array( $group_data ) ) {
                    continue;
                }
                // Extract group information from HTML data attributes.
                $group_info = array(
                    'group_id'    => sanitize_text_field( $group_id ),
                    'layout_type' => 'single',
                    'rows_count'  => 1,
                );
                // Process each row within the group.
                foreach ( $group_data as $row_id => $row_data ) {
                    if ( !is_array( $row_data ) ) {
                        continue;
                    }
                    // Extract row information.
                    $row_info = array(
                        'row_id'   => sanitize_text_field( $row_id ),
                        'group_id' => $group_info['group_id'],
                        'layout'   => 'single',
                        'columns'  => 1,
                    );
                    // Process fields within this row and add them to the main fields structure.
                    if ( isset( $row_data['fields'] ) && is_array( $row_data['fields'] ) ) {
                        foreach ( $row_data['fields'] as $field_id => $field_data ) {
                            if ( is_array( $field_data ) ) {
                                // Process field with row association and add to main structure.
                                self::process_field_properties(
                                    $field_data,
                                    $field_id,
                                    $section_id,
                                    'fields',
                                    $new_epofw_data,
                                    $row_info
                                );
                            }
                        }
                    }
                }
            }
        }

        /**
         * Save Field Option when add or edit.
         *
         * @since    1.0.0
         *
         * @param int $method_id Product Field id.
         *
         * @return bool false when nonce is not verified.
         * @uses     epofw_count_method()
         * @uses     Extra_Product_Options_For_WooCommerce::epofw_updated_message()
         */
        private static function epofw_save_method( $method_id = 0 ) {
            if ( !current_user_can( 'manage_options' ) ) {
                wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'extra-product-options-for-woocommerce' ) );
            }
            $action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $epofw_save = filter_input( INPUT_POST, 'epofw_save', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
            $epofw_save = ( isset( $epofw_save ) ? sanitize_text_field( wp_unslash( $epofw_save ) ) : '' );
            if ( isset( $action ) && !empty( $action ) ) {
                if ( !empty( $epofw_save ) ) {
                    if ( !isset( $_POST['epofw_save_addon_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['epofw_save_addon_nonce'] ) ), 'epofw_save_addon' ) ) {
                        wp_die( esc_html__( 'Security check failed.', 'extra-product-options-for-woocommerce' ) );
                    }
                    // Parse optimized flat structure with custom tables.
                    $raw_post_data = $_POST;
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
                    $parsed_data = EPOFW_Post_Parser::parse_addon_data( $raw_post_data );
                    /**
                     * Filter parsed addon data before save (e.g. normalize Product Group options).
                     *
                     * @since 4.4.6
                     * @param array $parsed_data Parsed addon data.
                     */
                    $parsed_data = apply_filters( 'epofw_parsed_addon_data_before_save', $parsed_data );
                    if ( empty( $parsed_data ) ) {
                        wp_die( esc_html__( 'Invalid addon data format. Please try again.', 'extra-product-options-for-woocommerce' ) );
                    }
                    $epofw_data = $parsed_data;
                    // v4.4.0: Parser already creates complete structure - use it directly!
                    $new_epofw_data = $epofw_data;
                    // Extract meta for wp_posts table.
                    $post_title = ( isset( $new_epofw_data['epofw_addon_name'] ) ? $new_epofw_data['epofw_addon_name'] : '' );
                    $epofw_shipping_status = ( isset( $new_epofw_data['epofw_addon_status'] ) ? $new_epofw_data['epofw_addon_status'] : '' );
                    // Data processing completed successfully.
                    $product_option_count = self::epofw_count_method();
                    $method_id = (int) $method_id;
                    if ( isset( $epofw_shipping_status ) && 'on' === $epofw_shipping_status ) {
                        $post_status = 'publish';
                    } else {
                        $post_status = 'draft';
                    }
                    if ( '' !== $method_id && 0 !== $method_id ) {
                        $fee_post = array(
                            'ID'          => $method_id,
                            'post_title'  => $post_title,
                            'post_status' => $post_status,
                            'menu_order'  => $product_option_count + 1,
                            'post_type'   => self::$post_type,
                        );
                        $method_id = wp_update_post( $fee_post );
                    } else {
                        $fee_post = array(
                            'post_title'  => $post_title,
                            'post_status' => $post_status,
                            'menu_order'  => $product_option_count + 1,
                            'post_type'   => self::$post_type,
                        );
                        $method_id = wp_insert_post( $fee_post );
                    }
                    if ( '' !== $method_id && 0 !== $method_id ) {
                        if ( $method_id > 0 ) {
                            // v4.4.0+: Save to custom tables only (migration provided).
                            if ( EPOFW_Custom_Tables::is_enabled() ) {
                                // Reorganize fields from section level to row_groups structure.
                                if ( !empty( $new_epofw_data['general'] ) ) {
                                    foreach ( $new_epofw_data['general'] as $section_id => &$section_data ) {
                                        if ( !empty( $section_data['fields'] ) && is_array( $section_data['fields'] ) ) {
                                            // First pass: Group fields by group_id and layout.
                                            $fields_by_group = array();
                                            foreach ( $section_data['fields'] as $field_id => $field_data ) {
                                                if ( !is_array( $field_data ) || !isset( $field_data['row_association'] ) ) {
                                                    continue;
                                                }
                                                $group_id = $field_data['row_association']['group_id'];
                                                $row_id = ( isset( $field_data['row_association']['row_id'] ) ? $field_data['row_association']['row_id'] : '' );
                                                $layout = ( isset( $field_data['row_association']['layout'] ) ? $field_data['row_association']['layout'] : 'single' );
                                                // Generate group_id if empty (fallback for fields without proper association).
                                                if ( empty( $group_id ) ) {
                                                    $group_id = 'group_' . $section_id . '_' . $field_id;
                                                    $field_data['row_association']['group_id'] = $group_id;
                                                }
                                                // Generate row_id if empty (fallback for fields without proper association).
                                                if ( empty( $row_id ) ) {
                                                    $row_id = 'row_' . $section_id . '_' . $field_id;
                                                    $field_data['row_association']['row_id'] = $row_id;
                                                }
                                                if ( !isset( $fields_by_group[$group_id] ) ) {
                                                    $fields_by_group[$group_id] = array(
                                                        'layout' => $layout,
                                                        'fields' => array(),
                                                    );
                                                }
                                                $fields_by_group[$group_id]['fields'][$field_id] = $field_data;
                                            }
                                            // Second pass: Assign unique row_ids to each field (rows = columns in UI).
                                            foreach ( $fields_by_group as $group_id => $group_info ) {
                                                $group_fields = $group_info['fields'];
                                                $layout = $group_info['layout'];
                                                // Ensure structure exists.
                                                if ( !isset( $section_data['row_groups'][$group_id] ) ) {
                                                    $section_data['row_groups'][$group_id] = array(
                                                        'row_group_settings' => array(
                                                            'enabled' => '',
                                                        ),
                                                        'rows'               => array(),
                                                    );
                                                }
                                                // For multi-column, preserve original row_ids from each field.
                                                if ( 'multiple' === $layout && count( $group_fields ) > 1 ) {
                                                    $column_number = 1;
                                                    foreach ( $group_fields as $field_id => $field_data ) {
                                                        // USE ORIGINAL row_id instead of generating new one.
                                                        $original_row_id = $field_data['row_association']['row_id'];
                                                        // Create row structure with ORIGINAL row_id.
                                                        if ( !isset( $section_data['row_groups'][$group_id]['rows'][$original_row_id] ) ) {
                                                            $section_data['row_groups'][$group_id]['rows'][$original_row_id] = array(
                                                                'column_settings' => array(
                                                                    'enabled' => '',
                                                                ),
                                                                'row_number'      => $column_number,
                                                                'fields'          => array(),
                                                            );
                                                        }
                                                        $section_data['row_groups'][$group_id]['rows'][$original_row_id]['fields'][$field_id] = $field_data;
                                                        ++$column_number;
                                                    }
                                                } else {
                                                    // Single column: Use original row_id.
                                                    foreach ( $group_fields as $field_id => $field_data ) {
                                                        $row_id = $field_data['row_association']['row_id'];
                                                        if ( !isset( $section_data['row_groups'][$group_id]['rows'][$row_id] ) ) {
                                                            $section_data['row_groups'][$group_id]['rows'][$row_id] = array(
                                                                'column_settings' => array(
                                                                    'enabled' => '',
                                                                ),
                                                                'row_number'      => 1,
                                                                'fields'          => array(),
                                                            );
                                                        }
                                                        $section_data['row_groups'][$group_id]['rows'][$row_id]['fields'][$field_id] = $field_data;
                                                    }
                                                }
                                            }
                                            // Remove fields from section level.
                                            unset($section_data['fields']);
                                        }
                                    }
                                }
                                EPOFW_Custom_Tables::save_addon( $method_id, $new_epofw_data );
                            }
                        }
                    } else {
                        echo '<div class="updated error"><p>' . esc_html__( 'Error saving Product Option.', 'extra-product-options-for-woocommerce' ) . '</p></div>';
                        return false;
                    }
                    $epofw_add = wp_create_nonce( 'epofw_add' );
                    if ( 'add' === $action ) {
                        $add_action_redirect_url = EPOFW_Admin::dynamic_url(
                            self::$current_page,
                            self::$current_tab,
                            'edit',
                            $method_id,
                            esc_attr( $epofw_add ),
                            'created'
                        );
                        wp_safe_redirect( $add_action_redirect_url );
                        exit;
                    }
                    if ( 'edit' === $action ) {
                        $edit_action_redirect_url = EPOFW_Admin::dynamic_url(
                            self::$current_page,
                            self::$current_tab,
                            'edit',
                            $method_id,
                            esc_attr( $epofw_add ),
                            'saved'
                        );
                        wp_safe_redirect( $edit_action_redirect_url );
                        exit;
                    }
                }
            }
        }

        /**
         * Edit Product Option screen.
         *
         * @since    1.0.0
         *
         * @param string $id Get Product Option id.
         *
         * @uses     epofw_edit_method()
         * @uses     epofw_save_method()
         */
        public static function epofw_edit_method_screen( $id ) {
            self::epofw_save_method( $id );
            self::epofw_edit_method();
        }

        /**
         * Edit Product Option.
         *
         * @since    1.0.0
         */
        public static function epofw_edit_method() {
            include EPOFW_PLUGIN_DIR . '/builder/addon-builder.php';
        }

        /**
         * Add new button in Product Option list section.
         *
         * @param string $link_method_url Link method url.
         * @param string $text            button text.
         */
        public function add_new_btn_prd_list_fn( $link_method_url, $text ) {
            ?>
			<a href="<?php 
            echo esc_url( $link_method_url );
            ?>" class="page-title-action">
				<?php 
            echo esc_html( $text );
            ?>
			</a>
			<a href="<?php 
            echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=epofw_import_all_fields' ), 'epofw_import_fields_nonce' ) );
            ?>" class="page-title-action">
				<?php 
            esc_html_e( 'Import Dummy Fields', 'extra-product-options-for-woocommerce' );
            ?>
			</a>
			<?php 
        }

        /**
         * List_product_options function.
         *
         * @since 1.0.0
         */
        public static function epofw_list_methods_screen() {
            include EPOFW_PLUGIN_DIR . '/builder/addons-list.php';
        }

        /**
         * Add_product_option_form function.
         *
         * @since    1.0.0
         */
        public static function epofw_add_product_option_form() {
            include EPOFW_PLUGIN_DIR . '/builder/addon-builder.php';
        }

    }

}