<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/conf.php');
session_start();

if (!auth_is_login()) {
    redirect('/');
}

if (session("groups") !== "admin") {
    send_json(message_error("Недостаточно прав доступа"));
    redirect('/');
}

$search = escape(post('term'));
$search = htmlspecialchars($search);

if ($search && strlen($search) >= 3) {
    $sql = 'SELECT `login`, `password` FROM `users` WHERE `login` LIKE '.escape_db('%'.$search.'%');
    $res = $mysqli->query($sql);

    if ($result) {
        while ($row = $res->fetch_assoc()) {
            $list[] = $row;
        }
    } else {
        mysqli_error_log($mysqli, $sql);
    }

    if (!empty($list)) {
        $res = [];

        foreach ($list as $item) {
            $user['id'] = $item['login'];
            $user['text'] = $item['login'];
            if ($item['password'] === 'fakefake') {
                $user['text'] = 'fake | ' . $user['text'];
            }
            $user['text'] .= ' ('.format_currency(login_sum_balans($item['login']), $val)." ".escape($val).')';

            $res[] = $user;
        }

        $results['results'] = $res;

        send_json($results);
    }
}
