nhance/app/Controllers/EmployeeRestController.php

8166 lines
388 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Controllers\EmployeeServiceController;
use App\Controllers\Jobs;
use App\Controllers\MediAssistApiController;
use App\Controllers\TicketController;
use App\Helpers\JWTToken;
use App\Helpers\MailHelper;
use App\Helpers\sendMailNotification;
use App\Models\AddImgModel;
use App\Models\AuditHistoryModel;
use App\Models\BatchFileModel;
use App\Models\ClaimFilesModel;
use App\Models\ClientBranchModel;
use App\Models\ClientDepositModel;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\EmployeeRetailPolicy;
use App\Models\FEContentModel;
use App\Models\FileModel;
use App\Models\HRAccessControlModel;
use App\Models\HrFileUploadModel;
use App\Models\InsurerModel;
use App\Models\NotificationModel;
use App\Models\PolicesModel;
use App\Models\PolicyPremium1Model;
use App\Models\PolicyPremium2Model;
use App\Models\PolicyTransactionModel;
use App\Models\PolicyTypeModel;
use App\Models\PTFileModel;
use App\Models\RelationshipModel;
use App\Models\TicketClaimStatusModel;
use App\Models\TicketMailTemplateModel;
use App\Models\TicketMasterModel;
use App\Models\TicketMessageModel;
use App\Models\TpaApiSeviceModel;
use App\Models\UserActivityHistoryModel;
use App\Models\UserModel;
use CodeIgniter\API\ResponseTrait;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class EmployeeRestController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $clientRMModel;
protected $fileModel;
protected $policesModel;
protected $relationshipModel;
protected $clientPolicyModel;
protected $policyPremium1Model;
protected $policyPremium2Model;
protected $policyTypeModel;
protected $notificationModel;
protected $userModel;
protected $feContentModel;
protected $addImgModel;
protected $clientBranchModel;
protected $auditHistoryModel;
protected $claimStatusModel;
protected $ticketMaster;
protected $ticketMessage;
protected $ticketController;
protected $hrAccessControlModel;
protected $insurerModel;
protected $hrFileUploadModel;
protected $ticketMailTemplateModel;
protected $employeeRetailPolicy;
protected $batchFileModel;
protected $UserActivityHistoryModel;
public function __construct()
{
// helper('utility');
set_session_context('Employee');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->clientRMModel = new ClientRMModel();
$this->policesModel = new PolicesModel();
$this->relationshipModel = new RelationshipModel();
$this->fileModel = new FileModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->policyPremium1Model = new PolicyPremium1Model();
$this->policyPremium2Model = new PolicyPremium2Model();
$this->policyTypeModel = new PolicyTypeModel();
$this->notificationModel = new NotificationModel();
$this->userModel = new UserModel();
$this->feContentModel = new FEContentModel();
$this->addImgModel = new AddImgModel();
$this->clientBranchModel = new ClientBranchModel();
$this->auditHistoryModel = new AuditHistoryModel();
$this->claimStatusModel = new TicketClaimStatusModel();
$this->ticketMaster = new TicketMasterModel();
$this->ticketMessage = new TicketMessageModel();
$this->employeeRetailPolicy = new EmployeeRetailPolicy();
$this->ticketController = new TicketController();
$this->hrAccessControlModel = new HRAccessControlModel();
$this->insurerModel = new InsurerModel();
$this->hrFileUploadModel = new HrFileUploadModel();
$this->ticketMailTemplateModel = new TicketMailTemplateModel();
$this->batchFileModel = new BatchFileModel();
$this->UserActivityHistoryModel = new UserActivityHistoryModel();
}
public function getEmployeeProfile()
{
try {
$emp_code = $this->request->getGet('emp_code');
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
if ($emp_code) {
$relationship = 'self';
// $employee = $this->employeeModel->where('emp_code', $emp_code)
// ->where('client_id', $client_id)
// ->where('client_branch_id', $client_branch_id)
// ->where('is_active', 1 )
// ->where('relationship', $relationship)
// ->first();
$employee = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.emp_code', $emp_code)
->where('employees.client_id', $client_id)
->where('employees.client_branch_id', $client_branch_id)
->where('employees.is_active', 1)
->where('employees.relationship', $relationship)
->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.is_active', 1)
->whereIn('employees.emp_status', ['active', 'expired'])
->first();
if (null !== $this->request->getGet('client_policy_id')) {
$date_coverage = $this->employeePolicyModel->where('employee_id', $employee['id'])->where('client_policy_id', $this->request->getGet('client_policy_id'))->get()->getRow()->date_coverage;
$employee['date_coverage'] = $date_coverage;
}
$result = $employee;
$AccountManagerDetails = $this->clientRMModel->select('client_rm.* , user_profiles.*')
->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left')
->where('client_rm.client_id', $client_id)
->where('client_rm.level', 3)
->findAll();
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'AccountManagerDetails' => isset($AccountManagerDetails[0]) ? $AccountManagerDetails[0] : null], 200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
//not in use
public function editEmployeeProfile()
{
try {
$data = $this->request->getJSON();
if ($data) {
$id = $data->id;
$employee = $this->employeeModel->where('is_active', 1)->update($id, $data);
if ($employee) {
$result = [];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
//not in use
public function getEmployeeAndDependence()
{
try {
$emp_code = $this->request->getGet('emp_code');
if ($emp_code) {
$employee = $this->employeeModel->where('is_active', 1)->where('emp_code', $emp_code)->findAll();
$dateConverter = function ($item) {
if ($item['dob'] !== '0000-00-00') {
$dateTime = \DateTime::createFromFormat('Y-m-d', $item['dob']);
$item['dob'] = $dateTime->format('d-m-Y');
}
return $item;
};
$employee = array_map($dateConverter, $employee);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $employee], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
//not in use
public function editEmployeeAndDependence()
{
try {
$data = $this->request->getJSON();
if ($data) {
$updatedCount = 0;
foreach ($data as $item) {
$id = $item->id;
$item->dob = $this->convertDateFormatYMD($item->dob);
$employee = $this->employeeModel->where('is_active', 1)->update($id, (array) $item);
if ($employee) {
$updatedCount++;
}
}
if ($updatedCount > 0) {
$result = [];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e], 500);
}
}
public function addEmployeeAndDependence()
{
try {
$data = $this->request->getJSON();
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($data[0]->client_policy_id);
if ($openForEnrollment == false) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Enrollment closed'], 200);
}
if ($data) {
$Count = 0;
foreach ($data as $item) {
if (isset($item->id)) {
//update old data
$id = $item->id;
$item->family_floater_key = $this->RelationshipMap($item->relationship);
$item->gender = $this->GenderMap($item->relationship, $item->emp_code);
$item->dob = $this->convertDateFormatYMD($item->dob);
$item->emp_status = 'draft';
$employee = $this->employeeModel->where('is_active', 1)->update($id, (array) $item);
if ($employee) {
$Count++;
}
} else {
//create new data
$item->family_floater_key = $this->RelationshipMap($item->relationship);
$item->gender = $this->GenderMap($item->relationship, $item->emp_code);
$item->dob = $this->convertDateFormatYMD($item->dob);
$item->emp_status = 'draft';
$employee = $this->employeeModel->insert($item);
if ($employee) {
$Count++;
}
}
}
if ($Count > 0) {
if (isset($data[0]->id)) {
$this->createEmployeePolicyData($data[0]->id, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si);
} else {
$payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id, $data[0]->relationship);
$this->createEmployeePolicyData($employee, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si, $payable_employee);
}
$this->updatePremiumAmount($data[0]->client_policy_id, $data[0]->emp_code, $data[0]->client_branch_id);
$result = [];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function getEmployeePayableValue($client_policy_id, $relationship)
{
$terms = $this->clientPolicyModel->where('id', $client_policy_id)->get()->getRow()->policy_terms;
if (isset(json_decode($terms)->is_payable_employee)) {
$is_payable_obj = json_decode($terms)->is_payable_employee;
if ($relationship === 'Mother' || $relationship === 'Father' || $relationship === 'Father in Law' || $relationship === 'Mother in Law') {
return $is_payable_obj->elders;
} else if ($relationship === 'Son' || $relationship === 'Daughter') {
return $is_payable_obj->childern;
} else if ($relationship === 'Spouse') {
return $is_payable_obj->spouse;
}
} else {
return 0;
}
}
public function createEmployeePolicyData($employee_id, $emp_code, $client_id, $client_policy_id, $basic_cover_si = null, $payable_employee = 0, $extra_data = [])
{
$client_policy = $this->clientPolicyModel->where('id', $client_policy_id)->where('client_id', $client_id)->first();
$policy_terms = json_decode($client_policy['policy_terms']);
$dependent_effective_date = $extra_data['dependent_effective_date'] ?? null;
$hr_id = $extra_data['hr_id'] ?? null;
$self_data = $this->employeeModel
->select('employees.id')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employees.emp_code', $emp_code)
->where('employees.client_id', $client_id)
->where('employees.relationship', 'self')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->first();
if ($basic_cover_si == null) {
$basic_cover_si = $policy_terms->sum_insured;
}
$checkDataExist = $this->employeePolicyModel->where('employee_id', $employee_id)->where('client_policy_id', $client_policy_id)->first();
if ($checkDataExist) {
$data = [
'basic_cover_si' => $basic_cover_si,
'updated_by' => $self_data['id'] ?? null,
];
if (!empty($dependent_effective_date)) {
$data['date_coverage'] = $this->convertDateFormatYMD($dependent_effective_date);
}
$this->employeePolicyModel
->where('client_policy_id', $client_policy_id)
->where('employee_id', $employee_id)
->where('is_active', 1)
->set($data)->update();
} else {
$data['employee_id'] = $employee_id;
$data['client_policy_id'] = $client_policy_id;
$data['basic_cover_si'] = $basic_cover_si;
$data['payable_employee'] = $payable_employee;
$data['policy_end_date'] = $client_policy['policy_end_date'];
$data['date_coverage'] = $this->convertDateFormatYMD($dependent_effective_date);
$data['status'] = 'pending_approval';
$data['created_by'] = $hr_id ?? $self_data['id'] ?? null;
$data['emp_policy_created_by'] = $hr_id ? "HR" : 'USER';
$this->employeePolicyModel->insert($data);
}
return true;
}
public function updatePremiumAmount($client_policy_id, $emp_code, $client_branch_id)
{
$response = $this->calculatePremium($client_policy_id, $emp_code, null, $client_branch_id);
if (count($response[$emp_code])) {
foreach ($response[$emp_code] as $key => $value) {
if (isset($value['temp'])) {
$checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])
->where('client_policy_id', $value['policy_details']['client_policy_id'])
->where('is_active', 1)
->findAll();
if ($checkIfExist) {
$this->employeePolicyModel
->where('client_policy_id', $value['policy_details']['client_policy_id'])
->where('employee_id', $value['temp']['emp_id'])
->where('is_active', 1)
->set(['basic_cover_si' => $value['policy_details']['basic_cover_si'], 'premium' => $value['policy_details']['premium'], 'rata_premimum' => $value['policy_details']['rata_premimum'], 'gst' => $value['policy_details']['gst']])
->update();
}
}
}
}
}
public function getEmployeeCoverageDate($emp_code, $client_policy_id)
{
$empData = $this->employeeModel->where('emp_code', $emp_code)->where('relationship', 'self')->where('is_active', 1)->first();
if ($empData) {
$empPolicyData = $this->employeePolicyModel->select('employee_polices.employee_id,employee_polices.client_policy_id,employee_polices.date_coverage,client_policy.policy_type_id,client_policy.base_policy')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id', 'left')
->where('employee_polices.employee_id', $empData['id'])
->where('employee_polices.is_active', 1)
->findAll();
if (count($empPolicyData)) {
// find same policy 'self' date of coverage
$filterSelfPolicy = array_filter($empPolicyData, function ($row) use ($client_policy_id) {
return $row['client_policy_id'] == $client_policy_id;
});
$filterSelfPolicy = array_values($filterSelfPolicy); // Reset the index of the filtered result
if (count($filterSelfPolicy)) {
return $filterSelfPolicy[0]['date_coverage'];
} else {
// find base policy 'self' date of coverage
$basePolicy = $this->clientPolicyModel->where('id', $client_policy_id)->get()->getRow()->base_policy;
$filterSelfBasePolicy = array_filter($empPolicyData, function ($row) use ($basePolicy) {
return $row['client_policy_id'] == $basePolicy;
});
$filterSelfBasePolicy = array_values($filterSelfBasePolicy); // Reset the index of the filtered result
if (count($filterSelfBasePolicy)) {
return $filterSelfBasePolicy[0]['date_coverage'];
} else {
return null;
}
}
} else {
return null;
}
} else {
return null;
}
}
public function RelationshipMap($value)
{
if ($value === 'Mother' || $value === 'Father') {
return 'parent';
} else if ($value === 'Son' || $value === 'Daughter') {
return 'child';
} else if ($value === 'Father in Law' || $value === 'Mother in Law') {
return 'parent_in_law';
} else if ($value === 'Spouse') {
return 'spouse';
}
}
public function GenderMap($value, $empCode)
{
if ($value === 'Mother' || $value === 'Daughter' || $value === 'Mother in Law') {
return 'F';
} else if ($value === 'Son' || $value === 'Father' || $value === 'Father in Law') {
return 'M';
} else if ($value === 'Spouse') {
$Gender = $this->employeeModel->where('emp_code', $empCode)->where('relationship', 'Self')->get()->getRow()->gender;
if ($Gender == 'M') {
return 'F';
} else {
return 'M';
}
}
}
private function convertDateFormatYMD($dateString)
{
// Attempt to create a DateTime object from the provided date string
$dateTime = \DateTime::createFromFormat('d-m-Y', $dateString);
if ($dateTime instanceof \DateTime) {
return $dateTime->format('Y-m-d');
} else {
// return null;
return change_date_format($dateString);
}
}
private function convertDateFormatDMY($dateString)
{
// Attempt to create a DateTime object from the provided date string
$dateTime = \DateTime::createFromFormat('Y-m-d', $dateString);
if ($dateTime instanceof \DateTime) {
return $dateTime->format('d-m-Y');
} else {
return null;
}
}
private function getClaimStatusReason(string $claimStatus, array $claimsData): string
{
$statusReasonConfig = [
'REJECTED' => ['denial_reason', 'head_rejection_reason'],
'CANCELLED' => ['cancel_remark'],
'CANCELED' => ['cancel_remark'],
'RETURNED' => ['return_remark'],
];
$claimStatusKey = strtoupper($claimStatus);
if (! isset($statusReasonConfig[$claimStatusKey])) {
return '';
}
foreach ($statusReasonConfig[$claimStatusKey] as $field) {
if (! empty($claimsData[$field])) {
$reason = trim((string) $claimsData[$field]);
if ($reason !== '') {
return $reason;
}
}
}
return '';
}
public function deleteDependence()
{
try {
if ($this->request->getGet('id')) {
$this->employeeModel->where('id', $this->request->getGet('id'))
->where('is_active', 1)
->set(['is_active' => 0])
->update();
$this->employeePolicyModel->where('employee_id', $this->request->getGet('id'))
->where('is_active', 1)
->set(['is_active' => 0])
->update();
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function createOrUpdateEmployeePolicySiAmount()
{
try {
$requestData = $this->request->getJSON();
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($requestData[0]->client_policy_id);
if ($openForEnrollment == false) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Enrollment closed'], 200);
}
foreach ($requestData as $key => $value) {
$checkIfExist = $this->employeePolicyModel->where('employee_id', $value->employee_id)
->where('client_policy_id', $value->client_policy_id)
->where('is_active', 1)
->findAll();
if ($checkIfExist) {
$empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si);
} else {
$data['employee_id'] = $value->employee_id;
$data['client_policy_id'] = $value->client_policy_id;
$data['basic_cover_si'] = $value->basic_cover_si;
$data['status'] = 'draft';
$this->employeePolicyModel->insert($data);
}
}
if (count($requestData)) {
$this->updatePremiumAmount($requestData[0]->client_policy_id, $requestData[0]->emp_code, $requestData[0]->client_branch_id);
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function findPremiumAmount($slabArray, $siAmount)
{
foreach ($slabArray as $key => $value) {
if ($value['si'] == $siAmount) {
return $value['premium'];
break;
}
}
}
public function relationshipList()
{
try {
$relation_ships = $this->relationshipModel->findAll();
if (count($relation_ships) > 0) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $relation_ships], 200);
} else {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => "No Data..!"], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function getEmployeeAndDependenceByClientId()
{
try {
$search = trim((string) $this->request->getGet('search'));
$empData = $this->employeePolicyModel->getEmployeePolicy(
client_id: $this->request->getGet('client_id'),
policy_id: $this->request->getGet('client_policy_id'),
status: 0,
branch_id: $this->request->getGet('client_branch_id'),
status_type: 'inactive',
search: $search
);
if ($empData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function exportDataByClientPolicyId()
{
try {
$empData = $this->employeePolicyModel->getEmployeePolicy(client_id: $this->request->getGet('client_id'), policy_id: $this->request->getGet('client_policy_id'), status: 0, branch_id: $this->request->getGet('client_branch_id'));
if (count($empData)) {
// Define headers and map database fields to Excel fields
$headers = [
'Employee Code' => 'emp_code',
'Name' => 'name',
'Relationship' => 'relationship',
'DOB' => 'dob',
'Gender' => 'gender',
'Mobile' => 'mobile',
'Email' => 'email_corporate',
'SI' => 'basic_cover_si',
'Premium' => 'rata_premimum',
'Policy Name' => 'policy_name',
'Insurer Branch Name' => 'insurer_branch_name',
'TPA Name' => 'tpa_name',
'Status' => 'emp_status',
];
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Add headers
$column = 'A';
foreach ($headers as $header => $dbField) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Add data
$row = 2;
foreach ($empData as $employee) {
$column = 'A';
foreach ($headers as $dbField) {
$sheet->setCellValue($column . $row, $employee[$dbField]);
$column++;
}
$row++;
}
// Set the header for download
$filename = $empData[0]['policy_name'] . '-Enrolment.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// Save the Excel file to output
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
/**
* Download all employees for client/branch/policy as Excel
* (Emp Code, Name, TPA ID, Relationship, Date Of Birth, Gender, Mobile, Email, Status).
*
* Query params: client_id, policy_id (or client_policy_id), branch_id (or client_branch_id)
*/
public function downloadEmployeeListExcel()
{
try {
$clientId = $this->request->getGet('client_id');
$policyId = $this->request->getGet('policy_id') ?: $this->request->getGet('client_policy_id');
$branchId = $this->request->getGet('branch_id') ?: $this->request->getGet('client_branch_id');
if (empty($clientId) || empty($policyId) || empty($branchId)) {
return $this->respond([
'status' => 'failed',
'code' => 400,
'message' => 'client_id, policy_id and branch_id are required',
'data' => [],
], 200);
}
$empData = $this->employeePolicyModel->getEmployeePolicy(
client_id: $clientId,
policy_id: $policyId,
status: 0,
branch_id: $branchId,
status_type: 'inactive'
);
if (!count($empData)) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
$headers = [
'Emp Code',
'Name',
'TPA ID',
'Relationship',
'Date Of Birth',
'Gender',
'Mobile',
'Email',
'Status',
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
$row = 2;
foreach ($empData as $employee) {
$gender = strtoupper(trim((string) ($employee['gender'] ?? '')));
if ($gender === 'MALE' || $gender === 'M') {
$gender = 'M';
} elseif ($gender === 'FEMALE' || $gender === 'F') {
$gender = 'F';
} elseif ($gender !== '') {
$gender = strtoupper(substr($gender, 0, 1));
}
$dob = $employee['formatted_dob'] ?? '';
if ($dob === '' && !empty($employee['dob'])) {
$ts = strtotime((string) $employee['dob']);
$dob = $ts ? date('d/m/Y', $ts) : (string) $employee['dob'];
}
$sheet->setCellValue('A' . $row, $employee['emp_code'] ?? '');
$sheet->setCellValue('B' . $row, $employee['name'] ?? '');
$sheet->setCellValue('C' . $row, $employee['tpa_id'] ?? '');
$sheet->setCellValue('D' . $row, $employee['relationship'] ?? '');
$sheet->setCellValue('E' . $row, $dob);
$sheet->setCellValue('F' . $row, $gender);
$sheet->setCellValueExplicit('G' . $row, (string) ($employee['mobile'] ?? ''), \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('H' . $row, $employee['email_corporate'] ?? '');
$sheet->setCellValue('I' . $row, $employee['emp_status'] ?? ($employee['status'] ?? ''));
$row++;
}
$policyName = preg_replace('/[^A-Za-z0-9_\- ]/', '', (string) ($empData[0]['policy_name'] ?? 'Employees'));
$filename = trim($policyName) !== '' ? $policyName . '-Employees.xlsx' : 'Employees.xlsx';
// Return via CI Response (no header()/exit) so global Cors after-filter can attach ACAO headers.
$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save('php://output');
$content = ob_get_clean();
return $this->response
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment;filename="' . $filename . '"')
->setHeader('Cache-Control', 'max-age=0')
->setBody($content);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
//not in use
public function getClientPolicy()
{
try {
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, policies.id as policy_id,policies.policy_type_id as policy_type_id, policies.name as policy_name , client_policy.is_addon as is_addon')
->join('policies', 'client_policy.policy_id = policies.id', 'left')
->where('client_policy.client_id', $this->request->getGet('client_id'))
->findAll();
$result = [];
foreach ($ClientPolicyData as $key => $value) {
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($value['client_policy_id'], $value['client_id']);
if ($value['is_addon'] == "2") {
$value['type'] = 'SI TopUp';
} else if ($value['is_addon'] == "3") {
$value['type'] = 'Dependent AddOn';
} else {
$value['type'] = $getSlabAndGridData['grid_master']['policy_type'];
}
array_push($result, $value);
}
if ($ClientPolicyData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
// Upload the Employee Detail in DB by Sheet Data
public function employeeUpload()
{
try {
$file = $this->request->getFile('file');
$client_id = $this->request->getPost('client_id');
$client_branch_id = $this->request->getPost('client_branch_id');
$policy_id = $this->request->getPost('policy_id');
if (!$file || !$file->isValid()) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'No file uploaded or invalid file.'], 200);
}
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.'], 200);
}
$client_data = $this->clientModel->where('id', $client_id)->first();
$notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_welcome_mail')->first();
$jwt = $this->request->getHeaderLine('Authorization');
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[1];
$decodedPayload = json_decode(base64_decode(explode('.', $token)[1]), true);
// get the employee id from token
$employee_id = $decodedPayload['id'];
$client_policy = $this->clientPolicyModel->where('id', $policy_id)->where('client_id', $client_id)->where('client_branch_id', $client_branch_id)->first();
if ($client_policy) {
$policy = $this->policesModel->where('id', $client_policy['policy_id'])->first();
$policy_permium_1 = $this->policyPremium1Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1])->first();
$policy_permium_2 = $this->policyPremium2Model->where(['client_id' => $client_id, 'client_policy_id' => $policy_id, 'is_active' => 1])->first();
$sum_insured_amount_for_check_employee_1 = isset($policy_permium_1['si']) ? $policy_permium_1['si'] : null;
$sum_insured_amount_for_check_employee_2 = isset($policy_permium_2['si']) ? $policy_permium_2['si'] : null;
$filename = storage_file_Upload($file, WRITEPATH . 'uploads/excel/', UPLOAD_EXT_EXCEL);
if ($filename === '') {
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'File upload failed.'], 200);
}
$file_name_with_path = storage_ensure_local_file(WRITEPATH . 'uploads/excel', $filename);
//make an entry in DB
$file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master
$this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]);
$empServiceController = new EmployeeServiceController();
$result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
if (isset($result['error_summary']) && count($result['error_summary'])) {
$result = $empServiceController->getExcelErrorData($file_id);
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "The data format is invalid. Click 'Next' to view details.", 'data' => $result], 200);
}
//check the file exist or not
if (empty($file_name_with_path) || ! file_exists($file_name_with_path)) {
session()->setFlashdata('error', 'File not found');
return redirect()->to(base_url('employee/upload'));
}
// Load the Excel file
$spreadsheet = IOFactory::load($file_name_with_path);
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Get the highest row and column numbers
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestRowAndColumn = $sheet->getHighestRowAndColumn();
$data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
// $extractData['file_name']= $filename;
// $extractData['client_id']= $client_id;
// $extractData['client_branch_id']= $client_branch_id;
// $extractData['status']= 'success';
// $extractData['policy_id']= $policy_id;
// $extractData['action']= 'enrollment';
// $extractData['created_by']=$employee_id;
// $file_data =$this->fileModel->insert($extractData);
// $extra = [];
// if (count($data[0]) == 11) {
// $value = ['Sno','Emp_Code','Name','DOJ','Gender','Relation','DOB','Mail','Mobile','SI','Grade'];
// $check_miss_match = [];
// for ($i=0; $i <count($value) ; $i++) {
// if ($data[0][$i] != $value[$i]) {
// $check_miss_match[]=$data[0][$i];
// }
// }
// if (count($check_miss_match) > 0) {
// return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Column Name's are miss Match's!", 'data'=> $check_miss_match], 200);
// }
// }
// if(count($data[0]) != 11){
// return json_encode($data[0]);
// return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Uploaded file row count is Not Match!" ], 200);
// }
//this change the column name into index number
for ($i = 0; $i < count($data[0]); $i++) {
$data[0][$i] = $i;
}
for ($i = 0; $i < count($data); $i++) {
if ($i == 0) {
// Loop through the first row to extract keys
for ($j = 0; $j < count($data[$i]); $j++) {
$extra[$data[$i][$j]] = []; // Initialize keys with empty array
}
} else {
// Loop through subsequent rows
for ($j = 0; $j < count($data[$i]); $j++) {
// Append values to corresponding keys in $extra
if (isset($extra[$data[0][$j]])) {
// Make sure the key exists in the $extra array
$extra[$data[0][$j]][] = $data[$i][$j];
}
}
}
}
$dataToInsert = [];
$basic_cover_si = [];
foreach ($extra['0'] as $index => $id) {
$relation = '';
if (strtolower(trim($extra['5'][$index])) === 'mother' || strtolower(trim($extra['5'][$index])) === 'father') {
$relation = 'parent';
} else if (strtolower(trim($extra['5'][$index])) === 'son' || strtolower(trim($extra['5'][$index])) === 'daughter') {
$relation = 'child';
} else if (strtolower(trim($extra['5'][$index])) === 'father in law' || strtolower(trim($extra['5'][$index])) === 'mother in law') {
$relation = 'parent_in_law';
} else if (strtolower(trim($extra['5'][$index])) === 'spouse') {
$relation = 'spouse';
} else {
$relation = 'self';
}
// Simplified formatDate function
// Assigning formatted dates
$doj = $extra['3'][$index];
$dob = $extra['6'][$index];
// Change date format for $doj
$doj_new_format = date('Y-m-d', strtotime($doj)); // $doj_new_format will be "2001-02-12"
// Change date format for $dob
$dob_new_format = date('Y-m-d', strtotime($dob));
// Your existing code here
$emp_code = isset($extra['1'][$index]) ? $extra['1'][$index] : 0;
$name = $extra['2'][$index];
if ($emp_code != 0 && $name != '' || $name != null) {
$record = [
// 'id' => $id,
'emp_code' => $emp_code,
'name' => $name,
// Check if the 'doj' key exists before accessing it
'doj' => $doj_new_format,
'gender' => $extra['4'][$index],
'relationship' => ucfirst(trim($extra['5'][$index])),
'family_floater_key' => $relation,
'dob' => $dob_new_format,
'email_corporate' => $extra['7'][$index],
'mobile' => $extra['8'][$index],
'client_id' => $client_id,
'emp_status' => 'draft',
'band' => $extra['10'][$index],
'basic_pay' => $extra['11'][$index],
'unit' => isset($extra['12'][$index]) ? $extra['12'][$index] : null,
'client_branch_id' => $client_branch_id,
'date_coverage' => $extra['13'][$index] != "" && $extra['13'][$index] != null ? change_date_format($extra['13'][$index], 'd-M-Y', 'Y-m-d') : null,
];
$basic_cover_si_value = null;
//Grid id is 10 and 11 sum insure value add only for self other grid type self sum insure is for the dependence
if (isset($policy_permium_2['policy_grid_id']) == 10 || isset($policy_permium_2['policy_grid_id']) == 11) {
if (strtolower($extra['5'][$index]) == 'self') {
$basic_cover_si_value = $extra['9'][$index];
} else {
$basic_cover_si_value = null;
}
} else {
if (strtolower($extra['5'][$index]) == 'self') {
$basic_cover_si_value = $extra['9'][$index];
} else {
for ($i = 0; $i < count($extra['1']); $i++) {
if ($extra['1'][$i] == $extra['1'][$index]) {
if (strtolower($extra['5'][$i]) == 'self') {
$basic_cover_si_value = $extra['9'][$i];
}
}
}
}
}
$record2 = [
'basic_cover_si' => $basic_cover_si_value,
];
$dataToInsert[] = $record;
$basic_cover_si[] = $basic_cover_si_value;
}
}
$count = 0;
$wholeData = []; // Initialize an empty array to store employee email.
for ($a = 0; $a < count($dataToInsert); $a++) {
$date_coverage = $dataToInsert[$a]['date_coverage'];
unset($dataToInsert[$a]['date_coverage']);
$employee = $this->employeeModel->checkExistingEmployee($dataToInsert[$a], $client_branch_id);
$emp_id = 0;
$data_after_gpa_or_gmc = [];
if ($client_policy['policy_type_id'] == 1) {
if (strtolower($dataToInsert[$a]['relationship']) == 'self') {
$data_after_gpa_or_gmc = $dataToInsert[$a];
}
} else {
$data_after_gpa_or_gmc = $dataToInsert[$a];
}
date_default_timezone_set('Asia/Kolkata');
$current_timestamp = time();
$formatted_date_time = date('Y-m-d H:i:s', $current_timestamp);
if ($employee) {
$emp_id = $employee['id'];
$id = $emp_id;
$data_after_gpa_or_gmc['id'] = $id;
$data_after_gpa_or_gmc['updated_by'] = $employee_id;
$data_after_gpa_or_gmc['updated_at'] = $formatted_date_time;
$result = $this->employeeModel->save($data_after_gpa_or_gmc);
if ($result) {
$log_message = 'Update Employee - ' . $employee['name'] . '(' . $employee['emp_code'] . ') with PK ' . $employee['id'];
$this->myLogger->logme('error', ('Update - ' . $employee['id'] . ' - ' . $employee['emp_code'] . ' - ' . $employee['name']));
}
} else {
if ($dataToInsert[$a]['emp_code'] != 0) {
$result = false;
if (count($data_after_gpa_or_gmc) != 0) {
$data_after_gpa_or_gmc['created_by'] = $employee_id;
$result = $this->employeeModel->insert($data_after_gpa_or_gmc);
}
$emp_id = $result;
if ($result) {
$emp = $this->employeeModel->where('id', $result)->get()->getResult();
$policy_name = $this->employeePolicyModel->where('employee_id', $result)->get()->getResult();
$log_message = 'Insert Employee- ' . $dataToInsert[$a]['name'] . '(' . $dataToInsert[$a]['emp_code'] . ') with PK ';
$this->myLogger->logme('error', ('Insert - ' . $dataToInsert[$a]['emp_code'] . ' - ' . $dataToInsert[$a]['name']));
}
}
}
$employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id, 'client_policy_id' => $policy_id]);
$emp_policy_data = [
'employee_id' => $emp_id,
'client_policy_id' => $policy_id,
'status' => 'draft',
'date_coverage' => $date_coverage,
'payable_employee' => check_pay_by_employee_or_company($client_policy['policy_terms'], $dataToInsert[$a]['relationship']),
'basic_cover_si' => isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null,
'file_id' => isset($employee_policy['file_id']) && $employee_policy['file_id'] != '' ? $employee_policy['file_id'] : $file_id,
];
// print_r($employee_policy); die;
if ($employee_policy) {
foreach ($employee_policy as $existing_policy) {
$emp_policy_data['id'] = $existing_policy['id'];
$emp_policy_data['updated_at'] = $formatted_date_time;
$this->employeePolicyModel->save($emp_policy_data);
}
$emp_policy_id = $employee_policy[0]['id'];
} else {
$emp_policy_id = $this->employeePolicyModel->insert($emp_policy_data);
}
if (isset($notification) && $notification['enabled'] == 1 && ! empty($notification['mail_content'])) {
//trigger
// $wholeData=[];
if ($dataToInsert[$a]['relationship'] == 'Self' && isset($dataToInsert[$a]['email_corporate']) && ! empty($dataToInsert[$a]['email_corporate'])) {
$params['dataToInsert'] = $dataToInsert[$a];
$params['notification'] = $notification;
$params['client_data'] = $client_data;
$params['common'] = [
'client_id' => $client_id,
'client_branch_id' => $client_branch_id,
'client_policy_id' => $policy_id,
'employee_policy_id' => $emp_policy_id ?? null,
'employee_id' => $emp_id,
'mail_type' => 'member_welcome_mail',
];
$wholeData[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
$count++;
}
// if($count == 20 || $a == count($dataToInsert)-1){
// if (count($wholeData) > 0) {
// $job_details = new Jobs();
// $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $wholeData]);
// $wholeData = [];
// $count = 0;
// }
// }
// if ($dataToInsert[$a]['email_corporate'] != null || $dataToInsert[$a]['email_corporate'] != '' && $dataToInsert[$a]['relationship'] == 'Self') {
}
}
// print_r($wholeData); die;
// for bulk mail queue job push
if (! empty($wholeData) && count($wholeData) > 0) {
$wholeData = array_chunk($wholeData, 20);
foreach ($wholeData as $key => $value) {
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
}
}
$this->fileModel->where('id', $file_id)->set(['status' => 'success', 'reason' => '', 'error_data' => ''])->update();
return $this->respond(['status' => 'success', 'code' => 200, 'message' => "Success"], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Client id and Client Policy id is Not Match!"], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
//-------------------------------------
public function getAgeRange($terms, $familyFloatesValue)
{
$ageRangeArray = ['self' => ['min' => 18, 'max' => 60], 'spouse' => ['min' => 18, 'max' => 60], 'child' => ['min' => 0, 'max' => 25], 'elders' => ['min' => 18, 'max' => 60]];
$ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue);
if (isset($terms->age_ratio)) {
return $terms->age_ratio->$ageKey;
} else {
return $ageRangeArray[$ageKey];
}
}
public function getEmployeePolicy()
{
try {
$id = $this->request->getGet('id');
$emp_code = $this->request->getGet('emp_code');
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
$login_by_hr = $this->request->getGet('login_by_hr');
// This is an array containing keys to be removed from the terms and conditions array
$keysToRemove = ["removable_keys"];
// Retrieve employee policy data by passing the employee primary key
$empPolicy = $this->employeeModel->getEmployeePolicy($id);
// dd($empPolicy);
// Retrieve employee and dependents data by passing the employee code
$employeeData = $this->employeeModel->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('client_branch_id', $client_branch_id)
->where('is_active', 1)
->where('is_addon_value', 0)->findAll();
if ($empPolicy) {
$result = [];
foreach ($empPolicy as $array) {
// Reset employee array
$empData = $employeeData;
// Removes specific keys from the decoded array and assigns the result to $refusingData
$decodedArray = json_decode($array->Policy_Terms);
$refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove));
$array->Policy_Terms = $refusingData;
// Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId, $array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
if ($array->tpa_id != null) {
$array->eCardDownload = base_url('download-e-card/') . $array->rand_string . '/1';
} else {
$array->eCardDownload = null;
}
// Construct value for policy type GPA
// $getSlabAndGridData['grid_master']['policy_type'] == "GPA"
if ($array->policy_type_id == 1 && $this->request->getGet('policy') == 'GPA') {
$si_value = 0;
$si_premium_value = 0;
$si_gst_value = 0;
// Filter employee data where the family_floater_key is 'self'
$selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self');
$employee_policy = $this->employeePolicyModel->where('employee_id', $selfData[0]['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow();
$si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
$si_premium_value = $si_premium_value + $employee_policy->rata_premimum;
$si_gst_value = $si_gst_value + $employee_policy->gst;
}
$self['is_value_exist'] = true;
$self['data']['family_floater_key'] = 'self';
$self['data']['employee_id'] = $id;
$self['data']['relationship'] = 'Self';
$self['data']['name'] = $selfData[0]['name'];
$self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']);
$self['data']['mobile'] = $selfData[0]['mobile'];
$self['data']['client_policy_id'] = $array->ClientPolicyId;
$self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
$array->mapped_family_floaters = $self;
$array->type = 'GPA';
$array->si_value = $si_value;
$array->si_premium_value = $si_premium_value;
$array->si_gst_value = $si_gst_value;
$res = [];
array_push($res, $array);
$EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData, 6, $emp_code, $client_id, $client_branch_id, $login_by_hr);
if ($EDLIPolicy) {
array_push($res, $EDLIPolicy);
}
$GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData, 7, $emp_code, $client_id, $client_branch_id, $login_by_hr);
if ($GTLIPolicy) {
array_push($res, $GTLIPolicy);
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $res], 200);
// Return result
if ($this->request->getGet('policy') == 'GPA') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $array], 200);
}
// Construct value for policy type GMC
// $getSlabAndGridData['grid_master']['policy_type'] == "GMC"
} else if ($array->policy_type_id == 2 && $this->request->getGet('policy') == 'GMC') {
// Map family floaters that already exist in the employee table
$familyFloates = $array->Policy_Terms->family_floaters;
// Generate Notes string based on familyFloates terms
$array->notes = $this->FloterNotesConvertion($familyFloates);
if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) {
$array->floter_text_heading = 'Floater Sum Insured';
$array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.';
} else {
$array->floter_text_heading = 'Sum Insured';
$array->floter_text_description = '';
}
// remove parent and parent-in-law from familyFloaters
if ($familyFloates->{'either-parents-pil'} != 0) {
unset($familyFloates->parents);
unset($familyFloates->parents_in_law);
}
$floters = $this->FloterConvertion($familyFloates);
$data = [];
$dependent_and_si_value = 0;
$dependent_and_si_premium_value = 0;
$dependent_and_si_gst_value = 0;
foreach ($floters as $familyFloatesValue) {
$dependent = preg_replace('/\d/', '', $familyFloatesValue);
if (count($empData)) {
foreach ($empData as $key => $value) {
if ($value['family_floater_key'] === $dependent) {
$employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow();
if (isset($employee_policy->basic_cover_si)) {
$dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;
}
}
$temp['is_value_exist'] = true;
$temp['data']['family_floater_key'] = $familyFloatesValue;
$temp['data']['employee_id'] = $value['id'];
$temp['data']['relationship'] = $value['relationship'];
$temp['data']['name'] = $value['name'];
$temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp['data']['client_policy_id'] = $array->ClientPolicyId;
$temp['data']['form_type'] = $dependent;
$temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
$temp['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
array_push($data, $temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
// Remove Unwanted floter key from floters array based on either-parents-pil term value
if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if ($count_parent != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false);
}
if ($count_parent_in_law != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false);
}
} else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if (($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
// Add family floter buttons placement data for FE validation
if (count($floters)) {
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array->ClientPolicyId;
$temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
array_push($data, $temp2);
}
}
$array->mapped_family_floaters = $data;
$array->type = "GMC";
$array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0;
$array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0;
$array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0;
$checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('client_policy.policy_type_id', 3)
->where('client_policy.is_addon', 1)
->where('client_policy.client_id', $this->request->getGet('client_id'))
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id'))
->where('client_policy.is_active', 1)
->get()
->getResult();
if ($checkGmcParentsPolicyExist) {
$GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist, $emp_code, $client_id, $client_branch_id);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => [$array, $GmcParrentsData]], 200);
}
if ($this->request->getGet('policy') == 'GMC') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => [$array]], 200);
}
}
// $result[] = $array;
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getLine()], 500);
}
}
public function getGmcParrentsPolicy($GmcParrentsPolicy, $emp_code, $client_id, $client_branch_id)
{
$employeeData = $this->employeeModel->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('client_branch_id', $client_branch_id)
->where('is_active', 1)
->where('is_addon_value', 0)->findAll();
// return $employeeData;
foreach ($GmcParrentsPolicy as $key => $array) {
// Reset employee array
$empData = $employeeData;
$array->Policy_Terms = json_decode($array->Policy_Terms);
// Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId, $array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
$tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $emp_code)
->where('employees.is_active', 1)
->where('employee_polices.client_policy_id', $array->ClientPolicyId)
->get()
->getResult();
if (count($tpaArray)) {
if ($tpaArray[0]->tpa_id != null) {
$array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1';
} else {
$array->eCardDownload = null;
}
} else {
$array->eCardDownload = null;
}
$array->eCardDownload = null;
// Map family floaters that already exist in the employee table
$familyFloates = $array->Policy_Terms->family_floaters;
// Generate Notes string based on familyFloates terms
$array->notes = $this->FloterNotesConvertion($familyFloates);
if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) {
$array->floter_text_heading = 'Floater Sum Insured';
$array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.';
} else {
$array->floter_text_heading = 'Sum Insured';
$array->floter_text_description = '';
}
// remove parent and parent-in-law from familyFloaters
if ($familyFloates->{'either-parents-pil'} != 0) {
unset($familyFloates->parents);
unset($familyFloates->parents_in_law);
}
// Convert familyFloaters terms data to plain array
$floters = $this->FloterConvertion($familyFloates);
$data = [];
$dependent_and_si_value = 0;
$dependent_and_si_premium_value = 0;
$dependent_and_si_gst_value = 0;
foreach ($floters as $familyFloatesValue) {
$dependent = preg_replace('/\d/', '', $familyFloatesValue);
if (count($empData)) {
foreach ($empData as $key => $value) {
if ($value['family_floater_key'] === $dependent) {
$employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow();
if (isset($employee_policy->basic_cover_si)) {
$dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;
}
}
$temp['is_value_exist'] = true;
$temp['data']['family_floater_key'] = $familyFloatesValue;
$temp['data']['employee_id'] = $value['id'];
$temp['data']['relationship'] = $value['relationship'];
$temp['data']['name'] = $value['name'];
$temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp['data']['client_policy_id'] = $array->ClientPolicyId;
$temp['data']['form_type'] = $dependent;
$temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
$temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue);
array_push($data, $temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
// Remove Unwanted floter key from floters array based on either-parents-pil term value
if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if ($count_parent != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false);
}
if ($count_parent_in_law != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false);
}
} else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if (($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
// Add family floter buttons placement data for FE validation
if (count($floters)) {
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array->ClientPolicyId;
$temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue);
array_push($data, $temp2);
}
}
$array->mapped_family_floaters = $data;
$array->type = "GMC - Parents";
$array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0;
$array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0;
$array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0;
return $array;
}
}
public function getAdditionalGPAPolicy($empData, $policy_type, $emp_code, $client_id, $client_branch_id, $login_by_hr)
{
$checkPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms , client_policy.enrolment_visibility')
->where('client_policy.policy_type_id', $policy_type)
->where('client_policy.is_addon', 1)
->where('client_policy.client_id', $client_id)
->where('client_policy.client_branch_id', $client_branch_id)
->where('client_policy.is_active', 1)
->get()
->getResult();
if ($checkPolicyExist) {
foreach ($checkPolicyExist as $key => $array) {
$decodedArray = json_decode($array->Policy_Terms);
$array->Policy_Terms = $decodedArray;
$si_value = 0;
$si_premium_value = 0;
$si_gst_value = 0;
// Filter employee data where the family_floater_key is 'self'
$selfData = array_filter($empData, fn($arr) => trim(strtolower($arr['family_floater_key'])) === 'self');
$employee_policy = $this->employeePolicyModel->where('employee_id', $selfData[0]['id'])->where('client_policy_id', $array->ClientPolicyId)->where('is_active', 1)->get()->getRow();
$si_value = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
$si_premium_value = $si_premium_value + $employee_policy->rata_premimum;
$si_gst_value = $si_gst_value + $employee_policy->gst;
}
$policyTypeData = $this->policyTypeModel->where('id', $policy_type)->get()->getRow();
$array->type = $policyTypeData->policy_type;
$array->Policy_Name = $policyTypeData->long_name;
$array->si_value = $si_value;
$array->si_premium_value = $si_premium_value;
$array->si_gst_value = $si_gst_value;
if ($employee_policy) {
if ($employee_policy->tpa_id != null) {
$array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string . '/1';
} else {
$array->eCardDownload = null;
}
$self['is_value_exist'] = true;
$self['data']['family_floater_key'] = 'self';
$self['data']['employee_id'] = $selfData[0]['id'];
$self['data']['relationship'] = 'Self';
$self['data']['name'] = $selfData[0]['name'];
$self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']);
$self['data']['mobile'] = $selfData[0]['mobile'];
$self['data']['client_policy_id'] = $array->ClientPolicyId;
$self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
$array->mapped_family_floaters = $self;
if (isset($login_by_hr) && $login_by_hr == true) {
return $array;
} else {
if ($array->enrolment_visibility == 1) {
return $array;
} else {
return false;
}
}
} else {
return false;
}
}
}
}
public function FloterConvertion($array)
{
$result = [];
foreach ($array as $key => $value) {
if ($value > 0 && $key != 'elders_count') {
if ($value != 0 && $key === 'childrens') {
// if ($value > 2) {
// $value = 2;
// }
for ($i = 1; $i <= $value; $i++) {
$result[] = "child" . $i;
}
} else if ($value != 0 && $key === 'parents') {
for ($i = 1; $i <= $value; $i++) {
$result[] = "parent" . $i;
}
} else if ($value != 0 && $key === 'parents-in-law') {
for ($i = 1; $i <= $value; $i++) {
$result[] = "parent_in_law" . $i;
}
} else if ($value != 0 && $key === 'either-parents-pil') {
for ($i = 1; $i <= 2; $i++) {
$result[] = "parent" . $i;
$result[] = "parent_in_law" . $i;
}
} else {
$result[] = $key;
}
}
}
return $result;
}
public function FloterNotesConvertion($array)
{
$result = ' ';
foreach ($array as $key => $value) {
if ($value > 0) {
if ($value == 1 && $key === 'either-parents-pil') {
$result .= ' + Either 2 Parents or 2 Parents in law';
} else if ($value == 2 && $key === 'either-parents-pil') {
$result .= ' + Any 2 of Parents and Parents in law';
} else if ($value != 0 && $key === 'spouse') {
$string = str_replace('-', ' ', $key);
$string = ucwords($string);
$result .= ' + ' . $string;
} else if ($value != 0 && $key === 'self') {
$result = 'Allowed members Self ';
} else if ($value != 0 && $key === 'childrens') {
if ($value > 1) {
$result .= ' + ' . $value . ' Children';
} else {
$result .= ' + ' . $value . ' Child';
}
} else if ($value != 0 && $key === 'elders_count') {
} else {
$string = str_replace('-', ' ', $key);
$string = ucwords($string);
$result .= ' + ' . $value . ' ' . $string;
}
}
}
$first_two_chars = substr($result, 0, 3);
if ($first_two_chars == " +") {
$modified_string = substr($result, 3);
return "Allowed members " . $modified_string;
} else {
return $result;
}
return substr($result, 0, 2) !== " +";
}
public function getClientDetails()
{
try {
$client_id = $this->request->getGet('client_id');
if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$client = $this->clientModel->where('MD5(id)', $client_id)->first();
} else {
$client = $this->clientModel->where('id', $client_id)->first();
}
if (! empty($client)) {
$client['client_logo'] = base_url() . 'public/uploads/logo/' . $client['client_logo'];
$clientPolicy = $this->clientPolicyModel->where('client_id', $client['id'])
->where('client_branch_id', $this->request->getGet('client_branch_id'))->findAll();
return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['client' => $client, 'client_policy' => $clientPolicy]], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function getClientRM()
{
try {
$client_id = $this->request->getGet('client_id');
if (empty($client_id)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'client_id is required'], 200);
}
$clientRmRecords = $this->clientRMModel
->select('client_rm.level, user_profiles.first_name, user_profiles.email, user_profiles.mobile')
->join('user_profiles', 'user_profiles.id = client_rm.user_id')
->where('md5(client_rm.client_id)', $client_id)
->where('client_rm.is_active', 1)
->whereIn('client_rm.level', [1, 3])
->findAll();
$level_1 = [];
$level_2 = [];
foreach ($clientRmRecords as $record) {
$user = [
'first_name' => $record['first_name'],
'email' => $record['email'],
'mobile' => $record['mobile'],
];
if ((int) $record['level'] === 3) {
$level_1[] = $user;
} else {
$level_2[] = $user;
}
}
$responseData = [
'level_1' => $level_1,
'level_2' => $level_2,
];
$tpaNetworkHospitals = $this->getTpaNetworkHospitalsByClientId($client_id);
if (! empty($tpaNetworkHospitals)) {
$responseData['tpa_network_hospitals'] = $tpaNetworkHospitals;
}
return $this->respond([
'status' => 'success',
'code' => 200,
'data' => $responseData,
], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
private function getTpaNetworkHospitalsByClientId($client_id)
{
$tpaRecords = $this->clientPolicyModel
->select('tpa.name as tpa_name, tpa.network_hospitals')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->where('MD5(client_policy.client_id)', $client_id)
->where('client_policy.is_active', 1)
->where('tpa.is_active', 1)
->where('tpa.network_hospitals IS NOT NULL', null, false)
->where('tpa.network_hospitals !=', '')
->groupBy('tpa.id')
->findAll();
$tpaNetworkHospitals = [];
foreach ($tpaRecords as $tpaRecord) {
$tpaName = trim((string) ($tpaRecord['tpa_name'] ?? ''));
$networkHospitals = trim((string) ($tpaRecord['network_hospitals'] ?? ''));
if ($tpaName !== '' && $networkHospitals !== '') {
$tpaNetworkHospitals[$tpaName] = $networkHospitals;
}
}
return $tpaNetworkHospitals;
}
public function getAddOnPolicy()
{
try {
$addOnEmployeeData = $this->employeeModel->where('is_active', 1)
->where('emp_code', $this->request->getGet('emp_code'))
->where('client_id', $this->request->getGet('client_id'))
->where('client_branch_id', $this->request->getGet('client_branch_id'))
->where('is_addon_value', 1)->findAll();
$clientPolicy = $this->clientPolicyModel->where('client_id', $this->request->getGet('client_id'))
->where('client_branch_id', $this->request->getGet('client_branch_id'))
->where('policy_status', 1)
->where('is_active', 1)
->findAll();
if (count($clientPolicy)) {
$self = $this->employeeModel->where('employees.is_active', 1)
->where('employees.emp_code', $this->request->getGet('emp_code'))
->where('employees.client_id', $this->request->getGet('client_id'))
->where('employees.client_branch_id', $this->request->getGet('client_branch_id'))
->where('employees.family_floater_key', 'self')
->get()
->getRow();
$band = $self->band;
$PolicyData = [];
foreach ($clientPolicy as $key => $array) {
$responce = [];
$decodedArray = json_decode($array['policy_terms']);
$policy_terms = $decodedArray;
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'], $array['client_id']);
$uniqueData = [];
$siValues = [];
foreach ($getSlabAndGridData['slab_rates'] as $item) {
if ($getSlabAndGridData['grid_master']['emp_band'] == 1) {
if ($item['grade'] == $band) {
$uniqueData[] = $item;
}
} else {
if (! in_array($item['si'], $siValues)) {
if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) {
$uniqueData[] = $item;
$siValues[] = $item['si'];
} else if ($item['policy_grid_id'] != 11) {
$uniqueData[] = $item;
$siValues[] = $item['si'];
}
}
}
}
$policyTypeData = $this->policyTypeModel->where('id', $array['policy_type_id'])->get()->getRow();
$responce['policy_name'] = $policyTypeData->long_name;
$responce['type'] = $policyTypeData->policy_type;
$responce['SlabRates'] = $uniqueData;
$responce['GridMaster'] = $getSlabAndGridData['grid_master'];
$responce['client_id'] = $array['client_id'];
$responce['client_policy_id'] = $array['id'];
$responce['is_addon'] = $array['is_addon'];
$responce['OpenForEnrollment'] = $array['open_for_enrollment'];
$responce['policy_terms'] = $decodedArray;
$responce['policy_type_id'] = $array['policy_type_id'];
//$responce['is_member_modify_allowed'] = $array['is_member_modify_allowed'];
$responce['disclaimer'] = $array['disclaimer'];
$tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $this->request->getGet('emp_code'))
->where('employees.is_active', 1)
->where('employee_polices.client_policy_id', $array['id'])
->get()
->getResult();
if (count($tpaArray)) {
if ($tpaArray[0]->tpa_id != null) {
$responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1';
} else {
$responce['eCardDownload'] = null;
}
} else {
$responce['eCardDownload'] = null;
}
if (count($getSlabAndGridData['slab_rates'])) {
if ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3) {
$responce['floter_text_heading'] = 'Floater Sum Insured';
} else {
$responce['floter_text_heading'] = 'Sum Insured';
}
}
if ($array['is_addon'] == 3 && $array['policy_type_id'] == 3) //dependent add on policy
{
if ($this->request->getGet('client_id') == 8) // This changes only for client "sterling"
{
$selfGMC = $this->employeeModel->select('employees.name , employee_polices.basic_cover_si')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id AND client_policy.policy_type_id = 2')
->where('employees.is_active', 1)
->where('employees.emp_code', $this->request->getGet('emp_code'))
->where('employees.client_id', $this->request->getGet('client_id'))
->where('employees.client_branch_id', $this->request->getGet('client_branch_id'))
->where('employees.family_floater_key', 'self')
->get()
->getRow();
$selfSi = $selfGMC->basic_cover_si;
$filteredSlabRates = array_filter($responce['SlabRates'], function ($rate) use ($selfSi) {
return $rate['si'] === $selfSi;
});
// To reindex the array to have a proper 0 index
$responce['SlabRates'] = array_values($filteredSlabRates);
}
// Map family floaters that already exist in the employee table
$familyFloates = $policy_terms->family_floaters;
// remove parent and parent-in-law from familyFloaters
if ($familyFloates->{'either-parents-pil'} != 0) {
unset($familyFloates->parents);
unset($familyFloates->parents_in_law);
}
// Convert familyFloaters terms data to plain array
$floters = $this->FloterConvertion($familyFloates);
$data = [];
$dependent_and_si_value = 0;
$dependent_and_si_premium_value = 0;
$dependent_and_si_gst_value = 0;
foreach ($floters as $familyFloatesValue) {
$dependent = preg_replace('/\d/', '', $familyFloatesValue);
if (count($addOnEmployeeData)) {
foreach ($addOnEmployeeData as $key => $value) {
if ($value['family_floater_key'] === $dependent) {
$employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow();
if (isset($employee_policy->basic_cover_si)) {
$dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;
}
}
$temp['is_value_exist'] = true;
$temp['data']['family_floater_key'] = $familyFloatesValue;
$temp['data']['employee_id'] = $value['id'];
$temp['data']['relationship'] = $value['relationship'];
$temp['data']['name'] = $value['name'];
$temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp['data']['client_policy_id'] = $array['id'];
$temp['data']['form_type'] = $dependent;
$temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
$temp['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
array_push($data, $temp);
unset($addOnEmployeeData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
//Remove Unwanted floter key from floters array based on either-parents-pil term value
if ($familyFloates->{'either-parents-pil'} == 1 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if ($count_parent != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false);
}
if ($count_parent_in_law != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false);
}
} else if ($familyFloates->{'either-parents-pil'} == 2 && count($floters)) {
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') {
$count_parent++;
}
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {
$count_parent_in_law++;
}
}
if (($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
// Add family floter buttons placement data for FE validation
if (count($floters)) {
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array['id'];
$temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
array_push($data, $temp2);
}
}
$responce['family_floaters_of_dependent_and_si_array'] = $data;
$responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0;
$responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0;
$responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0;
if ($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_dependent_addon' => $responce]], 200);
}
//array_push($PolicyData, $responce);
} else if ($array['is_addon'] == 2 && $array['policy_type_id'] == 4) //Topup policy
{
$whereArray = [];
foreach ($decodedArray->family_floaters as $key => $value) {
if ($value != 0) {
if ($key == 'parents') {
$text = ["parent"];
} else if ($key == 'childrens') {
$text = ["child"];
} else if ($key == 'parents-in-law') {
$text = ["parent_in_law"];
} else if ($key === 'either-parents-pil') {
$text = ["parent", "parent_in_law"];
} else {
$text = [$key];
}
$whereArray = array_merge($whereArray, $text);
}
}
$getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow();
$basePolicyAddOnType = $getAddOnType->is_addon;
// if is_addon value is 1 it is GMC if not it is one of the Add On policy
if ($basePolicyAddOnType == 1) {
$is_addon_value = 0;
} else {
$is_addon_value = 1;
}
$only_si_array = [];
$only_si_value = 0;
$only_si_premium_value = 0;
$only_si_gst_value = 0;
$BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1)->where('emp_code', $this->request->getGet('emp_code'))->where('client_id', $this->request->getGet('client_id'))->where('is_addon_value', $is_addon_value)->whereIn('family_floater_key', $whereArray)->findAll();
foreach ($BasePolicyEmployeeData as $key => $value) {
$employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow();
if (isset($employee_policy->basic_cover_si)) {
$only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$only_si_gst_value = $only_si_gst_value + $employee_policy->gst;
}
}
$temp3['is_value_exist'] = true;
$temp3['data']['employee_id'] = $value['id'];
$temp3['data']['relationship'] = $value['relationship'];
$temp3['data']['name'] = $value['name'];
$temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp3['data']['client_policy_id'] = $array['id'];
$temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
array_push($only_si_array, $temp3);
}
$responce['family_floaters_of_only_si_array'] = $only_si_array;
$responce['family_floaters_of_only_si_value'] = $only_si_value;
$responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value);
$responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value;
if ($this->request->getGet('policy') == 'GMC-SI-TOPUP') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_si_topup' => $responce]], 200);
}
} else if ($array['is_addon'] == 2 && $array['policy_type_id'] == 5) //Parents Topup policy
{
$whereArray = [];
foreach ($decodedArray->family_floaters as $key => $value) {
if ($value != 0) {
if ($key == 'parents') {
$text = ["parent"];
} else if ($key == 'childrens') {
$text = ["child"];
} else if ($key == 'parents-in-law') {
$text = ["parent_in_law"];
} else if ($key === 'either-parents-pil') {
$text = ["parent", "parent_in_law"];
} else {
$text = [$key];
}
$whereArray = array_merge($whereArray, $text);
}
}
$getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow();
$basePolicyAddOnType = $getAddOnType->is_addon;
// if is_addon value is 1 it is GMC if not it is one of the Add On policy
if ($basePolicyAddOnType == 1) {
$is_addon_value = 0;
} else {
$is_addon_value = 1;
}
$only_si_array = [];
$only_si_value = 0;
$only_si_premium_value = 0;
$only_si_gst_value = 0;
$BasePolicyEmployeeData = $this->employeeModel->where('is_active', 1)->where('emp_code', $this->request->getGet('emp_code'))->where('client_id', $this->request->getGet('client_id'))->where('is_addon_value', $is_addon_value)->whereIn('family_floater_key', $whereArray)->findAll();
foreach ($BasePolicyEmployeeData as $key => $value) {
$employee_policy = $this->employeePolicyModel->where('employee_id', $value['id'])->where('client_policy_id', $array['id'])->where('is_active', 1)->get()->getRow();
if (isset($employee_policy->basic_cover_si)) {
$only_si_value = ($only_si_value == 0) ? $employee_policy->basic_cover_si : $only_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$only_si_gst_value = $only_si_gst_value + $employee_policy->gst;
}
}
$temp3['is_value_exist'] = true;
$temp3['data']['employee_id'] = $value['id'];
$temp3['data']['relationship'] = $value['relationship'];
$temp3['data']['name'] = $value['name'];
$temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp3['data']['client_policy_id'] = $array['id'];
$temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
array_push($only_si_array, $temp3);
}
$responce['family_floaters_of_only_si_array'] = $only_si_array;
$responce['family_floaters_of_only_si_value'] = $only_si_value;
$responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value);
$responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value);
if ($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_si_parent_topup' => $responce]], 200);
}
}
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function iAgreeForAddOn()
{
$postData = json_decode($this->request->getBody(), true);
$this->myLogger->logme("error", $this->request->getBody());
$client_policy_id = $postData['client_policy_id'];
sort($client_policy_id);
$emp_code = $postData['emp_code'];
$client_id = $postData['client_id'];
$empData = $this->employeeModel->where('emp_code', $emp_code)->where('client_id', $client_id)->where('is_active', 1)->findAll();
$employeeIds = array_column($empData, 'id');
//for mail common parameter
$filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self');
if (! is_null($client_policy_id) && is_array($client_policy_id)) {
$array_list = [];
foreach ($client_policy_id as $key => $value) {
$policy = $this->clientPolicyModel->where('id', $value)->where('open_for_enrollment', 1)->find();
if ($policy) {
$this->myLogger->logme("error", 'client policy id = ' . $value . ' is open for enrollment');
$empPolicyData = $this->employeePolicyModel->where('client_policy_id', $value)
->where('is_active', 1)
->whereIn('employee_id', $employeeIds)
->findAll();
if (count($empPolicyData)) {
$empIdsFromPolicyData = array_column($empPolicyData, 'employee_id');
//update emp polict table
$this->employeePolicyModel->where('client_policy_id', $value)
->where('is_active', 1)
->whereIn('employee_id', $empIdsFromPolicyData)
->groupStart()
->where('status', 'draft')
->orWhere('status', 'enrolled')
->groupEnd()
->set(['status' => 'enrolled'])
->update();
//update Employee table
$this->employeeModel->where('emp_code', $emp_code)
->whereIn('id', $empIdsFromPolicyData)
->where('client_id', $client_id)
->where('is_active', 1)
->groupStart()
->where('emp_status', 'draft')
->orWhere('emp_status', 'enrolled')
->groupEnd()
->set(['emp_status' => 'enrolled'])
->update();
}
$find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']);
if (count($find) > 0) {
$array_list[] = $find;
}
} else {
$this->myLogger->logme("error", 'client policy id = ' . $value . ' is not open for enrollment');
}
}
$notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_review_and_summary_mail')->first();
if (isset($notification) && $notification['enabled'] == 1 && count($array_list)) {
$params['array_list'] = $array_list;
$params['client_policy_id'] = $client_policy_id;
$params['emp_code'] = $emp_code;
$params['client_id'] = $client_id;
$params['notification'] = $notification;
$params['common'] = [
'client_id' => $filteredEmpData[0]['client_id'],
'client_branch_id' => $filteredEmpData[0]['client_branch_id'],
'client_policy_id' => null,
'employee_policy_id' => null,
'employee_id' => $filteredEmpData[0]['id'],
'mail_type' => 'member_review_and_summary_mail',
];
// print_r($params);die;
$wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
$mail_send_return = MailHelper::send_email($wholeData[0]);
$this->myLogger->logme("error", $mail_send_return);
if (isset($wholeData[0])) {
$params['common']['mail_type'] = 'account_maneger_summary_mail';
$account_manager_wholeData = sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params);
if ($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData)) {
foreach ($account_manager_wholeData as $key => $value) {
$mail_send_return1 = MailHelper::send_email($value);
$this->myLogger->logme("error", $mail_send_return1);
}
} else {
$this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client');
}
$params['common']['mail_type'] = 'client_hr_summary_mail';
$client_hr_wholeData = sendMailNotification::sendMailNotification('client_hr_summary_mail', $params);
if ($client_hr_wholeData != null && $client_hr_wholeData != '' && count($client_hr_wholeData)) {
foreach ($client_hr_wholeData as $key => $value) {
$mail_send_return2 = MailHelper::send_email($value);
$this->myLogger->logme("error", $mail_send_return2);
}
} else {
$this->myLogger->logme("error", 'Client HR Mail Configuration not Enable for this client');
}
}
} else {
$this->myLogger->logme("error", 'Member Review Mail Configuration not Enable for this client');
}
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
}
//Post method - which receives client_policy id and empcode of the family.
//Pull records againest emp code and calculate premium
// retun array
public function calculatePremium($clientPolicyId = null, $empCode = null, $default_si = null, $client_branch_id = null) //family level
{
// dd($clientPolicyId, $empCode, $default_si, $client_branch_id);
helper('excel_util_helper');
if ($this->request) { //
$client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId;
$emp_code = $this->request->getVar('emp_code') ?? $empCode;
$default_si = $this->request->getVar('si') ?? $default_si; // si amt which choosed in add on policy
$client_branch_id = $this->request->getVar('client_branch_id') ?? $client_branch_id;
} else {
//Cli and enrollment
$client_policy_id = $clientPolicyId;
$emp_code = $empCode;
$default_si = $default_si; // si amt which choosed in add on policy
$client_branch_id = $client_branch_id;
}
// dd($client_policy_id);
$client_id = ($this->clientPolicyModel->select('client_id')->find((int) $client_policy_id))['client_id'];
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id);
$policy_type = $policy_terms[0]->is_addon;
$base_policy = $policy_terms[0]->base_policy;
$policy_terms = (array) $policy_terms[0]; // convert obj to array
//get policy slab rates
$slab_details = $this->policesModel->getPolicySlabRatesForEmpOnboard($client_policy_id, $client_id);
// print_r($slab_details);die();
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_code: $emp_code, emp_status: ['draft', 'enrolled', 'pending_approval'], policy_status: ['draft', 'enrolled', 'pending_approval']);
if (! count($existing_famility_details) && $policy_type == 2) //top up addon only
{
//get basepolicy id then pull emplist from base policy if only current policy is DA addon policy and emplist is zero
// echo 'inside';
$client_policy_id = $base_policy;
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id, client_policy_id: $client_policy_id, emp_code: $emp_code, emp_status: ['draft', 'enrolled', 'pending_approval'], policy_status: ['draft', 'enrolled', 'pending_approval']);
}
$file = ['id' => null, 'client_id' => $client_id, 'policy_id' => $client_policy_id, 'action' => 'inception'];
// dd($this->employeeModel->getLastQuery());
// print_r($existing_famility_details);die();
$employee_data_group_by_family = data_group_by_family($existing_famility_details, $data_source = 'db');
// print_r(($employee_data_group_by_family)); die();
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id, client_branch_id: $client_branch_id);
foreach ($employee_data_group_by_family as $emp_id => $family) {
$transformed_famility_details = transform_db_data_to_excel($family);
$data = calculate_premium_new(family_data: $transformed_famility_details, policy_terms: $policy_terms, slab_details: $slab_details, fileArr: $file, existing_units: $existing_units, default_si: $default_si);
$employee_data_group_by_family[$emp_id] = $data;
}
if ($clientPolicyId != null && $empCode != null) {
return $employee_data_group_by_family;
} else {
// dd ($employee_data_group_by_family);
return $this->respond(['status' => 'success', 'code' => (count($employee_data_group_by_family) ? 200 : 404), 'data' => [$employee_data_group_by_family]], 200);
}
}
public function getHRAccessData($hr_id = null, $request_for = 'post_enrollment')
{
$hr_id = $this->request->getGet('hr_id') ?? $hr_id;
$request_for = $this->request->getGet('request_for') ?? $request_for;
if ($request_for == 'pre_enrollment') {
$idField = 'pre_hr_id';
} else {
$idField = 'post_hr_id';
}
$data = $this->hrAccessControlModel->where($idField, $hr_id)->where('is_active', 1)->first();
if ($request_for == 'post_enrollment') {
return $data ?? [];
}
return $this->respond(['status' => (($data) ? 'success' : 'failed'), 'code' => (($data) ? 200 : 404), 'data' => $data], 200);
}
public function getPolicyLevelEmployeeSummaryData()
{
$hr_id = $this->request->getGet('hr_id');
$HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment');
if (isset($HRAccessData['allowed_active_policies'])) {
$policyId = json_decode($HRAccessData['allowed_active_policies'], true);
} else {
$policyId = [];
}
if (count($policyId) == 0) {
return $this->respond(['status' => 'failed', 'code' => (count($policyId) ? 200 : 404), 'data' => []], 200);
}
if ($this->request->getGet('policy_status') == 0) {
$emp_policy_status = 'expired';
} else {
$emp_policy_status = 'active';
}
$db = \Config\Database::connect();
$emp_policy_status = $db->escape($emp_policy_status);
$ClientPolicyData = $this->clientPolicyModel
->select("
client_policy.id as client_policy_id ,
client_policy.client_id as client_id,
client_policy.policy_type_id as policy_type_id,
client_policy.is_addon as is_addon ,
client_policy.open_for_enrollment as OpenForEnrollment ,
client_policy.inception_type as inception_type,
client_policy.policy_no as policy_no,
client_policy.insurer_id as insurer_id,
client_policy.policy_terms,
insurers.name as insurer_name,
tpa.name as tpa_name,
tpa.short_name as tpa_short_name,
insurers.short_name as insurer_short_name,
DATE_FORMAT(client_policy.policy_start_date, '%d-%m-%Y') AS policy_start_date,
DATE_FORMAT(client_policy.policy_end_date, '%d-%m-%Y') AS policy_expiry_date,
clients.client_logo as client_logo,
(
select COALESCE(ROUND(SUM(rata_premimum + gst)), 0)
from employee_polices
where is_active = 1
and status = $emp_policy_status
and client_policy_id = client_policy.id
) as total_premium,
CASE WHEN policy_type.allocg IN ('Non-EB', 'Marine') THEN 'Non-EB' ELSE 'EB' END as allocg
", false)
->join('clients', 'clients.id = client_policy.client_id', 'left')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->join('insurers', 'insurers.id = client_policy.insurer_id', 'left')
->join('tpa', 'tpa.id = client_policy.tpa_id', 'left')
->where('md5(client_policy.client_id)', $this->request->getGet('client_id'))
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id'))
->where('client_policy.is_active', 1)
->where('client_policy.policy_status', $this->request->getGet('policy_status'))
->whereIn('client_policy.id', $policyId)
->findAll();
$result = [];
// dd( $ClientPolicyData);
foreach ($ClientPolicyData as $key => $value) {
$policyTypeData = $this->policyTypeModel->where('id', $value['policy_type_id'])->get()->getRow();
$insurerData = $this->insurerModel->where('id', $value['insurer_id'])->get()->getRow();
$value['type'] = $policyTypeData->policy_type;
$value['policy_name'] = $policyTypeData->long_name;
$value['insurer_name'] = $insurerData->name;
$value['insurer_short_name'] = $insurerData->short_name;
$value['client_logo'] = ! empty($value['client_logo']) ? base_url() . 'public/uploads/logo/' . $value['client_logo'] : '';
$employeeDetails = $this->employeePolicyModel->getEmployeePolicy(client_id: $value['client_id'], policy_id: $value['client_policy_id'], status: 0, branch_id: $this->request->getGet('client_branch_id'), status_type: 'inactive');
// dd($employeeDetails);
$activeCount = 0;
$inactiveCount = 0;
if (count($employeeDetails)) {
foreach ($employeeDetails as $item) {
if ($item['status'] === 'active') {
$activeCount++;
} elseif ($item['status'] === 'inactive') {
$inactiveCount++;
}
}
}
$value['totalMembersCount'] = count($employeeDetails);
$value['membersCountOfActive'] = $activeCount;
$value['membersCountOfInactive'] = $inactiveCount;
$value['is_ecard_bulk_download'] = 0;
$value['is_ecard_bulk_download_for_employee'] = 0;
$terms = json_decode($value['policy_terms'], true) ?? [];
if ($value['policy_type_id'] == 1) {
$policyGroup = 'gpa';
} elseif (in_array($value['policy_type_id'], [6, 7, 72])) {
$policyGroup = 'other';
} else {
$policyGroup = 'gmc';
}
$value['policy_terms'] = isset($terms['enrollment_display_key']) && ! empty($terms['enrollment_display_key'])
? $terms['enrollment_display_key']
: $this->policyTermsFiter($terms, $policyGroup);
$sumInsuredLabel = in_array($value['policy_type_id'], [1, 6, 7]) ? 'Sum Assured' : 'Sum Insured';
$sumInsuredValue = $terms['sum_insured'] ?? ($terms['sumInsured2'] ?? null);
if ($sumInsuredValue !== null && $sumInsuredValue !== '') {
if (! array_key_exists($sumInsuredLabel, $value['policy_terms'])) {
$value['policy_terms'] = array_merge([$sumInsuredLabel => $sumInsuredValue], $value['policy_terms']);
}
}
array_push($result, $value);
}
if ($result) {
return $this->respond(['status' => 'success', 'code' => (count($result) ? 200 : 404), 'data' => $result], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => (count($result) ? 200 : 404), 'data' => []], 200);
}
}
public function cdSummaryData()
{
$hr_id = $this->request->getGet('hr_id');
$HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment');
// print_rr($HRAccessData);die();
if (isset($HRAccessData['allowed_cd'])) {
$allowed_cd = json_decode($HRAccessData['allowed_cd'], true);
} else {
$allowed_cd = [];
}
// $allowed_cd = [125];
// print_r($allowed_cd);die();
if (count($allowed_cd) == 0) {
return $this->respond(['status' => 'failed', 'code' => (count($allowed_cd) ? 200 : 404), 'data' => []], 200);
}
$clientId = $this->request->getGet('client_id');
$clientController = new ClientController;
$result = $clientController->deposit($clientId, $requestFrom = 'rest', []);
// print_rr($result);die();
$data = [];
foreach ($result['clientData'] as $key => $value) {
if (in_array($value->cd_ac_pk, $allowed_cd)) {
$temp['client_id'] = $value->client_id;
$temp['insurer_id'] = $value->insurer_id;
$temp['cd_ac_pk'] = $value->cd_ac_pk;
$temp['insurer_name'] = $value->insurer_name;
$temp['cd_master_account_no'] = $value->cd_master_account_no;
if (isset($result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']])) {
$balance = $result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']]->balance;
$temp['balance'] = $balance;
} else {
$temp['balance'] = "N/A";
}
array_push($data, $temp);
}
}
if ($data) {
return $this->respond(['status' => 'success', 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => (count($data) ? 200 : 404), 'data' => []], 200);
}
}
public function cdTransactionData()
{
$clientId = $this->request->getGet('client_id');
$insurerId = $this->request->getGet('insurer_id');
$cdAccountPrimaryKey = $this->request->getGet('cd_ac_pk');
$clientController = new ClientController;
$result = $clientController->view_Deposit($insurerId, $requestFrom = 'rest', $param = ['client_id' => $clientId, 'cd_ac_pk' => $cdAccountPrimaryKey]);
$data['insurer_name'] = $result['insurerName']->name;
$data['insurer_short_name'] = $result['insurerName']->short_name;
$data['account_number'] = $result['insurerName']->cd_master_account_no;
$data['total_deposit'] = $result['deposiamount']->total_credit;
$data['total_consumed'] = $result['deposiamount']->total_withdraw;
$data['total_refund'] = $result['deposiamount']->total_refund;
$data['currect_balance'] = $result['deposiamount']->balance;
$data['deposit_data'] = $result['depositdata'];
// dd($data);
if ($data) {
return $this->respond(['status' => 'success', 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => (count($data) ? 200 : 404), 'data' => []], 200);
}
}
public function claimsSearch()
{
if ($this->request->is('get')) {
$client_id = $this->request->getGet('client_id') ?? null;
$data['claim_status'] = $this->claimStatusModel
->select('id, ticket_type, display_name as claim_status')
->where('is_active', 1)
->groupStart()
->where('display_name IS NOT NULL')
->orWhere('display_name <>', '')
->groupEnd()
->whereIn('ticket_type', [1, 2, 3, 4])
->groupBy('display_name')
->findAll();
if (!empty($client_id)) {
if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$client_data = $this->clientModel->where('MD5(id)', $client_id)->first();
$client_id = $client_data['id'] ?? null;
}
$client_policy_data = $this->clientPolicyModel
->where('client_id', $client_id)
->where('is_active', 1)
->groupBy('policy_type_id')
->findAll();
$data['ticket_type'] = [];
$addedTypes = [];
foreach ($client_policy_data as $value) {
if (in_array($value['policy_type_id'], [2, 3, 4, 5]) && !in_array('1', $addedTypes)) {
$data['ticket_type'][] = ["ticket_type" => "1", "type_name" => "Claim-GMC"];
$addedTypes[] = '1';
} elseif (in_array($value['policy_type_id'], [1]) && !in_array('2', $addedTypes)) {
$data['ticket_type'][] = ["ticket_type" => "2", "type_name" => "Claim-GPA"];
$addedTypes[] = '2';
} elseif (in_array($value['policy_type_id'], [6]) && !in_array('3', $addedTypes)) {
$data['ticket_type'][] = ["ticket_type" => "3", "type_name" => "EDLI"];
$addedTypes[] = '3';
} elseif (in_array($value['policy_type_id'], [7]) && !in_array('4', $addedTypes)) {
$data['ticket_type'][] = ["ticket_type" => "4", "type_name" => "GTLI"];
$addedTypes[] = '4';
} elseif (in_array($value['policy_type_id'], [72]) && !in_array('72', $addedTypes)) {
$data['ticket_type'][] = ["ticket_type" => "72", "type_name" => "OPD"];
$addedTypes[] = '72';
}
}
usort($data['ticket_type'], fn($a, $b) => $a['ticket_type'] <=> $b['ticket_type']);
} else {
$data['ticket_type'] = [
["ticket_type" => "1", "type_name" => "Claim-GMC"],
["ticket_type" => "2", "type_name" => "Claim-GPA"],
["ticket_type" => "3", "type_name" => "EDLI"],
["ticket_type" => "4", "type_name" => "GTLI"],
];
}
$claim_type = $this->ticketController->claimType;
// unset($claim_type[1][2]);
// unset($claim_type[1][4]);
$data['claim_type'] = $claim_type;
return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
}
$db = db_connect();
$search_data = $this->request->getJSON(true); // Get JSON as associative array
if (isset($search_data['client_id']) && is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) {
$client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first();
$search_data['client_id'] = $client_data['id'] ?? null;
}
$client_id = isset($search_data['client_id']) ? (int) $search_data['client_id'] : 0;
unset($search_data['client_id']);
unset($search_data['client_branch_id']);
$policy_number = isset($search_data['policy_no']) ? $search_data['policy_no'] : null;
// From JWT (ignore body active_policy_ids to prevent widening access)
$active_policy_ids = JWTToken::getValueFromToken($this->request, 'allowed_active_policies', []);
// print_rr($active_policy_ids); die;
log_message('error', 'claim search active_policy_ids: ' . json_encode($active_policy_ids, JSON_PRETTY_PRINT));
if (! is_array($active_policy_ids)) {
$active_policy_ids = [];
}
if (empty($active_policy_ids)) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
$from_date = isset($search_data['from_date']) ? $search_data['from_date'] : null;
$to_date = isset($search_data['to_date']) ? $search_data['to_date'] : null;
$claim_status_id = isset($search_data['claim_status_id']) ? $search_data['claim_status_id'] : null;
unset(
$search_data['from_date'],
$search_data['to_date'],
$search_data['claim_status_id'],
$search_data['policy_no'],
$search_data['active_policy_ids']
);
$where = [];
// Dynamically build WHERE conditions from non-empty parameters
foreach ($search_data as $key => $value) {
if (! empty($value) && $value !== 0 && $value !== '0') {
$where["tm.$key"] = $value;
}
}
$claim_status_ids = [];
if (! empty($claim_status_id)) {
$claim_status_ids = $this->getTicketClaimStatusIdBasedOnTheDisplayName($claim_status_id);
}
$builder = $db->table('ticket_master tm');
$builder->select([
'tm.id',
'tm.ticket_type_id',
'tcs.claim_status AS original_status',
"CASE
WHEN tcs.display_name IS NULL OR tcs.display_name = ''
THEN tcs.claim_status
ELSE UPPER(tcs.display_name)
END AS status
",
"CASE
WHEN tm.tpa_claim_type IS NOT NULL OR tm.tpa_claim_type != ''
THEN tm.tpa_claim_type
ELSE 'Reimbursement'
END AS cl_type
",
'tm.claim_number AS claim_no',
'tm.claim_status_id',
'tm.is_head_approved',
'tm.tpa_id',
'tm.tpa_no',
'tm.emp_name',
'tm.emp_code',
'tm.relationship',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
'c.short_name',
'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
'(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name',
'(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name_sub',
'(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name',
'tm.acm_id',
'tm.insurer_id',
'tm.client_policy_id',
'tm.policy_no',
'tm.priority',
'tm.emp_mobile',
'tm.emp_mail',
'tm.emp_personal_mail',
'tm.mode_of_intimation',
'tm.claim_type',
'tm.hospital_name',
'tm.doa',
'tm.dod',
'tm.claim_amount',
'tm.pod_no',
'tm.date_of_join',
'tm.date_of_incep',
'tm.dob',
'tm.date_of_accident',
'tm.date_of_death',
'tm.date_of_intimat',
'tm.si_amt',
'tm.raised_date',
'tm.registration_date',
'tm.query_received_date',
'tm.denial_date',
'tm.approved_date',
'tm.settled_date',
'tm.denial_reason',
'tm.approved_letter',
'tm.approved_amount',
'tm.utr_details',
'tm.settle_letter',
'tm.return_remark',
'tm.cancel_remark',
'tm.awb_no_courier_name',
'tm.non_id_reason',
'tm.pay_initiate_date',
'tm.approved_description',
'pt.policy_type as policy_type',
'cp.policy_no as client_policy_no',
]);
$builder->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left');
$builder->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left');
$builder->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left');
$builder->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left');
$builder->join('policy_type pt', 'cp.policy_type_id = pt.id', 'left');
$builder->where('tm.is_active', 1);
if ($client_id > 0) {
$builder->where('tm.client_id', $client_id);
}
if (! empty($from_date) && ! empty($to_date)) {
$from_date_mysql = date('Y-m-d', strtotime($from_date));
$to_date_mysql = date('Y-m-d', strtotime($to_date));
$builder->where("DATE(tm.created_at) BETWEEN '$from_date_mysql' AND '$to_date_mysql'");
}
if (! empty($where)) {
$builder->where($where);
}
if (! empty($claim_status_ids)) {
$builder->whereIn('claim_status_id', $claim_status_ids);
}
if (! empty($policy_number)) {
$builder->where('cp.policy_no', $policy_number);
}
if (! empty($active_policy_ids)) {
$builder->whereIn('cp.id', $active_policy_ids);
}
$builder->orderBy('tm.id', 'DESC');
$data = $builder->get()->getResultArray();
return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
}
public function claimView()
{
try {
$ticket_id = $this->request->getGet('ticket_id');
$ticketController = new TicketController;
$data['ticket_history'] = $ticketController->ticketHistory($ticket_id);
$data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id);
$data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id);
$required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first();
$data['required_docs'] = json_decode($required_docs['required_docs'] ?? '{}', true) ?? [];
// print_rr($data['ticket_history']); die;
$filteredArray = array_filter($data['ticket_history'], function($item) {
return $item['field_name'] == 'claim_status_id';
});
$filteredArray = array_reverse(array_values($filteredArray));
$currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first();
$ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('ticket_type', $data['claims_data']['ticket_type_id'])->where('is_active', 1)->findAll();
$status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status');
// dd($filteredArray, $status_list); die;
$filtered_history = [];
$counter = 0;
foreach ($filteredArray as $key => $value) {
foreach ($status_list as $status => $display_name) {
if ($value['new_value'] == $status) {
if($display_name == 'Under Process'){
$unique_key = $display_name . str_repeat("\u{200B}", $counter++);
}else{
$unique_key = $display_name;
}
$modifiedAt = date('d-m-Y h:i A', strtotime($value['created_at']));
$reason = $this->getClaimStatusReason($status, $data['claims_data']);
$statusEntry = [
'modified_by' => "",
'modified_at' => $modifiedAt,
];
if ($reason !== '') {
$statusEntry['reason'] = ' Reason : ' . $reason;
}
$filtered_history[$unique_key] = $statusEntry;
}
}
}
// dd($filteredArray, $status_list, $filtered_history); die;
// $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []);
// // Loop through ticket_data
// foreach ($data['ticket_data'] as $status => &$fields) {
// // Search ticket_history for matching old_status_value
// foreach ($data['ticket_history'] as $history) {
// if ($history['old_status_value'] === $status) {
// // Attach modified_by and created_at
// // $fields['modified_by'] = $history['modified_by'];
// $fields['modified_by'] = "";
// $fields['modified_at'] = date('d-m-Y h:i A', strtotime($history['created_at']));
// // Break after first match (assuming latest entry is enough)
// break;
// }
// }
// }
// $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_by'] = "";
// $data['ticket_data'][$currentClaimStatus['claim_status']]['modified_at'] = $formatted = date('d-m-Y h:i A', strtotime($data['claims_data']['updated_at']));
// $new_ticket_data = [];
// foreach ($data['ticket_data'] as $oldKey => $value) {
// // Only process if key exists in status_list
// if (! isset($status_list[$oldKey])) {
// continue; // skip and do NOT add to new array
// }
// // Get new key based on mapping
// $newKey = $status_list[$oldKey];
// // Avoid duplicates
// if (! isset($new_ticket_data[$newKey])) {
// $new_ticket_data[$newKey] = $value;
// }
// }
// uasort($new_ticket_data, function ($a, $b) {
// $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']);
// $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']);
// return $timeA <=> $timeB; // Ascending
// });
// $data['ticket_data'] = $new_ticket_data;
$data['ticket_data'] = $filtered_history;
$ticketMesssageModel = new TicketMessageModel();
$ticket_message = $ticketMesssageModel
->where('is_active', 1)
->where('sender', "user")
->where('ticket_id', $ticket_id)
->orderBy('id', "desc")
->first();
$claim_file_urls = [];
if (isset($ticket_message['id'])) {
$claimFiles = new ClaimFilesModel();
$claim_files_data = $claimFiles
->select('id as claim_file_id, doc_name as claim_file_name')
->where('is_active', 1)
->where('file_type', 2)
->where('ticket_id', $ticket_id)
// ->where('ticket_message_id', $ticket_message['id'])
->findAll();
foreach ($claim_files_data as &$value) {
$value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id'];
$claim_file_urls[] = $value;
}
unset($value);
}
$data['claim_files'] = $claim_file_urls;
return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200);
} catch (\Throwable $th) {
$this->myLogger->logme("error", 'claim_view' . ($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString()));
$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,
];
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'error_data' => $errorData], 500);
}
}
public function exportCashDepositData()
{
$CashDepositData = $this->clientPolicyModel->getdepositData($this->request->getGet('client_id'), $this->request->getGet('insurer_id'));
// echo '<pre>';print_r($CashDepositData); echo '</pre>';die;
if (count($CashDepositData)) {
// Define headers and map database fields to Excel fields
$headers = [
'Date' => 'created_at',
'Type' => 'transaction_type',
'Amount' => 'amount',
'Balance' => 'balance',
'Description' => 'description',
'Insurer Name' => 'insurer_name',
'Client Name' => 'clientname',
];
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Add headers
$column = 'A';
foreach ($headers as $header => $dbField) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Add data
$row = 2;
foreach ($CashDepositData as $Cashvalue) {
$column = 'A';
foreach ($headers as $dbField) {
$sheet->setCellValue($column . $row, $Cashvalue->$dbField);
$column++;
}
$row++;
}
// Set the header for download
$filename = $CashDepositData[0]->insurer_name . '-CashDeposit.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// Save the Excel file to output
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
}
public function removeEmpAndEmpPolicyData()
{
try {
$clientPolicy = $this->clientPolicyModel->where('id', $this->request->getGet('client_policy_id'))
->where('open_for_enrollment', 1)->findAll();
if (count($clientPolicy)) {
if ($clientPolicy[0]['is_addon'] == 2) //Topup
{
if ($clientPolicy[0]['policy_type_id'] == 4) //GMC-Topup
{
$empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code'))
->where('is_addon_value', 0)
->findAll();
} else if ($clientPolicy[0]['policy_type_id'] == 5) //GMC-Parent-Topup
{
$empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code'))
->where('is_addon_value', 1)
->findAll();
}
if (count($empData)) {
foreach ($empData as $key => $value) {
$this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id'))
->where('employee_id', $value['id'])
->set(['is_active' => 0])
->update();
}
}
} else if ($clientPolicy[0]['is_addon'] == 3) //Dependent addon
{
$empData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code'))
->where('is_addon_value', 1)->findAll();
if (count($empData)) {
foreach ($empData as $key => $value) {
$this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id'))
->where('employee_id', $value['id'])
->set(['is_active' => 0])
->update();
}
$this->employeeModel->where('emp_code', $this->request->getGet('emp_code'))
->where('is_active', 1)->where('is_addon_value', 1)
->set(['is_active' => 0])
->update();
}
}
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function getEmployeeActiveOrInactivePolicy()
{
// for retail user policy only
$receviedPayload = $this->request->getGet();
if (
empty($receviedPayload['client_id']) &&
empty($receviedPayload['client_branch_id']) &&
empty($receviedPayload['emp_code'])
) {
if (! empty($receviedPayload['mobile_no']) || ! empty($receviedPayload['email_id'])) {
$retailUserData = (object) [
'id' => null,
'mobile' => $receviedPayload['mobile_no'],
'email_id' => $receviedPayload['email_id'],
];
$emp_reatail_policy_data = $this->getEmpRetailPolicy($retailUserData);
$wellness_data = ['status' => 'failed', 'message' => 'Coming soon........!'];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $emp_reatail_policy_data[0]['insurerd_name'] ?? "", 'pre_policy_count' => 0, 'emp_not_enrolled_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200);
}
}
if ($this->request->getGet('type') == 'Active') {
$policy_status = 1;
$policy_status_key = "Active";
} else {
$policy_status = 0;
$policy_status_key = "InActive";
}
$dayInterval = 10;
$ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date")
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('client_policy.client_id', $this->request->getGet('client_id'))
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id'))
->where('client_policy.is_active', 1)
->where('client_policy.policy_status', $policy_status)
->where('client_policy.enrolment_visibility', 1)
->orderby('client_policy.id', 'ASC')
->findAll();
// Retrieve employee and dependents data by passing the employee code
$employeeData = $this->employeeModel->where('emp_code', $this->request->getGet('emp_code'))
->where('client_id', $this->request->getGet('client_id'))
->where('client_branch_id', $this->request->getGet('client_branch_id'))
->where('is_active', 1)->findAll();
// get self data corporate email ore mobile no should not be null
$employeeSelfData = $this->employeeModel
->where('emp_code', $this->request->getGet('emp_code'))
->where('client_id', $this->request->getGet('client_id'))
->where('client_branch_id', $this->request->getGet('client_branch_id'))
->where('family_floater_key', 'self')
->where('is_active', 1)
->groupStart()
->where('email_corporate IS NOT NULL', null, false)
->orWhere('mobile IS NOT NULL', null, false)
->groupEnd()
->orderBy('id', 'DESC')
->get()
->getRow();
// dd(db_connect()->getLastQuery()->getQuery());
// dd($employeeSelfData->id); //employee id
$employeeName = $employeeSelfData->name ?? "";
//for get the pre enrollment policy count
$empMobileNo = $this->request->getGet('mobile_no');
$clientId = $this->request->getGet('client_id');
if (! empty($employeeSelfData) && isset($employeeSelfData->email_corporate)) {
$prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate);
$prePolicyCount = $prePolicyCountData['pre_policy_count'] ?? 0;
$empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
} else {
$prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId);
$prePolicyCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
$empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0;
}
$whereArrayForId = [];
foreach ($employeeData as $key => $value) {
array_push($whereArrayForId, $value['id']);
}
if (count($ClientPolicyData) > 0 && count($employeeData) > 0) {
$result = [];
foreach ($ClientPolicyData as $key => $ClientPolicyValue) {
if (strtotime(date('Y-m-d') > strtotime($ClientPolicyValue['claims_grace_date']))) {
continue;
}
if ($ClientPolicyValue['policy_type_id'] == 1) {
$policyGroup = 'gpa';
$data['ticket_type_id'] = 2;
$data['ticket_settled_status_id'] = 24;
$data['claim_subject'] = "Claim GPA";
$data['sum_insured_label'] = "Sum Assured";
} else if ($ClientPolicyValue['policy_type_id'] == 6) {
$policyGroup = 'other';
$data['ticket_type_id'] = 3;
$data['ticket_settled_status_id'] = 34;
$data['claim_subject'] = "Claim EDLI";
$data['sum_insured_label'] = "Sum Assured";
} else if ($ClientPolicyValue['policy_type_id'] == 7) {
$policyGroup = 'other';
$data['ticket_type_id'] = 4;
$data['ticket_settled_status_id'] = 44;
$data['claim_subject'] = "Claim GTLI";
$data['sum_insured_label'] = "Sum Assured";
} else if ($ClientPolicyValue['policy_type_id'] == 72) {
$policyGroup = 'other';
$data['ticket_type_id'] = 72;
$data['ticket_settled_status_id'] = 76;
$data['claim_subject'] = "Claim OPD";
$data['sum_insured_label'] = "Sum Insured";
} else {
$policyGroup = 'gmc';
$data['ticket_type_id'] = 1;
$data['ticket_settled_status_id'] = 11;
$data['claim_subject'] = "Claim GMC";
$data['sum_insured_label'] = "Sum Insured";
}
$terms = json_decode($ClientPolicyValue['policy_terms'], true);
$data['policy_terms'] = isset($terms['enrollment_display_key']) && ! empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup);
$data['client_id'] = $ClientPolicyValue['client_id'];
$data['client_policy_id'] = $ClientPolicyValue['id'];
$data['policy_name'] = $ClientPolicyValue['policy_type'];
$data['policy_type'] = $ClientPolicyValue['policy_type'];
$data['policy_no'] = $ClientPolicyValue['policy_no'];
$data['insurer_name'] = $ClientPolicyValue['insurer_name'];
$data['tpa_name'] = $ClientPolicyValue['tpa_name'];
$data['network_hospitals_url'] = $ClientPolicyValue['network_hospitals_url'];
$data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']);
$data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']);
$data['heading'] = $ClientPolicyValue['policy_long_name'];
$data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']);
$data['policy_status'] = $policy_status_key;
$data['pre_policy_count'] = $prePolicyCount;
$data['emp_not_enrolled_count'] = $empNotEnrolledCount;
// $data['policy_terms'] = $terms;
// if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else
// if($ClientPolicyValue['policy_type_id'] == 2){ $data['heading'] = 'Group Medical Coverage'; }else
// if($ClientPolicyValue['policy_type_id'] == 3){ $data['heading'] = 'Group Medical Coverage - Parents'; }else
// if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else
// if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; }else
// if($ClientPolicyValue['policy_type_id'] == 7){ $data['heading'] = 'Group Term Life Insurance'; }
if ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7) {
$data['floter_text_heading'] = 'Sum Insured';
} else {
if (isset($terms['family_floater']) && strpos(strtolower($terms['family_floater']), "no") !== false) {
$data['floter_text_heading'] = 'Sum Insured';
} else {
$data['floter_text_heading'] = 'Floter Sum Insured';
}
}
$employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employee_polices.employee_id', $whereArrayForId)
->where('employee_polices.client_policy_id', $ClientPolicyValue['id'])
->where('employee_polices.is_active', 1)->findAll();
if (count($employee_policy) > 0) {
$si_value = 0;
$si_premium_value = 0;
$si_gst_value = 0;
foreach ($employee_policy as $key => $value) {
if (isset($value['basic_cover_si'])) {
$si_value = ($si_value == 0) ? $value['basic_cover_si'] : $si_value;
}
if (isset($value['premium'])) {
$si_premium_value = $si_premium_value + $value['premium'];
}
if (isset($value['gst'])) {
$si_gst_value = $si_gst_value + $value['gst'];
}
}
if ($employee_policy[0]['tpa_id'] != null) {
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1';
} else {
$data['eCardDownload'] = null;
}
$data['si_value'] = $si_value;
$data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_premium_value);
$data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_gst_value);
$data['EmployeePolicy'] = $employee_policy;
//fetch claims data
$approvedClaimsAmount = $this->ticketMaster
->select('SUM(approved_amount) AS total_settled_amount')
->where('emp_code', $employee_policy[0]['emp_code'])
->where('client_policy_id', $data['client_policy_id'])
->where('claim_status_id', $data['ticket_settled_status_id'])
->groupBy('emp_code')
->groupBy('client_policy_id')
->groupBy('claim_status_id')
->get()->getRow();
$data['total_settled_amount'] = $approvedClaimsAmount ? ($approvedClaimsAmount->total_settled_amount ?? 0) : 0;
array_push($result, $data);
}
}
$emp_reatail_policy_data = $this->getEmpRetailPolicy($employeeSelfData);
$apiServiceController = new ApiServiceController;
// dd($employeeSelfData->id);
$emp_wellness_data = $apiServiceController->getWellnessUrl($employeeSelfData->id ?? null);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount, 'emp_not_enrolled_count' => $empNotEnrolledCount, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $emp_wellness_data], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
}
public function policyTermsFiter($terms, $type)
{
if (empty($terms)) {
return [];
}
$gpa = [
"sumInsured2" => "Sum Insured",
"totalSumInsured" => "Total Sum Assured",
"self" => "Self",
"self_min_age" => "Min Age",
"self_max_age" => "Max Age",
"accidentalDeathBenefit" => "Accidental Death Benefit",
"permanentTotalDisablement" => "Permanent Total Disablement",
"permanentPartialDisablement" => "Permanent Partial Disablement",
"temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit",
"accidentalHospitalizationExpenses" => "Accidental Hospitalization Expenses",
"childrenEducationWelfareFund" => "Children Education Welfare Fund",
"compassionateVisitExpenses" => "Compassionate Visit Expenses",
"compassionateVisitExpensesData" => "Compassionate Visit Expenses Data",
"brokenBoneExpenses" => "Broken Bone Expenses",
"brokenBoneExpensesData" => "Broken Bone Expenses Data",
"ambulanceCharges" => "Ambulance charges",
"ambulanceChargesData" => "Ambulance charges Data",
"burnExpenses" => "Burn Expenses",
"burnExpensesData" => "Burn Expenses Data",
"carriageOfDeadBody" => "Carriage of Dead Body",
"carriageOfDeadBodyData" => "Carriage of Dead Body Data",
"animalSnakeInsectBite" => "Animal/Snake/Insect bite",
"terrorism" => "Terrorism",
"worldwideCover" => "Worldwide Cover",
];
$gmc = [
"waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases",
"waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions",
"waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period",
"9monthwaitingperiodwaived" => "9-month waiting Period waived",
"twindelivery" => "Twin Delivery",
"maternitycoverage" => "Maternity Coverage",
"preandpostnatal" => "Pre and Post natal",
"prehospitalizationcover" => "Pre Hospitalization Cover",
"posthospitalizationcover" => "Post Hospitalization Cover ",
"congenitaldiseasesinternal" => "Congenital Diseases - Internal ",
"congenitaldiseasesexternal" => "Congenital Diseases - External ",
"roomrentlimit" => "Room Rent Limit",
"proportionatedeductionclause" => "Proportionate Deduction Clause",
"ayudhtreatmentcover" => "AYUSH treatment covered",
"lasiksurgery" => "Lasik Surgery",
"cataract" => "Cataract",
"ailmentcapping" => "Ailment capping",
"moderntreatmentsasperirdai" => "Modern Treatment ",
];
$finalarray = [];
if ($type == 'gpa') {
foreach ($gpa as $key => $value) {
if (isset($terms->$key)) {
if ($terms->$key == 1) {
$termsValue = 'Yes';
} else if ($terms->$key == 0) {
$termsValue = 'No';
} else {
$termsValue = $terms->$key;
}
$finalarray[$value] = $termsValue;
}
}
if (isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)) {
for ($i = 0; $i < count($terms->gpa_special_condition_label); $i++) {
$finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i];
}
}
} else if ($type == 'other') {
foreach ($terms as $key => $value) {
if ($key != "multiple_sum_insured" && $value != "") {
$result = ucwords(str_replace('_', ' ', $key));
$finalarray[$result] = $value;
}
}
if (isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)) {
for ($i = 0; $i < count($terms->gpa_special_condition_label); $i++) {
$finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i];
}
}
} else {
foreach ($gmc as $key => $value) {
if (isset($terms->$key)) {
if ($terms->$key == 1) {
$termsValue = 'Yes';
} else if ($terms->$key == 0) {
$termsValue = 'No';
} else {
$termsValue = $terms->$key;
}
$finalarray[$value] = $termsValue;
}
}
if (isset(($terms->special_condition_label)) && is_array($terms->special_condition_label) && is_array($terms->special_condition_input)) {
for ($i = 0; $i < count($terms->special_condition_label); $i++) {
$finalarray[$terms->special_condition_label[$i]] = $terms->special_condition_input[$i];
}
}
}
return $finalarray;
}
private function convertDateFormatDisplay($dateString)
{
// Attempt to create a DateTime object from the provided date string
$dateTime = \DateTime::createFromFormat('Y-m-d', $dateString);
if ($dateTime instanceof \DateTime) {
return $dateTime->format('d-M-Y');
} else {
return null;
}
}
public function getFEContent()
{
try {
$feContentData = $this->feContentModel->where('is_active', 1)->findAll();
if (count($feContentData) > 0) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $feContentData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
// public function getAdvertisementImage_old()
// {
// try {
// $client_id = $this->request->getGet('client_id');
// $img = $this->addImgModel->where('is_active', 1)->where('client_id',$client_id)->findAll();
// if (count($img) > 0) {
// $data = [];
// foreach ($img as $key => $value) {
// $url = base_url('public/uploads/add_image_upload/') . $value['name'];
// array_push($data, $url);
// }
// return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
// } else {
// return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'No Data'], 200);
// }
// } catch (\Throwable $th) {
// return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
// }
// }
public function getAdvertisementImage()
{
try {
$client_id = $this->request->getGet('client_id');
// get client_id & convert empty/null/undefined → 0
// $client_id = ($client_id === null || $client_id === '' || $client_id === 'undefined') ? 0 : $client_id;
// fetch images for client
$images = $this->addImgModel->where('is_active', 1)->where('client_id', $client_id)->findAll();
// if no client images → load default client 0
if (count($images) == 0) {
$images = $this->addImgModel->where('is_active', 1)->where('client_id', 0)->findAll();
}
// prepare URLs
$data = array_map(function ($img) {return base_url('public/uploads/add_image_upload/' . $img['name']);}, $images);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200);
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
}
}
public function storeFireBase()
{
try {
$firebase_token = isset($this->request->getJSON()->firebase_token) ? $this->request->getJSON()->firebase_token : null;
$mobile = isset($this->request->getJSON()->mobile) ? $this->request->getJSON()->mobile : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
// Ensure the mobile number is provided
if (empty($mobile)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Mobile number is required'], 400);
}
// Fetch employee
if (isset($mobile)) {
$employee = $this->employeeModel->where('mobile', $mobile)->where('relationship', 'self')->where('is_active', 1)->first();
} else {
$employee = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->where('is_active', 1)->first();
}
if ($employee) {
// Check if firebase_token is provided
if (! empty($firebase_token)) {
// Check if the current firebase_token is different from the new one
if ($employee['firebase_token'] !== $firebase_token) {
// Update the employee's firebase_token
$data['firebase_token'] = $firebase_token;
$id = $employee['id'];
// return json_encode($data);
// Direct database update query for testing
$db = \Config\Database::connect();
$builder = $db->table('employees');
$update_emp = $builder->update($data, ['id' => $id]);
// Check if the update was successful
if ($db->affectedRows() > 0) {
// Fetch the updated employee data
$updated_employee = $this->employeeModel->find((int) $id);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $updated_employee], 200);
} else {
log_message('error', 'Update failed. No rows affected.');
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Failed to update employee data'], 500);
}
} else {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'New Firebase Token is the same as the current one'], 200);
}
} else {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Firebase Token is required'], 400);
}
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'Employee not found'], 200);
}
} catch (\Throwable $th) {
log_message('error', 'An error occurred: ' . $th->getMessage());
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'An error occurred', 'error' => $th->getMessage()], 500);
}
}
// public function sendPushNotification()
// {
// $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H';
// $title = 'Nhance';
// $body = 'All your policy enrolled successfully ..!';
// // Initialize Firebase with the service account
// $firebase = (new Factory)
// ->withServiceAccount(APPPATH . 'Config/google-services.json')
// ->createMessaging();
// $notification = Notification::create($title, $body);
// $message = CloudMessage::withTarget('token', $deviceToken)
// ->withNotification($notification);
// try {
// $firebase->send($message);
// return $this->response->setJSON(['status' => 'success']);
// } catch (MessagingException $e) {
// //return $this->response->setJSON(['status' => 'error', 'message' => $e->getMessage()]);
// log_message('error', $e->getMessage());
// }
// }
public function getBackToEnrolledDetails()
{
// Get query parameters
$empCode = $this->request->getGet('emp_code');
$clientId = $this->request->getGet('client_id');
$clientBranchId = $this->request->getGet('client_branch_id');
if (! $empCode || ! $clientId || ! $clientBranchId) {
return $this->fail("emp_code, client_id, and client_branch_id are required parameters.");
}
//Fetch active employee details
$employees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at')
->where([
'emp_code' => $empCode,
'client_id' => $clientId,
'client_branch_id' => $clientBranchId,
'is_active' => 1,
])
->findAll();
//Find status of self
$selfEmployee = array_filter($employees, function ($employee) {
return $employee['relationship'] === 'Self';
});
$data['self_status'] = ! empty($selfEmployee) ? array_values($selfEmployee)[0]['emp_status'] : null;
$data['self_enrolled_time'] = ! empty($selfEmployee) ? array_values($selfEmployee)[0]['updated_at'] : null;
$data['self_employee_id'] = ! empty($selfEmployee) ? array_values($selfEmployee)[0]['id'] : null;
//Fetch employee policy details
$employeeIds = array_column($employees, 'id');
$policies = $this->employeePolicyModel->whereIn('employee_id', $employeeIds)->where('is_active', 1)->findAll();
//Find the stage of enrolment process
$employeeStatuses = array_column($employees, 'emp_status');
$employeePolicyStatuses = array_column($policies, 'status');
$uniqueStatuses = array_unique(array_merge($employeeStatuses, $employeePolicyStatuses));
if (count($uniqueStatuses) > 1) {
$enrolmentStagekey = 1;
} else {
if ($uniqueStatuses[0] == 'draft') {
$enrolmentStagekey = 0;
} else {
$enrolmentStagekey = 2;
}
}
$enrolmentStage = ['Draft Only', 'Intermittent Enrollment', 'Successful Enrollment'];
$data['enrolment_stage'] = $enrolmentStage[$enrolmentStagekey];
$data['revert_employee_data'] = [];
$data['revert_employee_policy_data'] = [];
if ($enrolmentStagekey == 1) {
//Find active employee history
$empIdsWithoutSelf = $employeeIds;
$key = array_search($data['self_employee_id'], $empIdsWithoutSelf);
unset($empIdsWithoutSelf[$key]);
foreach ($empIdsWithoutSelf as $key => $pk) {
$retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employees', $pk);
if ($retrivedData != false) {
array_push($data['revert_employee_data'], $retrivedData);
}
}
//Find inactive employee history
$inActiveEmployees = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at')
->where([
'emp_code' => $empCode,
'client_id' => $clientId,
'client_branch_id' => $clientBranchId,
'is_active' => 0,
])
->findAll();
$inActiveEmployeeIds = array_column($inActiveEmployees, 'id');
foreach ($inActiveEmployeeIds as $key => $pk) {
$retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employees', $pk);
if ($retrivedData != false) {
array_push($data['revert_employee_data'], $retrivedData);
}
}
//Merged active and inactive employees , employee_polict history
$mergedEmpIds = array_merge($employeeIds, $inActiveEmployeeIds);
$empPolicyData = $this->employeePolicyModel->whereIn('employee_id', $mergedEmpIds)->findAll();
$employeePolicyIds = array_column($empPolicyData, 'id');
foreach ($employeePolicyIds as $key => $pk) {
$retrivedData = $this->retriveOldData($data['self_enrolled_time'], 'employee_polices', $pk);
if ($retrivedData != false) {
array_push($data['revert_employee_policy_data'], $retrivedData);
}
}
}
if ($this->request->getGet('revert_data') == 1) {
//update data back to employee
if (count($data['revert_employee_data'])) {
foreach ($data['revert_employee_data'] as $key => $val) {
$this->employeeModel->where('id', $val['id'])->set($val['data'])->update();
}
}
//update data back to employee policy
if (count($data['revert_employee_policy_data'])) {
foreach ($data['revert_employee_policy_data'] as $key => $val) {
$this->employeePolicyModel->where('id', $val['id'])->set($val['data'])->update();
}
}
//update enrolled status for self
if (count($data['revert_employee_data']) || count($data['revert_employee_policy_data'])) {
$this->employeeModel->where('id', $data['self_employee_id'])->set(['emp_status' => 'enrolled'])->update();
$data['retrieve_status'] = 'Data revert successfully';
} else {
$data['retrieve_status'] = 'There is no data to revert';
}
}
// Fetch all policies related to these employees who currently active
$current_employee_data = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at')
->where([
'emp_code' => $empCode,
'client_id' => $clientId,
'client_branch_id' => $clientBranchId,
'is_active' => 1,
])
->findAll();
$Ids = array_column($current_employee_data, 'id');
$policies = $this->employeePolicyModel->whereIn('employee_id', $Ids)->where('is_active', 1)->findAll();
// Group policies by policy_id
$groupedPolicies = [];
foreach ($policies as $policy) {
$policyId = $policy['client_policy_id'];
if (! isset($groupedPolicies[$policyId])) {
$groupedPolicies[$policyId] = [
'policy_id' => $policy['id'],
'client_policy_id' => $policy['client_policy_id'],
'uhid' => $policy['uhid'],
'status' => $policy['status'],
'basic_cover_si' => $policy['basic_cover_si'],
'date_coverage' => $policy['date_coverage'],
'policy_end_date' => $policy['policy_end_date'],
'members' => [],
];
}
// Add member details to the current policy
foreach ($current_employee_data as $employee) {
if ($employee['id'] === $policy['employee_id']) {
$groupedPolicies[$policyId]['members'][] = [
'id' => $employee['id'],
'emp_code' => $employee['emp_code'],
'name' => $employee['name'],
'relationship' => $employee['relationship'],
'dob' => $employee['dob'],
'emp_status' => $employee['emp_status'],
'is_addon_value' => $employee['is_addon_value'],
];
}
}
}
// Re-index the grouped policies
$data['currentPolicies'] = array_values($groupedPolicies);
return $this->respond(['data' => $data]);
}
public function retriveOldData($self_enrolled_time, $table, $pk)
{
$historyData = $this->auditHistoryModel->where('pk', $pk)->where('table_name', $table)->findAll();
$beforeEnrolled = [];
$afterEnrolled = [];
// Split the array
foreach ($historyData as $val) {
if ($val['created_at'] <= $self_enrolled_time) {
$beforeEnrolled[] = $val;
} else {
$afterEnrolled[] = $val;
}
}
if (count($beforeEnrolled) && count($afterEnrolled)) { //After enrolment edited some of the data
$temp['table'] = $table;
$temp['id'] = $pk;
// Extract earliest `old_value` for each `field_name`
$originalValues = [];
foreach ($afterEnrolled as $entry) {
$field = $entry['field_name'];
// If the field is not already in originalValues , update it
if (! isset($originalValues[$field])) {
$originalValues[$field] = $entry['old_value'];
}
}
$temp['data'] = $originalValues;
return $temp;
} else if (! count($beforeEnrolled) && ! count($afterEnrolled)) { //After enrolment created new data
$temp['table'] = $table;
$temp['id'] = $pk;
$temp['data'] = ['is_active' => 0];
return $temp;
} else if (! count($beforeEnrolled) && count($afterEnrolled)) { //After enrolment created new data and edited some of the data
$temp['table'] = $table;
$temp['id'] = $pk;
$temp['data'] = ['is_active' => 0];
return $temp;
} else if (count($beforeEnrolled) && ! count($afterEnrolled)) { //After enrolment nothing changes from the data
return false;
}
}
public function findThePolicyIsOpenForEnrollment($plicy_id)
{
$policy = $this->clientPolicyModel->where('id', $plicy_id)->where('open_for_enrollment', 1)->find();
if ($policy) {
return true;
} else {
return false;
}
}
// ---------------- TICKET API's ---------------------------------------------------------------------------------------------------
//Get Data from post for inserting ticket and message
public function initiateClaim()
{
$received_data = $this->request->getPost();
$this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? []));
$get_file_data = $this->request->getFiles('claim_docs') ?? null;
$get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
$policy_transaction_id = $this->request->getPost('policy_transaction_id') ?? null;
if (is_string($received_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $received_data['client_id'])) {
$client_data = $this->clientModel->where('MD5(id)', $received_data['client_id'])->first();
$received_data['client_id'] = $client_data['id'] ?? null;
}
$client_policy_data = $this->clientPolicyModel->where('id', $received_data['client_policy_id'] ?? null)->first();
$isduplicate = checkDuplicateClaim([
'doa' => change_date_format($received_data['doa'] ?? '') ?? null,
'emp_code' => $received_data['emp_code'] ?? null,
'claim_amount' => $received_data['claim_amount'] ?? null,
'policy_no' => $client_policy_data['policy_no'] ?? null,
]);
if ($isduplicate) {
$response = ['status' => false, 'code' => 404, 'message' => 'Claim already exist'];
return $this->respond($response, 200);
}
if (! empty($policy_transaction_id)) {
$response = $this->retailClaimInitiate($received_data);
return $this->respond($response, 200);
}
if (is_string($get_docs_name)) {
$decoded = json_decode($get_docs_name, true);
$get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : [];
} elseif (! is_array($get_docs_name)) {
$get_docs_name = [];
}
// print_r($get_file_data); die;
$employee_id = $received_data['emp_id'];
$client_policy_id = $received_data['client_policy_id'];
$insured_emp_id = $received_data['insured_emp_id'];
$file_data = [];
if (isset($get_file_data) && ! empty($get_file_data)) {
$file_path = WRITEPATH . 'uploads/claim_files/';
$file_data = storage_multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS);
}
if (empty($received_data['doa'])) {
$received_data['doa'] = null;
} else {
$ticket_data['doa'] = change_date_format($received_data['doa']);
}
if (empty($received_data['dod'])) {
$received_data['dod'] = null;
} else {
$ticket_data['dod'] = change_date_format($received_data['dod']);
}
$sql = "
select
cp.policy_type_id,
cl_rm.user_id as acm_id,
cp.insurer_id as insurer_id,
cp.tpa_id as tpa_id,
emp.client_id,
emp.id as emp_id,
cp.policy_no,
emp.emp_code,
emp_pol.tpa_id as tpa_no,
emp.name as emp_name,
emp.email_corporate as emp_mail,
emp.mobile as emp_mobile,
empl.id as insured_emp_id,
empl.name as insured_name,
empl.relationship,
CASE
WHEN cp.policy_type_id IN (2, 3, 4, 5) THEN 1
WHEN cp.policy_type_id = 1 THEN 2
WHEN cp.policy_type_id = 6 THEN 3
WHEN cp.policy_type_id = 7 THEN 4
ELSE cp.policy_type_id
END AS ticket_type_id
from employees emp
left join employees empl on empl.id = :insured_emp_id: and empl.is_active = 1 and empl.emp_status = 'active'
left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = :client_policy_id: and emp_pol.is_active = 1
left join client_policy cp on cp.id = emp_pol.client_policy_id and cp.is_active = 1
left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3
where emp.id = :employee_id: and emp.is_active = 1 and emp.emp_status = 'active'
limit 1 ";
$binds = ['insured_emp_id' => $insured_emp_id, 'client_policy_id' => (int) $client_policy_id, 'employee_id' => $employee_id];
$emp_ticket_data = $this->employeeModel->query($sql, $binds)->getResultArray();
// print_r(db_connect()->getLastQuery()); die;
if (! empty($emp_ticket_data)) {
$received_relationship = $received_data['relationship'] ?? null;
unset($received_data['relationship']);
$fetchData = $emp_ticket_data[0];
$claimStatusQuery = $this->claimStatusModel
->select('id')
->where('ticket_type', $fetchData['ticket_type_id'])
->orderBy('id', 'asc');
if ($fetchData['ticket_type_id'] == 1 && ! empty($fetchData['tpa_no'])) {
$results = $claimStatusQuery->findAll(2);
$fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id'];
} else if ($fetchData['ticket_type_id'] == 72 && ! empty($fetchData['tpa_no'])) {
$results = $claimStatusQuery->findAll(2);
$fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id'];
} else {
$fetchData['claim_status_id'] = $claimStatusQuery->first()['id'];
}
$fetchData['priority'] = 1;
$fetchData['mode_of_intimation'] = 3;
if (! isset($received_data['claim_type']) || (isset($received_data['claim_type']) && empty($received_data['claim_type']))) {
$received_data['claim_type'] = 1;
}
$fetchData = array_merge($fetchData, $received_data);
// $fetchData['relationship'] = isset($fetchData['relationship']) ? strtolower($fetchData['relationship']) : null;
$fetchData['relationship'] = strtolower($received_relationship ?? $fetchData['relationship'] ?? '') ?: null;
$fetchData['created_by'] = $fetchData['emp_id'];
$fetchData['claim_created_by'] = "USER";
// print_r($fetchData); die;
$insert_status = $this->ticketMaster->insert($fetchData);
$ticket_id = $this->ticketMaster->insertID();
if ($insert_status && ! empty($ticket_id)) {
//insert first history
$this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id);
$messagesData = [
'ticket_id' => $ticket_id ?? null,
'sender' => 'user',
'claim_status' => $fetchData['claim_status_id'] ?? null,
'emp_mail' => $fetchData['emp_mail'] ?? null,
'mail_subject' => $fetchData['subject'] ?? "New Claim",
'mail_content' => $fetchData['message'] ?? "New Claim",
];
$ticket_message_id = null;
if (! empty($messagesData['ticket_id'])) {
$TicketMessageModel = new TicketMessageModel();
$ticket_message_id = $TicketMessageModel->insert($messagesData);
}
$this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id);
$mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
if (gettype($mail_sent_status) == 'array') {
$message = 'Claim Iniated Successfully';
return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
} else {
$mail_sent_status_object = json_decode($mail_sent_status);
}
if ($mail_sent_status_object->status == 'success') {
$message_insert_status = $this->ticketController->autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id);
if ($message_insert_status) {
$message = 'Claim Initiated Successfully';
return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
} else {
$message = 'Claim Initiated, Mail Sent Successfully';
$this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
}
} else {
$message = 'Claim Initiated, Failed to send Mail ';
$this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
}
} else {
$message = 'Something Went Wrong';
return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
}
} else {
return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'The employee is not active.'])->setStatusCode(200);
}
}
public function retailClaimInitiate($data)
{
if (isset($data['policy_transaction_id'])) {
$policy_transaction_model = new PolicyTransactionModel();
$policy = $policy_transaction_model
->select('policy_transaction.*, clients.client_name, clients.phone as client_mobile, clients.email as client_email')
->join('clients', 'policy_transaction.client_id = clients.id')
->where('policy_transaction.is_active', 1)
->where('clients.is_active', 1)
->where('policy_transaction.id', $data['policy_transaction_id'])
->first();
if (! empty($policy)) {
$claimData = [
'ticket_type_id' => $data['policy_type_id'],
'policy_transaction_id' => $data['policy_transaction_id'],
'claim_status_id' => 62,
'policy_no' => $policy['policy_no'],
'client_policy_id' => $policy['client_policy_id'],
'insurer_id' => $policy['insurer_id'],
'client_id' => $policy['client_id'] ?? null,
'agent_id' => $policy['agent_id'] ?? null,
'manager_id' => $policy['manager_id'] ?? null,
'vehicle_id' => $policy['vehicle_id'] ?? null,
'insured_name' => $policy['client_name'] ?? null,
'emp_name' => $policy['client_name'] ?? null,
'emp_mobile' => $policy['client_mobile'] ?? null,
'emp_mail' => $policy['client_email'] ?? null,
'emp_personal_mail' => $policy['client_email'] ?? null,
'claim_type' => $data['claim_type'],
'claim_description' => $data['claim_description'],
'created_by' => $policy['client_id'] ?? null,
];
$ticket_id = $this->ticketMaster->insert($claimData);
if ($ticket_id) {
$mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
if (gettype($mail_sent_status) == 'array') {
$message = 'Claim Iniated Successfully';
return ['status' => true, 'code' => 200, 'message' => $message];
} else {
$mail_sent_status_object = json_decode($mail_sent_status);
}
if ($mail_sent_status_object->status == 'success') {
$message = 'Claim Initiated Successfully';
return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message];
} else {
$message = 'Claim Initiated, Failed to send Mail ';
$this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
return ['status' => false, 'code' => 400, 'message' => $message];
}
$message = 'Claim Initiated Successfully';
return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message];
} else {
$message = 'Claim Initiation failed';
return ['status' => false, 'code' => 404, 'message' => $message];
}
} else {
$message = 'Claim Initiation failed. Policy data not found';
return ['status' => false, 'code' => 404, 'message' => $message];
}
} else {
$message = 'Claim Initiation failed';
return ['status' => false, 'code' => 404, 'message' => $message];
}
}
public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null, $tpa_claim_push = true, $ir_docs = false)
{
if (! empty($data) && ! empty($ticket_id)) {
$insert_ids = [];
$pdf_exist_in_the_file = false;
$claim_file = new ClaimFilesModel();
foreach ($data as $key => $value) {
$data = [
'ticket_id' => $ticket_id,
'doc_name' => $value['doc_name'],
'file_name' => $value['file_name'],
'url' => $value['file_path'],
'file_type' => 2,
'ticket_message_id' => $ticket_message_id,
'mime_type' => getMimeTypeByFileName($value['file_name']),
];
if ($ir_docs == true) {
$data['docs_for_ir'] = 1;
}
$insert_ids[] = $claim_file->insert($data);
if (getMimeTypeByFileName($value['file_name']) == "application/pdf") {
$pdf_exist_in_the_file = true;
}
}
if (! empty($insert_ids)) {
try {
helper('merge_pdf');
merge_ticket_pdfs((int) $ticket_id);
} catch (\Throwable $e) {
log_message('error', 'EmployeeRestController::handleCliamFiles | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage());
}
}
$count = $this->ticketMaster->where('id', $ticket_id)->where('is_active', 1)->where('tpa_claim_push_reference_no IS NULL')->countAllResults();
log_message('error', 'Ticket validation | Ticket ID: ' . $ticket_id . ' | Matching active tickets with NULL TPA reference: ' . $count);
if ($count > 0 && $pdf_exist_in_the_file && $tpa_claim_push == true) {
try {
// this call for TPA integration
$apiServiceController = new ApiServiceController();
$apiServiceController->pushClaims($ticket_id);
log_message('error', "pushClaims function called with Ticket ID: {$ticket_id}, In Employee Rest Controller");
} catch (\Throwable $e) {
log_message('error', "Error in TPA Claim Push via Benifits or HR : ApiServiceController pushClaims function call for Ticket ID: {$ticket_id}. Error: " . $e->getMessage() . " Trace: " . $e->getTraceAsString());
}
} else {
if ($tpa_claim_push == false) {
log_message('error', 'Skip the TPA claim push for IR DOCUMENTS');
} else if ($count == 0) {
log_message('error', 'TPA claim push skipped as the claim reference number is already generated.');
} else {
log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist.");
}
}
if($tpa_claim_push == false){
try {
// this call for TPA integration Multiple document push for IR DOCUMENTS
$apiServiceController = new ApiServiceController();
$apiServiceController->pushClaimFiles($ticket_id);
log_message('error', "pushClaimFiles IR FILE SUBMISSION function called with Ticket ID: {$ticket_id}, In Employee Rest Controller");
} catch (\Throwable $e) {
log_message('error', "Error in TPA Claim Files Push via CRM : ApiServiceController pushClaims function call for Ticket ID: {$ticket_id}. Error: " . $e->getMessage() . " Trace: " . $e->getTraceAsString());
}
}
return $insert_ids;
}
return [];
}
//department
// public function get_ticket_type()
// {
// $ticket_type = $this->ticketController->ticketType;
// $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
// // print_r($ticket_type); die;
// return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
// }
public function get_ticket_type()
{
try {
$client_id = $this->request->getGet('client_id');
$emp_code = $this->request->getGet('emp_code');
if (empty($client_id) || empty($emp_code)) {
$this->myLogger->logme('error', "Missing required parameters: client_id={$client_id}, emp_code={$emp_code}");
// return $this->response->setJSON([
// 'status' => false,
// 'code' => 400,
// 'message' => 'client_id and emp_code are required'
// ])->setStatusCode(400);
$ticket_type = $this->ticketController->ticketType;
$claim_type = $this->ticketController->claimType;
// unset($claim_type[1][2]);
// unset($claim_type[1][4]);
$ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
return $this->response->setJSON(['ticket_type' => $ticket_type, 'claim_type' => $claim_type])->setStatusCode(200);
}
// Get policy type ids
$policy_type_ids = $this->employeePolicyModel
->select('client_policy.policy_type_id')
->join('employees', 'employee_polices.employee_id = employees.id')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id')
->where('employees.is_active', 1)
->whereIn('employees.emp_status', ['active', 'expired'])
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.client_id', $client_id)
->where('employees.emp_code', $emp_code)
->groupBy('employee_polices.client_policy_id')
->findAll();
if (! $policy_type_ids) {
$this->myLogger->logme('error', "No policy types found for client_id={$client_id}, emp_code={$emp_code}");
return $this->response->setJSON([
'status' => false,
'code' => 404,
'message' => 'No policy types found',
])->setStatusCode(200);
}
$this->myLogger->logme('error', "Policy type IDs fetched: " . json_encode($policy_type_ids));
$ticket_type = $this->ticketController->ticketType;
$claim_type = $this->ticketController->claimType;
// unset($claim_type[1][2]);
// unset($claim_type[1][4]);
$filtered = [];
$mapping = [
2 => 1,
3 => 1,
4 => 1,
5 => 1,
1 => 2,
6 => 3,
7 => 4,
72 => 72,
];
foreach ($policy_type_ids as $value) {
$ticketTypeId = $value['policy_type_id'] ?? null;
if (isset($mapping[$ticketTypeId]) && isset($ticket_type[$mapping[$ticketTypeId]])) {
$mappedId = $mapping[$ticketTypeId];
$mappedName = $ticket_type[$mappedId];
// Use mappedId as key to avoid duplicates
$filtered[$mappedId] = [
'id' => $mappedId,
'name' => $mappedName,
];
$this->myLogger->logme('error', "Ticket type resolved: ID={$ticketTypeId}, Name={$mappedName}");
} else {
$this->myLogger->logme('error', "No valid ticket type mapping for policy_type_id={$ticketTypeId}");
}
}
$filtered = array_values($filtered);
return $this->response->setJSON(['status' => true, 'code' => 200, 'ticket_type' => $filtered, 'claim_type' => $claim_type])->setStatusCode(200);
} catch (\Throwable $e) {
$this->myLogger->logme('error', "Error in get_ticket_type: " . $e->getMessage() . " Trace: " . $e->getTraceAsString());
return $this->response->setJSON([
'status' => false,
'code' => 500,
'message' => 'Internal Server Error',
])->setStatusCode(500);
}
}
//ticket data
public function get_ticket_data()
{
$priorityType = $this->ticketController->priorityType;
$modeOFIntimate = $this->ticketController->modeOFIntimate;
$claimType = $this->ticketController->claimType;
$relationshipType = $this->ticketController->relationshipType;
$ticketTypeArray = $this->ticketController->ticketType;
$emp_id = $this->request->getGet('emp_id');
$ticket_type = $this->request->getGet('ticket_type') ?? null;
$ticket_id = $this->request->getGet('ticket_id') ?? null;
$mobile_number = $this->request->getGet('mobile_number') ?? null;
$email_id = $this->request->getGet('email_id') ?? null;
$request = \Config\Services::request();
$uri = $request->uri->getPath();
$returnType = "";
// $returnType = (strpos($uri, 'api') !== false) ? 'api' : 'web';
// dd($emp_id);
if (empty($emp_id)) {
return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'emp_id is required.'])->setStatusCode(200);
}
$retail_ticket_data = [];
if (! empty($mobile_number) || ! empty($email_id)) {
$retail_ticket_data = $this->getRetailPolicyClaimData($this->request->getGet());
}
$TicketMasterModel = new TicketMasterModel();
$ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id);
// print_r($ticket_data);die;
if (! empty($ticket_data)) {
// $client_claim_status = [
// 'Received' => [1, 2, 3, 4, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38],
// 'Rejected' => [8, 49, 55, 60],
// 'Cancelled' => [13, 47, 53, 58],
// 'Returned' => [14, 48, 54, 59],
// 'Closed' => [12, 22, 32, 42],
// 'Approved' => [9, 20, 30, 40],
// 'Settled' => [11, 24, 34],
// 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56],
// ];
// $client_claim_status = [
// 'Claim Received' => [1, 2, 3, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38],
// 'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56],
// 'Information Required' => [4],
// 'Approved' => [9, 20, 30, 40],
// 'Settled' => [11, 24, 34],
// 'Denial Review Awaited' => [66],
// 'Rejected' => [8, 49, 55, 60],
// ];
// construct the claim status
$client_claim_status = $this->getClaimStatusGrouped();
foreach ($ticket_data as $key => $value) {
foreach ($client_claim_status as $claim_key => $claim_value) {
if (in_array($value['claim_status_id'], $claim_value)) { // Corrected argument order
$ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
} else if (in_array($value['old_status_id'], $claim_value)) {
$ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
}
}
$ticket_data[$key]['priority_type'] = $priorityType[$value['priority']] ?? null;
$ticket_data[$key]['mode_of_intimate_type'] = $modeOFIntimate[$value['mode_of_intimation']] ?? null;
$ticket_data[$key]['relationship_type'] = ucfirst($value['relationship']) ?? null;
$claimPrimaryTypey = "1";
if (in_array($value['claim_type'], [2, 3, 4])) {
$claimPrimaryTypey = "2";
}
$ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null;
$ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null;
$claim_file_urls = [];
if (isset($value['ticket_message_id'])) {
$claimFiles = new ClaimFilesModel();
$claim_files_data = $claimFiles
->select('id as claim_file_id, doc_name as claim_file_name')
->where('is_active', 1)
->where('file_type', 2)
->where('ticket_id', $value['id'])
->where('ticket_message_id', $value['ticket_message_id'])
->findAll();
foreach ($claim_files_data as &$value) {
$value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id'];
$claim_file_urls[] = $value;
}
unset($value);
}
// always set the key (empty if no files found)
$ticket_data[$key]['claim_files'] = $claim_file_urls;
}
}
$ticket_data = array_merge($ticket_data, $retail_ticket_data);
return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200);
}
public function getRetailPolicyClaimData($receviedPayload)
{
try {
// Create minimal retail user object
$retailUserData = (object) [
'id' => null,
'mobile' => $receviedPayload['mobile_number'] ?? null,
'email_id' => $receviedPayload['email_id'] ?? null,
];
// Get retail policies of user
$empRetailPolicyData = $this->getEmpRetailPolicy($retailUserData);
if (empty($empRetailPolicyData)) {
return [];
}
// Fetch ticket data for each policy
$retail_ticket_data = [];
foreach ($empRetailPolicyData as $policy) {
$tickets = $this->ticketMaster
->select("
ticket_master.*,
vehicle.vehicle_no,
(
SELECT th1.old_value
FROM ticket_history th1
JOIN ticket_claim_status tcs ON th1.old_value = tcs.id
WHERE th1.field_name = 'claim_status_id'
AND th1.ticket_id = ticket_master.id
AND th1.id = (
SELECT MAX(th2.id)
FROM ticket_history th2
WHERE th2.ticket_id = th1.ticket_id
AND th2.field_name = 'claim_status_id'
)
) AS old_status_id
")
->join("vehicle", "ticket_master.vehicle_id = vehicle.id", "left")
->where('ticket_master.is_active', 1)
->where('ticket_master.client_id', $policy['client_id'])
->where('ticket_master.policy_transaction_id', $policy['policy_transaction_id'])
->findAll();
if (! empty($tickets)) {
$retail_ticket_data = array_merge($retail_ticket_data, $tickets);
}
}
if (empty($retail_ticket_data)) {
return [];
}
// Fetch grouped claim statuses
$client_claim_status = $this->getClaimStatusGrouped(); // Format expected: [status => [ids]]
$claim_type = $this->getClaimTypeMaster('internal');
// Convert claim type for quick access
$typeMap = array_column($claim_type, 'claim_type', 'id');
// Map status name to each ticket
foreach ($retail_ticket_data as &$ticket) {
$ticket['claim_status'] = null; // Default
$ticket['claim_type_name'] = $typeMap[$ticket['claim_type']] ?? null;
if ($ticket['ticket_type_id'] == 8) {
$ticket['ticket_policy_type'] = 'Motor';
}
foreach ($client_claim_status as $status_name => $status_list) {
if (in_array($ticket['claim_status_id'], $status_list)) {
$ticket['claim_status'] = $status_name;
break;
}
if (in_array($ticket['old_status_id'], $status_list)) {
$ticket['claim_status'] = $status_name;
break;
}
}
}
return $retail_ticket_data;
} catch (\Throwable $th) {
$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,
];
$this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getRetailPolicyClaimData: Exception: " . json_encode($errorData ?? []));
return [];
}
}
public function getClaimStatusGrouped()
{
// Fetch active claim statuses
$ticketClaimStatus = $this->claimStatusModel
->select('id, display_name')
->where('display_name IS NOT NULL')
->where('is_active', 1)
->findAll();
$result = [];
foreach ($ticketClaimStatus as $row) {
$name = $row['display_name'];
$id = $row['id'];
if (! isset($result[$name])) {
$result[$name] = [];
}
$result[$name][] = $id;
}
return $result;
}
// not in use did for testing
public function encrypt_for_sso(): string
{
$key = "32D1D5535157AF3D4667ADAB0CC795D77D022BB281AD3272EB134C72BD0B185E";
$userParams = [
"name" => "John Doe 3",
"email" => "john.doe3@email.com",
"memberId" => "TEST-REL-01",
"gender" => "Male",
"dob" => "1997-01-01",
"policyName" => "Nhance DEMO",
"phone" => "6676126763",
"employeeId" => "EMP-NHANCE-TEST-03",
"policyNumber" => "EMP-NHANCE-TEST-03",
"policyStartDate" => "2025-09-08",
"policyEndDate" => "2026-09-08",
"moduleName" => "home",
"relation" => "self",
"planId" => "NHANCE-PLAN-1",
];
$algorithm = "aes-256-cbc";
// Derive 32-byte key from SHA256
$derivedKey = hash('sha256', $key, true);
// Fixed IV (must be 16 bytes)
$iv = "getvisitappdocom";
// Build query string like Node.js
$plainText = '';
foreach ($userParams as $k => $v) {
$plainText .= "&{$k}={$v}";
}
$plainText = ltrim($plainText, '&');
// echo ($plainText); die;
// Encrypt
$encrypted = openssl_encrypt($plainText, $algorithm, $derivedKey, OPENSSL_RAW_DATA, $iv);
// Base64URL encode (same as Node.js output)
$output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
// return $output;
$baseURL = 'https://web.getvisitapp.net';
$clientId = 'nhance-gt-2tx7';
$finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId;
return $finalUrl;
}
public function getEmployeePolicyCount()
{
$db2 = \Config\Database::connect('preDB');
$mobile_no = $this->request->getGet('mobile_no');
$builder = $db2->table('employees')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.is_active', 1)
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->where('employees.mobile', $mobile_no)
->groupBy('employee_polices.client_policy_id');
$query = $builder->get();
$count = $query->getNumRows(); // count grouped rows manually
return $this->respond([
'status' => 'success',
'code' => 200,
'policy_count' => $count,
], 200);
}
public function getClaimFiles()
{
$ticket_id = $this->request->getGet('ticket_id');
}
// public function getPreEmployeePolicyCount($mobile_no, $clientId = null)
// {
// log_message('error', 'getPreEmployeePolicyCount called with params : ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId], true));
// if (empty($mobile_no)) {
// log_message('error', 'Mobile number is empty or null.');
// return 0;
// }
// $client_short_name = [];
// if(!empty($clientId)){
// $client_data = $this->clientModel->where('is_active', 1)->where('id', $clientId)->first();
// $client_short_name = $client_data['short_name'] ?? null;
// }
// $post_data = [
// 'mobile_number' => $mobile_no,
// 'client_data' => $client_short_name
// ];
// $response = $this->callThirdPartyAPI($post_data, 'getPreEmployeePolicyCount');
// print_r( $response); die;
// return $response['data'] ?? 0 ;
// try {
// log_message('error', 'Attempting to connect to preDB...');
// $db2 = \Config\Database::connect('preDB');
// log_message('error', 'Connection to preDB successful.');
// } catch (\Throwable $e) {
// log_message('error', 'DB connection to preDB failed: ' . $e->getMessage());
// return 0;
// }
// try {
// log_message('error', 'Building query to count employee policies...');
// $builder = $db2->table('employees')
// ->join('employee_polices', 'employees.id = employee_polices.employee_id')
// ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id')
// ->where('employees.is_active', 1)
// ->whereIn('employees.emp_status', ['draft', 'enrolled'])
// ->where('employee_polices.is_active', 1)
// ->whereIn('employee_polices.status', ['draft', 'enrolled'])
// ->where('cp.enrolment_visibility', 1)
// ->where('cp.open_for_enrollment', 1)
// ->whereIn('cp.policy_type_id', [1,2,6,7])
// ->where('employees.mobile', $mobile_no)
// ->orderBy('employees.created_at', 'desc')
// ->groupBy('employee_polices.client_policy_id');
// if(!empty($clientId)){
// $builder->where('employees.client_id', $clientId);
// }
// log_message('error', 'Executing policy count query...');
// $query = $builder->get();
// $count = $query->getNumRows();
// // dd($db2->getLastQuery());
// log_message('error', 'Policy count result: ' . $count);
// return $count;
// } catch (\Throwable $e) {
// log_message('error', 'Query failed in getPreEmployeePolicyCount: ' . $e->getMessage());
// return 0;
// }
// }
public function getPreEmployeePolicyCount($mobile_no, $clientId = null, $email = null)
{
log_message('error', 'STEP 1: getPreEmployeePolicyCount called with params: ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId, 'email' => $email]));
if (empty($mobile_no) && empty($email)) {
log_message('error', 'STEP 2: Mobile number and Email is empty or null. Returning 0.');
return 0;
}
$client_short_name = null;
if (! empty($clientId)) {
log_message('error', 'STEP 3: Fetching client short name for client ID: ' . $clientId);
$client_data = $this->clientModel->where('is_active', 1)->where('id', $clientId)->first();
if ($client_data) {
$client_short_name = $client_data['short_name'] ?? null;
log_message('error', 'STEP 4: Found client short name: ' . $client_short_name);
} else {
log_message('error', 'STEP 4: No client found for ID: ' . $clientId);
}
} else {
log_message('error', 'STEP 3: No clientId provided. Skipping client lookup.');
}
if (! empty($email)) {
$post_data = [
'email_id' => $email,
'client_short_name' => $client_short_name,
];
} else {
$post_data = [
'mobile_number' => $mobile_no,
'client_short_name' => $client_short_name,
];
}
log_message('error', 'STEP 5: Calling third-party API with payload: ' . json_encode($post_data));
try {
$response = $this->callThirdPartyAPI($post_data, 'getPreEmployeePolicyCount');
log_message('error', 'STEP 6: API raw response: ' . json_encode($response ?? []));
$response = json_decode($response ?? '{}', true);
$count = $response ?? [];
log_message('error', 'STEP 8: Final count extracted: ' . json_encode($count ?? []));
return $count;
} catch (\Throwable $e) {
log_message('error', 'STEP 6: API call failed: ' . $e->getMessage());
return 0;
}
}
private function callThirdPartyAPI($postData, $endPoint)
{
$client = \Config\Services::curlrequest();
$url = env('PRE_ENROLLMENT_BASEURL') . $endPoint;
$headers = ['App-Signature' => getenv('APP_SIGNATURE')];
$response = $client->post($url, ['json' => $postData, 'headers' => $headers, 'http_errors' => false]);
// return json_decode($response->getBody(), true);
return $response->getBody();
}
//--------------------------------------------------------------------------------------------
public function hrFileUpload()
{
try {
$post_data = [
'client_id' => $this->request->getPost('client_id') ?? null,
'client_branch_id' => $this->request->getPost('client_branch_id') ?? null,
'policy_id' => $this->request->getPost('policy_id') ?? null,
'file_action' => $this->request->getPost('file_action') ?? null,
'created_by' => $this->request->getPost('created_by') ?? null,
'file_name' => $this->request->getFile('file_name') ?? null,
'policy_no' => $this->request->getPost('policy_no') ?? null,
];
// print_r($post_data); die;
$Query = $this->clientPolicyModel
->select("
client_policy.id as client_policy_id ,
client_policy.client_id as client_id,
client_policy.policy_type_id as policy_type_id,
client_policy.is_addon as is_addon ,
client_policy.open_for_enrollment as OpenForEnrollment ,
client_policy.inception_type as inception_type,
client_policy.policy_no as policy_no,
client_policy.insurer_id as insurer_id,
DATE_FORMAT(client_policy.policy_start_date, '%d-%m-%Y') AS policy_start_date,
DATE_FORMAT(client_policy.policy_end_date, '%d-%m-%Y') AS policy_expiry_date,
CASE WHEN policy_type.allocg IN ('Non-EB', 'Marine') THEN 'Non-EB' ELSE 'EB' END as allocg
", false)
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->where('md5(client_policy.client_id)', $post_data['client_id'])
->where('client_policy.client_branch_id', $post_data['client_branch_id'])
->where('client_policy.is_active', 1);
// ->where('client_policy.policy_status', $this->request->getGet('policy_status'))
if (is_array($post_data['policy_id'])) {
$Query->whereIn('client_policy.id', $post_data['policy_id']);
} else {
$Query->where('client_policy.id', $post_data['policy_id']);
}
$ClientPolicyData = $Query->first();
if (empty($post_data['client_id'])) {
return $this->respondCreated(['status' => false, 'message' => 'Client is required', 'data' => []]);
}
// Handle raw client_id vs MD5
if (is_string($post_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $post_data['client_id'])) {
$client_data = $this->clientModel->where('MD5(id)', $post_data['client_id'])->first();
$post_data['client_id'] = $client_data['id'];
} else {
$client_data = $this->clientModel->where('id', $post_data['client_id'])->first();
}
if (empty($client_data)) {
return $this->respondCreated(['status' => false, 'message' => 'Invalid Client Id', 'data' => []]);
}
// print_r($client_data); die;
if ($client_data['hr_file_processed_by'] == 1 && $ClientPolicyData['allocg'] == 'EB') {
$responce = $this->fileUploadInFilesTable($post_data);
} else {
$responce = $this->fileUploadInHrFileUploadTable($post_data);
}
return $this->respondCreated($responce);
} catch (\Exception $e) {
// return $this->failServerError($e->getMessage());
log_message('error', 'Error in hrFileUpload: ' . $e->getMessage() . ' in file ' . $e->getFile() . ' on line ' . $e->getLine() . ' Trace: ' . $e->getTraceAsString());
return $this->respondCreated(['status' => false, 'message' => $e->getMessage(), 'data' => []]);
}
}
public function fileUploadInHrFileUploadTable($post_data)
{
// Check file
$file = $post_data['file_name'];
if (!$file || !$file->isValid()) {
return [
'status' => false,
'message' => "Invalid file or file not uploaded.",
'data' => [],
];
}
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return [
'status' => false,
'message' => "Only Excel files (xls, xlsx, ods, csv) are allowed.",
'data' => [],
];
}
// Upload folder path (S3-only when FILE_STORAGE_DRIVER=s3)
$uploadPath = WRITEPATH . 'uploads/hr_files/';
$newFileName = storage_file_Upload($file, $uploadPath, UPLOAD_EXT_EXCEL);
if ($newFileName === '') {
return [
'status' => false,
'message' => 'File upload failed.',
'data' => [],
];
}
// Prepare data
$data = [
'client_id' => $post_data['client_id'],
'client_branch_id' => $post_data['client_branch_id'],
'policy_id' => $post_data['policy_id'],
'policy_no' => $post_data['policy_no'],
'file_name' => $newFileName,
'file_action' => $post_data['file_action'],
'status' => 'Yet to start',
'created_by' => $post_data['created_by'],
'updated_by' => $post_data['created_by'],
];
// Save into DB
$result = $this->hrFileUploadModel->insert($data);
if ($result) {
$this->giveNotificationToClientsAccountManager($data);
$response = [
'status' => true,
'message' => 'File uploaded successfully',
'data' => $data,
];
return $response;
}
}
public function fileUploadInFilesTable($post_data)
{
$employeeController = new EmployeeController();
$responce = $employeeController->employeesUplodWithEvents($post_data);
// print_r($responce); die;
if ($responce['status']) {
$this->giveNotificationToClientsAccountManager($post_data);
}
return $responce;
// if(isset($responce['file_id'])){
// $file_data = $this->getDataFromHrFilesTable(['hr_id' => $responce['created_by']]);
// $responce['data'] = $file_data;
// return $responce;
// }else{
// $responce['data'] = [];
// return $responce;
// }
}
private function giveNotificationToClientsAccountManager($data)
{
$client_name = $this->clientModel->where('id', $data['client_id'])->findAll()[0]['client_name'] ?? [];
$account_manager_email = $this->clientRMModel->findAccountManagerEmail($data['client_id']);
$templateName = "hr_endorsement_template";
$mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? [];
if (empty($mailTemplate)) {
//empty mail template please update the template in database or create one..!!
log_message("error", "Empty mail template for inception_addition please update the template in database or create one..!!");
return;
}
$data['file_action'] = ucwords(preg_replace("/_/", " ", $data['file_action']));
$mailTemplate['mail_content'] = str_replace('%file_action%', $data['file_action'] ?? '', $mailTemplate['mail_content']);
$mailTemplate['mail_content'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['mail_content']);
$mailTemplate['mail_content'] = str_replace('%policy_no%', $data['policy_no'] ?? '', $mailTemplate['mail_content']);
$mailTemplate['subject'] = str_replace('%subject%', $data['file_action'] ?? '', $mailTemplate['subject']);
$mailTemplate['subject'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['subject']);
$from_mail = "";
$to_mail = $account_manager_email;
$subject = $mailTemplate['subject'];
$message = $mailTemplate['mail_content'];
$cc_string = "";
$attachments = "";
$reply_to = "";
$bcc_string = "";
MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
}
public function updateHrFileUploadData()
{
try {
$id = $this->request->getPost('id');
if (! $id) {
return $this->failValidationErrors('ID is required for update.');
}
// Prepare data
$data = [
'client_id' => $this->request->getPost('client_id'),
'client_branch_id' => $this->request->getPost('client_branch_id'),
'policy_id' => $this->request->getPost('policy_id'),
'policy_no' => $this->request->getPost('policy_no'),
'file_action' => $this->request->getPost('file_action'),
'status' => $this->request->getPost('status'),
'updated_by' => $this->request->getPost('updated_by'),
];
// Check if record exists
$record = $this->hrFileUploadModel->find((int) $id);
if (! $record) {
return $this->failNotFound("Record with ID {$id} not found.");
}
// Update record
$this->hrFileUploadModel->update($id, $data);
return $this->respond([
'status' => true,
'message' => 'File record updated successfully',
'data' => $data,
], 200);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function hrFileDownload($id = null)
{
try {
$file_id = $this->request->getGet('id') ?? $id;
$client_id = $this->request->getGet('cliend_id') ?? null;
$client_data = [];
if (! empty($client_id)) {
if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$client_data = $this->clientModel->where('MD5(id)', $client_id)->first();
} else {
$client_data = $this->clientModel->where('id', $client_id)->first();
}
}
// Find record
if ($client_data && $client_data['hr_file_processed_by'] == 1) {
$record = $this->fileModel->where('id', (int) $file_id)->find();
$uploadPath = WRITEPATH . 'uploads/excel';
} else {
$record = $this->hrFileUploadModel->where('id', (int) $file_id)->find();
$uploadPath = WRITEPATH . 'uploads/hr_files';
}
if (! $record) {
return $this->failNotFound("File record not found");
}
$storedName = basename((string) ($record[0]['file_name'] ?? ''));
if ($storedName === '') {
return $this->failNotFound("File not found on server");
}
$storage = \Config\Services::getFileStorageService();
$result = $storage->download($uploadPath, $storedName);
if (! ($result['success'] ?? false)) {
return $this->failNotFound("File not found on server");
}
$downloadAs = storage_upload_display_name($storedName);
if (! empty($result['path']) && is_file($result['path'])) {
return $this->response->download($result['path'], null)->setFileName($downloadAs);
}
if (! empty($result['content'])) {
return $this->response->download($downloadAs, $result['content'])->setFileName($downloadAs);
}
return $this->failNotFound("File not found on server");
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
// public function hrFileList()
// {
// try {
// $request = service('request');
// $builder = $this->hrFileUploadModel
// ->select('hr_file_upload.* , c.short_name , cb.branch_name , lc.name as first_name ');
// // Allowed filter keys
// $filters = [
// 'client_id',
// 'client_branch_id',
// 'policy_no',
// 'file_action',
// 'status',
// 'created_by'
// ];
// // Apply filters dynamically
// foreach ($filters as $key) {
// $value = $request->getGetPost($key); // supports both GET and POST
// if (!empty($value)) {
// $builder->where($key, $value);
// }
// }
// // Fetch results
// $builder->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left');
// $builder->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left');
// $builder->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left');
// $data = $builder->findAll();
// return $this->respond([
// 'status' => true,
// 'message' => 'File list fetched successfully',
// 'data' => $data
// ]);
// } catch (\Exception $e) {
// return $this->failServerError($e->getMessage());
// }
// }
public function hrFileList()
{
try {
$request = service('request');
$search_data = $request->getGetPost() ?? []; // supports both GET and POST
$table = "";
if (isset($search_data['hr_file_type']) && $search_data['hr_file_type'] == "CRM") {
$data = $this->getDataFromHrFileUploadTable($search_data);
$table = "hr_file_upload";
} else {
if (is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) {
$client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first();
$search_data['client_id'] = $client_data['id'];
} else {
$client_data = $this->clientModel->where('id', $search_data['client_id'])->first();
}
if ($client_data['hr_file_processed_by'] == 1) {
$data = $this->getDataFromHrFilesTable($search_data);
$table = "files";
} else {
$data = $this->getDataFromHrFileUploadTable($search_data);
$table = "hr_file_upload 2";
}
}
return $this->respond([
'status' => "success",
'message' => 'File list fetched successfully',
'data' => $data,
'table' => $table,
]);
} catch (\Exception $th) {
$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,
];
return $this->failServerError($th->getMessage());
}
}
public function getDataFromHrFileUploadTable($search_data)
{
// Start builder from model
// $builder = $this->hrFileUploadModel
// ->select('hr_file_upload.* , c.short_name , cb.branch_name , lc.name as first_name')
// ->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left')
// ->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left')
// ->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left');
$builder = $this->hrFileUploadModel
->select("
hr_file_upload.id,
hr_file_upload.client_id,
hr_file_upload.client_branch_id,
hr_file_upload.policy_id,
hr_file_upload.policy_no,
hr_file_upload.file_name,
hr_file_upload.file_action,
hr_file_upload.created_at,
hr_file_upload.created_by,
hr_file_upload.updated_at,
hr_file_upload.updated_by,
c.short_name,
cb.branch_name,
lc.name as first_name,
CASE
WHEN f.status IS NULL
THEN hr_file_upload.status
ELSE CONCAT(UCASE(LEFT(f.status, 1)), LCASE(SUBSTRING(f.status, 2)))
END AS status,
'0' as file_error_status,
'' as file_error_status
", false)
->join('clients c', 'c.id = hr_file_upload.client_id AND c.is_active = 1', 'left')
->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left')
->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left')
->join(
'(SELECT f1.*
FROM files f1
WHERE f1.is_active = 1
ORDER BY f1.id DESC
LIMIT 1) f',
'f.hr_file_id = hr_file_upload.id',
'left'
);
// Allowed filter keys
$filters = [
'client_id',
'client_branch_id',
'policy_id',
'policy_no',
'file_action',
'status',
'created_by',
];
// Apply filters dynamically
foreach ($filters as $key) {
$value = $search_data[$key] ?? null; // supports both GET and POST
if (! empty($value)) {
$builder->where("hr_file_upload.$key", $value);
}
}
// Execute query
$builder->orderBy('hr_file_upload.id', 'DESC');
$data = $builder->get()->getResultArray();
if (! empty($data)) {
return $data;
}
return [];
}
public function getDataFromHrFilesTable($search_data)
{
$file_download_base = base_url('downloadFileTableFile/');
$builder = $this->fileModel
->select("
files.id,
files.client_id,
files.client_branch_id,
files.policy_id,
cp.policy_no,
files.file_name,
files.action as file_action,
files.created_at,
files.created_by,
files.updated_at,
files.updated_by,
c.short_name,
cb.branch_name,
lc.name as first_name,
CONCAT(UCASE(LEFT(files.status, 1)), LCASE(SUBSTRING(files.status, 2))) as status,
CASE
WHEN status = 'failed' THEN 1
ELSE 0
END AS file_error_status,
CONCAT('{$file_download_base}', files.id, '/api') AS file_download_link
", false)
->join('clients c', 'files.client_id = c.id AND c.is_active = 1', 'left')
->join('client_branch cb', 'files.client_branch_id = cb.id AND cb.is_active = 1', 'left')
->join('client_policy cp', 'files.policy_id = cp.id AND cp.is_active = 1', 'left')
->join('level_contacts lc', 'files.hr_id = lc.id AND lc.contact_type = "client" AND lc.is_active = 1', 'left');
if (isset($search_data['policy_id']) && ! empty($search_data['policy_id'])) {
$builder->where("files.policy_id", $search_data['policy_id']);
}
if (isset($search_data['created_by']) && ! empty($search_data['created_by'])) {
$builder->where("files.hr_id", $search_data['created_by']);
}
if (isset($search_data['policy_no']) && ! empty($search_data['policy_no'])) {
$builder->where("cp.policy_no", $search_data['policy_no']);
}
if (isset($search_data['client_id']) && ! empty($search_data['client_id'])) {
if (is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) {
$builder->where("MD5(files.client_id)", $search_data['client_id']);
} else {
$builder->where("files.client_id", $search_data['client_id']);
}
}
if (isset($search_data['file_id']) && ! empty($search_data['file_id'])) {
$builder->where("files.id", $search_data['file_id']);
}
// Execute query
$builder->orderBy('files.id', 'DESC');
$data = $builder->get()->getResultArray();
if (! empty($data)) {
return $data;
}
return [];
}
public function hrFileUploadMasters()
{
$type = $this->request->getGet('type');
if (empty($type)) {
$type = 'EB';
}
try {
//for inception upload
if ($type == 'EB') {
$data['actions'] = ['all' => 'All', 'addition' => 'Addition (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
} else {
$data['actions'] = ['addition' => 'Adding New Assets', 'deletion' => 'Removing Assets', 'correction' => 'Correction of assets details'];
}
return $this->respond([
'status' => true,
'message' => 'File inception upload masters',
'data' => $data,
]);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function checkTpaApiEnable($policy_id = null, $api_name = null, $return_type = 'api')
{
$this->myLogger->logme('error', '--- START checkTpaApiEnable ---');
try {
// Step 1: Handle input parameters
if (empty($policy_id)) {
$policy_id = $this->request->getGet('policy_id');
$api_name = $this->request->getGet('api_name');
log_message('error', "Input parameters fetched from GET: policy_id={$policy_id}, api_name={$api_name}");
} else {
log_message('error', "Input parameters received directly: policy_id={$policy_id}, api_name={$api_name}");
}
// Step 2: Validate policy_id
if (empty($policy_id)) {
log_message('error', 'Policy ID is empty');
if ($return_type == 'api') {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Policy ID missing']);
}
return false;
}
// Step 3: Fetch policy data
log_message('error', "Fetching policy data for policy_id={$policy_id}");
$policy_data = $this->clientPolicyModel
->where('is_active', 1)
->where('id', $policy_id)
->first();
if (empty($policy_data)) {
log_message('error', "Policy data not found for policy_id={$policy_id}");
if ($return_type == 'api') {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Policy data not found']);
}
return false;
}
// Step 4: Check for TPA ID
if (empty($policy_data['tpa_id'])) {
log_message('error', "TPA ID not found for policy_id={$policy_id}");
if ($return_type == 'api') {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'TPA ID not found']);
}
return false;
}
$tpa_id = $policy_data['tpa_id'];
log_message('error', "Found TPA ID={$tpa_id} for policy_id={$policy_id}");
// Step 5: Check if API service is enabled
log_message('error', "Checking TPA API service for TPA ID={$tpa_id} and API name={$api_name}");
$tpaApiServiceModel = new TpaApiSeviceModel();
$api_data = $tpaApiServiceModel
->where('is_active', 1)
->where('api_name', $api_name)
->where('tpa_id', $tpa_id)
->first();
if (! empty($api_data)) {
log_message('error', "API '{$api_name}' is enabled for TPA ID={$tpa_id}");
if ($return_type == 'api') {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'API services enabled']);
}
return true;
} else {
log_message('error', "API '{$api_name}' is NOT enabled for TPA ID={$tpa_id}");
if ($return_type == 'api') {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'API services not enabled']);
}
return false;
}
} catch (\Throwable $th) {
log_message('error', 'Exception in checkTpaApiEnable: ' . $th->getMessage());
if ($return_type == 'api') {
return $this->respond(['status' => false, 'code' => 500, 'message' => 'Internal Server Error']);
}
return false;
} finally {
log_message('error', '--- END checkTpaApiEnable ---');
}
}
public function getEcardURL()
{
try {
$id = $this->request->getGet('id');
$emp_code = $this->request->getGet('emp_code');
$client_policy_id = $this->request->getGet('client_policy_id');
$policy_no = $this->request->getGet('policy_no');
$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();
if (count($employee_policy) > 0) {
if ($employee_policy[0]['tpa_id'] != null) {
if ($employee_policy[0]['tpa_primary_id'] == 2) //Medi assist
{
$mediAssistController = new MediAssistApiController();
$data['eCardDownload'] = $mediAssistController->EcardRequest($emp_code, $policy_no);
} else {
$data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1';
}
} else {
$data['eCardDownload'] = null;
}
} else {
$data['eCardDownload'] = null;
}
return $this->respond(['status' => true, 'message' => '', 'data' => $data]);
} catch (\Exception $e) {
}
}
public function addEmpRetailPolicy()
{
$this->myLogger->logme("error", "EMPLOYEE-RETAIL-POLICY-CONTROLLER - addEmpRetailPolicy: Received payload = " . json_encode($this->request->getJSON() ?? []));
try {
$payload = $this->request->getJSON(true);
$pk = $payload['retail_policy_id'] ?? null;
$emp_id = $payload['emp_id'] ?? null;
if (empty($emp_id)) {
$this->myLogger->logme("error", "addEmpRetailPolicy: emp_id is missing");
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'emp_id is required'], 200);
}
if (isset($payload['policy_end_date']) && ! empty($payload['policy_end_date'])) {
$payload['policy_end_date'] = change_date_format($payload['policy_end_date'], 'd M Y', 'Y-m-d');
} else {
$payload['policy_end_date'] = null;
}
if (isset($payload['policy_start_date']) && ! empty($payload['policy_start_date'])) {
$payload['policy_start_date'] = change_date_format($payload['policy_start_date'], 'd M Y', 'Y-m-d');
} else {
$payload['policy_start_date'] = null;
}
if (empty($pk)) {
$payload['created_by'] = $emp_id;
$emp_retail_policy_id = $this->employeeRetailPolicy->insert($payload);
} else {
$payload['updated_by'] = $emp_id;
$emp_retail_policy_id = $this->employeeRetailPolicy->where('id', $pk)->set($payload)->update();
}
if ($emp_retail_policy_id) {
$this->myLogger->logme("error", "addEmpRetailPolicy: Employee Retail Policy created successfully. Policy ID = " . $emp_retail_policy_id);
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Employee Retail Policy created successfully',
'data' => [
'emp_retail_policy_id' => $emp_retail_policy_id,
],
], 200);
} else {
$this->myLogger->logme("error", "addEmpRetailPolicy: Failed to create Employee Retail Policy. Insert returned false");
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Failed to create Employee Retail Policy'], 500);
}
} catch (\Throwable $th) {
$this->myLogger->logme("error", "addEmpRetailPolicy: Exception occurred - " . $th->getMessage());
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Internal server error: ' . $th->getMessage()], 500);
}
}
public function getEmpRetailPolicy($employeeData)
{
$this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Given params: " . json_encode($employeeData ?? []));
try {
$emp_id = $employeeData->id ?? null;
$mobile_number = $employeeData->mobile ?? null;
$email_id = $employeeData->email_id ?? null;
$emp_retail_policy_data = [];
if ($emp_id != null) {
$emp_retail_policy_data = $this->employeeRetailPolicy
->select("
employee_retail_policies.emp_id,
employee_retail_policies.insurer_id,
employee_retail_policies.policy_type_id,
employee_retail_policies.policy_no,
DATE_FORMAT(employee_retail_policies.policy_start_date, '%d-%b-%Y') as policy_start_date,
DATE_FORMAT(employee_retail_policies.policy_end_date, '%d-%b-%Y') as policy_end_date,
policy_type.policy_type,
policy_type.long_name as policy_type_long_name,
insurers.name as insurer_name,
insurers.short_name as insurer_short_name
")
->join('insurers', 'employee_retail_policies.insurer_id = insurers.id')
->join('policy_type', 'employee_retail_policies.policy_type_id = policy_type.id')
->where('employee_retail_policies.is_active', 1)
->where('emp_id', $emp_id)
->findAll();
}
$emp_retail_client_data = [];
if (! empty($mobile_number)) {
$emp_retail_client_data = $this->clientModel
->select("
'{$emp_id}' AS emp_id,
clients.id as client_id,
clients.client_name as insurerd_name,
clients.email as insurerd_mail,
clients.phone as insurerd_mobile,
policy_transaction.id as policy_transaction_id,
policy_transaction.insurer_id,
policy_transaction.policy_type_id,
policy_transaction.policy_no,
policy_transaction.client_policy_id,
policy_transaction.vehicle_id,
vehicle.vehicle_no,
DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date,
DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date,
policy_type.policy_type,
policy_type.long_name as policy_type_long_name,
insurers.name as insurer_name,
insurers.short_name as insurer_short_name
")
->join('policy_transaction', 'policy_transaction.client_id = clients.id')
->join('insurers', 'policy_transaction.insurer_id = insurers.id')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id')
->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type', "inception")
->where('clients.is_active', 1)
->where('clients.client_type', 2)
->where('clients.phone IS NOT NULL')
->where('clients.phone', $mobile_number)
->findAll();
} else {
$emp_retail_client_data = $this->clientModel
->select("
'{$emp_id}' AS emp_id,
clients.id as client_id,
clients.client_name as insurerd_name,
clients.email as insurerd_mail,
clients.phone as insurerd_mobile,
policy_transaction.id as policy_transaction_id,
policy_transaction.insurer_id,
policy_transaction.policy_type_id,
policy_transaction.policy_no,
policy_transaction.client_policy_id,
policy_transaction.vehicle_id,
vehicle.vehicle_no,
DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date,
DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date,
policy_type.policy_type,
policy_type.long_name as policy_type_long_name,
insurers.name as insurer_name,
insurers.short_name as insurer_short_name
")
->join('policy_transaction', 'policy_transaction.client_id = clients.id')
->join('insurers', 'policy_transaction.insurer_id = insurers.id')
->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id')
->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left')
->where('policy_transaction.is_active', 1)
->where('policy_transaction.action_type', "inception")
->where('clients.is_active', 1)
->where('clients.client_type', 2)
->where('clients.email IS NOT NULL')
->where('clients.email', $email_id)
->findAll();
}
// print_r($this->clientModel->getLastQuery()); die;
$complete_emp_retail_policy_data = array_values(
array_column(
array_merge($emp_retail_client_data ?: [], $emp_retail_policy_data ?: []),
null,
'policy_no'
)
);
return $complete_emp_retail_policy_data;
} catch (\Throwable $th) {
$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,
];
$this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Exception: " . json_encode($errorData ?? []));
return [];
}
}
public function getPolicyTypeAndInsurer()
{
$policy_type_ids = [8, 37, 38, 39, 62];
$policy_type = $this->policyTypeModel
->select('id as policy_type_id, policy_type, long_name as policy_type_long_name')
->where('is_active', 1)
->whereIn('id', $policy_type_ids)
->findAll();
$insurer_category = ['general'];
$insurers = $this->insurerModel
->select('id as insurer_id, name as insurer_name, short_name as insurer_short_name')
->where('is_active', 1)
->where('category', $insurer_category)
->findAll();
return $this->respond([
'status' => 'success',
'code' => 200,
'data' => [
'insurer' => $insurers,
'policy_type' => $policy_type,
],
], 200);
}
public function getClaimTypeMaster($return_type = 'api')
{
$data = db_connect()->table('partner_claim_type_master')->select('id,claim_type')->where('is_active', 1)->get()->getResultArray();
if (! $data) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
if ($return_type == 'api') {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data]);
} else {
return $data;
}
}
public function uploadIRDocs()
{
$ticket_id = $this->request->getPost('ticket_id') ?? null;
$get_file_data = $this->request->getFiles('claim_docs') ?? null;
$get_docs_name = $this->request->getPost('claim_doc_names') ?? [];
$required_docs = $this->request->getPost('required_docs') ?? [];
if (is_string($get_docs_name)) {
$decoded = json_decode($get_docs_name, true);
$get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : [];
} elseif (! is_array($get_docs_name)) {
$get_docs_name = [];
}
$file_data = [];
if (isset($get_file_data) && ! empty($get_file_data)) {
$file_path = WRITEPATH . 'uploads/claim_files/';
$file_data = storage_multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS);
}
$result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true);
if (! empty($result)) {
// $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update();
db_connect()->query(
"UPDATE ticket_master SET required_docs = ? WHERE id = ?",
[$required_docs, $ticket_id]
);
$apiServiceController = new ApiServiceController();
$tpaIrFilePushResponce = $apiServiceController->pushClaimFiles($ticket_id);
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files uploaded successfully', 'tpaIrFilePushResponce' => $tpaIrFilePushResponce], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Failed to upload the file'], 200);
}
}
public function getTicketClaimStatusIdBasedOnTheDisplayName($claim_status_id)
{
$claim_status_data_display_name = $this->claimStatusModel->where('is_active', 1)->where('id', $claim_status_id)->first();
$claim_status_data_id = $this->claimStatusModel
->select('id')
->where('is_active', 1)
->where('display_name', $claim_status_data_display_name['display_name'])
->findAll();
$claim_status_data_id = array_column($claim_status_data_id, 'id');
return $claim_status_data_id;
}
public function downloadCdSplitUpFile()
{
try {
$file_id = $this->request->getGet('id');
// Find record
$record = $this->batchFileModel->where('MD5(id)', $file_id)->first();
if (! $record) {
$data['message'] = 'File record not found';
return view('errors/404', $data);
}
$uploadPath = WRITEPATH . 'uploads/import_excel';
$fileName = basename((string) ($record['file_name'] ?? ''));
$storage = \Config\Services::getFileStorageService();
$result = $storage->download($uploadPath, $fileName);
if (! ($result['success'] ?? false)) {
$data['message'] = 'The Physical File Not Found';
return view('errors/404', $data);
}
$downloadAs = storage_upload_display_name($fileName);
if (! empty($result['path']) && is_file($result['path'])) {
return $this->response->download($result['path'], null)->setFileName($downloadAs);
}
if (! empty($result['content'])) {
return $this->response->download($downloadAs, $result['content'])->setFileName($downloadAs);
}
$data['message'] = 'The Physical File Not Found';
return view('errors/404', $data);
} catch (\Exception $e) {
$data['message'] = 'File record not found';
return view('errors/404', $data);
}
}
public function getHrDashboad()
{
// $dashboard_id = $this->request->getGet('dashboard_id') ?? null;
$client_id = $this->request->getPost('client_id') ?? null;
$client_policy_id = $this->request->getPost('client_policy_id') ?? null;
$received_data = $this->request->getJSON(true) ?? null;
// 🔐 Move this to .env in real projects
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$is_tpa_dashboard_enable = $this->clientPolicyModel
->select('tpa.dashboard_id')
->join('tpa', 'client_policy.tpa_id = tpa.id')
->where('client_policy.id', $received_data['client_policy_id'])
->where('tpa.dashboard_id IS NOT NULL')
->first();
$payload = [
'resource' => [
'dashboard' => 2,
],
'params' => (object) ['client_policy' => $received_data['client_policy_id']], // MUST be object for Metabase
'exp' => time() + (10 * 60), // 10 minutes
];
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// // You can either return token only
// return $this->response->setJSON([
// 'token' => $token,
// 'iframe_url' => "https://your-metabase-domain/embed/dashboard/{$token}#bordered=true&titled=true"
// ]);
// if($this->request->getGet('api') == 1)
// {
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
],
'is_tpa_dashboard_enable' => ! empty($is_tpa_dashboard_enable ?? []),
]);
// }
return view('meta_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
public function getHrTpaDashboard($client_policy_id = null, $return_type = 'api')
{
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
if ($return_type === 'api') {
$received_data = $this->request->getJSON(true) ?? [];
$policy_id = $received_data['client_policy_id'] ?? null;
} else {
// Internal call
$policy_id = $client_policy_id;
}
if (empty($policy_id)) {
return $this->respond([
'status' => 'failed',
'message' => 'Client Policy ID is required.',
'data' => [],
]);
}
$client_policy_data = $this->clientPolicyModel
->select('tpa.dashboard_id')
->join('tpa', 'client_policy.tpa_id = tpa.id')
->where('client_policy.id', $policy_id)
->first();
$database_id = isset($client_policy_data['dashboard_id']) ? (int) $client_policy_data['dashboard_id'] : null;
if (empty($database_id)) {
return $this->respond([
'status' => 'failed',
'message' => 'There is no dashboard for this TPA.',
'data' => [],
]);
}
$payload = [
'resource' => [
'dashboard' => $database_id,
],
'exp' => time() + (10 * 60),
'params' => (object) ['client_policy' => $policy_id ], // MUST be object for Metabase
];
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
if ($return_type === 'internal') {
// Return raw data for internal usage
return [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
];
}
return $this->respond([
'status' => 'success',
'message' => 'Dashboard fetched successfully.',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
],
]);
}
// get policy files
public function getPolicyAndEndorsementFiles()
{
$cd_ac_pk = $this->request->getGet('cd_ac_pk') ?? null;
$cdModel = new ClientDepositModel();
$cd_data = $cdModel->where('id', $cd_ac_pk)
->where('is_active', 1)
->where('client_policy_id IS NOT NULL')
->first();
if (empty($cd_data)) {
$this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Deposit data found for cd_ac_pk=' . $cd_ac_pk);
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
}
$client_policy_data = $this->clientPolicyModel
->where('id', $cd_data['client_policy_id'])
->where('is_active', 1)
->first();
if (empty($client_policy_data)) {
$this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Policy data found for client_policy_id=' . $cd_data['client_policy_id']);
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
}
$policyTransactionModel = new PolicyTransactionModel();
$builder = $policyTransactionModel
->where('is_active', 1)
->where('policy_no', $client_policy_data['policy_no'])
->where('action_type', $cd_data['event_name']);
if (! empty($cd_data['endorsement_no']) && $cd_data['event_name'] != 'inception') {
$builder->where('endorsement_no', $cd_data['endorsement_no']);
}
$policy_transaction_data = $builder->findAll();
if (empty($policy_transaction_data)) {
$this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Policy Transaction data found for policy_no=' . $client_policy_data['policy_no']);
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
}
$policy_transaction_ids = array_column($policy_transaction_data, 'id');
$ptFilesModel = new PTFileModel();
$pt_files_data = $ptFilesModel->where('is_active', 1)->whereIn('pt_id', $policy_transaction_ids)->findAll();
if (empty($pt_files_data)) {
$this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No PT Files data found for pt_ids=' . implode(',', $policy_transaction_ids));
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200);
}
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files found', 'data' => $pt_files_data], 200);
}
// download policy file
public function downloadPolicyFiles()
{
$pt_file_id = $this->request->getGet('file_id') ?? null;
if (empty($pt_file_id)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'File ID is required'], 200);
}
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$ptFilesModel = new PTFileModel();
$pt_files_data = $ptFilesModel->where('is_active', 1)->where('id', $pt_file_id)->first();
if (empty($pt_files_data)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
}
$storedFileName = basename((string) ($pt_files_data['file_name'] ?? ''));
if ($storedFileName === '') {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
}
$storage = \Config\Services::getFileStorageService();
$result = $storage->download($uploadFilePath, $storedFileName);
if (! ($result['success'] ?? false)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
}
$downloadAs = storage_upload_display_name($storedFileName);
if (! empty($result['path']) && is_file($result['path'])) {
return $this->response->download($result['path'], null)->setFileName($downloadAs);
}
if (! empty($result['content'])) {
return $this->response
->download($downloadAs, $result['content'])
->setFileName($downloadAs);
}
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200);
}
public function bulkEcardDownloadAsZip()
{
$received_data = $this->request->getJSON(true) ?? null;
$this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Received payload = ' . json_encode($received_data ?? []));
if (empty($received_data['client_policy_id']) && empty($received_data['emp_policy_ids'])) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'client_policy_id or employee_policy_ids is required'], 200);
}
if (empty($received_data['hr_id'])) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'hr_id is required'], 200);
}
$employee_data = $this->employeePolicyModel->getEmployeeDataWithPolicyUsingClientPolicyIdOrEmployeePolicyIds($received_data);
if (empty($employee_data)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No employee data found for the policy'], 200);
}
$received_data['folder_name'] = 'bulk_ecards_' . $employee_data[0]['policy_no'] . '_' . date('Y-m-d_H-i-s');
// Dispatch background job to process the bulk e-card download
$r = Jobs::addJob(['job_name' => 'bulkEcardDownloadAsZipFromS3', 'payload' => $received_data]);
$this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Job dispatched with result = ' . json_encode($r ?? []));
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Bulk E-card download process started. Link share your mail'], 200);
}
public function bulkEcardDownloadAsZipNew()
{
$received_data = $this->request->getJSON(true) ?? [];
if (empty($received_data['client_policy_id']) && empty($received_data['emp_policy_ids'])) {
return $this->respond(['status' => false, 'message' => 'client_policy_id or employee_policy_ids is required'], 400);
}
if (empty($received_data['hr_id'])) {
return $this->respond(['status' => false, 'message' => 'hr_id is required'], 400);
}
$employee_data = $this->employeePolicyModel->getEmployeeDataWithPolicyUsingClientPolicyIdOrEmployeePolicyIds($received_data, 1);
if (empty($employee_data)) {
return $this->respond(['status' => false, 'message' => 'No employee data found'], 404);
}
// Define naming convention
$folderName = 'bulk_ecards_' . ($employee_data[0]['client_short_name'] ?? 'export') . '_' . date('Ymd_His');
$insert_data = [
'user_id' => $received_data['hr_id'],
'user_type' => 'hr',
'activity' => 'download_employees_ecard_zip',
'misc_data' => json_encode([
'folder_name' => $folderName,
'status' => 'pending',
's3_key' => null,
]),
];
$zip_id = $this->UserActivityHistoryModel->insert($insert_data);
$payload = array_merge($received_data, [
'zip_id' => $zip_id,
'folder_name' => $folderName,
'batch_no' => 1,
'last_id' => 0,
'limit' => 100,
]);
// Dispatch job
Jobs::addJob(['job_name' => 'bulkEcardDownloadAsZipFromS3', 'payload' => $payload]);
return $this->respond([
'status' => true,
'message' => 'Process started. You will receive an email with the download link shortly.',
], 200);
}
public function sendMailForIndividualEmployeeEcard()
{
$received_data = $this->request->getJSON(true) ?? [];
$id = $received_data['emp_policy_id'] ?? null;
$client_policy_id = $received_data['client_policy_id'] ?? null;
if (empty($id)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'emp_policy_id is required'], 200);
}
if (empty($client_policy_id)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'client_policy_id is required'], 200);
}
$ids[] = $id;
$empDataServiceController = new EmpDataServiceController();
$result = $empDataServiceController->sendMailForDownloadingECard(['ids' => $ids, 'client_policy_id' => $client_policy_id], 1);
if (isset($result['status']) && $result['status'] == true) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail sent successfully', 'result' => $result], 200);
}
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to sent mail.', 'result' => $result], 200);
}
public function getInsurerClaimFormDownloadUrl()
{
$clientPolicyId = trim((string) ($this->request->getGet('client_policy_id') ?? ''));
if ($clientPolicyId === '') {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'client_policy_id is required',
'client_policy_id' => null,
'request_uri' => (string) current_url(),
'request_method' => $this->request->getMethod(),
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Missing required parameter | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Missing required parameter | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'client_policy_id is required',
'data' => [],
], 200);
}
if (! ctype_digit($clientPolicyId) || (int) $clientPolicyId <= 0) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Invalid client_policy_id',
'client_policy_id' => $clientPolicyId,
'request_uri' => (string) current_url(),
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Invalid client_policy_id | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Invalid client_policy_id | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'client_policy_id must be a valid positive number',
'data' => [],
], 200);
}
try {
$clientPolicy = $this->clientPolicyModel
->select('client_policy.id, client_policy.insurer_id, client_policy.policy_no, client_policy.is_active, insurers.id as insurer_pk, insurers.name as insurer_name, insurers.short_name as insurer_short_name, insurers.is_active as insurer_is_active, insurers.insurer_claim_form, insurers.insurer_claim_form_original_name')
->join('insurers', 'insurers.id = client_policy.insurer_id', 'left')
->where('client_policy.id', (int) $clientPolicyId)
->first();
if (empty($clientPolicy)) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Client policy not found',
'client_policy_id' => (int) $clientPolicyId,
'request_uri' => (string) current_url(),
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Client policy not found | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Client policy not found | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Client policy not found for the given client_policy_id',
'data' => [],
], 200);
}
if ((int) ($clientPolicy['is_active'] ?? 0) !== 1) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Client policy is inactive',
'client_policy_id' => (int) $clientPolicyId,
'policy_no' => $clientPolicy['policy_no'] ?? null,
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Inactive client policy | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Inactive client policy | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Client policy is inactive',
'data' => [],
], 200);
}
if (empty($clientPolicy['insurer_id'])) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Insurer is not mapped to client policy',
'client_policy_id' => (int) $clientPolicyId,
'policy_no' => $clientPolicy['policy_no'] ?? null,
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Insurer not mapped | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Insurer not mapped | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Insurer is not mapped to this client policy',
'data' => [],
], 200);
}
if ((int) ($clientPolicy['insurer_is_active'] ?? 0) !== 1) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Insurer is inactive',
'client_policy_id' => (int) $clientPolicyId,
'insurer_id' => (int) $clientPolicy['insurer_id'],
'insurer_name' => $clientPolicy['insurer_name'] ?? null,
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Inactive insurer | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Inactive insurer | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Insurer is inactive for this client policy',
'data' => [],
], 200);
}
$insurerData = [
'id' => $clientPolicy['insurer_id'],
'name' => $clientPolicy['insurer_name'] ?? '',
'short_name' => $clientPolicy['insurer_short_name'] ?? '',
'insurer_claim_form' => $clientPolicy['insurer_claim_form'] ?? null,
'insurer_claim_form_original_name'=> $clientPolicy['insurer_claim_form_original_name'] ?? null,
];
$claimFormAvailability = resolve_insurer_claim_form_file($insurerData);
if (empty($claimFormAvailability['available'])) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => 'Insurer claim form file not found',
'client_policy_id' => (int) $clientPolicyId,
'insurer_id' => (int) $clientPolicy['insurer_id'],
'insurer_name' => $clientPolicy['insurer_name'] ?? null,
'insurer_short_name' => $clientPolicy['insurer_short_name'] ?? null,
'stored_claim_form' => $clientPolicy['insurer_claim_form'] ?? null,
'checked_paths' => $claimFormAvailability['checked_paths'] ?? [],
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Claim form file not found | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Claim form file not found | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Insurer claim form is not available for this client policy',
'data' => [],
], 200);
}
$downloadUrl = base_url('claim-form-download/' . md5((string) $clientPolicy['insurer_id']));
log_message('error', '[getInsurerClaimFormDownloadUrl] Success | ' . json_encode([
'client_policy_id' => (int) $clientPolicyId,
'insurer_id' => (int) $clientPolicy['insurer_id'],
'file_source' => $claimFormAvailability['source'],
'file_name' => $claimFormAvailability['file_name'],
'download_url' => $downloadUrl,
]));
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Insurer claim form download URL fetched successfully',
'data' => [
'download_url' => $downloadUrl,
],
], 200);
} catch (\Throwable $th) {
$errorContext = [
'api' => 'getInsurerClaimFormDownloadUrl',
'error' => $th->getMessage(),
'client_policy_id' => $clientPolicyId,
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTraceAsString(),
];
log_message('error', '[getInsurerClaimFormDownloadUrl] Exception | ' . json_encode($errorContext));
$this->myLogger->logme('error', '[getInsurerClaimFormDownloadUrl] Exception | ' . json_encode($errorContext));
return $this->respond([
'status' => false,
'code' => 500,
'message' => 'Unable to fetch insurer claim form download URL. Please try again later.',
'data' => [],
], 200);
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
// Employee Dependent Add API Endpoints
//---------------------------------------------------------------------------------------------------------------------------------------------
public function addEmployeeAndDependencev2()
{
try {
$data = $this->request->getJSON();
// print_r($data);die;
if ($data) {
$Count = 0;
$newDependentsForNotification = [];
foreach ($data as $item) {
$self_data = $this->employeeModel
->select('employees.id')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employee_polices.client_policy_id', $item->client_policy_id)
->where('employees.emp_code', $item->emp_code)
->where('employees.client_id', $item->client_id)
->where('employees.relationship', 'self')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->first();
$item->family_floater_key = $this->RelationshipMap($item->relationship);
$item->gender = $this->GenderMap($item->relationship, $item->emp_code);
$item->dob = $this->convertDateFormatYMD($item->dob);
$item->emp_status = 'pending_approval';
$item->emp_created_by = isset($item->hr_id) ? 'HR' : 'USER';
if (isset($item->id)) {
//update old data
$id = $item->id;
$item->updated_by = $item->hr_id ?? $self_data['id'];
$employee = $this->employeeModel->where('is_active', 1)->update($id, (array) $item);
if ($employee) {
$Count++;
}
} else {
//create new data
$item->created_by = $item->hr_id ?? $self_data['id'];
$employee = $this->employeeModel->insert($item);
if ($employee) {
$Count++;
$newDependentsForNotification[] = [
'employee_id' => (int) $employee,
'emp_code' => (string) ($item->emp_code ?? ''),
'dependent_name' => (string) ($item->name ?? ''),
'relationship' => (string) ($item->relationship ?? ''),
'dob' => (string) ($item->dob ?? ''),
'client_id' => (int) ($item->client_id ?? 0),
'client_branch_id' => (int) ($item->client_branch_id ?? 0),
'client_policy_id' => (int) ($item->client_policy_id ?? 0),
'dependent_effective_date' => (string) ($item->dependent_effective_date ?? ''),
'created_by_type' => isset($item->hr_id) ? 'HR' : 'USER',
];
}
}
}
if ($Count > 0) {
if (isset($data[0]->id)) {
$this->createEmployeePolicyData($data[0]->id, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si, null, ['dependent_effective_date' => $data[0]->dependent_effective_date, 'hr_id' => $data[0]->hr_id ?? null]);
} else {
$payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id, $data[0]->relationship);
$this->createEmployeePolicyData($employee, $data[0]->emp_code, $data[0]->client_id, $data[0]->client_policy_id, $data[0]->basic_cover_si, $payable_employee, ['dependent_effective_date' => $data[0]->dependent_effective_date, 'hr_id' => $data[0]->hr_id ?? null]);
}
$this->updatePremiumAmount($data[0]->client_policy_id, $data[0]->emp_code, $data[0]->client_branch_id);
if (! empty($newDependentsForNotification)) {
foreach ($newDependentsForNotification as $dependentNotificationData) {
$this->sendDependentAddNotificationMail($dependentNotificationData);
}
}
$result = [];
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
}
}else{
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => "Requested parameters are required"], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
/**
* Notify client/branch HRs and client account managers when a dependent is added.
*/
private function sendDependentAddNotificationMail(array $dependentData): void
{
try {
$clientId = (int) ($dependentData['client_id'] ?? 0);
$branchId = (int) ($dependentData['client_branch_id'] ?? 0);
$clientPolicyId = (int) ($dependentData['client_policy_id'] ?? 0);
if ($clientId <= 0 || $branchId <= 0 || $clientPolicyId <= 0) {
return;
}
$db = \Config\Database::connect();
$clientData = $this->clientModel
->select('id, client_name, email, common_mails')
->where('id', $clientId)
->first();
$branchData = $this->clientBranchModel
->select('id, branch_name')
->where('id', $branchId)
->first();
$policyData = $this->clientPolicyModel
->select('id, policy_no')
->where('id', $clientPolicyId)
->first();
$selfEmployee = $this->employeeModel
->select('name')
->where('client_id', $clientId)
->where('emp_code', (string) ($dependentData['emp_code'] ?? ''))
->where('relationship', 'Self')
->where('is_active', 1)
->first();
$branchHrEmails = $db->table('level_contacts')
->select('email')
->where('ref_id', $branchId)
->where('contact_type', 'client')
->where('is_active', 1)
->where('email IS NOT NULL', null, false)
->where("TRIM(email) != ''", null, false)
->get()
->getResultArray();
$accountManagerEmails = $this->clientRMModel->findAccountManagerEmail($clientId) ?? [];
$recipientEmails = [];
if (! empty($clientData['email'])) {
$recipientEmails[] = trim((string) $clientData['email']);
}
$clientCommonMails = array_filter(array_map('trim', explode(',', (string) ($clientData['common_mails'] ?? ''))));
foreach ($clientCommonMails as $commonMail) {
$recipientEmails[] = $commonMail;
}
foreach ($branchHrEmails as $branchHrEmailRow) {
$recipientEmails[] = trim((string) ($branchHrEmailRow['email'] ?? ''));
}
if (is_array($accountManagerEmails)) {
foreach ($accountManagerEmails as $accountManagerEmail) {
$recipientEmails[] = trim((string) $accountManagerEmail);
}
}
$uniqueEmails = [];
foreach ($recipientEmails as $email) {
$email = trim((string) $email);
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
continue;
}
$emailKey = strtolower($email);
if (! isset($uniqueEmails[$emailKey])) {
$uniqueEmails[$emailKey] = $email;
}
}
$recipientEmails = array_values($uniqueEmails);
if (empty($recipientEmails)) {
log_message('error', '[DependentAddMail] No recipient emails found for client_id=' . $clientId . ', branch_id=' . $branchId);
return;
}
$clientName = (string) ($clientData['client_name'] ?? '');
$branchName = (string) ($branchData['branch_name'] ?? '');
$policyNo = (string) ($policyData['policy_no'] ?? '');
$employeeName = (string) ($selfEmployee['name'] ?? '');
$dependentName = (string) ($dependentData['dependent_name'] ?? '');
$relationship = (string) ($dependentData['relationship'] ?? '');
$dependentDob = ! empty($dependentData['dob']) ? date('d/m/Y', strtotime((string) $dependentData['dob'])) : '-';
// $effectiveDate = ! empty($dependentData['dependent_effective_date']) ? date('d/m/Y', strtotime((string) $dependentData['dependent_effective_date'])) : '-';
$effectiveRaw = (string) ($dependentData['dependent_effective_date'] ?? '');
$effectiveYmd = $effectiveRaw !== '' ? $this->convertDateFormatYMD($effectiveRaw) : null;
$effectiveDate = (! empty($effectiveYmd) && strtotime($effectiveYmd) !== false)
? date('d/m/Y', strtotime($effectiveYmd))
: '-';
$createdByType = (string) ($dependentData['created_by_type'] ?? 'USER');
$employeeCode = (string) ($dependentData['emp_code'] ?? '');
$subject = 'Dependent Added - Approval Required | ' . ($clientName ?: 'Client');
$message = '
<p>Dear ' . esc($employeeName ?: 'Team') . ',</p>
<p>A new dependent has been added and is pending for approval.</p>
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">
<tr><td><strong>Client</strong></td><td>' . esc($clientName) . '</td></tr>
<tr><td><strong>Branch</strong></td><td>' . esc($branchName) . '</td></tr>
<tr><td><strong>Policy</strong></td><td>' . esc($policyNo) . '</td></tr>
<tr><td><strong>Employee</strong></td><td>' . esc($employeeName) . '</td></tr>
<tr><td><strong>Employee Code</strong></td><td>' . esc($employeeCode) . '</td></tr>
<tr><td><strong>Dependent Name</strong></td><td>' . esc($dependentName) . '</td></tr>
<tr><td><strong>Relationship</strong></td><td>' . esc($relationship) . '</td></tr>
<tr><td><strong>Date of Birth</strong></td><td>' . esc($dependentDob) . '</td></tr>
<tr><td><strong>Effective Date</strong></td><td>' . esc($effectiveDate) . '</td></tr>
<tr><td><strong>Added By</strong></td><td>' . esc($createdByType) . '</td></tr>
</table>
<p>Please review this request in Approvals.</p>
<p>Best regards,<br>Nhance Team</p>
<p><small>This is an auto-generated email. Please do not reply.</small></p>
';
$mailPayload = [
'mail' => $recipientEmails,
'subject' => $subject,
'message' => $message,
'attachments' => [],
'reply_to' => '',
];
$mailResult = MailHelper::send_email($mailPayload);
$this->myLogger->logme('error', '[DependentAddMail] mail_result=' . json_encode($mailResult));
} catch (\Throwable $th) {
log_message('error', '[DependentAddMail] ' . $th->getMessage() . ' in ' . $th->getFile() . ':' . $th->getLine());
$this->myLogger->logme('error', '[DependentAddMail] ' . $th->getMessage());
}
}
/**
* Send dependent rejection notification mail using client notification template
* only when the template is enabled for that client.
*/
private function sendDependentRejectedNotificationMail(array $employee, array $employeePolicy, string $rejectReason, string $processedByRole): void
{
try {
$clientId = (int) ($employee['client_id'] ?? 0);
$branchId = (int) ($employee['client_branch_id'] ?? 0);
$clientPolicyId = (int) ($employeePolicy['client_policy_id'] ?? 0);
$empCode = (string) ($employee['emp_code'] ?? '');
$dependentName = (string) ($employee['name'] ?? '');
if ($clientId <= 0 || $branchId <= 0 || $clientPolicyId <= 0) {
log_message('error', '[DependentRejectMail] Skipped - invalid IDs | client_id=' . $clientId . ', branch_id=' . $branchId . ', client_policy_id=' . $clientPolicyId . ', emp_code=' . $empCode);
return;
}
$notificationData = $this->notificationModel
->where('client_id', $clientId)
->where('template_name', 'dependent_rejection_mail')
->where('enabled', 1)
->first();
if (empty($notificationData) || empty($notificationData['subject']) || empty($notificationData['mail_content'])) {
log_message('error', '[DependentRejectMail] Skipped - template disabled or missing | client_id=' . $clientId . ', emp_code=' . $empCode . ', dependent=' . $dependentName);
return;
}
$clientData = $this->clientModel
->select('client_name, common_mails')
->where('id', $clientId)
->first();
$branchData = $this->clientBranchModel
->select('branch_name')
->where('id', $branchId)
->first();
$policyData = $this->clientPolicyModel
->select('policy_no')
->where('id', $clientPolicyId)
->first();
$selfEmployee = $this->employeeModel
->select('name, email_corporate, email_personal')
->where('client_id', $clientId)
->where('emp_code', (string) ($employee['emp_code'] ?? ''))
->where('relationship', 'Self')
->where('is_active', 1)
->first();
$selfEmployeeEmail = trim((string) ($selfEmployee['email_corporate'] ?? $selfEmployee['email_personal'] ?? ''));
if (! filter_var($selfEmployeeEmail, FILTER_VALIDATE_EMAIL)) {
log_message('error', '[DependentRejectMail] Skipped - invalid self employee email | client_id=' . $clientId . ', emp_code=' . $empCode . ', dependent=' . $dependentName);
return;
}
$clientCommonMails = trim((string) ($clientData['common_mails'] ?? ''));
$placeholders = [
'{{client_name}}' => (string) ($clientData['client_name'] ?? ''),
'{{branch_name}}' => (string) ($branchData['branch_name'] ?? ''),
'{{policy_no}}' => (string) ($policyData['policy_no'] ?? ''),
'{{employee_name}}' => (string) ($selfEmployee['name'] ?? ''),
'{{employee_code}}' => (string) ($employee['emp_code'] ?? ''),
'{{dependent_name}}'=> (string) ($employee['name'] ?? ''),
'{{relationship}}' => (string) ($employee['relationship'] ?? ''),
'{{dob}}' => ! empty($employee['dob']) ? date('d/m/Y', strtotime((string) $employee['dob'])) : '-',
'{{effective_date}}'=> ! empty($employeePolicy['date_coverage']) ? date('d/m/Y', strtotime((string) $employeePolicy['date_coverage'])) : '-',
'{{reject_reason}}' => $rejectReason !== '' ? $rejectReason : '-',
'{{processed_by}}' => $processedByRole,
];
$subject = (string) $notificationData['subject'];
$mailContent = (string) $notificationData['mail_content'];
foreach ($placeholders as $key => $value) {
$subject = str_ireplace($key, $value, $subject);
$mailContent = str_ireplace($key, $value, $mailContent);
}
log_message('error', '[DependentRejectMail] Sending mail | client_id=' . $clientId . ', emp_code=' . $empCode . ', dependent=' . $dependentName . ', to=' . $selfEmployeeEmail . ', bcc=' . ($clientCommonMails !== '' ? $clientCommonMails : '-'));
$mailResult = MailHelper::send_email([
'mail' => $selfEmployeeEmail,
'subject' => $subject,
'message' => $mailContent,
'bcc' => $clientCommonMails,
]);
log_message('error', '[DependentRejectMail] mail_result=' . json_encode($mailResult));
$this->myLogger->logme('error', '[DependentRejectMail] mail_result=' . json_encode($mailResult));
} catch (\Throwable $th) {
log_message('error', '[DependentRejectMail] ' . $th->getMessage() . ' in ' . $th->getFile() . ':' . $th->getLine());
$this->myLogger->logme('error', '[DependentRejectMail] ' . $th->getMessage());
}
}
public function deleteDependencev2()
{
try {
if ($this->request->getGet('id')) {
$this->employeeModel->where('id', $this->request->getGet('id'))
->where('is_active', 1)
->set(['emp_status' => 'truncated', 'is_active' => 0])
->update();
$this->employeePolicyModel->where('employee_id', $this->request->getGet('id'))
->where('is_active', 1)
->set(['status' => 'truncated', 'is_active' => 0])
->update();
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
public function getEmployeeByPolicyv2()
{
try {
$id = $this->request->getGet('id') ?? $this->request->getPost('id');
$emp_code = $this->request->getGet('emp_code') ?? $this->request->getPost('emp_code');
$client_id = $this->request->getGet('client_id') ?? $this->request->getPost('client_id');
$client_branch_id = $this->request->getGet('client_branch_id') ?? $this->request->getPost('client_branch_id');
$client_policy_id = $this->request->getGet('client_policy_id') ?? $this->request->getPost('client_policy_id');
if (empty($id) || empty($emp_code) || empty($client_id) || empty($client_branch_id) || empty($client_policy_id)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Required parameters missing: id, emp_code, client_id, client_branch_id and client_policy_id are required', 'data' => []], 200);
}
$keysToRemove = ["removable_keys"];
// Filtered by client_policy_id — returns at most one GMC policy
$empPolicyList = $this->employeeModel->getEmployeePolicy($id, $client_policy_id);
$array = $empPolicyList[0] ?? null;
if (!$array) {
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => 'Employee policy not found for the given employee and client policy', 'data' => []], 200);
}
// GMC only (policy_type_id = 2)
if ((int) $array->policy_type_id !== 2) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Only GMC policy is supported for dependent add', 'data' => []], 200);
}
$empData = $this->employeeModel
->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('client_branch_id', $client_branch_id)
->where('is_active', 1)
->where('is_addon_value', 0)
->groupStart()
->whereIn('family_floater_key', ['self', 'spouse', 'child'])
->orWhereIn('relationship', ['Self', 'Spouse', 'Son', 'Daughter'])
->groupEnd()
->findAll();
$decodedArray = json_decode($array->Policy_Terms);
$refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove));
$array->Policy_Terms = $refusingData;
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId, $array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
$array->eCardDownload = $array->tpa_id != null
? base_url('download-e-card/') . $array->rand_string . '/1'
: null;
$familyFloates = $array->Policy_Terms->family_floaters ?? (object) [];
// Only spouse + children (ignore parents / parents-in-law)
$hasSpouse = isset($familyFloates->spouse) && (int) $familyFloates->spouse > 0;
$hasChildren = isset($familyFloates->childrens) && (int) $familyFloates->childrens > 0;
$spouseCount = $hasSpouse ? (int) $familyFloates->spouse : 0;
$childrenCount = $hasChildren ? (int) $familyFloates->childrens : 0;
$spouseChildrenTerms = (object) [
'self' => isset($familyFloates->self) ? (int) $familyFloates->self : 1,
'spouse' => $spouseCount,
'childrens' => $childrenCount,
];
$array->notes = $this->FloterNotesConvertion($spouseChildrenTerms);
$allowedRelationships = [];
if ($hasSpouse) {
$allowedRelationships[] = 'Spouse';
}
if ($hasChildren) {
$allowedRelationships[] = 'Son';
$allowedRelationships[] = 'Daughter';
}
$array->allowed_relationships = $allowedRelationships;
if (!empty($getSlabAndGridData['slab_rates'][0]) && ($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1 || $getSlabAndGridData['slab_rates'][0]['premium_type'] == 3)) {
$array->floter_text_heading = 'Floater Sum Insured';
$array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.';
} else {
$array->floter_text_heading = 'Sum Insured';
$array->floter_text_description = '';
}
$floters = $this->FloterConvertion($spouseChildrenTerms);
$data = [];
$dependent_and_si_value = 0;
$dependent_and_si_premium_value = 0;
$dependent_and_si_gst_value = 0;
foreach ($floters as $familyFloatesValue) {
$dependent = preg_replace('/\d/', '', $familyFloatesValue);
if (!in_array($dependent, ['self', 'spouse', 'child'], true)) {
continue;
}
if ($dependent === 'spouse' && !$hasSpouse) {
continue;
}
if ($dependent === 'child' && !$hasChildren) {
continue;
}
if (count($empData)) {
foreach ($empData as $key => $value) {
$empFloaterKey = !empty($value['family_floater_key'])
? preg_replace('/\d/', '', strtolower(trim($value['family_floater_key'])))
: $this->RelationshipMap($value['relationship']);
$relationship = strtolower(trim($value['relationship'] ?? ''));
$matches = ($empFloaterKey === $dependent)
|| ($dependent === 'spouse' && $relationship === 'spouse')
|| ($dependent === 'child' && in_array($relationship, ['son', 'daughter'], true))
|| ($dependent === 'self' && $relationship === 'self');
if ($matches) {
$employee_policy = $this->employeePolicyModel
->where('employee_id', $value['id'])
->where('client_policy_id', $array->ClientPolicyId)
->where('is_active', 1)
->get()
->getRow();
if (isset($employee_policy->basic_cover_si)) {
$dependent_and_si_value = ($dependent_and_si_value == 0) ? $employee_policy->basic_cover_si : $dependent_and_si_value;
}
if (isset($employee_policy->payable_employee) && $employee_policy->payable_employee == 1) {
if (isset($employee_policy->rata_premimum)) {
$dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->rata_premimum;
}
if (isset($employee_policy->gst)) {
$dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;
}
}
$temp = [];
$temp['is_value_exist'] = true;
$temp['data']['family_floater_key'] = $familyFloatesValue;
$temp['data']['employee_id'] = $value['id'];
$temp['data']['relationship'] = $value['relationship'];
$temp['data']['name'] = $value['name'];
$temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp['data']['client_policy_id'] = $array->ClientPolicyId;
$temp['data']['form_type'] = $dependent;
$temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0;
$temp['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
array_push($data, $temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
// Remaining allowed spouse/child slots → Add buttons
if (count($floters)) {
foreach ($floters as $familyFloatesValue) {
$dependent = preg_replace('/\d/', '', $familyFloatesValue);
if (!in_array($dependent, ['spouse', 'child'], true)) {
continue;
}
if ($dependent === 'spouse' && !$hasSpouse) {
continue;
}
if ($dependent === 'child' && !$hasChildren) {
continue;
}
$temp2 = [];
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array->ClientPolicyId;
$temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', $dependent));
$temp2['data']['form_type'] = $dependent;
$temp2['data']['age_validation'] = $this->getAgeRange($decodedArray, $familyFloatesValue);
$temp2['data']['allowed_relationships'] = $dependent === 'spouse'
? ['Spouse']
: ['Son', 'Daughter'];
array_push($data, $temp2);
}
}
$array->mapped_family_floaters = $data;
$array->type = 'GMC';
$array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0;
$array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0;
$array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0;
$employeePolicy = $this->getEmployeePolicyMembersForDependentAdd(
$emp_code,
$client_id,
$client_branch_id,
$client_policy_id
);
// Show add button when any spouse/child slot is still available
$addButtonShow = false;
foreach ($data as $floaterItem) {
if (empty($floaterItem['is_value_exist'])) {
$addButtonShow = true;
break;
}
}
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Employee policy and dependent details fetched successfully',
'data' => $array,
'EmployeePolicy' => $employeePolicy,
'add_button_show' => $addButtonShow,
], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Something went wrong while fetching employee policy details', 'data' => $e->getMessage()], 500);
}
}
/**
* Fetch Self / Spouse / Children employee+policy rows for a GMC client policy.
* Same data shape as EmployeePolicy in getEmployeeActiveOrInactivePolicy.
*/
private function getEmployeePolicyMembersForDependentAdd($emp_code, $client_id, $client_branch_id, $client_policy_id)
{
$employeeIds = $this->employeeModel
->select('id')
->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('client_branch_id', $client_branch_id)
->where('is_active', 1)
->where('is_addon_value', 0)
->groupStart()
->whereIn('family_floater_key', ['self', 'spouse', 'child'])
->orWhereIn('relationship', ['Self', 'Spouse', 'Son', 'Daughter'])
->groupEnd()
->findColumn('id');
if (empty($employeeIds)) {
return [];
}
return $this->employeePolicyModel
->select('
employees.*,
employee_polices.employee_id,
employee_polices.basic_cover_si,
employee_polices.premium,
employee_polices.gst,
employee_polices.tpa_id,
employee_polices.rand_string,
employee_polices.uhid as uhid,
employee_polices.processed_by,
employee_polices.reject_reason,
employee_polices.date_coverage
')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->join('client_policy', 'client_policy.id = employee_polices.client_policy_id', 'left')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->whereIn('employee_polices.employee_id', $employeeIds)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.is_active', 1)
->findAll();
}
public function processDependentAdd()
{
try {
$data = $this->request->getJSON(true);
log_message('error', '[processDependentAdd] Step 1: Request received | payload=' . json_encode($data));
$this->myLogger->logme('error', '[processDependentAdd] Step 1: Request received | payload=' . json_encode($data));
if (empty($data)) {
log_message('error', '[processDependentAdd] Step 1 failed: Request body is required');
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Request body is required'], 200);
}
$employee_id = $data['employee_id'] ?? null;
$client_policy_id = $data['client_policy_id'] ?? null;
$hr_id = $data['hr_id'] ?? null;
$status = $data['status'] ?? "approved";
$reject_reason = trim((string) ($data['reject_reason'] ?? ''));
$updated_by = $hr_id ?? get_session_userid() ?? null;
// Processor role: HR (app) or ACM (internal portal session user) — used for approve and reject
$processed_by_role = ! empty($hr_id) ? 'HR' : 'ACM';
log_message('error', '[processDependentAdd] Step 2: Parsed params | employee_id=' . $employee_id
. ' | client_policy_id=' . $client_policy_id
. ' | status=' . $status
. ' | hr_id=' . ($hr_id ?? 'null')
. ' | updated_by=' . ($updated_by ?? 'null')
. ' | processed_by_role=' . $processed_by_role);
$this->myLogger->logme('error', '[processDependentAdd] Step 2: Parsed params | employee_id=' . $employee_id
. ' | client_policy_id=' . $client_policy_id
. ' | status=' . $status
. ' | processed_by_role=' . $processed_by_role);
if (empty($employee_id)) {
log_message('error', '[processDependentAdd] Step 2 failed: employee_id is required');
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'employee_id is required'], 200);
}
if (empty($client_policy_id)) {
log_message('error', '[processDependentAdd] Step 2 failed: client_policy_id is required');
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'client_policy_id is required'], 200);
}
if (empty($status)) {
log_message('error', '[processDependentAdd] Step 2 failed: status is required');
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'status is required'], 200);
}
if ($status !== 'approved' && $status !== 'rejected') {
log_message('error', '[processDependentAdd] Step 2 failed: status is invalid | status=' . $status);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'status is invalid'], 200);
}
if ($status === 'rejected' && $reject_reason === '') {
log_message('error', '[processDependentAdd] Step 2 failed: reject_reason is required for rejection');
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'reject_reason is required'], 200);
}
log_message('error', '[processDependentAdd] Step 3: Fetching employee | employee_id=' . $employee_id);
$employee = $this->employeeModel
->where('id', $employee_id)
->first();
if (!$employee) {
log_message('error', '[processDependentAdd] Step 3 failed: Employee not found | employee_id=' . $employee_id);
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Employee not found'], 200);
}
$emp_status = strtolower((string) ($employee['emp_status'] ?? ''));
log_message('error', '[processDependentAdd] Step 3 success: Employee found | emp_code=' . ($employee['emp_code'] ?? '')
. ' | relationship=' . ($employee['relationship'] ?? '')
. ' | emp_status=' . $emp_status
. ' | family_floater_key=' . ($employee['family_floater_key'] ?? ''));
if ($emp_status === 'active') {
log_message('error', '[processDependentAdd] Step 4 failed: Dependent is already approved | employee_id=' . $employee_id);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Dependent is already approved'], 200);
}
if ($status === 'approved') {
if (! in_array($emp_status, ['pending_approval', 'rejected'], true)) {
log_message('error', '[processDependentAdd] Step 4 failed: Dependent cannot be approved | emp_status=' . $emp_status);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Dependent cannot be approved'], 200);
}
} elseif ($emp_status !== 'pending_approval') {
log_message('error', '[processDependentAdd] Step 4 failed: Only pending dependents can be rejected | emp_status=' . $emp_status);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Only pending dependents can be rejected'], 200);
}
log_message('error', '[processDependentAdd] Step 4: Employee status validation passed | emp_status=' . $emp_status);
log_message('error', '[processDependentAdd] Step 5: Fetching employee policy | employee_id=' . $employee_id
. ' | client_policy_id=' . $client_policy_id);
$employee_policy = $this->employeePolicyModel
->where('employee_id', $employee_id)
->where('client_policy_id', $client_policy_id)
->first();
if (!$employee_policy) {
log_message('error', '[processDependentAdd] Step 5 failed: Employee policy not found');
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => 'Employee policy not found'], 200);
}
$policy_status = strtolower((string) ($employee_policy['status'] ?? ''));
log_message('error', '[processDependentAdd] Step 5 success: Employee policy found | policy_status=' . $policy_status);
if ($status === 'approved') {
if (! in_array($policy_status, ['pending_approval', 'rejected'], true)) {
log_message('error', '[processDependentAdd] Step 6 failed: Employee policy cannot be approved | policy_status=' . $policy_status);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Employee policy cannot be approved'], 200);
}
} elseif ($policy_status !== 'pending_approval') {
log_message('error', '[processDependentAdd] Step 6 failed: Only pending employee policy can be rejected | policy_status=' . $policy_status);
return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Only pending employee policy can be rejected'], 200);
}
log_message('error', '[processDependentAdd] Step 6: Policy status validation passed | policy_status=' . $policy_status);
if ($status === 'approved') {
log_message('error', '[processDependentAdd] Step 7: Checking family floater spouse/child limit');
$floaterLimitCheck = $this->checkFamilyFloaterDependentLimit(
$employee,
(int) $client_policy_id,
(int) $employee_id
);
log_message('error', '[processDependentAdd] Step 7 result: family floater check | '
. json_encode($floaterLimitCheck));
$this->myLogger->logme('error', '[processDependentAdd] Step 7 result: family floater check | '
. json_encode($floaterLimitCheck));
if ($floaterLimitCheck['allowed'] === false) {
log_message('error', '[processDependentAdd] Step 7 failed: Limit exceeded | message='
. ($floaterLimitCheck['message'] ?? ''));
return $this->respond([
'status' => 'failed',
'code' => 400,
'data' => $floaterLimitCheck['message'],
], 200);
}
$employee_update_data = [
'updated_by' => $updated_by,
'processed_by' => $processed_by_role,
'emp_status' => 'active',
'is_active' => 1,
'reject_reason' => null,
];
$policy_update_data = [
'updated_by' => $updated_by,
'processed_by' => $processed_by_role,
'status' => 'active',
'is_active' => 1,
'reject_reason' => null,
];
log_message('error', '[processDependentAdd] Step 8: Prepared approve update data');
} else {
$employee_update_data = [
'updated_by' => $updated_by,
'processed_by' => $processed_by_role,
'reject_reason' => $reject_reason,
'emp_status' => 'rejected',
'is_active' => 0,
];
$policy_update_data = [
'updated_by' => $updated_by,
'processed_by' => $processed_by_role,
'reject_reason' => $reject_reason,
'status' => 'rejected',
'is_active' => 0,
];
log_message('error', '[processDependentAdd] Step 8: Prepared reject update data | reject_reason=' . $reject_reason);
}
log_message('error', '[processDependentAdd] Step 9: Updating employee | employee_id=' . $employee_id
. ' | data=' . json_encode($employee_update_data));
$employee_updated = $this->employeeModel->update($employee_id, $employee_update_data);
if (!$employee_updated) {
log_message('error', '[processDependentAdd] Step 9 failed: Failed to update employee status');
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Failed to update employee status'], 200);
}
log_message('error', '[processDependentAdd] Step 9 success: Employee updated');
log_message('error', '[processDependentAdd] Step 10: Updating employee policy | employee_id=' . $employee_id
. ' | client_policy_id=' . $client_policy_id
. ' | data=' . json_encode($policy_update_data));
$policy_updated = $this->employeePolicyModel
->where('employee_id', $employee_id)
->where('client_policy_id', $client_policy_id)
->set($policy_update_data)
->update();
if (!$policy_updated) {
log_message('error', '[processDependentAdd] Step 10 failed: Failed to update employee policy status');
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => 'Failed to update employee policy status'], 200);
}
log_message('error', '[processDependentAdd] Step 10 success: Employee policy updated');
$truncatedDependentIds = [];
if ($status === 'approved') {
log_message('error', '[processDependentAdd] Step 11: Truncating excess pending dependents if limit exceeded');
$truncatedDependentIds = $this->truncateExcessPendingDependents(
$employee,
(int) $client_policy_id,
(int) $employee_id,
$updated_by,
$processed_by_role
);
log_message('error', '[processDependentAdd] Step 11 result: truncated_dependent_ids='
. json_encode($truncatedDependentIds));
$this->myLogger->logme('error', '[processDependentAdd] Step 11 result: truncated_dependent_ids='
. json_encode($truncatedDependentIds));
}
if ($status === 'rejected') {
log_message('error', '[processDependentAdd] Step 12: Sending dependent rejected notification mail');
$this->sendDependentRejectedNotificationMail(
employee: $employee,
employeePolicy: $employee_policy,
rejectReason: $reject_reason,
processedByRole: $processed_by_role
);
log_message('error', '[processDependentAdd] Step 12 done: Reject notification mail triggered');
}
log_message('error', '[processDependentAdd] Step 13: Success | status=' . $status
. ' | employee_id=' . $employee_id
. ' | truncated_dependent_ids=' . json_encode($truncatedDependentIds));
$this->myLogger->logme('error', '[processDependentAdd] Step 13: Success | status=' . $status
. ' | employee_id=' . $employee_id
. ' | truncated_dependent_ids=' . json_encode($truncatedDependentIds));
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => $status === 'approved' ? 'Dependent approved successfully' : 'Dependent rejected successfully',
'data' => [
'employee_id' => $employee_id,
'client_policy_id' => $client_policy_id,
'status' => $status,
'reject_reason' => $status === 'rejected' ? $reject_reason : null,
'truncated_dependent_ids' => $truncatedDependentIds,
],
], 200);
} catch (\Exception $e) {
log_message('error', 'Error in processDependentAdd: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
$this->myLogger->logme('error', 'Error in processDependentAdd: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500);
}
}
/**
* On approve: ensure spouse/child counts stay within policy_terms.family_floaters limits.
*
* @return array{allowed: bool, message: string|null}
*/
private function checkFamilyFloaterDependentLimit(array $employee, int $clientPolicyId, int $employeeId): array
{
log_message('error', '[checkFamilyFloaterDependentLimit] Start | employee_id=' . $employeeId
. ' | client_policy_id=' . $clientPolicyId
. ' | emp_code=' . ($employee['emp_code'] ?? '')
. ' | relationship=' . ($employee['relationship'] ?? '')
. ' | family_floater_key=' . ($employee['family_floater_key'] ?? ''));
$relationship = strtolower(trim((string) ($employee['relationship'] ?? '')));
$floaterKey = ! empty($employee['family_floater_key'])
? preg_replace('/\d/', '', strtolower(trim((string) $employee['family_floater_key'])))
: strtolower((string) ($this->RelationshipMap($employee['relationship'] ?? '') ?? ''));
$isSpouse = ($relationship === 'spouse' || $floaterKey === 'spouse');
$isChild = in_array($relationship, ['son', 'daughter'], true) || $floaterKey === 'child';
log_message('error', '[checkFamilyFloaterDependentLimit] Resolved type | relationship=' . $relationship
. ' | floater_key=' . $floaterKey
. ' | is_spouse=' . ($isSpouse ? '1' : '0')
. ' | is_child=' . ($isChild ? '1' : '0'));
// Only spouse / child are validated against family_floaters for dependent-add approve
if (! $isSpouse && ! $isChild) {
log_message('error', '[checkFamilyFloaterDependentLimit] Skip: not spouse/child, allowing');
return ['allowed' => true, 'message' => null];
}
$clientPolicy = $this->clientPolicyModel->select('policy_terms')->where('id', $clientPolicyId)->first();
if (empty($clientPolicy['policy_terms'])) {
log_message('error', '[checkFamilyFloaterDependentLimit] Skip: policy_terms empty, allowing');
return ['allowed' => true, 'message' => null];
}
$policyTerms = json_decode($clientPolicy['policy_terms'], true);
if (! is_array($policyTerms) || empty($policyTerms['family_floaters'])) {
log_message('error', '[checkFamilyFloaterDependentLimit] Skip: family_floaters missing, allowing');
return ['allowed' => true, 'message' => null];
}
$familyFloaters = is_array($policyTerms['family_floaters'])
? $policyTerms['family_floaters']
: (array) $policyTerms['family_floaters'];
$allowedSpouseCount = (int) ($familyFloaters['spouse'] ?? 0);
$allowedChildCount = (int) ($familyFloaters['childrens'] ?? 0);
log_message('error', '[checkFamilyFloaterDependentLimit] Allowed counts | spouse=' . $allowedSpouseCount
. ' | childrens=' . $allowedChildCount
. ' | family_floaters=' . json_encode($familyFloaters));
$existingFamily = $this->employeeModel
->select('employees.id, employees.relationship, employees.family_floater_key')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $employee['emp_code'])
->where('employees.client_id', $employee['client_id'])
->where('employee_polices.client_policy_id', $clientPolicyId)
->where('employees.emp_status', 'active')
->where('employee_polices.status', 'active')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.id !=', $employeeId)
->findAll();
log_message('error', '[checkFamilyFloaterDependentLimit] Active family members found | count='
. count($existingFamily) . ' | members=' . json_encode($existingFamily));
$activeSpouseCount = 0;
$activeChildCount = 0;
foreach ($existingFamily as $member) {
$memberRelationship = strtolower(trim((string) ($member['relationship'] ?? '')));
$memberFloaterKey = ! empty($member['family_floater_key'])
? preg_replace('/\d/', '', strtolower(trim((string) $member['family_floater_key'])))
: '';
if ($memberRelationship === 'spouse' || $memberFloaterKey === 'spouse') {
$activeSpouseCount++;
} elseif (in_array($memberRelationship, ['son', 'daughter'], true) || $memberFloaterKey === 'child') {
$activeChildCount++;
}
}
log_message('error', '[checkFamilyFloaterDependentLimit] Active counts | spouse=' . $activeSpouseCount
. ' | child=' . $activeChildCount);
if ($isSpouse) {
if (($activeSpouseCount + 1) > $allowedSpouseCount) {
$message = 'Spouse count exceeds policy family floater limit. Allowed: '
. $allowedSpouseCount . ', existing active: ' . $activeSpouseCount;
log_message('error', '[checkFamilyFloaterDependentLimit] Blocked: ' . $message);
return [
'allowed' => false,
'message' => $message,
];
}
}
if ($isChild) {
if (($activeChildCount + 1) > $allowedChildCount) {
$message = 'Child count exceeds policy family floater limit. Allowed: '
. $allowedChildCount . ', existing active: ' . $activeChildCount;
log_message('error', '[checkFamilyFloaterDependentLimit] Blocked: ' . $message);
return [
'allowed' => false,
'message' => $message,
];
}
}
log_message('error', '[checkFamilyFloaterDependentLimit] Allowed: within family floater limit');
return ['allowed' => true, 'message' => null];
}
/**
* After approving a spouse/child: if family_floaters slots are full (or pending would exceed),
* mark excess remaining pending_approval dependents as truncate + is_active = 0.
*
* @return int[] Truncated employee ids
*/
private function truncateExcessPendingDependents(
array $employee,
int $clientPolicyId,
int $approvedEmployeeId,
$updatedBy,
string $processedByRole
): array {
log_message('error', '[truncateExcessPendingDependents] Start | approved_employee_id=' . $approvedEmployeeId
. ' | client_policy_id=' . $clientPolicyId
. ' | emp_code=' . ($employee['emp_code'] ?? '')
. ' | relationship=' . ($employee['relationship'] ?? '')
. ' | updated_by=' . ($updatedBy ?? 'null')
. ' | processed_by_role=' . $processedByRole);
$relationship = strtolower(trim((string) ($employee['relationship'] ?? '')));
$floaterKey = ! empty($employee['family_floater_key'])
? preg_replace('/\d/', '', strtolower(trim((string) $employee['family_floater_key'])))
: strtolower((string) ($this->RelationshipMap($employee['relationship'] ?? '') ?? ''));
$isSpouse = ($relationship === 'spouse' || $floaterKey === 'spouse');
$isChild = in_array($relationship, ['son', 'daughter'], true) || $floaterKey === 'child';
log_message('error', '[truncateExcessPendingDependents] Resolved type | is_spouse=' . ($isSpouse ? '1' : '0')
. ' | is_child=' . ($isChild ? '1' : '0'));
if (! $isSpouse && ! $isChild) {
log_message('error', '[truncateExcessPendingDependents] Skip: not spouse/child');
return [];
}
$clientPolicy = $this->clientPolicyModel->select('policy_terms')->where('id', $clientPolicyId)->first();
if (empty($clientPolicy['policy_terms'])) {
log_message('error', '[truncateExcessPendingDependents] Skip: policy_terms empty');
return [];
}
$policyTerms = json_decode($clientPolicy['policy_terms'], true);
if (! is_array($policyTerms) || empty($policyTerms['family_floaters'])) {
log_message('error', '[truncateExcessPendingDependents] Skip: family_floaters missing');
return [];
}
$familyFloaters = is_array($policyTerms['family_floaters'])
? $policyTerms['family_floaters']
: (array) $policyTerms['family_floaters'];
$allowedCount = $isSpouse
? (int) ($familyFloaters['spouse'] ?? 0)
: (int) ($familyFloaters['childrens'] ?? 0);
log_message('error', '[truncateExcessPendingDependents] Allowed count for type | allowed=' . $allowedCount
. ' | family_floaters=' . json_encode($familyFloaters));
$familyMembers = $this->employeeModel
->select('employees.id, employees.relationship, employees.family_floater_key, employees.emp_status, employee_polices.status as policy_status')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code', $employee['emp_code'])
->where('employees.client_id', $employee['client_id'])
->where('employee_polices.client_policy_id', $clientPolicyId)
->where('employees.id !=', $approvedEmployeeId)
->groupStart()
->groupStart()
->where('employees.emp_status', 'active')
->where('employee_polices.status', 'active')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->groupEnd()
->orGroupStart()
->where('employees.emp_status', 'pending_approval')
->where('employee_polices.status', 'pending_approval')
->groupEnd()
->groupEnd()
->orderBy('employees.id', 'ASC')
->findAll();
log_message('error', '[truncateExcessPendingDependents] Family members fetched | count='
. count($familyMembers) . ' | members=' . json_encode($familyMembers));
$activeCount = 1; // just-approved dependent already counts toward the limit
$pendingIds = [];
foreach ($familyMembers as $member) {
$memberRelationship = strtolower(trim((string) ($member['relationship'] ?? '')));
$memberFloaterKey = ! empty($member['family_floater_key'])
? preg_replace('/\d/', '', strtolower(trim((string) $member['family_floater_key'])))
: '';
$sameType = $isSpouse
? ($memberRelationship === 'spouse' || $memberFloaterKey === 'spouse')
: (in_array($memberRelationship, ['son', 'daughter'], true) || $memberFloaterKey === 'child');
if (! $sameType) {
continue;
}
$memberEmpStatus = strtolower((string) ($member['emp_status'] ?? ''));
$memberPolicyStatus = strtolower((string) ($member['policy_status'] ?? ''));
if ($memberEmpStatus === 'active' && $memberPolicyStatus === 'active') {
$activeCount++;
} elseif ($memberEmpStatus === 'pending_approval' && $memberPolicyStatus === 'pending_approval') {
$pendingIds[] = (int) $member['id'];
}
}
log_message('error', '[truncateExcessPendingDependents] Counts | active_including_approved=' . $activeCount
. ' | pending_ids=' . json_encode($pendingIds));
if (empty($pendingIds)) {
log_message('error', '[truncateExcessPendingDependents] No pending dependents to truncate');
return [];
}
$remainingSlots = max(0, $allowedCount - $activeCount);
// Keep only as many pending as remaining slots; truncate the rest (excess)
$idsToTruncate = array_slice($pendingIds, $remainingSlots);
log_message('error', '[truncateExcessPendingDependents] Slot calc | allowed=' . $allowedCount
. ' | active=' . $activeCount
. ' | remaining_slots=' . $remainingSlots
. ' | ids_to_truncate=' . json_encode($idsToTruncate));
if (empty($idsToTruncate)) {
log_message('error', '[truncateExcessPendingDependents] No excess pending; nothing to truncate');
return [];
}
log_message('error', '[truncateExcessPendingDependents] Updating employees to truncate | ids='
. json_encode($idsToTruncate));
$this->employeeModel
->whereIn('id', $idsToTruncate)
->set([
'emp_status' => 'truncate',
'is_active' => 0,
'updated_by' => $updatedBy,
'processed_by' => $processedByRole,
])
->update();
log_message('error', '[truncateExcessPendingDependents] Updating employee_polices to truncate | ids='
. json_encode($idsToTruncate) . ' | client_policy_id=' . $clientPolicyId);
$this->employeePolicyModel
->whereIn('employee_id', $idsToTruncate)
->where('client_policy_id', $clientPolicyId)
->set([
'status' => 'truncate',
'is_active' => 0,
'updated_by' => $updatedBy,
'processed_by' => $processedByRole,
])
->update();
log_message('error', '[truncateExcessPendingDependents] Done | truncated_ids=' . json_encode($idsToTruncate));
$this->myLogger->logme('error', '[truncateExcessPendingDependents] Done | truncated_ids=' . json_encode($idsToTruncate));
return $idsToTruncate;
}
/**
* List dependent-add workflow members (API + mobile).
* Returns only pending_approval, approved, and rejected dependents (not all members).
* Filters: client_id, client_branch_id / branch_id, client_policy_id / policy_id, optional search.
*/
public function getPendingApprovalDependents()
{
try {
$client_id = $this->request->getGet('client_id');
$branch_id = $this->request->getGet('client_branch_id') ?? $this->request->getGet('branch_id');
$policy_id = $this->request->getGet('client_policy_id') ?? $this->request->getGet('policy_id');
$search = trim((string) ($this->request->getGet('search') ?? ''));
$empData = $this->employeePolicyModel->getPendingApprovalDependents(
client_id: $client_id ?? 0,
policy_id: $policy_id ?? 0,
branch_id: $branch_id ?? 0,
search: $search
);
if ($empData) {
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Dependent approval list fetched successfully',
'data' => $empData,
], 200);
}
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'No dependent approval records found',
'data' => [],
], 200);
} catch (\Exception $e) {
return $this->respond([
'status' => 'failed',
'code' => 500,
'message' => $e->getMessage(),
'data' => [],
], 500);
}
}
/**
* Policy-wise employee details API (chat context).
* Input: emp_code, client_id (numeric id or MD5 hash of id)
* user_key format: {employee_id}_{client_id}
*/
public function getEmployeePolicyWiseDetails()
{
try {
$emp_code = trim((string) ($this->request->getGet('emp_code') ?? $this->request->getPost('emp_code') ?? ''));
$client_id = $this->request->getGet('client_id') ?? $this->request->getPost('client_id') ?? null;
if ($emp_code === '' || $client_id === null || $client_id === '') {
return $this->respond([
'status' => 'failed',
'code' => 400,
'message' => 'Required parameters missing: emp_code and client_id are required',
'data' => [],
], 200);
}
$client_id = $this->resolveClientId($client_id);
if (empty($client_id)) {
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'Invalid client_id',
'data' => [],
], 200);
}
$employeeRows = $this->employeeModel
->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('is_active', 1)
->findAll();
if (empty($employeeRows)) {
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'Employee not found for the given emp_code and client_id',
'data' => [],
], 200);
}
$selfEmployee = null;
foreach ($employeeRows as $row) {
$rel = strtolower(trim((string) ($row['relationship'] ?? '')));
$floater = strtolower(trim((string) ($row['family_floater_key'] ?? '')));
if ($rel === 'self' || $floater === 'self') {
$selfEmployee = $row;
break;
}
}
if ($selfEmployee === null) {
$selfEmployee = $employeeRows[0];
}
$employeeId = (string) $selfEmployee['id'];
$clientIdStr = (string) $client_id;
$userKey = $employeeId . '_' . $clientIdStr;
$employeeIds = array_column($employeeRows, 'id');
$dayInterval = 10;
$enrolledPolicyIds = $this->employeePolicyModel
->select('client_policy_id')
->whereIn('employee_id', $employeeIds)
->where('is_active', 1)
->whereIn('status', ['active', 'expired'])
->groupBy('client_policy_id')
->findColumn('client_policy_id');
if (empty($enrolledPolicyIds)) {
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'No active policies found for the employee',
'data' => [],
], 200);
}
$enrolledPolicies = $this->clientPolicyModel
->select("client_policy.*, policy_type.policy_type, policy_type.long_name AS policy_long_name, insurers.name AS insurer_name, tpa.name AS tpa_name, tpa.network_hospitals AS network_hospitals_url, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) AS claims_grace_date")
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->join('insurers', 'insurers.id = client_policy.insurer_id', 'left')
->join('tpa', 'tpa.id = client_policy.tpa_id', 'left')
->whereIn('client_policy.id', $enrolledPolicyIds)
->where('client_policy.is_active', 1)
->where('client_policy.policy_status', 1)
->orderBy('client_policy.id', 'ASC')
->findAll();
if (empty($enrolledPolicies)) {
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'No active policies found for the employee',
'data' => [],
], 200);
}
$policies = [];
foreach ($enrolledPolicies as $policy) {
$clientPolicyId = (int) $policy['id'];
$policyTypeId = (int) $policy['policy_type_id'];
$ticketMeta = $this->getPolicyTicketMeta($policyTypeId);
$termsRaw = json_decode($policy['policy_terms'] ?? '{}');
$termsArray = json_decode($policy['policy_terms'] ?? '{}', true) ?: [];
$coveredMembers = $this->employeePolicyModel
->select('
employees.id AS employee_id,
employees.emp_code,
employees.name,
employees.relationship,
employees.family_floater_key,
employees.gender,
employees.dob,
employees.emp_status,
employee_polices.uhid,
employee_polices.tpa_id,
employee_polices.rand_string,
employee_polices.basic_cover_si,
employee_polices.premium,
employee_polices.rata_premimum,
employee_polices.gst,
employee_polices.payable_employee,
employee_polices.date_coverage,
employee_polices.policy_end_date AS member_policy_end_date,
employee_polices.status AS emp_policy_status
')
->join('employees', 'employees.id = employee_polices.employee_id', 'left')
->whereIn('employee_polices.employee_id', $employeeIds)
->where('employee_polices.client_policy_id', $clientPolicyId)
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.is_active', 1)
->findAll();
if (empty($coveredMembers)) {
continue;
}
$premiumSummary = $this->buildPremiumDetails($coveredMembers, $policyTypeId);
$claimsSummary = $this->getClaimsForPolicy($emp_code, $clientPolicyId);
$sumInsured = $premiumSummary['sum_insured'];
$benefits = [];
if (!empty($termsArray['enrollment_display_key']) && is_array($termsArray['enrollment_display_key'])) {
$benefits = $this->normalizePolicyTermsKeys($termsArray['enrollment_display_key']);
} else {
$benefits = $this->normalizePolicyTermsKeys(
$this->policyTermsFiter($termsRaw, $ticketMeta['policy_group']) ?: []
);
}
$policyTerms = [];
if (!empty($termsArray['enrollment_display_key']) && is_array($termsArray['enrollment_display_key'])) {
$policyTerms = $this->normalizePolicyTermsKeys($termsArray['enrollment_display_key']);
}
$familyFloaters = $this->extractFamilyFloaters($termsArray);
$isFamilyFloater = true;
if (isset($termsArray['family_floater']) && strpos(strtolower((string) $termsArray['family_floater']), 'no') !== false) {
$isFamilyFloater = false;
}
$policies[] = [
'policy_type' => $policy['policy_type'],
'policy_no' => $policy['policy_no'],
'policy_name' => $policy['policy_type'],
'heading' => $policy['policy_long_name'],
'insurer_name' => $policy['insurer_name'],
'tpa_name' => $policy['tpa_name'] ?: null,
'network_hospitals_url' => $policy['network_hospitals_url'] ?: null,
'policy_status' => ((int) $policy['policy_status'] === 1) ? 'Active' : 'Inactive',
'policy_start_date' => $this->convertDateFormatDisplay($policy['policy_start_date']),
'policy_end_date' => $this->convertDateFormatDisplay($policy['policy_end_date']),
'claims_grace_date' => $this->convertDateFormatDisplay($policy['claims_grace_date']),
'sum_insured_label' => $ticketMeta['sum_insured_label'],
'sum_insured' => (string) $sumInsured,
'sum_insured_display' => $this->formatAmountDisplay($sumInsured),
'claim_subject' => $ticketMeta['claim_subject'],
'family_floater' => $isFamilyFloater,
'family_floaters' => $familyFloaters,
'age_limits' => $this->extractAgeLimits($termsRaw),
'members' => $this->buildPolicyMembersList($coveredMembers),
'benefits' => $benefits ?: new \stdClass(),
'policy_terms' => $policyTerms ?: new \stdClass(),
'premium_summary' => $premiumSummary,
'claims_summary' => $claimsSummary,
];
}
if (empty($policies)) {
return $this->respond([
'status' => 'failed',
'code' => 404,
'message' => 'No policy coverage found for the employee',
'data' => [],
], 200);
}
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Policy chat context fetched successfully',
'data' => [
'employee_id' => $employeeId,
'client_id' => $clientIdStr,
'user_key' => $userKey,
'employee_summary' => [
'name' => $selfEmployee['name'] ?? null,
'emp_code' => $selfEmployee['emp_code'] ?? $emp_code,
'designation' => $selfEmployee['designation'] ?? null,
'band' => $selfEmployee['band'] ?? null,
'unit' => $selfEmployee['unit'] ?? null,
'emp_status' => $selfEmployee['emp_status'] ?? null,
'email_corporate' => $selfEmployee['email_corporate'] ?? null,
'mobile' => $selfEmployee['mobile'] ?? null,
],
'policies' => $policies,
'support' => $this->getClientSupportContacts((int) $client_id),
],
], 200);
} catch (\Exception $e) {
$this->myLogger->logme('error', 'getEmployeePolicyWiseDetails: ' . $e->getMessage() . ' --- ' . $e->getLine());
return $this->respond([
'status' => 'failed',
'code' => 500,
'message' => 'Something went wrong while fetching employee policy-wise details',
'data' => [],
], 500);
}
}
/**
* Resolve numeric client_id from MD5 hash or plain id.
*/
private function resolveClientId($client_id)
{
if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) {
$client = $this->clientModel->where('MD5(id)', $client_id)->first();
return $client['id'] ?? null;
}
if (is_numeric($client_id)) {
$client = $this->clientModel->where('id', (int) $client_id)->where('is_active', 1)->first();
return $client['id'] ?? (int) $client_id;
}
return null;
}
/**
* Support contacts for a client.
* level 1 = Head, level 2 = Manager, level 3 = Account Manager
*/
private function getClientSupportContacts(int $clientId): array
{
$support = [
'account_managers' => [],
'managers' => [],
'heads' => [],
];
$records = $this->clientRMModel
->select('client_rm.level, user_profiles.first_name, user_profiles.email, user_profiles.mobile')
->join('user_profiles', 'user_profiles.id = client_rm.user_id')
->where('client_rm.client_id', $clientId)
->where('client_rm.is_active', 1)
->whereIn('client_rm.level', [1, 2, 3])
->findAll();
foreach ($records as $record) {
$contact = [
'name' => $record['first_name'] ?? null,
'mobile' => $record['mobile'] ?? null,
'email' => $record['email'] ?? null,
];
$level = (int) ($record['level'] ?? 0);
if ($level === 3) {
$support['account_managers'][] = $contact;
} elseif ($level === 2) {
$support['managers'][] = $contact;
} elseif ($level === 1) {
$support['heads'][] = $contact;
}
}
return $support;
}
private function getPolicyTicketMeta(int $policyTypeId): array
{
if ($policyTypeId === 1) {
return [
'policy_group' => 'gpa',
'ticket_type_id' => 2,
'ticket_settled_status_id' => 24,
'claim_subject' => 'Claim GPA',
'sum_insured_label' => 'Sum Assured',
];
}
if ($policyTypeId === 6) {
return [
'policy_group' => 'other',
'ticket_type_id' => 3,
'ticket_settled_status_id' => 34,
'claim_subject' => 'Claim EDLI',
'sum_insured_label' => 'Sum Assured',
];
}
if ($policyTypeId === 7) {
return [
'policy_group' => 'other',
'ticket_type_id' => 4,
'ticket_settled_status_id' => 44,
'claim_subject' => 'Claim GTLI',
'sum_insured_label' => 'Sum Assured',
];
}
if ($policyTypeId === 72) {
return [
'policy_group' => 'other',
'ticket_type_id' => 72,
'ticket_settled_status_id' => 76,
'claim_subject' => 'Claim OPD',
'sum_insured_label' => 'Sum Insured',
];
}
return [
'policy_group' => 'gmc',
'ticket_type_id' => 1,
'ticket_settled_status_id' => 11,
'claim_subject' => 'Claim GMC',
'sum_insured_label' => 'Sum Insured',
];
}
private function extractFamilyFloaters(array $termsArray): array
{
$floaters = $termsArray['family_floaters'] ?? [];
if (!is_array($floaters)) {
$floaters = [];
}
return [
'self' => $floaters['self'] ?? 0,
'spouse' => $floaters['spouse'] ?? 0,
'childrens' => $floaters['childrens'] ?? 0,
'parents' => $floaters['parents'] ?? 0,
'parents-in-law' => $floaters['parents-in-law'] ?? ($floaters['parents_in_law'] ?? 0),
'either-parents-pil' => $floaters['either-parents-pil'] ?? 0,
'elders_count' => $floaters['elders_count'] ?? null,
];
}
private function extractAgeLimits($termsRaw): array
{
$defaults = [
'self' => ['min' => 18, 'max' => 60],
'spouse' => ['min' => 18, 'max' => 60],
'child' => ['min' => 0, 'max' => 25],
'elders' => ['min' => 18, 'max' => 60],
];
if (is_object($termsRaw) && isset($termsRaw->age_ratio) && is_object($termsRaw->age_ratio)) {
$ageRatio = $termsRaw->age_ratio;
return [
'self' => [
'min' => $ageRatio->self->min ?? $defaults['self']['min'],
'max' => $ageRatio->self->max ?? $defaults['self']['max'],
],
'spouse' => [
'min' => $ageRatio->spouse->min ?? $defaults['spouse']['min'],
'max' => $ageRatio->spouse->max ?? $defaults['spouse']['max'],
],
'child' => [
'min' => $ageRatio->child->min ?? $defaults['child']['min'],
'max' => $ageRatio->child->max ?? $defaults['child']['max'],
],
'elders' => [
'min' => $ageRatio->elders->min ?? $defaults['elders']['min'],
'max' => $ageRatio->elders->max ?? $defaults['elders']['max'],
],
];
}
return $defaults;
}
private function buildPolicyMembersList(array $coveredMembers): array
{
$members = [];
foreach ($coveredMembers as $member) {
$members[] = $this->formatChatContextMember($member);
}
usort($members, function ($a, $b) {
$order = ['self' => 0, 'spouse' => 1, 'son' => 2, 'daughter' => 3];
$aKey = strtolower((string) ($a['relationship'] ?? ''));
$bKey = strtolower((string) ($b['relationship'] ?? ''));
return ($order[$aKey] ?? 99) <=> ($order[$bKey] ?? 99);
});
return $members;
}
private function formatChatContextMember(array $member): array
{
$eCardDownload = null;
if (!empty($member['tpa_id']) && !empty($member['rand_string'])) {
$eCardDownload = base_url('download-e-card/') . $member['rand_string'] . '/1';
}
$basicCoverSi = $member['basic_cover_si'] ?? 0;
return [
'name' => $member['name'] ?? null,
'relationship' => $member['relationship'] ?? null,
'gender' => $member['gender'] ?? null,
'dob' => !empty($member['dob']) ? $this->convertDateFormatDMY($member['dob']) : null,
'emp_status' => $member['emp_status'] ?? null,
'basic_cover_si' => $basicCoverSi,
'basic_cover_si_display' => $this->formatAmountDisplay($basicCoverSi),
'premium' => $member['premium'] ?? null,
'gst' => $member['gst'] ?? null,
'payable_employee' => isset($member['payable_employee']) ? (int) $member['payable_employee'] : 0,
'date_coverage' => !empty($member['date_coverage']) ? $this->convertDateFormatDMY($member['date_coverage']) : null,
'member_policy_end_date' => !empty($member['member_policy_end_date']) ? $this->convertDateFormatDMY($member['member_policy_end_date']) : null,
'emp_policy_status' => $member['emp_policy_status'] ?? null,
'eCardDownload' => $eCardDownload,
];
}
private function formatAmountDisplay($amount): string
{
if ($amount === null || $amount === '') {
return '0';
}
if (function_exists('formatIndianCurrency')) {
return (string) formatIndianCurrency($amount);
}
return number_format((float) $amount, 0, '.', ',');
}
/**
* Normalize enrollment_display_key terms:
* - "Room Rent Limit" => room_rent_limit
* - whitespace-only values => ""
*/
private function normalizePolicyTermsKeys(array $terms): array
{
$normalized = [];
foreach ($terms as $key => $value) {
$snakeKey = strtolower(trim((string) $key));
$snakeKey = preg_replace('/[^a-z0-9]+/', '_', $snakeKey);
$snakeKey = trim($snakeKey, '_');
if (is_string($value)) {
$value = trim($value);
} elseif (is_array($value)) {
$value = $this->normalizePolicyTermsKeys($value);
}
if ($snakeKey === '') {
continue;
}
$normalized[$snakeKey] = $value;
}
return $normalized;
}
private function buildPremiumDetails(array $coveredMembers, int $policyTypeId): array
{
$siValue = 0;
$premiumTotal = 0;
$gstTotal = 0;
$rataTotal = 0;
foreach ($coveredMembers as $member) {
if ($siValue == 0 && isset($member['basic_cover_si'])) {
$siValue = $member['basic_cover_si'];
}
$premiumTotal += (float) ($member['premium'] ?? 0);
$gstTotal += (float) ($member['gst'] ?? 0);
$rataTotal += (float) ($member['rata_premimum'] ?? 0);
}
$hidePremium = in_array($policyTypeId, [1, 2], true);
return [
'sum_insured' => $siValue,
'total_premium' => $hidePremium ? 0 : round($premiumTotal),
'total_gst' => $hidePremium ? 0 : round($gstTotal),
'total_rata_premium' => $hidePremium ? 0 : round($rataTotal),
'total_with_gst' => $hidePremium ? 0 : round($premiumTotal + $gstTotal),
'member_count' => count($coveredMembers),
];
}
private function getClaimsForPolicy(string $empCode, int $clientPolicyId): array
{
$db = db_connect();
$claims = $db->table('ticket_master tm')
->select([
'tm.id AS ticket_id',
'tm.claim_number AS claim_no',
"CASE
WHEN tcs.display_name IS NULL OR tcs.display_name = ''
THEN tcs.claim_status
ELSE UPPER(tcs.display_name)
END AS status",
"CASE
WHEN tm.tpa_claim_type IS NOT NULL AND tm.tpa_claim_type != ''
THEN tm.tpa_claim_type
ELSE 'Reimbursement'
END AS claim_type",
'tm.insured_name',
'tm.relationship',
'tm.hospital_name',
'tm.doa',
'tm.dod',
'tm.claim_amount',
'tm.approved_amount',
'tm.settled_date',
'tm.denial_reason',
'tm.utr_details',
])
->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id', 'left')
->where('tm.emp_code', $empCode)
->where('tm.client_policy_id', $clientPolicyId)
->where('tm.is_active', 1)
->orderBy('tm.id', 'DESC')
->get()
->getResultArray();
$formattedClaims = [];
$totalClaimAmount = 0;
$totalApprovedAmount = 0;
foreach ($claims as $claim) {
$totalClaimAmount += (float) ($claim['claim_amount'] ?? 0);
$totalApprovedAmount += (float) ($claim['approved_amount'] ?? 0);
$formattedClaims[] = [
'ticket_id' => (string) ($claim['ticket_id'] ?? ''),
'claim_no' => $claim['claim_no'] ?? null,
'status' => $claim['status'] ?? null,
'claim_type' => $claim['claim_type'] ?? null,
'insured_name' => $claim['insured_name'] ?? null,
'relationship' => $claim['relationship'] ?? null,
'hospital_name' => $claim['hospital_name'] ?? null,
'doa' => $claim['doa'] ?? null,
'dod' => $claim['dod'] ?? null,
'claim_amount' => $claim['claim_amount'] ?? null,
'approved_amount' => $claim['approved_amount'] ?? null,
'settled_date' => $claim['settled_date'] ?? null,
'denial_reason' => $claim['denial_reason'] ?? null,
'utr_details' => $claim['utr_details'] ?? null,
];
}
return [
'count' => count($formattedClaims),
'total_claim_amount' => round($totalClaimAmount, 2),
'total_approved_amount' => round($totalApprovedAmount, 2),
'claims' => $formattedClaims,
];
}
}