<?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 Event implements JsonSerializable {

    private $id = "";
    private $event = [];
    private $exists = false;

    public function __construct($eventid) {
        global $database;
        $this->id = $eventid;
        if (\Event::exists($eventid)) {
            $this->exists = true;
            $this->event = $database->get('events', ['machineid', 'eventid', 'techuid', 'date', 'privatenotes', 'publicnotes'], ['historyid' => $eventid]);
        }
    }

    public static function create(string $machineid = "", string $date = "", int $event = 0, string $techuid = "", string $publicnotes = "", string $privatenotes = ""): Event {
        if ($machineid == "" || $date == "" || $event == 0) {
            return new Event("");
        } else {
            if (!Machine::exists($machineid)) {
                throw new Exception("Invalid machine ID $machineid");
            }
            if (strtotime($date) === false) {
                throw new Exception("Invalid date.");
            }
            $date = date("Y-m-d H:i:s", strtotime($date));
            if (!array_key_exists($event, \Event::getTypes())) {
                throw new Exception("Invalid event type.");
            }
            $evt = new Event("");

            $evt->setMachineID($machineid);
            $evt->setTypeID($event);
            $evt->setDate($date);
            $evt->setTechUID($techuid);
            $evt->setPrivateNotes($privatenotes);
            $evt->setPublicNotes($publicnotes);
            $evt->save();

            return $evt;
        }
    }

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

    public static function getTypes() {
        global $database;
        $types = $database->select("event_types", ["eventid (id)", "eventname (name)"]);

        $list = [];
        foreach ($types as $t) {
            $list[$t['id']] = $t['name'];
        }
        return $list;
    }

    public function toArray() {
        global $Strings;
        if ($this->exists) {
            return [
                "info" => [
                    "id" => $this->getID(),
                    "machineid" => $this->getMachineID(),
                    "type" => $this->getTypeID(),
                    "date" => $this->getDate(),
                    "techuid" => $this->getTechUID(),
                    "publicnotes" => $this->getPublicNotes(),
                    "privatenotes" => $this->getPrivateNotes()
                ],
                "formdata" => [
                    "types" => $this->getTypes(),
                    "inputtypes" => [
                        "machineid" => "text",
                        "type" => "number",
                        "date" => "datetime",
                        "techuid" => "text",
                        "privatenotes" => "textarea",
                        "publicnotes" => "textarea"
                    ],
                    "labels" => [
                        "machineid" => $Strings->get("Machine ID", false),
                        "type" => $Strings->get("Type", false),
                        "date" => $Strings->get("Date", false),
                        "techuid" => $Strings->get("Technician", false),
                        "privatenotes" => $Strings->get("Private Notes", false),
                        "publicnotes" => $Strings->get("Public Notes", false)
                    ],
                    "icons" => []
                ]
            ];
        }
        return [];
    }

    public function jsonSerialize() {
        return $this->toArray();
    }

    public function save() {
        global $database;
        if ($this->exists) {
            $database->update("events", $this->event, ["historyid" => $this->id]);
        } else {
            $database->insert("events", $this->event);
            $this->id = $database->id();
            $this->exists = true;
        }
    }

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

    public function getMachineID(): string {
        if (!empty($this->event["machineid"])) {
            return $this->event["machineid"];
        }
        return "";
    }

    public function getTypeID(): int {
        if (!empty($this->event["eventid"])) {
            return $this->event["eventid"] * 1;
        }
        return 0;
    }

    public function getName(): string {
        return $this->getTypes()[$this->getTypeID()] ?? "";
    }

    public function getDate(): string {
        if (!empty($this->event["date"])) {
            return $this->event["date"];
        }
        return "";
    }

    public function getTechUID(): string {
        if (!empty($this->event["techuid"])) {
            return $this->event["techuid"];
        }
        return "";
    }

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

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

    public function setMachineID($id) {
        $this->event["machineid"] = $id;
    }

    public function setTypeID(int $id) {
        if (!empty($this->getTypes()[$id])) {
            $this->event["eventid"] = $id;
        }
    }

    public function setTechUID($uid) {
        $this->event["techuid"] = $uid;
    }

    public function setDate(string $date) {
        $this->event["date"] = date("Y-m-d H:i:s", strtotime($date));
    }

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

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

}
