<?php
error_reporting(-1);


function ASBON($state, $zipcode)
{
    $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();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.convoso.com/v1/leads/insert?auth_token=h1e7b21sdieg7ll7nik3lo2eydeup9jx&list_id=12913&check_dup=0&check_dup_archive=0&check_dnc=0&update_if_found=&update_order_by_last_called_time=DESC&phone_code=1&phone_number=' . $phone . '&state=' . $state . '&phone=' . $phone . '',
        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);

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

    $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'] != '' && isset($_GET['buyer_asb_state_phone']) && $_GET['buyer_asb_state_phone'] != '') {
    $jsonRes = ASBState($_GET['state'], $_GET['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>' . $response . '</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'] : '';
$ASBON_phone        = (isset($_GET['asbon_phone']) && $_GET['asbon_phone'] != '') ? $_GET['asbon_phone'] : '';

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

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