<?php
error_reporting(-1);
function randomColorHex()
{
    return sprintf("#%06X", mt_rand(0, 0xFFFFFF));
}
function buyers_available_server($state, $phone)
{
    $curl = curl_init();

    $URL = 'https://api.enrollhere.com/dialer/availability/byQueue/DrnGjSO0nf6T6ZZci5L2';
    curl_setopt_array($curl, array(
        CURLOPT_URL => $URL,
        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);
//    print_r($firstData);
    $msg = '';

    if (isset($firstData['count']) && $firstData['count'] >= 1) {
        $status = 'Available';
        $msg .= '<div class="result" style="background-color: lightseagreen;">';
        $msg .= "<strong>Available - Count: " . $firstData['count'] . "</strong>";
        $msg .= '</div>';
    } else {
        $status = 'Rejected';
        $msg .= '<div class="result rejected">';
        $msg .= "<strong>Rejected - Do not want this call </strong>";
        $msg .= '</div>';
    }

    include "api_store.php";
    $SQL = "INSERT INTO `api_calls` ( `APIName`, `APIRequest`, `APIResponse`, `APIEndpoint`, `APIStatus`) VALUES ('M1', '', '" . $firstResponse . "', '" . $URL . "', '". $status."');";
    $db->query($SQL);

    return $msg;
}



// echo ASBON();
// exit;
$M1_state        = (isset($_GET['M1_state']) && $_GET['M1_state'] != '') ? $_GET['M1_state'] : '';
$M1_phone        = (isset($_GET['M1_phone']) && $_GET['M1_phone'] != '') ? $_GET['M1_phone'] : '';

$data = [
    "buyers_available_server_m1" => buyers_available_server($M1_state, $M1_phone),
];

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