<?php

namespace GriffinForms\Admin\Ajax;

class Field extends \GriffinForms\Admin\Ajax\Format
{   
    public function dbTableList()
    {
        $nonce_status = isset($_POST['nonce']) ? wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'db_table_list') : false;
        if ($nonce_status != false) {
            $table_list = $this->sql->getDbTableList();
            echo esc_html(implode(",", $table_list));
        } else {
            echo 'nonce_error';
            wp_die();
        }
        
        wp_die();
    }    
    
    public function dbColumnList()
    {
        $nonce_status = isset($_POST['nonce']) ? wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'db_column_list') : false;
        
        if ($nonce_status != false) {
            // Check if 'table' is set
            if (!isset($_POST['table'])) {
                echo 'table_error';
                wp_die();
            }

            $this->sql->table = sanitize_text_field(wp_unslash($_POST['table']));
            $columns = $this->sql->getColumns();
            $list = '';
            foreach($columns as $name => $value) {
                $list .= $value['Field'] . ',';
            }
            echo wp_kses_post($list);
        } else {
            echo 'nonce_error';
            wp_die();
        }
        
        wp_die();
    }
    
    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_dbTableList', array($this, 'dbTableList'));
        add_action('wp_ajax_dbColumnList', array($this, 'dbColumnList'));
    }
}