<?php
error_reporting(-1);
function AW()
{

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://cxone.niceincontact.com/auth/token',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => 'grant_type=password&username=JKU4CU462VPSRP43RRXVGKH5HRP2FBZT444IZNAMKYBDN7LRIGJQ%3D%3D%3D%3D&password=NBHCQYDOW4IWGY3IVFGSJRI2KSBPX6UD44IXVYCV5OHIQSFFPOVA%3D%3D%3D%3D&client_id=b4d5a185-da99-4898-a733-4c1d678dcaab&client_secret=yckO9VQg6b3JQd%2Fg%2FXwudQ%3D%3D',
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    $accessToken = json_decode($response, true)['access_token'];
    // echo $accessToken;


    $curl = curl_init();
    ////// https://developer.niceincontact.com/API/RealTimeDataAPI#/RealTime/SkillActivity

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api-c63.nice-incontact.com/incontactapi/services/v32.0/skills/activity?IsOutbound=false&fields=skillname%2CagentsAvailable%2CagentsIdle&skip=55&top=1',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            ////// New 28 July 25
            'Authorization: Bearer ' . $accessToken,
            'Cookie: AWSALB=aRHyJlUCTGUpZHHk3KOdZc2HlNI9aSmeJc8qQZyTSQjO0JjhuMZxkXkeojG36lexp72OeUsurH5juCYElJp+Sb/8qJOvD97cQN8EJGCYQD50xRiJAxG8dhlRkCI7; AWSALBCORS=aRHyJlUCTGUpZHHk3KOdZc2HlNI9aSmeJc8qQZyTSQjO0JjhuMZxkXkeojG36lexp72OeUsurH5juCYElJp+Sb/8qJOvD97cQN8EJGCYQD50xRiJAxG8dhlRkCI7'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $jsonRes = json_decode($response, true);
    // echo "<pre>";
    // print_r($jsonRes);
    $available = ((isset($jsonRes['skillActivity'][0]['agentsAvailable'])) ? $jsonRes['skillActivity'][0]['agentsAvailable'] : 0);
    $total_agents = ((isset($jsonRes['skillActivity'][0]['agentsIdle'])) ? $jsonRes['skillActivity'][0]['agentsIdle'] : 0);
    if ($available >= 1) {
        if ($total_agents > 1) {
            $msg = $total_agents . " Agents are available";
        } else if ($total_agents == 1) {
            $msg = $total_agents . " Agent is available";
        } else {
            $msg = "No Agents are available";
        }
    } else {
        $msg = "No Agents are available";
    }
    return $msg;
}

function ASB()
{
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.convoso.com/v1/user-activity/search?auth_token=spd0pnbqr5zbrpuqhksdctogsmd7rsx9&campaign_id=&queue_id=9313&user_id=&filter_by_skill_options=',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'Cookie: APIUBUNTUBACKEND=apiapp112'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $jsonRes = json_decode($response, true);
    // print_r($jsonRes);
    $total_agents = $jsonRes['data']['available_agents'];
    if ($total_agents > 1) {
        $msg = $total_agents . " Agents are available";
    } else if ($total_agents == 1) {
        $msg = $total_agents . " Agent is available";
    } else {
        $msg = "No Agents are available";
    }
    return $msg;
}

function ASBTEST()
{
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.convoso.com/v1/agent-monitor/search?auth_token=rgy2wqogcb9jmqu1zkm3vcmwd5m8hq2z&campaign_id=&queue_id=9313&user_id=&filter_by_skill_options=',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'Cookie: APIUBUNTUBACKEND=apiapp112'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $jsonRes = json_decode($response, true);
    // print_r($jsonRes);
    $total_agents = $jsonRes['data']['available_agents'];
    if ($total_agents > 1) {
        $msg = $total_agents . " Agents are available";
    } else if ($total_agents == 1) {
        $msg = $total_agents . " Agent is available";
    } else {
        $msg = "No Agents are available";
    }
    return $msg;
}

function ASBON($state, $zipcode, $phone)
{
    $curl = curl_init();
    $fields = [];
    if (isset($state) && $state != '') {
        $fields['state'] = $state;
    }
    if (isset($zipcode) && $zipcode != '') {
        $fields['zip_code'] = $zipcode;
    }
    if (isset($phone) && $phone != '') {
        $fields['phone'] = $phone;
        $fields['phone_number'] = $phone;
        $fields['phone_code'] = "1";
    }

    //echo json_encode($fields);
    if (count($fields) > 0) {
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://communication.onyxplatform.com/api/v1/external/organizations/1333/campaigns/72/sources/66/utilization',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($fields),
            CURLOPT_HTTPHEADER => array(
                'Authorization: comm_VLsjoZK69EMH67lcir_stFXehi7Ioqb6hZ1SahIqF1k',
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $jsonRes = json_decode($response, true);
        // print_r($jsonRes);
        $available_workers_count = "0";
        if (isset($jsonRes['available_workers_count']) && $jsonRes['available_workers_count'] > 0) {
            $available_workers_count = $jsonRes['available_workers_count'];
        }
        if ($jsonRes["available"]) {

            $msg = $available_workers_count . " Agents are available";
        } else {
            $msg = $available_workers_count . " Agents are available";
        }
    } else {
        $msg =  "Please provide state or zipcode to check Agent Availability";
    }
    return $msg;
}

function ASBState($state, $phone)
{
    $curl = curl_init();
    $URL = 'https://api.convoso.com/v1/leads/insert?auth_token=h1e7b21sdieg7ll7nik3lo2eydeup9jx&list_id=12913&check_dup=3&check_dup_archive=0&check_dnc=1&update_if_found=&update_order_by_last_called_time=DESC&phone_code=1&phone_number=' . $phone . '&state=' . $state . '&phone=' . $phone . '';
    curl_setopt_array($curl, array(
        CURLOPT_URL => $URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'Cookie: APIUBUNTUBACKEND=apiapp112'
        ),
    ));

    $response = curl_exec($curl);
    //echo $response;

    curl_close($curl);

    //////////////////////////////////////////////////////////////////////////////////////////

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.convoso.com/v1/user-activity/search?auth_token=h1e7b21sdieg7ll7nik3lo2eydeup9jx&campaign_id=&queue_id=9313&user_id=&filter_by_skill_options=' . $state . '&exclude_remote_users=Y',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'Cookie: APIUBUNTUBACKEND=apiapp112'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $jsonRes = json_decode($response, true);
    // print_r($jsonRes);
    return $jsonRes;
}


function AUREN($state)
{
    $url = "https://mcc.phdialer.com/vicidial/non_agent_api.php?source=Ping&user=CCSapiUSER&pass=NFV983SKLAjsjk930Skj&stage=http&function=in_group_status&in_groups=" . $state . "&header=YES";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);            // Set the URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL verification (use with caution)
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);


    $HTML = '';
    //     $response = "ingroups|total_calls|calls_waiting|agents_logged_in|agents_in_calls|agents_waiting|agents_paused|agents_in_dispo|agents_in_dial
    // FL|0|0|1|1|0|0|0|0";

    $lines = explode("\n", $response);

    $headers = explode("|", $lines[0]);
    $data = explode("|", $lines[1]);

    $HTML .= "<table class='table' cellpadding='5' cellspacing='0'>";
    $HTML .= "<tr>";
    //print_r($headers);
    $HTML .= "<th>" . ucwords(str_replace("_", " ", htmlspecialchars($headers[4]))) . "</th>";
    $HTML .= "<th>" . ucwords(str_replace("_", " ", htmlspecialchars($headers[5]))) . "</th>";
    // foreach ($headers as $header) {
    //     $HTML .= "<th>" . ucwords(str_replace("_", " ", htmlspecialchars($header))) . "</th>";
    // }
    $HTML .= "</tr>";

    $HTML .= "<tr>";
    $HTML .= "<td>" . htmlspecialchars($data[4]) . "</td>";
    $HTML .= "<td>" . htmlspecialchars($data[5]) . "</td>";
    // foreach ($data as $value) {
    //     $HTML .= "<td>" . htmlspecialchars($value) . "</td>";
    // }
    $HTML .= "</tr>";
    $HTML .= "</table>";
    return $HTML;
}


$us_states = [
    'AL' => 'Alabama',
    'AK' => 'Alaska',
    'AZ' => 'Arizona',
    // 'AR' => 'Arkansas',
    // 'CA' => 'California',
    // 'CO' => 'Colorado',
    // 'CT' => 'Connecticut',
    // 'DE' => 'Delaware',
    // 'FL' => 'Florida',
    // 'GA' => 'Georgia',
    // 'HI' => 'Hawaii',
    // 'ID' => 'Idaho',
    // 'IL' => 'Illinois',
    // 'IN' => 'Indiana',
    // 'IA' => 'Iowa',
    // 'KS' => 'Kansas',
    // 'KY' => 'Kentucky',
    // 'LA' => 'Louisiana',
    // 'ME' => 'Maine',
    // 'MD' => 'Maryland',
    // 'MA' => 'Massachusetts',
    // 'MI' => 'Michigan',
    // 'MN' => 'Minnesota',
    // 'MS' => 'Mississippi',
    // 'MO' => 'Missouri',
    // 'MT' => 'Montana',
    // 'NE' => 'Nebraska',
    // 'NV' => 'Nevada',
    // 'NH' => 'New Hampshire',
    // 'NJ' => 'New Jersey',
    // 'NM' => 'New Mexico',
    // 'NY' => 'New York',
    // 'NC' => 'North Carolina',
    // 'ND' => 'North Dakota',
    // 'OH' => 'Ohio',
    // 'OK' => 'Oklahoma',
    // 'OR' => 'Oregon',
    // 'PA' => 'Pennsylvania',
    // 'RI' => 'Rhode Island',
    // 'SC' => 'South Carolina',
    // 'SD' => 'South Dakota',
    // 'TN' => 'Tennessee',
    // 'TX' => 'Texas',
    // 'UT' => 'Utah',
    // 'VT' => 'Vermont',
    // 'VA' => 'Virginia',
    // 'WA' => 'Washington',
    // 'WV' => 'West Virginia',
    // 'WI' => 'Wisconsin',
    // 'WY' => 'Wyoming'
];
$StateHTML = '';
if (isset($_GET['state']) && $_GET['state'] != '') {
    $buyer_asb_state_phone = (isset($_GET['buyer_asb_state_phone'])) ? $_GET['buyer_asb_state_phone'] : '' ;
    $jsonRes = ASBState($_GET['state'], $buyer_asb_state_phone);
    $name = isset($us_states[$_GET['state']]) ? $us_states[$_GET['state']] : 'Unknown State';
    if ($jsonRes['success'] == 1) {
        $StateHTML .= '<p><strong>' . $jsonRes['data']['available_agents'] . '</strong> Agents Available out of <strong>' . $jsonRes['data']['logged_in_agents'] . '</strong> Logged Agents.</p>';
    } else {
        $StateHTML .= '<p><code>' . json_encode($jsonRes) . '</code></p>';
    }
} else {
    $StateHTML .= '<p>Please select state to check Agent Availability</p>';
}

///////////////////////////////////////////////////////////////////////////////////////
$AURENStateHTML = '';
if (isset($_GET['buyer_auren_state']) && $_GET['buyer_auren_state'] != '') {
    $jsonRes = AUREN($_GET['buyer_auren_state']);
    $name = isset($us_states[$_GET['buyer_auren_state']]) ? $us_states[$_GET['state']] : 'Unknown State';
    $AURENStateHTML .= $jsonRes;
} else {
    $AURENStateHTML .= '<p>Please select state to check Agent Availability</p>';
}



// echo ASBON();
// exit;
$ASBON_state = (isset($_GET['asbon_state']) && $_GET['asbon_state'] != '') ? $_GET['asbon_state'] : '';
$ASBON_zipcode = (isset($_GET['asbon_zipcode']) && $_GET['asbon_zipcode'] != '') ? $_GET['asbon_zipcode'] : '';

$data = [
    "buyer_aw" => AW(),
    "buyer_asb" => '',//ASB(),
    //"buyer_asb_on" => ASBON($ASBON_state, $ASBON_zipcode),
    // "buyer_asb_test" => ASBTEST(),
    "buyer_asb_state" => $StateHTML,
    "buyer_auren" => $AURENStateHTML,
];

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