<?php

GFForms::include_addon_framework();

require_once('includes/gravity-extra-license.php');

class GFAutocompleteFieldAddOn extends GFAddOn

{

    protected $_version = GF_AUTOCOMPLETE_FIELD_ADDON_VERSION;

    protected $_min_gravityforms_version = '1.9.1';

    protected $_slug = 'autocompletefieldaddon';

    protected $_path = 'autocompletefieldaddon/autocompletefieldaddon.php';

    protected $_full_path = __FILE__;

    protected $_title = 'GravityForms Autocomplete Field Add-On';

    protected $_short_title = 'Autocomplete Field';



    /** 

     * @var object $_instance If available, contains an instance of this class. 

     */

    private static $_instance = null;

    protected $matches = '';

    /** 

     * Returns an instance of this class, and stores it in the $_instance property. 

     * 

     * @return object $_instance An instance of this class. 

     */

    public static function get_instance()

    {

        if (self::$_instance == null) {

            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /** 

     * Include the field early so it is available when entry exports are being performed. 

     */

    public function pre_init()

    {

        parent::pre_init();

        if ($this->is_gravityforms_supported() && class_exists('GF_Field')) {

            require_once('includes/class-autocomplete-gf-field.php');
        }

        add_action('wp_ajax_gf_autocomplete_delete_file', array($this, 'delete_file'));

        // add_action( 'wp_ajax_nopriv_my_action',array($this,'my_action') ); 

        // add_action('wp_enqueue_scripts', array($this, 'jquery_ui_style')); 

        // add_action('wp_enqueue_scripts', array($this,'pass_var_to_js') ); 

        add_action('gform_register_init_scripts', array($this, 'gform_bb_addClass'));

        add_action('gform_register_init_scripts', array($this, 'add_json'));

        add_action('gform_editor_js', array($this, 'bb_editor_script'));
    }

    public function init()

    {

        $addon_args = array(

            '_slug' => $this->_slug,

            '_path' => $this->_path,

            '_title' => $this->_title,

            '_short_title' => $this->_short_title

        );

        $this->gravityextra = new GravityExtra_GFAutocompletekAddon\License($addon_args, $this->is_gravityforms_supported('2.5-beta'));

        parent::init();

        $url = 'https://gravityextra.com/addon-version/';
        $curl = curl_init();
        $timeout = 5;
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($curl);
        curl_close($curl);
        preg_match('/<td\s+id="autocomplete-addon">([^<]+)<\/td>/', $data, $this->matches);

        add_action('load-plugins.php', function () {

            add_filter('site_transient_update_plugins', array($this, 'update_plugins_auto_complete_field_addon'));
        });

        add_filter('gform_field_validation', [$this, 'qh_custom_validate_field'], 10, 4);
        add_filter( 'gform_routing_field_types', function( $field_types ) {
            array_push( $field_types, 'autocomplete' );
              return $field_types;
        });

        // add_action( 'wp_enqueue_scripts' , array($this,'locale_script_auto_complete'), 10, 1 );

    }

    function update_plugins_auto_complete_field_addon($transient)

    {

        $plugin_path = plugin_dir_path(__FILE__);

        $plugin_directory_name = basename($plugin_path);

        $slug = $plugin_directory_name;

        $plugin_name = $plugin_directory_name . '/autocompletefieldaddon.php';

        $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_name);

        $plugin_current_version = $plugin_data['Version'];



        $new_version = '';

        if (!empty($this->matches)) {

            $new_version = $this->matches[1];
        }

        $package = 'https://gravityextra.com/gf-product-update/' . $plugin_directory_name . '-v-' . $new_version . '.zip';

        if (!$this->gravityextra->is_valid_license()) {

            $package = '';
        }

        $update = (object)[

            'url' => 'https://gravityextra.com/gravity-forms-advanced-autocomplete-field/',

            'plugin' => $plugin_name,

            'package' => $package,

            'new_version' => $new_version,

            'id' => $plugin_name,

        ];

        if (isset($transient->response) && is_array($transient->response) && version_compare($plugin_current_version, $new_version, '<')) {

            $transient->response[$plugin_name] = $update;
        } else if (isset($transient->no_update) && is_array($transient->no_update)) {

            $transient->no_update[$plugin_name] = $update;
        }

        return $transient;
    }

    public function plugin_settings_fields()

    {

        $license_section = $this->gravityextra->license_section();

        if ($this->gravityextra->is_valid_license()) {

            return array($license_section);
        } else {

            return array($license_section);
        }
    }

    public function init_admin()

    {

        parent::init_admin();

        // add_filter( 'gform_tooltips', array( $this, 'tooltips' ) ); 

        // add_action( 'gform_field_appearance_settings', array( $this, 'field_appearance_settings' ), 10, 2 ); 

        if ($this->gravityextra->is_valid_license()) {

            add_action('gform_field_advanced_settings', array($this, 'my_advanced_settings'), 10, 2);
        }

        // else {

        // add_action('gform_field_advanced_settings', array($this, 'my_advanced_settings'), 10, 2); 

        // add_action('gform_field_standard_settings', array($this, 'check_license_active'), 10, 2);

        // } 

        add_action('gform_field_advanced_settings', array($this, 'bb_advanced_settings_select_multiple_value'), 10, 2);

        add_action('gform_field_advanced_settings', array($this, 'bb_advanced_settings_record_limit'), 10, 2);

        add_action('gform_field_advanced_settings', array($this, 'bb_advanced_settings_minimum_input_letters'), 10, 2);

        add_action('gform_editor_js', function () {

?>

            <script type='text/javascript'>
                fieldSettings['autocomplete'] += ", .select_multiple_value_setting";

                fieldSettings['autocomplete'] += ", .enter_other_value_setting";

                jQuery(document).on("gform_load_field_settings", function(event, field, form) {

                    jQuery("#select_multiple_value").attr("checked", field["select_multiple_value_custField"] == true);

                    jQuery('#enter_other_value').prop('checked', field.enterOtherValueOption);

                });

                fieldSettings['autocomplete'] += ", .record_limit_setting";

                fieldSettings['autocomplete'] += ", .minimum_input_letters_setting";
            </script>

        <?php

        });

        //Filter to add a new tooltip 

        add_filter('gform_tooltips', array($this, 'add_suggestion_tooltips'));

        add_filter('gform_tooltips', array($this, 'add_tooltips_for_file'));

        add_filter('gform_tooltips', array($this, 'add_tooltips_for_select_multiple_value'));

        add_filter('gform_tooltips', array($this, 'add_tooltips_for_record_limit'));

        add_filter('gform_tooltips', array($this, 'add_tooltips_for_minimum_input_letters'));
    }

    function gform_bb_addClass($form)

    {

        $bb_script1 = '';

        foreach ($form["fields"] as $field) {

            if ($field->type == 'autocomplete') {

                if ($field->select_multiple_value_custField == true) {

                    $bb_script1 .= "

 jQuery( '#input_" . $field->formId . "_" . $field->id . "').addClass('bb_multipe_value');

 ";
                } else if ($field->select_multiple_value_custField == false) {

                    $bb_script1 .= "

 jQuery( '#input_" . $field->formId . "_" . $field->id . "').removeClass('bb_multipe_value');

 ";
                }
            }
        }

        GFFormDisplay::add_init_script($form['id'], 'bb_addClass', GFFormDisplay::ON_PAGE_RENDER, $bb_script1);
    }

    public function qh_custom_validate_field($result, $value, $form, $field)

    {

        global $wpdb;

        $arr_suggest = explode(',', $field->suggest_word);

        $check_value_valid = in_array($value, $arr_suggest);

        // delete_option("efe_suggest_word_$field->id");

        $enable_other_value = isset($field['enterOtherValueOption']) ? $field['enterOtherValueOption'] : false;

        // var_dump($enable_other_value); 

        if ($field['type'] == 'autocomplete') {

            if ($field->my_la == 'file') {

                $url_file = $field->url_file;

                $arrContextOptions = array(

                    "ssl" => array(

                        "verify_peer" => false,

                        "verify_peer_name" => false,

                    ),

                );

                $json = file_get_contents($url_file, false, stream_context_create($arrContextOptions));

                $data = json_decode($json, true);

                // var_dump($data);

                // die();

                $check_value_valid = in_array($value, $data);

                // var_dump($check_value_valid);

            }

            if ($field->my_la == 'sql') {

                $tableName = $field->suggest_sql_tableName;

                $columnName = $field->suggest_sql_columnName;

                // $checkSql = true;

                // if ($wpdb->get_var("show tables like '{$tableName}'") == $tableName) {

                // $column = $wpdb->get_results("DESC {$tableName}");

                // foreach ($column as $row) {

                // if ($row->Field === $columnName) {

                // $checkSql = true;

                // }

                // }

                // } elseif ($wpdb->get_var("show tables like '{$wpdb->prefix}{$tableName}'") == $wpdb->prefix . $tableName) {

                // $column = $wpdb->get_results("DESC {$wpdb->prefix}{$tableName}");

                // foreach ($column as $row) {

                // if ($row->Field === $columnName) {

                // $tableName = $wpdb->prefix . $tableName;

                // $checkSql = true;

                // }

                // }

                // }

                // var_dump($checkSql);

                // die(); 

                // if ($checkSql) {

                $results = $wpdb->get_results("SELECT {$columnName} FROM {$tableName}", ARRAY_A);

                $data = array();

                if (count($results) != 0) {

                    foreach ($results as $val) {

                        array_push($data, $val[$columnName]);
                    }
                }

                $check_value_valid = in_array($value, $data);

                // }

            }

            if ($enable_other_value == false && $check_value_valid == false) {

                $result['is_valid'] = false;

                $result['message'] = "Please enter a valid value.";
            }
        }

        return $result;
    }

    function bb_editor_script()

    {

        ?>

        <script type='text/javascript'>
            jQuery(document).on('gform_load_field_settings', function(event, field, form) {

                jQuery('input#record_limit').val(field.record_limit_custField);

                jQuery('input#minimum_input_letters').val(field.minimum_input_letters_custField);

            });
        </script>

        <?php

    }

    function add_json($form)
    {
        global $wpdb;
        
        $jsonFields = array();

        foreach ($form["fields"] as $field) {

            if ($field->record_limit_custField == '') {

                $field->record_limit_custField = 20;
            }

            if ($field->minimum_input_letters_custField == '') {

                $field->minimum_input_letters_custField = 1;
            }

            if ($field->type == 'autocomplete') {
                $field_id = $field->id;
                $pageNumber = !empty($field->pageNumber) ? $field->pageNumber : 1;

                if ($field->my_la == 'word') {

                    $su1 = $field->suggest_word;

                    $su2 = str_replace(', ', ',', $su1);
                    $su3 = str_replace(' ,', ',', $su2);

                    $su = explode(',', $su3);
                    $jsonFields[$pageNumber][$field_id]["data"] = $su;

                    $jsonFields[$pageNumber][$field_id]["limit"] = $field->record_limit_custField;

                    $jsonFields[$pageNumber][$field_id]["minimum"] = $field->minimum_input_letters_custField;
                } elseif ($field->my_la == 'file' && !empty($field->url_file)) {

                    $url_file = $field->url_file;

                    $arrContextOptions = array(

                        "ssl" => array(

                            "verify_peer" => false,

                            "verify_peer_name" => false,

                        ),

                    );

                    $json = file_get_contents($url_file, false, stream_context_create($arrContextOptions));

                    $data = json_decode($json, true);

                    $jsonFields[$pageNumber][$field_id]["data"] = $data;

                    $jsonFields[$pageNumber][$field_id]["limit"] = $field->record_limit_custField;

                    $jsonFields[$pageNumber][$field_id]["minimum"] = $field->minimum_input_letters_custField;
                } elseif ($field->my_la == 'sql') {

                    $tableName = $field->suggest_sql_tableName;

                    $columnName = $field->suggest_sql_columnName;

                    $checkSql = false;

                    if ($wpdb->get_var("show tables like '{$tableName}'") == $tableName) {

                        $column = $wpdb->get_results("DESC {$tableName}");

                        foreach ($column as $row) {

                            if ($row->Field === $columnName) {

                                $checkSql = true;
                            }
                        }
                    } elseif ($wpdb->get_var("show tables like '{$wpdb->prefix}{$tableName}'") == $wpdb->prefix . $tableName) {

                        $column = $wpdb->get_results("DESC {$wpdb->prefix}{$tableName}");

                        foreach ($column as $row) {

                            if ($row->Field === $columnName) {

                                $tableName = $wpdb->prefix . $tableName;

                                $checkSql = true;
                            }
                        }
                    }

                    if ($checkSql) {

                        $results = $wpdb->get_results("SELECT {$columnName} FROM {$tableName}", ARRAY_A);

                        $data = array();

                        if (count($results) != 0) {

                            foreach ($results as $val) {
                                array_push($data, $val[$columnName]);

                            }
                        }

                        $jsonFields[$pageNumber][$field_id]["data"] = $data;

                        $jsonFields[$pageNumber][$field_id]["limit"] = $field->record_limit_custField;

                        $jsonFields[$pageNumber][$field_id]["minimum"] = $field->minimum_input_letters_custField;
                    }
                } elseif ($field->my_la == 'post') {
                    $posts = get_posts(array(
                        'post_type' => $field->post_type,
                        'posts_per_page' => -1,
                        'post_status' => 'publish', 
                    ));
                    $data = [];
                    if (!$field->post_field) {
                        $field->post_field = 'post_title';
                    }
                    foreach ($posts as $post) {
                        array_push($data, $post->{$field->post_field});
                    }
                    $jsonFields[$pageNumber][$field_id]["data"] = $data;

                    $jsonFields[$pageNumber][$field_id]["limit"] = $field->record_limit_custField;

                    $jsonFields[$pageNumber][$field_id]["minimum"] = $field->minimum_input_letters_custField;
                }
                $jsonFields[$pageNumber][$field_id]["enter_other_value"] = isset($field->enterOtherValueOption) ? ($field->enterOtherValueOption == false ? "1" : "0") : "1";
            }
        }
        

        // return json_encode($jsonFields);

        $script = "var autocompleteFields = JSON.parse('" . addslashes(json_encode($jsonFields)) . "'); 
        function split( val ) {
            return val.split( /,\s*/ );
        }
        function extractLast( term ) {
            return split( term ).pop();
        }
        
        for(let page_id in autocompleteFields) { 
            let autocompletField = autocompleteFields[page_id];
            for(let field_id in autocompletField){
                let vqh_checkDisableLoading = false;
                jQuery(document).on('keypress', '#input_'+formId+'_'+field_id,function(event) {
                    jQuery('.dosan_check_error'+field_id).css('display','none');
                    if(autocompletField[field_id]['enter_other_value'] == 1){
                        let arr_data_suggestion = autocompletField[field_id]['data'];
                        if( typeof autocompletField[field_id]['data'] == 'object'){
                            arr_data_suggestion = Object.values(autocompletField[field_id]['data']);
                        }
                        let arr_character = [];
                        arr_data_suggestion.forEach(item =>{
                            for(const char of item){
                                if(char != ''){
                                    arr_character.push(char);
                                }
                            }
                        })
                        
                        var char = String.fromCharCode(event.which).toLowerCase();
                        if (arr_character.indexOf(char) === -1 && arr_character.indexOf(char.toUpperCase()) === -1) {
                            jQuery('.dosan_check_error'+field_id).css('display','block');
                            jQuery( '#input_'+formId +'_'+field_id).removeClass('ui-autocomplete-loading');
                            vqh_checkDisableLoading = true;
                            event.preventDefault();
                        }else{	
                            vqh_checkDisableLoading = false;
                        }

                        if (arr_data_suggestion.indexOf(event.target.value) != -1 ) {
                            jQuery( '#input_'+formId +'_'+field_id).removeClass('ui-autocomplete-loading');
                            vqh_checkDisableLoading = true;
                            event.preventDefault();
                        }else{
                            vqh_checkDisableLoading = false;
                        }
                    }
                });
                jQuery('#field_'+formId +'_'+field_id+' .ginput_container_autocomplete').append('<span class='+'bb_check_error'+' style='+'display:none;color:red;'+'>Minimum ' + autocompletField[field_id]['minimum'] + ' letters required</span>');
                jQuery('#field_'+formId +'_'+field_id+' .ginput_container_autocomplete').append('<span class=' + 'dosan_check_error'+field_id+ ' style=' + 'display:none;color:red;padding-top:10px;' + '>Please enter a valid value.</span>');
                jQuery(document).on('keyup', '#input_'+formId +'_'+field_id,function(event) {
                    if(jQuery( '#input_'+formId +'_'+field_id ).val().length < 0 || jQuery( '#input_'+formId +'_'+field_id ).val().length < autocompletField[field_id]['minimum']){
                        jQuery( '#field_'+formId +'_'+field_id+' .ginput_container_autocomplete .bb_check_error' ).show();
                    }else{
                        if(vqh_checkDisableLoading == false){
                            jQuery('#input_'+formId+'_'+field_id).addClass('ui-autocomplete-loading');
                        }
                        jQuery('#input_'+formId +'_'+field_id).addClass('ui-autocomplete-loading');
                        jQuery( '#field_'+formId +'_'+field_id+' .ginput_container_autocomplete .bb_check_error' ).hide();
                    }

                    jQuery( '#input_'+formId +'_'+field_id ).on( 'keydown', function( event ) {
                        if ( event.keyCode === jQuery.ui.keyCode.TAB && jQuery( this ).autocomplete( 'instance' ).menu.active ) {
                            event.preventDefault();
                        }
                    });

                    if(jQuery( '#input_'+formId +'_'+field_id ).val().length == 0){
                        jQuery( '#field_'+formId +'_'+field_id+' .ginput_container_autocomplete .bb_check_error' ).hide();
                        jQuery( '#input_'+formId +'_'+field_id ).removeClass('ui-autocomplete-loading');
                    }
                    
                    jQuery( '#input_'+formId +'_'+field_id ).autocomplete({
                        minLength: autocompletField[field_id]['minimum'],
                        source: function( request, response ) {
                            var results = jQuery.ui.autocomplete.filter(autocompletField[field_id]['data'], extractLast( request.term ) );
                            response(results.slice(0, autocompletField[field_id]['limit']));
                        },
                    });
                    jQuery( '.bb_multipe_value' ).autocomplete({
                        focus: function() {
                            // prevent value inserted on focus
                            return false;
                        },
                        select: function( event, ui ) {
                            var terms = split( this.value );
                            // remove the current input
                            terms.pop();
                            // add the selected item
                            terms.push( ui.item.value );
                            // add placeholder to get the comma-and-space at the end
                            terms.push('' );
                            this.value = terms.join( ', ' );
                            return false;
                        }
                    });
                });
            }
        }";
        GFFormDisplay::add_init_script($form['id'], 'autocomplete_fields', GFFormDisplay::ON_PAGE_RENDER, $script);
    }

    function jquery_ui_style()

    {

        wp_enqueue_style('jquery_ui_css', $this->get_base_url() . '/css/jquery-ui.css');
    }

    function delete_file()

    {

        global $wpdb;

        $whatever = $_POST['whatever'];

        $path = parse_url($whatever, PHP_URL_PATH); // Remove "http://localhost" 

        // $fullPath = get_home_path() . $path; 

        $fullPath = $_SERVER['DOCUMENT_ROOT'] . $path;

        unlink($fullPath);

        die();
    }



    // # SCRIPTS & STYLES ----------------------------------------------------------------------------------------------- 

    /** 

     * Include my_script.js when the form contains a 'simple' type field. 

     * 

     * @return array 

     */

    public function scripts()

    {

        $scripts = array(

            array(

                'handle' => 'gf_autocomplete_admin_js',

                'src' => $this->get_base_url() . '/js/auto_complete_script.js',

                'version' => $this->_version,

                'deps' => array('jquery-ui_js'),

                'enqueue' => array(

                    array('field_types' => array('autocomplete')),

                ),

                'strings' => array(

                    'ajaxUrl' => admin_url('admin-ajax.php'),

                ),

            ),

            array(

                'handle' => 'autocomplete_js',

                'version' => $this->_version,

                'deps' => array('jquery-ui-autocomplete'),

                'enqueue' => array(

                    array('field_types' => array('autocomplete')),

                ),

            ),

            array(

                'handle' => 'jquery-ui_js',

                'src' => 'https://code.jquery.com/ui/1.13.2/jquery-ui.js',

                'version' => $this->_version,

                'deps' => array('jquery'),

                'enqueue' => array(

                    array('field_types' => array('autocomplete')),

                ),

            ),

        );

        return array_merge(parent::scripts(), $scripts);
    }

    /** 

     * Include my_styles.css when the form contains a 'autocomplete' type field. 

     * 

     * @return array 

     */

    public function styles()

    {

        $styles = array(

            array(

                'handle' => 'my_styles_css',

                'src' => $this->get_base_url() . '/css/auto_complete_styles.css',

                'version' => $this->_version,

                // 'deps' => array('jquery-ui-autocomplete', 'jquery-ui'), 

                'enqueue' => array(

                    array('field_types' => array('autocomplete')),

                    !GFCommon::is_form_editor()

                )

            ),

            array(

                'handle' => 'jquery-ui_css',

                // 'src' => '//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css',

                'src' => $this->get_base_url() . '/css/jquery-autocomplete-custom.css',

                'version' => $this->_version,

                // 'deps' => array('jquery-ui-autocomplete', 'jquery-ui'), 

                'enqueue' => array(

                    array('field_types' => array('autocomplete')),

                    !GFCommon::is_form_editor()

                )

            ),

        );

        return array_merge(parent::styles(), $styles);
    }



    // # FIELD SETTINGS ------------------------------------------------------------------------------------------------- 

    public function locale_script_auto_complete($hook)

    {

        if ($is_form_editor = GFCommon::is_form_editor()) {

            wp_register_script('gf_autocomplete_scripts', $this->get_base_url() . '/js/auto_complete_script.js');

            $translation_array = array(

                'ajaxUrl' => admin_url('admin-ajax.php'),

            );

            wp_localize_script('gf_autocomplete_scripts', 'GFAutocomplete', $translation_array);

            wp_enqueue_script('gf_autocomplete_scripts');
        }
    }

    function check_license_active($position, $form_id)

    {

        if ($position == 0) { ?>

            <li class="autocomplete_setting field_setting"><?php echo $this->gravityextra->notices_user_active_license(); ?></li>

        <?php }
    }

    public function bb_advanced_settings_select_multiple_value($position, $form_id)

    {

        if ($position === 100) :

        ?>

            <li class="select_multiple_value_setting field_setting">

                <input type="checkbox" id="select_multiple_value" onclick="SetFieldProperty('select_multiple_value_custField', this.checked);" />

                <label for="select_multiple_value" class="inline">

                    <?php esc_html_e('Select multiple value', 'gravityforms'); ?>

                    <?php gform_tooltip("select_multiple_value") ?>

                </label>

            </li>

        <?php

        endif;

        if ($position == 50) {

        ?>

            <li class="enter_other_value_setting field_setting">

                <input type="checkbox" id="enter_other_value" onchange="SetFieldProperty('enterOtherValueOption', this.checked);" />

                <label for="enter_other_value" class="inline">

                    <?php esc_html_e('Enable the ability to enter other values than source', 'gravityforms'); ?>

                    <?php gform_tooltip('When selecting this option, users can input anything they want, by default, it is not enabled.') ?>

                </label>

            </li>

        <?php

        }
    }

    public function bb_advanced_settings_record_limit($position, $form_id)

    {

        if ($position === 100) :

        ?>

            <li class="record_limit_setting field_setting">

                <label for="record_limit" class=" section_label">

                    <?php esc_html_e('Record Limit', 'gravityforms'); ?>

                    <?php gform_tooltip("record_limit") ?>

                </label>

                <input type="number" min="1" id="record_limit" onchange="SetFieldProperty('record_limit_custField',jQuery(this).val());" onkeyup="SetFieldProperty('record_limit_custField',jQuery(this).val());" style=" max-height: 2.25rem;min-height: 2.25rem;width: 100%;" placeholder="20" />

            </li>

        <?php

        endif;
    }

    public function bb_advanced_settings_minimum_input_letters($position, $form_id)

    {

        if ($position === 100) :

        ?>

            <li class="minimum_input_letters_setting field_setting">

                <label for="minimum_input_letters" class=" section_label">

                    <?php esc_html_e('Minimum Input Letters', 'gravityforms'); ?>

                    <?php gform_tooltip("minimum_input_letters") ?>

                </label>

                <input type="number" min="1" id="minimum_input_letters" onchange="SetFieldProperty('minimum_input_letters_custField',jQuery(this).val());" onkeyup="SetFieldProperty('minimum_input_letters_custField',jQuery(this).val());" style=" max-height: 2.25rem;min-height: 2.25rem;width: 100%;" placeholder="1" />

            </li>

        <?php

        endif;
    }

    public function my_advanced_settings($position, $form_id)

    {
        
        // die();
        // $field_one = GFAPI::get_field( $form_id, 1 );

        // var_dump($form_id); 

        //create settings on position 50 (right after Admin Label) 

        if ($position == 50) {
            $post_types = get_post_types(array(
                'public'   => true,
                '_builtin' => false
            ), 'objects');
            $main_post_types = array_keys($post_types);
            array_push($main_post_types, 'post', 'page') ;
            $main_fields = [
                'post_title',
                'post_content',
                'post_author',
                'post_date',
                'post_status',
            ];
        ?>

            <li class="autocomplete_setting field_setting">
                <h2><?php _e("Autocomplete Settings", "gravityforms"); ?></h2>
                <label for="suggest_word" class="section_label">

                    
                    <?php _e("Please Select Source Type", "gravityforms"); ?>

                    <?php gform_tooltip("suggestion_value") ?>

                </label>
                <select name="my_la" id="my_la" style="margin-bottom: 10px;">
                    <option value="word">Input String</option>
                    <option value="sql">MySQL Database Table</option>
                    <option value="file">Imported JSON File</option>
                    <option value="post">Post Type</option>
                </select>
                <!-- <input type="radio" id="by_input_word" name="chosse" value="by_input_word" onclick="show_input_word()" onchange="show_input_word()">

                <label for="by_input_word" class="inline" style=" margin-bottom: 0.7rem !important;">String Input</label>&nbsp;&nbsp;

                <input type="radio" id="by_input_sql" name="chosse" value="by_input_sql" onclick="show_input_sql()" onchange="show_input_sql()">

                <label for="by_input_sql" class="inline" style=" margin-bottom: 0.7rem !important;">Database</label>&nbsp;&nbsp;

                <input type="radio" id="by_file_given" name="chosse" value="by_file_given" onclick="show_input_file()">

                <label for="by_file_given" class="inline" style=" margin-bottom: 0.7rem !important;">JSON File</label>

                <input type="radio" id="by_post_type" name="chosse" value="by_post_type" onclick="show_post_type()">

                <label for="by_post_type" class="inline" style=" margin-bottom: 0.7rem !important;">Post type</label><br> -->

                <div class="input_word" style="display: none">

                    <textarea id="suggest_word" rows="4" cols="50" onkeyup="SetFieldProperty('suggest_word',jQuery(this).val());" onchange="SetFieldProperty('suggest_word',jQuery(this).val());"></textarea>

                </div>

                <div class="input_sql">

                    <div class="" style=" margin-bottom: 0.7rem !important;">

                        <label for="">Table Name</label>

                        <input style=" margin-top: 0.7rem !important;" type="text" id="suggest_sql_tableName" onkeyup="SetFieldProperty('suggest_sql_tableName',jQuery(this).val());" onchange="SetFieldProperty('suggest_sql_tableName',jQuery(this).val());">

                    </div>

                    <div class="" style=" margin-bottom: 0.7rem !important;">

                        <label for="">Column Name</label>

                        <input style=" margin-top: 0.7rem !important;" type="text" id="suggest_sql_columnName" onkeyup="SetFieldProperty('suggest_sql_columnName',jQuery(this).val());" onchange="SetFieldProperty('suggest_sql_columnName',jQuery(this).val());">

                    </div>

                    <div class="resultSql">

                        <!-- <textarea id="resultSql" disabled></textarea> -->

                    </div>

                </div>

                <div class="file_input" style="display: none">

                    <input type="file" name="file" id="file" style="width: 100%; margin-bottom: 0.7rem;">

                    <div id="curren_file">

                        <label for="curren_file_name" class="section_label">Existing file <?php gform_tooltip("form_field_file") ?></label>

                        <input type="text" disabled="" name="" id="curren_file_name" value="" style="display: none">

                        <input type="text" id="name" name="" value="" disabled="" style=" margin-bottom: 0.7rem;">

                        <input type="button" id="delete_file" name="" value="Delete" onclick="delete_my_file()">

                    </div>

                </div>
                <div class="input_post" style="display: none">
                    <label for="" class="section_label">Post Type</label>
                    <select name="post_type" id="post_type" style="margin-bottom: 10px" onchange="SetFieldProperty('post_type',jQuery(this).val());">
                        <?php foreach ($main_post_types as $post_type) :?>
                            <option value="<?=$post_type?>"><?=$post_type?></option>
                        <?php endforeach ?>  
                    </select>
                    <label for="" class="section_label">Post Field</label>
                    <select name="post_field" id="post_field"  onchange="SetFieldProperty('post_field',jQuery(this).val());">
                        <?php foreach ($main_fields as $main_field) :?>
                            <option value="<?=$main_field?>"><?=$main_field?></option>
                        <?php endforeach ?>  
                    </select>
                </div>


                <script type="text/javascript">
                       jQuery("#my_la").change(function(){
                            var selectedValue = jQuery(this).val();
                            if (selectedValue === 'word') {
                                jQuery('.input_word').css({
                                    "display": "block"
                                });

                                jQuery('.file_input').css({
                                    "display": "none"
                                });

                                jQuery('.input_sql').css({
                                    "display": "none"
                                });
                                jQuery('.input_post').css({
                                    "display": "none"
                                });
                            } else if (selectedValue === 'sql') {
                                jQuery('.input_word').css({
                                    "display": "none"
                                });

                                jQuery('.file_input').css({
                                    "display": "none"
                                });

                                jQuery('.input_sql').css({
                                    "display": "block"
                                });
                                jQuery('.input_post').css({
                                    "display": "none"
                                });
                            } else if(selectedValue === 'file') {
                                jQuery('.input_word').css({

                                "display": "none"

                                });

                                jQuery('.file_input').css({

                                "display": "block"

                                });

                                jQuery('.input_sql').css({

                                "display": "none"

                                });
                                jQuery('.input_post').css({

                                "display": "none"

                                });
                            } else if(selectedValue === 'post') {
                                jQuery('.input_word').css({

                                "display": "none"

                                });

                                jQuery('.file_input').css({

                                "display": "none"

                                });

                                jQuery('.input_sql').css({

                                "display": "none"

                                });
                                jQuery('.input_post').css({

                                "display": "block"

                                });
                            } 
                            console.log(selectedValue);
                            SetFieldProperty('my_la',selectedValue);
                        });
                    // function my_la() {
                    //     console.log(jQuery(this).val());
                    //     body... 

                    //     jQuery('.input_word').css({

                    //         "display": "block"

                    //     });

                    //     jQuery('.file_input').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.input_sql').css({

                    //         "display": "none"

                    //     });
                    //     jQuery('.input_post').css({

                    //         "display": "none"

                    //     });
                    //     SetFieldProperty('my_la', "word");

                    // }

                    // function show_input_file() {

                    //     // body... 

                    //     jQuery('.input_word').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.file_input').css({

                    //         "display": "block"

                    //     });

                    //     jQuery('.input_sql').css({

                    //         "display": "none"

                    //     });
                    //     jQuery('.input_post').css({

                    //         "display": "none"

                    //     });
                    //     SetFieldProperty('my_la', "file");


                    // }

                    // function show_input_sql() {

                    //     jQuery('.input_word').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.file_input').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.input_sql').css({

                    //         "display": "block"

                    //     });
                    //     jQuery('.input_post').css({

                    //         "display": "none"

                    //     });
                    //     SetFieldProperty('my_la', "sql");

                    // }

                    // function show_post_type() {

                    //     jQuery('.input_word').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.file_input').css({

                    //         "display": "none"

                    //     });

                    //     jQuery('.input_sql').css({

                    //         "display": "none"

                    //     });
                    //     jQuery('.input_post').css({

                    //         "display": "block"

                    //     });
                    //     SetFieldProperty('my_la', "post");

                    // }



                    jQuery("#file").change(function() {


                        var formData = new FormData();

                        formData.append("action", "upload-attachment");

                        var fileInputElement = document.getElementById("file");

                        formData.append("async-upload", fileInputElement.files[0]);

                        formData.append("name", fileInputElement.files[0].name);

                        var name = fileInputElement.files[0].name;

                        SetFieldProperty("file_name", name);

                        var file_extendtion = name.split('.').pop();

                        if (file_extendtion == "json") {

                            console.log(file_extendtion);

                            //also available on page from _wpPluploadSettings.defaults.multipart_params._wpnonce 

                            jQuery('#name').val(name);

                            <?php $my_nonce = wp_create_nonce('media-form'); ?>

                            formData.append("_wpnonce", "<?php echo $my_nonce; ?>");

                            var xhr = new XMLHttpRequest();

                            var response;

                            var html = "";

                            xhr.onreadystatechange = function() {

                                if (xhr.readyState == 4 && xhr.status == 200) {

                                    console.log(JSON.parse(xhr.response).data.url);

                                    SetFieldProperty('url_file', JSON.parse(xhr.response).data.url);

                                    jQuery.getJSON(JSON.parse(xhr.response).data.url, function(data) {

                                        console.log("type: " + typeof data);

                                        console.log("type string: " + typeof JSON.stringify(data));

                                        console.log(data);

                                        var p = jQuery('#suggest_word').val() + "," + Object.values(data).toString();

                                        jQuery('#suggest_word').val(p);

                                    });

                                    // console.log(xhr); 

                                }

                            };

                            xhr.open("POST", ajaxurl);

                            xhr.send(formData);

                        } else {

                            console.log("No! do not upload");

                            alert("Wrong file support, this plugin only support JSON format.");

                            document.getElementById("file").value = "";

                        }

                    });
                </script>

            </li>

<?php

        }
    }

    function add_suggestion_tooltips($tooltips)

    {

        $tooltips['suggestion_value'] = "<h6>Please Select Source Type</h6>Please select source type from here to pull data for the autocomplete values.";

        return $tooltips;
    }

    function add_tooltips_for_file($tooltips)

    {

        $tooltips['form_field_file'] = '<h6>Suggestion Json structure</h6>Please follow the below JSON structure to make it work. Your JSON file should look like this:</br> 

 [</br>&nbsp{</br> 

 &nbsp&nbsp"label": "label1",</br> 

 &nbsp&nbsp"value": "value1"</br> 

 &nbsp},</br>&nbsp{</br> 

 &nbsp&nbsp"label": "label2",</br> 

 &nbsp&nbsp"value": "value2"</br> 

 &nbsp}</br>]';

        return $tooltips;
    }

    function add_tooltips_for_select_multiple_value($tooltips)

    {

        $tooltips['select_multiple_value'] = "<h6>Select multiple value</h6>User can select multiple values for autocomplete field";

        return $tooltips;
    }

    function add_tooltips_for_record_limit($tooltips)

    {

        $tooltips['record_limit'] = "<h6>Record Limit</h6>Set the number of records to return for the result - Default value: 20";

        return $tooltips;
    }

    function add_tooltips_for_minimum_input_letters($tooltips)

    {

        $tooltips['minimum_input_letters'] = "<h6>Minimum Input Letters</h6>Define the minimum number of letters for the autocomplete to trigger, default is 1";

        return $tooltips;
    }
}
