nhance/app/Controllers/ApiServiceController.php
2026-07-29 16:59:35 +05:30

1003 lines
42 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\Controllers\VoloApiController;
use App\Models\BatchFileModel;
use App\Models\ClaimFilesModel;
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 $claimFilesModel;
protected $medi_assist_primary_key;
protected $vidal_primary_key;
protected $icici_primary_key;
protected $fhpl_primary_key;
protected $health_india_primary_key;
protected $volo_primary_key;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->claimFilesModel = new ClaimFilesModel();
$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');
$this->health_india_primary_key = getenv('HEALTH_INDIA_PRIMARY_KEY_CONSTANT');
$this->volo_primary_key = getenv('VOLO_PRIMARY_KEY_CONSTANT');
}
// Push Claims
public function pushClaims($claimId)
{
helper('tpa_claim_push_log');
init_tpa_claim_push_logs($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 if ($tpaID == $this->health_india_primary_key)
{ // health india
$healthIndiaApiController = new HealthIndiaApiController;
return $healthIndiaApiController->SubmitClaim($claimId);
}else if ($tpaID == $this->volo_primary_key)
{ // Volo / TrueCover (EWA)
$voloApiController = new VoloApiController();
return $voloApiController->SubmitClaim($claimId);
}else{
tpa_claim_push_log($claimId, "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 ?? ""));
}
log_message('error', 'Ecard Request started | client_policy_id: '.$client_policy_id.' | policyNo: '.$policy_no.' | emp_code: '.$emp_code.' | type: '.$type);
// $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();
log_message('error', 'Ecard Request - Employee data fetched | count: '.count($employee_policy).' | type: '.$type);
if(count($employee_policy) > 0)
{
if($employee_policy[0]['tpa_id'] != null)
{
log_message('error', 'Ecard Request - tpa_id found | tpa_id: '.$employee_policy[0]['tpa_id'].' | type: '.$type);
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($employee_policy[0]['tpa_primary_id'] == $this->health_india_primary_key)// health india
{
$healthIndiaApiController = new HealthIndiaApiController;
$data['eCardDownload'] = $healthIndiaApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}else if($employee_policy[0]['tpa_primary_id'] == $this->volo_primary_key)// Volo / TrueCover
{
$voloApiController = new VoloApiController();
$data['eCardDownload'] = $voloApiController->EcardRequest( $emp_code, $policy_no , $employee_policy[0]['tpa_id'] );
}
if (empty($data['eCardDownload'])) {
$data['eCardDownload'] = $this->buildDefaultEcardDownloadUrl(
$employee_policy[0]['rand_string'],
$type,
$all_member ?? null
);
}
$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){
}
}
private function buildDefaultEcardDownloadUrl(string $randString, string $type = 'download', $allMember = null): string
{
if ($type === 'download') {
return base_url('download-e-card/') . $randString . '/1';
}
if (!empty($allMember)) {
return base_url('download-e-card/') . $randString . '/1/1';
}
return base_url('download-e-card/') . $randString . '/0/1';
}
// 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('tata');
// die();
// $mediAssistController = new MediAssistApiController();
// $mediAssistController->MediAssistGetBenefDetails( [ 'policy_no' => '97000063250400000012', 'file_id' =>'5704','client_policy_id' => '1839' ] );
// $mediAssistController->MediAssistGetBenefDetails( [ 'policy_no' => '97000063250400000016', 'file_id' =>'5704','client_policy_id' => '2002' ] );
// die();
// $vidalApiController = new VidalApiController;
// $vidalApiController->VidalGetBenefDetails( [ 'policy_no' => '570000/48/2026/363', 'file_id' =>'5264','client_policy_id' => '9433'] );
// $fhplApiController = new FhplApiController;
// $fhplApiController->FhplGetBenefDetails( [ 'policy_no' => '570000/48/2026/453', 'file_id' =>'9999','client_policy_id' => '3557'] );
// $healthIndiaApiController = new HealthIndiaApiController;
// $healthIndiaApiController->HealthIndiaGetBenefDetails( [ 'policy_no' => '97000063250400000116', 'file_id' =>'9998','client_policy_id' => '6523'] );
// 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
->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
->where('client_policy.tpa_id', $tpa_id)
->where('batch_files.is_active', 1)
->where('batch_files.event_type', 'api')
->where('batch_files.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 if ($tpa_id == $this->health_india_primary_key) // health india
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
// $healthIndiaApiController = new HealthIndiaApiController;
// $healthIndiaApiController->HealthIndiaGetBenefDetails( [ 'polict_no' => $policy_no, 'file_id' =>$file_id ] );
$r = Jobs::addJob(['job_name' => 'HealthIndiaGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "HealthIndiaGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->volo_primary_key) // Volo / TrueCover
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
$r = Jobs::addJob(['job_name' => 'VoloGetBenefDetails', 'payload' => ['policy_no' => $policy_no, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "VoloGetBenefDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}else if ($tpa_id == $this->icici_primary_key) // ICICI Lombard (EWA)
{
$file_id = $fileModel->insert($data);
log_message('error', "ICICI - Files table inserted successfully, File id : {$file_id}");
$r = Jobs::addJob(['job_name' => 'getEnrollmentBatchStatus', 'payload' => ['client_policy_id' => $policy_id, 'file_id' => $file_id, 'client_policy_id' => $policy_id, 'return_type' => 'job']]);
log_message('error', "ICICI - getEnrollmentBatchStatus 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 if ($tpaID == $this->health_india_primary_key) { // health india
$healthIndiaApiController = new HealthIndiaApiController;
$res = $healthIndiaApiController->ClaimDetail($claimId);
return $this->response->setJSON(['status' => $res['status'],'message' => $res['message'] ]);
}else if ($tpaID == $this->volo_primary_key) { // Volo / TrueCover
$voloApiController = new VoloApiController();
$res = $voloApiController->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 if ($tpaID == $this->vidal_primary_key) { // Vidal
$vidalApiController = new VidalApiController();
return $vidalApiController->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,ep.id, 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)
->where('ep.wellness_onboard != 0')
->get()
->getResultArray();
$userParams = [];
foreach ($data as $row) {
if($row['wellness_vendor_id'] == $this->vidal_primary_key)
{
$vidalApiController = new VidalApiController();
return $vidalApiController->getWellnessSSORedirectUrl($row['email']);
}else if ($row['wellness_vendor_id'] == $this->medi_assist_primary_key)
{
$mediAssistController = new MediAssistApiController();
return $mediAssistController->getWellnessSSORedirectUrl($row['planId'], $row['memberId']);
}
else if ($row['planId'] != null && empty($row['wellness_vendor_id'])) // VISIT
{
//OLD PARAMS
// $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';
//NEW PARAMS
$userParams['memberId'] = $row['id']; // employee policy primary key (which used while onboard)from DB
$userParams['phone'] = $row['phone'];
$userParams['email'] = $row['email'];
$userParams['relationship'] = $row['relation'];
$userParams['gender'] = $row['gender'] == 'M' ? 'Male' : 'Female';
$userParams['dob'] = $row['dob'];
$userParams['policyNumber'] = $row['policyNumber'];
$userParams['policyStartDate'] = $row['policyStartDate'];
$userParams['policyEndDate'] = $row['policyEndDate'];
$userParams['plan'] = $row['planId'];
$userParams['source'] = 'NAHANCE';
$userParams['employeeId'] = $row['memberId'];
$userParams['firstName'] = $row['name'];
$userParams['middleName'] = '';
$userParams['lastName'] = '';
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........!'];
}
}
/**
* Decrypt Visit SSO userParams (reverse of Visit encryption in getWellnessUrl).
* Accepts encrypted string or full SSO URL via POST/GET as userParams or encrypted_sso.
*/
public function decryptVisitSso()
{
$encrypted = $this->request->getGet('encrypted_sso');
if (empty($encrypted)) {
return $this->response->setJSON([
'status' => false,
'message' => 'userParams or encrypted_sso is required',
]);
}
$result = $this->decryptVisitSsoParams($encrypted);
if ($result === false) {
return $this->response->setJSON([
'status' => false,
'message' => 'Decryption failed. Check encrypted value and VISIT_SECRET_KEY / VISIT_IV.',
]);
}
return $this->response->setJSON([
'status' => true,
'data' => $result['params'],
'plainText' => $result['plainText'],
]);
}
/**
* Decrypt Visit SSO payload using the same key/IV as getWellnessUrl Visit branch.
*
* @param string $encrypted Base64URL userParams value or full SSO URL containing userParams=
* @return array{plainText: string, params: array}|false
*/
private function decryptVisitSsoParams(string $encrypted)
{
if (strpos($encrypted, 'userParams=') !== false) {
$query = [];
parse_str(parse_url($encrypted, PHP_URL_QUERY) ?? '', $query);
$encrypted = $query['userParams'] ?? '';
}
$encrypted = trim($encrypted);
if ($encrypted === '') {
return false;
}
$base64 = strtr($encrypted, '-_', '+/');
$base64 .= str_repeat('=', (4 - strlen($base64) % 4) % 4);
$cipherRaw = base64_decode($base64, true);
if ($cipherRaw === false) {
return false;
}
$derivedKey = hash('sha256', env('VISIT_SECRET_KEY'), true);
$plainText = openssl_decrypt(
$cipherRaw,
'aes-256-cbc',
$derivedKey,
OPENSSL_RAW_DATA,
env('VISIT_IV')
);
if ($plainText === false) {
return false;
}
$params = [];
parse_str($plainText, $params);
return [
'plainText' => $plainText,
'params' => $params,
];
}
/**
* Manual TPA Claim Push - accepts claim_id via POST and delegates to pushClaims().
* Returns the response from pushClaims() as the API response.
*/
public function manualTpaClaimPush()
{
$claimId = $this->request->getPost('claim_id');
if (empty($claimId)) {
return $this->response->setJSON([
'status' => false,
'message' => 'claim_id is required'
]);
}
if (! $this->claimFilesModel->hasPdfFileForTicket($claimId)) {
return $this->response->setJSON([
'status' => false,
'message' => 'No PDF file found for this claim'
]);
}
$result = $this->pushClaims($claimId);
if ($result !== null && is_array($result)) {
return $this->response->setJSON([
'status' => $result['status'] ?? false,
'message' => $result['message'] ?? ($result['status'] ? 'Claim pushed successfully' : 'Claim push failed')
]);
}
return $this->response->setJSON([
'status' => false,
'message' => 'Claim push failed or TPA has no API service enabled for this ticket.'
]);
}
// 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"];
// }
public function sendDataToTPA()
{
$requested_data = $this->request->getPost() ?? [];
log_message('error', "getTPAID payloads :" . json_encode($requested_data));
$tpa_id = $requested_data['tpa_id'] ?? null;
$policy_no = $requested_data['policy_no'] ?? null;
$client_id = $requested_data['client_id'] ?? null;
$branch_id = $requested_data['client_branch_id'] ?? null;
$policy_id = $requested_data['client_policy_id'] ?? null;
$event = $requested_data['event'] ?? null;
$event_mapping = [
'inception' => 'A',
'missed_inception' => 'A',
'addition' => 'A',
'dependent_addition' => 'A',
'deletion' => 'D',
'correction' => 'M',
'si_enhancement' => 'M'
];
$fileModel = new BatchFileModel();
$filesData = $fileModel
->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
->where('client_policy.tpa_id', $tpa_id)
->where('batch_files.is_active', 1)
->where('batch_files.event_type', 'api')
->where('batch_files.client_policy_id', $policy_id)
->where('batch_files.icici_status_flag !=', 'COMPLETED')
->countAllResults();
if($filesData > 0){
log_message('error', "TPA initiation is in progress.");
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' => 'No employee to upload','data' => [] ]);
}
$data = [
'file_name' => "API - Employee data push",
'event_type' => $event,
'actions' => "push",
'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->icici_primary_key) // MediAssist
{
$file_id = $fileModel->insert($data);
log_message('error', "Files table inserted successfully, File id : {$file_id}");
$requested_data['file_id'] = $file_id;
$requested_data['return_type'] = 'job';
$requested_data['insurer_or_tpa'] = 'tpa';
$requested_data['flag_status'] = $event_mapping[$event] ?? "A";
// $ICICILombardController = new ICICILombardController();
// $apiResponse = $ICICILombardController->ICICIPushEmployeeDetails($requested_data);
$r = Jobs::addJob(['job_name' => 'ICICIPushEmployeeDetails', 'payload' => $requested_data]);
log_message('error', "ICICIPushEmployeeDetails job pushed successfully.");
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Action Triggered','data' => [] ]);
}
}
}