diff --git a/app/Config/Constants.php b/app/Config/Constants.php index 5cd84385..d47699d8 100755 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -35,11 +35,11 @@ defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload. */ defined('SECOND') || define('SECOND', 1); defined('MINUTE') || define('MINUTE', 60); -defined('HOUR') || define('HOUR', 3600); -defined('DAY') || define('DAY', 86400); -defined('WEEK') || define('WEEK', 604800); -defined('MONTH') || define('MONTH', 2_592_000); -defined('YEAR') || define('YEAR', 31_536_000); +defined('HOUR') || define('HOUR', 3600); +defined('DAY') || define('DAY', 86400); +defined('WEEK') || define('WEEK', 604800); +defined('MONTH') || define('MONTH', 2_592_000); +defined('YEAR') || define('YEAR', 31_536_000); defined('DECADE') || define('DECADE', 315_360_000); /* @@ -67,16 +67,16 @@ defined('DECADE') || define('DECADE', 315_360_000); | http://tldp.org/LDP/abs/html/exitcodes.html | */ -defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors -defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error -defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error -defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found -defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class +defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors +defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error +defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error +defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found +defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member -defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input -defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error -defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code -defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code +defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input +defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error +defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code +defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code /** * @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead. @@ -115,4 +115,19 @@ define('ACCOUNT_MANAGER_ROLE_ID', 3); define('STAFF_ROLE_ID', 4); define('HEAD_ROLE_ID', 5); +/** + * @Upload Allowed Extensions by Business Context + */ +define('UPLOAD_ALLOWED_EXTENSIONS', [ + 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', + 'pdf', 'doc', 'docx', 'odt', 'rtf', + 'xls', 'xlsx', 'ods', 'csv', 'txt', +]); +define('UPLOAD_EXT_IMAGES', ['jpg', 'jpeg', 'png']); +define('UPLOAD_EXT_KYC_DOCS', ['pdf', 'jpg', 'jpeg', 'png']); +define('UPLOAD_EXT_CLAIM_DOCS', ['pdf', 'jpg', 'jpeg', 'png']); +define('UPLOAD_EXT_POLICY_DOCS', ['pdf', 'jpg', 'jpeg', 'png', 'xls', 'xlsx']); +define('UPLOAD_EXT_LEAD_FILES', ['xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png']); +define('UPLOAD_EXT_EXCEL', ['xls', 'xlsx', 'ods', 'csv']); +define('UPLOAD_EXT_MAIL_ATTACHMENTS', ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx']); diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php index a7032a4c..a53d90d0 100755 --- a/app/Controllers/AppContentManagementController.php +++ b/app/Controllers/AppContentManagementController.php @@ -101,23 +101,22 @@ class AppContentManagementController extends AdminController $file = $this->request->getFile('advertise_image'); $client_id = $sanitized_post_data['client_id'] ?? null; - //1) original file name for vaildations - $fileName = $file->getClientName(); //original file name for vaildations - $existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first(); - if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); } - - //skip 1) and use this - // $fileName = $file->getRandomName(); // Same Name Multiple time upload means different name if (!$file || !$file->isValid()) { return $this->respond(['status' => false, 'message' => 'No file uploaded or invalid file.'], 400); } - // $uploadPath = WRITEPATH . 'uploads/advertiseImage/'; + if (!validate_upload_extension($file, UPLOAD_EXT_IMAGES)) { + return $this->respond(['status' => false, 'message' => 'Only JPG, JPEG, PNG files are allowed.'], 400); + } + + $fileName = sanitize_upload_filename($file->getClientName()); + $existing = $this->addImgModel->where('name', $fileName)->where('client_id', $client_id)->where('is_active', 1)->first(); + if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); } + $uploadPath = ROOTPATH . 'public/uploads/add_image_upload/'; if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true); - $file->move($uploadPath, $fileName); $id = $sanitized_post_data['add_image_id'] ?? null; diff --git a/app/Controllers/ClaimsUploadController.php b/app/Controllers/ClaimsUploadController.php index 02c9a187..a704ba3b 100644 --- a/app/Controllers/ClaimsUploadController.php +++ b/app/Controllers/ClaimsUploadController.php @@ -26,6 +26,13 @@ class ClaimsUploadController extends BaseController ], 400); } + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return $this->respond([ + 'status' => 'failed', + 'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.' + ], 400); + } + $data = [ 'client_id' => $this->request->getPost('client_id'), 'tpa_id' => $this->request->getPost('tpa_id'), diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 195ce4b9..62989198 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -1051,7 +1051,7 @@ class ClientController extends AdminController $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $sanitized_post_data['created_by'] = get_session_userid(); @@ -1149,7 +1149,7 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'edit client general info function called'); $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $id = $this->request->getPost('PrimaryKey'); $data = $this->request->getPost(); @@ -1191,7 +1191,7 @@ class ClientController extends AdminController // print_r($data); die; unset($data['file_name']); $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; - $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath); + $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if (!empty($File)) { $data['file_name'] = $File; @@ -1257,7 +1257,7 @@ class ClientController extends AdminController $file = $this->request->getFile('file_name'); - $fileName = file_Upload($file, $uploadFilePath); + $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if (!empty($fileName)) { $sanitized_data['file_name'] = $fileName; @@ -1313,7 +1313,7 @@ class ClientController extends AdminController $file = $this->request->getFile('file_name'); - $fileName = file_Upload($file, $uploadFilePath); + $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if (!empty($fileName)) { $sanitized_data['file_name'] = $fileName; @@ -1400,7 +1400,7 @@ class ClientController extends AdminController $file = $this->request->getFile('file_name'); $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; - $fileName = file_Upload($file, $uploadFilePath); + $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if (!empty($fileName)) { $sanitized_data['file_name'] = $fileName; @@ -1472,7 +1472,7 @@ class ClientController extends AdminController if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { - $new_file_name = file_Upload($uploadedFile, $uploadFilePath); + $new_file_name = file_Upload($uploadedFile, $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if (!$new_file_name) { return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200); } @@ -3479,7 +3479,7 @@ class ClientController extends AdminController if (!empty($docName) && $file->isValid() && !$file->hasMoved()) { // Upload the file - $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath); + $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS); if ($uploadedFileName) { // Prepare data for each document upload diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index 5c87df6c..3a0bea5b 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -1,77 +1,50 @@ myLogger = \Config\Services::mylogger(); - $this->employeeModel = new EmployeeModel(); - $this->employeePolicyModel = new EmployeePolicyModel(); - $this->clientModel = new ClientModel(); - $this->clientRMModel = new ClientRMModel(); - $this->policesModel = new PolicesModel(); - $this->relationshipModel = new RelationshipModel(); - $this->fileModel = new FileModel(); - $this->clientPolicyModel = new ClientPolicyModel(); - $this->policyPremium1Model = new PolicyPremium1Model(); - $this->policyPremium2Model = new PolicyPremium2Model(); - $this->policyTypeModel = new PolicyTypeModel(); - $this->notificationModel = new NotificationModel(); - $this->userModel = new UserModel(); - $this->feContentModel = new FEContentModel(); - $this->addImgModel = new AddImgModel(); - $this->clientBranchModel = new ClientBranchModel(); - $this->auditHistoryModel = new AuditHistoryModel(); - $this->claimStatusModel = new TicketClaimStatusModel(); - $this->ticketMaster = new TicketMasterModel(); - $this->ticketMessage = new TicketMessageModel(); + $this->myLogger = \Config\Services::mylogger(); + $this->employeeModel = new EmployeeModel(); + $this->employeePolicyModel = new EmployeePolicyModel(); + $this->clientModel = new ClientModel(); + $this->clientRMModel = new ClientRMModel(); + $this->policesModel = new PolicesModel(); + $this->relationshipModel = new RelationshipModel(); + $this->fileModel = new FileModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->policyPremium1Model = new PolicyPremium1Model(); + $this->policyPremium2Model = new PolicyPremium2Model(); + $this->policyTypeModel = new PolicyTypeModel(); + $this->notificationModel = new NotificationModel(); + $this->userModel = new UserModel(); + $this->feContentModel = new FEContentModel(); + $this->addImgModel = new AddImgModel(); + $this->clientBranchModel = new ClientBranchModel(); + $this->auditHistoryModel = new AuditHistoryModel(); + $this->claimStatusModel = new TicketClaimStatusModel(); + $this->ticketMaster = new TicketMasterModel(); + $this->ticketMessage = new TicketMessageModel(); $this->employeeRetailPolicy = new EmployeeRetailPolicy(); - $this->ticketController = new TicketController(); - $this->hrAccessControlModel = new HRAccessControlModel(); - $this->insurerModel = new InsurerModel(); - $this->hrFileUploadModel = new HrFileUploadModel(); + $this->ticketController = new TicketController(); + $this->hrAccessControlModel = new HRAccessControlModel(); + $this->insurerModel = new InsurerModel(); + $this->hrFileUploadModel = new HrFileUploadModel(); $this->ticketMailTemplateModel = new TicketMailTemplateModel(); - $this->batchFileModel = new BatchFileModel(); - $this->UserActivityHistoryModel = new UserActivityHistoryModel(); + $this->batchFileModel = new BatchFileModel(); + $this->UserActivityHistoryModel = new UserActivityHistoryModel(); } - public function getEmployeeProfile() { try { - $emp_code = $this->request->getGet('emp_code'); - $client_id = $this->request->getGet('client_id'); + $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'; @@ -175,12 +146,12 @@ class EmployeeRestController extends AdminController ->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; + $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.*') + $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) @@ -201,7 +172,7 @@ class EmployeeRestController extends AdminController try { $data = $this->request->getJSON(); if ($data) { - $id = $data->id; + $id = $data->id; $employee = $this->employeeModel->where('is_active', 1)->update($id, $data); if ($employee) { @@ -223,10 +194,10 @@ class EmployeeRestController extends AdminController try { $emp_code = $this->request->getGet('emp_code'); if ($emp_code) { - $employee = $this->employeeModel->where('is_active', 1)->where('emp_code', $emp_code)->findAll(); + $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']); + $dateTime = \DateTime::createFromFormat('Y-m-d', $item['dob']); $item['dob'] = $dateTime->format('d-m-Y'); } return $item; @@ -251,9 +222,9 @@ class EmployeeRestController extends AdminController $updatedCount = 0; foreach ($data as $item) { - $id = $item->id; + $id = $item->id; $item->dob = $this->convertDateFormatYMD($item->dob); - $employee = $this->employeeModel->where('is_active', 1)->update($id, (array)$item); + $employee = $this->employeeModel->where('is_active', 1)->update($id, (array) $item); if ($employee) { $updatedCount++; } @@ -272,7 +243,6 @@ class EmployeeRestController extends AdminController } } - public function addEmployeeAndDependence() { try { @@ -290,21 +260,21 @@ class EmployeeRestController extends AdminController if (isset($item->id)) { //update old data - $id = $item->id; + $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); + $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->gender = $this->GenderMap($item->relationship, $item->emp_code); + $item->dob = $this->convertDateFormatYMD($item->dob); + $item->emp_status = 'draft'; $employee = $this->employeeModel->insert($item); @@ -339,7 +309,7 @@ class EmployeeRestController extends AdminController public function getEmployeePayableValue($client_policy_id, $relationship) { - $terms = $this->clientPolicyModel->where('id', $client_policy_id)->get()->getRow()->policy_terms; + $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; @@ -360,8 +330,8 @@ class EmployeeRestController extends AdminController { 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']); + $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; } @@ -373,16 +343,16 @@ class EmployeeRestController extends AdminController ->where('client_policy_id', $client_policy_id) ->where('employee_id', $employee_id) ->where('is_active', 1) - ->set(array('basic_cover_si' => $basic_cover_si)) + ->set(['basic_cover_si' => $basic_cover_si]) ->update(); } else { - $data['employee_id'] = $employee_id; + $data['employee_id'] = $employee_id; $data['client_policy_id'] = $client_policy_id; - $data['basic_cover_si'] = $basic_cover_si; + $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); + $data['status'] = 'draft'; + $data['date_coverage'] = $this->getEmployeeCoverageDate($emp_code, $client_policy_id); $this->employeePolicyModel->insert($data); } @@ -408,7 +378,7 @@ class EmployeeRestController extends AdminController ->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'])) + ->set(['basic_cover_si' => $value['policy_details']['basic_cover_si'], 'premium' => $value['policy_details']['premium'], 'rata_premimum' => $value['policy_details']['rata_premimum'], 'gst' => $value['policy_details']['gst']]) ->update(); } } @@ -418,7 +388,7 @@ class EmployeeRestController extends AdminController public function getEmployeeCoverageDate($emp_code, $client_policy_id) { - $empData = $this->employeeModel->where('emp_code', $emp_code)->where('relationship', 'self')->where('is_active', 1)->first();; + $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') @@ -457,12 +427,11 @@ class EmployeeRestController extends AdminController } } - public function RelationshipMap($value) { if ($value === 'Mother' || $value === 'Father') { - return 'parent'; + return 'parent'; } else if ($value === 'Son' || $value === 'Daughter') { return 'child'; } else if ($value === 'Father in Law' || $value === 'Mother in Law') { @@ -476,14 +445,14 @@ class EmployeeRestController extends AdminController { if ($value === 'Mother' || $value === 'Daughter' || $value === 'Mother in Law') { - return 'F'; + 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'; + return 'F'; } else { return 'M'; } @@ -521,12 +490,12 @@ class EmployeeRestController extends AdminController if ($this->request->getGet('id')) { $this->employeeModel->where('id', $this->request->getGet('id')) ->where('is_active', 1) - ->set(array('is_active' => 0)) + ->set(['is_active' => 0]) ->update(); $this->employeePolicyModel->where('employee_id', $this->request->getGet('id')) ->where('is_active', 1) - ->set(array('is_active' => 0)) + ->set(['is_active' => 0]) ->update(); return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } else { @@ -556,16 +525,15 @@ class EmployeeRestController extends AdminController ->where('is_active', 1) ->findAll(); - if ($checkIfExist) { - $empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si); + $empPolicy = $this->employeePolicyModel->updateSiAndPremium($value->client_policy_id, $value->employee_id, $value->basic_cover_si); } else { - $data['employee_id'] = $value->employee_id; + $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['basic_cover_si'] = $value->basic_cover_si; + $data['status'] = 'draft'; $this->employeePolicyModel->insert($data); } @@ -610,7 +578,7 @@ class EmployeeRestController extends AdminController { 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'), status_type: 'inactive'); + $empData = $this->employeePolicyModel->getEmployeePolicy(client_id: $this->request->getGet('client_id'), policy_id: $this->request->getGet('client_policy_id'), status: 0, branch_id: $this->request->getGet('client_branch_id'), status_type: 'inactive'); if ($empData) { return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200); @@ -626,24 +594,24 @@ class EmployeeRestController extends AdminController { 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')); + $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', + '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' + 'TPA Name' => 'tpa_name', + 'Status' => 'emp_status', ]; // Create a new Spreadsheet object @@ -670,9 +638,8 @@ class EmployeeRestController extends AdminController $row++; } - // Set the header for download - $filename = $empData[0]['policy_name'] . '-Enrolment.xlsx'; + $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'); @@ -696,7 +663,7 @@ class EmployeeRestController extends AdminController 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') + $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(); @@ -727,16 +694,23 @@ class EmployeeRestController extends AdminController public function employeeUpload() { try { - $file = $this->request->getFile('file'); - $client_id = $this->request->getPost('client_id'); + $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'); + $policy_id = $this->request->getPost('policy_id'); - $client_data = $this->clientModel->where('id', $client_id)->first(); + if (!$file || !$file->isValid()) { + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'No file uploaded or invalid file.'], 200); + } + + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.'], 200); + } + + $client_data = $this->clientModel->where('id', $client_id)->first(); $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_welcome_mail')->first(); - - $jwt = $this->request->getHeaderLine('Authorization'); + $jwt = $this->request->getHeaderLine('Authorization'); $jwtParts = explode(' ', $jwt); $token = $jwtParts[1]; @@ -746,36 +720,34 @@ class EmployeeRestController extends AdminController // 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 = $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(); + $fileName = sanitize_upload_filename($file->getName()); + $is_moved = $file->move(WRITEPATH . 'uploads/excel', $fileName); + $filename = $file->getName(); $file_name_with_path = WRITEPATH . "/uploads/excel/" . $filename; - //make an entry in DB + //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]); + $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); if (isset($result['error_summary']) && count($result['error_summary'])) { $result = $empServiceController->getExcelErrorData($file_id); return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "The data format is invalid. Click 'Next' to view details.", 'data' => $result], 200); } - - //check the file exist or not - if (!file_exists($file_name_with_path)) { + if (! file_exists($file_name_with_path)) { session()->setFlashdata('error', 'File not found'); return redirect()->to(base_url('employee/upload')); } @@ -786,11 +758,11 @@ class EmployeeRestController extends AdminController $sheet = $spreadsheet->getActiveSheet(); // Get the highest row and column numbers - $highestRow = $sheet->getHighestRow(); + $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); $highestRowAndColumn = $sheet->getHighestRowAndColumn(); - $data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); // $extractData['file_name']= $filename; // $extractData['client_id']= $client_id; @@ -806,9 +778,9 @@ class EmployeeRestController extends AdminController // 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 0) { @@ -842,7 +814,7 @@ class EmployeeRestController extends AdminController } } } - $dataToInsert = []; + $dataToInsert = []; $basic_cover_si = []; foreach ($extra['0'] as $index => $id) { $relation = ''; @@ -863,7 +835,7 @@ class EmployeeRestController extends AdminController $doj = $extra['3'][$index]; $dob = $extra['6'][$index]; - // Change date format for $doj + // 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 @@ -871,28 +843,28 @@ class EmployeeRestController extends AdminController // Your existing code here $emp_code = isset($extra['1'][$index]) ? $extra['1'][$index] : 0; - $name = $extra['2'][$index]; + $name = $extra['2'][$index]; if ($emp_code != 0 && $name != '' || $name != null) { $record = [ // 'id' => $id, - 'emp_code' => $emp_code, - 'name' => $name, + '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])), + '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 + '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; @@ -922,19 +894,19 @@ class EmployeeRestController extends AdminController $record2 = [ 'basic_cover_si' => $basic_cover_si_value, ]; - $dataToInsert[] = $record; + $dataToInsert[] = $record; $basic_cover_si[] = $basic_cover_si_value; } } - $count = 0; + $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; + $emp_id = 0; $data_after_gpa_or_gmc = []; if ($client_policy['policy_type_id'] == 1) { @@ -945,18 +917,17 @@ class EmployeeRestController extends AdminController $data_after_gpa_or_gmc = $dataToInsert[$a]; } date_default_timezone_set('Asia/Kolkata'); - $current_timestamp = time(); + $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; + $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); + $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'])); @@ -966,36 +937,35 @@ class EmployeeRestController extends AdminController $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); + $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();; - + $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'])); + $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, + 'employee_id' => $emp_id, 'client_policy_id' => $policy_id, - 'status' => 'draft', - 'date_coverage' => $date_coverage, + '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, + '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['id'] = $existing_policy['id']; $emp_policy_data['updated_at'] = $formatted_date_time; $this->employeePolicyModel->save($emp_policy_data); } @@ -1004,22 +974,22 @@ class EmployeeRestController extends AdminController $emp_policy_id = $this->employeePolicyModel->insert($emp_policy_data); } - if (isset($notification) && $notification['enabled'] == 1 && !empty($notification['mail_content'])) { + 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'])) { + 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, + $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', + 'employee_id' => $emp_id, + 'mail_type' => 'member_welcome_mail', ]; $wholeData[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params); @@ -1029,13 +999,12 @@ class EmployeeRestController extends AdminController // if($count == 20 || $a == count($dataToInsert)-1){ // if (count($wholeData) > 0) { // $job_details = new Jobs(); - // $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $wholeData]); + // $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') { } @@ -1043,14 +1012,14 @@ class EmployeeRestController extends AdminController // print_r($wholeData); die; - // for bulk mail queue job push - if (!empty($wholeData) && count($wholeData) > 0) { + // 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]); + $job_details = new Jobs(); + $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]); } } @@ -1064,14 +1033,13 @@ class EmployeeRestController extends AdminController } } - //------------------------------------- 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); + $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 { @@ -1083,14 +1051,14 @@ class EmployeeRestController extends AdminController { try { - $id = $this->request->getGet('id'); - $emp_code = $this->request->getGet('emp_code'); - $client_id = $this->request->getGet('client_id'); + $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'); + $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"]; + $keysToRemove = ["removable_keys"]; // Retrieve employee policy data by passing the employee primary key $empPolicy = $this->employeeModel->getEmployeePolicy($id); // dd($empPolicy); @@ -1101,7 +1069,6 @@ class EmployeeRestController extends AdminController ->where('is_active', 1) ->where('is_addon_value', 0)->findAll(); - if ($empPolicy) { $result = []; @@ -1109,16 +1076,15 @@ class EmployeeRestController extends AdminController // 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)); + $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 + // 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']; + $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'; @@ -1126,55 +1092,51 @@ class EmployeeRestController extends AdminController $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_value = 0; $si_premium_value = 0; - $si_gst_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'); + $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; + $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; + $si_gst_value = $si_gst_value + $employee_policy->gst; } - $self['is_value_exist'] = true; + $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; + $self['data']['employee_id'] = $id; + $self['data']['relationship'] = 'Self'; + $self['data']['name'] = $selfData[0]['name']; + $self['data']['dob'] = $this->convertDateFormatDMY($selfData[0]['dob']); + $self['data']['mobile'] = $selfData[0]['mobile']; + $self['data']['client_policy_id'] = $array->ClientPolicyId; + $self['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; $array->mapped_family_floaters = $self; - $array->type = 'GPA'; - $array->si_value = $si_value; - $array->si_premium_value = $si_premium_value; - $array->si_gst_value = $si_gst_value; - - + $array->type = 'GPA'; + $array->si_value = $si_value; + $array->si_premium_value = $si_premium_value; + $array->si_gst_value = $si_gst_value; $res = []; array_push($res, $array); - $EDLIPolicy = $this->getAdditionalGPAPolicy($employeeData, 6, $emp_code, $client_id, $client_branch_id, $login_by_hr); + $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); + $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); @@ -1184,8 +1146,6 @@ class EmployeeRestController extends AdminController // $getSlabAndGridData['grid_master']['policy_type'] == "GMC" } else if ($array->policy_type_id == 2 && $this->request->getGet('policy') == 'GMC') { - - // Map family floaters that already exist in the employee table $familyFloates = $array->Policy_Terms->family_floaters; @@ -1193,26 +1153,26 @@ class EmployeeRestController extends AdminController $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_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_heading = 'Sum Insured'; $array->floter_text_description = ''; } - // remove parent and parent-in-law from familyFloaters + // 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; + $data = []; + $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; - $dependent_and_si_gst_value = 0; + $dependent_and_si_gst_value = 0; foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); + $dependent = preg_replace('/\d/', '', $familyFloatesValue); if (count($empData)) { foreach ($empData as $key => $value) { @@ -1230,16 +1190,15 @@ class EmployeeRestController extends AdminController } } - $temp['is_value_exist'] = true; + $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']['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); @@ -1252,11 +1211,9 @@ class EmployeeRestController extends AdminController } } - - // 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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1273,7 +1230,7 @@ class EmployeeRestController extends AdminController $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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1292,12 +1249,11 @@ class EmployeeRestController extends AdminController if (count($floters)) { foreach ($floters as $familyFloatesValue) { - $temp2['is_value_exist'] = false; + $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']['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); @@ -1305,23 +1261,23 @@ class EmployeeRestController extends AdminController } } - $array->mapped_family_floaters = $data; - $array->type = "GMC"; - $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; - $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; - $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; + $array->mapped_family_floaters = $data; + $array->type = "GMC"; + $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; + $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') - ->where('client_policy.policy_type_id', 3) - ->where('client_policy.is_addon', 1) + ->where('client_policy.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); + $GmcParrentsData = $this->getGmcParrentsPolicy($checkGmcParentsPolicyExist, $emp_code, $client_id, $client_branch_id); return $this->respond(['status' => 'success', 'code' => 200, 'data' => [$array, $GmcParrentsData]], 200); } @@ -1342,7 +1298,6 @@ class EmployeeRestController extends AdminController } } - public function getGmcParrentsPolicy($GmcParrentsPolicy, $emp_code, $client_id, $client_branch_id) { @@ -1354,19 +1309,15 @@ class EmployeeRestController extends AdminController // 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 + // 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']; + $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') @@ -1378,15 +1329,16 @@ class EmployeeRestController extends AdminController if (count($tpaArray)) { - if ($tpaArray[0]->tpa_id != null) + if ($tpaArray[0]->tpa_id != null) { $array->eCardDownload = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1'; - else + } else { $array->eCardDownload = null; + } + } else { $array->eCardDownload = null; } - $array->eCardDownload = null; // Map family floaters that already exist in the employee table @@ -1395,30 +1347,29 @@ class EmployeeRestController extends AdminController // 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'; + 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_heading = 'Sum Insured'; $array->floter_text_description = ''; } - - // remove parent and parent-in-law from familyFloaters + // 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 + // Convert familyFloaters terms data to plain array $floters = $this->FloterConvertion($familyFloates); - $data = []; - $dependent_and_si_value = 0; + $data = []; + $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; - $dependent_and_si_gst_value = 0; + $dependent_and_si_gst_value = 0; foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); + $dependent = preg_replace('/\d/', '', $familyFloatesValue); if (count($empData)) { foreach ($empData as $key => $value) { @@ -1436,17 +1387,16 @@ class EmployeeRestController extends AdminController } } - $temp['is_value_exist'] = true; + $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); - + $temp['data']['employee_id'] = $value['id']; + $temp['data']['relationship'] = $value['relationship']; + $temp['data']['name'] = $value['name']; + $temp['data']['dob'] = $this->convertDateFormatDMY($value['dob']); + $temp['data']['client_policy_id'] = $array->ClientPolicyId; + $temp['data']['form_type'] = $dependent; + $temp['data']['basic_cover_si'] = isset($employee_policy->basic_cover_si) ? $employee_policy->basic_cover_si : 0; + $temp['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue); array_push($data, $temp); unset($empData[$key]); @@ -1459,7 +1409,7 @@ class EmployeeRestController extends AdminController // 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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1476,7 +1426,7 @@ class EmployeeRestController extends AdminController $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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1495,32 +1445,31 @@ class EmployeeRestController extends AdminController if (count($floters)) { foreach ($floters as $familyFloatesValue) { - $temp2['is_value_exist'] = false; + $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); + $temp2['data']['client_policy_id'] = $array->ClientPolicyId; + $temp2['data']['button_name'] = 'Add ' . ucfirst(str_replace('_', ' ', preg_replace('/\d/', '', $familyFloatesValue))); + $temp2['data']['form_type'] = preg_replace('/\d/', '', $familyFloatesValue); + $temp2['data']['age_validation'] = $this->getAgeRange($array->Policy_Terms, $familyFloatesValue); array_push($data, $temp2); } } - $array->mapped_family_floaters = $data; - $array->type = "GMC - Parents"; - $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; - $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; - $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; + $array->mapped_family_floaters = $data; + $array->type = "GMC - Parents"; + $array->family_floaters_of_dependent_and_si_value = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; + $array->family_floaters_of_dependent_and_si_premium_value = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $array->family_floaters_of_dependent_and_gst_value = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; return $array; } } - public function getAdditionalGPAPolicy($empData, $policy_type, $emp_code, $client_id, $client_branch_id, $login_by_hr) { $checkPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type as inception_type , client_policy.policy_terms as Policy_Terms , client_policy.enrolment_visibility') - ->where('client_policy.policy_type_id', $policy_type) - ->where('client_policy.is_addon', 1) + ->where('client_policy.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) @@ -1531,28 +1480,27 @@ class EmployeeRestController extends AdminController foreach ($checkPolicyExist as $key => $array) { - $decodedArray = json_decode($array->Policy_Terms); + $decodedArray = json_decode($array->Policy_Terms); $array->Policy_Terms = $decodedArray; - $si_value = 0; - $si_premium_value = 0; - $si_gst_value = 0; + $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'); + $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; + $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; + $si_gst_value = $si_gst_value + $employee_policy->gst; } $policyTypeData = $this->policyTypeModel->where('id', $policy_type)->get()->getRow(); - $array->type = $policyTypeData->policy_type; - $array->Policy_Name = $policyTypeData->long_name; - $array->si_value = $si_value; + $array->type = $policyTypeData->policy_type; + $array->Policy_Name = $policyTypeData->long_name; + $array->si_value = $si_value; $array->si_premium_value = $si_premium_value; - $array->si_gst_value = $si_gst_value; - + $array->si_gst_value = $si_gst_value; if ($employee_policy) { @@ -1562,26 +1510,27 @@ class EmployeeRestController extends AdminController $array->eCardDownload = null; } - $self['is_value_exist'] = true; + $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; - + $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) + if ($array->enrolment_visibility == 1) { return $array; - else + } else { return false; + } + } } else { return false; @@ -1590,8 +1539,6 @@ class EmployeeRestController extends AdminController } } - - public function FloterConvertion($array) { @@ -1641,8 +1588,8 @@ class EmployeeRestController extends AdminController } 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); + $string = str_replace('-', ' ', $key); + $string = ucwords($string); $result .= ' + ' . $string; } else if ($value != 0 && $key === 'self') { $result = 'Allowed members Self '; @@ -1654,8 +1601,8 @@ class EmployeeRestController extends AdminController } } else if ($value != 0 && $key === 'elders_count') { } else { - $string = str_replace('-', ' ', $key); - $string = ucwords($string); + $string = str_replace('-', ' ', $key); + $string = ucwords($string); $result .= ' + ' . $value . ' ' . $string; } } @@ -1679,13 +1626,13 @@ class EmployeeRestController extends AdminController $client_id = $this->request->getGet('client_id'); if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) { $client = $this->clientModel->where('MD5(id)', $client_id)->first(); - }else{ + } else { $client = $this->clientModel->where('id', $client_id)->first(); - } + } - if (!empty($client)) { + if (! empty($client)) { $client['client_logo'] = base_url() . 'public/uploads/logo/' . $client['client_logo']; - $clientPolicy = $this->clientPolicyModel->where('client_id', $client['id']) + $clientPolicy = $this->clientPolicyModel->where('client_id', $client['id']) ->where('client_branch_id', $this->request->getGet('client_branch_id'))->findAll(); return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['client' => $client, 'client_policy' => $clientPolicy]], 200); } else { @@ -1706,8 +1653,6 @@ class EmployeeRestController extends AdminController ->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) @@ -1723,47 +1668,46 @@ class EmployeeRestController extends AdminController ->get() ->getRow(); - $band = $self->band; + $band = $self->band; $PolicyData = []; foreach ($clientPolicy as $key => $array) { $responce = []; - $decodedArray = json_decode($array['policy_terms']); - $policy_terms = $decodedArray; + $decodedArray = json_decode($array['policy_terms']); + $policy_terms = $decodedArray; $getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array['id'], $array['client_id']); - $uniqueData = []; - $siValues = []; + $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 (! in_array($item['si'], $siValues)) { if ($item['policy_grid_id'] == 11 && ($item['max_si'] != 0 || $item['max_si'] != null)) { $uniqueData[] = $item; - $siValues[] = $item['si']; + $siValues[] = $item['si']; } else if ($item['policy_grid_id'] != 11) { $uniqueData[] = $item; - $siValues[] = $item['si']; + $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']; + $policyTypeData = $this->policyTypeModel->where('id', $array['policy_type_id'])->get()->getRow(); + $responce['policy_name'] = $policyTypeData->long_name; + $responce['type'] = $policyTypeData->policy_type; + $responce['SlabRates'] = $uniqueData; + $responce['GridMaster'] = $getSlabAndGridData['grid_master']; + $responce['client_id'] = $array['client_id']; + $responce['client_policy_id'] = $array['id']; + $responce['is_addon'] = $array['is_addon']; $responce['OpenForEnrollment'] = $array['open_for_enrollment']; - $responce['policy_terms'] = $decodedArray; - $responce['policy_type_id'] = $array['policy_type_id']; + $responce['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']; @@ -1775,12 +1719,13 @@ class EmployeeRestController extends AdminController ->get() ->getResult(); - if (count($tpaArray)) { - if ($tpaArray[0]->tpa_id != null) + if ($tpaArray[0]->tpa_id != null) { $responce['eCardDownload'] = base_url('download-e-card/') . $tpaArray[0]->rand_string . '/1'; - else + } else { $responce['eCardDownload'] = null; + } + } else { $responce['eCardDownload'] = null; } @@ -1789,11 +1734,10 @@ class EmployeeRestController extends AdminController 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'; + $responce['floter_text_heading'] = 'Sum Insured'; } } - if ($array['is_addon'] == 3 && $array['policy_type_id'] == 3) //dependent add on policy { @@ -1811,7 +1755,7 @@ class EmployeeRestController extends AdminController ->get() ->getRow(); - $selfSi = $selfGMC->basic_cover_si; + $selfSi = $selfGMC->basic_cover_si; $filteredSlabRates = array_filter($responce['SlabRates'], function ($rate) use ($selfSi) { return $rate['si'] === $selfSi; }); @@ -1819,23 +1763,22 @@ class EmployeeRestController extends AdminController $responce['SlabRates'] = array_values($filteredSlabRates); } - // Map family floaters that already exist in the employee table $familyFloates = $policy_terms->family_floaters; - // remove parent and parent-in-law from familyFloaters + // 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 + // Convert familyFloaters terms data to plain array $floters = $this->FloterConvertion($familyFloates); - $data = []; - $dependent_and_si_value = 0; + $data = []; + $dependent_and_si_value = 0; $dependent_and_si_premium_value = 0; - $dependent_and_si_gst_value = 0; + $dependent_and_si_gst_value = 0; foreach ($floters as $familyFloatesValue) { - $dependent = preg_replace('/\d/', '', $familyFloatesValue); + $dependent = preg_replace('/\d/', '', $familyFloatesValue); if (count($addOnEmployeeData)) { foreach ($addOnEmployeeData as $key => $value) { if ($value['family_floater_key'] === $dependent) { @@ -1852,17 +1795,17 @@ class EmployeeRestController extends AdminController } } - $temp['is_value_exist'] = true; + $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); + $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]); @@ -1876,8 +1819,7 @@ class EmployeeRestController extends AdminController //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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1894,7 +1836,7 @@ class EmployeeRestController extends AdminController $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 = 0; $count_parent_in_law = 0; foreach ($floters as $value) { if (preg_replace('/\d/', '', $value) == 'parent') { @@ -1909,16 +1851,15 @@ class EmployeeRestController extends AdminController } } - // Add family floter buttons placement data for FE validation if (count($floters)) { foreach ($floters as $familyFloatesValue) { - $temp2['is_value_exist'] = false; + $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']['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); @@ -1926,14 +1867,10 @@ class EmployeeRestController extends AdminController } } - $responce['family_floaters_of_dependent_and_si_array'] = $data; - $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; - $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; - $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; - - - - + $responce['family_floaters_of_dependent_and_si_array'] = $data; + $responce['family_floaters_of_dependent_and_si_value'] = $dependent_and_si_value > 0 ? $dependent_and_si_value : 0; + $responce['family_floaters_of_dependent_and_si_premium_value'] = $dependent_and_si_premium_value > 0 ? round($dependent_and_si_premium_value) : 0; + $responce['family_floaters_of_dependent_and_gst_value'] = $dependent_and_si_gst_value > 0 ? round($dependent_and_si_gst_value) : 0; if ($this->request->getGet('policy') == 'GMC-DEPENDENT-ADDON') { return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_dependent_addon' => $responce]], 200); @@ -1944,7 +1881,6 @@ class EmployeeRestController extends AdminController } else if ($array['is_addon'] == 2 && $array['policy_type_id'] == 4) //Topup policy { - $whereArray = []; foreach ($decodedArray->family_floaters as $key => $value) { if ($value != 0) { @@ -1963,8 +1899,7 @@ class EmployeeRestController extends AdminController } } - - $getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $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) { @@ -1972,10 +1907,10 @@ class EmployeeRestController extends AdminController } else { $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; + $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) { @@ -1991,22 +1926,21 @@ class EmployeeRestController extends AdminController $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['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; + $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_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); - $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value; - + $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); @@ -2032,7 +1966,7 @@ class EmployeeRestController extends AdminController } } - $getAddOnType = $this->clientPolicyModel->where('id', $array['base_policy'])->where('policy_status', 1)->get()->getRow(); + $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) { @@ -2040,10 +1974,10 @@ class EmployeeRestController extends AdminController } else { $is_addon_value = 1; } - $only_si_array = []; - $only_si_value = 0; - $only_si_premium_value = 0; - $only_si_gst_value = 0; + $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) { @@ -2059,22 +1993,21 @@ class EmployeeRestController extends AdminController $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['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; + $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_array'] = $only_si_array; + $responce['family_floaters_of_only_si_value'] = $only_si_value; $responce['family_floaters_of_only_si_premium_value'] = round($only_si_premium_value); - $responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value); - + $responce['family_floaters_of_only_si_gst_value'] = round($only_si_gst_value); if ($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP') { return $this->respond(['status' => 'success', 'code' => 200, 'data' => ['gmc_si_parent_topup' => $responce]], 200); @@ -2082,7 +2015,6 @@ class EmployeeRestController extends AdminController } } - return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } else { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); @@ -2100,15 +2032,15 @@ class EmployeeRestController extends AdminController $client_policy_id = $postData['client_policy_id']; sort($client_policy_id); - $emp_code = $postData['emp_code']; + $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(); + $empData = $this->employeeModel->where('emp_code', $emp_code)->where('client_id', $client_id)->where('is_active', 1)->findAll(); $employeeIds = array_column($empData, 'id'); //for mail common parameter $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); - if (!is_null($client_policy_id) && is_array($client_policy_id)) { + if (! is_null($client_policy_id) && is_array($client_policy_id)) { $array_list = []; foreach ($client_policy_id as $key => $value) { $policy = $this->clientPolicyModel->where('id', $value)->where('open_for_enrollment', 1)->find(); @@ -2130,7 +2062,7 @@ class EmployeeRestController extends AdminController ->where('status', 'draft') ->orWhere('status', 'enrolled') ->groupEnd() - ->set(array('status' => 'enrolled')) + ->set(['status' => 'enrolled']) ->update(); //update Employee table $this->employeeModel->where('emp_code', $emp_code) @@ -2154,40 +2086,36 @@ class EmployeeRestController extends AdminController } } - - - $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['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, + $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', + '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]); + $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); + $mail_send_return = MailHelper::send_email($wholeData[0]); $this->myLogger->logme("error", $mail_send_return); if (isset($wholeData[0])) { $params['common']['mail_type'] = 'account_maneger_summary_mail'; - $account_manager_wholeData = sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); + $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); + $mail_send_return1 = MailHelper::send_email($value); $this->myLogger->logme("error", $mail_send_return1); } } else { @@ -2195,7 +2123,7 @@ class EmployeeRestController extends AdminController } $params['common']['mail_type'] = 'client_hr_summary_mail'; - $client_hr_wholeData = sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); + $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) { @@ -2214,47 +2142,46 @@ class EmployeeRestController extends AdminController 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 + //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 + $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 + $emp_code = $empCode; + $default_si = $default_si; // si amt which choosed in add on policy $client_branch_id = $client_branch_id; } // dd($client_policy_id); - - $client_id = ($this->clientPolicyModel->select('client_id')->find((int)$client_policy_id))['client_id']; + $client_id = ($this->clientPolicyModel->select('client_id')->find((int) $client_policy_id))['client_id']; // get policy and rack details $policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id); - $policy_type = $policy_terms[0]->is_addon; - $base_policy = $policy_terms[0]->base_policy; + $policy_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 + //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 + 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; + $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']); } @@ -2264,7 +2191,6 @@ class EmployeeRestController extends AdminController $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) { @@ -2283,11 +2209,9 @@ class EmployeeRestController extends AdminController } } - - public function getHRAccessData($hr_id = null, $request_for = 'post_enrollment') { - $hr_id = $this->request->getGet('hr_id') ?? $hr_id; + $hr_id = $this->request->getGet('hr_id') ?? $hr_id; $request_for = $this->request->getGet('request_for') ?? $request_for; if ($request_for == 'pre_enrollment') { @@ -2308,11 +2232,11 @@ class EmployeeRestController extends AdminController public function getPolicyLevelEmployeeSummaryData() { - $hr_id = $this->request->getGet('hr_id'); + $hr_id = $this->request->getGet('hr_id'); $HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment'); if (isset($HRAccessData['allowed_active_policies'])) { - $policyId = json_decode($HRAccessData['allowed_active_policies'], true); + $policyId = json_decode($HRAccessData['allowed_active_policies'], true); } else { $policyId = []; } @@ -2321,32 +2245,31 @@ class EmployeeRestController extends AdminController return $this->respond(['status' => 'failed', 'code' => (count($policyId) ? 200 : 404), 'data' => []], 200); } - - if($this->request->getGet('policy_status') == 0){ + if ($this->request->getGet('policy_status') == 0) { $emp_policy_status = 'expired'; - }else{ + } else { $emp_policy_status = 'active'; } - $db = \Config\Database::connect(); + $db = \Config\Database::connect(); $emp_policy_status = $db->escape($emp_policy_status); $ClientPolicyData = $this->clientPolicyModel ->select(" - client_policy.id as client_policy_id , - client_policy.client_id as client_id, - client_policy.policy_type_id as policy_type_id, - client_policy.is_addon as is_addon , - client_policy.open_for_enrollment as OpenForEnrollment , - client_policy.inception_type as inception_type, - client_policy.policy_no as policy_no, - client_policy.insurer_id as insurer_id, + client_policy.id as client_policy_id , + client_policy.client_id as client_id, + client_policy.policy_type_id as policy_type_id, + client_policy.is_addon as is_addon , + client_policy.open_for_enrollment as OpenForEnrollment , + client_policy.inception_type as inception_type, + client_policy.policy_no as policy_no, + client_policy.insurer_id as insurer_id, DATE_FORMAT(client_policy.policy_start_date, '%d-%m-%Y') AS policy_start_date, DATE_FORMAT(client_policy.policy_end_date, '%d-%m-%Y') AS policy_expiry_date, ( - select COALESCE(ROUND(SUM(rata_premimum + gst)), 0) - from employee_polices - where is_active = 1 + select COALESCE(ROUND(SUM(rata_premimum + gst)), 0) + from employee_polices + where is_active = 1 and status = $emp_policy_status and client_policy_id = client_policy.id ) as total_premium @@ -2358,22 +2281,21 @@ class EmployeeRestController extends AdminController ->whereIn('client_policy.id', $policyId) ->findAll(); - $result = []; // dd( $ClientPolicyData); foreach ($ClientPolicyData as $key => $value) { $policyTypeData = $this->policyTypeModel->where('id', $value['policy_type_id'])->get()->getRow(); - $insurerData = $this->insurerModel->where('id', $value['insurer_id'])->get()->getRow(); + $insurerData = $this->insurerModel->where('id', $value['insurer_id'])->get()->getRow(); - $value['type'] = $policyTypeData->policy_type; - $value['policy_name'] = $policyTypeData->long_name; - $value['insurer_name'] = $insurerData->name; + $value['type'] = $policyTypeData->policy_type; + $value['policy_name'] = $policyTypeData->long_name; + $value['insurer_name'] = $insurerData->name; $value['insurer_short_name'] = $insurerData->short_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'), status_type: 'inactive'); + $employeeDetails = $this->employeePolicyModel->getEmployeePolicy(client_id: $value['client_id'], policy_id: $value['client_policy_id'], status: 0, branch_id: $this->request->getGet('client_branch_id'), status_type: 'inactive'); // dd($employeeDetails); - $activeCount = 0; + $activeCount = 0; $inactiveCount = 0; - if (count($employeeDetails)) { + if (count($employeeDetails)) { foreach ($employeeDetails as $item) { if ($item['status'] === 'active') { $activeCount++; @@ -2383,18 +2305,15 @@ class EmployeeRestController extends AdminController } } - $value['totalMembersCount'] = count($employeeDetails); - $value['membersCountOfActive'] = $activeCount; - $value['membersCountOfInactive'] = $inactiveCount; - $value['is_ecard_bulk_download'] = 0; + $value['totalMembersCount'] = count($employeeDetails); + $value['membersCountOfActive'] = $activeCount; + $value['membersCountOfInactive'] = $inactiveCount; + $value['is_ecard_bulk_download'] = 0; $value['is_ecard_bulk_download_for_employee'] = 0; - array_push($result, $value); } - - if ($result) { return $this->respond(['status' => 'success', 'code' => (count($result) ? 200 : 404), 'data' => $result], 200); } else { @@ -2402,19 +2321,18 @@ class EmployeeRestController extends AdminController } } - public function cdSummaryData() { - $hr_id = $this->request->getGet('hr_id'); + $hr_id = $this->request->getGet('hr_id'); $HRAccessData = $this->getHRAccessData($hr_id, 'post_enrollment'); // print_rr($HRAccessData);die(); if (isset($HRAccessData['allowed_cd'])) { - $allowed_cd = json_decode($HRAccessData['allowed_cd'], true); + $allowed_cd = json_decode($HRAccessData['allowed_cd'], true); } else { $allowed_cd = []; } - // $allowed_cd = [125]; + // $allowed_cd = [125]; // print_r($allowed_cd);die(); if (count($allowed_cd) == 0) { return $this->respond(['status' => 'failed', 'code' => (count($allowed_cd) ? 200 : 404), 'data' => []], 200); @@ -2423,21 +2341,20 @@ class EmployeeRestController extends AdminController $clientId = $this->request->getGet('client_id'); $clientController = new ClientController; - $result = $clientController->deposit($clientId, $requestFrom = 'rest', []); + $result = $clientController->deposit($clientId, $requestFrom = 'rest', []); // print_rr($result);die(); $data = []; - foreach ($result['clientData'] as $key => $value) { if (in_array($value->cd_ac_pk, $allowed_cd)) { - $temp['client_id'] = $value->client_id; - $temp['insurer_id'] = $value->insurer_id; - $temp['cd_ac_pk'] = $value->cd_ac_pk; - $temp['insurer_name'] = $value->insurer_name; + $temp['client_id'] = $value->client_id; + $temp['insurer_id'] = $value->insurer_id; + $temp['cd_ac_pk'] = $value->cd_ac_pk; + $temp['insurer_name'] = $value->insurer_name; $temp['cd_master_account_no'] = $value->cd_master_account_no; if (isset($result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']])) { - $balance = $result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']]->balance; + $balance = $result['balances'][$temp['insurer_id'] . '-' . $temp['cd_ac_pk']]->balance; $temp['balance'] = $balance; } else { $temp['balance'] = "N/A"; @@ -2447,7 +2364,6 @@ class EmployeeRestController extends AdminController } } - if ($data) { return $this->respond(['status' => 'success', 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); } else { @@ -2458,22 +2374,21 @@ class EmployeeRestController extends AdminController public function cdTransactionData() { - $clientId = $this->request->getGet('client_id'); - $insurerId = $this->request->getGet('insurer_id'); + $clientId = $this->request->getGet('client_id'); + $insurerId = $this->request->getGet('insurer_id'); $cdAccountPrimaryKey = $this->request->getGet('cd_ac_pk'); $clientController = new ClientController; - $result = $clientController->view_Deposit($insurerId, $requestFrom = 'rest', $param = ['client_id' => $clientId, 'cd_ac_pk' => $cdAccountPrimaryKey]); + $result = $clientController->view_Deposit($insurerId, $requestFrom = 'rest', $param = ['client_id' => $clientId, 'cd_ac_pk' => $cdAccountPrimaryKey]); - $data['insurer_name'] = $result['insurerName']->name; + $data['insurer_name'] = $result['insurerName']->name; $data['insurer_short_name'] = $result['insurerName']->short_name; - $data['account_number'] = $result['insurerName']->cd_master_account_no; - $data['total_deposit'] = $result['deposiamount']->total_credit; - $data['total_consumed'] = $result['deposiamount']->total_withdraw; - $data['total_refund'] = $result['deposiamount']->total_refund; - $data['currect_balance'] = $result['deposiamount']->balance; - $data['deposit_data'] = $result['depositdata']; - + $data['account_number'] = $result['insurerName']->cd_master_account_no; + $data['total_deposit'] = $result['deposiamount']->total_credit; + $data['total_consumed'] = $result['deposiamount']->total_withdraw; + $data['total_refund'] = $result['deposiamount']->total_refund; + $data['currect_balance'] = $result['deposiamount']->balance; + $data['deposit_data'] = $result['depositdata']; // dd($data); @@ -2484,20 +2399,19 @@ class EmployeeRestController extends AdminController } } - public function claimsSearch() { if ($this->request->is('get')) { $data['claim_status'] = $this->claimStatusModel - ->select('id,ticket_type, display_name as claim_status') - ->where('is_active', 1) - ->where('display_name IS NOT NULL OR display_name <> ""') - ->groupBy('display_name') - ->findAll(); - - $data['ticket_type'] = [ + ->select('id,ticket_type, display_name as claim_status') + ->where('is_active', 1) + ->where('display_name IS NOT NULL OR display_name <> ""') + ->groupBy('display_name') + ->findAll(); + + $data['ticket_type'] = [ ["ticket_type" => "1", "type_name" => "Claim-GMC"], ["ticket_type" => "2", "type_name" => "Claim-GPA"], ["ticket_type" => "3", "type_name" => "EDLI"], @@ -2511,33 +2425,32 @@ class EmployeeRestController extends AdminController $search_data = $this->request->getJSON(true); // Get JSON as associative array - if ( isset($search_data['client_id']) &&is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) { - $client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first(); + if (isset($search_data['client_id']) && is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) { + $client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first(); $search_data['client_id'] = $client_data['id'] ?? null; - } - + } $client_id = isset($search_data['client_id']) ? (int) $search_data['client_id'] : 0; unset($search_data['client_id']); unset($search_data['client_branch_id']); $policy_number = isset($search_data['policy_no']) ? $search_data['policy_no'] : null; - $from_date = isset($search_data['from_date']) ? $search_data['from_date'] : null; - $to_date = isset($search_data['to_date']) ? $search_data['to_date'] : null; - $claim_status_id = isset($search_data['claim_status_id']) ? $search_data['claim_status_id'] : null; + $from_date = isset($search_data['from_date']) ? $search_data['from_date'] : null; + $to_date = isset($search_data['to_date']) ? $search_data['to_date'] : null; + $claim_status_id = isset($search_data['claim_status_id']) ? $search_data['claim_status_id'] : null; unset($search_data['from_date'], $search_data['to_date'], $search_data['claim_status_id'], $search_data['policy_no']); $where = []; // Dynamically build WHERE conditions from non-empty parameters foreach ($search_data as $key => $value) { - if (!empty($value) && $value !== 0 && $value !== '0') { + if (! empty($value) && $value !== 0 && $value !== '0') { $where["tm.$key"] = $value; } } $claim_status_ids = []; - if(!empty($claim_status_id)){ + if (! empty($claim_status_id)) { $claim_status_ids = $this->getTicketClaimStatusIdBasedOnTheDisplayName($claim_status_id); } @@ -2546,14 +2459,14 @@ class EmployeeRestController extends AdminController 'tm.id', 'tm.ticket_type_id', 'tcs.claim_status AS original_status', - "CASE - WHEN tcs.display_name IS NULL OR tcs.display_name = '' + "CASE + WHEN tcs.display_name IS NULL OR tcs.display_name = '' THEN tcs.claim_status ELSE UPPER(tcs.display_name) END AS status ", - "CASE - WHEN tm.tpa_claim_type IS NOT NULL OR tm.tpa_claim_type != '' + "CASE + WHEN tm.tpa_claim_type IS NOT NULL OR tm.tpa_claim_type != '' THEN tm.tpa_claim_type ELSE 'Reimbursement' END AS cl_type @@ -2631,21 +2544,21 @@ class EmployeeRestController extends AdminController $builder->where('tm.client_id', $client_id); } - if (!empty($from_date) && !empty($to_date)) { + if (! empty($from_date) && ! empty($to_date)) { $from_date_mysql = date('Y-m-d', strtotime($from_date)); - $to_date_mysql = date('Y-m-d', strtotime($to_date)); + $to_date_mysql = date('Y-m-d', strtotime($to_date)); $builder->where("DATE(tm.created_at) BETWEEN '$from_date_mysql' AND '$to_date_mysql'"); } - if (!empty($where)) { + if (! empty($where)) { $builder->where($where); } - if (!empty($claim_status_ids)) { + if (! empty($claim_status_ids)) { $builder->whereIn('claim_status_id', $claim_status_ids); } - if (!empty($policy_number)) { + if (! empty($policy_number)) { $builder->where('cp.policy_no', $policy_number); } @@ -2660,21 +2573,21 @@ class EmployeeRestController extends AdminController { try { - $ticket_id = $this->request->getGet('ticket_id'); - $ticketController = new TicketController; - $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); - $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); - $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); + $ticket_id = $this->request->getGet('ticket_id'); + $ticketController = new TicketController; + $data['ticket_history'] = $ticketController->ticketHistory($ticket_id); + $data['claims_data'] = $this->ticketMaster->getTicketDataByTicketID($ticket_id); + $data['ticket_data'] = $ticketController->getMoreInfo($requestFrom = 'rest', $ticket_id); - $required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first(); + $required_docs = $this->ticketMaster->select('required_docs')->where('id', $ticket_id)->first(); $data['required_docs'] = json_decode($required_docs['required_docs'] ?? '{}', true) ?? []; // $ticketData = $data['ticket_data']; // $ticketHistory = $data['ticket_history']; // print_r($ticketHistory); die; $currentClaimStatus = $this->claimStatusModel->select("claim_status")->where('id', $data['claims_data']['claim_status_id'])->where('is_active', 1)->first(); - $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('ticket_type', $data['claims_data']['ticket_type_id'])->where('is_active', 1)->findAll(); - $status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status'); + $ticketClaimStatus = $this->claimStatusModel->select('claim_status, display_name')->where('display_name is not null')->where('ticket_type', $data['claims_data']['ticket_type_id'])->where('is_active', 1)->findAll(); + $status_list = array_column($ticketClaimStatus, 'display_name', 'claim_status'); // print_r($currentClaimStatus); die; $data['ticket_data'] = array_fill_keys(array_keys($data['ticket_data']), []); @@ -2703,15 +2616,15 @@ class EmployeeRestController extends AdminController foreach ($data['ticket_data'] as $oldKey => $value) { // Only process if key exists in status_list - if (!isset($status_list[$oldKey])) { - continue; // skip and do NOT add to new array + if (! isset($status_list[$oldKey])) { + continue; // skip and do NOT add to new array } // Get new key based on mapping $newKey = $status_list[$oldKey]; // Avoid duplicates - if (!isset($new_ticket_data[$newKey])) { + if (! isset($new_ticket_data[$newKey])) { $new_ticket_data[$newKey] = $value; } } @@ -2719,14 +2632,13 @@ class EmployeeRestController extends AdminController uasort($new_ticket_data, function ($a, $b) { $timeA = \DateTime::createFromFormat('d-m-Y h:i A', $a['modified_at']); $timeB = \DateTime::createFromFormat('d-m-Y h:i A', $b['modified_at']); - return $timeA <=> $timeB; // Ascending + return $timeA <=> $timeB; // Ascending }); $data['ticket_data'] = $new_ticket_data; - $ticketMesssageModel = new TicketMessageModel(); - $ticket_message = $ticketMesssageModel + $ticket_message = $ticketMesssageModel ->where('is_active', 1) ->where('sender', "user") ->where('ticket_id', $ticket_id) @@ -2737,7 +2649,7 @@ class EmployeeRestController extends AdminController if (isset($ticket_message['id'])) { - $claimFiles = new ClaimFilesModel(); + $claimFiles = new ClaimFilesModel(); $claim_files_data = $claimFiles ->select('id as claim_file_id, doc_name as claim_file_name') ->where('is_active', 1) @@ -2747,7 +2659,7 @@ class EmployeeRestController extends AdminController ->findAll(); foreach ($claim_files_data as &$value) { - $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; + $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; $claim_file_urls[] = $value; } unset($value); @@ -2755,25 +2667,24 @@ class EmployeeRestController extends AdminController $data['claim_files'] = $claim_file_urls; - return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data,], 200); + return $this->respond(['status' => (count($data) ? 'success' : 'failed'), 'code' => (count($data) ? 200 : 404), 'data' => $data], 200); } catch (\Throwable $th) { - $this->myLogger->logme("error", 'claim_view' .($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString())); + $this->myLogger->logme("error", 'claim_view' . ($th->getMessage() . ' --- ' . $th->getLine() . '----' . $th->getTraceAsString())); $errorData = [ - 'message' => $th->getMessage(), - 'file' => $th->getFile(), - 'line' => $th->getLine(), - 'code' => $th->getCode(), - 'trace' => $th->getTraceAsString(), + '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, + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, ]; - return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'error_data' => $errorData], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => "", 'error_data' => $errorData], 500); } } - public function exportCashDepositData() { @@ -2784,13 +2695,13 @@ class EmployeeRestController extends AdminController 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', + 'Date' => 'created_at', + 'Type' => 'transaction_type', + 'Amount' => 'amount', + 'Balance' => 'balance', + 'Description' => 'description', 'Insurer Name' => 'insurer_name', - 'Client Name' => 'clientname' + 'Client Name' => 'clientname', ]; // Create a new Spreadsheet object @@ -2817,9 +2728,8 @@ class EmployeeRestController extends AdminController $row++; } - // Set the header for download - $filename = $CashDepositData[0]->insurer_name . '-CashDeposit.xlsx'; + $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'); @@ -2836,7 +2746,6 @@ class EmployeeRestController extends AdminController } } - public function removeEmpAndEmpPolicyData() { try { @@ -2846,7 +2755,6 @@ class EmployeeRestController extends AdminController if (count($clientPolicy)) { - if ($clientPolicy[0]['is_addon'] == 2) //Topup { @@ -2867,7 +2775,7 @@ class EmployeeRestController extends AdminController $this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id')) ->where('employee_id', $value['id']) - ->set(array('is_active' => 0)) + ->set(['is_active' => 0]) ->update(); } } @@ -2880,19 +2788,17 @@ class EmployeeRestController extends AdminController $this->employeePolicyModel->where('client_policy_id', $this->request->getGet('client_policy_id')) ->where('employee_id', $value['id']) - ->set(array('is_active' => 0)) + ->set(['is_active' => 0]) ->update(); } $this->employeeModel->where('emp_code', $this->request->getGet('emp_code')) ->where('is_active', 1)->where('is_addon_value', 1) - ->set(array('is_active' => 0)) + ->set(['is_active' => 0]) ->update(); } } - - return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } else { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); @@ -2902,42 +2808,41 @@ class EmployeeRestController extends AdminController } } - - function getEmployeeActiveOrInactivePolicy() - { + public function getEmployeeActiveOrInactivePolicy() + { // for retail user policy only $receviedPayload = $this->request->getGet(); - if( - empty($receviedPayload['client_id']) && - empty($receviedPayload['client_branch_id']) && + if ( + empty($receviedPayload['client_id']) && + empty($receviedPayload['client_branch_id']) && empty($receviedPayload['emp_code']) - ){ - - if(!empty($receviedPayload['mobile_no']) || !empty($receviedPayload['email_id'])){ - + ) { + + if (! empty($receviedPayload['mobile_no']) || ! empty($receviedPayload['email_id'])) { + $retailUserData = (object) [ - 'id' => null, - 'mobile' => $receviedPayload['mobile_no'], - 'email_id' => $receviedPayload['email_id'] + 'id' => null, + 'mobile' => $receviedPayload['mobile_no'], + 'email_id' => $receviedPayload['email_id'], ]; $emp_reatail_policy_data = $this->getEmpRetailPolicy($retailUserData); - $wellness_data = ['status' => 'failed','message' => 'Coming soon........!']; + $wellness_data = ['status' => 'failed', 'message' => 'Coming soon........!']; return $this->respond(['status' => 'success', 'code' => 200, 'data' => [], 'emp_name' => $emp_reatail_policy_data[0]['insurerd_name'] ?? "", 'pre_policy_count' => 0, 'emp_not_enrolled_count' => 0, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $wellness_data], 200); } } if ($this->request->getGet('type') == 'Active') { - $policy_status = 1; + $policy_status = 1; $policy_status_key = "Active"; } else { - $policy_status = 0; + $policy_status = 0; $policy_status_key = "InActive"; } - $dayInterval = 10; - $ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date") + $dayInterval = 10; + $ClientPolicyData = $this->clientPolicyModel->select("client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url, policy_type.long_name as policy_long_name, DATE_ADD(client_policy.policy_end_date, INTERVAL {$dayInterval} DAY) as claims_grace_date") ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') @@ -2961,21 +2866,20 @@ class EmployeeRestController extends AdminController ->where('family_floater_key', 'self')->where('is_active', 1) ->get()->getRow(); - $employeeName = $employeeSelfData->name ?? ""; - + $employeeName = $employeeSelfData->name ?? ""; //for get the pre enrollment policy count $empMobileNo = $this->request->getGet('mobile_no'); - $clientId = $this->request->getGet('client_id'); + $clientId = $this->request->getGet('client_id'); - if (!empty($employeeSelfData) && isset($employeeSelfData->email_corporate)) { - $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate); - $prePolicyCount = $prePolicyCountData['pre_policy_count'] ?? 0; - $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; + if (! empty($employeeSelfData) && isset($employeeSelfData->email_corporate)) { + $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId, $employeeSelfData->email_corporate); + $prePolicyCount = $prePolicyCountData['pre_policy_count'] ?? 0; + $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; } else { - $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId); - $prePolicyCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; - $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; + $prePolicyCountData = $this->getPreEmployeePolicyCount($empMobileNo, $clientId); + $prePolicyCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; + $empNotEnrolledCount = $prePolicyCountData['emp_not_enrolled_count'] ?? 0; } $whereArrayForId = []; @@ -2992,55 +2896,54 @@ class EmployeeRestController extends AdminController } if ($ClientPolicyValue['policy_type_id'] == 1) { - $policyGroup = 'gpa'; - $data['ticket_type_id'] = 2; + $policyGroup = 'gpa'; + $data['ticket_type_id'] = 2; $data['ticket_settled_status_id'] = 24; - $data['claim_subject'] = "Claim GPA"; - $data['sum_insured_label'] = "Sum Assured"; + $data['claim_subject'] = "Claim GPA"; + $data['sum_insured_label'] = "Sum Assured"; } else if ($ClientPolicyValue['policy_type_id'] == 6) { - $policyGroup = 'other'; - $data['ticket_type_id'] = 3; + $policyGroup = 'other'; + $data['ticket_type_id'] = 3; $data['ticket_settled_status_id'] = 34; - $data['claim_subject'] = "Claim EDLI"; - $data['sum_insured_label'] = "Sum Assured"; + $data['claim_subject'] = "Claim EDLI"; + $data['sum_insured_label'] = "Sum Assured"; } else if ($ClientPolicyValue['policy_type_id'] == 7) { - $policyGroup = 'other'; - $data['ticket_type_id'] = 4; + $policyGroup = 'other'; + $data['ticket_type_id'] = 4; $data['ticket_settled_status_id'] = 44; - $data['claim_subject'] = "Claim GTLI"; - $data['sum_insured_label'] = "Sum Assured"; - } else if ($ClientPolicyValue['policy_type_id'] == 72){ - $policyGroup = 'other'; - $data['ticket_type_id'] = 72; + $data['claim_subject'] = "Claim GTLI"; + $data['sum_insured_label'] = "Sum Assured"; + } else if ($ClientPolicyValue['policy_type_id'] == 72) { + $policyGroup = 'other'; + $data['ticket_type_id'] = 72; $data['ticket_settled_status_id'] = 76; - $data['claim_subject'] = "Claim OPD"; - $data['sum_insured_label'] = "Sum Insured"; + $data['claim_subject'] = "Claim OPD"; + $data['sum_insured_label'] = "Sum Insured"; } else { - $policyGroup = 'gmc'; - $data['ticket_type_id'] = 1; + $policyGroup = 'gmc'; + $data['ticket_type_id'] = 1; $data['ticket_settled_status_id'] = 11; - $data['claim_subject'] = "Claim GMC"; - $data['sum_insured_label'] = "Sum Insured"; + $data['claim_subject'] = "Claim GMC"; + $data['sum_insured_label'] = "Sum Insured"; } - $terms = json_decode($ClientPolicyValue['policy_terms'], true); - $data['policy_terms'] = isset($terms['enrollment_display_key']) && !empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup); + $terms = json_decode($ClientPolicyValue['policy_terms'], true); + $data['policy_terms'] = isset($terms['enrollment_display_key']) && ! empty($terms['enrollment_display_key']) ? $terms['enrollment_display_key'] : $this->policyTermsFiter($terms, $policyGroup); - - $data['client_id'] = $ClientPolicyValue['client_id']; - $data['client_policy_id'] = $ClientPolicyValue['id']; - $data['policy_name'] = $ClientPolicyValue['policy_type']; - $data['policy_type'] = $ClientPolicyValue['policy_type']; - $data['policy_no'] = $ClientPolicyValue['policy_no']; - $data['insurer_name'] = $ClientPolicyValue['insurer_name']; - $data['tpa_name'] = $ClientPolicyValue['tpa_name']; - $data['network_hospitals_url'] = $ClientPolicyValue['network_hospitals_url']; - $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); - $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); - $data['heading'] = $ClientPolicyValue['policy_long_name']; - $data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']); - $data['policy_status'] = $policy_status_key; - $data['pre_policy_count'] = $prePolicyCount; + $data['client_id'] = $ClientPolicyValue['client_id']; + $data['client_policy_id'] = $ClientPolicyValue['id']; + $data['policy_name'] = $ClientPolicyValue['policy_type']; + $data['policy_type'] = $ClientPolicyValue['policy_type']; + $data['policy_no'] = $ClientPolicyValue['policy_no']; + $data['insurer_name'] = $ClientPolicyValue['insurer_name']; + $data['tpa_name'] = $ClientPolicyValue['tpa_name']; + $data['network_hospitals_url'] = $ClientPolicyValue['network_hospitals_url']; + $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']); + $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']); + $data['heading'] = $ClientPolicyValue['policy_long_name']; + $data['claims_grace_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['claims_grace_date']); + $data['policy_status'] = $policy_status_key; + $data['pre_policy_count'] = $prePolicyCount; $data['emp_not_enrolled_count'] = $empNotEnrolledCount; // $data['policy_terms'] = $terms; @@ -3068,9 +2971,9 @@ class EmployeeRestController extends AdminController ->where('employee_polices.client_policy_id', $ClientPolicyValue['id']) ->where('employee_polices.is_active', 1)->findAll(); if (count($employee_policy) > 0) { - $si_value = 0; + $si_value = 0; $si_premium_value = 0; - $si_gst_value = 0; + $si_gst_value = 0; foreach ($employee_policy as $key => $value) { if (isset($value['basic_cover_si'])) { @@ -3084,30 +2987,28 @@ class EmployeeRestController extends AdminController } } - - if ($employee_policy[0]['tpa_id'] != null) + if ($employee_policy[0]['tpa_id'] != null) { $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1'; - else + } 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['si_value'] = $si_value; + $data['si_premium_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_premium_value); + $data['si_gst_value'] = ($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 2) ? 0 : round($si_gst_value); $data['EmployeePolicy'] = $employee_policy; //fetch claims data - $approvedClaimsAmount = $this->ticketMaster - ->select('SUM(approved_amount) AS total_settled_amount') - ->where('emp_code', $employee_policy[0]['emp_code']) - ->where('client_policy_id', $data['client_policy_id']) - ->where('claim_status_id', $data['ticket_settled_status_id']) - ->groupBy('emp_code') - ->groupBy('client_policy_id') - ->groupBy('claim_status_id') - ->get()->getRow(); + $approvedClaimsAmount = $this->ticketMaster + ->select('SUM(approved_amount) AS total_settled_amount') + ->where('emp_code', $employee_policy[0]['emp_code']) + ->where('client_policy_id', $data['client_policy_id']) + ->where('claim_status_id', $data['ticket_settled_status_id']) + ->groupBy('emp_code') + ->groupBy('client_policy_id') + ->groupBy('claim_status_id') + ->get()->getRow(); $data['total_settled_amount'] = $approvedClaimsAmount ? ($approvedClaimsAmount->total_settled_amount ?? 0) : 0; array_push($result, $data); } @@ -3115,8 +3016,8 @@ class EmployeeRestController extends AdminController } $emp_reatail_policy_data = $this->getEmpRetailPolicy($employeeSelfData); - $apiServiceController = new ApiServiceController; - $emp_wellness_data = $apiServiceController->getWellnessUrl($employeeSelfData->id ?? null); + $apiServiceController = new ApiServiceController; + $emp_wellness_data = $apiServiceController->getWellnessUrl($employeeSelfData->id ?? null); return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result, 'emp_name' => $employeeName, 'pre_policy_count' => $prePolicyCount, 'emp_not_enrolled_count' => $empNotEnrolledCount, 'retail_policy_data' => $emp_reatail_policy_data, 'wellness_data' => $emp_wellness_data], 200); } else { @@ -3124,60 +3025,59 @@ class EmployeeRestController extends AdminController } } - - function policyTermsFiter($terms, $type) + public function policyTermsFiter($terms, $type) { if (empty($terms)) { return []; } $gpa = [ - "sumInsured2" => "Sum Insured", - "totalSumInsured" => "Total Sum Assured", - "self" => "Self", - "self_min_age" => "Min Age", - "self_max_age" => "Max Age", - "accidentalDeathBenefit" => "Accidental Death Benefit", - "permanentTotalDisablement" => "Permanent Total Disablement", - "permanentPartialDisablement" => "Permanent Partial Disablement", - "temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit", + "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" + "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", + "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 " + "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 = []; @@ -3202,7 +3102,7 @@ class EmployeeRestController extends AdminController } else if ($type == 'other') { foreach ($terms as $key => $value) { if ($key != "multiple_sum_insured" && $value != "") { - $result = ucwords(str_replace('_', ' ', $key)); + $result = ucwords(str_replace('_', ' ', $key)); $finalarray[$result] = $value; } } @@ -3234,7 +3134,6 @@ class EmployeeRestController extends AdminController return $finalarray; } - private function convertDateFormatDisplay($dateString) { // Attempt to create a DateTime object from the provided date string @@ -3251,7 +3150,7 @@ class EmployeeRestController extends AdminController { try { - $feContentData = $this->feContentModel->where('is_active',1)->findAll(); + $feContentData = $this->feContentModel->where('is_active', 1)->findAll(); if (count($feContentData) > 0) { return $this->respond(['status' => 'success', 'code' => 200, 'data' => $feContentData], 200); @@ -3306,7 +3205,7 @@ class EmployeeRestController extends AdminController } // prepare URLs - $data = array_map(function($img){ return base_url('public/uploads/add_image_upload/' . $img['name']); }, $images); + $data = array_map(function ($img) {return base_url('public/uploads/add_image_upload/' . $img['name']);}, $images); return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data], 200); @@ -3321,41 +3220,40 @@ class EmployeeRestController extends AdminController 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; + $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 + // 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)) { + 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']; + $id = $employee['id']; // return json_encode($data); // Direct database update query for testing - $db = \Config\Database::connect(); - $builder = $db->table('employees'); + $db = \Config\Database::connect(); + $builder = $db->table('employees'); $update_emp = $builder->update($data, ['id' => $id]); // Check if the update was successful if ($db->affectedRows() > 0) { // Fetch the updated employee data - $updated_employee = $this->employeeModel->find((int)$id); + $updated_employee = $this->employeeModel->find((int) $id); return $this->respond(['status' => 'success', 'code' => 200, 'data' => $updated_employee], 200); } else { log_message('error', 'Update failed. No rows affected.'); @@ -3376,10 +3274,6 @@ class EmployeeRestController extends AdminController } } - - - - // public function sendPushNotification() // { // $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H'; @@ -3404,26 +3298,24 @@ class EmployeeRestController extends AdminController // } // } - public function getBackToEnrolledDetails() { // Get query parameters - $empCode = $this->request->getGet('emp_code'); - $clientId = $this->request->getGet('client_id'); + $empCode = $this->request->getGet('emp_code'); + $clientId = $this->request->getGet('client_id'); $clientBranchId = $this->request->getGet('client_branch_id'); - - if (!$empCode || !$clientId || !$clientBranchId) { + 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, + 'emp_code' => $empCode, + 'client_id' => $clientId, 'client_branch_id' => $clientBranchId, - 'is_active' => 1 + 'is_active' => 1, ]) ->findAll(); @@ -3431,20 +3323,18 @@ class EmployeeRestController extends AdminController $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; - + $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(); - + $policies = $this->employeePolicyModel->whereIn('employee_id', $employeeIds)->where('is_active', 1)->findAll(); //Find the stage of enrolment process - $employeeStatuses = array_column($employees, 'emp_status'); + $employeeStatuses = array_column($employees, 'emp_status'); $employeePolicyStatuses = array_column($policies, 'status'); - $uniqueStatuses = array_unique(array_merge($employeeStatuses, $employeePolicyStatuses)); + $uniqueStatuses = array_unique(array_merge($employeeStatuses, $employeePolicyStatuses)); if (count($uniqueStatuses) > 1) { $enrolmentStagekey = 1; @@ -3456,53 +3346,55 @@ class EmployeeRestController extends AdminController } } - $enrolmentStage = ['Draft Only', 'Intermittent Enrollment', 'Successful Enrollment']; + $enrolmentStage = ['Draft Only', 'Intermittent Enrollment', 'Successful Enrollment']; $data['enrolment_stage'] = $enrolmentStage[$enrolmentStagekey]; - - - $data['revert_employee_data'] = []; + $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); + $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) + 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, + 'emp_code' => $empCode, + 'client_id' => $clientId, 'client_branch_id' => $clientBranchId, - 'is_active' => 0 + '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) + 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(); + $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) + 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'])) { @@ -3518,43 +3410,39 @@ class EmployeeRestController extends AdminController } //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(); + $this->employeeModel->where('id', $data['self_employee_id'])->set(['emp_status' => 'enrolled'])->update(); $data['retrieve_status'] = 'Data revert successfully'; } else { $data['retrieve_status'] = 'There is no data to revert'; } } - - - - // Fetch all policies related to these employees who currently active $current_employee_data = $this->employeeModel->select('id,emp_code,name,relationship,dob,emp_status,is_addon_value,created_at,updated_at') ->where([ - 'emp_code' => $empCode, - 'client_id' => $clientId, + 'emp_code' => $empCode, + 'client_id' => $clientId, 'client_branch_id' => $clientBranchId, - 'is_active' => 1 + 'is_active' => 1, ]) ->findAll(); - $Ids = array_column($current_employee_data, 'id'); + $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])) { + if (! isset($groupedPolicies[$policyId])) { $groupedPolicies[$policyId] = [ - 'policy_id' => $policy['id'], + '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' => [] + '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' => [], ]; } @@ -3562,13 +3450,13 @@ class EmployeeRestController extends AdminController 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'] + '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'], ]; } } @@ -3586,7 +3474,7 @@ class EmployeeRestController extends AdminController $historyData = $this->auditHistoryModel->where('pk', $pk)->where('table_name', $table)->findAll(); $beforeEnrolled = []; - $afterEnrolled = []; + $afterEnrolled = []; // Split the array foreach ($historyData as $val) { if ($val['created_at'] <= $self_enrolled_time) { @@ -3599,46 +3487,47 @@ class EmployeeRestController extends AdminController if (count($beforeEnrolled) && count($afterEnrolled)) { //After enrolment edited some of the data $temp['table'] = $table; - $temp['id'] = $pk; + $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])) { + 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 + } else if (! count($beforeEnrolled) && ! count($afterEnrolled)) { //After enrolment created new data $temp['table'] = $table; - $temp['id'] = $pk; - $temp['data'] = ['is_active' => 0]; + $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 + } 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]; + $temp['id'] = $pk; + $temp['data'] = ['is_active' => 0]; return $temp; - } else if (count($beforeEnrolled) && !count($afterEnrolled)) { //After enrolment nothing changes from the data + } else if (count($beforeEnrolled) && ! count($afterEnrolled)) { //After enrolment nothing changes from the data return false; } } - public function findThePolicyIsOpenForEnrollment($plicy_id) { $policy = $this->clientPolicyModel->where('id', $plicy_id)->where('open_for_enrollment', 1)->find(); - if ($policy) + if ($policy) { return true; - else + } else { return false; + } + } // ---------------- TICKET API's --------------------------------------------------------------------------------------------------- @@ -3649,54 +3538,52 @@ class EmployeeRestController extends AdminController $received_data = $this->request->getPost(); $this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? [])); - $get_file_data = $this->request->getFiles('claim_docs') ?? null; - $get_docs_name = $this->request->getPost('claim_doc_names') ?? []; + $get_file_data = $this->request->getFiles('claim_docs') ?? null; + $get_docs_name = $this->request->getPost('claim_doc_names') ?? []; $policy_transaction_id = $this->request->getPost('policy_transaction_id') ?? null; - if (is_string($received_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $received_data['client_id'])) { - $client_data = $this->clientModel->where('MD5(id)', $received_data['client_id'])->first(); + $client_data = $this->clientModel->where('MD5(id)', $received_data['client_id'])->first(); $received_data['client_id'] = $client_data['id'] ?? null; - } + } $client_policy_data = $this->clientPolicyModel->where('id', $received_data['client_policy_id'] ?? null)->first(); $isduplicate = checkDuplicateClaim([ - 'doa' => change_date_format($received_data['doa'] ?? '') ?? null, - 'emp_code' => $received_data['emp_code'] ?? null, - 'claim_amount' => $received_data['claim_amount'] ?? null, - 'policy_no' => $client_policy_data['policy_no'] ?? null + 'doa' => change_date_format($received_data['doa'] ?? '') ?? null, + 'emp_code' => $received_data['emp_code'] ?? null, + 'claim_amount' => $received_data['claim_amount'] ?? null, + 'policy_no' => $client_policy_data['policy_no'] ?? null, ]); - if($isduplicate){ + if ($isduplicate) { $response = ['status' => false, 'code' => 404, 'message' => 'Claim already exist']; return $this->respond($response, 200); } - if(!empty($policy_transaction_id)){ - $response = $this->retailClaimInitiate($received_data); + if (! empty($policy_transaction_id)) { + $response = $this->retailClaimInitiate($received_data); return $this->respond($response, 200); } if (is_string($get_docs_name)) { - $decoded = json_decode($get_docs_name, true); + $decoded = json_decode($get_docs_name, true); $get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : []; - } elseif (!is_array($get_docs_name)) { + } elseif (! is_array($get_docs_name)) { $get_docs_name = []; } // print_r($get_file_data); die; - $employee_id = $received_data['emp_id']; + $employee_id = $received_data['emp_id']; $client_policy_id = $received_data['client_policy_id']; - $insured_emp_id = $received_data['insured_emp_id']; + $insured_emp_id = $received_data['insured_emp_id']; $file_data = []; - if (isset($get_file_data) && !empty($get_file_data)) { - $file_path = WRITEPATH . 'uploads/claim_files/'; - $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); + if (isset($get_file_data) && ! empty($get_file_data)) { + $file_path = WRITEPATH . 'uploads/claim_files/'; + $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS); } - if (empty($received_data['doa'])) { $received_data['doa'] = null; } else { @@ -3710,7 +3597,7 @@ class EmployeeRestController extends AdminController } $sql = " - select + select cp.policy_type_id, cl_rm.user_id as acm_id, cp.insurer_id as insurer_id, @@ -3726,30 +3613,30 @@ class EmployeeRestController extends AdminController empl.id as insured_emp_id, empl.name as insured_name, empl.relationship, - - CASE + + CASE WHEN cp.policy_type_id IN (2, 3, 4, 5) THEN 1 WHEN cp.policy_type_id = 1 THEN 2 WHEN cp.policy_type_id = 6 THEN 3 WHEN cp.policy_type_id = 7 THEN 4 - ELSE cp.policy_type_id + ELSE cp.policy_type_id END AS ticket_type_id - from employees emp + from employees emp left join employees empl on empl.id = :insured_emp_id: and empl.is_active = 1 and empl.emp_status = 'active' - left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = :client_policy_id: and emp_pol.is_active = 1 + left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = :client_policy_id: and emp_pol.is_active = 1 left join client_policy cp on cp.id = emp_pol.client_policy_id and cp.is_active = 1 - left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3 + left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3 where emp.id = :employee_id: and emp.is_active = 1 and emp.emp_status = 'active' limit 1 "; - $binds = ['insured_emp_id'=>$insured_emp_id,'client_policy_id'=>(int)$client_policy_id,'employee_id'=>$employee_id ]; - $emp_ticket_data = $this->employeeModel->query($sql,$binds)->getResultArray(); + $binds = ['insured_emp_id' => $insured_emp_id, 'client_policy_id' => (int) $client_policy_id, 'employee_id' => $employee_id]; + $emp_ticket_data = $this->employeeModel->query($sql, $binds)->getResultArray(); // print_r(db_connect()->getLastQuery()); die; - if (!empty($emp_ticket_data)) { + if (! empty($emp_ticket_data)) { unset($received_data['relationship']); $fetchData = $emp_ticket_data[0]; @@ -3759,21 +3646,20 @@ class EmployeeRestController extends AdminController ->where('ticket_type', $fetchData['ticket_type_id']) ->orderBy('id', 'asc'); - if ($fetchData['ticket_type_id'] == 1 && !empty($fetchData['tpa_no'])) { - $results = $claimStatusQuery->findAll(2); + if ($fetchData['ticket_type_id'] == 1 && ! empty($fetchData['tpa_no'])) { + $results = $claimStatusQuery->findAll(2); $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id']; - } else if ($fetchData['ticket_type_id'] == 72 && !empty($fetchData['tpa_no'])) { - $results = $claimStatusQuery->findAll(2); + } else if ($fetchData['ticket_type_id'] == 72 && ! empty($fetchData['tpa_no'])) { + $results = $claimStatusQuery->findAll(2); $fetchData['claim_status_id'] = $results[1]['id'] ?? $results[0]['id']; } else { $fetchData['claim_status_id'] = $claimStatusQuery->first()['id']; } - - $fetchData['priority'] = 1; + $fetchData['priority'] = 1; $fetchData['mode_of_intimation'] = 3; - - if(!isset($received_data['claim_type']) || (isset($received_data['claim_type']) && empty($received_data['claim_type']))) { + + if (! isset($received_data['claim_type']) || (isset($received_data['claim_type']) && empty($received_data['claim_type']))) { $received_data['claim_type'] = 1; } @@ -3784,26 +3670,26 @@ class EmployeeRestController extends AdminController // print_r($fetchData); die; $insert_status = $this->ticketMaster->insert($fetchData); - $ticket_id = $this->ticketMaster->insertID(); + $ticket_id = $this->ticketMaster->insertID(); - if ($insert_status && !empty($ticket_id)) { + if ($insert_status && ! empty($ticket_id)) { //insert first history $this->ticketController->putHistoryAfterInsert($fetchData, $ticket_id); $messagesData = [ - 'ticket_id' => $ticket_id ?? null, - 'sender' => 'user', + 'ticket_id' => $ticket_id ?? null, + 'sender' => 'user', 'claim_status' => $fetchData['claim_status_id'] ?? null, - 'emp_mail' => $fetchData['emp_mail'] ?? null, + 'emp_mail' => $fetchData['emp_mail'] ?? null, 'mail_subject' => $fetchData['subject'] ?? "New Claim", 'mail_content' => $fetchData['message'] ?? "New Claim", ]; $ticket_message_id = null; - if (!empty($messagesData['ticket_id'])) { + if (! empty($messagesData['ticket_id'])) { $TicketMessageModel = new TicketMessageModel(); - $ticket_message_id = $TicketMessageModel->insert($messagesData); + $ticket_message_id = $TicketMessageModel->insert($messagesData); } $this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id); @@ -3843,40 +3729,40 @@ class EmployeeRestController extends AdminController } public function retailClaimInitiate($data) - { - if(isset($data['policy_transaction_id'])){ + { + if (isset($data['policy_transaction_id'])) { $policy_transaction_model = new PolicyTransactionModel(); $policy = $policy_transaction_model - ->select('policy_transaction.*, clients.client_name, clients.phone as client_mobile, clients.email as client_email') - ->join('clients', 'policy_transaction.client_id = clients.id') - ->where('policy_transaction.is_active',1) - ->where('clients.is_active',1) - ->where('policy_transaction.id', $data['policy_transaction_id']) - ->first(); + ->select('policy_transaction.*, clients.client_name, clients.phone as client_mobile, clients.email as client_email') + ->join('clients', 'policy_transaction.client_id = clients.id') + ->where('policy_transaction.is_active', 1) + ->where('clients.is_active', 1) + ->where('policy_transaction.id', $data['policy_transaction_id']) + ->first(); - if(!empty($policy)){ + if (! empty($policy)) { $claimData = [ - 'ticket_type_id' => $data['policy_type_id'], - 'policy_transaction_id' => $data['policy_transaction_id'], - 'claim_status_id' => 62, - 'policy_no' => $policy['policy_no'], - 'client_policy_id' => $policy['client_policy_id'], - 'insurer_id' => $policy['insurer_id'], - 'client_id' => $policy['client_id'] ?? null, - 'agent_id' => $policy['agent_id'] ?? null, - 'manager_id' => $policy['manager_id'] ?? null, - 'vehicle_id' => $policy['vehicle_id'] ?? null, - 'insured_name' => $policy['client_name'] ?? null, - 'emp_name' => $policy['client_name'] ?? null, - 'emp_mobile' => $policy['client_mobile'] ?? null, - 'emp_mail' => $policy['client_email'] ?? null, - 'emp_personal_mail'=> $policy['client_email'] ?? null, - 'claim_type' => $data['claim_type'], - 'claim_description'=> $data['claim_description'], - 'created_by' => $policy['client_id'] ?? null, + 'ticket_type_id' => $data['policy_type_id'], + 'policy_transaction_id' => $data['policy_transaction_id'], + 'claim_status_id' => 62, + 'policy_no' => $policy['policy_no'], + 'client_policy_id' => $policy['client_policy_id'], + 'insurer_id' => $policy['insurer_id'], + 'client_id' => $policy['client_id'] ?? null, + 'agent_id' => $policy['agent_id'] ?? null, + 'manager_id' => $policy['manager_id'] ?? null, + 'vehicle_id' => $policy['vehicle_id'] ?? null, + 'insured_name' => $policy['client_name'] ?? null, + 'emp_name' => $policy['client_name'] ?? null, + 'emp_mobile' => $policy['client_mobile'] ?? null, + 'emp_mail' => $policy['client_email'] ?? null, + 'emp_personal_mail' => $policy['client_email'] ?? null, + 'claim_type' => $data['claim_type'], + 'claim_description' => $data['claim_description'], + 'created_by' => $policy['client_id'] ?? null, ]; $ticket_id = $this->ticketMaster->insert($claimData); @@ -3903,15 +3789,15 @@ class EmployeeRestController extends AdminController $message = 'Claim Initiated Successfully'; return ['status' => true, 'code' => 200, 'data' => $ticket_id, 'message' => $message]; - }else{ + } else { $message = 'Claim Initiation failed'; return ['status' => false, 'code' => 404, 'message' => $message]; } - }else{ + } else { $message = 'Claim Initiation failed. Policy data not found'; return ['status' => false, 'code' => 404, 'message' => $message]; } - }else{ + } else { $message = 'Claim Initiation failed'; return ['status' => false, 'code' => 404, 'message' => $message]; } @@ -3919,23 +3805,23 @@ class EmployeeRestController extends AdminController public function handleCliamFiles($data, $ticket_id, $ticket_message_id = null, $tpa_claim_push = true, $ir_docs = false) { - if (!empty($data) && !empty($ticket_id)) { - $insert_ids = []; + if (! empty($data) && ! empty($ticket_id)) { + $insert_ids = []; $pdf_exist_in_the_file = false; - $claim_file = new ClaimFilesModel(); + $claim_file = new ClaimFilesModel(); foreach ($data as $key => $value) { $data = [ - 'ticket_id' => $ticket_id, - 'doc_name' => $value['doc_name'], - 'file_name' => $value['file_name'], - 'url' => $value['file_path'], - 'file_type' => 2, + 'ticket_id' => $ticket_id, + 'doc_name' => $value['doc_name'], + 'file_name' => $value['file_name'], + 'url' => $value['file_path'], + 'file_type' => 2, 'ticket_message_id' => $ticket_message_id, - 'mime_type' => getMimeTypeByFileName($value['file_name']), + 'mime_type' => getMimeTypeByFileName($value['file_name']), ]; - if($ir_docs == true){ + if ($ir_docs == true) { $data['docs_for_ir'] = 1; } @@ -3959,11 +3845,11 @@ class EmployeeRestController extends AdminController log_message('error', "Error in TPA Claim Push via Benifits or HR : ApiServiceController pushClaims function call for Ticket ID: {$ticket_id}. Error: " . $e->getMessage() . " Trace: " . $e->getTraceAsString()); } } else { - if($tpa_claim_push == false){ + if ($tpa_claim_push == false) { log_message('error', 'Skip the TPA claim push for IR DOCUMENTS'); - } else if($count == 0){ + } else if ($count == 0) { log_message('error', 'TPA claim push skipped as the claim reference number is already generated.'); - }else{ + } else { log_message('error', "Failed to call the pushClaims function in EmployeeRestController for Ticket ID: {$ticket_id}, because the .pdf file does not exist."); } } @@ -4000,7 +3886,7 @@ class EmployeeRestController extends AdminController // ])->setStatusCode(400); $ticket_type = $this->ticketController->ticketType; - $claim_type = $this->ticketController->claimType; + $claim_type = $this->ticketController->claimType; unset($claim_type[1][2]); unset($claim_type[1][4]); @@ -4022,32 +3908,32 @@ class EmployeeRestController extends AdminController ->groupBy('employee_polices.client_policy_id') ->findAll(); - if (!$policy_type_ids) { + if (! $policy_type_ids) { $this->myLogger->logme('error', "No policy types found for client_id={$client_id}, emp_code={$emp_code}"); return $this->response->setJSON([ 'status' => false, 'code' => 404, - 'message' => 'No policy types found' + 'message' => 'No policy types found', ])->setStatusCode(200); } $this->myLogger->logme('error', "Policy type IDs fetched: " . json_encode($policy_type_ids)); $ticket_type = $this->ticketController->ticketType; - $claim_type = $this->ticketController->claimType; + $claim_type = $this->ticketController->claimType; unset($claim_type[1][2]); unset($claim_type[1][4]); - $filtered = []; + $filtered = []; $mapping = [ - 2 => 1, - 3 => 1, - 4 => 1, - 5 => 1, - 1 => 2, - 6 => 3, - 7 => 4, + 2 => 1, + 3 => 1, + 4 => 1, + 5 => 1, + 1 => 2, + 6 => 3, + 7 => 4, 72 => 72, ]; @@ -4061,7 +3947,7 @@ class EmployeeRestController extends AdminController // Use mappedId as key to avoid duplicates $filtered[$mappedId] = [ 'id' => $mappedId, - 'name' => $mappedName + 'name' => $mappedName, ]; $this->myLogger->logme('error', "Ticket type resolved: ID={$ticketTypeId}, Name={$mappedName}"); @@ -4077,30 +3963,28 @@ class EmployeeRestController extends AdminController return $this->response->setJSON([ 'status' => false, 'code' => 500, - 'message' => 'Internal Server Error' + 'message' => 'Internal Server Error', ])->setStatusCode(500); } } - //ticket data public function get_ticket_data() { - $priorityType = $this->ticketController->priorityType; - $modeOFIntimate = $this->ticketController->modeOFIntimate; - $claimType = $this->ticketController->claimType; + $priorityType = $this->ticketController->priorityType; + $modeOFIntimate = $this->ticketController->modeOFIntimate; + $claimType = $this->ticketController->claimType; $relationshipType = $this->ticketController->relationshipType; - $ticketTypeArray = $this->ticketController->ticketType; + $ticketTypeArray = $this->ticketController->ticketType; - - $emp_id = $this->request->getGet('emp_id'); - $ticket_type = $this->request->getGet('ticket_type') ?? null; - $ticket_id = $this->request->getGet('ticket_id') ?? null; + $emp_id = $this->request->getGet('emp_id'); + $ticket_type = $this->request->getGet('ticket_type') ?? null; + $ticket_id = $this->request->getGet('ticket_id') ?? null; $mobile_number = $this->request->getGet('mobile_number') ?? null; - $email_id = $this->request->getGet('email_id') ?? null; - $request = \Config\Services::request(); - $uri = $request->uri->getPath(); - $returnType = ""; + $email_id = $this->request->getGet('email_id') ?? null; + $request = \Config\Services::request(); + $uri = $request->uri->getPath(); + $returnType = ""; // $returnType = (strpos($uri, 'api') !== false) ? 'api' : 'web'; // dd($emp_id); @@ -4109,14 +3993,14 @@ class EmployeeRestController extends AdminController } $retail_ticket_data = []; - if(!empty($mobile_number) || !empty($email_id)){ + if (! empty($mobile_number) || ! empty($email_id)) { $retail_ticket_data = $this->getRetailPolicyClaimData($this->request->getGet()); } $TicketMasterModel = new TicketMasterModel(); - $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id); + $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id); - if (!empty($ticket_data)) { + if (! empty($ticket_data)) { // $client_claim_status = [ // 'Received' => [1, 2, 3, 4, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38], @@ -4138,7 +4022,7 @@ class EmployeeRestController extends AdminController // 'Denial Review Awaited' => [66], // 'Rejected' => [8, 49, 55, 60], // ]; - + // construct the claim status $client_claim_status = $this->getClaimStatusGrouped(); @@ -4147,26 +4031,26 @@ class EmployeeRestController extends AdminController foreach ($client_claim_status as $claim_key => $claim_value) { if (in_array($value['claim_status_id'], $claim_value)) { // Corrected argument order $ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array - }else if(in_array($value['old_status_id'], $claim_value)){ + } else if (in_array($value['old_status_id'], $claim_value)) { $ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array } } - $ticket_data[$key]['priority_type'] = $priorityType[$value['priority']] ?? null; + $ticket_data[$key]['priority_type'] = $priorityType[$value['priority']] ?? null; $ticket_data[$key]['mode_of_intimate_type'] = $modeOFIntimate[$value['mode_of_intimation']] ?? null; - $ticket_data[$key]['relationship_type'] = ucfirst($value['relationship']) ?? null; - $claimPrimaryTypey = "1"; + $ticket_data[$key]['relationship_type'] = ucfirst($value['relationship']) ?? null; + $claimPrimaryTypey = "1"; if (in_array($value['claim_type'], [2, 3, 4])) { $claimPrimaryTypey = "2"; } - $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null; + $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null; $ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null; $claim_file_urls = []; if (isset($value['ticket_message_id'])) { - $claimFiles = new ClaimFilesModel(); + $claimFiles = new ClaimFilesModel(); $claim_files_data = $claimFiles ->select('id as claim_file_id, doc_name as claim_file_name') ->where('is_active', 1) @@ -4176,7 +4060,7 @@ class EmployeeRestController extends AdminController ->findAll(); foreach ($claim_files_data as &$value) { - $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; + $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; $claim_file_urls[] = $value; } unset($value); @@ -4193,13 +4077,13 @@ class EmployeeRestController extends AdminController } public function getRetailPolicyClaimData($receviedPayload) - { + { try { // Create minimal retail user object $retailUserData = (object) [ - 'id' => null, - 'mobile' => $receviedPayload['mobile_number'] ?? null, - 'email_id' => $receviedPayload['email_id'] ?? null + 'id' => null, + 'mobile' => $receviedPayload['mobile_number'] ?? null, + 'email_id' => $receviedPayload['email_id'] ?? null, ]; // Get retail policies of user @@ -4236,7 +4120,7 @@ class EmployeeRestController extends AdminController ->where('ticket_master.policy_transaction_id', $policy['policy_transaction_id']) ->findAll(); - if (!empty($tickets)) { + if (! empty($tickets)) { $retail_ticket_data = array_merge($retail_ticket_data, $tickets); } } @@ -4245,9 +4129,9 @@ class EmployeeRestController extends AdminController return []; } - // Fetch grouped claim statuses + // Fetch grouped claim statuses $client_claim_status = $this->getClaimStatusGrouped(); // Format expected: [status => [ids]] - $claim_type = $this->getClaimTypeMaster('internal'); + $claim_type = $this->getClaimTypeMaster('internal'); // Convert claim type for quick access $typeMap = array_column($claim_type, 'claim_type', 'id'); @@ -4257,7 +4141,7 @@ class EmployeeRestController extends AdminController $ticket['claim_status'] = null; // Default $ticket['claim_type_name'] = $typeMap[$ticket['claim_type']] ?? null; - if($ticket['ticket_type_id'] == 8){ + if ($ticket['ticket_type_id'] == 8) { $ticket['ticket_policy_type'] = 'Motor'; } foreach ($client_claim_status as $status_name => $status_list) { @@ -4275,17 +4159,17 @@ class EmployeeRestController extends AdminController return $retail_ticket_data; - }catch (\Throwable $th) { + } catch (\Throwable $th) { $errorData = [ - 'message' => $th->getMessage(), - 'file' => $th->getFile(), - 'line' => $th->getLine(), - 'code' => $th->getCode(), - 'trace' => $th->getTraceAsString(), + '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, + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, ]; $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getRetailPolicyClaimData: Exception: " . json_encode($errorData ?? [])); @@ -4309,7 +4193,7 @@ class EmployeeRestController extends AdminController $name = $row['display_name']; $id = $row['id']; - if (!isset($result[$name])) { + if (! isset($result[$name])) { $result[$name] = []; } @@ -4320,27 +4204,26 @@ class EmployeeRestController extends AdminController } // not in use did for testing - function encrypt_for_sso(): string + public function encrypt_for_sso(): string { - $key = "32D1D5535157AF3D4667ADAB0CC795D77D022BB281AD3272EB134C72BD0B185E"; $userParams = [ - "name" => "John Doe 3", - "email" => "john.doe3@email.com", - "memberId" => "TEST-REL-01", - "gender" => "Male", - "dob" => "1997-01-01", - "policyName" => "Nhance DEMO", - "phone" => "6676126763", - "employeeId" => "EMP-NHANCE-TEST-03", - "policyNumber" => "EMP-NHANCE-TEST-03", + "name" => "John Doe 3", + "email" => "john.doe3@email.com", + "memberId" => "TEST-REL-01", + "gender" => "Male", + "dob" => "1997-01-01", + "policyName" => "Nhance DEMO", + "phone" => "6676126763", + "employeeId" => "EMP-NHANCE-TEST-03", + "policyNumber" => "EMP-NHANCE-TEST-03", "policyStartDate" => "2025-09-08", - "policyEndDate" => "2026-09-08", - "moduleName" => "home", - "relation" => "self", - "planId" => "NHANCE-PLAN-1" + "policyEndDate" => "2026-09-08", + "moduleName" => "home", + "relation" => "self", + "planId" => "NHANCE-PLAN-1", ]; $algorithm = "aes-256-cbc"; @@ -4358,7 +4241,6 @@ class EmployeeRestController extends AdminController } $plainText = ltrim($plainText, '&'); - // echo ($plainText); die; // Encrypt @@ -4367,22 +4249,15 @@ class EmployeeRestController extends AdminController // Base64URL encode (same as Node.js output) $output = rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '='); - // return $output; + // return $output; - - $baseURL = 'https://web.getvisitapp.net'; + $baseURL = 'https://web.getvisitapp.net'; $clientId = 'nhance-gt-2tx7'; $finalUrl = $baseURL . '/sso?userParams=' . $output . '&clientId=' . $clientId; return $finalUrl; } - - - - - - public function getEmployeePolicyCount() { $db2 = \Config\Database::connect('preDB'); @@ -4402,9 +4277,9 @@ class EmployeeRestController extends AdminController $count = $query->getNumRows(); // count grouped rows manually return $this->respond([ - 'status' => 'success', - 'code' => 200, - 'policy_count' => $count + 'status' => 'success', + 'code' => 200, + 'policy_count' => $count, ], 200); } @@ -4438,7 +4313,6 @@ class EmployeeRestController extends AdminController // return $response['data'] ?? 0 ; - // try { // log_message('error', 'Attempting to connect to preDB...'); // $db2 = \Config\Database::connect('preDB'); @@ -4493,7 +4367,7 @@ class EmployeeRestController extends AdminController $client_short_name = null; - if (!empty($clientId)) { + if (! empty($clientId)) { log_message('error', 'STEP 3: Fetching client short name for client ID: ' . $clientId); $client_data = $this->clientModel->where('is_active', 1)->where('id', $clientId)->first(); @@ -4508,20 +4382,18 @@ class EmployeeRestController extends AdminController log_message('error', 'STEP 3: No clientId provided. Skipping client lookup.'); } - if (!empty($email)) { + if (! empty($email)) { $post_data = [ - 'email_id' => $email, - 'client_short_name' => $client_short_name + 'email_id' => $email, + 'client_short_name' => $client_short_name, ]; } else { $post_data = [ 'mobile_number' => $mobile_no, - 'client_short_name' => $client_short_name + 'client_short_name' => $client_short_name, ]; } - - log_message('error', 'STEP 5: Calling third-party API with payload: ' . json_encode($post_data)); try { @@ -4542,16 +4414,14 @@ class EmployeeRestController extends AdminController private function callThirdPartyAPI($postData, $endPoint) { - $client = \Config\Services::curlrequest(); - $url = env('PRE_ENROLLMENT_BASEURL') . $endPoint; - $headers = [ 'App-Signature' => getenv('APP_SIGNATURE') ]; - $response = $client->post($url, ['json' => $postData,'headers' => $headers,'http_errors' => false]); + $client = \Config\Services::curlrequest(); + $url = env('PRE_ENROLLMENT_BASEURL') . $endPoint; + $headers = ['App-Signature' => getenv('APP_SIGNATURE')]; + $response = $client->post($url, ['json' => $postData, 'headers' => $headers, 'http_errors' => false]); // return json_decode($response->getBody(), true); return $response->getBody(); } - - //-------------------------------------------------------------------------------------------- public function hrFileUpload() { @@ -4568,34 +4438,34 @@ class EmployeeRestController extends AdminController ]; // print_r($post_data); die; - if(empty($post_data['client_id'])){ + if (empty($post_data['client_id'])) { return $this->respondCreated(['status' => false, 'message' => 'Client is required', 'data' => []]); } - // Handle raw client_id vs MD5 + // Handle raw client_id vs MD5 if (is_string($post_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $post_data['client_id'])) { - $client_data = $this->clientModel->where('MD5(id)', $post_data['client_id'])->first(); + $client_data = $this->clientModel->where('MD5(id)', $post_data['client_id'])->first(); $post_data['client_id'] = $client_data['id']; } else { - $client_data = $this->clientModel->where('id', $post_data['client_id'])->first(); + $client_data = $this->clientModel->where('id', $post_data['client_id'])->first(); } - if(empty($client_data)){ + if (empty($client_data)) { return $this->respondCreated(['status' => false, 'message' => 'Invalid Client Id', 'data' => []]); } // print_r($client_data); die; - if($client_data['hr_file_processed_by'] == 1){ + if ($client_data['hr_file_processed_by'] == 1) { $responce = $this->fileUploadInFilesTable($post_data); - }else{ + } else { $responce = $this->fileUploadInHrFileUploadTable($post_data); } return $this->respondCreated($responce); } catch (\Exception $e) { - // return $this->failServerError($e->getMessage()); + // return $this->failServerError($e->getMessage()); return $this->respondCreated(['status' => false, 'message' => $e->getMessage(), 'data' => []]); } } @@ -4605,11 +4475,19 @@ class EmployeeRestController extends AdminController // Check file $file = $post_data['file_name']; - if (!$file) { + if (!$file || !$file->isValid()) { return [ - 'status' => false, + 'status' => false, 'message' => "Invalid file or file not uploaded.", - 'data' => [] + 'data' => [], + ]; + } + + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return [ + 'status' => false, + 'message' => "Only Excel files (xls, xlsx, ods, csv) are allowed.", + 'data' => [], ]; } @@ -4617,8 +4495,8 @@ class EmployeeRestController extends AdminController $uploadPath = WRITEPATH . 'uploads/hr_files/'; // If directory not exists, create it - if (!is_dir($uploadPath)) { - mkdir($uploadPath, 0777, true); + if (! is_dir($uploadPath)) { + mkdir($uploadPath, 0755, true); } // New file name with timestamp @@ -4648,7 +4526,7 @@ class EmployeeRestController extends AdminController $response = [ 'status' => true, 'message' => 'File uploaded successfully', - 'data' => $data + 'data' => $data, ]; return $response; } @@ -4657,7 +4535,7 @@ class EmployeeRestController extends AdminController public function fileUploadInFilesTable($post_data) { $employeeController = new EmployeeController(); - $responce = $employeeController->employeesUplodWithEvents($post_data); + $responce = $employeeController->employeesUplodWithEvents($post_data); // print_r($responce); die; return $responce; @@ -4695,18 +4573,17 @@ class EmployeeRestController extends AdminController $mailTemplate['mail_content'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['mail_content']); $mailTemplate['mail_content'] = str_replace('%policy_no%', $data['policy_no'] ?? '', $mailTemplate['mail_content']); - $mailTemplate['subject'] = str_replace('%subject%', $data['file_action'] ?? '', $mailTemplate['subject']); - $mailTemplate['subject'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['subject']); - - $from_mail = ""; - $to_mail = $account_manager_email; - $subject = $mailTemplate['subject']; - $message = $mailTemplate['mail_content']; - $cc_string = ""; - $attachments = ""; - $reply_to = ""; - $bcc_string = ""; + $mailTemplate['subject'] = str_replace('%subject%', $data['file_action'] ?? '', $mailTemplate['subject']); + $mailTemplate['subject'] = str_replace('%client_name%', $client_name ?? '', $mailTemplate['subject']); + $from_mail = ""; + $to_mail = $account_manager_email; + $subject = $mailTemplate['subject']; + $message = $mailTemplate['mail_content']; + $cc_string = ""; + $attachments = ""; + $reply_to = ""; + $bcc_string = ""; MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); } @@ -4716,7 +4593,7 @@ class EmployeeRestController extends AdminController try { $id = $this->request->getPost('id'); - if (!$id) { + if (! $id) { return $this->failValidationErrors('ID is required for update.'); } @@ -4732,8 +4609,8 @@ class EmployeeRestController extends AdminController ]; // Check if record exists - $record = $this->hrFileUploadModel->find((int)$id); - if (!$record) { + $record = $this->hrFileUploadModel->find((int) $id); + if (! $record) { return $this->failNotFound("Record with ID {$id} not found."); } @@ -4743,46 +4620,45 @@ class EmployeeRestController extends AdminController return $this->respond([ 'status' => true, 'message' => 'File record updated successfully', - 'data' => $data + 'data' => $data, ], 200); } catch (\Exception $e) { return $this->failServerError($e->getMessage()); } } - public function hrFileDownload($id = null) { try { - $file_id = $this->request->getGet('id') ?? $id; + $file_id = $this->request->getGet('id') ?? $id; $client_id = $this->request->getGet('cliend_id') ?? null; $client_data = []; - if(!empty($client_id)){ + if (! empty($client_id)) { if (is_string($client_id) && preg_match('/^[a-f0-9]{32}$/i', $client_id)) { - $client_data = $this->clientModel->where('MD5(id)', $client_id)->first(); + $client_data = $this->clientModel->where('MD5(id)', $client_id)->first(); } else { - $client_data = $this->clientModel->where('id', $client_id)->first(); + $client_data = $this->clientModel->where('id', $client_id)->first(); } } // Find record - if($client_data && $client_data['hr_file_processed_by'] == 1){ - $record = $this->fileModel->where('id', (int)$file_id)->find(); + if ($client_data && $client_data['hr_file_processed_by'] == 1) { + $record = $this->fileModel->where('id', (int) $file_id)->find(); $uploadPath = WRITEPATH . 'uploads/excel/'; - }else{ - $record = $this->hrFileUploadModel->where('id', (int)$file_id)->find(); + } else { + $record = $this->hrFileUploadModel->where('id', (int) $file_id)->find(); $uploadPath = WRITEPATH . 'uploads/hr_files/'; } - if (!$record) { + if (! $record) { return $this->failNotFound("File record not found"); } $filePath = $uploadPath . $record[0]['file_name']; - if (!file_exists($filePath)) { + if (! file_exists($filePath)) { return $this->failNotFound("File not found on server"); } @@ -4840,27 +4716,27 @@ class EmployeeRestController extends AdminController { try { - $request = service('request'); + $request = service('request'); $search_data = $request->getGetPost() ?? []; // supports both GET and POST - $table = ""; + $table = ""; - if(isset($search_data['hr_file_type']) && $search_data['hr_file_type'] == "CRM"){ - $data = $this->getDataFromHrFileUploadTable($search_data); + if (isset($search_data['hr_file_type']) && $search_data['hr_file_type'] == "CRM") { + $data = $this->getDataFromHrFileUploadTable($search_data); $table = "hr_file_upload"; - }else{ + } else { if (is_string($search_data['client_id']) && preg_match('/^[a-f0-9]{32}$/i', $search_data['client_id'])) { - $client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first(); + $client_data = $this->clientModel->where('MD5(id)', $search_data['client_id'])->first(); $search_data['client_id'] = $client_data['id']; } else { - $client_data = $this->clientModel->where('id', $search_data['client_id'])->first(); + $client_data = $this->clientModel->where('id', $search_data['client_id'])->first(); } - if($client_data['hr_file_processed_by'] == 1){ - $data = $this->getDataFromHrFilesTable($search_data); + if ($client_data['hr_file_processed_by'] == 1) { + $data = $this->getDataFromHrFilesTable($search_data); $table = "files"; - }else{ - $data = $this->getDataFromHrFileUploadTable($search_data); + } else { + $data = $this->getDataFromHrFileUploadTable($search_data); $table = "hr_file_upload 2"; } @@ -4870,20 +4746,20 @@ class EmployeeRestController extends AdminController 'status' => "success", 'message' => 'File list fetched successfully', 'data' => $data, - 'table' => $table + 'table' => $table, ]); } catch (\Exception $th) { $errorData = [ - 'message' => $th->getMessage(), - 'file' => $th->getFile(), - 'line' => $th->getLine(), - 'code' => $th->getCode(), - 'trace' => $th->getTraceAsString(), + '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, + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, ]; return $this->failServerError($th->getMessage()); @@ -4901,24 +4777,24 @@ class EmployeeRestController extends AdminController $builder = $this->hrFileUploadModel ->select(" - hr_file_upload.id, - hr_file_upload.client_id, - hr_file_upload.client_branch_id, - hr_file_upload.policy_id, - hr_file_upload.policy_no, - hr_file_upload.file_name, - hr_file_upload.file_action, - hr_file_upload.created_at, - hr_file_upload.created_by, - hr_file_upload.updated_at, + hr_file_upload.id, + hr_file_upload.client_id, + hr_file_upload.client_branch_id, + hr_file_upload.policy_id, + hr_file_upload.policy_no, + hr_file_upload.file_name, + hr_file_upload.file_action, + hr_file_upload.created_at, + hr_file_upload.created_by, + hr_file_upload.updated_at, hr_file_upload.updated_by, - c.short_name, - cb.branch_name, + c.short_name, + cb.branch_name, lc.name as first_name, - CASE - WHEN f.status IS NULL - THEN hr_file_upload.status - ELSE CONCAT(UCASE(LEFT(f.status, 1)), LCASE(SUBSTRING(f.status, 2))) + CASE + WHEN f.status IS NULL + THEN hr_file_upload.status + ELSE CONCAT(UCASE(LEFT(f.status, 1)), LCASE(SUBSTRING(f.status, 2))) END AS status, '0' as file_error_status, '' as file_error_status @@ -4927,10 +4803,10 @@ class EmployeeRestController extends AdminController ->join('client_branch cb', 'cb.id = hr_file_upload.client_branch_id AND cb.is_active = 1', 'left') ->join('level_contacts lc', 'lc.id = hr_file_upload.created_by AND lc.contact_type = "client" AND lc.is_active = 1', 'left') ->join( - '(SELECT f1.* - FROM files f1 - WHERE f1.is_active = 1 - ORDER BY f1.id DESC + '(SELECT f1.* + FROM files f1 + WHERE f1.is_active = 1 + ORDER BY f1.id DESC LIMIT 1) f', 'f.hr_file_id = hr_file_upload.id', 'left' @@ -4944,13 +4820,13 @@ class EmployeeRestController extends AdminController 'policy_no', 'file_action', 'status', - 'created_by' + 'created_by', ]; // Apply filters dynamically foreach ($filters as $key) { $value = $search_data[$key] ?? null; // supports both GET and POST - if (!empty($value)) { + if (! empty($value)) { $builder->where("hr_file_upload.$key", $value); } } @@ -4959,7 +4835,7 @@ class EmployeeRestController extends AdminController $builder->orderBy('hr_file_upload.id', 'DESC'); $data = $builder->get()->getResultArray(); - if(!empty($data)){ + if (! empty($data)) { return $data; } @@ -4967,28 +4843,28 @@ class EmployeeRestController extends AdminController } public function getDataFromHrFilesTable($search_data) - { + { $file_download_base = base_url('downloadFileTableFile/'); - $builder = $this->fileModel + $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.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, + 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 + 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) @@ -4997,20 +4873,19 @@ class EmployeeRestController extends AdminController ->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'])) { + 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'])) { + 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'])) { + 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 (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 { @@ -5018,16 +4893,15 @@ class EmployeeRestController extends AdminController } } - if (isset($search_data['file_id']) && !empty($search_data['file_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)) { + if (! empty($data)) { return $data; } @@ -5038,12 +4912,12 @@ class EmployeeRestController extends AdminController { try { //for inception upload - $data['actions'] = ['addition' => 'Addition (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; + $data['actions'] = ['addition' => 'Addition (Employee + Dependents)', 'missed_inception' => 'Missed Inception (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 + 'data' => $data, ]); } catch (\Exception $e) { return $this->failServerError($e->getMessage()); @@ -5103,13 +4977,13 @@ class EmployeeRestController extends AdminController // Step 5: Check if API service is enabled log_message('error', "Checking TPA API service for TPA ID={$tpa_id} and API name={$api_name}"); $tpaApiServiceModel = new TpaApiSeviceModel(); - $api_data = $tpaApiServiceModel + $api_data = $tpaApiServiceModel ->where('is_active', 1) ->where('api_name', $api_name) ->where('tpa_id', $tpa_id) ->first(); - if (!empty($api_data)) { + if (! empty($api_data)) { log_message('error', "API '{$api_name}' is enabled for TPA ID={$tpa_id}"); if ($return_type == 'api') { return $this->respond(['status' => true, 'code' => 200, 'message' => 'API services enabled']); @@ -5133,16 +5007,14 @@ class EmployeeRestController extends AdminController } } - - public function getEcardURL() { try { - $id = $this->request->getGet('id'); - $emp_code = $this->request->getGet('emp_code'); + $id = $this->request->getGet('id'); + $emp_code = $this->request->getGet('emp_code'); $client_policy_id = $this->request->getGet('client_policy_id'); - $policy_no = $this->request->getGet('policy_no'); + $policy_no = $this->request->getGet('policy_no'); $employee_policy = $this->employeePolicyModel ->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ') @@ -5152,13 +5024,11 @@ class EmployeeRestController extends AdminController ->where('employee_polices.client_policy_id', $client_policy_id) ->where('employee_polices.is_active', 1)->findAll(); - - if (count($employee_policy) > 0) { if ($employee_policy[0]['tpa_id'] != null) { if ($employee_policy[0]['tpa_primary_id'] == 2) //Medi assist { - $mediAssistController = new MediAssistApiController(); + $mediAssistController = new MediAssistApiController(); $data['eCardDownload'] = $mediAssistController->EcardRequest($emp_code, $policy_no); } else { $data['eCardDownload'] = base_url('download-e-card/') . $employee_policy[0]['rand_string'] . '/1'; @@ -5170,8 +5040,7 @@ class EmployeeRestController extends AdminController $data['eCardDownload'] = null; } - - return $this->respond(['status' => true, 'message' => '', 'data' => $data]); + return $this->respond(['status' => true, 'message' => '', 'data' => $data]); } catch (\Exception $e) { } } @@ -5183,32 +5052,32 @@ class EmployeeRestController extends AdminController try { $payload = $this->request->getJSON(true); - $pk = $payload['retail_policy_id'] ?? null; - $emp_id = $payload['emp_id'] ?? null; + $pk = $payload['retail_policy_id'] ?? null; + $emp_id = $payload['emp_id'] ?? null; if (empty($emp_id)) { $this->myLogger->logme("error", "addEmpRetailPolicy: emp_id is missing"); - return $this->respond(['status' => 'failed','code' => 400,'message' => 'emp_id is required' ], 200); + return $this->respond(['status' => 'failed', 'code' => 400, 'message' => 'emp_id is required'], 200); } - if(isset($payload['policy_end_date']) && !empty($payload['policy_end_date'])){ + if (isset($payload['policy_end_date']) && ! empty($payload['policy_end_date'])) { $payload['policy_end_date'] = change_date_format($payload['policy_end_date'], 'd M Y', 'Y-m-d'); - }else{ - $payload['policy_end_date'] = null; + } else { + $payload['policy_end_date'] = null; } - if(isset($payload['policy_start_date']) && !empty($payload['policy_start_date'])){ + if (isset($payload['policy_start_date']) && ! empty($payload['policy_start_date'])) { $payload['policy_start_date'] = change_date_format($payload['policy_start_date'], 'd M Y', 'Y-m-d'); - }else{ - $payload['policy_start_date'] = null; + } else { + $payload['policy_start_date'] = null; } - if(empty($pk)){ + if (empty($pk)) { $payload['created_by'] = $emp_id; - $emp_retail_policy_id = $this->employeeRetailPolicy->insert($payload); - }else{ + $emp_retail_policy_id = $this->employeeRetailPolicy->insert($payload); + } else { $payload['updated_by'] = $emp_id; - $emp_retail_policy_id = $this->employeeRetailPolicy->where('id', $pk)->set($payload)->update(); + $emp_retail_policy_id = $this->employeeRetailPolicy->where('id', $pk)->set($payload)->update(); } if ($emp_retail_policy_id) { @@ -5220,44 +5089,44 @@ class EmployeeRestController extends AdminController 'code' => 200, 'message' => 'Employee Retail Policy created successfully', 'data' => [ - 'emp_retail_policy_id' => $emp_retail_policy_id - ] + 'emp_retail_policy_id' => $emp_retail_policy_id, + ], ], 200); } else { - $this->myLogger->logme( "error", "addEmpRetailPolicy: Failed to create Employee Retail Policy. Insert returned false" ); - return $this->respond(['status' => 'failed','code' => 500,'message' => 'Failed to create Employee Retail Policy'], 500); + $this->myLogger->logme("error", "addEmpRetailPolicy: Failed to create Employee Retail Policy. Insert returned false"); + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Failed to create Employee Retail Policy'], 500); } } catch (\Throwable $th) { $this->myLogger->logme("error", "addEmpRetailPolicy: Exception occurred - " . $th->getMessage()); - return $this->respond(['status' => 'failed','code' => 500,'message' => 'Internal server error: ' . $th->getMessage()], 500); + return $this->respond(['status' => 'failed', 'code' => 500, 'message' => 'Internal server error: ' . $th->getMessage()], 500); } } public function getEmpRetailPolicy($employeeData) - { + { $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Given params: " . json_encode($employeeData ?? [])); try { - $emp_id = $employeeData->id ?? null; + $emp_id = $employeeData->id ?? null; $mobile_number = $employeeData->mobile ?? null; - $email_id = $employeeData->email_id ?? null; + $email_id = $employeeData->email_id ?? null; $emp_retail_policy_data = []; if ($emp_id != null) { $emp_retail_policy_data = $this->employeeRetailPolicy ->select(" - employee_retail_policies.emp_id, - employee_retail_policies.insurer_id, - employee_retail_policies.policy_type_id, - employee_retail_policies.policy_no, + employee_retail_policies.emp_id, + employee_retail_policies.insurer_id, + employee_retail_policies.policy_type_id, + employee_retail_policies.policy_no, DATE_FORMAT(employee_retail_policies.policy_start_date, '%d-%b-%Y') as policy_start_date, DATE_FORMAT(employee_retail_policies.policy_end_date, '%d-%b-%Y') as policy_end_date, - policy_type.policy_type, - policy_type.long_name as policy_type_long_name, + policy_type.policy_type, + policy_type.long_name as policy_type_long_name, insurers.name as insurer_name, insurers.short_name as insurer_short_name ") @@ -5271,7 +5140,7 @@ class EmployeeRestController extends AdminController $emp_retail_client_data = []; - if (!empty($mobile_number)) { + if (! empty($mobile_number)) { $emp_retail_client_data = $this->clientModel ->select(" '{$emp_id}' AS emp_id, @@ -5288,8 +5157,8 @@ class EmployeeRestController extends AdminController vehicle.vehicle_no, DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date, DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date, - policy_type.policy_type, - policy_type.long_name as policy_type_long_name, + policy_type.policy_type, + policy_type.long_name as policy_type_long_name, insurers.name as insurer_name, insurers.short_name as insurer_short_name ") @@ -5304,7 +5173,7 @@ class EmployeeRestController extends AdminController ->where('clients.phone IS NOT NULL') ->where('clients.phone', $mobile_number) ->findAll(); - }else { + } else { $emp_retail_client_data = $this->clientModel ->select(" '{$emp_id}' AS emp_id, @@ -5321,8 +5190,8 @@ class EmployeeRestController extends AdminController vehicle.vehicle_no, DATE_FORMAT(policy_transaction.policy_start_date, '%d-%b-%Y') as policy_start_date, DATE_FORMAT(policy_transaction.policy_end_date, '%d-%b-%Y') as policy_end_date, - policy_type.policy_type, - policy_type.long_name as policy_type_long_name, + policy_type.policy_type, + policy_type.long_name as policy_type_long_name, insurers.name as insurer_name, insurers.short_name as insurer_short_name ") @@ -5353,14 +5222,14 @@ class EmployeeRestController extends AdminController } catch (\Throwable $th) { $errorData = [ - 'message' => $th->getMessage(), - 'file' => $th->getFile(), - 'line' => $th->getLine(), - 'code' => $th->getCode(), - 'trace' => $th->getTraceAsString(), + '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, + 'function' => $th->getTrace()[0]['function'] ?? null, + 'class' => $th->getTrace()[0]['class'] ?? null, ]; $this->myLogger->logme("error", "EMPLOYEE-REST-CONTROLLER - getEmpRetailPolicy: Exception: " . json_encode($errorData ?? [])); @@ -5369,19 +5238,17 @@ class EmployeeRestController extends AdminController } } - - public function getPolicyTypeAndInsurer() { $policy_type_ids = [8, 37, 38, 39, 62]; - $policy_type = $this->policyTypeModel + $policy_type = $this->policyTypeModel ->select('id as policy_type_id, policy_type, long_name as policy_type_long_name') ->where('is_active', 1) ->whereIn('id', $policy_type_ids) ->findAll(); $insurer_category = ['general']; - $insurers = $this->insurerModel + $insurers = $this->insurerModel ->select('id as insurer_id, name as insurer_name, short_name as insurer_short_name') ->where('is_active', 1) ->where('category', $insurer_category) @@ -5392,58 +5259,58 @@ class EmployeeRestController extends AdminController 'code' => 200, 'data' => [ 'insurer' => $insurers, - 'policy_type' => $policy_type - ] + 'policy_type' => $policy_type, + ], ], 200); } public function getClaimTypeMaster($return_type = 'api') { - $data = db_connect()->table('partner_claim_type_master')->select('id,claim_type')->where('is_active',1)->get()->getResultArray(); + $data = db_connect()->table('partner_claim_type_master')->select('id,claim_type')->where('is_active', 1)->get()->getResultArray(); - if (!$data) { + if (! $data) { return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 200); } - if($return_type == 'api'){ - return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data]); - }else{ + if ($return_type == 'api') { + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $data]); + } else { return $data; } } public function uploadIRDocs() - { - $ticket_id = $this->request->getPost('ticket_id') ?? null; + { + $ticket_id = $this->request->getPost('ticket_id') ?? null; $get_file_data = $this->request->getFiles('claim_docs') ?? null; $get_docs_name = $this->request->getPost('claim_doc_names') ?? []; $required_docs = $this->request->getPost('required_docs') ?? []; if (is_string($get_docs_name)) { - $decoded = json_decode($get_docs_name, true); + $decoded = json_decode($get_docs_name, true); $get_docs_name = json_last_error() === JSON_ERROR_NONE ? $decoded : []; - } elseif (!is_array($get_docs_name)) { + } elseif (! is_array($get_docs_name)) { $get_docs_name = []; } $file_data = []; - if (isset($get_file_data) && !empty($get_file_data)) { - $file_path = WRITEPATH . 'uploads/claim_files/'; - $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); + if (isset($get_file_data) && ! empty($get_file_data)) { + $file_path = WRITEPATH . 'uploads/claim_files/'; + $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS); } $result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true); - if(!empty($result)){ + if (! empty($result)) { // $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update(); - db_connect()->query( + db_connect()->query( "UPDATE ticket_master SET required_docs = ? WHERE id = ?", [$required_docs, $ticket_id] ); - $apiServiceController = new ApiServiceController(); + $apiServiceController = new ApiServiceController(); $tpaIrFilePushResponce = $apiServiceController->pushClaimFiles($ticket_id); return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files uploaded successfully', 'tpaIrFilePushResponce' => $tpaIrFilePushResponce], 200); - }else{ + } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'Failed to upload the file'], 200); } } @@ -5451,11 +5318,11 @@ class EmployeeRestController extends AdminController public function getTicketClaimStatusIdBasedOnTheDisplayName($claim_status_id) { $claim_status_data_display_name = $this->claimStatusModel->where('is_active', 1)->where('id', $claim_status_id)->first(); - $claim_status_data_id = $this->claimStatusModel - ->select('id') - ->where('is_active', 1) - ->where('display_name', $claim_status_data_display_name['display_name']) - ->findAll(); + $claim_status_data_id = $this->claimStatusModel + ->select('id') + ->where('is_active', 1) + ->where('display_name', $claim_status_data_display_name['display_name']) + ->findAll(); $claim_status_data_id = array_column($claim_status_data_id, 'id'); return $claim_status_data_id; @@ -5468,8 +5335,8 @@ class EmployeeRestController extends AdminController $file_id = $this->request->getGet('id'); // Find record - $record = $this->batchFileModel->where('MD5(id)', $file_id)->first(); - if (!$record) { + $record = $this->batchFileModel->where('MD5(id)', $file_id)->first(); + if (! $record) { $data['message'] = 'File record not found'; return view('errors/404', $data); } @@ -5477,7 +5344,7 @@ class EmployeeRestController extends AdminController $uploadPath = WRITEPATH . 'uploads/import_excel/'; $filePath = $uploadPath . $record['file_name']; - if (!file_exists($filePath)) { + if (! file_exists($filePath)) { // return $this->failNotFound("File not found on server"); $data['message'] = 'The Physical File Not Found'; return view('errors/404', $data); @@ -5491,14 +5358,13 @@ class EmployeeRestController extends AdminController } } - public function getHrDashboad() { // $dashboard_id = $this->request->getGet('dashboard_id') ?? null; - $client_id = $this->request->getPost('client_id') ?? null; + $client_id = $this->request->getPost('client_id') ?? null; $client_policy_id = $this->request->getPost('client_policy_id') ?? null; - $received_data = $this->request->getJSON(true) ?? null; - // 🔐 Move this to .env in real projects + $received_data = $this->request->getJSON(true) ?? null; + // 🔐 Move this to .env in real projects $METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY'); $is_tpa_dashboard_enable = $this->clientPolicyModel @@ -5507,13 +5373,13 @@ class EmployeeRestController extends AdminController ->where('client_policy.id', $received_data['client_policy_id']) ->where('tpa.dashboard_id IS NOT NULL') ->first(); - + $payload = [ 'resource' => [ - 'dashboard' => 2 + 'dashboard' => 2, ], - 'params' => (object)['client_policy' => $received_data['client_policy_id']], // MUST be object for Metabase - 'exp' => time() + (10 * 60) // 10 minutes + 'params' => (object) ['client_policy' => $received_data['client_policy_id']], // MUST be object for Metabase + 'exp' => time() + (10 * 60), // 10 minutes ]; $token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256'); @@ -5525,18 +5391,18 @@ class EmployeeRestController extends AdminController // ]); // if($this->request->getGet('api') == 1) // { - return $this->respond([ - 'status' => 'success', - 'message' => 'Form data received successfully!', - 'data' => [ - 'metabaseToken' => $token, - 'metabaseUrl' => 'https://nsights.nhanceindia.in' - ], - 'is_tpa_dashboard_enable' => !empty($is_tpa_dashboard_enable ?? []), - ]); + return $this->respond([ + 'status' => 'success', + 'message' => 'Form data received successfully!', + 'data' => [ + 'metabaseToken' => $token, + 'metabaseUrl' => 'https://nsights.nhanceindia.in', + ], + 'is_tpa_dashboard_enable' => ! empty($is_tpa_dashboard_enable ?? []), + ]); // } - return view('meta_dashboard_demo_one', [ + return view('meta_dashboard_demo_one', [ 'metabaseToken' => $token, 'metabaseUrl' => 'https://nsights.nhanceindia.in', ]); @@ -5549,7 +5415,7 @@ class EmployeeRestController extends AdminController if ($return_type === 'api') { $received_data = $this->request->getJSON(true) ?? []; - $policy_id = $received_data['client_policy_id'] ?? null; + $policy_id = $received_data['client_policy_id'] ?? null; } else { // Internal call @@ -5560,7 +5426,7 @@ class EmployeeRestController extends AdminController return $this->respond([ 'status' => 'failed', 'message' => 'Client Policy ID is required.', - 'data' => [] + 'data' => [], ]); } @@ -5576,16 +5442,16 @@ class EmployeeRestController extends AdminController return $this->respond([ 'status' => 'failed', 'message' => 'There is no dashboard for this TPA.', - 'data' => [] + 'data' => [], ]); } $payload = [ 'resource' => [ - 'dashboard' => $database_id + 'dashboard' => $database_id, ], - 'exp' => time() + (10 * 60), - 'params' => (object)[] + 'exp' => time() + (10 * 60), + 'params' => (object) [], ]; $token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256'); @@ -5595,7 +5461,7 @@ class EmployeeRestController extends AdminController // Return raw data for internal usage return [ 'metabaseToken' => $token, - 'metabaseUrl' => 'https://nsights.nhanceindia.in' + 'metabaseUrl' => 'https://nsights.nhanceindia.in', ]; } @@ -5604,11 +5470,10 @@ class EmployeeRestController extends AdminController 'message' => 'Dashboard fetched successfully.', 'data' => [ 'metabaseToken' => $token, - 'metabaseUrl' => 'https://nsights.nhanceindia.in' - ] + 'metabaseUrl' => 'https://nsights.nhanceindia.in', + ], ]); } - // get policy files public function getPolicyAndEndorsementFiles() @@ -5617,79 +5482,77 @@ class EmployeeRestController extends AdminController $cdModel = new ClientDepositModel(); $cd_data = $cdModel->where('id', $cd_ac_pk) - ->where('is_active', 1) - ->where('client_policy_id IS NOT NULL') - ->first(); + ->where('is_active', 1) + ->where('client_policy_id IS NOT NULL') + ->first(); - if(empty($cd_data)){ + if (empty($cd_data)) { $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Deposit data found for cd_ac_pk=' . $cd_ac_pk); return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200); } $client_policy_data = $this->clientPolicyModel - ->where('id', $cd_data['client_policy_id']) - ->where('is_active', 1) - ->first(); + ->where('id', $cd_data['client_policy_id']) + ->where('is_active', 1) + ->first(); - if(empty($client_policy_data)){ + if (empty($client_policy_data)) { $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Client Policy data found for client_policy_id=' . $cd_data['client_policy_id']); return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200); } - $policyTransactionModel = new PolicyTransactionModel(); - $builder = $policyTransactionModel + $policyTransactionModel = new PolicyTransactionModel(); + $builder = $policyTransactionModel ->where('is_active', 1) ->where('policy_no', $client_policy_data['policy_no']) ->where('action_type', $cd_data['event_name']); - if (!empty($cd_data['endorsement_no']) && $cd_data['event_name'] != 'inception') { + if (! empty($cd_data['endorsement_no']) && $cd_data['event_name'] != 'inception') { $builder->where('endorsement_no', $cd_data['endorsement_no']); } $policy_transaction_data = $builder->findAll(); - if(empty($policy_transaction_data)){ + if (empty($policy_transaction_data)) { $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No Policy Transaction data found for policy_no=' . $client_policy_data['policy_no']); return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200); } $policy_transaction_ids = array_column($policy_transaction_data, 'id'); - - $ptFilesModel = new PTFileModel(); + $ptFilesModel = new PTFileModel(); $pt_files_data = $ptFilesModel->where('is_active', 1)->whereIn('pt_id', $policy_transaction_ids)->findAll(); - if(empty($pt_files_data)){ + if (empty($pt_files_data)) { $this->myLogger->logme('error', 'getPolicyAndEndorsementFiles: No PT Files data found for pt_ids=' . implode(',', $policy_transaction_ids)); return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file found', 'data' => []], 200); } - return $this->respond(['status' => true, 'code' => 200, 'message' => 'Files found', 'data' => $pt_files_data], 200); - + } // download policy file public function downloadPolicyFiles() - { + { $pt_file_id = $this->request->getGet('file_id') ?? null; - if(empty($pt_file_id)){ + if (empty($pt_file_id)) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'File ID is required'], 200); } $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; - $ptFilesModel = new PTFileModel(); + $ptFilesModel = new PTFileModel(); $pt_files_data = $ptFilesModel->where('is_active', 1)->where('id', $pt_file_id)->first(); - if(empty($pt_files_data)){ + if (empty($pt_files_data)) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200); } $filePath = $uploadFilePath . '/' . $pt_files_data['file_name']; - if (!file_exists($filePath)) { + if (! file_exists($filePath)) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Physical File Not Found in server'], 200); } @@ -5702,29 +5565,29 @@ class EmployeeRestController extends AdminController $received_data = $this->request->getJSON(true) ?? null; $this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Received payload = ' . json_encode($received_data ?? [])); - if(empty($received_data['client_policy_id']) && empty($received_data['emp_policy_ids'])){ + if (empty($received_data['client_policy_id']) && empty($received_data['emp_policy_ids'])) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'client_policy_id or employee_policy_ids is required'], 200); } - if(empty($received_data['hr_id'])){ + if (empty($received_data['hr_id'])) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'hr_id is required'], 200); } $employee_data = $this->employeePolicyModel->getEmployeeDataWithPolicyUsingClientPolicyIdOrEmployeePolicyIds($received_data); - if(empty($employee_data)){ + if (empty($employee_data)) { return $this->respond(['status' => false, 'code' => 404, 'message' => 'No employee data found for the policy'], 200); } - + $received_data['folder_name'] = 'bulk_ecards_' . $employee_data[0]['policy_no'] . '_' . date('Y-m-d_H-i-s'); // Dispatch background job to process the bulk e-card download - $r = Jobs::addJob(['job_name' => 'bulkEcardDownloadAsZipFromS3', 'payload' => $received_data]); + $r = Jobs::addJob(['job_name' => 'bulkEcardDownloadAsZipFromS3', 'payload' => $received_data]); $this->myLogger->logme('error', 'bulkEcardDownloadAsZip: Job dispatched with result = ' . json_encode($r ?? [])); - + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Bulk E-card download process started. Link share your mail'], 200); - } + } public function bulkEcardDownloadAsZipNew() { @@ -5754,8 +5617,8 @@ class EmployeeRestController extends AdminController 'misc_data' => json_encode([ 'folder_name' => $folderName, 'status' => 'pending', - 's3_key' => null - ]) + 's3_key' => null, + ]), ]; $zip_id = $this->UserActivityHistoryModel->insert($insert_data); @@ -5765,7 +5628,7 @@ class EmployeeRestController extends AdminController 'folder_name' => $folderName, 'batch_no' => 1, 'last_id' => 0, - 'limit' => 100 + 'limit' => 100, ]); // Dispatch job @@ -5773,7 +5636,7 @@ class EmployeeRestController extends AdminController return $this->respond([ 'status' => true, - 'message' => 'Process started. You will receive an email with the download link shortly.' + 'message' => 'Process started. You will receive an email with the download link shortly.', ], 200); } diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 2c2d9bcf..a712688f 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -1035,7 +1035,7 @@ class LeadsController extends BaseController $multi_file_data = []; foreach ($files as $index => $value) { - $file_name = file_Upload_for_lead($value, $uploadFilePath); + $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES); $multi_file_data[] = [ 'file_name' => $file_name, 'docs_name' => $docs_names[$index], diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index c03b7069..4087b301 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -367,7 +367,7 @@ class MasterController extends AdminController } $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); @@ -593,7 +593,7 @@ class MasterController extends AdminController } $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['PrimaryKey']; @@ -974,11 +974,11 @@ class MasterController extends AdminController $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $template_bg_path = ROOTPATH . 'public/uploads/template_bg'; - $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path); - $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); + $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES); + $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES); $eCardTemplate = $sanitized_post_data['ecard_content']; @@ -1264,11 +1264,11 @@ class MasterController extends AdminController $uploadFilePath = ROOTPATH . 'public/uploads/logo/'; - $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); + $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES); $template_bg_path = ROOTPATH . 'public/uploads/template_bg'; - $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path); - $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); + $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES); + $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES); $id = $sanitized_post_data['PrimaryKey'] ?? null; diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php index 8014f0c5..4b743cc3 100755 --- a/app/Controllers/NotificationController.php +++ b/app/Controllers/NotificationController.php @@ -364,7 +364,7 @@ class NotificationController extends AdminController // Define upload path and attempt file upload $uploadFilePath = WRITEPATH . 'uploads/attachments'; $uploadedFile = $this->request->getFile('file'); - $fileName = file_Upload_for_lead($uploadedFile, $uploadFilePath); // Assume file_Upload handles file saving + $fileName = file_Upload_for_lead($uploadedFile, $uploadFilePath, UPLOAD_EXT_MAIL_ATTACHMENTS); if ($fileName) { // Prepare data for insertion diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index c6b47973..59c115fe 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -3411,7 +3411,7 @@ class PolicyTransactionController extends BaseController if (!empty($docName) && $file->isValid() && !$file->hasMoved()) { // Upload the file - $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath); + $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath, UPLOAD_EXT_POLICY_DOCS); if ($uploadedFileName) { // Prepare data for each document upload diff --git a/app/Controllers/RuleImportController.php b/app/Controllers/RuleImportController.php index e624fbad..3a6c53e4 100644 --- a/app/Controllers/RuleImportController.php +++ b/app/Controllers/RuleImportController.php @@ -104,6 +104,10 @@ class RuleImportController extends AdminController return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']); } + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return $this->response->setJSON(['status'=>false,'message'=>'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.']); + } + // Move uploaded file to writable temp location $tmpPath = WRITEPATH . 'uploads/' . $file->getRandomName(); $file->move(WRITEPATH . 'uploads', $file->getName()); // keep original name inside uploads @@ -140,6 +144,10 @@ class RuleImportController extends AdminController return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file uploaded or upload error.'], 200); } + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.'], 200); + } + // --------------------------------------------------------- // 2. Read POST fields // --------------------------------------------------------- diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 56842b57..01109672 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -3237,7 +3237,7 @@ class TicketController extends BaseController $file_data = []; if(isset($get_file_data) && !empty($get_file_data)){ $file_path = WRITEPATH . 'uploads/claim_files/'; - $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); + $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS); } if(!empty($file_data)){ @@ -3932,7 +3932,7 @@ class TicketController extends BaseController if ($is_moved) { $file_path = WRITEPATH.'uploads/claims_mis'; - $filename = file_Upload_for_lead($file, $file_path); + $filename = file_Upload_for_lead($file, $file_path, UPLOAD_EXT_EXCEL); $fileSize = $file->getSize(); // File size in bytes $fileSize = $fileSize / (1024 * 1024); // Convert to MB @@ -3983,7 +3983,7 @@ class TicketController extends BaseController } $file_path = WRITEPATH.'uploads/claims_mis'; - $file_name = file_Upload_for_lead($file, $file_path); + $file_name = file_Upload_for_lead($file, $file_path, UPLOAD_EXT_EXCEL); if(!empty($file_name)){ $data['file_name'] = $file_name; diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 97ed35bd..e2947d7d 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -1009,8 +1009,15 @@ class UserController extends AdminController $fileId = $this->request->getPost('id'); if ($file && $file->isValid() && !$file->hasMoved()) { - - $originalName = $file->getClientName(); + + if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) { + return $this->response->setJSON([ + 'status' => 'error', + 'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.', + ])->setStatusCode(400); + } + + $originalName = sanitize_upload_filename($file->getClientName()); $extension = $file->getExtension(); $fileName = pathinfo($originalName, PATHINFO_FILENAME) . '_' . date('Ymd_His') . '.' . $extension; diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php index efc2842e..c5237bc5 100755 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -1,21 +1,19 @@ '; - // Set version to 0100 + // Set version to 0100 $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set bits 6-7 to 10 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); @@ -26,8 +24,8 @@ if (!function_exists('generate_uuid')) { } } -if (!function_exists('change_date_format2')) { - +if (! function_exists('change_date_format2')) { + function change_date_format2($data, $source_format, $output_format) { $data = trim($data); @@ -53,13 +51,47 @@ if (!function_exists('change_date_format2')) { } } -if (!function_exists('file_Upload')) { - function file_Upload($fileToUpload, $filepath) +if (! function_exists('sanitize_upload_filename')) { + function sanitize_upload_filename(string $fileName): string { - if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { - $fileToUpload->move($filepath); - $fileName = $fileToUpload->getName(); - $fileName = preg_replace('/[\s\x{00A0}\x{200B}-\x{200D}\x{FEFF}]/u', '', $fileName); + $fileName = preg_replace('/[\x00-\x1F\x7F]/u', '', $fileName); + $fileName = preg_replace('/[\x{00A0}\x{200B}-\x{200D}\x{FEFF}\x{00AD}\x{2060}\x{180E}\x{2028}\x{2029}]/u', '', $fileName); + $fileName = preg_replace('/[\/\\\\:*?"<>|;`${}()\'&!#]/', '', $fileName); + $fileName = preg_replace('/\.{2,}/', '.', $fileName); + $fileName = trim($fileName, ". \t\n\r"); + + if ($fileName === '' || strlen($fileName) > 200) { + $fileName = time() . '_' . bin2hex(random_bytes(8)); + } + + return $fileName; + } +} + +if (! function_exists('validate_upload_extension')) { + function validate_upload_extension($file, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS): bool + { + $ext = strtolower($file->getClientExtension()); + if (! in_array($ext, $allowedExtensions, true)) { + log_message('critical', '[UPLOAD_HELPER] Blocked extension: {ext} | File: {name}', [ + 'ext' => $ext, + 'name' => $file->getClientName(), + ]); + return false; + } + return true; + } +} + +if (! function_exists('file_Upload')) { + function file_Upload($fileToUpload, $filepath, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS) + { + if ($fileToUpload !== null && $fileToUpload->isValid() && ! $fileToUpload->hasMoved()) { + if (! validate_upload_extension($fileToUpload, $allowedExtensions)) { + return ""; + } + $fileName = sanitize_upload_filename($fileToUpload->getName()); + $fileToUpload->move($filepath, $fileName); return $fileName; } else { return ""; @@ -67,12 +99,15 @@ if (!function_exists('file_Upload')) { } } -if (!function_exists('file_Upload_for_lead')) { - function file_Upload_for_lead($fileToUpload, $filepath) +if (! function_exists('file_Upload_for_lead')) { + function file_Upload_for_lead($fileToUpload, $filepath, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS) { - if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { - $fileToUpload->move($filepath); - $fileName = $fileToUpload->getName(); + if ($fileToUpload !== null && $fileToUpload->isValid() && ! $fileToUpload->hasMoved()) { + if (! validate_upload_extension($fileToUpload, $allowedExtensions)) { + return ""; + } + $fileName = sanitize_upload_filename($fileToUpload->getName()); + $fileToUpload->move($filepath, $fileName); return $fileName; } else { return ""; @@ -97,7 +132,7 @@ if (!function_exists('file_Upload_for_lead')) { // ]; // } // } -// } +// } // // Handle single file // else { // if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { @@ -115,8 +150,8 @@ if (!function_exists('file_Upload_for_lead')) { // } // function for only using in the Flutter Claim File Upload -if (!function_exists('multi_file_Upload')) { - function multi_file_Upload($fileToUpload, $filepath, $docs_name = []) +if (! function_exists('multi_file_Upload')) { + function multi_file_Upload($fileToUpload, $filepath, $docs_name = [], array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS) { $uploadedFiles = []; @@ -127,26 +162,32 @@ if (!function_exists('multi_file_Upload')) { // If file is itself an array (multiple under same input name) if (is_array($file)) { foreach ($file as $index => $f) { - if ($f !== null && $f->isValid() && !$f->hasMoved()) { - $fileRandomName = $f->getRandomName(); // safer unique name - $fileName = $f->getName(); + if ($f !== null && $f->isValid() && ! $f->hasMoved()) { + if (! validate_upload_extension($f, $allowedExtensions)) { + continue; + } + $fileRandomName = $f->getRandomName(); + $fileName = sanitize_upload_filename($f->getName()); $f->move($filepath, $fileRandomName); $uploadedFiles[] = [ 'file_name' => $fileName, - 'doc_name' => $docs_name[$index] ?? $fileName, - // 'file_path' => $filepath . $fileRandomName - 'file_path' => $fileRandomName + 'doc_name' => $docs_name[$index] ?? $fileName, + 'file_path' => $fileRandomName, ]; } } } else { // Single file - if ($file !== null && $file->isValid() && !$file->hasMoved()) { - $fileName = $file->getRandomName(); - $file->move($filepath, $fileName); + if ($file !== null && $file->isValid() && ! $file->hasMoved()) { + if (! validate_upload_extension($file, $allowedExtensions)) { + continue; + } + $fileName = sanitize_upload_filename($file->getName()); + $diskName = $file->getRandomName(); + $file->move($filepath, $diskName); $uploadedFiles[] = [ 'file_name' => $fileName, - 'file_path' => $filepath . $fileName + 'file_path' => $filepath . $diskName, ]; } } @@ -156,8 +197,7 @@ if (!function_exists('multi_file_Upload')) { } } - -if (!function_exists('file_unlink')) { +if (! function_exists('file_unlink')) { function file_unlink($filepath) { if (is_file($filepath) && file_exists($filepath)) { @@ -166,7 +206,7 @@ if (!function_exists('file_unlink')) { } } -if (!function_exists('compressImage')) { +if (! function_exists('compressImage')) { function compressImage($file, $destinationPath, $newWidth = 100, $newHeight = 100) { // Load the image manipulation library @@ -174,23 +214,24 @@ if (!function_exists('compressImage')) { // Resize and compress the image $image->withFile($file) - ->fit($newWidth, $newHeight, 'center') - ->save($destinationPath); + ->fit($newWidth, $newHeight, 'center') + ->save($destinationPath); return true; } } -if (!function_exists('fancy_date_time_format')) { - function fancy_date_time_format($datetime,$return_type = 'fancy') { +if (! function_exists('fancy_date_time_format')) { + function fancy_date_time_format($datetime, $return_type = 'fancy') + { date_default_timezone_set('Asia/Kolkata'); $currentDateTime = new DateTime(); - $passedDateTime = new DateTime($datetime); - + $passedDateTime = new DateTime($datetime); + // Calculate the interval between the current time and the passed datetime $interval = $currentDateTime->diff($passedDateTime); - + // If the interval is more than 1 month or the year is different, return the original datetime if ($interval->m > 1 || $interval->y != 0) { if ($return_type == 'fancy') { @@ -215,7 +256,7 @@ if (!function_exists('fancy_date_time_format')) { } -if(!function_exists('check_string_date')){ +if (! function_exists('check_string_date')) { function check_string_date($str) { if (DateTime::createFromFormat('Y-m-d H:i:s', $str) !== false) { @@ -225,10 +266,11 @@ if(!function_exists('check_string_date')){ } } -if (!function_exists('generate_download_link')) { +if (! function_exists('generate_download_link')) { + + function generate_download_link($rand_string) + { - function generate_download_link($rand_string) { - // Generate the link using provided emp_code and client_policy_id $link = htmlspecialchars(base_url('download-e-card/' . $rand_string)); @@ -238,8 +280,9 @@ if (!function_exists('generate_download_link')) { } } -if (!function_exists('generate_random_alphanumeric')) { - function generate_random_alphanumeric($length = 12) { +if (! function_exists('generate_random_alphanumeric')) { + function generate_random_alphanumeric($length = 12) + { $random_string = ''; for ($i = 0; $i < $length; $i++) { $random_ascii = rand(0, 61); @@ -256,7 +299,7 @@ if (!function_exists('generate_random_alphanumeric')) { } } -if (!function_exists('get_base64_image')) { +if (! function_exists('get_base64_image')) { function get_base64_image($path) { @@ -273,49 +316,51 @@ if (!function_exists('get_base64_image')) { } } -if (!function_exists('format_indian_number')) { - function format_indian_number($number) { - // Round the number to two decimal places - $number = isset($number) ? $number : 0; - $number = round($number, 2); +if (! function_exists('format_indian_number')) { + function format_indian_number($number) + { + // Round the number to two decimal places + $number = isset($number) ? $number : 0; + $number = round($number, 2); - // Split the number into integer and decimal parts - $numberParts = explode('.', number_format($number, 2, '.', '')); - $integerPart = $numberParts[0]; - $decimalPart = isset($numberParts[1]) ? $numberParts[1] : '00'; + // Split the number into integer and decimal parts + $numberParts = explode('.', number_format($number, 2, '.', '')); + $integerPart = $numberParts[0]; + $decimalPart = isset($numberParts[1]) ? $numberParts[1] : '00'; - // Format the integer part with commas - $length = strlen($integerPart); - $formattedStr = ''; - $counter = 0; + // Format the integer part with commas + $length = strlen($integerPart); + $formattedStr = ''; + $counter = 0; - for ($i = $length - 1; $i >= 0; $i--) { - $formattedStr = $integerPart[$i] . $formattedStr; - $counter++; - if ($counter == 3 && $i != 0) { - $formattedStr = ',' . $formattedStr; - $counter = 0; - } elseif ($counter == 2 && $i != 0 && $length - $i > 3) { - $formattedStr = ',' . $formattedStr; - $counter = 0; + for ($i = $length - 1; $i >= 0; $i--) { + $formattedStr = $integerPart[$i] . $formattedStr; + $counter++; + if ($counter == 3 && $i != 0) { + $formattedStr = ',' . $formattedStr; + $counter = 0; + } elseif ($counter == 2 && $i != 0 && $length - $i > 3) { + $formattedStr = ',' . $formattedStr; + $counter = 0; + } } - } - // Combine the integer and decimal parts - return $formattedStr . '.' . $decimalPart; + // Combine the integer and decimal parts + return $formattedStr . '.' . $decimalPart; } } -if (!function_exists('get_username')) { - function get_username($user_id) { +if (! function_exists('get_username')) { + function get_username($user_id) + { // Connect to the database $db = \Config\Database::connect(); // Query the database $query = $db->table('user_profiles') - ->select('first_name') - ->where('id', $user_id) - ->get(); + ->select('first_name') + ->where('id', $user_id) + ->get(); // Get the result $result = $query->getRow(); @@ -325,21 +370,23 @@ if (!function_exists('get_username')) { } } -if (!function_exists('get_role_id')) { - function get_role_id() { +if (! function_exists('get_role_id')) { + function get_role_id() + { $role_id = isset(get_session_userdata()->role) ? get_session_userdata()->role : null; return $role_id; } } -if (!function_exists('teams')) { - function teams() { +if (! function_exists('teams')) { + function teams() + { // Load the UserTeamsModel $teamModel = new \App\Models\UserTeamsModel(); // Get the user ID from the session $user_id = get_session_userid(); - + // Fetch the team IDs associated with the user $user_teams = $teamModel->select('team_id')->where('user_id', $user_id)->findAll(); @@ -348,7 +395,7 @@ if (!function_exists('teams')) { // log_message('info', 'User Teams: ' . json_encode($user_teams)); // Optionally log it // Check if the result is not empty - if (!empty($user_teams)) { + if (! empty($user_teams)) { // Extract only the 'team_id' values $team_ids = array_column($user_teams, 'team_id'); return $team_ids; // Return array of team IDs @@ -358,15 +405,14 @@ if (!function_exists('teams')) { } } - - -if (!function_exists('generate_client_code')) { - function generate_client_code($string = 'GC') { +if (! function_exists('generate_client_code')) { + function generate_client_code($string = 'GC') + { $clientModel = new \App\Models\ClientModel(); - + $latestClient = $clientModel->select('id')->orderBy('id', 'DESC')->first(); - $id = $latestClient ? $latestClient['id'] : 0; + $id = $latestClient ? $latestClient['id'] : 0; $year = date('y'); @@ -378,21 +424,22 @@ if (!function_exists('generate_client_code')) { } } -if (!function_exists('generate_tsi_code')) { - function generate_tsi_code($type) { +if (! function_exists('generate_tsi_code')) { + function generate_tsi_code($type) + { $PolicyTransactionModel = new \App\Models\PolicyTransactionModel(); - - $latestClient = $PolicyTransactionModel->select('id')->orderBy('id', 'DESC')->first(); - $id = $latestClient ? $latestClient['id'] : 0; - $year = date('y'); - $month = date('m'); + $latestClient = $PolicyTransactionModel->select('id')->orderBy('id', 'DESC')->first(); + $id = $latestClient ? $latestClient['id'] : 0; + + $year = date('y'); + $month = date('m'); $string = 'P'; - if($type == 2){ + if ($type == 2) { $string2 = 'R'; - }else{ + } else { $string2 = 'F'; } @@ -404,35 +451,37 @@ if (!function_exists('generate_tsi_code')) { } } -if (!function_exists('generateRandomCode')) { - function generateRandomCode($prefix = 'RTL-', $length = 6) { +if (! function_exists('generateRandomCode')) { + function generateRandomCode($prefix = 'RTL-', $length = 6) + { // Generate a random number with the specified length - $randomNumber = str_pad(mt_rand(0, pow(10, $length)-1), $length, '0', STR_PAD_LEFT); - + $randomNumber = str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT); + // Return the code with the prefix return $prefix . $randomNumber; } } -if (!function_exists('excelFileGDriveUpload')) { +if (! function_exists('excelFileGDriveUpload')) { - function excelFileGDriveUpload($file_id, $table_name) { - $doc_type = "UPLOADS"; + function excelFileGDriveUpload($file_id, $table_name) + { + $doc_type = "UPLOADS"; $uploadFilePath = WRITEPATH . 'uploads/' . ($table_name == 'batch_file' ? 'import_excel' : 'excel'); $models = [ 'batch_file' => [ - 'model' => new BatchFileModel(), - 'select' => "client_id, client_policy_id, file_name" + 'model' => new BatchFileModel(), + 'select' => "client_id, client_policy_id, file_name", ], - 'files' => [ - 'model' => new FileModel(), - 'select' => "client_id, policy_id as client_policy_id, file_name" + 'files' => [ + 'model' => new FileModel(), + 'select' => "client_id, policy_id as client_policy_id, file_name", ], ]; - if (!array_key_exists($table_name, $models)) { - return; + if (! array_key_exists($table_name, $models)) { + return; } // Retrieve data @@ -442,54 +491,53 @@ if (!function_exists('excelFileGDriveUpload')) { ->where('is_active', 1) ->first(); - - if ($data) { $uploadFilePath .= '/' . $data['file_name']; // dd($data, $uploadFilePath); $GoogleDriveController = new GoogleDriveController(); - $result = $GoogleDriveController->uploadFiletoGdrive( + $result = $GoogleDriveController->uploadFiletoGdrive( // client_id : $data['client_id'], client_policy_id: $data['client_policy_id'], - doc_type : $doc_type, - file_path : $uploadFilePath, - file_name : $data['file_name'] + doc_type: $doc_type, + file_path: $uploadFilePath, + file_name: $data['file_name'] ); // dd($result); return true; - }else{ + } else { return false; } } } -if(!function_exists('checkFamilyFloaters')){ +if (! function_exists('checkFamilyFloaters')) { - function checkFamilyFloaters($policy_premium_data, $client_policy_data, $emp_data){ + function checkFamilyFloaters($policy_premium_data, $client_policy_data, $emp_data) + { - if($policy_premium_data['premium_type'] == 1){ + if ($policy_premium_data['premium_type'] == 1) { //only family floater if ($emp_data['relationship'] == 'Self') { return true; } - if($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3){ - if($emp_data['rata_premimum'] > 0){ + if ($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3) { + if ($emp_data['rata_premimum'] > 0) { return true; - }else{ + } else { return false; } } return false; - }else{ + } else { //individual return true; } @@ -497,20 +545,20 @@ if(!function_exists('checkFamilyFloaters')){ } } -if (!function_exists('numberToWords')) { +if (! function_exists('numberToWords')) { function numberToWords($number) { - $words = array( - '0' => 'Zero', - '1' => 'One', - '2' => 'Two', - '3' => 'Three', - '4' => 'Four', - '5' => 'Five', - '6' => 'Six', - '7' => 'Seven', - '8' => 'Eight', - '9' => 'Nine', + $words = [ + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '3' => 'Three', + '4' => 'Four', + '5' => 'Five', + '6' => 'Six', + '7' => 'Seven', + '8' => 'Eight', + '9' => 'Nine', '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve', @@ -528,30 +576,30 @@ if (!function_exists('numberToWords')) { '60' => 'Sixty', '70' => 'Seventy', '80' => 'Eighty', - '90' => 'Ninety' - ); + '90' => 'Ninety', + ]; if ($number < 21) { return $words[$number]; } if ($number < 100) { - $tens = (int)($number / 10) * 10; + $tens = (int) ($number / 10) * 10; $units = $number % 10; return $words[$tens] . ($units ? ' ' . $words[$units] : ''); } if ($number < 1000) { - $hundreds = (int)($number / 100); + $hundreds = (int) ($number / 100); $remainder = $number % 100; return $words[$hundreds] . ' Hundred' . ($remainder ? ' and ' . numberToWords($remainder) : ''); } - $levels = array('', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion'); + $levels = ['', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion']; for ($i = 0, $unit = 1; $i < count($levels); $i++, $unit *= 1000) { if ($number < $unit * 1000) { - $current = (int)($number / $unit); + $current = (int) ($number / $unit); $remainder = $number % $unit; return numberToWords($current) . $levels[$i] . ($remainder ? ' ' . numberToWords($remainder) : ''); } @@ -561,7 +609,7 @@ if (!function_exists('numberToWords')) { } } -if (!function_exists('print_rr')) { +if (! function_exists('print_rr')) { function print_rr($data) { echo "
";
@@ -570,7 +618,7 @@ if (!function_exists('print_rr')) {
     }
 }
 
-if (!function_exists('get_server_details')) {
+if (! function_exists('get_server_details')) {
     /**
      * Get the hostname and server name.
      *
@@ -578,70 +626,72 @@ if (!function_exists('get_server_details')) {
      */
     function get_server_details(): array
     {
-        $hostname = gethostname(); // Get the hostname of the server
+        $hostname   = gethostname();                        // Get the hostname of the server
         $serverName = $_SERVER['SERVER_NAME'] ?? 'Unknown'; // Get the server name
 
         return [
-            'hostname' => $hostname,
+            'hostname'    => $hostname,
             'server_name' => $serverName,
         ];
     }
 }
 
-if (!function_exists('isJsonString')) {
+if (! function_exists('isJsonString')) {
 
     function isJsonString($input)
     {
-        json_decode($input); // Decode the string
+        json_decode($input);                            // Decode the string
         return (json_last_error() === JSON_ERROR_NONE); // Check if the last JSON error is "no error"
     }
 }
 
-if (!function_exists('isValidDate')) {
-    function isValidDate($date, $format) {
+if (! function_exists('isValidDate')) {
+    function isValidDate($date, $format)
+    {
         $parsed_date = DateTime::createFromFormat($format, $date);
         return $parsed_date && $parsed_date->format($format) === $date;
     }
 }
 
-if (!function_exists('change_date_format')) {
+if (! function_exists('change_date_format')) {
 
-    function change_date_format($date_str, $source_format = null, $output_format = 'Y-m-d') {
+    function change_date_format($date_str, $source_format = null, $output_format = 'Y-m-d')
+    {
 
         $date_str = trim($date_str);
         // Allowed date formats
         $allowed_formats = [
-            // Day Month Year (clear unambiguous formats)
-            'd M Y',     // 01 Dec 2024
-            'd-M-Y',     // 01-Dec-2024
-            'd/M/Y',     // 01/Dec/2024
-            'd.M.Y',     // 01.Dec.2024
-            'd,M,Y',     // 01,Dec,2024
+                     // Day Month Year (clear unambiguous formats)
+            'd M Y', // 01 Dec 2024
+            'd-M-Y', // 01-Dec-2024
+            'd/M/Y', // 01/Dec/2024
+            'd.M.Y', // 01.Dec.2024
+            'd,M,Y', // 01,Dec,2024
 
-            // Month Day Year (clear unambiguous formats)
-            'M d Y',     // Dec 01 2024
-            'M-d-Y',     // Dec-01-2024
-            'M/d/Y',     // Dec/01/2024
-            'M.d.Y',     // Dec.01.2024
-            'M,d,Y',     // Dec,01,2024
+                     // Month Day Year (clear unambiguous formats)
+            'M d Y', // Dec 01 2024
+            'M-d-Y', // Dec-01-2024
+            'M/d/Y', // Dec/01/2024
+            'M.d.Y', // Dec.01.2024
+            'M,d,Y', // Dec,01,2024
 
-            // Year Month Day (clear unambiguous formats)
-            'Y M d',     // 2024 Dec 01
-            'Y-M-d',     // 2024-Dec-01
-            'Y/M/d',     // 2024/Dec/01
-            'Y.M.d',     // 2024.Dec.01
-            'Y,M,d',     // 2024,Dec,01
+                     // Year Month Day (clear unambiguous formats)
+            'Y M d', // 2024 Dec 01
+            'Y-M-d', // 2024-Dec-01
+            'Y/M/d', // 2024/Dec/01
+            'Y.M.d', // 2024.Dec.01
+            'Y,M,d', // 2024,Dec,01
 
-            // Year Numeric Month Numeric Day
-            'Y-m-d',     // 2024-12-01
-            'Y/m/d',     // 2024/12/01
-            'Y.m.d',     // 2024.12.01
-            'Y,m,d',     // 2024,12,01
+                     // Year Numeric Month Numeric Day
+            'Y-m-d', // 2024-12-01
+            'Y/m/d', // 2024/12/01
+            'Y.m.d', // 2024.12.01
+            'Y,m,d', // 2024,12,01
 
-            'd/m/Y',     // 01/01/2025
-            'd-m-Y',     // 01-01-2025
-            'm/d/Y h:i:s A',     // 01-01-2025
-            'm/d/Y',     // 25-05-2025
+            'd/m/Y',         // 01/01/2025
+            'd-m-Y',         // 01-01-2025
+            'm/d/Y h:i:s A', // 01-01-2025
+            'm/d/Y',         // 25-05-2025
 
         ];
 
@@ -649,7 +699,7 @@ if (!function_exists('change_date_format')) {
             // Case 1: Source and Output formats are provided
             if ($source_format !== null && $output_format !== null) {
                 $date = DateTime::createFromFormat($source_format, $date_str);
-                if (!$date) {
+                if (! $date) {
                     // throw new Exception("Invalid date string for source format: $source_format");
                     // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
                     return null;
@@ -660,7 +710,7 @@ if (!function_exists('change_date_format')) {
             // Case 2: Source format is provided, Output format is null
             if ($source_format !== null && $output_format === null) {
                 $date = DateTime::createFromFormat($source_format, $date_str);
-                if (!$date) {
+                if (! $date) {
                     // throw new Exception("Invalid date string for source format: $source_format");
                     // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
                     return null;
@@ -695,7 +745,7 @@ if (!function_exists('change_date_format')) {
     }
 }
 
-// if (!function_exists('check_pay_by_employee_or_company')) 
+// if (!function_exists('check_pay_by_employee_or_company'))
 // {
 
 //     function check_pay_by_employee_or_company($is_payable_employee = null, $relationship = null) {
@@ -711,7 +761,7 @@ if (!function_exists('change_date_format')) {
 //         }else if($relationship == 'spouse'){
 
 //             $result = $is_payable_employee['spouse'] == 1 ? 1 : 0;
-            
+
 //         }else if(in_array($relationship, ['son', 'daughter'])){
 
 //             $result = $is_payable_employee['childern'] == 1 ? 1 : 0;
@@ -726,55 +776,55 @@ if (!function_exists('change_date_format')) {
 //     }
 // }
 
-if (!function_exists('check_pay_by_employee_or_company')) {
+if (! function_exists('check_pay_by_employee_or_company')) {
 
     function check_pay_by_employee_or_company($policy_terms = null, $relationship = null)
     {
-       
+
         // dd($policy_terms, $relationship);
 
-        if (!$policy_terms || !($policy_terms = json_decode($policy_terms, true))) {
+        if (! $policy_terms || ! ($policy_terms = json_decode($policy_terms, true))) {
             return 0;
         }
 
         // dd($policy_terms, $relationship);
-    
-        if (!isset($policy_terms['is_payable_employee'])) {
-            return 0; 
+
+        if (! isset($policy_terms['is_payable_employee'])) {
+            return 0;
         }
-    
+
         $is_payable_employee = $policy_terms['is_payable_employee'];
-    
+
         $relationship = strtolower(str_replace(" ", "_", $relationship));
 
         // dd($is_payable_employee, $relationship);
-    
+
         $relationshipMap = [
-            'self' => 'self',
-            'spouse' => 'spouse',
-            'son' => 'childern',
-            'daughter' => 'childern',
-            'father' => 'elders',
-            'mother' => 'elders',
+            'self'          => 'self',
+            'spouse'        => 'spouse',
+            'son'           => 'childern',
+            'daughter'      => 'childern',
+            'father'        => 'elders',
+            'mother'        => 'elders',
             'father_in_law' => 'elders',
-            'mother_in_law' => 'elders'
+            'mother_in_law' => 'elders',
         ];
-    
+
         if (array_key_exists($relationship, $relationshipMap)) {
             $key = $relationshipMap[$relationship];
-    
+
             return isset($is_payable_employee[$key]) && $is_payable_employee[$key] == 1 ? 1 : 0;
         }
-    
+
         return 0;
     }
-    
+
 }
 
-if (!function_exists('is_json_string')) {
+if (! function_exists('is_json_string')) {
     function is_json_string($string)
     {
-        if (!is_string($string)) {
+        if (! is_string($string)) {
             return false;
         }
 
@@ -783,16 +833,16 @@ if (!function_exists('is_json_string')) {
     }
 }
 
-if (!function_exists('check_cd_entry_exist')) {
+if (! function_exists('check_cd_entry_exist')) {
     function check_cd_entry_exist($params)
     {
         $db = db_connect();
 
-        $client_id = $params['client_id'];
+        $client_id        = $params['client_id'];
         $client_policy_id = $params['client_policy_id'];
-        $insurer_id = $params['insurer_id'];
-        $cd_ac_pk = $params['cd_ac_pk'];
-        $event_name = $params['event_name'];
+        $insurer_id       = $params['insurer_id'];
+        $cd_ac_pk         = $params['cd_ac_pk'];
+        $event_name       = $params['event_name'];
 
         // Check if truncated entry (sub_type = 8) exists
         $has_truncated = $db->table('cash_deposit')
@@ -823,7 +873,7 @@ if (!function_exists('check_cd_entry_exist')) {
             if (count($entries) > 1) {
                 // Only one entry found (truncated)
                 return true;
-            }else{
+            } else {
                 return false;
             }
         } else {
@@ -838,7 +888,7 @@ if (!function_exists('check_cd_entry_exist')) {
                 ->get()
                 ->getRowArray();
 
-            if (!empty($entry)) {
+            if (! empty($entry)) {
                 return true;
             }
         }
@@ -847,24 +897,23 @@ if (!function_exists('check_cd_entry_exist')) {
     }
 }
 
-if (!function_exists('expected_amount_calc')) {
+if (! function_exists('expected_amount_calc')) {
     function expected_amount_calc($data, $index)
     {
-        $agreed_amount      = (float) ($data['agreed_amount'][$index] ?? 0);
-        $agreed_bp_per      = (float) ($data['agreed_bp'][$index] ?? 0);
-        $agreed_tp_per      = (float) ($data['agreed_tp'][$index] ?? 0);
-        $agreed_tep_per     = (float) ($data['agreed_ter'][$index] ?? 0);
+        $agreed_amount  = (float) ($data['agreed_amount'][$index] ?? 0);
+        $agreed_bp_per  = (float) ($data['agreed_bp'][$index] ?? 0);
+        $agreed_tp_per  = (float) ($data['agreed_tp'][$index] ?? 0);
+        $agreed_tep_per = (float) ($data['agreed_ter'][$index] ?? 0);
 
-        $standard_bp_per    = (float) ($data['standard_bp'][$index] ?? 0);
-        $standard_tp_per    = (float) ($data['standard_tp'][$index] ?? 0);
-        $standard_tep_per   = (float) ($data['standard_ter'][$index] ?? 0);
+        $standard_bp_per  = (float) ($data['standard_bp'][$index] ?? 0);
+        $standard_tp_per  = (float) ($data['standard_tp'][$index] ?? 0);
+        $standard_tep_per = (float) ($data['standard_ter'][$index] ?? 0);
 
-
-        if($data['bro_payable_by'] == 0){
+        if ($data['bro_payable_by'] == 0) {
             $base_premium       = (float) ($data['co_premium'][$index] ?? 0);
             $third_part_premium = (float) ($data['co_tp_premium'][$index] ?? 0);
             $terrisom_premium   = (float) ($data['co_ter_premium'][$index] ?? 0);
-        }else{
+        } else {
             $base_premium       = (float) ($data['base_premium'][$index] ?? 0);
             $third_part_premium = (float) ($data['tp_premium'][$index] ?? 0);
             $terrisom_premium   = (float) ($data['ter_premium'][$index] ?? 0);
@@ -892,24 +941,24 @@ if (!function_exists('expected_amount_calc')) {
     }
 }
 
-if (!function_exists('getFileIfExists')) {
+if (! function_exists('getFileIfExists')) {
     function getFileIfExists($path)
-    {   
+    {
         return file_exists(FCPATH . $path) ? base_url($path) : '';
     }
 }
 
-if (!function_exists('removeNumberFormatting')) {
+if (! function_exists('removeNumberFormatting')) {
     function removeNumberFormatting($number)
     {
         return (float) str_replace(',', '', trim($number));
     }
 }
 
-if (!function_exists('formatKey')) {
+if (! function_exists('formatKey')) {
     function formatKey($key, $len = 3)
     {
-        $words = explode('_', $key);
+        $words     = explode('_', $key);
         $formatted = array_map(function ($word) use ($len) {
             return strlen($word) < $len ? strtoupper($word) : ucfirst(strtolower($word));
         }, $words);
@@ -917,7 +966,7 @@ if (!function_exists('formatKey')) {
     }
 }
 
-if (!function_exists('getMimeTypeByFileName')) {
+if (! function_exists('getMimeTypeByFileName')) {
     function getMimeTypeByFileName($file_name)
     {
         $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
@@ -943,7 +992,7 @@ if (!function_exists('getMimeTypeByFileName')) {
     }
 }
 
-if (!function_exists('validateExcelFile')) {
+if (! function_exists('validateExcelFile')) {
 
     function validateExcelFile($file)
     {
@@ -963,13 +1012,13 @@ if (!function_exists('validateExcelFile')) {
             'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
             'application/vnd.oasis.opendocument.spreadsheet',
             'application/zip',
-            'application/octet-stream'
+            'application/octet-stream',
         ];
 
         $allowedExtensions = ['xls', 'xlsx', 'ods', 'xlsm'];
 
         // Get the actual values using CI4 methods
-        $mime = $file->getClientMimeType();
+        $mime      = $file->getClientMimeType();
         $extension = $file->getExtension(); // This is the CI4 method
 
         // 4. Validate
@@ -981,23 +1030,24 @@ if (!function_exists('validateExcelFile')) {
     }
 }
 
-if (!function_exists('generate_ecard_download_link_based_on_tpa')) {
+if (! function_exists('generate_ecard_download_link_based_on_tpa')) {
+
+    function generate_ecard_download_link_based_on_tpa($params)
+    {
 
-    function generate_ecard_download_link_based_on_tpa($params) {
-       
         $apiServiceController = new ApiServiceController();
-        $data = $apiServiceController->ecardRequest($params, $return_type = 'internal');
+        $data                 = $apiServiceController->ecardRequest($params, $return_type = 'internal');
         log_message('error', 'E-card request call from the helper for mail send');
 
-        if(isset($data['eCardDownload']) && !empty($data['eCardDownload'])){
+        if (isset($data['eCardDownload']) && ! empty($data['eCardDownload'])) {
             return $data['eCardDownload'];
-        }else{
+        } else {
             return $data['message'];
         }
     }
 }
 
-if (!function_exists('canSendOtp')) {
+if (! function_exists('canSendOtp')) {
     function canSendOtp(array $row, int $limitSeconds = 60): array
     {
         // If OTP does not exist → allow
@@ -1014,8 +1064,8 @@ if (!function_exists('canSendOtp')) {
         // If still within limit → block
         if ($currentTime < $allowedAfter) {
             return [
-                'allowed' => false,
-                'retry_after' => $allowedAfter - $currentTime
+                'allowed'     => false,
+                'retry_after' => $allowedAfter - $currentTime,
             ];
         }
 
@@ -1023,14 +1073,14 @@ if (!function_exists('canSendOtp')) {
     }
 }
 
-if (!function_exists('checkDuplicateClaim')) {
+if (! function_exists('checkDuplicateClaim')) {
 
-   function checkDuplicateClaim(array $params): bool
-    {   
+    function checkDuplicateClaim(array $params): bool
+    {
         $ticketMaster = new TicketMasterModel();
-        $query = $ticketMaster->where('is_active', 1);
+        $query        = $ticketMaster->where('is_active', 1);
 
-        if(empty($params['doa']) && empty($params['claim_amount'])){
+        if (empty($params['doa']) && empty($params['claim_amount'])) {
             return false;
         }
 
@@ -1043,26 +1093,25 @@ if (!function_exists('checkDuplicateClaim')) {
             }
         }
 
-        if (!$hasValidCondition) {
+        if (! $hasValidCondition) {
             return false;
         }
 
         $result = $query->countAllResults();
         // print_r($ticketMaster->getLastQuery()->getQuery());  die;
-        if($result > 0){ return true; }else{ return false; }
+        if ($result > 0) {return true;} else {return false;}
     }
 }
 
-
 function getRealClientIP()
 {
     $request = service('request');
 
-    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
+    if (! empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
         return $_SERVER['HTTP_CF_CONNECTING_IP'];
     }
 
-    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
+    if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
     }
 
@@ -1089,7 +1138,7 @@ function generateFingerprint(bool $exclude_ua = false): string
     // IPv6 handling
     elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
         // Use first 4 blocks of IPv6 (rough /64 grouping)
-        $blocks = explode(':', $ip);
+        $blocks  = explode(':', $ip);
         $ipGroup = implode(':', array_slice($blocks, 0, 4));
     }
     // Fallback
@@ -1097,16 +1146,13 @@ function generateFingerprint(bool $exclude_ua = false): string
         $ipGroup = 'unknown';
     }
 
-    if($exclude_ua){
+    if ($exclude_ua) {
         return hash('sha256', $ipGroup);
     }
     return hash('sha256', $ua . '|' . $ipGroup);
 }
 
-
-
-
-if (!function_exists('convertGoogleDriveToDownloadLink')) {
+if (! function_exists('convertGoogleDriveToDownloadLink')) {
     function convertGoogleDriveToDownloadLink(?string $url): ?string
     {
         if (empty($url)) {
@@ -1120,7 +1166,7 @@ if (!function_exists('convertGoogleDriveToDownloadLink')) {
         $patterns = [
             '#https?://drive\.google\.com/file/d/([^/]+)/?#',
             '#https?://drive\.google\.com/open\?id=([^&]+)#',
-            '#https?://drive\.google\.com/uc\?id=([^&]+)#'
+            '#https?://drive\.google\.com/uc\?id=([^&]+)#',
         ];
 
         foreach ($patterns as $pattern) {
@@ -1137,21 +1183,21 @@ if (!function_exists('convertGoogleDriveToDownloadLink')) {
     }
 }
 
-if (!function_exists('get_cd_balance')) {
+if (! function_exists('get_cd_balance')) {
     function get_cd_balance(): array
     {
         $session = session();
 
         return [
             'has_cd_balance'  => $session->has('cd_balance'),
-            'cd_balance'  => $session->get('cd_balance') ?? null,
+            'cd_balance'      => $session->get('cd_balance') ?? null,
             'hr_data'         => $session->get('hr_data') ?? [],
             'cd_balance_info' => $session->get('cd_balance_info') ?? [],
         ];
     }
 }
 
-if (!function_exists('clear_cd_balance_session')) {
+if (! function_exists('clear_cd_balance_session')) {
     function clear_cd_balance_session(): void
     {
         $session = session();
@@ -1164,16 +1210,25 @@ if (!function_exists('clear_cd_balance_session')) {
     }
 }
 
-if (!function_exists('format_gender_v2')) {
-    function format_gender_v2($gender) {
-        if (empty($gender)) return null;
+if (! function_exists('format_gender_v2')) {
+    function format_gender_v2($gender)
+    {
+        if (empty($gender)) {
+            return null;
+        }
 
         $g = strtoupper(trim($gender));
 
         // Direct-ah check pannuvom
-        if (str_starts_with($g, 'M')) return 'M'; // Male, M
-        if (str_starts_with($g, 'F')) return 'F'; // Female, F
-        
+        if (str_starts_with($g, 'M')) {
+            return 'M';
+        }
+        // Male, M
+        if (str_starts_with($g, 'F')) {
+            return 'F';
+        }
+        // Female, F
+
         // Others, Transgender, O - ivatrai 'O' ena return seiyum
         if (str_starts_with($g, 'O') || str_starts_with($g, 'T')) {
             return 'O';
@@ -1183,20 +1238,22 @@ if (!function_exists('format_gender_v2')) {
     }
 }
 
-if (!function_exists('map_relationship')) {
+if (! function_exists('map_relationship')) {
     /**
      * Employee -> self, WIFE -> spouse ena maatri return seiyum.
      */
-    function map_relationship($relation) {
-        if (empty($relation)) return '';
+    function map_relationship($relation)
+    {
+        if (empty($relation)) {
+            return '';
+        }
 
         // Case prechanai varaamal irukka lowercase-kku maatri check seivom
         $r = strtolower(trim($relation));
 
         if ($r == 'employee') {
             return 'self';
-        } 
-        else if ($r == 'wife') {
+        } else if ($r == 'wife') {
             return 'spouse';
         }
 
@@ -1205,135 +1262,123 @@ if (!function_exists('map_relationship')) {
     }
 }
 
-
 /**
-     * Extract identity from POST body or GET params.
-     * Looks for 'email' or 'mobile_number'.
-     */
-    function resolveIdentity($request): ?string
-    {
-        // Try POST body first
-        $email  = $request->getPost('email');
-        // print_r($email);die;
-        $mobile = $request->getPost('mobile_number');
+ * Extract identity from POST body or GET params.
+ * Looks for 'email' or 'mobile_number'.
+ */
+function resolveIdentity($request): ?string
+{
+    // Try POST body first
+    $email = $request->getPost('email');
+    // print_r($email);die;
+    $mobile = $request->getPost('mobile_number');
 
-        // Fallback to GET params
-        if (! $email && ! $mobile) {
-            $email  = $request->getGet('email');
-            $mobile = $request->getGet('mobile_number');
-        }
-        // Fallback to JSON params
-        if (! $email && ! $mobile) {
-         $req_data = $request->getJSON();
-         // print_r( $req_data);
-         
-         $mobile = $req_data->mobile_number ?? null;
-         // return trim($mobile_number);
+    // Fallback to GET params
+    if (! $email && ! $mobile) {
+        $email  = $request->getGet('email');
+        $mobile = $request->getGet('mobile_number');
+    }
+    // Fallback to JSON params
+    if (! $email && ! $mobile) {
+        $req_data = $request->getJSON();
+        // print_r( $req_data);
 
-         $email = $req_data->email ?? null;
-          
-          if (!$email)
-          {
+        $mobile = $req_data->mobile_number ?? null;
+        // return trim($mobile_number);
+
+        $email = $req_data->email ?? null;
+
+        if (! $email) {
             $email = $req_data->email_id ?? null;
-          }
-         // return trim($email);
         }
-
-        if ($email) {
-            return strtolower(trim($email));
-        }
-
-        if ($mobile) {
-            return trim($mobile);
-        }
-
-        return null;
+        // return trim($email);
     }
 
+    if ($email) {
+        return strtolower(trim($email));
+    }
 
-    function recordRateLimitFailure(string $context = 'authApi'): void
+    if ($mobile) {
+        return trim($mobile);
+    }
+
+    return null;
+}
+
+function recordRateLimitFailure(string $context = 'authApi'): void
+{
+    /** @var IncomingRequest $request */
+    $request = \Config\Services::request();
+
+    $limiter = \Config\Services::limiter(); // or your custom limiter service
+
+    $fingerprint = $request->getVar('rateLimitFingerprint') ?? generateFingerprint(exclude_ua: true);
+
+    $identity = $request->getVar('rateLimitIdentity') ?? resolveIdentity($request);
+
+    // Record IP-level failure
+    $limiter->recordIpFailure($fingerprint);
+
+    // Record user-level failure
+    if (! empty($identity)) {
+        $limiter->recordUserFailure($identity, $context);
+    }
+}
+
+if (! function_exists('getCurrentFinancialYear')) {
+    function getCurrentFinancialYear()
     {
-        /** @var IncomingRequest $request */
-        $request = \Config\Services::request();
+        // Get current year and month
+        $date         = new DateTime();
+        $currentYear  = (int) $date->format('Y');
+        $currentMonth = (int) $date->format('m');
 
-        $limiter = \Config\Services::limiter(); // or your custom limiter service
+        // If month is Jan, Feb, or March, we are still in the previous year's FY
+        if ($currentMonth < 4) {
+            $startYear = $currentYear - 1;
+            $endYear   = $currentYear;
+        } else {
+            $startYear = $currentYear;
+            $endYear   = $currentYear + 1;
+        }
 
-        $fingerprint = $request->getVar('rateLimitFingerprint')
-            ?? generateFingerprint(exclude_ua: true);
+        return $startYear . '-' . $endYear;
+    }
+}
 
-        
+if (! function_exists('format_financial_year')) {
+    function format_financial_year(string $financialYear): string
+    {
+        if (empty($financialYear) || ! str_contains($financialYear, '-')) {
+            return $financialYear;
+        }
 
-        $identity = $request->getVar('rateLimitIdentity')
-            ?? resolveIdentity($request);
+        $years = explode('-', $financialYear);
 
-        // Record IP-level failure
-        $limiter->recordIpFailure($fingerprint);
+        // Ensure we have both parts
+        $startYear = $years[0] ?? '';
+        $endYear   = $years[1] ?? '';
 
-        // Record user-level failure
-        if (!empty($identity)) {
-            $limiter->recordUserFailure($identity, $context);
+        return "APR " . $startYear . " - MAR " . $endYear;
+    }
+}
+
+if (! function_exists('add_google_calender_event')) {
+    function add_google_calender_event($data)
+    {
+
+        $calendar = new \App\Libraries\GoogleCalendarService();
+
+        // Check if user is authenticated without passing tokens manually
+        if (! $calendar->isReady()) {
+            return ['status' => 'failed', 'code' => '404', 'message' => 'Google Access Token Expired'];
+        }
+
+        try {
+            $response = $calendar->createEvent($data);
+            return ['status' => 'success', 'code' => '200', 'message' => 'Follow-up Saved', 'response' => $response];
+        } catch (\Exception $e) {
+            return ['status' => 'failed', 'code' => '500', 'message' => 'Error: ' . $e->getMessage()];
         }
     }
-
-
-    if (!function_exists('getCurrentFinancialYear')) {
-        function getCurrentFinancialYear() 
-        {
-            // Get current year and month
-            $date = new DateTime();
-            $currentYear = (int)$date->format('Y');
-            $currentMonth = (int)$date->format('m');
-
-            // If month is Jan, Feb, or March, we are still in the previous year's FY
-            if ($currentMonth < 4) {
-                $startYear = $currentYear - 1;
-                $endYear = $currentYear;
-            } else {
-                $startYear = $currentYear;
-                $endYear = $currentYear + 1;
-            }
-
-            return $startYear . '-' . $endYear;
-        }
-    }
-
-
-    if (!function_exists('format_financial_year')) {
-        function format_financial_year(string $financialYear): string
-        {
-            if (empty($financialYear) || !str_contains($financialYear, '-')) {
-                return $financialYear;
-            }
-
-            $years = explode('-', $financialYear);
-            
-            // Ensure we have both parts
-            $startYear = $years[0] ?? '';
-            $endYear   = $years[1] ?? '';
-
-            return "APR " . $startYear . " - MAR " . $endYear;
-        }
-    }
-
-
-    if(!function_exists('add_google_calender_event')){
-        function add_google_calender_event($data){
-            
-            $calendar = new \App\Libraries\GoogleCalendarService();
-
-            // Check if user is authenticated without passing tokens manually
-            if (!$calendar->isReady()) {
-                return ['status' => 'failed', 'code' => '404' , 'message' => 'Google Access Token Expired'];
-            }
-
-            try {
-                $response = $calendar->createEvent($data);
-                return ['status' => 'success', 'code' => '200' , 'message' => 'Follow-up Saved', 'response' => $response];
-            } catch (\Exception $e) {
-                return ['status' => 'failed', 'code' => '500' , 'message' => 'Error: ' . $e->getMessage()];
-            }
-        }
-    }
-
-
-
+}