nhance/app/Controllers/VidalApiController.php

640 lines
23 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class VidalApiController extends BaseController
{
protected $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
function uploadFileToVidal($filePath,$filename)
{
// $apiUrl = "https://devapigw.vidalhealthtpa.com/partner-integration/api/files/upload-url";
$apiUrl = getenv('VIDAL_API_BASE_URL').'/files/upload-url';
$subscriptionKey = getenv('VIDAL_API_SUBSCRIPTION_KEY');
log_message('error', "Starting file upload process for filename: $filename | Path: $filePath");
// Step 1: Get signed URL from Vidal API
// $filePath = '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png';
$payload = json_encode(["scope" => 'document type' , 'fileName' => $filename]);
$headers = [
"Content-Type: application/json",
"Ocp-Apim-Subscription-Key: $subscriptionKey"
];
log_message('error', "Requesting signed URL from Vidal API: $apiUrl | Payload: $payload");
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
log_message('error', "Curl error while requesting signed URL: " . curl_error($ch));
return ["status" => false, "message" => curl_error($ch)];
}
curl_close($ch);
$responseData = json_decode($response, true);
if (!isset($responseData['data']['signedUrl']) || !isset($responseData['data']['fileId'])) {
log_message('error', "Invalid signed URL response received: " . json_encode($responseData));
return ["status" => false, "message" => "Invalid signed URL response", "response" => $responseData];
}
$signedUrl = $responseData['data']['signedUrl'];
$fileId = $responseData['data']['fileId'];
log_message('error', "Received signed URL & fileId. fileId: $fileId");
// Step 2: Upload file to signed URL using PUT (Azure Blob)
$fileSize = filesize($filePath);
$fileContent = fopen($filePath, 'r');
$ch2 = curl_init($signedUrl);
curl_setopt($ch2, CURLOPT_PUT, true);
curl_setopt($ch2, CURLOPT_INFILE, $fileContent);
curl_setopt($ch2, CURLOPT_INFILESIZE, $fileSize);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, [
"x-ms-blob-type: BlockBlob",
"Content-Length: $fileSize"
]);
$uploadResponse = curl_exec($ch2);
$httpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch2);
fclose($fileContent);
curl_close($ch2);
if ($curlErr) {
log_message('error', "Curl error during file upload: $curlErr");
return ["status" => false, "message" => "File upload failed", "data" => $curlErr];
}
if ($httpCode !== 200 && $httpCode !== 201) {
log_message('error', "File upload failed with HTTP Code: $httpCode | Response: $uploadResponse");
return [
"status" => false,
"message" => "File upload failed",
"httpCode" => $httpCode,
"response" => $uploadResponse
];
}
// Step 3: Return File ID for reference
return [
"status" => true,
"message" => "File uploaded successfully",
"fileId" => $fileId,
"signedUrl" => $signedUrl,
"uploadResponse" => json_decode($uploadResponse, true)
];
}
public function SubmitClaim ($claimId = 515)
{
helper('api');
// Fetch the data from DB
$data = $this->db->table('ticket_master tm')
->select('
tm.id,
tm.emp_mobile as mobileNo,
tm.emp_mail as emailId,
tm.doa as admissionDate,
tm.dod as dischargeDate,
tm.hospital_name as hospitalName,
tm.hospital_address as hospitalAddress,
tm.hospital_state as hospitalState,
tm.hospital_city as hospitalCity,
tm.hospital_pin_code as hospitalPinCode,
tm.hospital_phone_no as hospitalPhoneNo,
tm.claim_amount as requestedAmount,
tm.tpa_no as dependentUniqueId,
cp.policy_no as policyNo,
e.emp_code as memberId,
tn.note as disease,
tn.note as reasonForHospitalization,
cf.url as fileName,
cf.url as filePath,
pt.policy_type as typeOfClaim,
ep.tpa_id as empanelmentNo,
')
->join('employees e', 'e.id = tm.emp_id', 'left')
->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left')
->join('policy_type pt', 'pt.id = cp.policy_type_id', 'left')
->join('employee_polices ep', 'ep.employee_id = e.id AND ep.client_policy_id = cp.id', 'left')
->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left')
->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 and cf.mime_type = 'application/pdf'", 'left')
->where('tm.id', $claimId)
->get()
->getRowArray(); // single record
if (count($data) && $data['filePath'] == null) {
log_message('error', "Submit claim failed - Claim or File Missing");
return $this->response->setJSON(['status' => false,'message' => 'Claim or File Missing', ]);
}
$filePath = $data['filePath'] ?? '';
$filename = basename($filePath);
$filePath = WRITEPATH . 'uploads/claim_files/'.$filename;
// dd($data);
// Upload file first
$upload = $this->uploadFileToVidal($filePath,$filename);
if ($upload['status'] !== true) {
log_message('error', "Submit claim failed - File upload failed");
return $this->response->setJSON([
'status' => false,
'message' => 'File upload failed',
'data' => $upload
]);
}
$fileId = $upload['fileId'];
// $url = 'https://devapigw.vidalhealthtpa.com/partner-integration/api/claims/submit';
$url = getenv('VIDAL_API_BASE_URL').'/claims/submit';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'',
];
$body = [
'policyNo' => $data['policyNo'],
'dependentUniqueId' => $data['dependentUniqueId'],
'typeOfClaim' => "Main hospitalization claim",
'claimSubType' => "OPD",
'requestedAmount' => $data['requestedAmount'],
'ailmentType' => "Non covid",
'admissionDate' => change_date_format($data['admissionDate'], 'Y-m-d', 'd-m-Y'),
'dischargeDate' => change_date_format($data['dischargeDate'], 'Y-m-d', 'd-m-Y'),
'hospitalName' => $data['hospitalName'],
'empanelmentNo' => 0,
"ailmentName" => "hospitalization",
"hospitalAddress" => $data['hospitalAddress'] ?? null,
"hospitalState" => $data['hospitalState'] ?? null,
"hospitalCity" => $data['hospitalCity'] ?? null,
"hospitalPinCode" => $data['hospitalPinCode'] ?? null,
"hospitalPhoneNo" => $data['hospitalPhoneNo'] ?? null,
"fileId" => $fileId,
"bankDetails" => [
"accountHolderName" => null,
"accountType" => null,
"accountNo" => null,
"ifscCode" => null,
],
];
// dd($body);
log_message('error', 'TPA CLAIM PUSH | claimId: '.$claimId.' | payload: '.json_encode($body));
// $body = [
// 'policyNo' => "351500/D0534/PP/20-20/PC",
// 'dependentUniqueId' => "EN000000182-C-41",
// 'typeOfClaim' => "Main hospitalization claim",
// 'claimSubType' => "Hospitalization",
// 'requestedAmount' => "2500",
// 'ailmentType' => "Non covid",
// 'admissionDate' => "01-12-2025",
// 'dischargeDate' => "01-12-2025",
// 'hospitalName' => "AKSHAY SUPER SPECIALITY HOSPITAL",
// 'empanelmentNo' => "HOS-MUM-031423",
// "ailmentName" => "Cold",
// "hospitalAddress" => "No. 6, Officers Colony, Puthur.,dfgdfgdfg,dfgdfg,560058",
// "hospitalState" => "karnataka",
// "hospitalCity" => "bangalore",
// "hospitalPinCode" => "560036",
// "hospitalPhoneNo" => "1234567890",
// "bankDetails" => [
// "accountHolderName" =>"Testing claim",
// "accountType" =>"savings",
// "accountNo" =>"1234567890",
// "ifscCode" =>"ICICI098768"
// ],
// "fileId" => "https://devapigw.vidalhealthtpa.com/doc-storage/api/private/691eda388973c60b83f80568"
// ];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
log_message('error', 'TPA CLAIM PUSH FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
return;
}
// return $this->response->setJSON($response);
if($response['data']['status'] == 'SUCCESS')
{
$claimNO = $response['data']['data']['claimNO'] ?? null;
$claimInwardNO = $response['data']['data']['claimInwardNO'] ?? null;
if(!empty($claimNO) && !empty($claimInwardNO)){
log_message('error', 'TPA CLAIM PUSH SUCCESS | claimId: '.$claimId.' | claimNO: '.$claimNO.' | claimInwardNO: '.$claimInwardNO);
$this->db->table('ticket_master')
->where('id',$claimId)
->update([ 'tpa_claim_push_reference_no' => $claimInwardNO , 'tpa_claim_id' => $claimNO ]);
return;
} else {
log_message('error', 'TPA CLAIM PUSH API SUCCESS BUT claimNO,claimInwardNO EMPTY | claimId: '.$claimId.' | response: '.json_encode($response));
return;
}
}else{
log_message('error', 'TPA CLAIM PUSH API FAILED | claimId: '.$claimId.' | response: '.json_encode($response));
return;
}
}
function getWellnessSSORedirectUrl($email = 'test@getvisitapp.com')
{
log_message('info', "SSO: Starting authentication for email: $email");
// ---------- CONFIG ----------
$authUrl = env('VIDAL_WELLNESS_BASE_URL');
$subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY');
$apiVersion = "1";
// Provided Base64 AES key
$base64Key = env('VIDAL_WELLNESS_BASE64_KEY');
$key = base64_decode($base64Key);
log_message('info', "SSO: Config loaded, Auth URL: $authUrl");
// ---------- STEP 1: Build plaintext payload ----------
$plainPayload = json_encode([
"email" => $email,
// "corporateId" => env('VIDAL_WELLNESS_CORPORATE_ID'),
"urlIdentifier" => env('VIDAL_WELLNESS_URL_IDENTIFIER')
]);
// ---------- STEP 2: Encrypt payload ----------
$iv = random_bytes(16);
$encryptedRaw = openssl_encrypt($plainPayload, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
$encryptedPayload = base64_encode($iv) . ":" . base64_encode($encryptedRaw);
log_message('info', "SSO: Payload encrypted successfully");
// ---------- STEP 3: Call Authentication API ----------
$requestBody = json_encode([
"payload" => $encryptedPayload,
"source" => env('VIDAL_WELLNESS_SUB_PARTNER_ID'),
"subPartnerId" => env('VIDAL_WELLNESS_SUB_PARTNER_ID')
]);
$headers = [
"Ocp-Apim-Subscription-Key: $subscriptionKey",
"apiver: $apiVersion",
"mode: encrypt",
"Content-Type: application/json"
];
$ch = curl_init($authUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
log_message('info', "SSO: API response received, HTTP Code: $httpCode");
// Check for cURL errors
if ($curlError) {
log_message('error', "SSO: cURL error - $curlError");
return ['status' => 'failed','message' => $curlError];
}
// Check HTTP status
if ($httpCode !== 200) {
log_message('error', "SSO: HTTP error - Code: $httpCode, Response: $apiResponse");
return ['status' => 'failed','message' => "HTTP error: $httpCode" , "response" => $apiResponse ];
}
$jsonResponse = json_decode($apiResponse, true);
// Check JSON decode error
if (json_last_error() !== JSON_ERROR_NONE) {
log_message('error', "SSO: JSON decode error - " . json_last_error_msg());
return ['status' => 'failed','message' => "JSON decode error: " . json_last_error_msg(), "response" => $apiResponse];
}
// Check API response status
if (!isset($jsonResponse["status"]) || $jsonResponse["status"] !== "success") {
log_message('error', "SSO: API error - " . json_encode($jsonResponse));
return ['status' => 'failed','message' => "API error", "response" => $jsonResponse];
}
if (!isset($jsonResponse["data"])) {
log_message('error', "SSO: Missing data field in response");
return ['status' => 'failed','message' => "Invalid API response - missing data field", "response" => $jsonResponse];
}
log_message('info', "SSO: API response validated successfully");
// ---------- STEP 4: Decrypt response ----------
log_message('info', "SSO: Starting response decryption");
$dataParts = explode(":", $jsonResponse["data"]);
if (count($dataParts) !== 2) {
log_message('error', "SSO: Invalid encrypted data format");
return ['status' => 'failed','message' => "Invalid encrypted data format", "data" => $jsonResponse["data"]];
}
list($ivBase64, $cipherBase64) = $dataParts;
$respIv = base64_decode($ivBase64);
$respCipher = base64_decode($cipherBase64);
if ($respIv === false || $respCipher === false) {
log_message('error', "SSO: Base64 decode error");
return ['status' => 'failed','message' => "Base64 decode error"];
}
$decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv);
if ($decryptedJson === false) {
log_message('error', "SSO: Decryption failed");
return ['status' => 'failed','message' => "Decryption failed"];
}
$decryptedData = json_decode($decryptedJson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
log_message('error', "SSO: Decrypted JSON decode error - " . json_last_error_msg());
return ['status' => 'failed','message' => "Decrypted JSON decode error: " . json_last_error_msg()];
}
if (!isset($decryptedData["redirectUrl"])) {
log_message('error', "SSO: redirectUrl missing in decrypted data");
return ['status' => 'failed','message' => "redirectUrl missing", "decrypted" => $decryptedData];
}
// ---------- FINAL ----------
log_message('info', "SSO: Authentication successful, redirectUrl obtained");
return ['status' => 'success','data' => $decryptedData["redirectUrl"]];
}
//----------yet to start only submit claim given
public function fileUpload()
{
helper('api');
$url = getenv('VIDAL_API_BASE_URL') . '/files/upload-url';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'x-ms-blob-type: BlockBlob',
'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'',
];
$body = [
'scope' => 'application/pdf',
'fileName' => '1760013019_73d94af7b96ddc2e3d51.png',
'file' => '/opt/lampp/htdocs/nhance/writable/uploads/claim_files/1760013019_73d94af7b96ddc2e3d51.png',
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
// {
// "status": true,
// "data": {
// "status": "SUCCESS",
// "data": {
// "signedUrl": "https://devapigw.vidalhealthtpa.com/doc-storage/api/deeplink/6912d37a9f09fc3f6be4cd9c/56fb8e76-39a4-4e4b-99f2-4748e224e4a7?se=2025-11-18T06:11:06.304Z",
// "expiresAt": "2025-11-18T06:11:06.304Z",
// "fileId": "https://devapigw.vidalhealthtpa.com/doc-storage/api/private/6912d37a9f09fc3f6be4cd9c"
// },
// "trace": "T_ID_a09327df-ea34-4874-9e3f-05ac5c0a2c68",
// "successful": true
// },
// "code": 200
// }
}
public function claimStatus ($claimId = null)
{
helper('api');
$url = getenv('VIDAL_API_BASE_URL').'/claims/claim-dependent-info';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Ocp-Apim-Subscription-Key:' .getenv('VIDAL_API_SUBSCRIPTION_KEY').'',
];
$body = [
'empNO' => "",
'tpaCardID' => "",
'claimID' => "BLR-0284-CL-9349459",
'emailID' => "",
'mobileNO' => "",
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function hospitalNetwork(){
$postData = $this->request->getJSON(true);
helper('api');
$url = ''. getenv('VIDAL_API_BASE_URL').'/hospitalnetwork';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Authorization:'. getenv('VIDAL_API_KEY').'',
'username:'. getenv('VIDAL_API_USERNAME').'',
'password:'. getenv('VIDAL_API_PASSWORD').'',
'policynumber:'. $postData['policyNo'] ?? '',
];
$body = [];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function eCardService(){
$postData = $this->request->getJSON(true);
helper('api');
$url = ''. getenv('VIDAL_API_BASE_URL').'/ecardservice';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Authorization:'.getenv('VIDAL_API_KEY').'',
'username:' .getenv('VIDAL_API_USERNAME').'',
'password:' .getenv('VIDAL_API_PASSWORD').'',
'PolicyNo:' .$postData['PolicyNo'] ?? '',
'enrollmentNo:' .$postData['enrollmentNo'] ?? '',
];
$body = [
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function claimStatusCheck(){
$postData = $this->request->getJSON(true);
helper('api');
$url = ''. getenv('VIDAL_API_BASE_URL').'/claimpreauthservice';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Authorization:' .getenv('VIDAL_API_KEY').'',
'username:' .getenv('VIDAL_API_USERNAME').'',
'password:' .getenv('VIDAL_API_PASSWORD').'',
'PolicyNo:' .$postData['policyNo'] ?? '',
'enrollmentNo:' .$postData['enrollmentNo'] ?? '',
'empNo:' .$postData['empNo'] ?? '',
'startdate:' .$postData['startdate'] ?? '',
'enddate:' .$postData['enddate'] ?? '',
'tpaclaimNo:' .$postData['tpaclaimNo'] ?? ''
];
$body = [];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
public function enrollment()
{
$postData = $this->request->getJSON(true);
helper('api');
$url = getenv('VIDAL_API_BASE_URL').'/enrollmendataservice';
$method = 'POST';
$headers = [
'Content-Type: application/json',
'Authorization:'. getenv('VIDAL_API_KEY').'',
'username:' . getenv('VIDAL_API_USERNAME').'',
'password:' . getenv('VIDAL_API_PASSWORD').'',
'policyNo:' .$postData['policyNo'] ?? '',
'startindex:' .$postData['startindex'] ?? '',
'endindex:' .$postData['endindex'] ?? ''
];
$body = [
];
$response = call_third_party_api($url, $method, $headers, $body);
if($response['status'] != true){
return $this->response->setJSON([
'status' => false,
'message' => 'Token generation failed.',
'data' => $response
]);
}
return $this->response->setJSON($response);
}
}