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

if (!function_exists('brainx_get_select_matched_value')) {

    function brainx_get_select_matched_value($brainx_form_type, $brainx_form_id, $brainx_value, $brainx_name, $brainx_type) {

        if ($brainx_form_type == 'ninja') {
            $brainx_key_matched = '_brainx_ninja_form_api_select_matching_' . $brainx_form_id;
        } else {
            $brainx_key_matched = 'brainx_formidable_form_api_select_matching_' . $brainx_form_id;
        }
        if ($brainx_type == 'single') {
            $brainx_response = '';
            $brainx_saved_mapping = get_option($brainx_key_matched);

            if (!empty($brainx_saved_mapping)) {
                if (isset($brainx_saved_mapping[$brainx_name])) {
                    foreach ($brainx_saved_mapping[$brainx_name] as $brainx_mp_array) {

                        if ($brainx_mp_array['form_field_value'] == $brainx_value) {
                            $brainx_response = $brainx_mp_array['api_field_value'];
                            break;
                        }
                    }
                }
            }
        } else {
            $brainx_saved_mapping = get_option($brainx_key_matched);
            $brainx_response = array();
            if (!empty($brainx_saved_mapping)) {
                if (isset($brainx_saved_mapping[$brainx_name])) {
                    foreach ($brainx_saved_mapping[$brainx_name] as $brainx_mp_array) {
                        foreach ($brainx_value as $brainx_val) {
                            if ($brainx_mp_array['form_field_value'] == $brainx_val) {
                                $brainx_response[] = $brainx_mp_array['api_field_value'];
                            }
                        }
                    }
                }
            }
        }
        return $brainx_response;
    }

}

if (!function_exists('brainx_ninja_submit_form_api_call')) {

    function brainx_ninja_submit_form_api_call($brainx_form_id, $brainx_form_data, $brainx_entry_id) {
//        update_option('fdata',$brainx_form_data);        
//        update_option('fdata1',$brainx_entry_id);
        $brainx_key1 = 'brainx_crm_ninja_form_status_' . $brainx_form_id;
        $sts = get_option($brainx_key1);
        if (!empty($sts) && $sts == 'Enable') {
            $brainx_key = 'brainx_crm_settings_for_form_' . $brainx_form_id;
            $brainx_key2 = 'brainx_crm_settings_ninja_checked_fields_' . $brainx_form_id;
            $brainx_checkedBoxFields = get_option($brainx_key2);
            $brainx_settings = get_option($brainx_key);
            if (!empty($brainx_settings) && isset($brainx_settings['mapping']) && !empty($brainx_settings['mapping'])) {
                $brainx_mapping = $brainx_settings['mapping'];
                $brainx_req = isset($brainx_settings['req']) ? $brainx_settings['req'] : '';
                $brainx_fields = $brainx_form_data['fields'];
                $brainx_data_to_send = [];
                foreach ($brainx_fields as $brainx_field) {
                    $brainx_value = $brainx_field['value'];
                    $brainx_id = $brainx_field['id'];
                    $found = 0;
                    if (!empty($brainx_checkedBoxFields)) {
                        $brainx_key = array_search($brainx_id, $brainx_checkedBoxFields);
                        if ($brainx_key) {
                            $found = 1;
                            if ($brainx_value == 1) {
                                $brainx_data_to_send[$brainx_key] = 'true';
                            } else {
                                $brainx_data_to_send[$brainx_key] = 'false';
                            }
                        }
                    }
                    if (0 == $found) {
                        $brainx_key = array_search($brainx_id, $brainx_mapping);
                        if ($brainx_key) {
                            if ($brainx_field['type'] == 'listselect' || $brainx_field['type'] == 'listradio') {
                                $brainx_selected_value = $brainx_value;
                                $brainx_response = brainx_get_select_matched_value('ninja', $brainx_form_id, $brainx_value, $brainx_key, 'single');
                                if (!empty($brainx_response)) {
                                    $brainx_value = $brainx_response;
                                }
                            } else if ($brainx_field['type'] == 'listmultiselect' || $brainx_field['type'] == 'listcheckbox') {
                                $brainx_response = brainx_get_select_matched_value('ninja', $brainx_form_id, $brainx_value, $brainx_key, 'array');
                                if (!empty($brainx_response)) {
                                    $brainx_response = implode(',', $brainx_response);
                                    $brainx_value = $brainx_response;
                                }
                            }

                            $brainx_data_to_send[$brainx_key] = $brainx_value;
                        }
                    }
                }
                if (!empty($brainx_req)) {
                    foreach ($brainx_req as $brainx_kk => $brainx_vv) {
                        if (!empty($brainx_vv)) {
                            $brainx_data_to_send[$brainx_kk] = $brainx_vv;
                        }
                    }
                }

                if (!empty($brainx_data_to_send)) {
                    $brainx_key3 = 'ninja_entity_id_for_form_' . $brainx_form_id;
                    $brainx_enity_id_saved = get_option($brainx_key3);
                    brainx_setdatatoapi_brainxcrm($brainx_data_to_send, $brainx_entry_id, $brainx_form_id, 'ninja_form', $brainx_enity_id_saved);
                }
            }
        }
    }

}

if (!function_exists('brainx_formidable_submit_form_api_call')) {

    function brainx_formidable_submit_form_api_call($brainx_form_id, $brainx_form_data, $brainx_entry_id) {
        $brainx_key1 = 'brainx_crm_formidable_form_status_' . $brainx_form_id;

        $sts = get_option($brainx_key1);
        if (!empty($sts) && $sts == 'Enable') {
            $brainx_key = 'brainx_crm_settings_for_form_formidable_' . $brainx_form_id;
            $brainx_key2 = 'brainx_crm_settings_checked_fields_' . $brainx_form_id;
            $brainx_checkedBoxFields = get_option($brainx_key2);
            $brainx_settings = get_option($brainx_key);
            if (!empty($brainx_settings) && isset($brainx_settings['mapping']) && !empty($brainx_settings['mapping'])) {
                $brainx_mapping = $brainx_settings['mapping'];
                $brainx_req = isset($brainx_settings['req']) ? $brainx_settings['req'] : '';
                $brainx_data_to_send = array();
                foreach ($brainx_mapping as $brainx_key => $brainx_id) {
                    if (isset($brainx_form_data['item_meta'][$brainx_id])) {
                        $brainx_val = isset($brainx_form_data['item_meta'][$brainx_id]) ? $brainx_form_data['item_meta'][$brainx_id] : '';
                        if (is_array($brainx_val)) {
                            $brainx_val = array_map('sanitize_text_field', $brainx_val);
                        } else {
                            $brainx_val = sanitize_text_field($brainx_val);
                        }
                        $brainx_field = FrmField::getOne($brainx_id);

                        if ($brainx_field->type == 'select' || $brainx_field->type == 'radio') {

                            $brainx_response = brainx_get_select_matched_value('formidable', $brainx_form_id, $brainx_val, $brainx_key, 'single');
                            if (!empty($brainx_response)) {
                                $brainx_val = $brainx_response;
                            }
                        } else if ($brainx_field->type == 'checkbox' || $brainx_field->type == 'multiselect') {
                            $brainx_response = brainx_get_select_matched_value('formidable', $brainx_form_id, $brainx_val, $brainx_key, 'array');
                            $brainx_response = implode(',', $brainx_response);
                            if (!empty($brainx_response)) {
                                $brainx_val = $brainx_response;
                            }
                        }
                        $brainx_data_to_send[$brainx_key] = $brainx_val;
                    }
                }
                if (!empty($brainx_checkedBoxFields)) {
                    foreach ($brainx_checkedBoxFields as $brainx_key => $brainx_id) {
                        $checkbox_value = FrmEntryMeta::get_entry_meta_by_field($brainx_entry_id, $brainx_id);
                        if (!empty($checkbox_value)) {
                            $brainx_data_to_send[$brainx_key] = 'true';
                        } else {
                            $brainx_data_to_send[$brainx_key] = 'false';
                        }
                    }
                }
                if (!empty($brainx_req)) {
                    foreach ($brainx_req as $brainx_kk => $brainx_vv) {
                        if (!empty($brainx_vv)) {
                            $brainx_data_to_send[$brainx_kk] = $brainx_vv;
                        }
                    }
                }
                if (!empty($brainx_data_to_send)) {
                    $brainx_key3 = 'brainx_frm_entity_id_for_form_' . $brainx_form_id;
                    $brainx_enity_id_saved = get_option($brainx_key3);
                    brainx_setdatatoapi_brainxcrm($brainx_data_to_send, $brainx_entry_id, $brainx_form_id, 'formidable_form', $brainx_enity_id_saved);
                }
            }
        }
    }

}

add_action('ninja_forms_after_submission', 'brainx_send_data_to_api', 10, 1);

if (!function_exists('brainx_send_data_to_api')) {

    function brainx_send_data_to_api($brainx_form_data) {
        $brainx_entry_id = $brainx_form_data['actions']['save']['sub_id'];
        brainx_ninja_submit_form_api_call($brainx_form_data['form_id'], $brainx_form_data, $brainx_entry_id);
    }

}
add_action('frm_after_create_entry', 'brainx_frm_send_data_to_api', 10, 2);

if (!function_exists('brainx_frm_send_data_to_api')) {

    function brainx_frm_send_data_to_api($brainx_entry_id, $brainx_form_id) {
        if (
                isset($_GET['brainx-form-nonceverification']) &&
                !wp_verify_nonce(
                        sanitize_text_field(wp_unslash($_GET['brainx-form-nonceverification'])),
                        'brainx-form-nonceverification-action'
                )
        ) {
            wp_die();
        }
        brainx_formidable_submit_form_api_call($brainx_form_id, $_POST, $brainx_entry_id);
    }

}

if (!function_exists('brainx_create_organization_for_contact')) {

    function brainx_create_organization_for_contact($brainx_company_id_saved, $brainx_org, $brainx_accessToken) {
        $brainx_idss = 0;
        if (!empty($brainx_accessToken)) {

            $brainx_settings = get_option('_brainx_api_creds_settings');
            $brainx_server_url = isset($brainx_settings['server_url']) ? $brainx_settings['server_url'] : '';
            if (substr($brainx_server_url, -1) === '/') {
                $brainx_server_url = rtrim($brainx_server_url, '/');
            }
            $brainx_entityId = 6;
            $brainx_url = $brainx_server_url . "/api/entity/$brainx_entityId/records";
            $brainx_args = [
                'headers' => [
                    'Authorization' => 'Bearer ' . $brainx_accessToken . '',
                    'Content-Type' => 'application/json',
                ],
                'body' => wp_json_encode([
                    'accountname' => $brainx_org,
                    'assigned_user_id' => 1,
                    'assigned_company_id' => $brainx_company_id_saved,
                ]),
                'method' => 'POST',
                'timeout' => 20,
            ];

            $brainx_response = wp_remote_post($brainx_url, $brainx_args);

            if (is_wp_error($brainx_response)) {
                
            } else {
                $brainx_res = wp_remote_retrieve_body($brainx_response);
                $brainx_res = json_decode($brainx_res, true);
                $brainx_idss = isset($brainx_res['data']['id']) ? $brainx_res['data']['id'] : 0;
            }
        }
        return $brainx_idss;
    }

}

if (!function_exists('brainx_setdatatoapi_brainxcrm')) {

    function brainx_setdatatoapi_brainxcrm($brainx_data_to_send, $brainx_entry_id, $brainx_form_id, $brainx_type, $brainx_entityId) {
        $brainx_company_id = 0;
        $brainx_key4 = '';
        if ($brainx_type == 'ninja_form') {
            $brainx_key4 = 'brainx_ninja_assigned_company_id_' . $brainx_form_id;
        } else {
            $brainx_key4 = 'brainx_formidable_assigned_company_id_' . $brainx_form_id;
        }
        $brainx_company_id_saved = 1;
        $brainx_company_id_op = get_option($brainx_key4);
        if (!empty($brainx_company_id_op)) {
            $brainx_company_id_saved = $brainx_company_id_op;
        }
        $brainx_accessToken = brainxGetApiToken();
        if ($brainx_entityId == 4 && isset($brainx_data_to_send['account_id']) && !empty($brainx_data_to_send['account_id'])) {
            $brainx_checkboxkey = '';
            if ($brainx_type == 'ninja_form') {
                $brainx_checkboxkey = 'brainx_ninja_api_enable_org_creation_' . $brainx_form_id;
            } else {
                $brainx_checkboxkey = 'brainx_frm_brainx_api_enable_org_creation_' . $brainx_form_id;
            }
            if (get_option($brainx_checkboxkey) == 'on') {
                $brainx_company_id = brainx_create_organization_for_contact($brainx_company_id_saved, $brainx_data_to_send['account_id'], $brainx_accessToken);
            }
        }

        $brainx_data_to_send['assigned_user_id'] = 1;
        if (!empty($brainx_company_id) && $brainx_company_id > 0) {
            $brainx_data_to_send['account_id'] = $brainx_company_id;
        } else {
            if (isset($brainx_data_to_send['account_id'])) {
                unset($brainx_data_to_send['account_id']);
            }
        }
        if (isset($brainx_data_to_send['assigned_company_id'])) {
            $brainx_data_to_send['assigned_company_id'] = $brainx_company_id_saved;
        }
        if (!empty($brainx_accessToken)) {
            $brainx_settings = get_option('_brainx_api_creds_settings');
            $brainx_server_url = isset($brainx_settings['server_url']) ? $brainx_settings['server_url'] : '';
            if (substr($brainx_server_url, -1) === '/') {
                $brainx_server_url = rtrim($brainx_server_url, '/');
            }
            if (empty($brainx_entityId)) {
                $brainx_entityId = isset($brainx_settings['entity_id']) ? $brainx_settings['entity_id'] : '';
            }
            $api_url = $brainx_server_url . "/api/entity/$brainx_entityId/records";
            $headers = [
                'Authorization' => 'Bearer ' . $brainx_accessToken,
                'Content-Type' => 'application/json',
            ];
            $json_data = json_encode($brainx_data_to_send);

            $brainx_response = wp_remote_post($api_url, [
                'headers' => $headers,
                'body' => $json_data,
            ]);

            if (is_wp_error($brainx_response)) {
                brainx_save_api_response($brainx_form_id, $brainx_entry_id, $brainx_type, 'error', $brainx_response, $brainx_response->get_error_message());
            } else {
                $brainx_response_body = wp_remote_retrieve_body($brainx_response);
                $brainx_response_code = wp_remote_retrieve_response_code($brainx_response);
                if ($brainx_response_code >= 200 && $brainx_response_code <= 204) {
                    brainx_save_api_response($brainx_form_id, $brainx_entry_id, $brainx_type, 'success', $brainx_response, $brainx_response_body);
                } else {
                    brainx_save_api_response($brainx_form_id, $brainx_entry_id, $brainx_type, 'error', $brainx_response, $brainx_response_body);
                }
            }
        }
    }

}

if (!function_exists('brainx_save_api_response')) {

    function brainx_save_api_response($brainx_form_id, $brainx_entry, $brainx_type, $brainx_status, $brainx_response, $brainx_msg) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'brainx_api_responses';

// Data to insert
        $data = array(
            'form_id' => $brainx_form_id,
            'entry_id' => $brainx_entry,
            'form_type' => $brainx_type,
            'status' => $brainx_status,
            'response_got' => $brainx_response,
            'message' => $brainx_msg,
            'date' => gmdate('Y-m-d H:i:s'),
        );

        $data_format = array('%d', '%d', '%s', '%s', '%s', '%s', '%s');
        $wpdb->insert($table_name, $data, $data_format);
    }

}
