<?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/.
 */

if (!empty($VARS["id"])) {
    if (Machine::exists($VARS["id"])) {
        $machine = new Machine($VARS['id']);
    } else if (Machine::serialExists($VARS["id"])) {
        $machine = new Machine(Machine::getIDFromSerial($VARS['id']));
    } else {
        http_response_code(404);
        sendJsonResp("Requested ID does not exist.", "ERROR");
    }
} else {
    $machine = Machine::create();
}

$user = getRequestUser();


if ($VARS["action"] != "lookup" && $VARS["action"] != "getmachineformfields") {

    if (!$user->hasPermission("MACHINEMANAGER_EDIT")) {
        http_response_code(403);
        sendJsonResp("You don't have permission to edit.", "ERROR");
    }

    if (!empty($VARS["type"])) {
        $machine->setType($VARS['type']);
    }
    if (!empty($VARS["model"])) {
        $machine->setModel($VARS['model']);
    }
    if (!empty($VARS["clientid"])) {
        $machine->setClientID($VARS['clientid']);
    }
    if (!empty($VARS["os"])) {
        $machine->setOS($VARS['os']);
    }
    if (!empty($VARS["serial"])) {
        $machine->setSerial($VARS['serial']);
    }
    if (!empty($VARS["manufacturer"])) {
        $machine->setManufacturer($VARS['manufacturer']);
    }
    if (!empty($VARS["condition"])) {
        $machine->setCondition($VARS['condition']);
    }
    if (!empty($VARS["price"])) {
        $machine->setPrice($VARS['price']);
    }
    if (!empty($VARS["privatenotes"])) {
        $machine->setPrivateNotes($VARS['privatenotes']);
    }
    if (!empty($VARS["publicnotes"])) {
        $machine->setPublicNotes($VARS['publicnotes']);
    }

    $machine->save();
}

header("Content-Type: application/json");

$output = $machine->toArray();
$output["editable"] = $user->hasPermission("MACHINEMANAGER_EDIT");

exit(json_encode($output));
