<?php
session_start(); // Start session

// Function to get new Salesforce access token
function getSalesforceAccessToken()
{
    $url = 'https://login.salesforce.com/services/oauth2/token';

    $data = [
        'grant_type'    => 'password',
        'client_id'     => '3MVG9OGq41FnYVsFFlZwxhSsKw6srq5XuG.eqonKYI1_pEZs7U8X.6Co0.KG50bPY5fCwdfIQA0t5JRCnypSq',
        'client_secret' => '93B2FE2A5109FFF0ACC4DC82BD7E9C98EB61AA6561CAD271F5BB2A3D9879B6BD',
        'username'      => 'apiuser@startencore.com',
        'password'      => 'ASDashdF@#r298!skaHM55pUHcNEPGB6nkdxJnTeeD2t2DA'
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        exit;
    }

    curl_close($ch);

    $result = json_decode($response, true);

    // Store token in session
    if (isset($result['access_token'])) {
        $_SESSION['sf_access_token'] = $result['access_token'];
    }

    return $result['access_token'] ?? null;
}

// Get access token from session or request a new one
$access_token = $_SESSION['sf_access_token'] ?? getSalesforceAccessToken();

// Validate input
$ocn_phone = (isset($_GET['ocn_phone']) && $_GET['ocn_phone'] != '') ? $_GET['ocn_phone'] : '';

if (!$ocn_phone) {
    echo json_encode(['error' => 'Missing ocn_phone']);
    exit;
}

$areaCode = substr((int)$ocn_phone, 0, 3);
$url = 'https://encorehealth.my.salesforce.com/services/apexrest/Five9ReadyAgents?areaCode=' . $areaCode;

// Call Salesforce API
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $access_token,
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
    exit;
}

curl_close($ch);

$result = json_decode($response, true);

// Optional: If the token is expired or invalid, clear session and try again
if (isset($result['error']) || !$result) {
    unset($_SESSION['sf_access_token']);
    // Optionally: Retry once here by getting a new token
    // You could add retry logic here if needed
}

$msg = (!empty($result['readyAgents'])) ? "Agents Available..." : "Agent Not Available...";

$data = [
    "ocn_msg" => $msg,
];

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