db = \Config\Database::connect(); $this->vidal_primary_key = getenv('VIDAL_PRIMARY_KEY_CONSTANT'); } 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 = null) //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)); $this->db->table('ticket_master') ->where('id',$claimId) ->update([ 'tpa_push_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 , 'claim_number' => $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"]]; } public function ClaimDetail($claimId = null) //234 { 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').'', ]; // Fetch ticket master details $ticket = $this->db->table('ticket_master tm') ->select(" tm.id, tm.tpa_no as memberId, tm.tpa_claim_push_reference_no as claimRefNo, tm.tpa_claim_id as claimID, cp.policy_no as policyNo, cp.policy_start_date as startDate, cp.policy_end_date as endDate, e.emp_code as employeeCode ") ->join('employees e', 'e.id = tm.emp_id', 'left') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); if (!$ticket) { return ['status' => false,'message' => 'Invalid Claim ID' ]; } $body = []; // REQUEST BODY if($ticket['claimID'] != null) { $body = [ 'empNO' => "", 'tpaCardID' => "", 'claimID' => $ticket['claimID'], 'emailID' => "", 'mobileNO' => "", ]; } $response = call_third_party_api($url, $method, $headers, $body); // dd($response); if ($response['status'] != true || empty($response['data']['data']['claims'][0])) { log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response)); return ['status' => false, 'message' => 'API call failed.','data' => $response]; } // Extract claim status $claimData = $response['data']['data']['claims'][0]; $currentStatus = $claimData['status'] ?? ''; // VALID STATUS LIST $validStatuses = [ "In-Progress" => 5, "Required Information" => 4, "Paid" => 11, "Rejected" => 8, "Approved" => 8, ]; // Maping tpa claim status with local claim Status if (isset($validStatuses[$currentStatus])) { $updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'updated_at' => date('Y-m-d H:i:s')]; }else{ $updateArray = ['tpa_claim_status' => $currentStatus , 'updated_at' => date('Y-m-d H:i:s')]; } // UPDATE ticket_master $this->db->table('ticket_master')->where('id', $claimId)->update($updateArray); // LOG UPDATE log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); return ['status' => true,'message' => 'Claim status updated.','updated_status' => $currentStatus,'api_response' => $response]; } public function ClaimStatusUpdate() { 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').'', ]; // Fetch ticket master details $TicketData = $this->db->table('ticket_master tm') ->select(" tm.id, tm.tpa_no as memberId, tm.tpa_claim_push_reference_no as claimRefNo, tm.tpa_claim_id as claimNo, cp.policy_no as policyNo, cp.policy_start_date as startDate, cp.policy_end_date as endDate, e.emp_code as employeeCode ") ->join('employees e', 'e.id = tm.emp_id', 'left') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') ->where('tm.tpa_claim_push_reference_no IS NOT NULL') ->where('tm.is_active', 1) ->whereNotIn('tm.claim_status_id', [8, 11, 12, 13, 66, 22, 24, 47, 49, 32, 34, 53, 55, 42, 44, 58, 60]) ->where('tm.tpa_id', $this->vidal_primary_key) ->get() ->getResultArray(); // dd($TicketData); if (!$TicketData) { log_message('error', "Claims not found to update status"); return $this->response->setJSON(['status' => false,'message' => 'Claims not found' ]); } $error_data = []; $status_updated_count = 0; foreach ($TicketData as $key => $ticket) { $claimId = $ticket['id']; $body = []; // REQUEST BODY if($ticket['claimNo'] != null) { $body = [ 'empNO' => "", 'tpaCardID' => "", 'claimID' => $ticket['claimNo'], 'emailID' => "", 'mobileNO' => "", ]; } // CALL API $response = call_third_party_api($url, $method, $headers, $body); if ($response['status'] != true || empty($response['data']['data']['claims'][0])) { log_message('error', 'CLAIM STATUS FAILED | for ticket ID: ' . $claimId.' | response: '.json_encode($response)); $error_data[$claimId][['status' => false,'message' => 'API call failed.','data' => $response]]; } // Extract claim status $claimData = $response['data']['data']['claims'][0]; $currentStatus = $claimData['status'] ?? ''; // VALID STATUS LIST $validStatuses = [ "In-Progress" => 5, "Required Information" => 4, "Paid" => 11, "Rejected" => 8, "Approved" => 8, ]; // Maping tpa claim status with local claim Status if (isset($validStatuses[$currentStatus])) { $updateArray = ['claim_status_id' => $validStatuses[$currentStatus] , 'tpa_claim_status' => $currentStatus , 'updated_at' => date('Y-m-d H:i:s')]; }else{ $updateArray = ['tpa_claim_status' => $currentStatus , 'updated_at' => date('Y-m-d H:i:s')]; } // UPDATE ticket_master $this->db->table('ticket_master')->where('id', $claimId)->update($updateArray); // LOG UPDATE log_message('error', "CLAIM STATUS SUCCESS | Updated ticket ID $claimId with claim status: $currentStatus"); $status_updated_count ++; } return $this->response->setJSON([ 'status' => true, 'message' => 'Claim status updated.', 'updated_status' => $currentStatus, 'api_response' => $response, 'count' => $status_updated_count, 'error_data' => $error_data, ]); } public function EcardRequest($employeeId = null, $policyNo = null , $tpaNo = 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' => $tpaNo, 'claimID' => "", 'emailID' => "", 'mobileNO' => "", ]; // $body = [ // 'empNO' => "", // 'tpaCardID' => "BLR-NI-H0351-03925-0030320-A", // 'claimID' => "", // 'emailID' => "", // 'mobileNO' => "", // ]; $response = call_third_party_api($url, $method, $headers, $body); // dd($response); if($response['status'] != true){ log_message('error', 'Ecard Request FAILED | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | response: '.json_encode($response)); return null; } $ecardUrl = $response['data']['data']['dependents'][0]['ecardLink'] ?? null; if(!empty($ecardUrl)){ log_message('error', 'Ecard Request PUSH SUCCESS | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | ecardUrl: '.$ecardUrl); return $ecardUrl; } else { log_message('error', 'Ecard Request SUCCESS BUT ecardUrl EMPTY | employeeId: '.$employeeId.' | policyNo: '.$policyNo.' | response: '.json_encode($response)); return null; } } public function VidalGetBenefDetails($requestData) { $function_calling_type = $requestData['return_type'] ?? 'job'; try { 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').'', ]; $policyNo = $requestData['policy_no'] ?? null; $client_policy_id = $requestData['client_policy_id'] ?? null; if (empty($policyNo)) { log_message('error', 'TPA ID PULL | policy_no missing in request'); if($function_calling_type == "job"){ return ['status' => false, 'message' => 'policy_no required']; }else{ return $this->respond(['status' => false, 'message' => 'policy_no required']); } } if (empty($client_policy_id)) { log_message('error', 'TPA ID PULL | client_policy_id missing in request'); if($function_calling_type == "job"){ return ['status' => false, 'message' => 'client_policy_id required']; }else{ return $this->respond(['status' => false, 'message' => 'client_policy_id required']); } } log_message('error', "TPA ID PULL | called for policy_no: {$policyNo} , client_policy_id: {$client_policy_id}"); // Fetch file download dates $batchFiles = $this->db->table('batch_files f') ->select("f.created_at") ->where('f.client_policy_id', $client_policy_id) ->where('f.insurer_or_tpa', 'tpa') ->where('f.actions', 'export') ->get() ->getResultArray(); // dd($batchFiles); if (empty($batchFiles)) { log_message('error', 'TPA ID PULL FAILED | batchFiles is empty for this tpa id pull request'); if($function_calling_type == "job"){ return ['status' => false, 'message' => 'batchFiles not found']; }else{ return $this->respond(['status' => false, 'message' => 'batchFiles not found']); } } $allBenef = []; foreach ($batchFiles as $key => $value) { $createdAt = new \DateTime($value['created_at']); $startDate = $createdAt->format('d/m/Y'); $endDateObj = clone $createdAt; $endDateObj->modify('+2 days'); $endDate = $endDateObj->format('d/m/Y'); $body = [ 'policyNO' => $policyNo, 'startDate' => $startDate, 'endDate' => $endDate ]; // $body = [ 'empNO' => "Mem 1" ]; log_message('error', "TPA ID PULL | API parems " . json_encode([$url, $method, $headers, $body])); $response = call_third_party_api($url, $method, $headers, $body); if ($response['status'] != true) { // update file table status after the tpa id failed to update if (isset($requestData['file_id']) && !empty($requestData['file_id'])) { $file_model = new BatchFileModel(); $file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update(); log_message('error', "Files table status updated for the file id : {$requestData['file_id']}"); } else { log_message('error', "Failed to update file table status."); } log_message('error', 'TPA ID PULL API FAILED | API failed: ' . json_encode($response)); if($function_calling_type == "job"){ return ['status' => false, 'message' => 'API call failed', 'data' => $response]; }else{ return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $response]); } } $data = $response['data']['data'] ?? []; if (!isset($data['dependents'])) { log_message('error', "TPA ID PULL FAILED |: 'benefDetails' missing in API response: " . json_encode($data)); break; } $fetchedCount = count($data['dependents']); log_message('error', "Fetched {$fetchedCount} records "); $allBenef = array_merge($allBenef, $data['dependents']); } // dd($allBenef ); //save API data as JSON for analysis $json = json_encode($allBenef, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); // $filename = time() . '.json'; $filePath = WRITEPATH . 'tmp/'.time().'_'.$requestData['file_id'].'.json'; file_put_contents($filePath, $json); //call a job for dump JSON data to DB $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'saveVidalAPIData', 'payload' => [ 'file_id' => $requestData['file_id'],'json_file_path' => $filePath ]]); // now update DB $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', $client_policy_id) ->findAll(); $batch_file_success = 'success'; $updated = 0; $totalCount = count($employeePolicyData); $employee_policy_ids = []; foreach ($employeePolicyData as $policy_data) { $hasMatchForThisPolicy = false; foreach ($allBenef as $row) { if ( strtolower(trim($policy_data['name'] ?? '')) == strtolower(trim($row['name'] ?? '')) && ($policy_data['emp_code'] ?? '') == ($row['empNo'] ?? '') && strtolower(trim($policy_data['relationship'] ?? '')) == strtolower(trim(str_replace('-', ' ', $row['relationship'] ?? ''))) && ($policy_data['gender'] ?? '') == ($row['gender'] ?? '') && ($policy_data['dob'] ?? '') == (change_date_format($row['dob'], 'Y-m-d H:i:s') ?? '') ) { $hasMatchForThisPolicy = true; // log_message('error', "✅ Match found: emp_code={$row['empNo']} policy={$row['policyNumber']}"); $sql = "UPDATE employee_polices SET tpa_id = ? WHERE id = ?"; $this->db->query($sql, [$row['enrollmentId'], $policy_data['emp_policy_id']]); // for e-card send if(strtolower(trim($policy_data['relationship'])) == 'self'){ $employee_policy_ids[] = $policy_data['emp_policy_id']; } if ($this->db->affectedRows() > 0) { $updated++; log_message('error', "✅ Updated tpa_id={$row['enrollmentId']} for emp_code={$row['empNo']} policy={$row['policyNumber']}"); } else { log_message('error', "⚠️ No update (already set or not matched) for emp_code={$row['empNo']} policy={$row['policyNumber']}"); } } } // Handle NO MATCH for this policy if (!$hasMatchForThisPolicy) { $nhanceSideData = [ 'name' => $policy_data['name'] ?? null, 'emp_code' => $policy_data['emp_code'] ?? null, 'relationship' => $policy_data['relationship'] ?? null, 'gender' => $policy_data['gender'] ?? null, 'dob' => $policy_data['dob'] ?? null, ]; $batch_file_success = 'partially success'; log_message( 'error', "❌ No match for Nhance = " . json_encode($nhanceSideData) ); } } // send e-card if(!empty($employee_policy_ids)){ log_message('error', "sendMailForDownloadingECard JOB PUSHED."); Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => ['ids' => $employee_policy_ids, 'client_policy_id' => $client_policy_id]]); } // update file table status after the tpa id successfully updated if (isset($requestData['file_id']) && !empty($requestData['file_id'])) { $file_model = new BatchFileModel(); $file_model->where('id', $requestData['file_id'])->set('status', $batch_file_success)->update(); log_message('error', "Files table status updated for the file id : {$requestData['file_id']}"); } else { log_message('error', "Failed to update file table status."); } log_message('error', "TPA ID PULL SUCCESS | completed. Total fetched={$totalCount}, updated={$updated}"); if($function_calling_type == "job"){ return [ 'status' => true, 'message' => 'Updated successfully', 'total_fetched' => $totalCount, 'total_updated' => $updated ]; }else{ return $this->respond([ 'status' => true, 'message' => 'Updated successfully', 'total_fetched' => $totalCount, 'total_updated' => $updated ]); } } catch (\Throwable $th) { // update file table status after the tpa id failed to update if (isset($requestData['file_id']) && !empty($requestData['file_id'])) { $file_model = new BatchFileModel(); $file_model->where('id', $requestData['file_id'])->set('status', 'failed-8')->update(); log_message('error', "Files table status updated for the file id : {$requestData['file_id']}"); } else { log_message('error', "Failed to update file table status."); } $errorData = [ 'message' => $th->getMessage(), 'file' => $th->getFile(), 'line' => $th->getLine(), 'code' => $th->getCode(), 'trace' => $th->getTraceAsString(), 'trace_array' => $th->getTrace(), // full array version (optional) 'function' => $th->getTrace()[0]['function'] ?? null, 'class' => $th->getTrace()[0]['class'] ?? null, ]; log_message('error', 'Exception thrown while calling GetBenefDetails API: ' . json_encode($errorData)); if($function_calling_type == "job"){ return ['status' => false, 'message' => 'API call failed', 'data' => $errorData]; }else{ return $this->respond(['status' => false, 'message' => 'API call failed', 'data' => $errorData]); } } } }