<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

function e($value) {
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

$client = new Client();
$responseBody = '';
$responseHeaders = [];
$jsonRequest = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	
	if($_POST['apiType']=='production'){
		$baseUrl 		= 'https://apigw.optum.com';
		$clientId 		= '9c918db5-877d-41a5-884f-d8ef3b2172ea';
		$clientSecret 	= '4RsocQxzZmr5hEQTAsIiogkT17l9mbtr';
		  $environment = 'production';
	}else{
		$baseUrl 		= 'https://sandbox-apigw.optum.com';
		$clientId 		= '0bc8d959-abfe-4b70-991f-88059ff411a0';
		$clientSecret 	= 'ekE6I72Fdzrf9r776LZMZjN0LGxLH5XM';
		  $environment = 'sandbox';
	}
    try {

        /*
        |--------------------------------------------------------------------------
        | 1️⃣ Generate Token
        |--------------------------------------------------------------------------
        */

        $tokenResponse = $client->post(
            $baseUrl . '/apip/auth/sntl/v1/token',
            [
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'form_params' => [
                    'grant_type'    => 'client_credentials',
                    'client_id'     => $clientId,
                    'client_secret' => $clientSecret
                ]
            ]
        );

        $tokenData = json_decode($tokenResponse->getBody(), true);

        if (!isset($tokenData['access_token'])) {
            throw new Exception("Access token not received.");
        }

        $accessToken = $tokenData['access_token'];

        /*
        |--------------------------------------------------------------------------
        | 2️⃣ Build Payload From Form
        |--------------------------------------------------------------------------
        */
		
		
			$inputFields = [
				'serviceLevelCodes' => $_POST['serviceLevelCodes'] ?? '001',
				'payerId'           => $_POST['payerId'] ?? null,
				'memberId'          => $_POST['memberId'] ?? null,
				'firstName'         => $_POST['firstName'] ?? null,
				'lastName'          => $_POST['lastName'] ?? null,
				'groupNumber'       => $_POST['groupNumber'] ?? null,
				'dateOfBirth'       => $_POST['dateOfBirth'] ?? null,
				'serviceStartDate'  => $_POST['serviceStartDate'] ?? null,
				'serviceEndDate'    => $_POST['serviceEndDate'] ?? null,
				'trnId'             => $_POST['trnId'] ?? null,
				'providerLastName'  => $_POST['providerLastName'] ?? null,
				'providerNPI'       => $_POST['providerNPI'] ?? null,
				'planStartDate'     => $_POST['planStartDate'] ?? null,
				'planEndDate'       => $_POST['planEndDate'] ?? null,
				'familyIndicator'   => $_POST['familyIndicator'] ?? null,
			];

			// Remove empty values
			$inputFields = array_filter(
				$inputFields,
				function($value) {
					// Keep if value is not null AND not empty string
					return !is_null($value) && $value !== '';
				}
			);

        $requestPayload = [
            'variables' => [
                'input' => $inputFields
            ],
       'query' => 'query CheckEligibility($input: EligibilityInput!) { checkEligibility( input: $input ) { eligibility { eligibilityInfo { trnId member { memberId firstName lastName middleName suffix dateOfBirth gender relationshipCode dependentSequenceNumber individualRelationship { code description } relationshipType { code description } } contact { addresses { type street1 street2 city state country zip zip4 } } insuranceInfo { policyNumber eligibilityStartDate eligibilityEndDate planStartDate planEndDate policyStatus planTypeDescription groupName address { type street1 street2 city state country zip zip4 } stateOfIssueCode productType productId productCode payerId lineOfBusinessCode governmentProgramCode coverageType insuranceTypeCode insuranceType } associatedIds { alternateId medicaidRecipientId exchangeMemberId alternateSubscriberId hicNumber mbiNumber subscriberMemberFacingIdentifier survivingSpouseId subscriberId memberReplacementId legacyMemberId healthInsuranceExchangeId } planLevels { level family { networkStatus planAmount planAmountFrequency remainingAmount } individual { networkStatus planAmount planAmountFrequency remainingAmount } } delegatedInfo { entity payerId contact { phone fax email } addresses { type street1 street2 city state country zip zip4 } } } primaryCarePhysician { lastName firstName middleName phoneNumber address { type street1 street2 city state country zip zip4 } affiliateHospitalName providerGroupName pcpSpeciality pcpStartDate pcpEndDate providerNPI providerTIN acoNetworkDescription acoNetworkId } coordinationOfBenefits { coordinationOfBenefitDetails { member { id name } policy { policyNumber groupNumber coverageType insuranceTypeCode medicareEntitlementType medicareEntitlementReason effectiveDate terminationDate verificationDate } payer { name phoneNumber address { type street1 street2 city state country zip zip4 } } cobPrimacy { indicator description message } } primacyStatus { uhcPolicyNumber policyEffectiveDate policyTerminationDate primacy { indicator description message } } cobUpdateInformation { cobUpdateMessage cobLastVerifiedDate } disclaimer } idCardImages { side content contentType } providerNetwork { status tier speciality } serviceLevels { family { networkStatus services { service serviceCode serviceDate status planAmount remainingAmount metYearToDateAmount message { coPay { isSingleMessageDetail isViewDetail messages subMessages { service status copay frequency msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator exactCopay { coveredStatus copayDetails { amount serviceSetting } } } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } coInsurance { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } deductible { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } benefitsAllowed { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } benefitsRemaining { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } coPayList { placeOfService copay service startDate endDate messages } coInsuranceList { placeOfService coinsurancePercent service messages startDate endDate } } } } individual { networkStatus services { service serviceCode serviceDate status planAmount remainingAmount metYearToDateAmount message { coPay { isSingleMessageDetail isViewDetail messages subMessages { service status copay frequency msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator exactCopay { coveredStatus copayDetails { amount serviceSetting } } } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } coInsurance { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } deductible { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } benefitsAllowed { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } benefitsRemaining { isSingleMessageDetail isViewDetail messages subMessages { service status copay msg startDate endDate minCopay minCopayMsg maxCopay maxCopayMsg isPrimaryIndicator } limitationInfo { lmtPeriod lmtType lmtOccurPerPeriod lmtDollarPerPeriod message } isMultipleCopaysFound isMultipleCoinsuranceFound } coPayList { placeOfService copay service startDate endDate messages } coInsuranceList { placeOfService coinsurancePercent service messages startDate endDate } } } } } otherBeneficiaries { memberId firstName lastName middleName suffix dateOfBirth gender relationshipCode dependentSequenceNumber individualRelationship { code description } relationshipType { code description } } additionalInfo { fundingType businessSegment sizeDefinitionDescription revenueArrangementDescription hsa cdhp cmsHId cmsPackageBenefitPlanCode cmsSegmentId cmsContractId benefitPlanId virtualVisit designatedVirtualClinicNetwork medicaidVariableCode hraBalance hraMessage hraUnavailableMessage graceMessageByState gracePaidThrough gracePeriodMonth medicareGuidelines medicareEntitlementReason medicaidEntitlement { waiverLiabilityList { startDate endDate amount amountFrequency remainingAmount metYtdAmount } patientLiabilityList { startDate endDate amount amountFrequency remainingAmount metYtdAmount } transferOfPropertyPenaltyPeriod { startDate endDate } } } } } }'
        ];

        $jsonRequest = json_encode($requestPayload, JSON_PRETTY_PRINT);

        /*
        |--------------------------------------------------------------------------
        | 3️⃣ Call Eligibility API
        |--------------------------------------------------------------------------
        */

        $eligibilityResponse = $client->post(
            $baseUrl . '/oihub/eligibility/v1/pre-service/member',
            [
                'headers' => [
                    'Accept'        => 'application/json',
                    'Authorization' => 'Bearer ' . $accessToken,
                    'Content-Type'  => 'application/json',
					//"environment" 	=> $environment,
                    'providerTaxId' =>  $_POST['providerTaxId'] ?? '999999999'
                ],
                'json' => $requestPayload
            ]
        );

        $responseBody = $eligibilityResponse->getBody()->getContents();
        $responseHeaders = $eligibilityResponse->getHeaders();

    } catch (RequestException $e) {

        if ($e->hasResponse()) {
            $responseBody = $e->getResponse()->getBody()->getContents();
            $responseHeaders = $e->getResponse()->getHeaders();
        } else {
            $responseBody = $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Optum Eligibility Check</title>
</head>
<body>

<h2>Eligibility Input Form</h2>

<form method="POST">

    Service Level Code:
    <input type="text" name="serviceLevelCodes" value="001"><br><br>

    Payer ID:
    <input type="text" name="payerId" required value="39026"><br><br>

    Member ID:
    <input type="text" name="memberId" required value="15725310"><br><br>

    First Name:
    <input type="text" name="firstName" placeholder='Melissa'><br><br>

    Last Name:
    <input type="text" name="lastName" placeholder='Blechinger'><br><br>

    Group Number:
    <input type="text" name="groupNumber"><br><br>

    Date of Birth:
    <input type="date" name="dateOfBirth" value="1976-07-30"><br><br>

    Service Start Date:
    <input type="date" name="serviceStartDate" value="2025-11-04"><br><br>

    Service End Date:
    <input type="date" name="serviceEndDate"><br><br>

    TRN ID:
    <input type="text" name="trnId"><br><br>

    Provider Last Name:
    <input type="text" name="providerLastName" value="REVIVE BEHAVIORAL HEALTH"><br><br>

    Provider NPI:
    <input type="text" name="providerNPI" placeholder="1003601220"><br><br>

    Plan Start Date:
    <input type="date" name="planStartDate"><br><br>

    Plan End Date:
    <input type="date" name="planEndDate"><br><br>

    Family Indicator:
    <select name="familyIndicator">
        <option value="Yes">Yes</option>
        <option value="No">No</option>
    </select><br><br>
	
	 Provider Tax Id:
    <input type="text" name="providerTaxId" value="334424668"><br><br>
	
	 Api Type:
    <select name="apiType">
        <option value="sandbox">Sandbox</option>
        <option value="production">Production</option>
    </select><br><br>

    <button type="submit">Check Eligibility</button>

</form>

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>

<hr>

<h2>CLIENT REQUEST</h2>
<pre><?php echo e($jsonRequest); ?></pre>

<h2>RESPONSE HEADERS</h2>
<pre>
<?php
$formattedHeaders = '';
foreach ($responseHeaders as $key => $values) {
    foreach ($values as $value) {
        $formattedHeaders .= $key . ': ' . $value . "\n";
    }
}
echo e($formattedHeaders);
?>
</pre>

<h2>RESPONSE BODY</h2>
<pre>
<?php
echo "ProviderTaxId=".$_POST['providerTaxId']."<br/>";
echo e(json_encode(json_decode($responseBody), JSON_PRETTY_PRINT));
?>
</pre>

<?php endif; ?>

</body>
</html>
