<?php

if (!defined('ABSPATH')) {
    exit;
}

if (!class_exists('ReonAjax')) {

    class ReonAjax {

        public static function init() {
            self::add_action('rn_get_data_list_ajax', array(new self(), 'get_data_list_ajax'));
        }

        public static function add_action($action_name, $function, $add_non_priv = false) {
            add_action('wp_ajax_' . $action_name, $function);
            if ($add_non_priv === true) {
                add_action('wp_ajax_nopriv_' . $action_name, $function);
            }
        }

        public static function get_data_list_ajax() {
            $result = array();
            ob_start();
            $data_args = array(
                'source' => sanitize_text_field($_POST['ajaxsource']),
                'pagesize' => 50,
            );

            if (isset($_POST['term']) && $_POST['term'] != '') {
                $data_args['search_term'] = sanitize_text_field($_POST['term']);
            }
            
            if (isset($_POST['pagesize']) && $_POST['pagesize'] != '') {
                $data_args['pagesize'] = sanitize_text_field($_POST['pagesize']);
            }

            if (isset($_POST['ajaxsource_show_value']) && $_POST['ajaxsource_show_value'] != '') {
                $data_args['show_value'] = $_POST['ajaxsource_show_value'] == 'true';
            }

            if (isset($_POST['ajaxsource_value_col']) && $_POST['ajaxsource_value_col'] != '') {
                $data_args['value_col'] = sanitize_text_field($_POST['ajaxsource_value_col']);
            }

            if (isset($_POST['ajaxsource_value_col_pre']) && $_POST['ajaxsource_value_col_pre'] != '') {
                $data_args['value_col_pre'] = sanitize_text_field($_POST['ajaxsource_value_col_pre']);
            }


            $dt = array();
            ob_clean();

            foreach (ReonApi::get_data_list($data_args, array()) as $key => $value) {
                $dt[] = array(
                    'id' => $key,
                    'text' => $value,
//                    'children' => array(
//                        array(
//                            'id' => 1,
//                            'text' => 'Item One',
//                        ), array(
//                             'id' => 2,
//                            'text' => 'Item Two',
//                        )
//                    )
                );
            }


            $result['results'] = $dt;

            header("Access-Control-Allow-Origin: *");
            header("Content-Type: application/json; charset=UTF-8");
            echo json_encode($result);
            wp_die();
        }

    }

}
