nhance-enrollment/app/Controllers/EmployeeRestController.php
2026-08-06 11:40:32 +05:30

5219 lines
258 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Helpers\MailHelper;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Helpers\sendMailNotification;
use App\Helpers\EmployeeHelper;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientRMModel;
use App\Models\PolicesModel;
use App\Models\RelationshipModel;
use App\Models\FileModel;
use App\Models\ClientPolicyModel;
use App\Models\PolicyPremium1Model;
use App\Models\PolicyPremium2Model;
use App\Models\PolicyTypeModel;
use App\Models\NotificationModel;
use App\Models\UserModel;
use App\Models\FEContentModel;
use App\Models\AddImgModel;
use App\Models\ClientBranchModel;
use App\Models\AuditHistoryModel;
use App\Models\SIMappingModel;
use App\Models\InsurerModel;
use App\Models\HrFileUploadModel;
use App\Models\ReminderMailConfigModel;
use App\Controllers\Jobs ;
use App\Controllers\JobWorker ;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use CodeIgniter\API\ResponseTrait;
use Illuminate\Http\Request;
use App\Controllers\EmployeeServiceController;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Exception\MessagingException;
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 $siMappingModel;
protected $employeeHelper;
protected $insurerModel;
protected $hrFileUploadModel;
protected ReminderMailConfigModel $reminderMailConfigModel;
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->siMappingModel = new SIMappingModel();
$this->employeeHelper = new EmployeeHelper();
$this->insurerModel = new InsurerModel();
$this->hrFileUploadModel = new HrFileUploadModel();
$this->reminderMailConfigModel = new ReminderMailConfigModel();
}
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();
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();
$clientPolicyData = $this->clientPolicyModel->where('id',$data[0]->client_policy_id)
->where('is_active', 1)
->first();
if(in_array($clientPolicyData['policy_type_id'], [3,4,5,72])){
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($clientPolicyData['base_policy'], $data[0]->emp_code);
}else{
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($data[0]->client_policy_id, $data[0]->emp_code);
}
//enrolment check
if($openForEnrollment == false){
return $this->respond(['status' => 'failed','code' => 404,'data' => [],'message' => 'Enrollment closed.'], 200);
}
//dependent duplicate check
if ( ! isset($data[0]->id) ) {
$validationFailed = $this->employeeHelper->validation_addEmployeeAndDependence($data);
if($validationFailed){
return $this->respond(['status' => 'failed','code' => 404,'data' => [],'message' => "Relation already exists."], 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';
$item->is_dependent_modified = 1;
$item->band = $this->getSelfBand($item->emp_code,$item->client_id,$item->client_branch_id);
// dd($item);
$employee = $this->employeeModel->insert($item);
if ($employee) {
$Count++;
}
}
}
if ($Count > 0) {
if(isset($data[0]->id))
{
$payable_employee = $this->getEmployeePayableValue($data[0]->client_policy_id,$data[0]->relationship);
$this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si, $payable_employee);
}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,'message' => "Successfully updated."], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result,'message' => "Action failed."], 200);
}
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage() . $e->getLine(),'message' => "Action failed."], 500);
}
}
public function getSelfBand(string $emp_code, int $client_id, int $client_branch_id): ?string
{
$employee = $this->employeeModel
->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('client_branch_id', $client_branch_id)
->whereIn('emp_status', ['draft', 'enrolled'])
->where('is_active', 1)
->where('relationship','Self')
->first();
return $employee['band'] ?? null;
}
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)
{
if($basic_cover_si == null)
{
$client_policy = $this->clientPolicyModel->where('id', $client_policy_id)->where('client_id', $client_id)->first();
$policy_terms = json_decode($client_policy['policy_terms']);
$basic_cover_si = $policy_terms->sum_insured;
}
$other_employee_policy_data = $this->employeePolicyModel
->select('employee_polices.*')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employees.emp_code', $emp_code)
->where('employee_polices.client_policy_id', $client_policy_id)
->where('employee_polices.is_active', 1)
->where('employees.is_active', 1)
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->where('employee_polices.enrollment_open_date is not null')
->where('employee_polices.enrollment_close_date is not null')
->first();
$checkDataExist = $this->employeePolicyModel->where('employee_id',$employee_id)->where('client_policy_id',$client_policy_id)->where('is_active', 1)->first();
if($checkDataExist){
$this->employeePolicyModel
->where('client_policy_id',$client_policy_id )
->where('employee_id' , $employee_id )
->where('is_active', 1 )
->set(array('basic_cover_si'=> $basic_cover_si ))
->update();
}else{
$enrollment_dates = $this->getEnrollmentDates($client_policy_id, $emp_code);
$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['status']= 'draft';
$data['date_coverage'] = $this->getEmployeeCoverageDate($emp_code, $client_policy_id);
if(!empty($other_employee_policy_data)){
$data['enrollment_open_date']= $other_employee_policy_data['enrollment_open_date'] ?? null;
$data['enrollment_close_date']= $other_employee_policy_data['enrollment_close_date'] ?? null;
}else{
$data['enrollment_open_date'] = $enrollment_dates['enrollment_open_date'] ?? null;
$data['enrollment_close_date'] = $enrollment_dates['enrollment_close_date'] ?? null;
}
// dd($data);
$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(array('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'], 'payable_employee'=> $value['policy_details']['payable_employee'] ?? 0 ))
->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;
}
}
public function deleteDependence()
{
try {
if($this->request->getGet('id'))
{
$is_from_copy = $this->request->getGet('is_from_copy') ?? null;
if($is_from_copy == 'false' || $is_from_copy == false || $is_from_copy == 'null' || $is_from_copy == null){
$this->employeeModel->where('id', $this->request->getGet('id') )
->where('is_active', 1 )
->set(['emp_status' => 'truncated', 'is_active' => 0, 'is_dependent_modified' => 0])
->update();
}
$query = $this->employeePolicyModel
->where('employee_id', $this->request->getGet('id'))
->where('is_active', 1);
// 👉 Add condition only if client_policy_id exists
$clientPolicyId = $this->request->getGet('client_policy_id') ?? null;
if (!empty($clientPolicyId)) {
$query->where('client_policy_id', $clientPolicyId);
}
$query->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 createOrUpdateEmployeePolicySiAmount()
{
try {
$requestData = $this->request->getJSON();
// print_r($requestData);
// dd($requestData);
$clientPolicyData = $this->clientPolicyModel->where('id',$requestData[0]->client_policy_id)
->where('is_active', 1)
->first();
if(in_array($clientPolicyData['policy_type_id'], [3,4,5,72])){
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($clientPolicyData['base_policy'], $requestData[0]->emp_code);
}else{
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($requestData[0]->client_policy_id, $requestData[0]->emp_code);
}
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();
// dd($checkIfExist);
if ($checkIfExist) {
$empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si);
}else{
$enrollment_dates = $this->getEnrollmentDates($value->client_policy_id, $requestData[0]->emp_code);
$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';
$data['enrollment_open_date'] = $enrollment_dates['enrollment_open_date'] ?? null;
$data['enrollment_close_date'] = $enrollment_dates['enrollment_close_date'] ?? null;
$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 {
$cardDataParam = strtolower(trim((string) ($this->request->getGet('card_data') ?? '')));
$cardDataParam = str_replace(['-', ' '], '_', $cardDataParam);
$search = trim((string) ($this->request->getGet('search') ?? ''));
$cardFilters = ['all', 'emp_count', 'submitted', 'logged_in', 'not_logged_in', 'draft'];
$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: 'hr',
search: $cardDataParam === 'all' ? '' : $search
) ?: [];
if (in_array($cardDataParam, $cardFilters, true)) {
$response = $this->prepareMemberCardDataResponse($empData, $cardDataParam);
return $this->respond([
'status' => 'success',
'code' => 200,
'data' => $response['data'],
'card_data' => $response['card_data'],
], 200);
}
if ($empData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
/**
* Build Member Details response for card_data filters (Self relationship only).
*
* @return array{data: array, card_data: array}
*/
private function prepareMemberCardDataResponse(array $empData, string $cardDataParam): array
{
$cardData = $this->buildMemberCardData($empData);
if ($cardDataParam === 'all') {
return [
'data' => [],
'card_data' => $cardData,
];
}
$filteredData = array_values(array_filter($empData, function ($row) use ($cardDataParam) {
return $this->matchesMemberCardFilter($row, $cardDataParam);
}));
return [
'data' => $filteredData,
'card_data' => $cardData,
];
}
/**
* Whether a row matches the selected card filter (Self only).
*/
private function matchesMemberCardFilter(array $row, string $cardDataParam): bool
{
if (strtolower(trim((string) ($row['relationship'] ?? ''))) !== 'self') {
return false;
}
if ($cardDataParam === 'emp_count') {
return true;
}
$status = strtolower(trim((string) ($row['status'] ?? '')));
$empStatus = strtolower(trim((string) ($row['emp_status'] ?? '')));
$isSubmitted = in_array($status, ['submitted', 'enrolled'], true)
|| $empStatus === 'enrolled';
$isLoggedIn = strtolower((string) ($row['logged_in'] ?? '')) === 'yes';
return match ($cardDataParam) {
'submitted' => $isSubmitted,
'logged_in' => $isLoggedIn,
'not_logged_in' => !$isLoggedIn,
'draft' => !$isSubmitted,
default => false,
};
}
/**
* Member Details badge counts — Self relationship only.
*/
private function buildMemberCardData(array $empData): array
{
$counts = [
'emp_count' => 0,
'submitted' => 0,
'logged_in' => 0,
'not_logged_in' => 0,
'draft' => 0,
];
foreach ($empData as $row) {
if (strtolower(trim((string) ($row['relationship'] ?? ''))) !== 'self') {
continue;
}
$counts['emp_count']++;
$status = strtolower(trim((string) ($row['status'] ?? '')));
$empStatus = strtolower(trim((string) ($row['emp_status'] ?? '')));
$isSubmitted = in_array($status, ['submitted', 'enrolled'], true)
|| $empStatus === 'enrolled';
if ($isSubmitted) {
$counts['submitted']++;
}
$isLoggedIn = strtolower((string) ($row['logged_in'] ?? '')) === 'yes';
if ($isLoggedIn) {
$counts['logged_in']++;
} else {
$counts['not_logged_in']++;
}
// Draft = Self who has not submitted (matches Emp Count - Submitted).
if (!$isSubmitted) {
$counts['draft']++;
}
}
return $counts;
}
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 employee + dependent list Excel.
* Filters: client_id, branch_id, policy_id only (same as getEmployeePolicy base filters).
* Columns: Emp Code, Name, TPA ID, Relationship, Date Of Birth, Gender, Mobile, Email, Status
*/
public function downloadEmployeeListExcel()
{
try {
$clientId = $this->request->getGet('client_id');
$branchId = $this->request->getGet('branch_id');
$policyId = $this->request->getGet('policy_id');
$empData = $this->employeePolicyModel->getEmployeePolicy(
client_id: $clientId,
policy_id: $policyId,
status: 0,
branch_id: $branchId
);
if (!count($empData)) {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => [], 'message' => 'No employee data found'], 200);
}
$headers = [
'Emp Code' => 'emp_code',
'Name' => 'name',
'TPA ID' => 'tpa_id',
'Relationship' => 'relationship',
'Date Of Birth' => 'formatted_dob',
'Gender' => 'gender',
'Mobile' => 'mobile',
'Email' => 'email_corporate',
'Status' => 'status',
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Employee List');
$column = 'A';
foreach ($headers as $header => $dbField) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
$headerRange = 'A1:I1';
$sheet->getStyle($headerRange)->getFont()->setBold(true);
$sheet->getStyle($headerRange)->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setRGB('BDD7EE');
$row = 2;
foreach ($empData as $employee) {
$column = 'A';
foreach ($headers as $dbField) {
$value = $employee[$dbField] ?? '';
if ($dbField === 'formatted_dob' && empty($value) && !empty($employee['dob'])) {
$value = date('d/m/Y', strtotime($employee['dob']));
}
if ($dbField === 'gender' && $value !== '') {
$genderLower = strtolower(trim((string) $value));
if ($genderLower === 'male' || $genderLower === 'm') {
$value = 'M';
} elseif ($genderLower === 'female' || $genderLower === 'f') {
$value = 'F';
}
}
$sheet->setCellValue($column . $row, $value);
$column++;
}
$row++;
}
foreach (range('A', 'I') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
$policyName = $empData[0]['policy_name'] ?? 'Employee';
$filename = preg_replace('/[^A-Za-z0-9_\-]/', '_', $policyName) . '-Employee-List.xlsx';
// Write to memory and return via CI Response so CORS after() filters still run.
// Raw header() + exit skips filters and causes CORS errors for cross-origin fetch.
$tempFile = tempnam(sys_get_temp_dir(), 'emp_list_');
$writer = new Xlsx($spreadsheet);
$writer->save($tempFile);
$excelData = file_get_contents($tempFile);
@unlink($tempFile);
return $this->response
->setStatusCode(200)
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment;filename="' . $filename . '"')
->setHeader('Cache-Control', 'max-age=0')
->setBody($excelData);
} 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);
}
}
public function employeeUpload()
{
try{
$post_data = [
'client_id' => $this->request->getPost('client_id') ?? null,
'client_branch_id' => $this->request->getPost('client_branch_id'),
'policy_id' => $this->request->getPost('policy_id'),
'enrollment_open_date' => $this->request->getPost('enrollment_open_date'),
'enrollment_close_date' => $this->request->getPost('enrollment_close_date'),
'file_action' => "enrollment",
'created_by' => $this->request->getPost('created_by') ?? null,
'emplist' => $this->request->getFile('file')
];
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'];
}
// print_r($post_data); die;
if(empty($post_data['client_id'])){
return $this->respondCreated(['status' => false, 'message' => 'Client is required', 'data' => []]);
}
$employeeController = new EmployeeController();
$responce = $employeeController->employeesUplodWithEvents($post_data);
// print_r($responce); die;
return $this->respond($responce, 200);
// if(!$responce['status']){
// $file_data = $this->getDataFromFilesTable(['file_id' => $responce['file_id']]);
// $responce['data'] = $file_data;
// return $this->respond($responce, 200);
// }else{
// $responce['data'] = [];
// return $this->respond($responce, 200);
// }
}catch(\Exception $e){
return $this->respondCreated(['status' => false, 'message' => $e->getMessage(), 'data' => []]);
}
}
// Upload the Employee Detail in DB by Sheet Data (DO NOT REMOVE THIS)
public function employeeUploadOld()
{
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 (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'];
}
$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;
$is_moved = $file->move(WRITEPATH . 'uploads/excel');
$filename = $file->getName();
$file_name_with_path = 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']))
{
if(isset($result['error_type'])){
$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);
}else {
$message = "The import file is in an incorrect format. Please compare it with our template file to correct it.";
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => $message,'data' => $result], 200);
}
}
//check the file exist or not
if(!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 (\Throwable $th) {
$this->myLogger->logme("error", ($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' => $th->getMessage(), 'error_data' => $errorData], 500);
}
}
public function getDataFromFilesTable($search_data)
{
$file_download_base = base_url('util/download-file-list/');
$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 getHrFileUploadErrorDetails($file_id)
{
}
//-------------------------------------
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) {
$latest_gmc_policy_id = getLatestGMCPolicy((array)$empPolicy);
$result = [];
foreach ($empPolicy as $array) {
// Reset employee array
// $empData = $employeeData;
$empData = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code',$emp_code)
->where('employees.client_id',$client_id)
->where('employees.client_branch_id',$client_branch_id)
->where('employee_polices.client_policy_id',$array->ClientPolicyId)
->where('employees.is_active', 1 )
->where('employee_polices.is_active', 1 )
->where('employees.is_addon_value',0)
->findAll();
// 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;
if($array->is_premium_summery == 1){
$array->si_premium_value = $si_premium_value;
$array->si_gst_value = $si_gst_value;
}else{
$array->si_premium_value = 0;
$array->si_gst_value = 0;
}
$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' )
{
$array->to_be_added_relationship = [];
$array->existing_relationship = [];
if(!empty($latest_gmc_policy_id) && $latest_gmc_policy_id == $array->ClientPolicyId){
$array->copy_dependence_data_enable = true;
}else{
$array->copy_dependence_data_enable = false;
}
// 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 of 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($array->existing_relationship,$temp['data']['relationship']);
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']['relationship'] = ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $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_push($array->to_be_added_relationship,['relationship'=>$temp2['data']['relationship'],'age_validation'=>$temp2['data']['age_validation']]);
$array->to_be_added_relationship = array_values(
array_map('unserialize',
array_unique(
array_map('serialize', $array->to_be_added_relationship)
)
)
);
}
}
$array->relationship = [];
foreach ($array->to_be_added_relationship as $key => $value) {
if($value['relationship'] == 'Spouse'){
array_push($array->relationship,['relationship'=>'Spouse','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if($value['relationship'] == 'Child'){
array_push($array->relationship, ['relationship'=>'Son','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Daughter','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if($value['relationship'] == 'Parent'){
$Father = array_search('Father',$array->existing_relationship);
$Mother = array_search('Mother',$array->existing_relationship);
if ($Father === false && $Mother === false) {
array_push($array->relationship, ['relationship'=>'Father','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Mother','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if ($Father !== false && $Mother === false) {
array_push($array->relationship, ['relationship'=>'Mother','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
} else if ($Mother !== false && $Father === false) {
array_push($array->relationship, ['relationship'=>'Father','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}
}else if($value['relationship'] == 'Parent in law'){
$FatherinLaw = array_search('Father in Law',$array->existing_relationship);
$MotherinLaw = array_search('Mother in Law',$array->existing_relationship);
if ($FatherinLaw === false && $MotherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Father in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Mother in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if ($FatherinLaw !== false && $MotherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Mother in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
} else if ($MotherinLaw !== false && $FatherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Father in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}
}
}
// echo '<pre>';
// print_r($array->existing_relationship);
// print_r($array->to_be_added_relationship);
// print_r($array->relationship);
// die;
$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.0;
if($array->is_premium_summery == 1){
$array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0.0;
$array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0.0;
}else{
$array->family_floaters_of_dependent_and_si_premium_value = 0.0;
$array->family_floaters_of_dependent_and_gst_value = 0.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 ,
(
SELECT COALESCE(
MAX(
CASE
WHEN ep.enrollment_open_date <= CURDATE()
AND ep.enrollment_close_date >= CURDATE()
THEN 1
ELSE 0
END
), 0
)
FROM employee_polices ep
INNER JOIN employees e ON e.id = ep.employee_id
WHERE e.is_active = 1
AND ep.is_active = 1
AND ep.enrollment_open_date IS NOT NULL
AND ep.enrollment_close_date IS NOT NULL
AND e.emp_code = '{$emp_code}'
AND ep.client_policy_id = client_policy.id
) AS OpenForEnrollment,
client_policy.inception_type as inception_type ,
client_policy.policy_terms as Policy_Terms ,
client_policy.is_premium_summery as is_premium_summery,
client_policy.enrolment_visibility
")
->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 )
->where('client_policy.enrolment_visibility', 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);
$result[] = $array;
$result[] = $GmcParrentsData;
}
if($this->request->getGet('policy') == 'GMC' && !$checkGmcParentsPolicyExist){
// return $this->respond(['status' => 'success','code' => 200,'data' => [$array]], 200);
$result[] = $array;
}
}
// $result[] = $array;
}
if(!empty($result) && $this->request->getGet('policy') == 'GMC'){
return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200);
// echo json_encode(['status' => 'success','code' => 200,'data' => $result], JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION);
}else{
return $this->respond(['status' => 'success','code' => 200,'data' => []], 200);
}
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200);
}
} catch (\Exception $e) {
$errorData = [
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'code' => $e->getCode(),
'trace' => $e->getTraceAsString(),
'trace_array' => $e->getTrace(), // full array version (optional)
'function' => $e->getTrace()[0]['function'] ?? null,
'class' => $e->getTrace()[0]['class'] ?? null,
];
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getLine(), 'error_data' => $errorData], 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) {
$array->to_be_added_relationship = [];
$array->existing_relationship = [];
// Reset employee array
// $empData = $employeeData;
$empData = $this->employeeModel
->select('employees.*')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code',$emp_code)
->where('employees.client_id',$client_id)
->where('employees.client_branch_id',$client_branch_id)
->where('employee_polices.client_policy_id',$array->ClientPolicyId)
->where('employees.is_active', 1 )
->where('employee_polices.is_active', 1 )
->where('employees.is_addon_value',0)
->findAll();
$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.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($array->existing_relationship,$temp['data']['relationship']);
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']['relationship'] = ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $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_push($array->to_be_added_relationship,['relationship'=>$temp2['data']['relationship'],'age_validation'=>$temp2['data']['age_validation']]);
$array->to_be_added_relationship = array_values(
array_map('unserialize',
array_unique(
array_map('serialize', $array->to_be_added_relationship)
)
)
);
}
}
$array->relationship = [];
foreach ($array->to_be_added_relationship as $key => $value) {
if($value['relationship'] == 'Spouse'){
array_push($array->relationship,['relationship'=>'Spouse','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if($value['relationship'] == 'Child'){
array_push($array->relationship, ['relationship'=>'Son','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Daughter','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if($value['relationship'] == 'Parent'){
$Father = array_search('Father',$array->existing_relationship);
$Mother = array_search('Mother',$array->existing_relationship);
if ($Father === false && $Mother === false) {
array_push($array->relationship, ['relationship'=>'Father','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Mother','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if ($Father !== false && $Mother === false) {
array_push($array->relationship, ['relationship'=>'Mother','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
} else if ($Mother !== false && $Father === false) {
array_push($array->relationship, ['relationship'=>'Father','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}
}else if($value['relationship'] == 'Parent in law'){
$FatherinLaw = array_search('Father in Law',$array->existing_relationship);
$MotherinLaw = array_search('Mother in Law',$array->existing_relationship);
if ($FatherinLaw === false && $MotherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Father in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
array_push($array->relationship, ['relationship'=>'Mother in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}else if ($FatherinLaw !== false && $MotherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Mother in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
} else if ($MotherinLaw !== false && $FatherinLaw === false) {
array_push($array->relationship, ['relationship'=>'Father in Law','age_validation'=>$value['age_validation'] , 'client_policy_id' => $array->ClientPolicyId]);
}
}
}
$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.0;
if($array->is_premium_summery == 1){
$array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0.0;
$array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0.0;
}else{
$array->family_floaters_of_dependent_and_si_premium_value = 0.0;
$array->family_floaters_of_dependent_and_gst_value = 0.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 ,
(
SELECT COALESCE(
MAX(
CASE
WHEN ep.enrollment_open_date <= CURDATE()
AND ep.enrollment_close_date >= CURDATE()
THEN 1
ELSE 0
END
), 0
)
FROM employee_polices ep
INNER JOIN employees e ON e.id = ep.employee_id
WHERE e.is_active = 1
AND ep.is_active = 1
AND ep.enrollment_open_date IS NOT NULL
AND ep.enrollment_close_date IS NOT NULL
AND e.emp_code = '{$emp_code}'
AND ep.client_policy_id = client_policy.id
) AS OpenForEnrollment,
client_policy.inception_type as inception_type ,
client_policy.policy_terms as Policy_Terms ,
client_policy.enrolment_visibility,
client_policy.is_premium_summery
")
->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;
if($array->is_premium_summery == 1){
$array->si_premium_value = round($si_premium_value);
$array->si_gst_value = round($si_gst_value);
}else{
$array->si_premium_value = 0;
$array->si_gst_value = 0;
}
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 {
// $jwt = $this->request->getHeaderLine('Authorization');
// $jwtParts = explode(' ', $jwt);
// $token = $jwtParts[1];
// $decodedPayload = json_decode(base64_decode(explode('.', $token)[1]), true);
// $token_type = $decodedPayload['token_type'];
// if ($token_type == 'pre') {
// $client = $this->clientModel->where('id', $this->request->getGet('client_id'))->first();
// if ($client) {
// $client['client_logo'] = base_url() . 'public/uploads/logo/' . $client['client_logo'];
// $clientPolicy = $this->clientPolicyModel->where('client_id', $this->request->getGet('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 if ($token_type == 'post') {
// $restAuthController = new RestAuthenticationController;
// //call and get Client Details data from post enrollment
// $queryParams = [
// 'client_id' => $this->request->getGet('client_id'),
// 'client_branch_id' => $this->request->getGet('client_branch_id')
// ];
// return $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
// } else {
// return $this->respond(['status' => 'failed', 'code' => 404, '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 getClientDetails()
{
try {
$pre_client_id = $this->request->getGet('pre_client_id');
$pre_branch_id = $this->request->getGet('pre_branch_id');
$post_client_id = $this->request->getGet('post_client_id');
$post_branch_id = $this->request->getGet('post_branch_id');
// Both pre and post: prefer post data; fall back to pre logo if post has none
if (!empty($pre_client_id) && !empty($post_client_id)) {
$restAuthController = new RestAuthenticationController;
$queryParams = [
'client_id' => $post_client_id,
'client_branch_id' => $post_branch_id
];
$postResponse = $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
$postData = is_string($postResponse) ? json_decode($postResponse, true) : null;
if (
is_array($postData)
&& (($postData['status'] ?? '') === 'success' || (int) ($postData['code'] ?? 0) === 200)
&& !empty($postData['data']['client'])
) {
$postLogo = $postData['data']['client']['client_logo'] ?? '';
if (empty($postLogo)) {
if (is_string($pre_client_id) && preg_match('/^[a-f0-9]{32}$/i', $pre_client_id)) {
$preClient = $this->clientModel->where('MD5(id)', $pre_client_id)->first();
} else {
$preClient = $this->clientModel->where('id', $pre_client_id)->first();
}
$logoFilename = $preClient['client_logo'] ?? '';
$logoPath = ROOTPATH . 'public/uploads/logo/' . $logoFilename;
if (!empty($logoFilename) && file_exists($logoPath)) {
$postData['data']['client']['client_logo'] = base_url() . 'public/uploads/logo/' . $logoFilename;
}
}
return $this->respond($postData, 200);
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
if (!empty($pre_client_id)) {
if (is_string($pre_client_id) && preg_match('/^[a-f0-9]{32}$/i', $pre_client_id)) {
$client = $this->clientModel->where('MD5(id)', $pre_client_id)->first();
} else {
$client = $this->clientModel->where('id', $pre_client_id)->first();
}
if ($client) {
$logoFilename = $client['client_logo'] ?? '';
$logoPath = ROOTPATH . 'public/uploads/logo/' . $logoFilename;
$client['client_logo'] = (!empty($logoFilename) && file_exists($logoPath))
? base_url() . 'public/uploads/logo/' . $logoFilename
: '';
$clientPolicy = $this->clientPolicyModel
->where('client_id', $client['id'] ?? null)
->where('client_branch_id', $pre_branch_id)
->findAll();
return $this->respond([
'status' => 'success',
'code' => 200,
'data' => [
'client' => $client,
'client_policy' => $clientPolicy
]
], 200);
}
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
if (!empty($post_client_id)) {
$restAuthController = new RestAuthenticationController;
$queryParams = [
'client_id' => $post_client_id,
'client_branch_id' => $post_branch_id
];
return $restAuthController->callThirdPartyGETAPI($queryParams, 'getClientDetails');
}
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 getSiMappedArray($policy_id,$base_policy_id)
{
$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();
if($selfGMC)
{
$selfSi = $selfGMC->basic_cover_si;
// Fetch the value
$policySiAmounts = $this->siMappingModel
->where('policy_id', $policy_id)
->where('base_policy_id', $base_policy_id)
->where('base_policy_si_amount', $selfSi)
->get()
->getRow();
if($policySiAmounts && isset($policySiAmounts->policy_si_amounts))
{
// Decode the JSON string into a PHP array
$amountsArray = json_decode($policySiAmounts->policy_si_amounts, true);
// Convert the array into the desired format
$formattedArray = array_map(function ($amount) {
return ['si' => (int) $amount]; // Cast to integer for proper JSON format
}, $amountsArray);
// Output or return the result
return $formattedArray;
}else{
return false;
}
}else{
return false;
}
}
public function getAddOnPolicy()
{
try {
$emp_code = $this->request->getGet('emp_code');
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
$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();
$policyIds = $this->getEmployeeAddOnPolicies($emp_code, $client_id, $client_branch_id);
// dd($policyIds);
$clientPolicy = $this->clientPolicyModel->select("
client_policy.*,
(
SELECT COALESCE(
MAX(
CASE
WHEN ep.enrollment_open_date <= CURDATE()
AND ep.enrollment_close_date >= CURDATE()
THEN 1
ELSE 0
END
), 0
)
FROM employee_polices ep
INNER JOIN employees e ON e.id = ep.employee_id
WHERE e.is_active = 1
AND ep.is_active = 1
AND ep.enrollment_open_date IS NOT NULL
AND ep.enrollment_close_date IS NOT NULL
AND e.emp_code = '{$emp_code}'
AND ep.client_policy_id = client_policy.id
) AS open_for_enrollment
")
->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)
->where('enrolment_visibility', 1)
->whereIn('id', $policyIds)
->findAll();
if(empty($policyIds)){
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200);
}
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'];
}
}
}
}
if(isset($array['base_policy']) && !empty($array['base_policy']))
{
$openForEnrollmentValue = (int) $this->findThePolicyIsOpenForEnrollment($array['base_policy'], $emp_code);
}else{
$openForEnrollmentValue = $array['open_for_enrollment'];
}
$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'] = $openForEnrollmentValue;
$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'];
$responce['is_premium_summery'] = $array['is_premium_summery'];
$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
{
$siArray = $this->getSiMappedArray($array['id'],$array['base_policy']);
$responce['SlabRates'] = is_array($siArray) ? $siArray : $responce['SlabRates'];
$array['to_be_added_relationship'] = [];
$array['existing_relationship'] = [];
// 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($array['existing_relationship'],$temp['data']['relationship']);
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']['relationship'] = ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $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);
array_push($array['to_be_added_relationship'],['relationship'=>$temp2['data']['relationship'],'age_validation'=>$temp2['data']['age_validation']]);
$array['to_be_added_relationship'] = array_values(
array_map('unserialize',
array_unique(
array_map('serialize', $array['to_be_added_relationship'])
)
)
);
}
}
$responce['relationship'] = [];
foreach ($array['to_be_added_relationship'] as $key => $value) {
if($value['relationship'] == 'Spouse'){
array_push($responce['relationship'],['relationship' => 'Spouse','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}else if($value['relationship'] == 'Child'){
array_push($responce['relationship'], ['relationship' => 'Son','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
array_push($responce['relationship'], ['relationship' => 'Daughter','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}else if($value['relationship'] == 'Parent'){
$Father = array_search('Father',$array['existing_relationship']);
$Mother = array_search('Mother',$array['existing_relationship']);
if ($Father === false && $Mother === false) {
array_push($responce['relationship'], ['relationship' => 'Father','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
array_push($responce['relationship'], ['relationship' => 'Mother','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}else if ($Father !== false && $Mother === false) {
array_push($responce['relationship'], ['relationship' => 'Mother','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
} else if ($Mother !== false && $Father === false) {
array_push($responce['relationship'], ['relationship' => 'Father','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}
}else if($value['relationship'] == 'Parent in law'){
$FatherinLaw = array_search('Father in Law',$array['existing_relationship']);
$MotherinLaw = array_search('Mother in Law',$array['existing_relationship']);
if ($FatherinLaw === false && $MotherinLaw === false) {
array_push($responce['relationship'], ['relationship' => 'Father in Law','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
array_push($responce['relationship'], ['relationship' => 'Mother in Law','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}else if ($FatherinLaw !== false && $MotherinLaw === false) {
array_push($responce['relationship'], ['relationship' => 'Mother in Law','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
} else if ($MotherinLaw !== false && $FatherinLaw === false) {
array_push($responce['relationship'], ['relationship' => 'Father in Law','age_validation' => $value['age_validation'],'client_policy_id'=>$array['id']]);
}
}
}
$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.0;
if($array['is_premium_summery']){
$responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0.0;
$responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0.0;
}else{
$responce['family_floaters_of_dependent_and_si_premium_value'] = 0.0;
$responce['family_floaters_of_dependent_and_gst_value'] = 0.0;
}
if($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON'){
return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], 200);
// echo json_encode(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], JSON_PRETTY_PRINT | JSON_PRESERVE_ZERO_FRACTION);
}
//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;
if($array['is_premium_summery']){
$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;
}else{
$responce['family_floaters_of_only_si_premium_value'] = 0;
$responce['family_floaters_of_only_si_gst_value'] = 0;
}
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'] == 72))//OPD 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;
if($array['is_premium_summery']){
$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;
}else{
$responce['family_floaters_of_only_si_premium_value'] = 0;
$responce['family_floaters_of_only_si_gst_value'] = 0;
}
if($this->request->getGet('policy') == 'GMC-OPD'){
return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_opd'=>$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;
if($array['is_premium_summery']){
$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);
}else{
$responce['family_floaters_of_only_si_premium_value'] = 0;
$responce['family_floaters_of_only_si_gst_value'] = 0;
}
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_values(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)
{
$clientPolicyData = $this->clientPolicyModel->where('client_id',$client_id)
->where('id',$value)
->where('is_active', 1)
->first();
if(in_array($clientPolicyData['policy_type_id'], [3,4,5,72])){
$policy = $this->findThePolicyIsOpenForEnrollment($clientPolicyData['base_policy'], $emp_code);
}else{
$policy = $this->findThePolicyIsOpenForEnrollment($value, $emp_code);
}
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(array('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("info", $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("info", $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("info", $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($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'], policy_status: ['draft', 'enrolled']);
// kint::dump($existing_famility_decalculatePremiumtails);
//get the Auto SI amount
$auto_si_data = update_si_with_auto_si($client_id, $client_policy_id, $emp_code, $client_branch_id, $existing_famility_details);
log_message('error', '----- Auto SI Amount : {data} -----', ['data' => $auto_si_data]);
//Change the basic cover si to the auto si amount if the auto_si_amount is not null
if (!empty($auto_si_data)) {
foreach ($existing_famility_details as $emp_code => &$records) {
$records['basic_cover_si'] = $auto_si_data;
}
unset($record);
}
// dd($existing_famility_details);
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: $base_policy, emp_code: $emp_code, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']);
}
$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_rr(($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);
// print_r($data);
$employee_data_group_by_family[$emp_id] = $data;
foreach ($data as $value) {
if (!empty($value)) {
$newData = [];
$newData['employee_id'] = $value['temp']['emp_id'];
$newData['client_policy_id'] = $value['policy_details']['client_policy_id'];
$newData['status'] = "draft";
$newData['basic_cover_si'] = $value['policy_details']['basic_cover_si'];
$newData['date_coverage'] = $value['policy_details']['date_coverage'];
$newData['policy_end_date'] = $value['policy_details']['policy_end_date'];
$newData['days'] = $value['policy_details']['days'];
$isExistingEmpAndPolicy = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])->where('client_policy_id', $value['policy_details']['client_policy_id'])->where('is_active', 1)->get()->getRow();
if ($isExistingEmpAndPolicy) {
$this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])->where('client_policy_id', $value['policy_details']['client_policy_id'])->where('is_active', 1)->set($newData)->update();
} else {
$this->employeePolicyModel->insert($newData);
}
}
}
if (empty($clientPolicyId)) {
if (isset($policy_terms['policy_terms'])) {
$policyTermsJson = json_decode($policy_terms['policy_terms'], true);
// print_r($employee_data_group_by_family);die();
foreach ($employee_data_group_by_family[$emp_code] as $key => &$value) {
if (!empty($value)) {
if (strtolower($value['relationship']) == 'self' && $policyTermsJson['is_payable_employee']['self'] == 0) {
$value['policy_details']['rata_premimum'] = 0;
$value['policy_details']['premium'] = 0;
$value['policy_details']['gst'] = 0;
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['self'];
} else if (strtolower($value['relationship']) == 'self' && $policyTermsJson['is_payable_employee']['self'] == 1) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['self'];
}
if (strtolower($value['relationship']) == 'spouse' && $policyTermsJson['is_payable_employee']['spouse'] == 0) {
$value['policy_details']['rata_premimum'] = 0;
$value['policy_details']['premium'] = 0;
$value['policy_details']['gst'] = 0;
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['spouse'];
} else if (strtolower($value['relationship']) == 'spouse' && $policyTermsJson['is_payable_employee']['spouse'] == 1) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['spouse'];
}
if ((strtolower($value['relationship']) == 'son' || strtolower($value['relationship']) == 'daughter') && $policyTermsJson['is_payable_employee']['childern'] == 0) {
$value['policy_details']['rata_premimum'] = 0;
$value['policy_details']['premium'] = 0;
$value['policy_details']['gst'] = 0;
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['childern'];
} else if ((strtolower($value['relationship']) == 'son' || strtolower($value['relationship']) == 'daughter') && $policyTermsJson['is_payable_employee']['childern'] == 1) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['childern'];
}
if ((strtolower($value['relationship']) == 'father in law' || strtolower($value['relationship']) == 'mother in law' || strtolower($value['relationship']) == 'father' || strtolower($value['relationship']) == 'mother') && $policyTermsJson['is_payable_employee']['elders'] == 0) {
$value['policy_details']['rata_premimum'] = 0;
$value['policy_details']['premium'] = 0;
$value['policy_details']['gst'] = 0;
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['elders'];
} else if ((strtolower($value['relationship']) == 'father in law' || strtolower($value['relationship']) == 'mother in law' || strtolower($value['relationship']) == 'father' || strtolower($value['relationship']) == 'mother') && $policyTermsJson['is_payable_employee']['elders'] == 1) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['elders'];
}
} else {
unset($employee_data_group_by_family[$emp_code][$key]);
}
}
unset($value);
$employee_data_group_by_family[$emp_code] = array_values($employee_data_group_by_family[$emp_code]);
}
} else {
if (isset($policy_terms['policy_terms'])) {
$policyTermsJson = json_decode($policy_terms['policy_terms'], true);
foreach ($employee_data_group_by_family[$emp_code] as $key => &$value) {
if (!empty($value)) {
if (strtolower($value['relationship']) == 'self') {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['self'];
}
if (strtolower($value['relationship']) == 'spouse') {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['spouse'];
}
if ((strtolower($value['relationship']) == 'son' || strtolower($value['relationship']) == 'daughter')) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['childern'];
}
if ((strtolower($value['relationship']) == 'father in law' || strtolower($value['relationship']) == 'mother in law' || strtolower($value['relationship']) == 'father' || strtolower($value['relationship']) == 'mother')) {
$value['policy_details']['payable_employee'] = $policyTermsJson['is_payable_employee']['elders'];
}
} else {
unset($employee_data_group_by_family[$emp_code][$key]);
}
}
unset($value);
$employee_data_group_by_family[$emp_code] = array_values($employee_data_group_by_family[$emp_code]);
}
}
}
// die();
if ($clientPolicyId != null && $empCode != null) {
// dd ($employee_data_group_by_family);
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 : 200), 'data' => [$employee_data_group_by_family]], 200);
}
}
public function getPolicyLevelEmployeeSummaryData()
{
$hr_id = $this->request->getGet('hr_id');
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
$restAuthController = new RestAuthenticationController;
//call and get allowed policy data from post enrollment
$queryParams = [
'hr_id' => $hr_id,
'request_for' => 'pre_enrollment'
];
$HRAccessRes = $restAuthController->callThirdPartyGETAPI($queryParams,'getHRAccessData');
$HRAccessData = json_decode($HRAccessRes,true);
if(isset($HRAccessData['data']['allowed_pre_policies']))
{
$allowedPolicyIds = json_decode($HRAccessData['data']['allowed_pre_policies'],true);
}else{
$allowedPolicyIds = [];
}
if(empty($allowedPolicyIds)){
return $this->respond(['status' => 'failed','code' => 200,'data' => [] ], 200);
}
// $openEnrollmentPolicies = $this->employeePolicyModel
// ->select('employee_polices.client_policy_id')
// ->join('employees', 'employee_polices.employee_id = employees.id')
// ->whereIn('employee_polices.client_policy_id', $allowedPolicyIds)
// ->where('md5(employees.client_id)', $client_id)
// ->where('employees.client_branch_id', $client_branch_id)
// ->where('employee_polices.enrollment_open_date <= CURDATE()', null, false)
// ->where('employee_polices.enrollment_close_date >= CURDATE()', null, false)
// ->where('employee_polices.enrollment_open_date IS NOT NULL', null, false)
// ->where('employee_polices.enrollment_close_date IS NOT NULL', null, false)
// ->where('employees.is_active', 1)
// ->where('employee_polices.is_active', 1)
// ->whereIn('employee_polices.status', ['draft', 'enrolled'])
// ->whereIn('employees.emp_status', ['draft', 'enrolled'])
// ->groupBy('employee_polices.client_policy_id')
// ->findAll();
// $policyId = array_column($openEnrollmentPolicies, 'client_policy_id');
$policyId = $allowedPolicyIds;
if(empty($policyId)){
return $this->respond(['status' => 'failed','code' => 200,'data' => [] ], 200);
}
$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, DATE_FORMAT(client_policy.policy_end_date, "%d-%m-%Y") AS policy_expiry_date ')
->where('md5(client_policy.client_id)', $client_id )
->where('client_policy.client_branch_id', $client_branch_id )
->where('client_policy.is_active', 1 )
->where('client_policy.policy_status', 1)
->whereIn('client_policy.id', $policyId)
->findAll();
$loggedInCounts = [];
$clientPolicyIds = array_column($ClientPolicyData, 'client_policy_id');
if (!empty($clientPolicyIds)) {
$loggedInRows = $this->employeeModel
->select('employee_polices.client_policy_id, COUNT(DISTINCT employees.id) as logged_in_count')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->join('auth_history', 'employees.id = auth_history.user_id AND auth_history.user_type = "employee"', 'inner')
->whereIn('employee_polices.client_policy_id', $clientPolicyIds)
->where('md5(employees.client_id)', $client_id)
->where('employees.client_branch_id', $client_branch_id)
->where('employees.relationship', 'Self')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->groupBy('employee_polices.client_policy_id')
->findAll();
foreach ($loggedInRows as $loggedInRow) {
$loggedInCounts[$loggedInRow['client_policy_id']] = (int) $loggedInRow['logged_in_count'];
}
}
$result = [];
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 ?? null;
$value['policy_name'] = $policyTypeData->long_name ?? null;
$value['insurer_name'] = $insurerData->name ?? null;
$value['insurer_short_name'] = $insurerData->short_name ?? null;
$employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$client_branch_id);
$totalCount = 0;
$enrolledCount = 0;
$draftCount = 0;
if(count($employeeDetails))
{
foreach ($employeeDetails as $item) {
if ($item['relationship'] !== 'Self') {
continue;
}
$totalCount++;
if ($item['emp_status'] === 'enrolled') {
$enrolledCount++;
} elseif ($item['emp_status'] === 'draft') {
$draftCount++;
}
}
}
$value['totalMembersCount'] = $totalCount;
$value['membersCountOfEnrolled'] = $enrolledCount;
$value['membersCountOfDraft'] = $draftCount;
$value['membersCountOfLoggedIn'] = $loggedInCounts[$value['client_policy_id']] ?? 0;
array_push($result,$value);
}
if($result)
{
return $this->respond(['status' => 'success','code' => 200,'data' => $result ], 200);
}else{
return $this->respond(['status' => 'failed','code' => 200,'data' => [] ], 200);
}
}
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'))->findAll();
if(count($clientPolicy ?? []) == 0){
return $this->respond(['status' => 'failed','code' => 404, 'message' => 'Client policy not found', 'data' => [] ], 200);
}
if(in_array($clientPolicy[0]['policy_type_id'], [3,4,5,72])){
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($clientPolicy[0]['base_policy'], $this->request->getGet('emp_code'));
}else{
$openForEnrollment = $this->findThePolicyIsOpenForEnrollment($this->request->getGet('client_policy_id'), $this->request->getGet('emp_code'));
}
if($openForEnrollment)
{
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'] == 72)//OPD
{
$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(array('is_active'=> 0 , 'status' => 'truncated'))
->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(array('is_active'=> 0 ))
->update();
}
$this->employeeModel->where('emp_code', $this->request->getGet('emp_code') )
->where('is_active', 1 )->where('is_addon_value', 1 )
->set(array('is_active'=> 0 ))
->update();
}
}
return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200);
}else{
return $this->respond(['status' => 'failed', 'message' => 'Enrollment closed for this policy','code' => 404,'data' => [] ], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 200);
}
}
function getEmployeeActiveOrInactivePolicy()
{
if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
$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')
->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();
$employeeName = $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 )
->get()->getRow()->name;
$whereArrayForId = [];
foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); }
if(count($ClientPolicyData) > 0 && count($employeeData) > 0)
{
$result = [];
foreach ($ClientPolicyData as $key => $ClientPolicyValue) {
$terms = json_decode($ClientPolicyValue['policy_terms']);
if($ClientPolicyValue['policy_type_id'] == 1)
{
$data['policy_terms'] = $this->policyTermsFiter($terms,'gpa');
$data['department_id'] = 3;
}else{
$data['policy_terms'] = $this->policyTermsFiter($terms,'gmc');
$data['department_id'] = 4;
}
$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['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)'; }
if($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7)
{
$data['floter_text_heading'] = 'Sum Insured';
}else{
if($terms->family_floater == 1){ $data['floter_text_heading'] = 'Floter Sum Insured'; }else{ $data['floter_text_heading'] = '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;
array_push($result, $data);
}
}
return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'emp_name' => $employeeName ], 200);
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 200);
}
}
function policyTermsFiter($terms , $type)
{
$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{
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->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()
{
try {
$img = $this->addImgModel->where('is_active',1)->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 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($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(array('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($policy_id, $emp_code)
{
// $policy = $this->clientPolicyModel->where('id',$plicy_id)->where('open_for_enrollment',1)->find();
$policy = $this->employeePolicyModel
->join('employees', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code',$emp_code)
->where('employee_polices.client_policy_id',$policy_id)
->where('employee_polices.enrollment_open_date <= CURDATE()', null, false)
->where('employee_polices.enrollment_close_date >= CURDATE()', null, false)
->where('employee_polices.enrollment_open_date is not null')
->where('employee_polices.enrollment_close_date is not null')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->first();
if($policy)
return true;
else
return false;
}
public function getPreEmployeePolicyCountOld()
{
log_message('error', 'STEP 1: getPreEmployeePolicyCount API called');
$request = $this->request->getJSON(true);
$mobile_no = $request['mobile_number'] ?? null;
$email_id = $request['email_id'] ?? null;
$client_short_name = $request['client_short_name'] ?? null;
log_message('error', 'STEP 2: Received input - ' . json_encode($request));
// Step 3: Fetch client ID based on short name
$clientId = null;
if (!empty($client_short_name)) {
log_message('error', 'STEP 3: Looking up client with short_name: ' . $client_short_name);
$client_data = $this->clientModel
->where('is_active', 1)
->where('short_name', $client_short_name)
->first();
// $sql = "SELECT * FROM clients WHERE is_active = 1 AND short_name = ? LIMIT 1";
// $client_data = db_connect()->query($sql, [$client_short_name])->getRowArray();
if (!empty($client_data)) {
$clientId = $client_data['id'];
log_message('error', 'STEP 4: Found client ID: ' . $clientId);
} else {
log_message('error', 'STEP 4: No client found for short_name: ' . $client_short_name);
}
} else {
log_message('error', 'STEP 3: client_short_name is empty.');
}
// Step 5: Validate mobile number
if (empty($mobile_no) && empty($email_id)) {
log_message('error', 'STEP 5: Mobile number and Email is empty or null. Returning 0.');
return $this->respond(['data' => 0]);
}
try {
log_message('error', 'STEP 6: Building employee policy count query');
$builder = $this->employeeModel
->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('employees.family_floater_key', 'self')
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->where('cp.enrolment_visibility', 1)
->where('cp.open_for_enrollment', 1)
->where('cp.policy_status', 1)
->whereIn('cp.policy_type_id', [1, 2, 6, 7])
->orderBy('employees.created_at', 'desc')
->groupBy('employee_polices.client_policy_id');
if (!empty($clientId)) {
$builder->where('employees.client_id', $clientId);
log_message('error', 'STEP 7: Applied client ID filter: ' . $clientId);
} else {
log_message('error', 'STEP 7: No client ID filter applied.');
}
if (!empty($mobile_no)) {
$builder->where('employees.mobile', $mobile_no);
log_message('error', 'STEP 7: Applied mobile_no filter: ' . $mobile_no);
}
if (!empty($email_id)) {
$builder->where('employees.email_corporate', $email_id);
log_message('error', 'STEP 7: Applied email_id filter: ' . $email_id);
}
$count = $builder->get()->getNumRows();
log_message('error', 'STEP 8: Final policy count = ' . $count);
return $this->respond(['data' => $count]);
} catch (\Throwable $e) {
log_message('error', 'STEP 9: Exception occurred - ' . $e->getMessage());
return $this->respond(['data' => 0]);
}
}
public function getPreEmployeePolicyCount()
{
log_message('error', 'STEP 1: getPreEmployeePolicyCount API called');
$request = $this->request->getJSON(true);
$mobile_no = $request['mobile_number'] ?? null;
$email_id = $request['email_id'] ?? null;
$client_short_name = $request['client_short_name'] ?? null;
log_message('error', 'STEP 2: Received input - ' . json_encode($request));
/** ---------------------------------------------------------------
* STEP 3: Resolve Client ID (If client_short_name passed)
* --------------------------------------------------------------- */
$clientId = null;
if (!empty($client_short_name)) {
log_message('error', 'STEP 3: Looking up client with short_name: ' . $client_short_name);
$client = $this->clientModel
->select('id')
->where('is_active', 1)
->where('short_name', $client_short_name)
->first();
if (!empty($client)) {
$clientId = $client['id'];
log_message('error', 'STEP 4: Found client ID: ' . $clientId);
} else {
log_message('error', 'STEP 4: No client found for short_name: ' . $client_short_name);
}
} else {
log_message('error', 'STEP 3: client_short_name is empty.');
}
/** ---------------------------------------------------------------
* STEP 4: Validate Request (either mobile or email is required)
* --------------------------------------------------------------- */
if (empty($mobile_no) && empty($email_id)) {
log_message('error', 'STEP 5: Mobile number and Email both empty. Returning 0.');
return $this->respond(['data' => 0, 'empNotEnrolledCount' => 0]);
}
try {
/** ---------------------------------------------------------------
* STEP 6: Base Query Builder (extract common conditions)
* --------------------------------------------------------------- */
$baseQuery = $this->employeeModel
->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)
->where('employee_polices.is_active', 1)
->where('cp.enrolment_visibility', 1)
// ->where('cp.open_for_enrollment', 1)
->where('employee_polices.enrollment_open_date <= CURDATE()', null, false)
->where('employee_polices.enrollment_close_date >= CURDATE()', null, false)
->where('cp.policy_status', 1)
->whereIn('cp.policy_type_id', [1, 2, 3, 6, 7])
->orderBy('employees.created_at', 'desc')
->groupBy('employee_polices.client_policy_id');
// 🔹 Apply Client Filter if Provided
if (!empty($clientId)) {
$baseQuery->where('employees.client_id', $clientId);
log_message('error', 'Applied client ID filter: ' . $clientId);
}
// 🔹 Apply Mobile Filter if Provided
if (!empty($mobile_no)) {
$baseQuery->where('employees.mobile', $mobile_no);
log_message('error', 'Applied mobile_no filter: ' . $mobile_no);
}
// 🔹 Apply Email Filter if Provided
if (!empty($email_id)) {
$baseQuery->where('employees.email_corporate', $email_id);
log_message('error', 'Applied email_id filter: ' . $email_id);
}
/** ---------------------------------------------------------------
* STEP 7: Count Enrolled + Draft (eligible)
* --------------------------------------------------------------- */
$baseQuery->whereIn('employees.emp_status', ['draft', 'enrolled'])
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->where('employees.family_floater_key', 'self');
$count = $baseQuery->get()->getNumRows();
log_message('error', 'Eligible policy count = ' . $count);
/** ---------------------------------------------------------------
* STEP 8: Count Only Draft (Not Enrolled yet)
* --------------------------------------------------------------- */
$notEnrolledQuery = $this->employeeModel
->select("
(
SELECT COUNT(e2.id)
FROM employees AS e2
WHERE e2.is_active = 1
AND e2.emp_status = 'draft'
AND e2.emp_code = employees.emp_code
) AS draft_count
")
->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)
->where('employee_polices.is_active', 1)
->where('cp.enrolment_visibility', 1)
// ->where('cp.open_for_enrollment', 1)
->where('employee_polices.enrollment_open_date <= CURDATE()', null, false)
->where('employee_polices.enrollment_close_date >= CURDATE()', null, false)
->where('cp.policy_status', 1)
->whereIn('cp.policy_type_id', [1, 2, 3, 6, 7])
->orderBy('employees.created_at', 'desc');
// 🔹 Apply Client Filter if Provided
if (!empty($clientId)) {
$notEnrolledQuery->where('employees.client_id', $clientId);
log_message('error', 'Applied client ID filter: ' . $clientId);
}
// 🔹 Apply Mobile Filter if Provided
if (!empty($mobile_no)) {
$notEnrolledQuery->where('employees.mobile', $mobile_no);
log_message('error', 'Applied mobile_no filter: ' . $mobile_no);
}
// 🔹 Apply Email Filter if Provided
if (!empty($email_id)) {
$notEnrolledQuery->where('employees.email_corporate', $email_id);
log_message('error', 'Applied email_id filter: ' . $email_id);
}
$notEnrolledQuery->whereIn('employees.emp_status', ['draft'])
->whereIn('employee_polices.status', ['draft']);
$not_enrolled_count = $notEnrolledQuery->get()->getRowArray()['draft_count'] ?? 0;
log_message('error', 'Not enrolled policy count = ' . $not_enrolled_count);
/** ---------------------------------------------------------------
* STEP 9: Final Response
* --------------------------------------------------------------- */
return $this->respond([
'pre_policy_count' => $count,
'emp_not_enrolled_count' => (int) $not_enrolled_count
]);
} catch (\Throwable $e) {
log_message('error', 'Exception occurred: ' . $e->getMessage());
return $this->respond([
'pre_policy_count' => 0,
'emp_not_enrolled_count' => 0
]);
}
}
//--------------------------------------------------------------------------------------------
public function hrFileUpload()
{
try {
// Check file
$file = $this->request->getFile('file_name');
if (!$file) {
return $this->response->setJSON([
'status' => false,
'message' => "Invalid file or file not uploaded.",
'data' => "No Data"
]);
}
// Upload folder path
$uploadPath = WRITEPATH . 'uploads/hr_files/';
// If directory not exists, create it
if (!is_dir($uploadPath)) {
mkdir($uploadPath, 0777, true);
}
// New file name with timestamp
$newFileName = time() . '_' . $file->getRandomName();
// Move file
$file->move($uploadPath, $newFileName);
// Prepare data
$data = [
'client_id' => $this->request->getPost('client_id'),
'client_branch_id' => $this->request->getPost('client_branch_id'),
'policy_no' => $this->request->getPost('policy_no'),
'file_name' => $newFileName,
'file_action' => $this->request->getPost('file_action'),
'status' => $this->request->getPost('status'),
'created_by' => $this->request->getPost('created_by'),
'updated_by' => $this->request->getPost('created_by'),
];
// Save into DB
$this->hrFileUploadModel->insert($data);
return $this->respondCreated([
'status' => true,
'message' => 'File uploaded successfully',
'data' => $data
]);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function hrFileDownload($id = null)
{
try {
$file_id = $this->request->getGet('id') ?? $id;
// Find record
$record = $this->fileModel->where('id', $file_id)->first();
if (!$record) {
return $this->failNotFound("File record not found");
}
$uploadPath = WRITEPATH . 'uploads/excel/';
$filePath = $uploadPath . $record['file_name'];
if (!file_exists($filePath)) {
return $this->failNotFound("File not found on server");
}
// Force file download
return $this->response->download($filePath, null)->setFileName($record['file_name']);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function hrFileList()
{
try {
$request = service('request');
$search_data = $request->getGetPost() ?? [];
// Fetch results
$data = $this->getDataFromFilesTable($search_data);
return $this->respond([
'status' => true,
'message' => 'File list fetched successfully',
'data' => $data
]);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function hrFileListOld()
{
try {
$request = service('request');
$builder = $this->hrFileUploadModel;
// 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
$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 hrFileUploadMasters()
{
try {
//for inception upload
$data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
return $this->respond([
'status' => true,
'message' => 'File inception upload masters',
'data' => $data
]);
} catch (\Exception $e) {
return $this->failServerError($e->getMessage());
}
}
public function downloadSampleExcel()
{
$employeeController = new EmployeeController();
$file_path = $employeeController->downloadSampleExcelFile('enrollment', 1);
if(empty($file_path)){
return $this->respond(['status' => "success", 'code' => 404, 'data' => "", "message" => "Sample file not avilable"], 200);
}else{
return $this->respond(['status' => "success", 'code' => 200, 'data' => $file_path], 200);
}
}
// copy the active enrolled employee data
public function copyActiveEmployeeAndDependentDetails()
{
$received_payload = $this->request->getGet();
$client_id = $received_payload['client_id'] ?? null;
$emp_code = $received_payload['emp_code'] ?? null;
$new_client_policy_id = $received_payload['new_client_policy_id'] ?? null;
if (empty($client_id)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "client_id is required"], 200);
}
if (empty($new_client_policy_id)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "client_policy_id is required"], 200);
}
if (empty($emp_code)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "emp_code is required"], 200);
}
$client_policy_data = $this->clientPolicyModel
->where('is_active', 1)
->where('client_id', $client_id)
->where('id', $new_client_policy_id)
->whereIn('policy_type_id', [2, 3, 4, 5])
->first();
if (empty($client_policy_data)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "Policy data not found", 'data' => []], 200);
}
$policy_terms = $client_policy_data['policy_terms'] ?? null;
if (empty($policy_terms)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "Policy terms not found", 'data' => []], 200);
}
$policy_terms = json_decode($policy_terms, true);
$family_floaters = $policy_terms['family_floaters'];
$empData = $this->employeeModel
->where('emp_code', $emp_code)
->where('client_id', $client_id)
// ->where('emp_status', 'enrolled')
->where('is_active', 1)
->findAll();
if (empty($empData)) {
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "employee data not found", 'data' => []], 200);
}
$selfData = array_column(
array_filter($empData, function($row) {
return isset($row['relationship']) && strtolower($row['relationship']) == 'self';
}),
'id'
);
$selfId = !empty($selfData) ? reset($selfData) : null;
$floters = $this->FloterConvertion($family_floaters);
$data = [];
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', $selfId)->where('client_policy_id',$new_client_policy_id)->where('is_active', 1 )->get()->getRow();
$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'] = $new_client_policy_id;
$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($policy_terms, $familyFloatesValue);
array_push($data, $temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
if(!empty($data)){
return $this->respond(['status' => "success", 'code' => 200, 'data' => $data], 200);
}else{
return $this->respond(['status' => "failed", 'code' => 404, 'message' => "No data found", 'data' => []], 200);
}
}
public function getEnrollmentDates($client_policy_id, $emp_code)
{
$enrollment_open_date = null;
$enrollment_close_date = null;
$clientPolicyData = $this->clientPolicyModel->where('id', $client_policy_id)
->where('is_active', 1)
->first();
if(in_array($clientPolicyData['policy_type_id'] ?? null, [3,4,5,72])){
$policy = $this->employeePolicyModel
->select('employee_polices.enrollment_open_date, employee_polices.enrollment_close_date')
->join('employees', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code',$emp_code)
->where('employee_polices.client_policy_id', $clientPolicyData['base_policy'])
->where('employee_polices.enrollment_open_date <= CURDATE()', null, false)
->where('employee_polices.enrollment_close_date >= CURDATE()', null, false)
->where('employee_polices.enrollment_open_date is not null')
->where('employee_polices.enrollment_close_date is not null')
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->first();
$enrollment_open_date = $policy['enrollment_open_date'] ?? null;
$enrollment_close_date = $policy['enrollment_close_date'] ?? null;
}
return [
'enrollment_open_date' => $enrollment_open_date,
'enrollment_close_date' => $enrollment_close_date,
];
}
public function getEmployeeAddOnPolicies($emp_code, $client_id, $client_branch_id): array
{
$data = $this->employeeModel
->select("
client_policy.id AS gmc_client_policy_id,
(
SELECT id FROM client_policy
WHERE policy_type_id = 3
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS gmc_parent_policy_id,
(
SELECT id FROM client_policy
WHERE policy_type_id = 4
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS gmc_topup_policy_id,
(
SELECT id FROM client_policy
WHERE policy_type_id = 72
AND base_policy = gmc_client_policy_id AND is_active = 1
LIMIT 1
) AS opd_topup_policy_id
")
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id')
->whereIn('employees.emp_status', ['draft', 'enrolled'])
->whereIn('employee_polices.status', ['draft', 'enrolled'])
->where([
'employees.is_active' => 1,
'employee_polices.is_active' => 1,
'client_policy.is_active' => 1,
'client_policy.policy_type_id' => 2,
'employees.family_floater_key' => 'self',
'employees.emp_code' => $emp_code ?? null,
'employees.client_id' => $client_id ?? null,
'employees.client_branch_id' => $client_branch_id ?? null,
])
->orderBy('employee_polices.id', 'desc')
->first();
// dd($data);
// dd(db_connect()->getLastQuery());
if (!empty($data) && !empty($data['gmc_parent_policy_id'])) {
$getParentTopUp = $this->clientPolicyModel
->select('id AS gmc_parent_topup_policy_id')
->where('is_active', 1)
->where('policy_type_id', 5) // parent Top-Up
->where('base_policy', $data['gmc_parent_policy_id'])
->first();
}
if (empty($data)) {
return [];
}
$policyIds[] = $data['gmc_topup_policy_id'];
$policyIds[] = $data['gmc_parent_policy_id'];
$policyIds[] = $data['opd_topup_policy_id'] ?? null;
$policyIds[] = $getParentTopUp['gmc_parent_topup_policy_id'] ?? null;
return $policyIds;
}
public function getReminderMailConfig()
{
try {
$clientPolicyId = $this->request->getGet('client_policy_id');
$is_email_template = $this->request->getGet('is_email_template') ?? false;
if (empty($clientPolicyId)) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'client_policy_id is required',
], 200);
}
$clientPolicy = $this->clientPolicyModel->find($clientPolicyId);
if (empty($clientPolicy)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Client policy not found',
], 200);
}
$config = $this->reminderMailConfigModel->getByClientPolicyId((int) $clientPolicyId);
if ($is_email_template) {
$placeHolders = ['member_name', 'nhance_logo', 'client_logo', 'policy_no', 'app_link', 'client_name', 'enrollment_open_date', 'enrollment_close_date'];
if (empty($config) || empty($config['email_subject'] ?? null) || empty($config['email_body'] ?? null)) {
$notification = $this->notificationModel->where('client_id', $clientPolicy['client_id'])->where('template_name', 'member_reminder_mail')->first();
if (empty($notification)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Member reminder mail notification not found',
], 200);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => ['email_subject' => $notification['subject'], 'email_body' => $notification['mail_content']]], 200);
}
return $this->respond([
'status' => true,
'code' => 200,
'data' => ['email_subject' => $config['email_subject'], 'email_body' => $config['email_body'], 'place_holders' => $placeHolders],
], 200);
}
if (empty($config) && !empty($clientPolicy['reminder_date'])) {
$config = [
'client_policy_id' => (int) $clientPolicyId,
'frequency' => ReminderMailConfigModel::FREQUENCY_CUSTOM,
'reminder_days' => $clientPolicy['reminder_date'],
'is_enabled' => 1,
'is_active' => 1,
'source' => 'legacy_client_policy',
];
}
if (!empty($config)) {
$config = $this->reminderMailConfigModel->enrichConfig($config);
}
return $this->respond([
'status' => true,
'code' => 200,
'data' => $config,
'working_day_options' => $this->reminderMailConfigModel->getWorkingDayOptions(),
], 200);
} catch (\Exception $e) {
return $this->respond([
'status' => false,
'code' => 500,
'message' => $e->getMessage(),
], 500);
}
}
public function saveReminderMailConfig()
{
try {
$requestData = $this->getReminderMailConfigRequestData();
$clientPolicyId = $requestData['client_policy_id'] ?? null;
$configId = $requestData['id'] ?? null;
$frequency = strtolower(trim((string) ($requestData['frequency'] ?? '')));
$reminderDays = $requestData['reminder_days']
?? $requestData['working_days']
?? null;
$isEnabled = $requestData['is_enabled'] ?? null;
$hrId = $requestData['hr_id'] ?? null;
$emailSubject = $requestData['email_subject'] ?? null;
$emailBody = $requestData['email_body'] ?? null;
if (empty($clientPolicyId)) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'client_policy_id is required',
], 200);
}
if (empty($frequency)) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'frequency is required',
], 200);
}
$clientPolicy = $this->clientPolicyModel->find($clientPolicyId);
if (empty($clientPolicy)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Client policy not found',
], 200);
}
$saveOptions = [
'id' => $configId !== null && $configId !== '' ? (int) $configId : null,
'hr_id' => $hrId !== null && $hrId !== '' ? (int) $hrId : null,
];
if (array_key_exists('email_subject', $requestData)) {
$saveOptions['email_subject'] = $emailSubject;
}
if (array_key_exists('email_body', $requestData)) {
$saveOptions['email_body'] = $emailBody;
}
$result = $this->reminderMailConfigModel->saveConfig(
(int) $clientPolicyId,
$frequency,
$reminderDays !== null ? (string) $reminderDays : null,
$isEnabled === null ? 1 : (int) $isEnabled,
$saveOptions
);
if (!$result['status']) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => $result['message'],
], 200);
}
return $this->respond([
'status' => true,
'code' => 200,
'action' => $result['action'] ?? 'saved',
'message' => 'Reminder mail configuration saved successfully',
'data' => $result['data'],
], 200);
} catch (\Exception $e) {
return $this->respond([
'status' => false,
'code' => 500,
'message' => $e->getMessage(),
], 500);
}
}
private function getReminderMailConfigRequestData(): array
{
$json = $this->request->getJSON(true);
if (is_array($json) && !empty($json)) {
return $json;
}
return array_filter([
'id' => $this->request->getVar('id'),
'client_policy_id' => $this->request->getVar('client_policy_id'),
'frequency' => $this->request->getVar('frequency'),
'reminder_days' => $this->request->getVar('reminder_days'),
'working_days' => $this->request->getVar('working_days'),
'email_subject' => $this->request->getVar('email_subject'),
'email_body' => $this->request->getVar('email_body'),
'is_enabled' => $this->request->getVar('is_enabled'),
'hr_id' => $this->request->getVar('hr_id'),
], static fn ($value) => $value !== null && $value !== '');
}
public function sendReminderMail()
{
try {
if (!$this->request->is('post')) {
return $this->respond([
'status' => false,
'code' => 405,
'message' => 'Only POST method is allowed',
], 200);
}
try {
$requestData = $this->request->getJSON(true);
} catch (\CodeIgniter\HTTP\Exceptions\HTTPException $e) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'Invalid JSON request body',
], 200);
}
if (!is_array($requestData) || empty($requestData)) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'JSON request body is required',
], 200);
}
$clientPolicyId = $requestData['client_policy_id'] ?? null;
if (empty($clientPolicyId)) {
return $this->respond([
'status' => false,
'code' => 400,
'message' => 'client_policy_id is required',
], 200);
}
$clientPolicy = $this->clientPolicyModel->find($clientPolicyId);
if (empty($clientPolicy)) {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Client policy not found',
], 200);
}
$emailSubject = $requestData['email_subject'] ?? null;
$emailBody = $requestData['email_body'] ?? null;
$hrId = $requestData['hr_id'] ?? null;
if (array_key_exists('email_subject', $requestData) || array_key_exists('email_body', $requestData)) {
$this->reminderMailConfigModel->saveEmailTemplate(
(int) $clientPolicyId,
$emailSubject,
$emailBody,
$hrId !== null && $hrId !== '' ? (int) $hrId : null
);
}
return $this->dispatchManualReminder(
$clientPolicy['client_id'],
$clientPolicy['client_branch_id'],
$clientPolicyId
);
} catch (\Exception $e) {
return $this->respond([
'status' => false,
'code' => 500,
'message' => $e->getMessage(),
], 500);
}
}
protected function dispatchManualReminder($clientId, $clientBranchId, $clientPolicyId)
{
$dashboardController = new DashboardController();
$dashboardController->initController($this->request, $this->response, $this->logger);
return $dashboardController->sendManualReminder(
$clientId,
$clientBranchId,
$clientPolicyId
);
}
}