<?php

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

redirectIfNotLoggedIn();
$user = new User($_SESSION['uid']);
if (!$user->hasPermission("MACHINEMANAGER_EDIT")) {
    header("Location: ./app.php?msg=no_permission");
    die();
}

$editing = false;

if (!empty($_GET['arg']) && Machine::exists($_GET['arg'])) {
    $editing = true;
    $machine = new Machine($_GET['arg']);
} else {
    $machine = Machine::create();
}

if ($editing) {
    $form = new FormBuilder("Edit " . $machine->getTypeLabel() . " #" . $machine->getID(), "fas fa-desktop", "action.php", "POST");
} else {
    $form = new FormBuilder("Add Machine", "fas fa-desktop", "action.php", "POST");
}

$form->setID("editmachine");

$form->addHiddenInput("action", "editmachine");
$form->addHiddenInput("source", "viewmachine");

$clients = [
    "" => ""
];
foreach (Clients::getAll() as $c) {
    $clients[$c->getID()] = $c->getName();
}
$typelist = [
    "" => ""
];
foreach ($database->select("machine_types", ["machinetypeid (id)", "typename (name)"]) as $t) {
    $typelist[$t["id"]] = $t["name"];
}

if ($editing) {
    $form->addHiddenInput("id", $machine->getID());
} else {
    $form->addInput("id", $machine->getID(), "text", true, null, null, "Machine ID", "fas fa-desktop", 4, 1, 20);
}
$form->addInput("type", $machine->getType(), "select", true, null, $typelist, "Machine Type", "fas fa-desktop");
$form->addInput("client", $machine->getClientID(), "select2", false, null, $clients, "Client", "fas fa-user");
$form->addInput("model", $machine->getModel(), "text", false, null, null, "Model", "fas fa-hashtag", 4, 0, 200);
$form->addInput("os", $machine->getOS(), "text", false, null, null, "OS/Software", "fas fa-hdd", 4, 0, 200);
$form->addInput("serial", $machine->getSerial(), "text", false, null, null, "Serial", "fas fa-barcode", 4, 0, 200);
$form->addInput("manufacturer", $machine->getManufacturer(), "text", false, null, null, "Manufacturer", "fas fa-industry", 4, 0, 200);
$form->addInput("condition", $machine->getCondition(), "number", false, null, null, "Condition", "fas fa-star-half-alt");
$form->addInput("price", $machine->getPrice(), "number", false, null, null, "Price", "fas fa-money-bill-wave");

$form->addInput("privatenotes", $machine->getPrivateNotes(), "textarea", false, null, null, "Private Notes", "fas fa-comment-dots", 6, 0, 10000);
$form->addInput("publicnotes", $machine->getPublicNotes(), "textarea", false, null, null, "Public Notes", "far fa-comment-dots", 6, 0, 10000);

$form->addButton("Save", "fas fa-save", null, "submit", "savebtn");

$form->generate();