<?php
if (!defined('ABSPATH')) {
    exit;
}
$brainx_showcls = '';
$brainx_showcls2 = '';
if (isset($_POST['save_entity_id'])) {

    if (isset($_POST['brainx_nonce_fields'])) {
        $brainx_nonce = sanitize_text_field(wp_unslash($_POST['brainx_nonce_fields']));
        if (!wp_verify_nonce($brainx_nonce, 'brainx_save_settings_fields')) {
            wp_die(esc_html_e('Nonce verification failed', 'brainx-form-connector'));
        }
    }


    $brainx_showcls2 = 'show';
    $brainx_api_enabled_fields = isset($_POST['api_enabled_fields']) ? array_map('sanitize_text_field', wp_unslash($_POST['api_enabled_fields'])) : array();
    $brainx_form_id_for_entity = isset($_POST['form_id_for_entity']) ? sanitize_text_field(wp_unslash($_POST['form_id_for_entity'])) : '';
    $brainx_entity_id = isset($_POST['entity_id']) ? sanitize_text_field(wp_unslash($_POST['entity_id'])) : '';
    $brainx_current_entity_id = isset($_POST['current_entity_id']) ? sanitize_text_field(wp_unslash($_POST['current_entity_id'])) : '';
    $brainx_assigned_company_id = isset($_POST['assigned_company_id']) ? sanitize_text_field(wp_unslash($_POST['assigned_company_id'])) : '';
    $brainx_enable_org_creation = isset($_POST['enable_org_creation']) ? sanitize_text_field(wp_unslash($_POST['enable_org_creation'])) : '';
    $brainx_key3 = 'brainx_ninja_api_enable_org_creation_' . $brainx_form_id_for_entity;
    $brainx_key = 'brainx_ninja_entity_id_for_form_' . $brainx_form_id_for_entity;
    $brainx_key2 = 'brainx_ninja_brainx_api_enabled_form_fields_' . $brainx_form_id_for_entity;
    update_option($brainx_key, $brainx_entity_id);
    update_option($brainx_key2, $brainx_api_enabled_fields);
    update_option($brainx_key3, $brainx_enable_org_creation);
    if ($brainx_entity_id != $brainx_current_entity_id) {
        $brainx_key = 'brainx_crm_settings_for_form_' . $brainx_form_id_for_entity;
        update_option($brainx_key, '');
    }
    $brainx_key4 = 'brainx_ninja_assigned_company_id_' . $brainx_form_id_for_entity;
    update_option($brainx_key4, $brainx_assigned_company_id);
}
if (isset($_POST['ninja_single_field_mapping'])) {
    if (isset($_POST['brainx_nonce'])) {
        $brainx_nonce = sanitize_text_field(wp_unslash($_POST['brainx_nonce']));
        if (!wp_verify_nonce($brainx_nonce, 'brainx_save_settings')) {
            wp_die(esc_html_e('Nonce verification failed', 'brainx-form-connector'));
        }
    }


    $brainx_final_array = array();
    $brainx_form_id_save = isset($_POST['form_id_send']) ? absint($_POST['form_id_send']) : 0;
    $brainx_form_id_save = isset($_POST['form_id_send']) ? absint($_POST['form_id_send']) : 0;

    if (isset($_POST['select_map_fields_name']) && is_array($_POST['select_map_fields_name'])) {
        // Unsanitize the entire array first
        $brainx_select_map_fields_name = array();

        $brainx_raw_names = filter_input(INPUT_POST, 'select_map_fields_name', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

        if (is_array($brainx_raw_names)) {
            $brainx_raw_names = wp_unslash($brainx_raw_names);
            $brainx_select_map_fields_name = array_map('sanitize_text_field', $brainx_raw_names);
        }
        foreach ($brainx_select_map_fields_name as $brainx_name) { // Now the array is unslashed
            $brainx_arr = array();
            $brainx_name = sanitize_text_field($brainx_name); // Sanitize the name
            // Check and sanitize the api options
            if (isset($_POST['api_options_' . $brainx_name]) && is_array($_POST['api_options_' . $brainx_name])) {
                // Unsanitize the entire api_options array before sanitization
                $brainx_api_options = array();
                $brainx_raw_options = filter_input(INPUT_POST, 'api_options_' . $brainx_name, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
                if (is_array($brainx_raw_options)) {
                    $brainx_api_options = wp_unslash($brainx_raw_options);
                    $brainx_api_options = array_map('sanitize_text_field', $brainx_api_options);
                }
                
                foreach ($brainx_api_options as $brainx_key => $brainx_api_field) {
                    $brainx_api_field = sanitize_text_field($brainx_api_field); // Sanitize the api field
                    $brainx_form_value = isset($_POST['form_options_' . $brainx_name][$brainx_key]) ? sanitize_text_field(wp_unslash($_POST['form_options_' . $brainx_name][$brainx_key])) : ''; // Unsanitize and sanitize the form field value

                    $brainx_map_array = array(
                        'api_field_value' => $brainx_api_field,
                        'form_field_value' => $brainx_form_value
                    );
                    $brainx_arr[$brainx_api_field] = $brainx_map_array;
                }
            }

            $brainx_final_array[$brainx_name] = $brainx_arr;
        }
    }


    $brainx_key_matched = '_brainx_ninja_form_api_select_matching_' . $brainx_form_id_save;
    update_option($brainx_key_matched, $brainx_final_array);
    brainx_update_logs_data_for_form($brainx_form_id_save, 'ninja', 'maping');
    $brainx_showcls = 'show';
}

$brainx_enabled_fields = array();
$brainx_accessToken = brainxGetApiToken();
$brainx_fields = array();
$brainx_ninja_id = isset($_GET['ninja_connect']) ? sanitize_text_field(wp_unslash($_GET['ninja_connect'])) : '';

$brainx_key3 = 'brainx_ninja_entity_id_for_form_' . $brainx_ninja_id;
$brainx_enity_id_saved = get_option($brainx_key3);
if (!empty($brainx_accessToken)) {
    if (!empty($brainx_enity_id_saved)) {
        $brainx_kk = 'brainx_ninja_brainx_api_enabled_form_fields_' . $brainx_ninja_id;
        $brainx_enabled_fields = get_option($brainx_kk);
        $brainx_fields = BrainxGetFields($brainx_accessToken, $brainx_enity_id_saved);
    }
}
$brainx_checkboxkey = 'brainx_ninja_api_enable_org_creation_' . $brainx_ninja_id;
$brainx_checked = "";
if (get_option($brainx_checkboxkey) == 'on') {
    $brainx_checked = 'checked=""';
}
$brainx_required_fields = array();
$brainx_key = 'brainx_crm_settings_for_form_' . $brainx_ninja_id;
$brainx_key2 = 'brainx_crm_settings_ninja_checked_fields_' . $brainx_ninja_id;

$brainx_chekboxfields = get_option($brainx_key2);
$brainx_saved_data = get_option($brainx_key);
$brainx_req = isset($brainx_saved_data['req']) ? $brainx_saved_data['req'] : '';
$brainx_mapping = isset($brainx_saved_data['mapping']) ? $brainx_saved_data['mapping'] : '';
$brainx_select_fields = array();
$brainx_matched_fields_array = array();
$brainx_key4 = 'brainx_ninja_assigned_company_id_' . $brainx_ninja_id;
$brainx_assigned_company_id = get_option($brainx_key4);
$brainx_display = '';
if (!empty($brainx_showcls) || !empty($brainx_showcls2)) {
    $brainx_display = 'shownow';
}
?>
<div class="brainx_success-toast <?php echo esc_attr($brainx_display); ?>" id="brainx_success_toast" role="status" aria-live="polite" aria-atomic="true" hidden>
    <div class="brainx_success-inner">

        <div class="success_message success_message1 <?php echo esc_attr($brainx_showcls); ?>">
            <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB4PSIwIiB5PSIwIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTEyIDUxMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgY2xhc3M9IiI+PGc+PHBhdGggZmlsbD0iIzFlNTYxZiIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMjU2IDBDMTE0LjggMCAwIDExNC44IDAgMjU2czExNC44IDI1NiAyNTYgMjU2IDI1Ni0xMTQuOCAyNTYtMjU2UzM5Ny4yIDAgMjU2IDB6IiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiM0YmFlNGYiIGNsYXNzPSIiPjwvcGF0aD48cGF0aCBmaWxsPSIjZmZmZmZmIiBkPSJNMjA2LjcgMzczLjFjLTMyLjctMzIuNy02NS4yLTY1LjctOTgtOTguNC0zLjYtMy42LTMuNi05LjYgMC0xMy4ybDM3LjctMzcuN2MzLjYtMy42IDkuNi0zLjYgMTMuMiAwbDUzLjkgNTMuOUwzNTIuMSAxMzljMy43LTMuNiA5LjYtMy42IDEzLjMgMGwzNy44IDM3LjhjMy43IDMuNyAzLjcgOS42IDAgMTMuMkwyMTkuOSAzNzMuMWMtMy42IDMuNy05LjUgMy43LTEzLjIgMHoiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiNmZmZmZmYiPjwvcGF0aD48L2c+PC9zdmc+" /> <?php esc_html_e('Änderungen wurden erfolgreich gespeichert!', 'brainx-form-connector'); ?>
        </div>
        <div class="success_message success_messageremove <?php echo esc_attr($brainx_showcls2); ?>">
            <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB4PSIwIiB5PSIwIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTEyIDUxMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgY2xhc3M9IiI+PGc+PHBhdGggZmlsbD0iIzFlNTYxZiIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMjU2IDBDMTE0LjggMCAwIDExNC44IDAgMjU2czExNC44IDI1NiAyNTYgMjU2IDI1Ni0xMTQuOCAyNTYtMjU2UzM5Ny4yIDAgMjU2IDB6IiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiM0YmFlNGYiIGNsYXNzPSIiPjwvcGF0aD48cGF0aCBmaWxsPSIjZmZmZmZmIiBkPSJNMjA2LjcgMzczLjFjLTMyLjctMzIuNy02NS4yLTY1LjctOTgtOTguNC0zLjYtMy42LTMuNi05LjYgMC0xMy4ybDM3LjctMzcuN2MzLjYtMy42IDkuNi0zLjYgMTMuMiAwbDUzLjkgNTMuOUwzNTIuMSAxMzljMy43LTMuNiA5LjYtMy42IDEzLjMgMGwzNy44IDM3LjhjMy43IDMuNyAzLjcgOS42IDAgMTMuMkwyMTkuOSAzNzMuMWMtMy42IDMuNy05LjUgMy43LTEzLjIgMHoiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiNmZmZmZmYiPjwvcGF0aD48L2c+PC9zdmc+" /> <?php esc_html_e('Modul-Einstellungen gespeichert!', 'brainx-form-connector'); ?>
        </div>

    </div>
</div>
<div class="tab">
    <button class="tablinks tablinks1" onclick="open_frm_tab(event, 'Mapping')"><?php esc_html_e('Mapping', 'brainx-form-connector'); ?></button>
    <button class="tablinks tablinks2" onclick="open_frm_tab(event, 'Settings')"><?php esc_html_e('Einstellungen', 'brainx-form-connector'); ?></button>
</div>


<div class="tabcontent" id="Settings">

    <form method="post" action="">
        <input type="hidden" name="form_id_for_entity" value="<?php echo isset($_GET['ninja_connect']) ? intval($_GET['ninja_connect']) : 0; ?>" />
        <table class="form-table">
            <tr class="module_error hideit">
                <th></th>
                <td><?php esc_html_e('Bitte Modul auswählen!', 'brainx-form-connector'); ?></td>
            </tr>
            <tr>
                <th><?php esc_html_e('CRM Modul', 'brainx-form-connector'); ?> *</th>
                <td>
                    <input type="hidden" name="current_entity_id" value="<?php echo esc_attr($brainx_enity_id_saved); ?>"/>
                    <select name="entity_id" class="entity_id_select" required="">
                        <option value=""><?php esc_html_e('Modul auswählen', 'brainx-form-connector'); ?></option>
                        <option <?php selected($brainx_enity_id_saved, 4); ?> value="4"><?php esc_html_e('Kontakte', 'brainx-form-connector'); ?></option>
                        <option <?php selected($brainx_enity_id_saved, 7); ?> value="7"><?php esc_html_e('Leads', 'brainx-form-connector'); ?></option>
                    </select>
                </td>
            </tr>
            <tr class="enable_org_creation" style="display:none;">
                <th><?php esc_html_e('Organisation-Verknüpfung aktivieren', 'brainx-form-connector'); ?></th>
                <td>
                    <input type="checkbox" name="enable_org_creation" <?php echo esc_attr($brainx_checked); ?> />
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Vorhandene Felder', 'brainx-form-connector'); ?></th>
                <td>

                    <div class="button-container">
                        <button class="all" type="button" onclick="selectAll()"><?php esc_html_e('Alle hinzufügen', 'brainx-form-connector'); ?></button>
                        <button class="remove" type="button" onclick="deselectAll()"><?php esc_html_e('Alle entfernen', 'brainx-form-connector'); ?></button>
                    </div>

                    <select name="api_enabled_fields[]" class="api_enabled_fields_select" multiple id="select2">
                        <?php
                        foreach ($brainx_fields as $brainx_field) {
                            $brainx_name = sanitize_text_field($brainx_field['name']);
                            if ($brainx_name == 'assigned_user_id' || $brainx_name == 'assigned_company_id') {
                                continue;
                            }
                            $brainx_label = sanitize_text_field($brainx_field['label']);
                            $brainx_required = $brainx_field['required'];
                            $brainx_selected = '';
                            if ($brainx_required == 1) {
                                $brainx_selected = 'selected="selected"';
                            } else if (!empty($brainx_enabled_fields) && in_array($brainx_name, $brainx_enabled_fields)) {
                                $brainx_selected = 'selected="selected"';
                            }
                            ?>
                            <option <?php echo esc_attr($brainx_selected); ?> value="<?php echo esc_attr($brainx_name); ?>"><?php echo esc_html($brainx_label); ?></option>
                            <?php
                        }
                        ?>
                    </select>
                </td>
            </tr>
            <?php
            $brainx_company_ids = brainx_get_assigned_company_ids();
            ?>
            <tr>
                <th><?php esc_html_e('Mandaten ID', 'brainx-form-connector'); ?> *</th>
                <td>
                    <?php if (!empty($brainx_company_ids)) : ?>
                        <select name="assigned_company_id" class="assigned_company_id" required="">
                            <option value=""><?php esc_html_e('--select--', 'brainx-form-connector'); ?></option>
                            <?php foreach ($brainx_company_ids as $brainx_com) : ?>
                                <option value="<?php echo esc_attr($brainx_com['id']); ?>" 
                                        <?php selected($brainx_assigned_company_id, $brainx_com['id']); ?>>
                                            <?php echo esc_html($brainx_com['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    <?php else : ?>
                        <input type="number" 
                               name="assigned_company_id" 
                               value="<?php echo esc_attr($brainx_assigned_company_id); ?>" />
                           <?php endif; ?>
                </td>
            </tr>

            <tr>
                <?php wp_nonce_field('brainx_save_settings_fields', 'brainx_nonce_fields'); ?>
                <td style="padding:0"><input type="submit" class="button button-primary" name="save_entity_id" value="<?php esc_html_e('Einstellungen speichern', 'brainx-form-connector'); ?>" /></td>
            </tr>
        </table>
    </form>
</div>

<div class="tabcontent" id="Mapping">
    <div id="modal-alert" class="brx_modal">
        <div class="brx_modal-content">
            <h3><?php esc_html_e('Fehler aufgetreten!', 'brainx-form-connector'); ?></h3>
            <p><?php esc_html_e('Es sind nicht alle Pflichtfelder mit einem Wert hinterlegt.', 'brainx-form-connector'); ?></p>
            <button id="close-modal"><?php esc_html_e('OK, verstanden', 'brainx-form-connector'); ?></button>
        </div>
    </div>

    <div class="container" style="margin-top: 20px;">
        <!-- Fields brx_box -->
        <div class="brx_box form_fields">
            <h3><?php esc_html_e('Formularfelder', 'brainx-form-connector'); ?></h3>
            <div id="fields-brx_box">

            </div>
        </div>
        <div class="brx_box" id="api-values-brx_box">
            <h3><?php esc_html_e('Mapping:', 'brainx-form-connector'); ?> <span class="modulename"></span></h3>
            <?php
            if (!empty($brainx_fields)) {
                foreach ($brainx_fields as $brainx_field) {
                    $brainx_name = $brainx_field['name'];
                    $brainx_label = $brainx_field['label'];
                    $brainx_required = $brainx_field['required'];
                    if ($brainx_name == 'assigned_user_id' || $brainx_name == 'assigned_company_id') {
                        continue;
                    }
                    $brainx_enabled = 1;

                    if ($brainx_required == 1) {
                        $brainx_required_fields[] = $brainx_name;
                    } else {
                        if (!empty($brainx_enabled_fields)) {
                            if (!in_array($brainx_name, $brainx_enabled_fields)) {
                                $brainx_enabled = 0;
                            }
                        }
                    }
                    if ($brainx_enabled == 0) {
                        continue;
                    }
                    $brainx_is_enabled_field = 0;
                    $brainx_matched_id = 0;
                    if (!empty($brainx_mapping) && isset($brainx_mapping[$brainx_name])) {
                        $brainx_matched_id = $brainx_mapping[$brainx_name];
                        $brainx_is_enabled_field = 1;
                    } else {
                        
                    }
                    ?>
                    <div class="wrapper">
                        <p><?php echo esc_attr($brainx_label); ?> <?php
                            if ($brainx_required == 1) {
                                echo '<span class="req">*</span>';
                            }
                            ?></p>
                        <?php
                        if ($brainx_is_enabled_field == 1) {
                            if ($brainx_field['type'] == 'select' || $brainx_field['type'] == 'PickList') {
                                $brainx_select_fields[] = $brainx_field;
                                $brainx_matched_fields_array[] = $brainx_all_fields_data[$brainx_matched_id];
                            }
                            $brainx_is_checked = '';
                            if (!empty($brainx_chekboxfields) && isset($brainx_chekboxfields[$brainx_name])) {
                                $brainx_is_checked = 'checked=""';
                            }
                            ?>
                            <div class="droppable ui-droppable success <?php echo esc_attr($brainx_field['type']); ?>" data-map-to="<?php echo esc_attr($brainx_name); ?>">
                                <div class="draggable-item ui-draggable ui-draggable-handle ui-draggable-dragging" data-key="<?php echo esc_attr($brainx_matched_id); ?>"><?php echo esc_attr($brainx_fields_array[$brainx_matched_id]); ?></div>
                                <button class="remove-btn"><?php esc_html_e('Entfernen', 'brainx-form-connector'); ?></button>
                                <div class="istrueflasediv"><input type="checkbox" <?php echo esc_attr($brainx_is_checked); ?> class="istrueflase" name="istrueflase" /><?php esc_html_e('Kontrollkästchen(wahr/falsch)?', 'brainx-form-connector'); ?></div>
                            </div>
                            <?php
                        } else {
                            $brainx_vv = '';
                            if (!empty($brainx_req)) {
                                $brainx_vv = isset($brainx_req[$brainx_name]) ? $brainx_req[$brainx_name] : '';
                            }
                            ?>
                            <div class="droppable <?php echo esc_attr($brainx_field['type']); ?>" data-map-to="<?php echo esc_attr($brainx_name); ?>">
                                <input type="text" placeholder="Feld ausfüllen oder hinterlegen" class="custom-value" value="<?php echo esc_attr($brainx_vv); ?>">
                            </div>
                            <?php
                        }
                        ?>
                    </div>    
                    <?php
                }
            }
            ?>
            <div class="save_button">
                <button id="get-mapping"><?php esc_html_e('Mapping speichern', 'brainx-form-connector'); ?></button>
            </div>
        </div>
        <div class="brx_box fields_mapping_for_api">

        </div>
    </div>
</div>

</div></div>

<input type="hidden" id="current_form_id" value="<?php echo intval($_GET['ninja_connect']); ?>"/>
<?php
wp_enqueue_script('jquery-ui-draggable');
wp_enqueue_script('jquery-ui-droppable');
wp_enqueue_script('brainx_ninjaform_js', BRAINX_CRM_PLUGIN_URL . 'assets/brainx_ninjaform_js.js', array('select2_js', 'jquery-ui-draggable', 'jquery-ui-droppable'), '2.0.0', true);
wp_localize_script(
        'brainx_ninjaform_js',
        'brainxNinjaLocalizedData',
        array(
            'nonce' => wp_create_nonce('brainx-form-nonce'),
            'fields_array' => isset($brainx_fields_array) ? $brainx_fields_array : array(),
            'required_fields' => isset($brainx_required_fields) ? $brainx_required_fields : array(),
            'ajax_url' => admin_url('admin-ajax.php'),
            'form_id' => isset($_GET['ninja_connect']) ? intval($_GET['ninja_connect']) : 0,
        )
);
//include 'brainx-manage-single-options.php';
