<?php
// Web service configuration for REST endpoint
$restBaseUrl = 'https://api.thinktel.ca/rest.svc';
$ucontrolUsername = 'username';
$ucontrolPassword = 'password';

// Single REST client for life of task
$client = new RestClient($restBaseUrl, $ucontrolUsername, $ucontrolPassword);

try
{
    // If you are choosing the SIP Trunk interactively, then first get the list of SIP Trunks from your account.
    $listSipTrunksResponse = $client->invoke_operation("GET", "/SipTrunks");
    $sipTrunks = $listSipTrunksResponse;

    // Choose specific SIP Trunk. For example purposes, we will assume the choice was SIP Trunk 9999990088.
    foreach ($sipTrunks as $st)
    {
        if ($st->Number === 9999990088)
        {
            $sipTrunk = $st;
            break;
        }
    }
    $sipTrunkNumber = $sipTrunk->Number;

    // If you are choosing the rate center interactively, then first get the list of rate centers with enough available inventory to fulfill the order.
    $listRateCentersResponse = $client->invoke_operation("GET", "/RateCenters");
    $rateCenters = array_filter($listRateCentersResponse, function($rc)
    {
        return ($rc->Available >= 3);
    });

    // Choose specific rate center. For example purposes, we will assume the choice was "Toronto, ON".
    foreach ($rateCenters as $rc)
    {
        if ($rc->Name === 'Toronto, ON')
        {
            $rateCenter = $rc;
            break;
        }
    }
    $rateCenterName = $rateCenter->Name;

    // Order the next available 3 DIDs from chosen rate center.
    $addSipTrunkRateCenterDidsResponse = $client->invoke_operation("POST", "/SipTrunks/{$sipTrunkNumber}/Dids/NextAvailable", array(array(
        'RateCenterName' => $rateCenterName,
        'Quantity' => 3,
    )));

    // Check response for what 3 DIDs were added, or for any exceptions
    foreach ($addSipTrunkRateCenterDidsResponse as $result)
    {
        if ($result->Reply == 1)
        {
            echo "Added DID {$result->Number} to SIP Trunk {$sipTrunkNumber}.", PHP_EOL;
            
            // Provide 911 information for recently added DID.
            $addV911Response = $client->invoke_operation("POST", "/V911s", array(
                'Number' => $result->Number,
                // If providing a business name, leave FirstName blank and provide the business name as LastName.
                'FirstName' => '',
                'LastName' => 'Distributel',
                'SuiteNumber' => '801',
                'StreetNumber' => '3300',
                'StreetName' => 'Bloor St W',
                // Emergency address requires the specific municipal city name, not the general city name.
                'City' => 'Etobicoke',
                'ProvinceState' => 'ON',
                'PostalZip' => 'M8X2X2',
                // Optional information for emergency personal to access the physical location.
                // For non-municipal addresses, this where you could provide latitude and longitude coordinates.
                'OtherInfo' => 'Elevators require keycard access, see building security desk first.'
            ));
            if ($addV911Response->Reply == 1)
            {
                echo "Added V911 information to telephone number {$addV911Response->Number}.", PHP_EOL;
            }
            else
            {
                echo "V911 information for telephone number {$addV911Response->Number} was not accepted: {$addV911Response->Message}", PHP_EOL;
            }

            // Set additional settings for recently ordered DID, such as update the Label
            $updateSipTrunkDidV2Response = $client->invoke_operation("PUT", "/v2/SipTrunks/{$sipTrunkNumber}/Dids/{$result->Number}", array(
                'Number' => $result->Number,
                'LabelSpecified' => true,
                'Label' => 'Drop-in Desk',
                'AdditionalLabelSpecified' => false,
                'TranslatedNumberSpecified' => false,
                'UnavailableCallForwardingSpecified' => false
            ));
            if ($updateSipTrunkDidV2Response->Reply == 1)
            {
                echo "Updated label for DID {$updateSipTrunkDidV2Response->Number}.", PHP_EOL;
            }
            else
            {
                echo "Update for DID {$updateSipTrunkDidV2Response->Number} was not accepted: {$updateSipTrunkDidV2Response->Message}", PHP_EOL;
            }
        }
        else
        {
            echo "Order not accepted for DID {$result->Number}: {$result->Message}", PHP_EOL;
        }
    }
}
catch (Exception $e)
{
    echo 'Caught exception: ',  $e->getMessage(), PHP_EOL;
}

// Helper class for invoking REST operations
class RestClient
{
    private $baseUrl;
    private $username;
    private $password;

    function __construct($baseUrl, $username, $password)
    {
        $this->baseUrl = $baseUrl;
        $this->username = $username;
        $this->password = $password;
    }

    public function invoke_operation($method, $operation, $data = false)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_VERBOSE, 1);

        $url = $this->baseUrl . $operation;
    
        switch ($method)
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data)
                {
                    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json', 'Expect:'));
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                }
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                if ($data)
                {
                    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json', 'Expect:'));
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    var_dump(json_encode($data));
                }
                break;
            case "GET":
                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));
                if ($data)
                {
                    $url = sprintf("%s?%s", $url, http_build_query($data));
                }
                break;
            default:
                break;
        }
    
        // Authentication
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_USERPWD, "{$this->username}:{$this->password}");
    
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
        $result = curl_exec($curl);

        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

        if ($statusCode == 200)
        {
            return json_decode($result);
        }
        else
        {
            trigger_error("REST Fault: (HTTP Status Code: {$statusCode}, Result: {$result})", E_USER_ERROR);
        }
    
        return $result;
    }
}
?>