<?php
if (!defined('ABSPATH')) {
    exit;
}

if (filter_has_var(INPUT_POST, 'ninja_single_field_mapping')) {

    // Verify nonce safely
    $brainx_nonce = filter_input(INPUT_POST, 'brainx_nonce', FILTER_SANITIZE_STRING);
    if (!wp_verify_nonce($brainx_nonce, 'brainx_save_settings')) {
        wp_die(esc_html__('Nonce verification failed', 'brainx-form-connector'));
    }

    $brainx_final_array = array();

    // Form ID
    $brainx_form_id_save = filter_input(INPUT_POST, 'form_id_send', FILTER_VALIDATE_INT) ?: 0;

    // Get the select_map_fields_name array safely
    $brainx_raw_select_names = filter_input(INPUT_POST, 'select_map_fields_name', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $brainx_select_map_fields_name = is_array($brainx_raw_select_names) 
        ? array_map('sanitize_text_field', wp_unslash($brainx_raw_select_names))
        : array();

    foreach ($brainx_select_map_fields_name as $brainx_name) {
        $brainx_arr = array();
        $brainx_name = sanitize_text_field($brainx_name);

        // Get API options safely
        $brainx_raw_api_options = filter_input(INPUT_POST, 'api_options_' . $brainx_name, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        $brainx_api_options = is_array($brainx_raw_api_options)
            ? array_map('sanitize_text_field', wp_unslash($brainx_raw_api_options))
            : array();

        // Get form field options safely
        $brainx_raw_form_options = filter_input(INPUT_POST, 'form_options_' . $brainx_name, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        $brainx_form_options = is_array($brainx_raw_form_options)
            ? array_map('sanitize_text_field', wp_unslash($brainx_raw_form_options))
            : array();

        foreach ($brainx_api_options as $brainx_key => $brainx_api_field) {
            $brainx_form_value = isset($brainx_form_options[$brainx_key]) ? $brainx_form_options[$brainx_key] : '';
            $brainx_arr[$brainx_api_field] = array(
                'api_field_value' => $brainx_api_field,
                'form_field_value' => $brainx_form_value
            );
        }

        $brainx_final_array[$brainx_name] = $brainx_arr;
    }

    // Save the mapping
    $brainx_key_matched = '_brainx_ninja_form_api_select_matching_' . $brainx_form_id_save;
    update_option($brainx_key_matched, $brainx_final_array);
}


$brainx_key_matched = '_brainx_ninja_form_api_select_matching_' . $brainx_form_id;
$brainx_saved_mapping = get_option($brainx_key_matched);

if (!empty($brainx_select_fields)) {
    ?>
    <div class="wrap">
        <h3><?php esc_attr_e('Select Fields Mapping', 'brainx-form-connector'); ?></h3>
        <form method="post" action="">
            <?php
            foreach ($brainx_select_fields as $brainx_key => $brainx_api_field) {
                if (isset($brainx_matched_fields_array[$brainx_key])) {
                    $brainx_matched_field_data = $brainx_matched_fields_array[$brainx_key];
                    $brainx_id = $brainx_matched_field_data->id;
                    $brainx_label = $brainx_matched_field_data->label;
                    $brainx_options = brainx_get_ninja_form_option_by_id($brainx_id);
                    if (!empty($brainx_options)) {
                        $brainx_options = unserialize($brainx_options);
                        $brainx_field_name = $brainx_api_field['name'];
                        $brainx_saved_values = isset($brainx_saved_mapping[$brainx_field_name]) ? $brainx_saved_mapping[$brainx_field_name] : '';
                        ?>
                        <div class="field_wrap_custom">
                            <h4 class="form_tab_div"><?php echo esc_html($brainx_api_field['label']); ?></h4>
                            <input type="hidden" name="select_map_fields_name[]" value="<?php echo esc_html($brainx_api_field['name']); ?>"/>
                            <table class="form-table hide_show">

                                <?php
                                foreach ($brainx_api_field['values'] as $brainx_kk => $brainx_oparr) {
                                    $brainx_opt_value = '';
                                    if (!empty($brainx_saved_values)) {
                                        $brainx_inn_array = isset($brainx_saved_values[$brainx_oparr['value']]) ? $brainx_saved_values[$brainx_oparr['value']] : '';
                                        $brainx_opt_value = isset($brainx_inn_array['form_field_value']) ? $brainx_inn_array['form_field_value'] : '';
                                    }
                                    ?>
                                    <tr>
                                        <td>API field:<select name="api_options_<?php echo esc_attr($brainx_api_field['name']); ?>[]">
                                                <option value="<?php echo esc_attr($brainx_oparr['value']) ?>"><?php echo esc_attr($brainx_oparr['label']) ?></option>
                                            </select></td>
                                        <td>
                                            Form Field:
                                            <select name="form_options_<?php echo esc_attr($brainx_api_field['name']); ?>[]">
                                                <?php
                                                echo '<option value="">--select--</option>';
                                                foreach ($brainx_options as $brainx_option) {
                                                    $brainx_label = $brainx_option['label'];
                                                    $brainx_value = $brainx_option['value'];
                                                    $brainx_selected = '';
                                                    if ($brainx_opt_value == $brainx_value) {
                                                        $brainx_selected = 'selected=""';
                                                    }
                                                    echo '<option value="' . esc_attr($brainx_value) . '" ' . esc_attr($brainx_selected) . '>' . esc_attr($brainx_label) . '</option>';
                                                }
                                                ?>
                                            </select></td>
                                        </td>    
                                    </tr>
                                    <?php
                                }
                                ?>

                            </table>
                        </div>
                        <?php
                    }
                }
            }
            wp_nonce_field('brainx_save_settings', 'brainx_nonce');
            ?>
            <input type="hidden" name="form_id_send" value="<?php echo esc_attr($brainx_form_id) ?>" />
            <input type="submit" name="ninja_single_field_mapping" value="Save" class="button button-primary" />
        </form>
</div>
    <?php
}