<?php

defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('CIWS_Account_Ajax')) {
    class CIWS_Account_Ajax
    {
        function __construct()
        {

            add_action('wp_ajax_search_accounts', [$this, 'ciws_search_accounts']);
        }

        function ciws_search_accounts()
        {
            global $wpdb;
            $search_term = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';

            global $wpdb;

            $table_name = esc_sql(CIWS_TABLE); // Make sure it's sanitized

            $like = '%' . $wpdb->esc_like($search_term) . '%';

            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "
                    SELECT DISTINCT account_id, account_name
                    FROM {$table_name}
                    WHERE account_name LIKE %s
                    ORDER BY account_id DESC
                    ",
                    $like
                )
            );


            wp_send_json_success($results);
        }
    }

    new CIWS_Account_Ajax();
}
