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

require_once __DIR__ . "/../lib/required_public.php";

header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

$publicsettings = json_decode(file_get_contents(__DIR__ . "/../custom/public.json"), true);

function sendResp($msg, $status = "ERROR") {
    exit(json_encode(["status" => $status, "msg" => $msg]));
}

function sendData($info, $events = [], $components = []) {
    exit(json_encode(["status" => "OK", "info" => $info, "events" => $events, "components" => $components]));
}
if (empty($_GET["id"])) {
    sendResp('No ID or tracking number entered.');
}
$ID = $_GET["id"];

if (!empty($ID) && strpos($ID, "68") === 0 && !CheckDigit::validateS10($ID)) {
    sendResp($ID . ' is not valid. Please try re-typing it.');
} else if (!Machine::exists($ID) && !Machine::serialExists($ID) && !Component::exists($ID)) {
    // try package tracking query
    $trackingok = false;
    if (preg_match("/^[a-z0-9]{10,}$/", $ID)) {
        $trkresp = json_decode(file_get_contents("https://apis.netsyms.net/packagehelper/track.php?code=$ID"), true);

        if ($trkresp["status"] == "OK" && $trkresp["current"]["status"] != "UNKNOWN" && $trkresp["service"]["id"] != null) {

            $trackingok = true;

            function trackingStatusToNiceString($status) {
                switch ($status) {
                    case "UNKNOWN":
                        return "Unknown";
                    case "PRE_TRANSIT":
                        return "Pre-transit";
                    case "TRANSIT":
                        return "In Transit";
                    case "DELIVERED":
                        return "Delivered";
                    case "RETURNED":
                        return "Returned";
                    case "FAILURE":
                        return "Failure";
                    default:
                        return $status;
                }
            }

            $events = [];
            $info = [
                "Tracking code" => $trkresp["code"],
                "Current status" => trackingStatusToNiceString($trkresp["current"]["status"]) . ": " . $trkresp["current"]["details"],
                "Last updated" => date($SETTINGS["datetime_format"], $trkresp["current"]["date"]),
                "Last location" => implode(" ", $trkresp["current"]["location"]),
                "Carrier" => $trkresp["carrier"]["name"]
            ];

            foreach ($trkresp["history"] as $his) {
                $events[] = [
                    "title" => trackingStatusToNiceString($his["status"]),
                    "details" => $his["details"] . "\n" . implode(" ", $his["location"]),
                    "date" => date($SETTINGS["datetime_format"], $his["date"])
                ];
            }

            sendData($info, $events);
        }
    }
    sendResp($ID . ' could not be found.');
} else {
    if (Component::exists($ID)) {
        $component = new Component($ID);
        $mid = $component->getMachineID();
        if (!empty($mid) && Machine::exists($mid)) {
            $machine = new Machine($mid);
        } else {
            // component exists but isn't attached to a machine
            sendResp($ID . ' exists as a component in our inventory system but is not assigned to a device.');
        }
    } else {
        if (Machine::exists($ID)) {
            $machine = new Machine($ID);
        } else {
            $machine = new Machine(Machine::getIDFromSerial($ID));
        }

        $info = [
            "ID" => $machine->getID()
        ];

        if (!empty($machine->getOS())) {
            $info["OS"] = $machine->getOS();
        }
        if (!empty($machine->getManufacturer())) {
            $info["Manufacturer"] = $machine->getManufacturer();
        }
        if (!empty($machine->getModel())) {
            $info["Model"] = $machine->getModel();
        }
        if (!empty($machine->getSerial())) {
            $info["Serial"] = $machine->getSerial();
        }
        if (!empty($machine->getPrice())) {
            $info["Price"] = "$" . number_format($machine->getPrice(), 2);
        }
        if (!empty($machine->getPublicNotes())) {
            $info["Notes"] = $machine->getPublicNotes();
        }



        $events = [];
        $components = [];

        foreach ($machine->getEvents() as $evt) {
            $events[] = [
                "title" => $evt->getName(),
                "details" => $evt->getPublicNotes(),
                "date" => date($SETTINGS["datetime_format"], strtotime($evt->getDate()))
            ];
        }

        foreach ($machine->getComponents() as $comp) {
            $compdata = [];
            if (!empty($comp->getModel())) {
                $compdata["Model"] = $comp->getModel();
            }
            if (!empty($comp->getCapacity())) {
                $compdata["Capacity"] = $comp->getCapacity();
            }
            if (!empty($comp->getSerial())) {
                $compdata["Serial"] = $comp->getSerial();
            }
            if (!empty($comp->getPrice())) {
                $compdata["Price"] = "$" . number_format($comp->getPrice(), 2);
            }
            if (!empty($comp->getPublicNotes())) {
                $compdata["Notes"] = $comp->getPublicNotes();
            }
            $components[] = $compdata;
        }

        sendData($info, $events, $components);
    }
}