<?php

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/EmptyPHP.php to edit this template
 */

class UPSAPIs {

    //const BASEURL = "https://wwwcie.ups.com";
    const BASEURL = "https://onlinetools.ups.com";

    public static function getBearerToken(bool $force = false): string {
        global $memcache;
        $clientid = env("ups_client_id");
        $clientsecret = env("ups_client_secret");

        if (!$force && $memcache->get("logistics.tracking.ups_bearer_token") != false) {
            return $memcache->get("logistics.tracking.ups_bearer_token");
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, static::BASEURL . "/security/v1/oauth/token");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: Basic ' . base64_encode("$clientid:$clientsecret")
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        $memcache->set("logistics.tracking.ups_bearer_token", $data["access_token"], ($data["expires_in"] * 1) - 120);
        return $data["access_token"];
    }

    public static function getAPIRequest($endpoint) {
        $headers = [
            "Authorization: Bearer " . UPSAPIs::getBearerToken(false),
            "transId: " . uniqid(),
            "transactionSrc: Netsyms"
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 45);
        curl_setopt($ch, CURLOPT_URL, static::BASEURL . "/api/$endpoint");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_ENCODING, "");
        $response = curl_exec($ch);

        return $response;
    }
}
