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

class Machine {

    private $machineid = "";
    private $machine = [];
    private $events = [];
    private $components = [];
    private $exists = false;

    public function __construct($machineid) {
        global $database;
        $this->machineid = $machineid;
        if (Machine::exists($machineid)) {
            $this->exists = true;
            $this->machine = $database->get('machines', ['model', 'condition', 'price', 'os', 'serial', 'manufacturer', 'clientid', 'privatenotes', 'publicnotes'], ['machineid' => $machineid]);
            $this->events = $database->select('events', ['[>]event_types' => 'eventid'], ['historyid', 'date', 'event_types.eventname', 'techuid', 'privatenotes', 'publicnotes'], ['machineid' => $machineid, "ORDER" => ["date" => "DESC"]]);
            $components = $database->select("components", "compid", ["machineid" => $machineid]);
            foreach ($components as $c) {
                $this->components[] = new Component($c);
            }
        }
    }

    public static function create(): Machine {
        return new Machine(Machine::generateId());
    }

    public static function exists($id): bool {
        global $database;
        return $database->has('machines', ['machineid' => $id]);
    }

    /**
     * Check if a given serial number can identify exactly one machine.
     * @global $database $database
     * @param type $serial
     * @return bool
     */
    public static function serialExists(string $serial): bool {
        global $database;
        return $database->has('machines', ['serial' => $serial]) && $database->count('machines', ['serial' => $serial]) == 1;
    }

    /**
     * Convert a serial into a machine ID.
     * @global $database $database
     * @param string $serial
     * @return string|bool machine ID if found, otherwise false.
     */
    public static function getIDFromSerial(string $serial) {
        global $database;
        if (Machine::serialExists($serial)) {
            return $database->get('machines', 'machineid', ['serial' => $serial]) . "";
        }
        return false;
    }

    public function save() {
        global $database;
        if ($this->exists) {
            $database->update("machines", $this->machine, ["machineid" => $this->machineid]);
        } else {
            $data = $this->machine;
            $data["machineid"] = $this->machineid;
            $database->insert("machines", $data);
            $this->exists = true;
        }
    }

    public function getID(): string {
        return $this->machineid . "";
    }

    public function getClientID() {
        if (!empty($this->machine["clientid"])) {
            return $this->machine["clientid"];
        }
        return "";
    }

    public function getModel(): string {
        if (!empty($this->machine["model"])) {
            return $this->machine["model"];
        }
        return "";
    }

    public function getCondition(): float {
        if (!empty($this->machine["condition"])) {
            return $this->machine["condition"] * 1.0;
        }
        return 0.0;
    }

    public function getPrice(): float {
        if (!empty($this->machine["price"])) {
            return $this->machine["price"] * 1.0;
        }
        return 0.0;
    }

    public function getOS(): string {
        if (!empty($this->machine["os"])) {
            return $this->machine["os"];
        }
        return "";
    }

    public function getSerial(): string {
        if (!empty($this->machine["serial"])) {
            return $this->machine["serial"];
        }
        return "";
    }

    public function getManufacturer(): string {
        if (!empty($this->machine["manufacturer"])) {
            return $this->machine["manufacturer"];
        }
        return "";
    }

    public function getPublicNotes(): string {
        if (!empty($this->machine["publicnotes"])) {
            return $this->machine["publicnotes"];
        }
        return "";
    }

    public function getPrivateNotes(): string {
        if (!empty($this->machine["privatenotes"])) {
            return $this->machine["privatenotes"];
        }
        return "";
    }

    public function getEvents() {
        return $this->events;
    }

    public function setClientID($id) {
        $this->machine["clientid"] = $id;
    }

    public function setModel(string $model) {
        $this->machine["model"] = $model;
    }

    public function setCondition(float $condition) {
        if ($condition < 0) {
            $condition = 0;
        }
        if ($condition > 10) {
            $condition = 10;
        }
        $condition = round($condition);
        $this->machine["condition"] = $condition;
    }

    public function setPrice(float $price) {
        $this->machine["price"] = $price;
    }

    public function setOS(string $os) {
        $this->machine["os"] = $os;
    }

    public function setSerial(string $serial) {
        $this->machine["serial"] = $serial;
    }

    public function setManufacturer(string $manufacturer) {
        $this->machine["manufacturer"] = $manufacturer;
    }

    public function setPrivateNotes(string $notes) {
        $this->machine["privatenotes"] = $notes;
    }

    public function setPublicNotes(string $notes) {
        $this->machine["publicnotes"] = $notes;
    }

    public function getComponents(): array {
        return $this->components;
    }

    public function addEvent(string $date, int $event, string $techuid = "", string $publicnotes = "", string $privatenotes = "") {
        global $database;
        if (strtotime($date) === false) {
            throw new Exception("Invalid date.");
        }
        $date = date("Y-m-d H:i:s", strtotime($date));
        if (!$database->has('event_types', ['eventid' => $event])) {
            throw new Exception("Invalid event type.");
        }
        $event = (int) $event;
        if (empty($publicnotes)) {
            $publicnotes = "";
        }
        if (empty($privatenotes)) {
            $privatenotes = "";
        }
        $database->insert('events', ['date' => $date, 'eventid' => $event, 'techuid' => $techuid, 'machineid' => $this->machineid, 'publicnotes' => $publicnotes, 'privatenotes' => $privatenotes]);
    }

    /**
     * Generate a random machine ID number that is not in use.
     * @global $database
     * @param int $min Optional minimum number.
     * @param int $max Optional maximum number.
     * @return int
     */
    public static function generateId(int $min = 1000000000, int $max = 9999999999): int {
        global $database;

        $id = random_int(1000000000, 9999999999);;

        do {
            $id = random_int(1000000000, 9999999999);
        } while ($database->has('machines', ['machineid' => $id]) || $database->has('components', ['compid' => $id]));

        return $id;
    }

}
