<?php

namespace GriffinForms\Admin\Html\FormControls\Field;

use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputText;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputNumber;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputUrl;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputPhone;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputEmail;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputDate;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputCheckbox;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\TextArea;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputAddress;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputPassword;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\InputTime;
use GriffinForms\Admin\Html\FormControls\Field\ValidationTraits\Imageselection;

class Validations extends \GriffinForms\Admin\Html\FormControls\Field\Format
{
    use InputText;
    use InputNumber;
    use InputUrl;
    use InputEmail;
    use InputPhone;
    use InputDate;
    use InputCheckbox;
    use TextArea;
    use InputAddress;
    use InputPassword;
    use InputTime;
    use Imageselection;
    
    protected $choices;
	protected $secure;
	protected $value;
    protected $validation_type_options;
    protected $validation_type;
    protected $pattern;
    protected $table;
    protected $column;
    protected $match_type_options;
    protected $match_type;
	
	protected function setValue()
	{
		$this->value = $this->secure->data('validations', $this->value);
	}
	
    protected function setValidationTypeOptions()
    {
        $choices = $this->choices->getChoices('validation_types_' . $this->data['field_type']);
        $this->validation_type_options = is_array($choices) ? $choices : [];
    }
    
    protected function setValidationType()
    {
        $this->validation_type = $this->fixEmptyValue('type', '', $this->validation_type_options);
    }
    
    protected function setPattern()
    {
        $this->pattern = $this->fixEmptyValue('pattern', '');
    }
    
    protected function setTable()
    {
        $this->table = $this->fixEmptyValue('table', 'wp_users');
    }
    
    protected function setColumn()
    {
        $this->column = $this->fixEmptyValue('column', 'ID');
    }
    
    protected function setMatchTypeOptions()
    {
        $this->match_type_options = $this->choices->getChoices('match_type');
    }
    
    protected function setMatchType()
    {
        $this->match_type = $this->fixEmptyValue('match_type', '', $this->match_type_options);
    }
    
    protected function selectValidationType()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\SelectField($this->data['field_type'] . '_validation', $this->validation_type, '');
        $field->selectOptions($this->validation_type_options);
        $field->html();
    }
    
    protected function validationOptions()
    {
        $method = 'validationOptions' . $this->data['field_type'];
        $this->$method();
    }
    
    protected function validationOptionsSelectField()
    {
    }

    protected function validationOptionsInputRadio()
    {
    }

    protected function validationOptionsInputrichtext()
    {
    }

    protected function validationOptionsInputlikert()
    {
    }

    protected function validationOptionsSignature()
    {
    }

    protected function validationOptionsInputrating()
    {
        $min_rating = isset($this->value['validation_value']) ? floatval($this->value['validation_value']) : '';
        echo '<div class="col-md-12 gf-validation-options" id="gf-min-rating-wrap">';
        echo '<span class="me-2">' . esc_html($this->lang->getText('min_rating_label')) . '</span>';
        $field = new \GriffinForms\Admin\Html\FormControls\InputNumber('minrating', $min_rating === '' ? '' : $min_rating, '');
        $field->html();
        echo '</div>';
    }
    
    protected function patternField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('validation_pattern', $this->pattern, '');
        echo '<span class="me-2">' . esc_html($this->lang->getText($this->data['field_type'] . '_pattern')) . '</span>';
        echo '<span>';
        $field->html();
        echo '</span>';
        
    }
    
    //For db-validate
    
    protected function tableSelect()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('table_select', $this->table, '');
        $field->selectOptions(array());
        echo '<div class="mb-3 w-50">';
        echo '<span class="me-2">' . esc_html($this->lang->getText('select_table_label')) . '</span>';
        echo '<span>';
        $field->html();
        echo '</span>';
        echo '</div>';
        
    }
    
    protected function columnSelect()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('column_select', $this->column, '');
        $field->selectOptions(array());
        echo '<div class="spinner-border spinner-border-sm text-primary" id="column-select-spinner" role="status"></div>';
        echo '<div class="mb-3 w-50" id="column-select-wrap">';
        echo '<span class="me-2">' . esc_html($this->lang->getText('select_column_label')) . '</span>';
        echo '<span>';
        $field->html();
        echo '</span>';
        echo '</div>';
        
    }    
    
    protected function MatchType()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('db_match_type', $this->match_type, '');
        $field->selectOptions($this->match_type_options);
        echo '<div class="mt-2 w-50" id="match-type-wrap">';
        echo '<span class="me-2">' . esc_html($this->lang->getText('match_type')) . '</span>';
        echo '<span>';
        $field->html();
        echo '</span>';
        echo '</div>';
        
    }
    
    public function html()
    {
        echo '<div class="row mb-3" id="griffinforms-field-validations-db-wrapper">';
        echo '<div class="col-md-12 mb-3" id="validations-select-wrap">';
        $this->selectValidationType();
        echo '</div>';
        echo '<div class="col-md-12" id="validations-options-wrap">';
        $this->validationOptions();
        echo '</div></div>';
        
    }
    
    public function fieldJs()
    {
        ob_start();
        $this->commonJs();
    
        $method = $this->data['field_type'] . 'Js';
        if (method_exists($this, $method)) {
            $this->$method();
        }
    
        $js = ob_get_clean();
    
        wp_add_inline_script('griffinforms-global-js', $js);
    }
    
    public function commonJs()
    {
        $db_table_list_nonce = wp_create_nonce('db_table_list');
        $db_column_list_nonce = wp_create_nonce('db_column_list');
        ?>
        
            jQuery(document).ready(function($) {
                
                let validationSelectField = "#griffinforms-<?php echo esc_js($this->data['field_type']); ?>validation-selectfield";
                $(validationSelectField).change(fillTablesSelect);
                $("#griffinforms-tableselect-selectfield").change(fillColumnsSelect);
    
                fillTablesSelect();
            
                function fillTablesSelect() {
    
                    if ($(validationSelectField).val() === "db-validate") {
                    
                        let selectedTable = "<?php echo esc_js($this->table); ?>";
                    
                        $("#griffinforms-field-validations-db-wrapper").css("opacity", 0.5);
                        $("#griffinforms-tableselect-selectfield").prop("disabled", true);
                        $("#griffinforms-columnselect-selectfield").prop("disabled", true);
                    
                        const data = {
                            "action": "dbTableList",
                            "nonce": "<?php echo esc_js($db_table_list_nonce); ?>"
                        };
    
                        $.post(ajaxurl, data, function(response) {
                            if (response === 'table_error') {
                                alert('Error: Table data missing.');
                                $("#griffinforms-field-validations-db-wrapper").css("opacity", 1);
                                return;
                            }

                            let tableList = response.split(",");
                            let options = "";
                            
                            if ($.inArray(selectedTable, tableList) == -1) {
                                selectedTable = tableList[0];
                            }
                            
                            $.each(tableList, function (index, value) {
                                let option = "<option value=" + value + ">" + value + "</option>";
                                options = options.concat("", option);
                            });
                            
                            $("#griffinforms-tableselect-selectfield").html(options);
                            $("#griffinforms-tableselect-selectfield").val(selectedTable);
                            fillColumnsSelect(selectedTable);
                        });
                    }
                }
                
                $("#griffinforms-tableselect-selectfield").change(function () {
                    fillColumnsSelect($(this).val());
                });
                
                function fillColumnsSelect() {
                                        
                    let selectedTable = $("#griffinforms-tableselect-selectfield").val();
                    let selectedColumn = "<?php echo esc_js($this->column); ?>";
                    
                    $("#column-select-wrap").hide();
                    $("#column-select-spinner").show();
                    
                    const data = {
                        "action": "dbColumnList",
                        "table": selectedTable,
                        "nonce": "<?php echo esc_js($db_column_list_nonce); ?>"
                    };
                    
                    $.post(ajaxurl, data, function(response) {
                        if (response === 'nonce_error') {
                            alert('Error: Invalid or missing nonce.');
                            $("#griffinforms-field-validations-db-wrapper").css("opacity", 1);
                            return;
                        }
                        
                        let columnList = response.split(",");
                        let options = "";
                        
                        if ($.inArray(selectedColumn, columnList) == -1) {
                            selectedColumn = columnList[0];
                        }
                        
                        $.each(columnList, function (index, value) {
                            if (value != "") {
                                let option = "<option value=" + value + ">" + value + "</option>";
                                options = options.concat("", option);
                            }
                        });
                        
                        $("#griffinforms-columnselect-selectfield").html(options);
                        $("#griffinforms-columnselect-selectfield").val(selectedColumn);
                        $("#column-select-wrap").show();
                        
                        $("#column-select-spinner").hide();
                        $("#griffinforms-field-validations-db-wrapper").css("opacity", 1);
                        $("#griffinforms-tableselect-selectfield").prop("disabled", false);
                        $("#griffinforms-columnselect-selectfield").prop("disabled", false);
                    });
                }
            });
        <?php
    }
}
