nhance/app/Controllers/EmployeeRestController.php

2550 lines
123 KiB
PHP
Executable File
Raw Blame History

<?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\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\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;
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();
}
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();
$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],404);
}
} 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],404);
}
}
} 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' => []],404);
}
} 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], 404);
}
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e], 500);
}
}
public function addEmployeeAndDependence()
{
// try {
$data = $this->request->getJSON();
if ($data) {
$Count = 0;
foreach ($data as $item) {
if (isset($item->id)) {
//update old data
$id = $item->id;
$item->family_floater_key = $this->RelationshipMap($item->relationship);
$item->gender = $this->GenderMap($item->relationship , $item->emp_code);
$item->dob = $this->convertDateFormatYMD($item->dob);
$item->emp_status = 'draft';
$employee = $this->employeeModel->where('is_active', 1 )->update($id, (array)$item);
if ($employee) {
$Count++;
}
}else{
//create new data
$item->family_floater_key = $this->RelationshipMap($item->relationship);
$item->gender = $this->GenderMap($item->relationship , $item->emp_code);
$item->dob = $this->convertDateFormatYMD($item->dob);
$item->emp_status = 'draft';
$employee = $this->employeeModel->insert($item);
if ($employee) {
$Count++;
}
}
}
if ($Count > 0) {
if(isset($data[0]->id))
{
if(!isset($data[0]->is_addon_value))
{
$this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id);
}else{
$this->createEmployeePolicyData($data[0]->id , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si);
}
}else{
if(!isset($data[0]->is_addon_value))
{
$this->createEmployeePolicyData($employee , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id);
}else{
$this->createEmployeePolicyData($employee , $data[0]->emp_code , $data[0]->client_id , $data[0]->client_policy_id , $data[0]->basic_cover_si);
}
}
$this->updatePremiumAmount($data[0]->client_policy_id , $data[0]->emp_code , $data[0]->client_branch_id);
$result = [];
return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404);
}
}
// } catch (\Exception $e) {
// return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
// }
}
public function createEmployeePolicyData($employee_id,$emp_code,$client_id,$client_policy_id,$basic_cover_si = null)
{
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;
}
$checkDataExist = $this->employeePolicyModel->where('employee_id',$employee_id)->where('client_policy_id',$client_policy_id)->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{
$data['employee_id']= $employee_id;
$data['client_policy_id']= $client_policy_id;
$data['basic_cover_si']= $basic_cover_si;
$data['status']= 'draft';
$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('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum'] , 'gst'=> $value['policy_details']['gst'] ))
->update();
}
}
}
}
}
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;
}
}
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'))
{
$this->employeeModel->where('id', $this->request->getGet('id') )
->where('is_active', 1 )
->set(array('is_active'=> 0 ))
->update();
$this->employeePolicyModel->where('employee_id',$this->request->getGet('id') )
->where('is_active', 1 )
->set(array('is_active'=> 0 ))
->update();
return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200);
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
// Get the RelationShip list
public function createOrUpdateEmployeePolicySiAmount()
{
try {
$requestData = $this->request->getJSON();
foreach ($requestData as $key => $value) {
$checkIfExist = $this->employeePolicyModel->where('employee_id', $value->employee_id)
->where('client_policy_id', $value->client_policy_id)
->where('is_active', 1 )
->findAll();
if ($checkIfExist) {
$empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si);
}else{
$data['employee_id']= $value->employee_id;
$data['client_policy_id']= $value->client_policy_id;
$data['basic_cover_si']= $value->basic_cover_si;
$data['status'] = 'draft';
$this->employeePolicyModel->insert($data);
}
}
$this->updatePremiumAmount($requestData[0]->client_policy_id , $requestData[0]->emp_code);
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 {
$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 ($empData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function exportDataByClientPolicyId()
{
try {
$empData = $this->employeePolicyModel->getEmployeePolicy( client_id:$this->request->getGet('client_id'),policy_id: $this->request->getGet('client_policy_id'),status:0,branch_id:$this->request->getGet('client_branch_id'));
if(count($empData))
{
// Define headers and map database fields to Excel fields
$headers = [
'Employee Code' => 'emp_code',
'Name' => 'name',
'Relationship' => 'relationship',
'DOB' => 'dob',
'Gender' => 'gender',
'Mobile' => 'mobile',
'Email' => 'email_corporate',
'SI' => 'basic_cover_si',
'Premium' => 'rata_premimum',
'Policy Name' => 'policy_name',
'Insurer Branch Name' => 'insurer_branch_name',
'TPA Name' => 'tpa_name',
'Status' => 'emp_status'
];
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Add headers
$column = 'A';
foreach ($headers as $header => $dbField) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Add data
$row = 2;
foreach ($empData as $employee) {
$column = 'A';
foreach ($headers as $dbField) {
$sheet->setCellValue($column . $row, $employee[$dbField]);
$column++;
}
$row++;
}
// Set the header for download
$filename = $empData[0]['policy_name'].'-Enrolment.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// Save the Excel file to output
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200);
}else{
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
//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' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
// Upload the Employee Detail in DB by Sheet Data
public function employeeUpload()
{
try {
$file = $this->request->getFile('file');
$client_id = $this->request->getPost('client_id');
$client_branch_id = $this->request->getPost('client_branch_id');
$policy_id = $this->request->getPost('policy_id');
$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->getHeader('Authorization');
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[2];
$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' => 'draft', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master
$this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]);
$empServiceController = new EmployeeServiceController();
$result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
if(isset($result['error_summary']) && count($result['error_summary']))
{
$result = $empServiceController->getExcelErrorData($file_id);
return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "file upload failed with errors",'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
];
$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;
for ($a=0; $a <count($dataToInsert) ; $a++)
{
$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']));
}
}
}
$emp_policy_data =[
'employee_id'=>$emp_id,
'client_policy_id'=>$policy_id,
'status'=> 'draft',
'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null
];
$employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]);
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);
}
} else {
$emp_policy = $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;
$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') {
}
}
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!" ], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
//-------------------------------------
public function getAgeRange($terms,$familyFloatesValue)
{
$ageRangeArray = ['self' => ['min' => 18, 'max' => 60] , 'spouse' => ['min' => 18, 'max' => 60] , 'child' => ['min' => 0, 'max' => 25] , 'elders' => ['min' => 18, 'max' => 60] ];
$ageKey = (preg_replace('/\d/', '', $familyFloatesValue) == 'parent' || preg_replace('/\d/', '', $familyFloatesValue) == 'parent_in_law') ? 'elders' : preg_replace('/\d/', '', $familyFloatesValue);
if(isset($terms->age_ratio)){
return $terms->age_ratio->$ageKey;
}else{
return $ageRangeArray[$ageKey];
}
}
public function getEmployeePolicy()
{
try {
$id = $this->request->getGet('id');
$emp_code = $this->request->getGet('emp_code');
$client_id = $this->request->getGet('client_id');
$client_branch_id = $this->request->getGet('client_branch_id');
// 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);
// Retrieve employee and dependents data by passing the employee code
$employeeData = $this->employeeModel->where('emp_code',$emp_code)
->where('client_id',$client_id)
->where('client_branch_id',$client_branch_id)
->where('is_active', 1 )
->where('is_addon_value',0)->findAll();
if ($empPolicy) {
$result = [];
foreach ($empPolicy as $array) {
// Reset employee array
$empData = $employeeData;
// Removes specific keys from the decoded array and assigns the result to $refusingData
$decodedArray = json_decode($array->Policy_Terms);
$refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove));
$array->Policy_Terms = $refusingData;
// Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
if($array->tpa_id != null){
$array->eCardDownload = base_url('download-e-card/') . $array->rand_string;
}else{ $array->eCardDownload = null; }
// Construct value for policy type GPA
if($getSlabAndGridData['grid_master']['policy_type'] == "GPA" && $this->request->getGet('policy') == 'GPA'){
// 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();
$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'] = $employee_policy->basic_cover_si;
$array->mapped_family_floaters = $self;
$array->type = 'GPA';
$res = [];
array_push($res,$array);
$EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData,6,$emp_code,$client_id,$client_branch_id);
if($EDLIPolicy){ array_push($res,$EDLIPolicy); }
$GTLIPolicy = $this->getAdditionalGPAPolicy($employeeData,7,$emp_code,$client_id,$client_branch_id);
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
}else if($getSlabAndGridData['grid_master']['policy_type'] == "GMC" && $this->request->getGet('policy') == 'GMC' ){
// Map family floaters that already exist in the employee table
$familyFloates = $array->Policy_Terms->family_floaters;
// Generate Notes string based on familyFloates terms
$array->notes = $this->FloterNotesConvertion($familyFloates);
if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1)
{
$array->floter_text_heading = 'Floater Sum Insured';
$array->floter_text_description = 'This is a floater sum insured. A floater is a type of sum insured that provides coverage to more than one member ot a family at the same time. Simply put, its a single insurance cover for the entire family.';
}else{
$array->floter_text_heading = 'Sum Insured';
$array->floter_text_description = '';
}
// remove parent and parent-in-law from familyFloaters
if($familyFloates->{'either-parents-pil'} != 0){
unset($familyFloates->parents);
unset($familyFloates->parents_in_law);
}
$floters = $this->FloterConvertion($familyFloates);
$data = [];
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();
$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'] = $employee_policy->basic_cover_si;
$temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue);
array_push($data,$temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
// Remove Unwanted floter key from floters array based on either-parents-pil term value
if($familyFloates->{'either-parents-pil'} == 1 && count($floters))
{
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; }
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;}
}
if($count_parent != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false);
}
if($count_parent_in_law != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false);
}
}
else if($familyFloates->{'either-parents-pil'} == 2 && count($floters))
{
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; }
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;}
}
if(($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
// Add family floter buttons placement data for FE validation
if(count($floters)){
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array->ClientPolicyId;
$temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue);
array_push($data,$temp2);
}
}
$array->mapped_family_floaters = $data;
$array->type = "GMC";
$checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('client_policy.policy_type_id', 3 )
->where('client_policy.is_addon', 1 )
->where('client_policy.client_id', $this->request->getGet('client_id') )
->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') )
->where('client_policy.is_active', 1 )
->get()
->getResult();
if($checkGmcParentsPolicyExist)
{
$GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist,$emp_code,$client_id,$client_branch_id);
return $this->respond(['status' => 'success','code' => 200,'data' => [$array,$GmcParrentsData]], 200);
}
if($this->request->getGet('policy') == 'GMC'){
return $this->respond(['status' => 'success','code' => 200,'data' => [$array]], 200);
}
}
// $result[] = $array;
}
return $this->respond(['status' => 'success','code' => 200,'data' => []], 200);
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function getGmcParrentsPolicy($GmcParrentsPolicy,$emp_code,$client_id,$client_branch_id)
{
$employeeData = $this->employeeModel->where('emp_code',$emp_code)
->where('client_id',$client_id)
->where('client_branch_id',$client_branch_id)
->where('is_active', 1 )
->where('is_addon_value',0)->findAll();
// return $employeeData;
foreach ($GmcParrentsPolicy as $key => $array) {
// Reset employee array
$empData = $employeeData;
$array->Policy_Terms = json_decode($array->Policy_Terms);
// Retrieve slab rate and grid master data by passing the ClientPolicyId and ClientId
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
$tpaArray = $this->employeeModel->select('employees.name as name , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string')
->join('employee_polices', 'employee_polices.employee_id = employees.id')
->where('employees.emp_code',$emp_code)
->where('employees.is_active',1)
->where('employee_polices.client_policy_id',$array->ClientPolicyId)
->get()
->getResult();
if(count($tpaArray))
{
if($tpaArray[0]->tpa_id != null)
$array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string;
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)
{
$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 = [];
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();
// dd( $employee_policy);
$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'] = $employee_policy->basic_cover_si;
$temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue);
array_push($data,$temp);
unset($empData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
// Remove Unwanted floter key from floters array based on either-parents-pil term value
if($familyFloates->{'either-parents-pil'} == 1 && count($floters))
{
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; }
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;}
}
if($count_parent != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent_in_law') === false);
}
if($count_parent_in_law != 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false || strpos($value, 'parent_in_law') !== false);
}
}
else if($familyFloates->{'either-parents-pil'} == 2 && count($floters))
{
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; }
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;}
}
if(($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
// Add family floter buttons placement data for FE validation
if(count($floters)){
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array->ClientPolicyId;
$temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms,$familyFloatesValue);
array_push($data,$temp2);
}
}
$array->mapped_family_floaters = $data;
$array->type = "GMC - Parents";
return $array;
}
}
public function getAdditionalGPAPolicy($empData,$policy_type,$emp_code,$client_id,$client_branch_id)
{
$checkPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms , client_policy.enrolment_visibility')
->where('client_policy.policy_type_id', $policy_type )
->where('client_policy.is_addon', 1 )
->where('client_policy.client_id', $client_id )
->where('client_policy.client_branch_id', $client_branch_id )
->where('client_policy.is_active', 1 )
->get()
->getResult();
if($checkPolicyExist){
foreach ($checkPolicyExist as $key => $array) {
$decodedArray = json_decode($array->Policy_Terms);
$array->Policy_Terms = $decodedArray;
// 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();
$policyTypeData = $this->policyTypeModel->where('id',$policy_type)->get()->getRow();
$array->type = $policyTypeData->policy_type;
$array->Policy_Name = $policyTypeData->long_name;
if($employee_policy){
if($employee_policy->tpa_id != null){
$array->eCardDownload = base_url('download-e-card/') . $employee_policy->rand_string;
}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'] = $employee_policy->basic_cover_si;
$array->mapped_family_floaters = $self;
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') {
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 = 'Can Add 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 "Can Add ".$modified_string;
}else{
return $result;
}
return substr($result, 0, 2) !== " +";
}
public function getClientDetails()
{
try {
$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{
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function getAddOnPolicy()
{
try {
$addOnEmployeeData = $this->employeeModel->where('is_active', 1 )
->where('emp_code',$this->request->getGet('emp_code'))
->where('client_id',$this->request->getGet('client_id'))
->where('client_branch_id',$this->request->getGet('client_branch_id'))
->where('is_addon_value',1)->findAll();
$clientPolicy = $this->clientPolicyModel->where('client_id',$this->request->getGet('client_id'))
->where('client_branch_id',$this->request->getGet('client_branch_id'))
->where('policy_status', 1)
->findAll();
if(count($clientPolicy))
{
$band = $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('family_floater_key','self')->get()->getRow()->band;
$PolicyData = [];
foreach ($clientPolicy as $key => $array) {
$responce = [];
$decodedArray = json_decode($array['policy_terms']);
$policy_terms = $decodedArray;
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'],$array['client_id']);
$uniqueData = [];
$siValues = [];
foreach ($getSlabAndGridData['slab_rates'] as $item) {
if($getSlabAndGridData['grid_master']['emp_band'] == 1 ){
if ($item['grade'] == $band) {
$uniqueData[] = $item;
}
}else{
if (!in_array($item['si'], $siValues) ) {
if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) {
$uniqueData[] = $item;
$siValues[] = $item['si'];
}else if($item['policy_grid_id'] != 11){
$uniqueData[] = $item;
$siValues[] = $item['si'];
}
}
}
}
$policyTypeData = $this->policyTypeModel->where('id',$array['policy_type_id'])->get()->getRow();
$responce['policy_name'] = $policyTypeData->long_name;
$responce['type'] = $policyTypeData->policy_type;
$responce['SlabRates'] = $uniqueData;
$responce['GridMaster'] = $getSlabAndGridData['grid_master'];
$responce['client_id'] = $array['client_id'];
$responce['client_policy_id'] = $array['id'];
$responce['is_addon'] = $array['is_addon'];
$responce['OpenForEnrollment'] = $array['open_for_enrollment'];
$responce['policy_terms'] = $decodedArray;
$responce['policy_type_id'] = $array['policy_type_id'];
$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;
else
$responce['eCardDownload'] = null;
}else{
$responce['eCardDownload'] = null;
}
if(count($getSlabAndGridData['slab_rates'])){
if($getSlabAndGridData['slab_rates'][0]['premium_type'] == 1)
{
$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
{
// 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 = $employee_policy->basic_cover_si; }
if(isset($employee_policy->premium)){ $dependent_and_si_premium_value = $dependent_and_si_premium_value + $employee_policy->premium;}
if(isset($employee_policy->gst)){ $dependent_and_si_gst_value = $dependent_and_si_gst_value + $employee_policy->gst;}
$temp['is_value_exist'] = true;
$temp['data']['family_floater_key'] = $familyFloatesValue;
$temp['data']['employee_id'] = $value['id'];
$temp['data']['relationship'] = $value['relationship'];
$temp['data']['name'] = $value['name'];
$temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp['data']['client_policy_id'] = $array['id'];
$temp['data']['form_type'] = $dependent;
$temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
$temp['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue);
array_push($data,$temp);
unset($addOnEmployeeData[$key]);
$floters = array_diff($floters, [$familyFloatesValue]);
break;
}
}
}
}
//Remove Unwanted floter key from floters array based on either-parents-pil term value
if($familyFloates->{'either-parents-pil'} == 1 && count($floters))
{
if(count($addOnEmployeeData) == 0)
{
$GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
->where('is_addon_value',0)
->where('is_active', 1 )
->where('family_floater_key','parent')
->findAll();
if(count($GMCEmpData) > 0){
$floters = array_diff($floters, ["parent1","parent2"]);
}else{
$floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]);
}
}else{
$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))
{
if(count($addOnEmployeeData) == 0)
{
$GMCEmpData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
->where('is_addon_value',0)
->where('is_active', 1 )
->where('family_floater_key','parent')
->findAll();
if(count($GMCEmpData) > 0){
$floters = array_diff($floters, ["parent1","parent2"]);
}else{
$floters = array_diff($floters, ["parent_in_law1","parent_in_law2"]);
}
}else{
$count_parent = 0;
$count_parent_in_law = 0;
foreach ($floters as $value) {
if (preg_replace('/\d/', '', $value) == 'parent') { $count_parent++; }
if (preg_replace('/\d/', '', $value) == 'parent_in_law') {$count_parent_in_law++;}
}
if(($count_parent + $count_parent_in_law) == 2) {
$floters = array_filter($floters, fn($value) => strpos($value, 'parent') === false);
}
}
}
// Add family floter buttons placement data for FE validation
if(count($floters)){
foreach ($floters as $familyFloatesValue) {
$temp2['is_value_exist'] = false;
$temp2['data']['family_floater_key'] = $familyFloatesValue;
$temp2['data']['client_policy_id'] = $array['id'];
$temp2['data']['button_name'] = 'Add '.ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue)));
$temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue);
$temp2['data']['age_validation'] = $this->getAgeRange($decodedArray,$familyFloatesValue);
array_push($data,$temp2);
}
}
$responce['family_floaters_of_dependent_and_si_array'] = $data;
$responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value;
$responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value;
$responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value;
if($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON'){
return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_dependent_addon'=>$responce]], 200);
}
//array_push($PolicyData, $responce);
}else if($array['is_addon'] == 2 && $array['policy_type_id'] == 4)//Topup policy
{
$whereArray = [];
foreach ( $decodedArray->family_floaters as $key => $value) {
if($value != 0){
if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; }
array_push($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 = $employee_policy->basic_cover_si; }
if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;}
if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;}
$temp3['is_value_exist'] = true;
$temp3['data']['employee_id'] = $value['id'];
$temp3['data']['relationship'] = $value['relationship'];
$temp3['data']['name'] = $value['name'];
$temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp3['data']['client_policy_id'] = $array['id'];
$temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
array_push($only_si_array,$temp3);
}
$responce['family_floaters_of_only_si_array'] = $only_si_array;
$responce['family_floaters_of_only_si_value'] = $only_si_value;
$responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value;
$responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value;
if($this->request->getGet('policy') == 'GMC-SI-TOPUP'){
return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_topup'=>$responce]], 200);
}
}else if($array['is_addon'] == 2 && $array['policy_type_id'] == 5)//Parents Topup policy
{
$whereArray = [];
foreach ( $decodedArray->family_floaters as $key => $value) {
if($value != 0){
if($key == 'parents'){ $text = 'parent'; }else if($key == 'childrens'){ $text = 'child'; }else if($key == 'parents-in-law'){$text = 'parent_in_law';}else{ $text = $key; }
array_push($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 = $employee_policy->basic_cover_si; }
if(isset($employee_policy->premium)){ $only_si_premium_value = $only_si_premium_value + $employee_policy->rata_premimum;}
if(isset($employee_policy->gst)){ $only_si_gst_value = $only_si_gst_value + $employee_policy->gst;}
$temp3['is_value_exist'] = true;
$temp3['data']['employee_id'] = $value['id'];
$temp3['data']['relationship'] = $value['relationship'];
$temp3['data']['name'] = $value['name'];
$temp3['data']['dob'] = $this->convertDateFormatDMY($value['dob']);
$temp3['data']['client_policy_id'] = $array['id'];
$temp3['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : null;
$temp3['data']['premium'] = isset($employee_policy->premium) ? $employee_policy->premium : null;
array_push($only_si_array,$temp3);
}
$responce['family_floaters_of_only_si_array'] = $only_si_array;
$responce['family_floaters_of_only_si_value'] = $only_si_value;
$responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value;
$responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value;
if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){
return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_parent_topup'=>$responce]], 200);
}
}
}
return $this->respond(['status' => 'success','code' => 200,'data' => []], 200);
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function iAgreeForAddOn()
{
$postData = json_decode($this->request->getBody(), true);
$client_policy_id = $postData['client_policy_id'];
sort($client_policy_id);
// Alternatively, you can use echo to see the type
$emp_code = $postData['emp_code'];
$client_id = $postData['client_id'];
$this->employeeModel->where('emp_code', $emp_code )
->where('client_id', $client_id )
->where('is_active', 1 )
->set(array('emp_status'=>'enrolled'))
->update();
$empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll();
if (!is_null($client_policy_id) && is_array($client_policy_id))
{
$array_list = [];
foreach ($client_policy_id as $key => $value)
{
foreach ($empData as $empDataKey => $empDataValue)
{
$this->employeePolicyModel->where('client_policy_id', $value )
->where('is_active', 1 )
->where('employee_id', $empDataValue['id'] )
->set(array('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;
}
}
$notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first();
if (isset($notification) && $notification['enabled'] == 1) {
$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;
// 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])) {
$account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params);
if ($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');
}
$client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params);
if ($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
{
helper('excel_util_helper');
$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;
// 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']);
if(!count($existing_famility_details) && $policy_type == 2)//top up addon only
{
//get basepolicy id then pull emplist from base policy if only current policy is DA addon policy and emplist is zero
// echo 'inside';
$client_policy_id = $base_policy;
$existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_code: $emp_code,emp_status:['draft','enrolled'],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_r(($employee_data_group_by_family));//die();
$existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $client_branch_id);
foreach ($employee_data_group_by_family as $emp_id => $family)
{
$transformed_famility_details = transform_db_data_to_excel($family);
$data = calculate_premium_new(family_data: $transformed_famility_details,policy_terms:$policy_terms,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units,default_si : $default_si);
$employee_data_group_by_family[$emp_id] = $data;
}
if($clientPolicyId != null && $empCode != null)
{
return $employee_data_group_by_family;
}else{
// dd ($employee_data_group_by_family);
return $this->respond(['status' => 'success','code' => (count($employee_data_group_by_family) ? 200 : 404),'data' => [$employee_data_group_by_family] ], 200);
}
}
public function getCashDepositData()
{
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.client_id as clientId , client_policy.insurer_id as insurerId,insurers.name as insurer_name')
->join('insurers', 'client_policy.insurer_id = insurers.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', 1)
->groupBy('client_policy.insurer_id')
->findAll();
$result = [];
if(count($ClientPolicyData))
{
foreach ($ClientPolicyData as $key => $value) {
$data['clientId'] = $value['clientId'];
$data['insurerId'] = $value['insurerId'];
$data['insurerName'] = $value['insurer_name'];
$data['depositData'] = $this->clientPolicyModel->getdepositData($value['clientId'],$value['insurerId']);
$data['balance'] = count($data['depositData']) ? $data['depositData'][0]->balance : 0;
$data['policyDetails'] = [];
$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 ')
->where('client_policy.insurer_id', $value['insurerId'] )
->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', 1)
->findAll();
// dd( $ClientPolicyData);
foreach ($ClientPolicyData as $key => $value)
{
$policyTypeData = $this->policyTypeModel->where('id',$value['policy_type_id'])->get()->getRow();
$value['type'] = $policyTypeData->policy_type;
$value['policy_name'] = $policyTypeData->long_name;
$employeeDetails = $this->employeePolicyModel->getEmployeePolicy( client_id:$value['client_id'],policy_id: $value['client_policy_id'],status:0,branch_id:$this->request->getGet('client_branch_id'));
$enrolledCount = 0;
$draftCount = 0;
if(count($employeeDetails))
{
foreach ($employeeDetails as $item) {
if ($item['emp_status'] === 'enrolled') {
$enrolledCount++;
} elseif ($item['emp_status'] === 'draft') {
$draftCount++;
}
}
}
$value['totalMembersCount'] = count($employeeDetails);
$value['membersCountOfEnrolled'] = $enrolledCount;
$value['membersCountOfDraft'] = $draftCount;
array_push($data['policyDetails'],$value);
}
array_push($result,$data);
}
}
if($result)
{
return $this->respond(['status' => 'success','code' => (count($result) ? 200 : 404),'data' => $result ], 200);
}else{
return $this->respond(['status' => 'failed','code' => (count($result) ? 200 : 404),'data' => [] ], 200);
}
}
public function 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))
{
if($clientPolicy[0]['is_addon'] == 2)//Topup
{
$empData = $this->employeeModel->where('emp_code',$this->request->getGet('emp_code'))
->where('is_addon_value', 0 )->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();
}
}
}
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','code' => 404,'data' => [] ], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
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')
->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['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 = $value['basic_cover_si']; }
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'];
else
$data['eCardDownload'] = null;
$data['si_value'] = $si_value;
$data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $si_premium_value;
$data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : $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 = [
"sum_insured" => "Sum Insured",
"waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases",
"maternitycoverage" => "Maternity Coverage",
"babyday1cover" => "Baby Day 1 Cover",
"9monthwaitingperiodwaived" => "9-month waiting Period <20>waived",
"coverfromthedateofjoining" => "Cover from the date of Joining",
"waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions",
"waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period",
"prehospitalizationcover" => "Pre Hospitalization Cover",
"copayzonewisecopay" => "Co-Pay/Zone wise Co Pay",
"roomrentlimit" => "Room Rent Limit",
"ailmentcapping" => "Ailment capping",
];
$finalarray = [];
if($type == 'gpa'){
foreach ($gpa as $key => $value) {
if(isset($terms->$key))
$finalarray[$value] = $terms->$key;
}
}else{
foreach ($gmc as $key => $value) {
if(isset($terms->$key))
$finalarray[$value] = $terms->$key;
}
}
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'],404);
}
} 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'],404);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function storeFireBase()
{
// try {
$json = $this->request->getJSON();
$firebase_token = $json->firebase_token;
$mobile = $json->mobile;
// Ensure the mobile number is provided
if (empty($mobile)) {
return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Mobile number is required'], 400);
}
// Fetch employee by mobile number
$employee = $this->employeeModel->where('mobile', $mobile)->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'], 404);
}
// } 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());
}
}
}