<?php

class arforms_custom_db{

    function __construct(){

        add_action( 'arf_editor_general_options_menu', array( $this, 'arforms_editor_add_custom_database_menu' ) );

        add_action( 'arf_add_modal_in_editor', array( $this, 'arforms_editor_custom_database_connection_model') );

        add_action( 'arfaftercreateentry', array( $this, 'arforms_save_entries_to_external_database'), 10, 2 );

        add_filter('arf_update_form_option_outside', array($this, 'arf_database_form_option_update_ids'), 10, 4);
  
        add_filter('arf_update_form_return_json_outside', array($this, 'arf_database_form_option_update_return_json'),10,2);

        add_filter('arf_save_form_options_outside', array($this, 'arf_database_form_option_update'), 10, 3);
        
        add_filter( 'arfformoptionsbeforeupdateform', array( $this, 'arforms_custom_db_save_form_options' ), 11, 2 );

        add_action( 'arforms_additional_debug_log_settings', array( $this, 'arforms_custom_db_logs') );

        add_action( 'arforms_save_additional_debug_log_data', array( $this, 'arforms_save_custom_db_logs'));

    }

    function arforms_save_custom_db_logs( $posted_data ){
        global $arformsmain;

        $custom_db_logs = isset( $posted_data['custom_db_logs'] ) ? $posted_data['custom_db_logs'] : 0;
        $arformsmain->arforms_update_settings( 'custom_db_logs', $custom_db_logs, 'debug_log_settings' );
    }

    function arforms_custom_db_logs(){
        global $arformsmain, $arforms_pro_debug_log;
        $custom_db_logs = $arformsmain->arforms_get_settings( 'custom_db_logs', 'debug_log_settings' );

        $onchange_func = 'arforms_hide_show_debug_settings(this.checked, "custom_db_logs");';
        $onclick_func = '';
        $log_cls = '';

        if( $arforms_pro_debug_log->setvaltolic != 1 ){
            $onclick_func = 'alert(\'Please activate license to enable form database connection log\'); return false;';
            $onchange_func = 'return false;';
            $log_cls = 'arf_restricted_control';
        }

        ?>
            <div class="arf-inner-heading">
                <span class="lblsubtitle lblnotetitle "><?php echo esc_html__( 'External Table/Database Connection Log', 'ARForms' ); ?></span>
                <div class="arf_js_switch_wrapper <?php echo esc_attr( $log_cls ); ?> arf-checkbox">
                    
                    <input type="checkbox" class="js-switch" id="custom_db_logs" name="custom_db_logs" value="1" <?php echo !empty( $onclick_func ) ? 'onclick="' . $onclick_func . '"' : ''; //phpcs:ignore ?>  <?php checked($custom_db_logs, 1);?> onchange="<?php echo esc_attr( $onchange_func );  //phpcs:ignore ?>" />
                    <span class="arf_js_switch"></span>
                </div>
                <div class="arforms_debug_log_setting_wrapper" data-type="custom_db_logs" style="<?php echo ( 1 == $custom_db_logs ) ? 'display:table-row;' : 'display:none;'; ?>">
                    <div class="arf-log-button-div">
                        <button type="button" class="arf-debug-log-button arf-view-img arforms_view_debug_logs" data-log-type="custom_db_logs" data-token="<?php echo $arforms_pro_debug_log->arforms_view_log_token;//phpcs:ignore ?>" id="arf_email_popup_view_log"><?php esc_html_e('View Logs', 'ARForms' ); ?></button>
                        <button type="button" class="arf-debug-log-button arf-download-img" id="arf_email_popup_download_log" onclick="return Show_downloadpopup('custom_db_logs')";><?php esc_html_e('Download Logs', 'ARForms'); ?></button>
                        <button type="button" class="arf-debug-log-button arf-clear-img" id="arf_email_popup_clear_log" onclick="return Show_clearpopup('custom_db_logs')";><?php esc_html_e('Clear Logs', 'ARForms'); ?></button>
                    </div>
                </div>
            </div>
        <?php
    }

    function arforms_custom_db_save_form_options( $options, $values ){

        $options['arf_external_database_opt'] = !empty( $values['options']['arf_external_database_opt'] ) ? $values['options']['arf_external_database_opt'] : 0;
        $options['arf_wordpress_database_opt'] = !empty( $values['options']['arf_wordpress_database_opt'] ) ? $values['options']['arf_wordpress_database_opt'] : 0;
        $options['arf_table_name'] = !empty( $values['options']['arf_table_name'] ) ? $values['options']['arf_table_name'] : '';
        $options['arf_external_host'] = !empty( $values['options']['arf_external_host'] ) ? $values['options']['arf_external_host'] : '';
        $options['arf_external_username'] = !empty( $values['options']['arf_external_username'] ) ? $values['options']['arf_external_username'] : '';
        $options['arf_external_password'] = !empty( $values['options']['arf_external_password'] ) ? $values['options']['arf_external_password'] : '';
        $options['arf_external_database'] = !empty( $values['options']['arf_external_database'] ) ? $values['options']['arf_external_database'] : '';

        return $options;
    }

    function arf_database_form_option_update_ids($options,$return_json_data,$values_old_id,$values_new_id){

        $retunr_google_filter_data['options'] = $options;
                
        if(!empty($retunr_google_filter_data['options']['arf_db_headers'])){            
            foreach ($retunr_google_filter_data['options']['arf_db_headers'] as $key => $value) {
                if($value == $values_old_id){
                    $retunr_google_filter_data['options']['arf_db_headers'][$key] = str_replace($values_old_id, $values_new_id, $retunr_google_filter_data['options']['arf_db_headers'][$key]);
                }
            }
        }    
        
        return $retunr_google_filter_data['options'];
    }
    
    function arf_database_form_option_update_return_json($return_json_data,$options){

        if(!empty($options['arf_db_headers'])){            
            foreach ($options['arf_db_headers'] as $key => $value) {
                $key_update_value = $key+1;
                $return_json_data['arf_database_header_'.$key_update_value] = $options['arf_db_headers'][$key];
            }
        }

        return $return_json_data;
        
    }
    function arf_database_form_option_update($options,$values,$form_id){

        if( isset( $_GET['arfaction'] ) && 'preview' == $_GET['arfaction'] ){
            return $options;
        }
        
        if( !empty( $form_id ) ) {
            global $MdlDb,$wpdb,$arfversion,$arfform;

            if( version_compare( $arfversion, '4.3', '<' ) ){

                $results_old = $wpdb->get_results($wpdb->prepare("SELECT options FROM " .$MdlDb->forms." WHERE id = %d", $form_id)); //phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Reason: $MdlDb->forms is table name defined globally. False Positive alarm
            
            }else{

                $results_old = $arfform->arf_select_db_data( true, '', $MdlDb->forms, 'options', 'WHERE id = %d', array($form_id));
            }

            if( !isset( $results_old ) || empty( $results_old ) ){
                return $options;
            }

            $options_old = $results_old[0]->options;
            $options_old = arf_json_decode($options_old, true);
            
            $db_header_values     = isset( $options_old['arf_db_headers_value'] ) ? $options_old['arf_db_headers_value'] : array();
            $count_old_gs_headers = ( isset( $options_old['arf_db_headers'] ) && is_array($options_old['arf_db_headers'] ) ) ? count($options_old['arf_db_headers']) : '';
        }
        
        $options['arf_db_headers']  = ( isset($values['options']['arf_database_headers']) && is_array($values['options']['arf_database_headers']) && (count($values['options']['arf_database_headers'])>0) ) ? array_values($values['options']['arf_database_headers']) : array();

        $options['arf_db_headers_value'] = ( isset( $values['options']['arf_database_headers_value'] ) && is_array( $values['options']['arf_database_headers_value'] ) && (count($values['options']['arf_database_headers_value'])>0) )? array_values($values['options']['arf_database_headers_value']):array();

        $count_new_gs_headers = count($options['arf_db_headers']);
        
        $alt_headers = '0';
        if(isset($count_old_gs_headers) && $count_old_gs_headers != '0'){
            if($count_old_gs_headers != $count_new_gs_headers){
                
                $alt_headers = '1';
            }    
        }
        
        $alt_values = '0';
        if(isset($db_header_values) && count($db_header_values)>0){
        
            if($db_header_values != $options['arf_db_headers_value']){
              $alt_values = '1';
            }
        }   
        
        return $options;
    }

    function arforms_editor_add_custom_database_menu(){
        ?>
        <li class="arf_editor_top_dropdown_option" id="arf_database_opt"><?php echo addslashes(esc_html__('Database Connection', 'ARForms')); ?></li>
        <?php
    }

    function arforms_editor_custom_database_connection_model( $values ){
        ?>
        <div class="arf_modal_overlay">
            <div id="arf_database_opt_code_options_model" class="arf_popup_container arf_popup_container_other_option_model ">
                <div class="arf_popup_container_header"><?php echo addslashes(esc_html__('Database Connection', 'ARForms')); ?>
                    <div class="arfpopupclosebutton arfmodalclosebutton" data-dismiss="arfmodal" data-id="arf_submit-tracking-script">
                        <svg width="30px" height="30px" viewBox="1 0 20 20"><g id="preview"><path fill-rule="evenodd" clip-rule="evenodd" fill="#262944" d="M10.702,10.909L6.453,6.66l-4.249,4.249L1.143,9.848l4.249-4.249L1.154,1.361l1.062-1.061l4.237,4.237l4.238-4.237l1.061,1.061L7.513,5.599l4.249,4.249L10.702,10.909z"></path></g></svg>
                    </div>
                </div>

                <div class="arf_popup_content_container arf_other_options_container">

                    <div class="arf_submit_action_tab_wrapper">
                        <div class="arf_after_submission_database_opt_code">
                            <div class="arftablerow arforms_db_connection_model_box">
                            <div style="float: right;position:relative;top:-5px;right:-20px;">
                                <a target="_blank" class="arf_adminhelp_icon tipso_style" data-tipso="help" onclick="arf_help_doc_fun('arf_databse_connection');">
                                    <svg width="30px" height="30px" viewBox="0 0 26 32" class="arfsvgposition arfhelptip tipso_style" data-tipso="help">
                                    <path fill="#FF5A5A" d="M10.079,0.623c-4.971,0-9,4.029-9,9s4.029,9,9,9s9-4.029,9-9C19.073,4.654,15.047,0.628,10.079,0.623z    M10.079,1.796c1.159-0.001,2.304,0.257,3.35,0.755l-2.133,2.132c-0.833-0.206-1.705-0.197-2.534,0.025L6.645,2.593   C7.713,2.068,8.888,1.795,10.079,1.796z M5.14,10.839l-2.132,2.133c-1.02-2.149-1.005-4.646,0.041-6.783l2.117,2.117   c-0.222,0.828-0.231,1.699-0.025,2.532V10.839z M10.079,17.449c-1.224,0.002-2.43-0.285-3.521-0.838l2.107-2.097   c0.893,0.26,1.841,0.27,2.739,0.027l2.109,2.11C12.444,17.177,11.269,17.45,10.079,17.449z M10.079,13.536   c-2.161,0-3.913-1.752-3.913-3.913s1.752-3.913,3.913-3.913s3.913,1.752,3.913,3.913S12.24,13.536,10.079,13.536z M17.905,9.623   c0.001,1.19-0.271,2.365-0.797,3.434l-2.116-2.117c0.242-0.898,0.232-1.846-0.027-2.739l2.103-2.1   C17.62,7.192,17.907,8.399,17.905,9.623z"></path>                                                </svg>
                                </a>
                                </div>
                                <div class="arf_db_connection_header_title" style="margin-left: 0px;">
                                    <span class="arf_hidden_field_title" style="margin-top: 10px;margin-bottom: 10px;"><?php echo addslashes(esc_html__('Enable Database Connection', 'ARForms')); ?></span>
                                    <div class="arf_js_switch_wrapper arf_database_chechkbox" >                    
                                        <input type="checkbox" class="js-switch" name="options[arf_wordpress_database_opt]" id="arf_wordpress_database_opt" value="1"  <?php isset($values['arf_wordpress_database_opt']) ? checked($values['arf_wordpress_database_opt']) : ''; ?> onchange="arforms_hide_show_database_settings(this.checked, 'wordpress_table');" />                                
                                        <span class="arf_js_switch"></span>
                                    </div>
                                </div>
                                <div class="arf_db_connection_header_title" style="margin-left: 0px; padding-left: 20px;">
                                    <span class="arf_db_connection_subtitle"><?php echo addslashes(esc_html__('Use External table.', 'ARForms')); ?></span>
                                    <div class="arf_js_switch_wrapper arf_wordpress_checkbox">                    
                                        <input type="checkbox" class="js-switch" name="options[arf_external_database_opt]" id="arf_external_database_opt" value="1"  <?php isset($values['arf_external_database_opt']) ? checked($values['arf_external_database_opt']) : ''; ?> onchange="arforms_hide_show_custom_table_database_settings(this.checked, 'custom_table');"/>                                
                                        <span class="arf_js_switch"></span>
                                    </div>
                                </div>
                                <?php $arf_wordpress_db = isset($values['arf_wordpress_database_opt']) ? $values['arf_wordpress_database_opt'] : '';?>
                                <?php $arf_external_db= isset($values['arf_external_database_opt']) ? $values['arf_external_database_opt'] : ''; ?> 
                                <div class="arf_wordpress_database_options" data-type="wordpress_table" style="<?php echo ( 1 ==    $arf_wordpress_db ) ? 'display:block;' : 'display:none;'; ?>">
                                    <div class="arf_submit_action_options" >
                                        <label class="arf_label_database"><?php esc_html_e('Database Table Name', 'ARForms') ?></label>
                                        <input type="text" name="options[arf_table_name]" value="<?php echo(isset($values['arf_table_name']))?$values['arf_table_name']:''; ?>" class="arf_large_input_box arf_input_gs" id="arf_table_name">
                                        <div class="arf_custome_database_option" data-type="custom_table"  style="<?php echo ( 1 == $arf_external_db ) ? 'display:block;' : 'display:none;'; ?>">
                                            <div class="arf_submit_action_options" >
                                                <label class="arf_label_database"><?php esc_html_e('Database Host', 'ARForms') ?></label>
                                                <input type="text" name="options[arf_external_host]" value="<?php echo(isset($values['arf_external_host']))?$values['arf_external_host']:''; ?>" class="arf_large_input_box arf_input_gs" id="arf_external_host">
                                            </div>
                                            <div class="arf_submit_action_options" >
                                                <label class="arf_label_database"><?php esc_html_e('Database Username', 'ARForms') ?></label>
                                                <input type="text" name="options[arf_external_username]" value="<?php echo(isset($values['arf_external_username']))?$values['arf_external_username']:''; ?>" class="arf_large_input_box arf_input_gs" id="arf_external_username">
                                            </div>
                                            <div class="arf_submit_action_options" >
                                                <label class="arf_label_database"><?php esc_html_e('Database Password', 'ARForms') ?></label>
                                                <input type="text" name="options[arf_external_password]" value="<?php echo(isset($values['arf_external_password']))?$values['arf_external_password']:''; ?>" class="arf_large_input_box arf_input_gs" id="arf_external_password">
                                            </div>
                                            <div class="arf_submit_action_options" >
                                                <label class="arf_label_database"><?php esc_html_e('Database Name', 'ARForms') ?></label>
                                                <input type="text" name="options[arf_external_database]" value="<?php echo(isset($values['arf_external_database']))?$values['arf_external_database']:''; ?>" class="arf_large_input_box arf_input_gs" id="arf_external_database">
                                            </div>
                                        </div>
                                        <div class="arferrmessage arf_db_error_msg" id="arf_table_name_error"><?php esc_html_e('This field cannot be blank.', 'ARForms'); ?></div>
                                        <div class="arferrmessage arf_db_error_msg" id="arf_table_name_error"><?php esc_html_e('This field cannot be blank.', 'ARForms'); ?></div>
                                    </div>
                                    
                                    <?php

                                    $arforms_db_field_options = array(
                                        '' => array(
                                            '' => esc_html__( 'Please Select Field', 'ARForms' )
                                        )
                                    );
                                                                
                                    
                                   
                                    ?>
                                    <div class="arf_submit_action_options arfdbmaplabel">
                                        <label>
                                            <b><?php esc_html_e('Map form fields with the table columns', 'ARForms') ?></b>
                                            <input type="hidden" class="arf_db_clone_value" value="<?php echo(isset($values['arf_db_headers']))?count($values['arf_db_headers']):'1'?>">
                                        </label>
                                    </div><br/>
                                    <div class="arf_submit_action_options">
                                        <label class="arf_db_heading_label field_label_width"><?php esc_html_e('Form Fields', 'ARForms') ?></label>
                                        <label class="arf_db_heading_label column_label_width"><?php esc_html_e('Column Name', 'ARForms') ?><span><?php esc_html_e('(Table column name)','ARForms')?></span></label>
                                    </div>


                                    <div class="" id="arf_database_details">
                                        <?php
                                        global $arfieldhelper,$maincontroller;
                                        $arf_db_headers = isset($record->arf_db_headers) ? $record->arf_db_headers : '';
                                        $selectbox_field_options = array();
                                        $selectbox_field_options_attr = array();
                                        $selectbox_field_value_label = "";
                                        if (isset($values['fields']) and count($values['fields']) > 0) {

                                            $fields_omit = array('divider', 'section', 'arf_repeater', 'break', 'html', 'imagecontrol' , 'arf_accordion');

                                            foreach ($values['fields'] as $field1) {
                                                if(in_array($field1['type'],$fields_omit)){
                                                    continue;
                                                }
                                        
                                                if( isset( $field1['parent_field_type'] ) && $field1['parent_field_type'] == 'arf_repeater' ){
                                                    continue;
                                                }
        
                                                if (($field1["id"] == $arf_db_headers)) {
                                                    $selectbox_field_value_label = $field1["name"];
                                                }
            
                                                $current_field_id = $field1["id"];
                                                if ($current_field_id !="" && $arfieldhelper->arf_execute_function($field1["name"],'strip_tags')=="") {
                                                    $selectbox_field_options[$current_field_id] = '[Field Id:'.$current_field_id.']';
                                                }else{
                                                    $selectbox_field_options[$current_field_id] = $arfieldhelper->arf_execute_function($field1["name"],'strip_tags');
                                                }
        
                                                $selectbox_field_options_attr['data-type'][$current_field_id] = $field1['type'];      
                                            }
                                        }

                                        $form_fields_key = 'form_fields||'.addslashes( esc_html__( 'Form Fields', 'ARForms') );
                                        $arforms_db_field_options[ $form_fields_key ] = $selectbox_field_options;

                                        $extra_fields_key = 'extra_fields||' . addslashes( esc_html__( 'Extra Fields', 'ARForms') );
                                        
                                        $extra_fields_name_arr = array();

                                        $extra_fields_name_arr['id'] = esc_html__('Entry ID','ARForms');
                                        $extra_fields_name_arr['entry_key'] = esc_html__('Entry Key','ARForms');
                                        $extra_fields_name_arr['ip_address'] = esc_html__('IP Address','ARForms');
                                        $extra_fields_name_arr['browser_info'] = esc_html__('Browser Name','ARForms');
                                        $extra_fields_name_arr['created_date'] = esc_html__('Entry Creation Date','ARForms');
                                        $extra_fields_name_arr['page_url'] = esc_html__('Page URL','ARForms');
                                        $extra_fields_name_arr['referrer'] = esc_html__('Referrer URL','ARForms');
                                        $extra_fields_name_arr['country'] = esc_html__('Country','ARForms');
                                        $arforms_db_field_options[ $extra_fields_key ] = $extra_fields_name_arr;
                                        
                                        if(isset($values['arf_db_headers']) && count($values['arf_db_headers'])>0){
                                            $i = '';
                                            for($i=1;$i<=count($values['arf_db_headers']);$i++){?>
                                                <div id="map_header_db_<?php echo $i;?>" class="map_header_db_main">
                                                <input type="hidden" class="arf_database_input" name="options[arf_database_headers][arf_database_header_<?php echo $i;?>]" id="arf_database_header_<?php echo $i;?>" value="<?php echo(isset($values['arf_db_headers'][$i])) ? $values['arf_db_headers'][$i-1] :'';?>" />
                                                    <?php
                                                    echo $maincontroller->arf_selectpicker_dom( 'options[arf_database_headers][arf_database_header_'.$i.']' , 'arf_database_header_'.$i , 'arf_name_field_dropdown', 'width:170px;', $values['arf_db_headers'][$i-1] , array(), $arforms_db_field_options, true, array(), false, $selectbox_field_options_attr, false, array(), true);
                                                    ?>
                                                    <input type="text" name="options[arf_database_headers_value][arf_database_header_value_<?php echo $i;?>]" value="<?php echo(isset($values['arf_db_headers_value'][$i-1])) ? $values['arf_db_headers_value'][$i-1]:'';?>" class="arf_large_input_box headers_value_input arf_db_value_input" />

                                                    <span class="arfdb_bulk_add_remove_wrapper">
                                                        <span class="bulk_add" onclick="arf_database_col_add(<?php echo $i; ?>);"><svg viewBox="0 -2 28 25"><g id="email"><?php echo ARF_PLUS_ICON; ?></g></svg></span>
                                                        <span class="bulk_remove" onclick="arf_database_col_delete(jQuery(this));" <?php echo(count($values['arf_db_headers'])<2)?'style="display:none;"':'style="margin-left:5px;"';?>>
                                                        <svg viewBox="0 -2 28 25"><g id="email"><?php echo ARF_MINUS_ICON; ?></g></svg></span>
                                                    </span>
                                                    <span class="map_header_db_error_msg" id="map_header_db_error_msg"><?php esc_html_e('This field cannot be blank.','ARForms'); ?></span> 
                                                </div>
                                                
                                        <?php  }
                                        }else{?>
                                            <div id="map_header_db_1" class="map_header_db_main">
                                                <input type="hidden" class="arf_database_input" name="options[arf_database_headers][arf_database_header_1]" id="arf_database_header_1" value="">
                                              
                                                <?php
                                                echo $maincontroller->arf_selectpicker_dom( 'options[arf_database_headers][arf_database_header_1]' , 'arf_database_header_1' , 'arf_name_field_dropdown', 'width:170px;', '' , array(), $arforms_db_field_options, true, array(), false,$selectbox_field_options_attr, false, array(), true);
                                                ?>
                                                  <input type="text" name="options[arf_database_headers_value][arf_database_header_value_1]" value="<?php echo(isset($values['arf_db_headers_value'])) ? $values['arf_db_headers_value']:'';?>"class="arf_large_input_box headers_value_input arf_db_value_input"/>
                                                <span class="arfdb_bulk_add_remove_wrapper">
                                                    <span class="bulk_add" onclick="arf_database_col_add(1);"><svg viewBox="0 -2 28 25" width="25px" height="25px"><g id="email"><?php echo ARF_PLUS_ICON; ?></g></svg></span>
                                                    <span class="bulk_remove arf_db_bulk_remove" onclick="arf_database_col_delete(jQuery(this));"><svg viewBox="0 -4 28 25"><g id="email"><?php echo ARF_MINUS_ICON; ?></g></svg></span>
                                                </span>
                                                <span class="map_header_db_error_msg" id="map_header_db_error_msg"><?php esc_html_e('This field cannot be blank.','ARForms'); ?></span>
                                            </div>
                                        <?php }
                                        ?>
                                    </div>  
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="arf_popup_container_footer">
                    <button type="button" class="arf_popup_close_button" data-id="arf_submit-tracking-script" ><?php echo esc_html__('OK', 'ARForms'); ?></button>
                </div>
            </div>                  
        </div>
        <?php
    }

    function arforms_save_entries_to_external_database( $entry_id, $form_id ){
        
        global $arfrecordmeta, $wpdb, $arfform,$arf_version,$arfform,$MdlDb,$armainhelper,$arformcontroller,$tbl_arf_custom_entry, $arrecordcontroller, $arrecordhelper;

        $ar_form = $arfform->getOne($form_id);

        $options = ($ar_form != '' && isset($ar_form->options)) ? $ar_form->options : array();

        if( !empty( $options['arf_wordpress_database_opt'] ) && 1 == $options['arf_wordpress_database_opt'] && !empty( $options['arf_table_name'] ) ){

            $column_names = $options['arf_db_headers_value'];
            $field_ids = $options['arf_db_headers'];
            $table_name = $options['arf_table_name'];

            $columns_arr = array();

            $entries_results = $arfform->arf_select_db_data( true, '', $MdlDb->entries, '*', 'WHERE id = %d', array($entry_id), '', '', '', false, true, ARRAY_A);

            foreach( $field_ids as $fkey => $fid ){

                $column_key = !empty( $column_names[ $fkey ] ) ? $column_names[ $fkey ] : '';

                if( empty( $column_key ) ){
                    continue;
                }

                if( preg_match( '/(\d+)/', $fid ) ){
                    $where_clause = "WHERE e.field_id  = '".$fid."' AND e.entry_id = %d";
                    $data_arr = $arfform->arf_select_db_data( true, '', $MdlDb->entry_metas." e INNER JOIN ".$MdlDb->fields." f ON  f.id = e.field_id", '*', $where_clause, array($entry_id), '', '', '', false, true, ARRAY_A);
                    if( !empty( $data_arr ) && !empty( $data_arr['entry_value'] ) ){

                        if( 'file' == $data_arr['type'] ){
                            $attach_file_values = explode('|', $data_arr['entry_value']);
                
                            $arf_uploaded_files = "";

                            foreach ($attach_file_values as $attach_file_val){

                                if($attach_file_val != "") {

                                    $meta_field = $wpdb->get_row($wpdb->prepare("select `meta_value` from " . $wpdb->prefix . "postmeta where post_id = %d AND meta_key = '_wp_attached_file'",$attach_file_val)); //phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Reason: $MdlDb->prefix is table name defined globally. False Positive alarm 
                                    if( $meta_field ) {
                                        $file = $meta_field->meta_value;
                                        if ($file) {
                                            $file = str_replace('thumbs/', '', $file);
                                            $arf_uploaded_files .= $file.'|';
                                        }
                                    }
                                }
                            }

                            if ($arf_uploaded_files != "") {
                                $arf_uploaded_files = rtrim($arf_uploaded_files, "|");
                                $columns_arr[ $column_key ] = $arf_uploaded_files;
                            }
                        } else {
                            $atts_params = array(
                                'type' => $data_arr['type'],
                                'truncate' => true,
                                'attachment_id' => $entries_results['attachment_id'],
                                'entry_id' => $entry_id
                            );
                            //$columns_arr[ $column_key ] = $arrecordhelper->display_value( $data_arr['entry_value'], json_decode( json_encode( $data_arr ) ), $atts_params );
                            $columns_arr[ $column_key ] = $data_arr['entry_value'];
                        }
                    } else {
                        $columns_arr[ $column_key ] = '';
                    }
                } else {
                    
                    switch( $fid ){
                        case 'id':
                            $columns_arr[ $column_key ] = !empty( $entries_results[ 'id'] ) ? intval( $entries_results[ 'id'] ) : 0;
                            break;
                        case 'entry_key':
                            $columns_arr[ $column_key ] = !empty( $entries_results[ 'entry_key'] ) ? $entries_results[ 'entry_key' ] : '';
                            break;
                        case 'created_date':
                            $columns_arr[ $column_key ] = !empty( $entries_results[ 'created_date'] ) ? $entries_results[ 'created_date' ] : '';
                        break;
                        case 'browser_info':
                            $browser_info = 'Unknown';
                            if( !empty( $entries_results[ 'browser_info'] ) ){
                                $browser_data = $arrecordcontroller->getBrowser( $entries_results[ 'browser_info' ] );
                                $browser_info = $browser_data[ 'name'] .' ('.$browser_data['version'] .')';
                            }
                            $columns_arr[ $column_key ] = $browser_info;
                            break;
                        case 'ip_address':
                            $columns_arr[ $column_key ] = !empty( $entries_results[ 'ip_address'] ) ? $entries_results[ 'ip_address' ] : '';
                            break;
                        case 'country':
                            $columns_arr[ $column_key ] = !empty( $entries_results[ 'country'] ) ? $entries_results[ 'country' ] : '';
                            break;
                        case 'page_url':
                        case 'referrer':
                            $description = maybe_unserialize( $entries_results['description'] );
                            if( 'page_url' == $fid ){
                                $columns_arr[ $column_key ] = !empty( $description['page_url'] ) ? $description['page_url'] : '';
                            } else {
                                $columns_arr[ $column_key ] = !empty( $description[ 'http_referrer' ] ) ? $description[ 'http_referrer' ] : '';
                            }
                            break;
                        default:
                            break;
                    }
                }
            }

            if( !empty( $columns_arr ) ){
                global $arf_debug_log_id;
                if( !empty( $options['arf_external_database_opt'] ) && 1 == $options['arf_external_database_opt'] ){
                    $db_host = $options['arf_external_host'];
                    $db_user = $options['arf_external_username'];
                    $db_pass = $options['arf_external_password'];
                    $db_name = $options['arf_external_database'];
                    $external_wpdb = new wpdb( $db_user, $db_pass, $db_name, $db_host );

                    if( $external_wpdb->has_connected ){
                        
                        $external_wpdb->insert(
                            $table_name,
                            $columns_arr
                        );
                        
                        if( !empty( $external_wpdb->last_error) ){
                            $arforms_custom_db_error_data = array(	
                                'success'   => 'false',
                                'message'   =>  $external_wpdb->last_error,
                                'params'    => array(
                                    'table_name' => $table_name,
                                    'columns_arr' => $columns_arr,
                                    'entry_id' => $entry_id,
                                    'form_id' => $form_id
                                    )
                                );
                                
                            do_action('arforms_debug_log_entry','custom_db_logs', 'Custom Database Connection response', 'custom_db_data', $arforms_custom_db_error_data , $arf_debug_log_id);
                        }
                    } else {
                        $arforms_custom_db_error_data = array(	
                            'success'   => 'false',
                            'message'   =>  esc_html__('There is an error while connecting to external database.', 'ARForms'),
                            'params'    => json_encode( $external_wpdb )
                        );
                            
                        do_action('arforms_debug_log_entry','custom_db_logs', 'Custom Database Connection response', 'custom_db_data', $arforms_custom_db_error_data , $arf_debug_log_id);   
                    }
                } else {
                    $wpdb->insert(
                        $table_name,
                        $columns_arr
                    );
                    if( !empty( $wpdb->last_error) ){
                        $arforms_custom_db_error_data = array(	
                            'success'   => 'false',
                            'message'   =>  $wpdb->last_error,
                            'params'    => array(
                                'table_name' => $table_name,
                                'columns_arr' => $columns_arr,
                            )
                        );
                        do_action('arforms_debug_log_entry','custom_db_logs', 'Custom Database Connection response', 'custom_db_data', $arforms_custom_db_error_data , $arf_debug_log_id);
                    }
                }
            }

        }

    }

}

global $arforms_custom_db;
$arforms_custom_db = new arforms_custom_db;