<?php

if (!class_exists("GFForms")) {
    die();
}

class Autocomplete_GF_Field extends GF_Field
{
    /**
	 * @var string $type The field type.
	 */
    public $type = "autocomplete";
    /**
	 * Return the field title, for use in the form editor.
	 *

	 * @return string
	 */
    public function get_form_editor_field_title()
    {
        return esc_attr__("Autocomplete", "simplefieldaddon");
    }

    /**
	 * Assign the field button to the Advanced Fields group.
	 * @return array
	 */
    public function get_form_editor_button()
    {
        return [
            "group" => "advanced_fields",

            "text" => $this->get_form_editor_field_title(),
        ];
    }
    /**
	 * The settings which should be available on the field in the form editor.
	 * @return array
	 */
    function get_form_editor_field_settings()
    {
        return [
            "label_setting",

            "description_setting",

            "rules_setting",

            "placeholder_setting",

            "input_class_setting",

            "css_class_setting",

            "size_setting",

            "admin_label_setting",

            "default_value_setting",

            "visibility_setting",

            "conditional_logic_field_setting",

            "prepopulate_field_setting",

            "label_placement_setting",

            "error_message_setting",

            "autocomplete_setting",
        ];
    }

    /**
	 * Enable this field for use with conditional logic.
	 * @return bool
	 */
    public function is_conditional_logic_supported()
    {
        return true;
    }

    /**
	 * The scripts to be included in the form editor.
	 *
	 * @return string
	 */
    public function get_form_editor_inline_script_on_page_render()
    {
        // set the default field label for the simple type field

        $script =
            sprintf(
                "function SetDefaultValues_autocomplete(field) { field.label = '%s';}",
                $this->get_form_editor_field_title()
            ) . PHP_EOL;

        // initialize the fields custom settings

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var inputClass = field.inputClass == undefined ? '' : field.inputClass;" .
            "jQuery('#input_class_setting').val(inputClass);" .
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var suggest_word = field.suggest_word == undefined ? '' : field.suggest_word;" .
            "jQuery('#suggest_word').val(suggest_word);" .
            "var post_type = field.post_type == undefined ? 'post' : field.post_type;
            jQuery('#post_type').val(post_type);
            var post_field = field.post_field == undefined ? 'post_title' : field.post_field;
            jQuery('#post_field').val(post_field);".
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var suggest_sql_tableName = field.suggest_sql_tableName == undefined ? '' : field.suggest_sql_tableName;" .
            "jQuery('#suggest_sql_tableName').val(suggest_sql_tableName);" .
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var suggest_sql_columnName = field.suggest_sql_columnName == undefined ? '' : field.suggest_sql_columnName;" .
            "jQuery('#suggest_sql_columnName').val(suggest_sql_columnName);" .
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var suggest_sql_columnName = field.suggest_sql_columnName == undefined ? '' : field.suggest_sql_columnName;" .
            "jQuery('#suggest_sql_columnName').val(suggest_sql_columnName);" .
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "if(field.my_la == '' || field.my_la == undefined){SetFieldProperty('my_la', 'word');}else{return;}" .
            "});" .
            PHP_EOL;

        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
                "var type = field.my_la == undefined ? 'word' : field.my_la;
                jQuery('#my_la').val(type);" .
                "if(type == 'word') {
                    jQuery('#by_input_word').attr('checked',true);
                    jQuery('.input_word').css({'display':'block'});
                    jQuery('.file_input').css({'display':'none'});
                    jQuery('.input_sql').css({'display':'none'});
                    jQuery('.input_post').css({'display':'none'});
                }" .
                "if(type == 'file'){
                    jQuery('#by_file_given').attr('checked',true);
                    jQuery('.file_input').css({'display':'block'});
                    jQuery('.input_word').css({'display':'none'});
                    jQuery('.input_sql').css({'display':'none'});
                    jQuery('.input_post').css({'display':'none'});
                }" .
                "if(type == 'sql'){
                    jQuery('#by_input_sql').attr('checked',true);
                    jQuery('.file_input').css({'display':'none'});
                    jQuery('.input_word').css({'display':'none'});
                    jQuery('.input_sql').css({'display':'block'});
                    jQuery('.input_post').css({'display':'none'});
                }" .
                "if(type == 'post'){
                    jQuery('#by_post_type').attr('checked',true);
                    jQuery('.file_input').css({'display':'none'});
                    jQuery('.input_word').css({'display':'none'});
                    jQuery('.input_sql').css({'display':'none'});
                    jQuery('.input_post').css({'display':'block'});
                }" .
            "});" .
            PHP_EOL;
        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var name_file = field.url_file == undefined ? '' : field.url_file;" .
            "jQuery('#curren_file_name').val(name_file);" .
            "});" .
            PHP_EOL;
        $script .=
            "jQuery(document).bind('gform_load_field_settings', function (event, field, form) {" .
            "var name = field.file_name == undefined  ? ' ' : field.file_name;" .
            "jQuery('#name').val(name);" .
            "});" .
            PHP_EOL;
        // saving the simple setting
        $script .=
            "function SetInputClassSetting(value) {SetFieldProperty('inputClass', value);}" .
            PHP_EOL;
        return $script;
    }

    // public function get_form_inline_script_on_page_render($form)
    //  {
    //     $enter_other_value = isset($this->enterOtherValueOption) ? ($this->enterOtherValueOption == false ? "1" : "0") : "1";

    //     global $wpdb;

    //     $jsonFields = [];

    //     $jsonFields["limit"] = empty($this->record_limit_custField)
    //         ? 20
    //         : $this->record_limit_custField;

    //     $jsonFields["minimum"] = empty($this->minimum_input_letters_custField)
    //         ? 1
    //         : $this->minimum_input_letters_custField;

    //     if ($this->my_la == "word") {
    //         $su1 = $this->suggest_word;

    //         $su2 = str_replace("", "", $su1);

    //         $su = explode(",", $su2);

    //         $jsonFields["data"] = $su;
    //     }

    //     if ($this->my_la == "file" && !empty($this->url_file)) {
    //         $url_file = $this->url_file;

    //         $arrContextOptions = [
    //             "ssl" => [
    //                 "verify_peer" => false,

    //                 "verify_peer_name" => false,
    //             ],
    //         ];

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

    //         $data = json_decode($json, true);

    //         $jsonFields["data"] = $data;
    //     }

    //     if ($this->my_la == "sql") {
    //         $tableName = $this->suggest_sql_tableName;

    //         $columnName = $this->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 = [];

    //             if (count($results) != 0) {
    //                 foreach ($results as $val) {
    //                     array_push($data, $val[$columnName]);
    //                 }
    //             }

    //             $jsonFields["data"] = $data;

    //             // print_r($data);

    //             // die();
    //         }
    //     }

    //     $script = "
    //     if(typeof window.autocompleteDataJson == 'undefined'){
	// 		window.autocompleteDataJson = {};
	// 	}
    //     if(typeof window.autocompleteDataJson[".$form["id"]."] == 'undefined'){
    //     window.autocompleteDataJson[".$form["id"]."] = {};
    //     }
    //     window.autocompleteDataJson[".$form["id"]."][".$this->id ."] = JSON.parse('" .addslashes(json_encode($jsonFields)) ."');

    //     var form_id = " .$form["id"] .";
    //     var field_id = " .$this->id .";
    //     var autocompletField = window.autocompleteDataJson[" .$form["id"] ."];
    //     function split(val) {
    //         return val.split(/,\s*/);
    //     }

    //     function extractLast(term) {
    //         return split(term).pop();
    //     }
    //     jQuery('#field_" .$form["id"] ."_" .$this->id ." .ginput_container_autocomplete').append('<span class=' + 'bb_check_error' + ' style=' + 'display:none;color:red;' + '>Minimum ' + autocompletField[" . $this->id ."]['minimum'] + ' letters required</span>');
    //     jQuery('#field_" .$form["id"] ."_" .$this->id ." .ginput_container_autocomplete').append('<span class=' + 'dosan_check_error" .$this->id ."' + ' style=' + 'display:none;color:red;padding-top:10px;' + '>Please enter a valid value.</span>');
    //     let vqh_checkDisableLoading" .$this->id ." = false;
    //     jQuery(document).on('keyup', '#input_" .$form["id"] ."_" .$this->id ."',function(event) {
    //         if(jQuery( '#input_" .$form["id"] ."_" .$this->id ."' ).val().length < 0 || jQuery( '#input_" .$form["id"] ."_" .$this->id ."' ).val().length < autocompletField[" .$this->id ."]['minimum']){
    //             jQuery( '#field_" .$form["id"] ."_" .$this->id ." .ginput_container_autocomplete .bb_check_error' ).show();
    //         }else{
    //             if(vqh_checkDisableLoading" .$this->id ." == false){
    //                 jQuery('#input_" .$form["id"] ."_" .$this->id ."').addClass('ui-autocomplete-loading');
    //             }
    //             jQuery( '#field_" .$form["id"] ."_" .$this->id ." .ginput_container_autocomplete .bb_check_error' ).hide();
    //         }
    //         jQuery( '#input_" .$form["id"] ."_" .$this->id ." ').on( 'keydown', function( event ) {
    //             if ( event.keyCode === jQuery.ui.keyCode.TAB && jQuery( this ).autocomplete( 'instance' ).menu.active ) {
    //                 event.preventDefault();
    //             }
    //         });
    //         if(jQuery( '#input_" .$form["id"] ."_" .$this->id ." ').val().length == 0){
    //             jQuery( '#field_" .$form["id"] ."_" .$this->id ." .ginput_container_autocomplete .bb_check_error' ).hide();
    //             jQuery( '#input_" .$form["id"] ."_" . $this->id ." ' ).removeClass('ui-autocomplete-loading');
    //         }
    //         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;
    //             }
    //         });
    //     });
    //     jQuery(document).on('keypress', '#input_" . $form["id"] . "_" .$this->id ."',function(event) {
    //         jQuery('.dosan_check_error" .$this->id ."').css('display','none');
    //         if(" .$enter_other_value ." == 1){
    //             let arr_data_suggestion = autocompletField[" .$this->id ."]['data']
    //             if( typeof autocompletField[" .$this->id ."]['data'] == 'object'){
    //                 arr_data_suggestion = Object.values(autocompletField[" . $this->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) {
    //                 jQuery('.dosan_check_error" .$this->id ."').css('display','block');
    //                 jQuery( '#input_" .$form["id"] ."_" .$this->id ." ' ).removeClass('ui-autocomplete-loading');
    //                 vqh_checkDisableLoading" .$this->id ." = true;
    //                 event.preventDefault();
    //             }else{	
    //                 vqh_checkDisableLoading" .$this->id ." = false;
    //             }

    //             if (arr_data_suggestion.indexOf(event.target.value) != -1 ) {
    //                 jQuery( '#input_" .$form["id"] ."_" .$this->id ." ' ).removeClass('ui-autocomplete-loading');
    //                 vqh_checkDisableLoading" .$this->id ." = true;
    //                 event.preventDefault();
    //             }else{
    //                 vqh_checkDisableLoading" .$this->id ." = false;
    //             }
    //         }
    //         jQuery( '#input_" .$form["id"] ."_" .$this->id . " ').autocomplete({
    //             minLength: autocompletField[" .$this->id . "]['minimum'],
    //             source: function( request, response ) {
    //                 let objToArrayDosan = autocompletField[" .$this->id ."]['data']
    //                 if( typeof autocompletField[" .$this->id ."]['data'] == 'object'){
    //                     objToArrayDosan = Object.values(autocompletField[" .$this->id ."]['data']);
    //                 }
    //                 var results = jQuery.ui.autocomplete.filter(
    //                     objToArrayDosan, extractLast( request.term ) );
    //                     response(results.slice(0, autocompletField[" . $this->id ."]['limit']));
    //             },
    //         });
    //     });";

    //     return $script;
    // }

    /**
	 * Define the fields inner markup.
	 *
	 * @param array $form The Form Object currently being processed.
	 * @param string|array $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
	 * @param null|array $entry Null or the Entry Object currently being edited.
	 * @return string
	 */
    public function get_field_input($form, $value = "", $entry = null)
    {
        // print_r($this);
        // die();
        $id = absint($this->id);

        $form_id = absint($form["id"]);

        $is_entry_detail = $this->is_entry_detail();

        $is_form_editor = $this->is_form_editor();

        // Prepare the value of the input ID attribute.

        $field_id =
            $is_entry_detail || $is_form_editor || $form_id == 0
                ? "input_$id"
                : "input_" . $form_id . "_$id";

        $value = esc_attr($value);

        // Get the value of the inputClass property for the current field.

        $inputClass = $this->inputClass;

        // Prepare the input classes.

        $size = $this->size;

        $class_suffix = $is_entry_detail ? "_admin" : "";

        $class = $size . $class_suffix . " " . $inputClass;

        // Prepare the other input attributes.

        $tabindex = $this->get_tabindex();

        $logic_event = version_compare(GFForms::$version, "2.4-beta-1", "<")
            ? $this->get_conditional_logic_event("keyup")
            : "";

        $placeholder_attribute = $this->get_field_placeholder_attribute();

        $required_attribute = $this->isRequired ? 'aria-required="true"' : "";

        $invalid_attribute = $this->failed_validation
            ? 'aria-invalid="true"'
            : 'aria-invalid="false"';

        $disabled_text = $is_form_editor ? 'disabled="disabled"' : "";

        if ($this->my_la == "word") {
            $input = "<input name='input_{$id}' id='{$field_id}' type='text' value='{$value}' class='{$class}' {$tabindex} {$logic_event} {$placeholder_attribute} {$required_attribute} {$invalid_attribute} autocomplete='off' {$disabled_text}/>";
        } else {
            if ($this->url_file == "") {
                # code...

                // echo "khong co url";

                // $data2='';

                $input = "<input name='input_{$id}' id='{$field_id}' type='text' value='{$value}' class='{$class} hung_auto' {$tabindex} {$logic_event} {$placeholder_attribute} {$required_attribute} {$invalid_attribute} autocomplete='off' {$disabled_text}/>";
            } else {
                //

                $input = "<input name='input_{$id}' id='{$field_id}' type='text' value='{$value}' class='{$class} hung_auto' {$tabindex} {$logic_event} {$placeholder_attribute} {$required_attribute} {$invalid_attribute} {$disabled_text}  autocomplete='off' />";
            }
        }
        // var_dump($this);
        return sprintf(
            "<div class='ginput_container ginput_container_%s'>%s</div>",
            $this->type,
            $input
        );
    }
}
GF_Fields::register(new Autocomplete_GF_Field());
