<?php

/*
 * Copyright 2020 Netsyms Technologies.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/* Get list of machines owned by a clientid */
if ($VARS["action"] == "getclient") {
    $allclients = Clients::getAllAsIDNameArray();
    if (isset($allclients[$VARS["clientid"]]) && !empty($allclients[$VARS["clientid"]])) {
        $machinelist = $database->select("machines", ["machineid (id)"], ["AND" => ["clientid" => $VARS["clientid"], "deleted[!]" => true]]);

        $machines = [];
        foreach ($machinelist as $m) {
            $machines[] = (new Machine($m["id"]))->toArrayLite();
        }

        $client = Clients::getClient($VARS["clientid"])->toArray();

        exitWithJson([
            "status" => "OK",
            "client" => $client,
            "machines" => $machines
        ]);
    } else {
        sendJsonResp("Client ID not found.", "ERROR");
    }
} else if ($VARS["action"] == "getclients") {
    $allclients = Clients::getAllAsIDNameArray();
    exitWithJson([
        "status" => "OK",
        "clients" => $allclients
    ]);
} else if ($VARS["action"] == "searchclients") {
    $clients = Clients::search($VARS["q"]);
    exitWithJson([
        "status" => "OK",
        "q" => $VARS["q"],
        "count" => count($clients),
        "clients" => $clients
    ]);
}