<?php

$trackinginfo;

$revision = 1;
if (!empty($VARS["revision"]) && preg_match("/[0-9]/", $VARS["revision"])) {
    $revision = $VARS["revision"];
}

$code = urldecode($VARS["code"]);
$carrier = "";
if (!empty($VARS["carrier"])) {
    $carrier = $VARS["carrier"];
}

// Check if code starts with carrier name and colon
if ($carrier == "") {
    $codeparts = explode(":", $code);
    if (count($codeparts) == 2) {
        switch (strtoupper(trim($codeparts[0]))) {
            case "FEDEX":
                $carrier = "fedex";
                break;
            case "UPS":
                $carrier = "ups";
                break;
            case "USPS":
                $carrier = "usps";
                break;
        }
        if ($carrier != "") {
            $code = trim($codeparts[1]);
        }
    }
}

function downgradeResponseVersion($data, int $version) {
    switch ($version) {
        case 2:
            return $data;
        case 1:
            // No "INFO" status type in first version
            if (!empty($data["current"]["status"]) && $data["current"]["status"] == "INFO") {
                $data["current"]["status"] = "TRANSIT";
            }
            if (!empty($data["history"])) {
                for ($i = 0; $i < count($data["history"]); $i++) {
                    if ($data["history"][$i]["status"] == "INFO") {
                        $data["history"][$i]["status"] = "TRANSIT";
                    }
                }
            }
            return $data;
    }
}

try {
    $cacheresp = $memcache->get("logistics.tracking.$code.$carrier");
    if ($cacheresp !== false && empty($VARS["nocache"])) {
        exitWithJson(downgradeResponseVersion(json_decode($cacheresp, true), $revision));
    }

    $trackinginfo = Tracking::track($code, $carrier);
} catch (TrackingException $ex) {
    if (env("debugmode", false)) {
        echo $ex->getTraceAsString();
    }
    $output = [
        "status" => "ERROR",
        "msg" => $ex->getMessage()
    ];
    \Sentry\captureException($ex);
    $memcache->set("logistics.tracking.$code.$carrier", json_encode($output), 60 * 10);
    exitWithJson(downgradeResponseVersion($output, $revision));
}

if (is_null($trackinginfo)) {
    sendJsonResp("Could not find any results for that tracking code.", "ERROR");
}

$output = $trackinginfo->toObject();
$memcache->set("logistics.tracking.$code.$carrier", json_encode($output), 60 * 60);
exitWithJson($output);
