<?php
error_reporting(-1);
function randomColorHex()
{
    return sprintf("#%06X", mt_rand(0, 0xFFFFFF));
}

function buyers_available_server($state, $phone)
{

    $secondApiUrl = "https://rtb.retreaver.com/rtbs.json?key=35fb4734-6582-491e-88d1-64fff3d56523&source_id=f849415d&caller_number={$phone}&state={$state}";

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $secondApiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $secondApiUrl,
    ));

    $secondResponse = curl_exec($curl);

    curl_close($curl);
    $secondData = json_decode($secondResponse, true);
    // print_r($secondData);
    $msg = '';
    if (isset($secondData['status']) && $secondData['status'] === "reserved") {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.enrollhere.com/dialer/availability/byQueue/f8e3K7fMKWvrsFcgXFc9',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));

        $firstResponse = curl_exec($curl);

        curl_close($curl);
        $firstData = json_decode($firstResponse, true);
        if (isset($firstData['count']) && $firstData['count'] >= 1) {
            $msg .= '<div class="result">';
            $msg .= "<strong>Status: Acceptable</strong>";
            $msg .= "<p>Inbound Number: " . htmlspecialchars($secondData['inbound_number']) . "</p>";
            $msg .= '</div>';
        } else {
            $msg .= '<div class="result rejected">';
            $msg .= "<strong>Rejected - Do not want this call</strong>";
            $msg .= "<br><small>Count: " . $firstData['count'] . "</small>";
            $msg .= '</div>';
        }
    } else {

        $msg .= '<div class="result rejected">';
        $msg .= "<strong>Rejected - Do not want this call</strong>";
        $msg .= "<br><small>Status: " . $secondData['status'] . "</small>";
        $msg .= '</div>';
    }

    return $msg;
}



// echo ASBON();
// exit;
$mm_state        = (isset($_GET['state']) && $_GET['state'] != '') ? $_GET['state'] : '';
$mm_phone        = (isset($_GET['phone']) && $_GET['phone'] != '') ? $_GET['phone'] : '';

$data = [
    "buyers_available_server_mm" => buyers_available_server($mm_state, $mm_phone),
];

header('Content-Type: application/json');
echo json_encode($data);