<?php
require 'd:/SMS/TelstraAPI.php';

class TelstraAPIv3Test extends TelstraAPI {
    public function getAccessTokenV3() {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://tapi.telstra.com/v2/oauth/token',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query([
                'grant_type' => 'client_credentials',
                'client_id' => getenv('TELSTRA_CLIENT_ID') ?: ($_ENV['TELSTRA_CLIENT_ID'] ?? ($_SERVER['TELSTRA_CLIENT_ID'] ?? '')),
                'client_secret' => getenv('TELSTRA_CLIENT_SECRET') ?: ($_ENV['TELSTRA_CLIENT_SECRET'] ?? ($_SERVER['TELSTRA_CLIENT_SECRET'] ?? '')),
                'scope' => 'free-trial-numbers:read free-trial-numbers:write messages:read messages:write virtual-numbers:read virtual-numbers:write'
            ]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
        ]);
        $response = curl_exec($ch);
        $data = json_decode($response, true);
        return $data;
    }
    
    public function getVirtualNumbers($token) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://products.api.telstra.com/messaging/v3/virtual-numbers',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Accept: application/json'
            ]
        ]);
        return json_decode(curl_exec($ch), true);
    }
    
    public function provisionVirtualNumber($token) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://products.api.telstra.com/messaging/v3/virtual-numbers',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(new stdClass()),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ]
        ]);
        return json_decode(curl_exec($ch), true);
    }
}

$api = new TelstraAPIv3Test();
$tokenData = $api->getAccessTokenV3();
echo "Token Data:\n";
print_r($tokenData);

if (isset($tokenData['access_token'])) {
    $token = $tokenData['access_token'];
    echo "\nGetting Virtual Numbers:\n";
    $numbers = $api->getVirtualNumbers($token);
    print_r($numbers);
    
    if (empty($numbers['virtualNumbers'])) {
        echo "\nProvisioning Virtual Number:\n";
        $provision = $api->provisionVirtualNumber($token);
        print_r($provision);
    }
}
