<?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 USPSAPIs {

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

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

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.usps.com/oauth2/v3/token');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"client_id\": \"$clientid\", \"client_secret\": \"$clientsecret\", \"grant_type\": \"client_credentials\", \"scope\": \"addresses international-prices pickup tracking scan-forms locations prices\"}");
        $response = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($response, true);
        $memcache->set("logistics.tracking.usps_bearer_token", $data["access_token"], ($data["expires_in"] * 1) - 120);
        return $data["access_token"];
    }

    public static function getAPIRequest($endpoint) {
        $headers = [
            "Authorization: Bearer " . USPSAPIs::getBearerToken(),
            'Content-Type: application/json'
        ];

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

        return $response;
    }
}
