nhance/app/Controllers/ApiServiceController.php

710 lines
28 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Models\EmployeePolicyModel;
use App\Controllers\BaseController;
use App\Controllers\VidalApiController;
use App\Controllers\ICICILombardController;
use App\Controllers\MediAssistApiController;
use App\Controllers\FhplApiController;
use App\Models\BatchFileModel;
use App\Models\FileModel;
use App\Helpers\TPADataCompareHelper;
use App\Helpers\TPADataCompareHelper2;
class ApiServiceController extends BaseController
{
use ResponseTrait;
// protected $format = 'json';
protected $db;
protected $employeePolicyModel;
protected $medi_assist_primary_key;
protected $vidal_primary_key;
protected $icici_primary_key;
protected $fhpl_primary_key;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->medi_assist_primary_key = getenv('MEDI_ASSIST_PRIMARY_KEY_CONSTANT');
$this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT');
$this->icici_primary_key = getenv('ICICI_PRIMARY_KEY_CONSTANT');
$this->fhpl_primary_key = getenv('FHPL_PRIMARY_KEY_CONSTANT');
}
// Push Claims
public function pushClaims($claimId)
{
$data = $this->db->table('ticket_master tm')
->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record
if($data){
$tpaID = $data['tpa_id'];
if ($tpaID == $this->medi_assist_primary_key)
{ // MediAssist
$mediAssistController = new MediAssistApiController();
return $mediAssistController->SubmitClaim($claimId);
}else if ($tpaID == $this->vidal_primary_key)
{ // Vidal
$vidalApiController = new VidalApiController;
return $vidalApiController->SubmitClaim($claimId);
}else if ($tpaID == $this->fhpl_primary_key)
{ // fhpl
$fhplApiController = new FhplApiController;
return $fhplApiController->SubmitClaim($claimId);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
}
}
}
// E-Card Request
public function ecardRequest($params = [], $return_type = 'api')
{
try{
if(empty($params) && $this->response){
$payload = $this->request->getJSON(true);
$id = $payload['id'] ?? null;
$emp_code = $payload['emp_code'] ?? null;
$client_policy_id = $payload['client_policy_id'] ?? null;
$policy_no = $payload['policy_no'] ?? null;
$type = $payload['type'] ?? 'download';
log_message('error', 'Received Payload API : '. json_encode($payload ?? ""));
}else{
$id = $params['id'] ?? null;
$emp_code = $params['emp_code'] ?? null;
$client_policy_id = $params['client_policy_id'] ?? null;
$policy_no = $params['policy_no'] ?? null;
$type = $params['type'] ?? 'download';
$all_member = $params['all_member'] ?? null;
log_message('error', 'Received Payload INTERNAL : '. json_encode($params ?? ""));
}
// $employee_policy = $this->employeePolicyModel
// ->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ')
// ->join('employees', 'employee_polices.employee_id = employees.id', 'left')
// ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left')
// ->where('employee_polices.employee_id',$id)
// ->where('employee_polices.client_policy_id',$client_policy_id)
// ->where('employee_polices.is_active', 1 )->findAll();
$employee_policy = $this->employeePolicyModel
->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id', 'left')
->where('employees.emp_code', $emp_code)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.id', $id)
->where('employee_polices.is_active', 1)
->where('employees.is_active', 1)
->whereIn('employee_polices.status', ['active', 'expired'])
->whereIn('employees.emp_status', ['active', 'expired'])
->findAll();
if(count($employee_policy) > 0)
{
if($employee_policy[0]['tpa_id'] != null)
{
if($employee_policy[0]['tpa_primary_id'] == $this->medi_assist_primary_key)//Medi assist
{
$mediAssistController = new MediAssistApiController();
$data['eCardDownload'] = $mediAssistController->EcardRequest( $emp_code, $policy_no );
}else if($employee_policy[0]['tpa_primary_id'] == $this->vidal_primary_key)// Vidal
{
$vidalApiController = new VidalApiController;
$data['eCardDownload'] = $vidalApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else if($employee_policy[0]['tpa_primary_id'] == $this->fhpl_primary_key)// Fhpl
{
$fhplApiController = new FhplApiController;
$data['eCardDownload'] = $fhplApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else{
if($type == "download"){
// direct download
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1';
}else{
if(isset($all_member) && !empty($all_member)){
// view and download all members
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/1/1';
}else{
// view and download single member
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'].'/0/1';
}
}
}
$data['message'] = "E-card generated";
if(empty($data['eCardDownload'])){
$data['message'] = "E-card not generated";
}
} else {
$data['eCardDownload'] = null;
$data['message'] = "E-card not generated";
log_message('error', 'TPA number is null');
}
}else{
$data['eCardDownload'] = null;
$data['message'] = "E-card not generated";
log_message('error', 'Employee not found');
}
if($return_type == 'api'){
return $this->respond(['status' => true, 'code' => 200, 'message' => '', 'data' => $data]);
}else{
return $data;
}
} catch(\Exception $e){
}
}
// Get TPAID
public function getTPAID()
{
// helper('TPADataCompareHelper');
// print_rr(json_decode(file_get_contents(WRITEPATH.'/tmp/medi.json'),true));die();
// $report = TPADataCompareHelper::compareDbVsMediassist(
// $report = TPADataCompareHelper2::compareDbVsMediassistGrouped(
// json_decode(file_get_contents(WRITEPATH.'/tmp/db.json'),true),
// json_decode(file_get_contents(WRITEPATH.'/tmp/medi.json'),true)
// );
// print_rr($report);
// die();
//START OF THE PROGRAM
log_message('error', "getTPAID payloads :" . json_encode($this->request->getPost() ?? []));
$tpa_id = $this->request->getPost('tpa_id') ?? null;
$policy_no = $this->request->getPost('policy_no') ?? null;
$client_id = $this->request->getPost('client_id') ?? null;
$branch_id = $this->request->getPost('client_branch_id') ?? null;
$policy_id = $this->request->getPost('client_policy_id') ?? null;
$fileModel = new BatchFileModel();
$filesData = $fileModel->where('is_active', 1)->where('event_type', 'api')->where('status', 'inprogress')->countAllResults();
if($filesData > 0){
log_message('error', "TPA GetBenefDetails job is already in process.");
return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA initiation is in progress.','data' => [] ]);
}
$employeePolicyModel = new EmployeePolicyModel();
$employeePolicyData = $employeePolicyModel
->select('
employees.*,
employee_polices.id as emp_policy_id,
employee_polices.client_policy_id,
')
->join('employees', 'employees.id = employee_polices.employee_id')
->where('employee_polices.is_active', 1)
->where('employee_polices.status', 'active')
->where('employees.is_active', 1)
->where('employees.emp_status', 'active')
->where('employee_polices.tpa_id IS NULL')
->where('employee_polices.client_policy_id', $policy_id)
->countAllResults();
if($employeePolicyData == 0){
log_message('error', "No Employee Policy found with null TPA ID. TPA ID is already updated.");
return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA ID Already updated','data' => [] ]);
}
if (empty($policy_no)) {
log_message('error', 'GetBenefDetails: policy_no missing in request');
return $this->respond(['status' => false, 'message' => 'policy_no required']);
}
$data = [
'file_name' => "API",
'event_type' => "api",
'actions' => "fetch",
'insurer_or_tpa' => "tpa",
'batch_code' => generate_random_string(4),
'status' => "inprogress",
'client_id' => $client_id,
'client_policy_id'=> $policy_id,
'client_branch_id'=> $branch_id,
'created_by'=> get_session_userid(),
];
if ($tpa_id == $this->medi_assist_primary_key) // MediAssist
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
// $mediAssistController = new MediAssistApiController();
// $mediAssistController->MediAssistGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] );
$r = Jobs::addJob(['job_name' => 'MediAssistGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "MediAssistGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->vidal_primary_key) // Vidal
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
// $vidalApiController = new VidalApiController;
// $vidalApiController->VidalGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] );
$r = Jobs::addJob(['job_name' => 'VidalGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "VidalGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->fhpl_primary_key) // Fhpl
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
// $fhplApiController = new FhplApiController;
// $fhplApiController->FhplGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] );
$r = Jobs::addJob(['job_name' => 'FhplGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "FhplGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else{
return $this->respond(['status' => false, 'code' => 200,'message' => 'TPA not found ','data' => [] ]);
}
}
// get Claim details
public function getClaimStatus()
{
$claimId = $this->request->getGet('claim_id');
$data = $this->db->table('ticket_master tm')
->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record
if($data){
$tpaID = $data['tpa_id'];
if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
$mediAssistController = new MediAssistApiController();
$res = $mediAssistController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->vidal_primary_key) { // vidal
$vidalApiController = new VidalApiController;
$res = $vidalApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->fhpl_primary_key) { // Fhpl
$fhplApiController = new FhplApiController;
$res = $fhplApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
$message = "This TPA has no API service enabled";
return $this->response->setJSON(['status' => false,'message' => $message ]);
}
}
}
// push Claim Files (IR submission)
public function pushClaimFiles($claimId)
{
// $claimId = $this->request->getGet('claim_id');
$data = $this->db->table('ticket_master tm')
->select('tm.id,tm.tpa_id ')->where('tm.id', $claimId)->get()->getRowArray(); // single record
if($data){
$tpaID = $data['tpa_id'];
if ($tpaID == $this->medi_assist_primary_key) { // MediAssist
$mediAssistController = new MediAssistApiController();
return $mediAssistController->IRSubmission($claimId);
}else{
log_message('error', "This ticket id ( {$claimId} ) TPA has no API service enabled. TPA ID : {$tpaID}");
}
}
}
//wellness sso url generator landing
public function getWellnessUrl($emp_id)
{
// $emp_id = $this->request->getGet('emp_id');
$db = \Config\Database::connect();
$data = $db->table('employees e')
->select('pt.policy_type,
e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation,
cp.policy_no as policyNumber, ep.employee_id as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate , cp.wellness_plan_id as planId , cp.wellness_vendor_id')
->join('employee_polices ep', 'e.id = ep.employee_id')
->join('client_policy cp', 'ep.client_policy_id = cp.id')
->join('policy_type pt', 'cp.policy_type_id = pt.id')
->where('e.id', $emp_id)
->where('e.emp_status', 'active')
->where('ep.status', 'active')
->where('e.is_active', 1)
->where('ep.is_active', 1)
->get()
->getResultArray();
$userParams = [];
foreach ($data as $row) {
if($row['wellness_vendor_id'] != null)
{
$vidalApiController = new VidalApiController();
return $vidalApiController->getWellnessSSORedirectUrl($row['email']);
}
else if ($row['planId'] != null) // VISIT
{
$userParams['name'] = $row['name'];
$userParams['email'] = $row['email'];
$userParams['phone'] = $row['phone'];
$userParams['memberId'] = $row['employeeId']; // memberId is unique primary key.
$userParams['gender'] = $row['gender'];
$userParams['dob'] = $row['dob'];
$userParams['relation'] = $row['relation'];
$userParams['policyNumber'] = $row['policyNumber'];
$userParams['employeeId'] = $row['memberId'];
$userParams['policyStartDate']= $row['policyStartDate'];
$userParams['policyEndDate'] = $row['policyEndDate'];
$userParams['policyName'] = $row['policy_type'];
$userParams['planId'] = $row['planId'];
$userParams['moduleName'] = 'home';
break; // stop after first GMC match
}
}
if (empty($userParams)) {
return ['status' => 'failed','message' => 'Coming soon........!'];
}
// echo 'coming';die();
// Derive 32-byte key from SHA256
$derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true);
// Build query string like Node.js
$plainText = '';
foreach ($userParams as $k => $v) {
$plainText .= "&{$k}={$v}";
}
$plainText = ltrim($plainText, '&');
// Encrypt
$algorithm = "aes-256-cbc";
$encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, env('VISIT_IV'));
// Base64URL encode (same as Node.js output)
$output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
$baseURL = env('VISIT_BASE_URL');
$clientId = env('VISIT_CLIENT_ID');
$finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId;
if (!empty($finalUrl)) {
log_message('error', 'VISIT SSO | emp_id: '.$emp_id.' | URL: '.$finalUrl);
return ['status' => 'success','data' => $finalUrl];
} else {
return ['status' => 'failed','message' => 'Coming soon........!'];
}
}
// public function getWellnessUrl()
// {
// $emp_id = $this->request->getGet('emp_id');
// $client_policy_id = $this->request->getGet('client_policy_id');
// $db = \Config\Database::connect();
// // $data = $db->table('employees e')
// // ->select('pt.policy_type,
// // e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation,
// // cp.policy_no as policyNumber, cp.policy_no as employeeId, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate')
// // ->join('employee_polices ep', 'e.id = ep.employee_id')
// // ->join('client_policy cp', 'ep.client_policy_id = cp.id')
// // ->join('policy_type pt', 'cp.policy_type_id = pt.id')
// // ->where('e.id', $emp_id)
// // ->where('e.emp_status', 'active')
// // ->where('ep.status', 'active')
// // ->where('e.is_active', 1)
// // ->where('ep.is_active', 1)
// // ->get()
// // ->getResultArray();
// $data = $db->table('employee_polices ep')
// ->select('pt.policy_type,
// e.name, e.email_corporate as email, e.mobile as phone, e.emp_code as memberId, e.gender, e.dob, e.relationship as relation, e.id as employeeId
// cp.policy_no as policyNumber, cp.policy_start_date as policyStartDate, cp.policy_end_date as policyEndDate, cp.wellness_plan_id as planId')
// ->join('employees e', 'e.id = ep.employee_id')
// ->join('client_policy cp', 'ep.client_policy_id = cp.id')
// ->join('policy_type pt', 'cp.policy_type_id = pt.id')
// ->where('ep.employee_id', $emp_id)
// ->where('ep.client_policy_id', $client_policy_id)
// ->where('ep.status', 'active')
// ->where('ep.is_active', 1)
// ->get()
// ->getRow();
// $userParams = [];
// if(!empty($data))
// {
// $userParams['name'] = $data->name;
// $userParams['email'] = $data->email;
// $userParams['phone'] = $data->phone;
// $userParams['memberId'] = $data->employeeId; // memberId is unique primary key.
// $userParams['gender'] = $data->gender;
// $userParams['dob'] = $data->dob;
// $userParams['relation'] = $data->relation;
// $userParams['policyNumber'] = $data->policyNumber;
// $userParams['employeeId'] = $data->memberId;
// $userParams['policyStartDate']= $data->policyStartDate;
// $userParams['policyEndDate'] = $data->policyEndDate;
// $userParams['policyName'] = 'Nhance ' . $data->policy_type;
// $userParams['planId'] = $data->planId;
// $userParams['moduleName'] = 'home';
// }
// // dd($userParams);
// if (empty($userParams)) {
// return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
// }
// // Derive 32-byte key from SHA256
// $derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true);
// // Build query string like Node.js
// $plainText = '';
// foreach ($userParams as $k => $v) {
// $plainText .= "&{$k}={$v}";
// }
// $plainText = ltrim($plainText, '&');
// // Encrypt
// $algorithm = "aes-256-cbc";
// $encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, env('VISIT_IV'));
// // Base64URL encode (same as Node.js output)
// $output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
// $baseURL = env('VISIT_BASE_URL');
// $clientId = env('VISIT_CLIENT_ID');
// $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId;
// if (!empty($finalUrl)) {
// log_message('error', 'VISIT SSO | emp_id: '.$emp_id.' | URL: '.$finalUrl);
// return $this->respond(['status' => 'success','data' => $finalUrl], 200);
// } else {
// return $this->respond(['status' => 'failed','message' => 'Coming soon........!'], 200);
// }
// }
// function getSSORedirectUrl($email = 'user@example.com')
// {
// // ---------- CONFIG ----------
// $authUrl = env('VIDAL_WELLNESS_BASE_URL'); // Authentication API URL
// $subscriptionKey = env('VIDAL_WELLNESS_SUBSCRIPTION_KEY');
// $apiVersion = "1";
// // Provided Base64 AES key
// $base64Key = env('VIDAL_WELLNESS_BASE64_KEY');
// $key = base64_decode($base64Key);
// // ---------- 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);
// // ---------- STEP 3: Call Authentication API ----------
// $requestBody = json_encode([
// "payload" => $encryptedPayload,
// "source" => "portal",
// "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);
// curl_close($ch);
// $jsonResponse = json_decode($apiResponse, true);
// dd($jsonResponse);
// if (!isset($jsonResponse["data"])) {
// return ["error" => "Invalid API response", "response" => $apiResponse];
// }
// // ---------- STEP 4: Decrypt response ----------
// list($ivBase64, $cipherBase64) = explode(":", $jsonResponse["data"]);
// $respIv = base64_decode($ivBase64);
// $respCipher = base64_decode($cipherBase64);
// $decryptedJson = openssl_decrypt($respCipher, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $respIv);
// $decryptedData = json_decode($decryptedJson, true);
// if (!isset($decryptedData["redirectUrl"])) {
// return ["error" => "redirectUrl missing", "decrypted" => $decryptedData];
// }
// // ---------- FINAL ----------
// return $decryptedData["redirectUrl"];
// }
// Get Claims
public function getClaims($id)
{
if ($id == 1) {
$controller = new VidalApiController();
} elseif ($id == 2) {
$controller = new ICICILombardController();
} elseif ($id == 3) {
$controller = new MediAssistApiController();
}
}
// Get UHID
public function getUhid($id)
{
if ($id == 1) {
$controller = new VidalApiController();
} elseif ($id == 2) {
$controller = new ICICILombardController();
} elseif ($id == 3) {
$controller = new MediAssistApiController();
}
}
// Push Enrollment
public function pushEnrollment($id)
{
if ($id == 1) {
$controller = new VidalApiController();
} elseif ($id == 2) {
$controller = new ICICILombardController();
} elseif ($id == 3) {
$controller = new MediAssistApiController();
}
}
// Get Hospital Network
public function getHospitalNetwork($id)
{
if ($id == 1) {
$controller = new VidalApiController();
} elseif ($id == 2) {
$controller = new ICICILombardController();
} elseif ($id == 3) {
$controller = new MediAssistApiController();
}
}
}