nhance/app/Helpers/excel_util_helper.php

3744 lines
195 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
use App\Models\EmployeeModel;
use App\Models\InsurerModel;
use Kint\Kint;
if (!function_exists('calculate_days_bw_dates')) {
function calculate_days_bw_dates(string $from_date = "", string $to_date = "", bool $include_start_date = true)
{
if ($to_date == "") {
$currentDateTime = new DateTime();
} else {
$to_date = convert_string_to_date($to_date);
$currentDateTime = new DateTime($to_date);
}
if ($from_date == "") {
$passedDateTime = new DateTime();
} else {
$from_date = convert_string_to_date($from_date);
$passedDateTime = new DateTime($from_date);
}
$interval = $currentDateTime->diff($passedDateTime);
// $totalDays = $interval->days;
// if ($include_start_date) {
// $totalDays += 1;
// }
//$interval->totalDays = $totalDays;
return $interval;
}
}
if (!function_exists('check_columns_name')) {
function check_columns_name($definedColumns, $excelColumns)
{
$mismatchedColumns = [];
foreach ($definedColumns as $colName => $definedCol) {
$definedColIdx = $definedCol['col_idx'];
$definedColName = $definedCol['col_name'];
if (!empty($definedCol['is_column_optional']) && !array_key_exists($definedColIdx, $excelColumns)) {
continue;
}
if (strtolower(strip_tags(trim($excelColumns[$definedColIdx]))) !== strtolower($definedColName)) {
$mismatchedColumns[] = "Column order conflict. Column order no " . ($definedColIdx + 1) . " expected : " . $definedColName . " and received : " . $excelColumns[$definedColIdx] . "<br/>";
}
}
return $mismatchedColumns;
}
}
if (!function_exists('check_row_is_empty_or_null')) {
function check_row_is_empty_or_null($arr)
{
unset($arr[0]); // unset SNO in the array, becoz we need to check only datapoints are empty not SNo, it may added by accidentally
foreach ($arr as $item) {
if ($item !== null && !empty($item)) {
return false; // If any item is not empty or not null, return false
}
}
return true; // If all items are empty or null, return true
}
}
if (!function_exists('check_excel_date_format')) {
function check_excel_date_format($dateString, $format)
{
if ($dateString == "") {
return array('status' => true);
}
$date = DateTime::createFromFormat('d-M-Y', $dateString);
if ($date && $date->format('d-M-Y') == $dateString) {
return array('status' => true);
} else {
$res = convert_string_to_date($dateString);
if (!$res) {
return array('status' => false, 'error' => "wrong date format: Expected 'd-M-Y' and received $dateString");
} else {
return array('status' => true);
}
}
}
}
if (!function_exists('check_relationship')) {
function check_relationship($row, $relationship, $policy_terms)
{
// print_r($relationship);
// echo '<br>';
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
if ($row[5] != null && $row[4] != null) //$row[5] = relationship $row[4] = Gender
{
$slug = \Config\Services::slug();
$col = $slug->slugify($row[5]);
// echo $col;//die();
if ($col != 'self' && $col != 'spouse') {
if (!isset($relationship[$col])) {
return array('status' => false, 'error' => 'Rule Conflict: Unknown Relationship');
}
$family_floaters = isset($policy_terms['family_floaters']);
if ($family_floaters) {
$relation_gender = normalizeGender($row[4]);
if (isset($relationship[$col]) && $relationship[$col]['gender'] != $relation_gender) {
$error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[4]";
return array('status' => false, 'error' => $error);
}
} else // if family_floaters not set the its GPA, reject all other dependents
{
if ($col != 'self') {
$error = "Dependent(s) are not allowed";
return array('status' => false, 'error' => $error);
}
}
}
return array('status' => true);
} else {
return array('status' => false, 'error' => 'Rule Conflict: Both Relationship and Gender required for check relationship conflict');
}
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('check_doj')) {
function check_doj($row)
{
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
if ($relationship == 'self' && $row[8] == "") {
return array('status' => false, 'error' => "DOJ mandantory for self");
}
return array('status' => true);
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('check_doc')) {
function check_doc($row, $policy_details)
{
if ($row['current_action'] != null && $row[7] != null && $row[7] != '' && in_array(strtoupper($row['current_action']), ['A', 'DA'])) // check rule only of action column data available
{
// dd($policy_details);
$dateString = convert_string_to_date($row[7]);
if ($dateString) {
$date = new DateTime($dateString);
$startDate = new DateTime($policy_details[0]->policy_start_date);
$endDate = new DateTime($policy_details[0]->policy_end_date);
if ($date >= $startDate && $date <= $endDate) {
return array('status' => true);
} else {
return array('status' => false, 'error' => 'the given date of coverage is not between policy start/end date');
}
} else {
return array('status' => false, 'error' => 'date format error');
}
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('check_employee_band')) {
function check_employee_band($row, $policy_terms, $slab_details)
{
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
$is_emp_band_needed = $slab_details['grid_master']['emp_band'];
// $is_emp_band_needed = true;
if ($slab_details['grid_master']['ui_type'] == 1) //gpa rack rate 1
{
if ($slab_details['slab_rates'][0]['si_or_bp'] == 3) {
$is_emp_band_needed = true;
}
}
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
if ($is_emp_band_needed && $relationship == 'self' && $row[10] == "") {
return array('status' => false, 'error' => "Band mandantory for self");
} else if ($is_emp_band_needed && $relationship == 'self' && $row[10] != "") {
$received_grade = $row[10];
$found = false;
foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
if ($slab_value['grade'] == $received_grade) {
$found = true;
break;
}
}
if (!$found) {
return array('status' => false, 'error' => "Emp band/Grade not found");
}
}
return array('status' => true);
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('check_si')) {
function check_si($row, $policy_details, $slab_details)
{
// Kint::dump($policy_details);
$policy_details = (array)$policy_details[0];
// dd($policy_details);
$return_array = array('status' => true, 'error' => '');
$is_si_found = false;
$is_age_slab_found = false;
if (($policy_details['policy_type_id'] == 1 || $policy_details['policy_type_id'] == 6 || $policy_details['policy_type_id'] == 7) && $slab_details['slab_rates'][0]['policy_grid_id'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay
{
$is_si_found = true;
$is_age_slab_found = true;
$return_array = array('status' => true, 'error' => '');
}
if ($policy_details['policy_type_id'] == 3 && strtolower($row['5']) == 'self') // if GMC parent and current relation is self then skip this . so set all true;
{
$is_si_found = true;
$is_age_slab_found = true;
$return_array = array('status' => true, 'error' => '');
}
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'SI', 'MI'])) // check rule only of action column data available
{
$received_si = $row['current_action'] == 'SI' ? $row[3] : $row[6];
foreach ($slab_details['slab_rates'] as $skey => $slab_value) {
if ($is_si_found && $is_age_slab_found) {
break;
}
if (!$is_si_found && $slab_value['si'] == $received_si) //match si amount
{
// echo 'found - ' . $slab_value['si']. ' - ' . $received_si;
$is_si_found = true;
}
// check age slab
if (in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI']) && (($slab_value['premium_type'] == 1 && strtolower($row['5']) == 'self') || ($slab_value['premium_type'] == 2) || ($slab_value['premium_type'] == 3))) {
if ($row[3] != '' && $row[3] != null) // dob
{
$dob = convert_string_to_date($row[3]);
if ($dob !== false) {
// echo $row[3].' - '.$dob;echo '<br>';
$currentDateTime = new DateTime(); //die();
$passedDateTime = new DateTime($dob);
$interval = $currentDateTime->diff($passedDateTime);
if (!$is_age_slab_found) {
if (isset($slab_value['age_from']) && isset($slab_value['age_to'])) {
if ($slab_value['age_from'] !== null && $slab_value['age_to'] !== null && $slab_value['age_from'] <= $interval->y && $slab_value['age_to'] >= $interval->y && $slab_value['si'] == $received_si) {
$is_age_slab_found = true; // send true if age slab found
}
} else {
$is_age_slab_found = true; // send true if age conditin is not applicable
}
}
}
}
} else {
$is_age_slab_found = true; // send true if age conditin is not applicable
$is_si_found = true;
} //end of check age slab
} // end of for loop
}
if (!$is_si_found) {
$return_array['status'] = false;
$return_array['error'] = "Sum insured not found";
}
if (!$is_age_slab_found) {
$return_array['status'] = false;
$return_array['error'] = !empty($return_array['error']) ? ($return_array['error'] . ', ' . 'Sum insured not configured for this age slab') : 'Sum insured not configured for this age slab';
}
if (empty($received_si)) {
$return_array['status'] = false;
$return_array['error'] = "Sum insured value mandantory";
}
// !Kint::dump($return_array);
return $return_array;
}
}
if (!function_exists('check_basic_pay')) {
function check_basic_pay($row, $policy_terms, $slab_details)
{
// dd($row, $policy_terms, $slab_details);
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
// $is_basic_pay_needed = $slab_details['grid_master']['basicpay'];
$is_basic_pay_needed = ($slab_details['grid_master']['basicpay'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2 && $slab_details['slab_rates'][0]['basic_pay'] != null) ? 1 : 0;
// $is_basic_pay_needed = true;
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
// echo $relationship;echo $row[7];
if ($is_basic_pay_needed && $relationship == 'self' && $row[9] == "") {
return array('status' => false, 'error' => "Basic pay mandantory for self");
}
return array('status' => true);
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('check_dob_diff')) {
function check_dob_diff($row, $relationships, $default_age_ratio, $policy_details)
{
if ($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I', 'A', 'DA', 'MI'])) // check rule only of action column data available
{
if ($row[3] != null && $row[5] != null) {
$dateString = convert_string_to_date($row[3]);
if ($dateString === false) {
return array('status' => false, 'error' => 'Not a valid Date');
}
// return array('status' => true);
$dob = $dateString;
//$currentDateTime = new DateTime();//previously dob calculated from current date time
$temp_date = ($row[7] != null && $row[7] != "") ? convert_string_to_date($row[7]) : $policy_details[0]->policy_start_date; //pick date of coverage from row if not then use policy start date as from to calculate DOB
$currentDateTime = new DateTime($temp_date); //later DOB calculated from date of coverage or policy_start_date
// die();
$passedDateTime = new DateTime($dob);
$interval = $currentDateTime->diff($passedDateTime);
//remap default age ratio data into relationship array
if (count($default_age_ratio)) {
$relationships = remap_default_age_ratio_into_relationship($relationships, $default_age_ratio);
}
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[5]);
$age_min = isset($relationships[$relationship]['age_min']) ? $relationships[$relationship]['age_min'] : NULL;
$age_max = isset($relationships[$relationship]['age_max']) ? $relationships[$relationship]['age_max'] : NULL;
if ($age_min !== null && $age_min > $interval->y) {
return array('status' => false, 'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y");
}
if ($age_max !== null && $age_max < $interval->y) {
return array('status' => false, 'error' => "Age conflict : maximum $age_max yrs allowed, received $interval->y");
}
return array('status' => true);
} else {
return array('status' => false, 'error' => 'Rule Conflict: Both DOB and Relationship required for age check');
}
} else {
return array('status' => true);
} // in else condition no need to check rule, just return true
}
}
if (!function_exists('data_group_by_family')) {
function data_group_by_family($emp_data, $data_source = 'excel', $action = '', $current_column_action = null)
{
$result = [];
// Kint::dump($emp_data);
foreach ($emp_data as $rkey => $row) {
if ($data_source == 'excel') {
if (!check_row_is_empty_or_null($row)) {
if(empty($action)){
$row['data_from'] = "excel";
}
// for this condition to avoid 5,00,000 to 500000
if($current_column_action == 'SI'){
$row[3] = removeNumberFormatting($row[3]);
}else if(in_array($current_column_action, ['I','DA', 'MI', 'A'])){
$row[6] = removeNumberFormatting($row[6]);
}
if ($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception
{
$row = transform_enrollment_row_to_inception_row($row);
}
if (isset($row[5]) && strtolower($row[5]) == 'self' && isset($result[$row[1]])) {
array_unshift($result[$row[1]], $row);
} else {
$result[$row[1]][] = $row;
}
}
} else if ($data_source = 'db') {
if (strtolower($row['relationship']) == 'self' && isset($result[$row['emp_code']])) {
array_unshift($result[$row['emp_code']], $row);
} else {
$result[$row['emp_code']][] = $row;
}
}
}
return $result;
}
}
if (!function_exists('name_dup_check_within_family')) {
function name_dup_check_within_family($family_data)
{
$result = [];
$temp = [];
foreach ($family_data as $rkey => $row) {
if (in_array($row[2], $temp)) {
// Kint::dump($row);
$emp_code = $row[1];
$tempFam = null;
foreach ($family_data as $family) {
if ($family[1] == $emp_code && !isset($family['temp'])) {
$tempFam = $family;
break; // Stop at the first match
}
}
// Kint::dump($tempFam);
// die();
array_push($result, $tempFam[0]);
} else {
array_push($temp, $row[2]);
}
}
// dd($result);
return $result;
}
}
if (!function_exists('check_self_available_in_family')) {
function check_self_available_in_family($family_data)
{
$is_self_found = false;
$row_id_from_excel = array_filter($family_data, function ($item) {
return !isset($item['temp']);
});
// Kint::dump($row_id_from_excel);
$row_id_from_excel = current($row_id_from_excel); // get excel sno/rowid of employee amoung familiy array where this array has both data from excel and db
$row_id_from_excel = $row_id_from_excel[0];
foreach ($family_data as $rkey => $row) {
if ($row[5] != null && strtolower($row[5]) == 'self') //$row[5] = relationship $row[4] = Gender
{
$is_self_found = true;
break;
}
}
return ['is_self_found' => $is_self_found, 'emp_code' => $family_data[0][1], 'row_id' => $row_id_from_excel];
}
}
if (!function_exists('name_and_empid_check_in_db')) {
function name_and_empid_check_in_db($family_data, $actionArr)
{
$employeeModel = new EmployeeModel();
$result = ['del' => [], 'i' => []];
$client_id = $actionArr['client_id'];
$policy_id = $actionArr['policy_id'];
$client_branch_id = $actionArr['client_branch_id'];
$current_action = $actionArr['action'];
foreach ($family_data as $rkey => $row) {
if ($current_action != 'dependent_addition' || (isset($row['temp']) && $row['temp']['source'] != 'db')) {
$res = $employeeModel
->join('client_policy cp', "employees.client_id = cp.client_id")
->join('employee_polices ep', "cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
->where("cp.id", $policy_id)
->where("employees.client_id", $client_id)
->where("employees.client_branch_id", $client_branch_id)
->where("employees.is_active", 1)
->where("employees.emp_status", 'active')
->where("ep.is_active", 1)
->where("ep.status", 'active')
// ->where("ep.client_id",$client_id)
->where('TRIM(name)', trim($row[2]))->where('TRIM(emp_code)', trim($row[1]))
->findAll();
// kint::dump($employeeModel->getLastQuery()->getQuery());
if (($current_action == 'deletion' || $current_action == 'correction' || $current_action == 'si_enhancement') && !count($res)) {
array_push($result['del'], $row[0]);
}
if (($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition' || $current_action == 'enrollment') && count($res)) {
$emp_code = $row[1];
$tempFam = null;
foreach ($family_data as $family) {
if ($family[1] == $emp_code && !isset($family['temp'])) {
$tempFam = $family;
break; // Stop at the first match
}
}
array_push($result['i'], $tempFam[0]);
}
}
}
return $result;
}
}
if (!function_exists('check_emp_code_duplication')) {
function check_emp_code_duplication($family_data, $actionArr)
{
$employeeModel = new EmployeeModel();
$row_ids = [];
$status = false;
$client_id = $actionArr['client_id'];
$policy_id = $actionArr['policy_id'];
$client_branch_id = $actionArr['client_branch_id'];
$current_action = $actionArr['action'];
foreach ($family_data as $rkey => $row) {
if ($current_action != 'dependent_addition' || (isset($row['temp']) && $row['temp']['source'] != 'db')) {
$res = $employeeModel
->join('client_policy cp', "employees.client_id = cp.client_id")
->join('employee_polices ep', "cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
->where("cp.id", $policy_id)
->where("employees.client_id", $client_id)
->where("employees.client_branch_id", $client_branch_id)
->where("employees.is_active", 1)
->where("employees.emp_status", 'active')
->where("ep.is_active", 1)
->where("ep.status", 'active')
->where('TRIM(emp_code)', trim($row[1]))
->findAll();
if(count($res) > 0){
$row_ids[] = $row[0];
}
}
}
if(!empty($row_ids)){
$status = true;
}
return ['status' => $status, 'row_ids' => $row_ids];
}
}
if (!function_exists('check_dependent_conflict')) {
function check_dependent_conflict($family_data, $policy_terms, $actionArr, $is_lgbtq)
{
// dd($family_data,$policy_terms,$actionArr,$is_lgbtq);
$result = ['status' => true];
$self_gender = null;
$spouse_gender = null;
$allowed_spouse_count = 0;
$received_spouse_count = 0;
$allowed_child_count = 0;
$received_child_count = 0;
$allowed_parents_count = 0;
$received_parents_count = 0;
$allowed_parent_in_laws_count = 0;
$received_parent_in_laws_count = 0;
$overall_famility_relationships = [];
$self_emp_row_id = null;
$temp_counts = [2, 3, 4, 5, 6, 7, 8, 9, 10]; //temp variable for check relation repetaed count
$slug = \Config\Services::slug();
// dd($policy_terms);
if (isset($policy_terms['family_floater']) && !empty($policy_terms['family_floaters'])) {
// $temp_string = implode(" ",$policy_terms['family_floaters']);
$temp = $policy_terms['family_floaters'];
$temp = is_array($temp) ? $temp : (is_object($temp) ? (array)$temp : []);
$allowed_child_count = $temp['childrens'];
$allowed_spouse_count = $temp['spouse'];
$allowed_adults = $temp['either-parents-pil'];
$allowed_parents_count = $temp['either-parents-pil'] == 0 ? $temp['parents'] : 0;
$allowed_parent_in_laws_count = $temp['either-parents-pil'] == 0 ? $temp['parents-in-law'] : 0;
// dd($allowed_adults == 0);
$firstNonTemp = null;
foreach ($family_data as $family) {
if (!isset($family['temp'])) {
$firstNonTemp = $family;
break;
}
}
// Kint::dump($firstNonTemp);
foreach ($family_data as $key => $row) {
// dd($family_data[0][0]);
$relationship = $slug->slugify($row[5]);
if ($actionArr != 'deletion' && $relationship != 'son' && $relationship != 'daughter') {
array_push($overall_famility_relationships, $relationship);
}
if ($relationship == 'self') {
$self_gender = $row[4];
$self_emp_row_id = isset($row['temp']) ? null : $row[0];
}
if ($relationship == 'spouse') {
$spouse_gender = $row[4];
$received_spouse_count = $received_spouse_count + 1;
}
if ($relationship == 'son' || $relationship == 'daughter') {
$received_child_count = $received_child_count + 1;
}
if ($relationship == 'father' || $relationship == 'mother') {
$received_parents_count = $received_parents_count + 1;
}
if ($relationship == 'father-in-law' || $relationship == 'mother-in-law') {
$received_parent_in_laws_count = $received_parent_in_laws_count + 1;
}
}
// print_r($overall_famility_relationships);
// echo '<br/>';
if ($actionArr != 'deletion') {
$repeated_relationships_count = array_count_values($overall_famility_relationships);
// print_r($repeated_relationships_count);
// echo '<br/>';
$repeated_count = array_intersect($repeated_relationships_count, $temp_counts);
if (is_array($repeated_count) && count($repeated_count)) {
// Kint::dump($firstNonTemp);die();
$result['status'] = false;
$result['error_data'][] = ['code' => 13, 'col_name' => 'relationship', 'msg' => 'Rule conflict: Twofold relationship found within family', 'row_id' => $firstNonTemp[0]];
}
}
// print_r($repeated_count);
// echo "===============";
// echo "<br/>";
// print_r(array_values(array_count_values($overall_famility_relationships)));
// print_r(in_array(2,array_values(array_count_values($overall_famility_relationships))));
//check if this policy is allowed LGBTQ
if ($is_lgbtq == 0) {
if ($self_gender && $spouse_gender && $self_gender == $spouse_gender) {
$result['status'] = false;
$result['error_data'][] = ['code' => 4, 'col_name' => 'gender', 'msg' => 'Rule conflict: Self and Spouse cannot be same gender', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])];
}
}
if (($allowed_spouse_count < $received_spouse_count) || ($allowed_child_count < $received_child_count)) {
$result['status'] = false;
$result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
// || ($allowed_parents_count < $received_parents_count) || ($allowed_parent_in_laws_count < $received_parent_in_laws_count)
if ($allowed_adults == 1 && $received_parents_count && $received_parent_in_laws_count) {
$result['status'] = false;
$result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: Parents and Parents in law both not allowed', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])];
if ((2 < $received_parents_count) || (2 < $received_parent_in_laws_count)) {
$result['status'] = false;
$result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
}
//check for any cross parents but not more than two
if ($allowed_adults == 2 && (2 < ($received_parents_count + $received_parent_in_laws_count))) {
// dd($allowed_adults);
$result['status'] = false;
$result['error_data'][] = ['code' => 12, 'col_name' => 'sno', 'msg' => 'Rule conflict:As per policy, count of dependents has exceeded configured count', 'row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $firstNonTemp[0])]; //dependent count mismatch
}
} else {
$result['status'] = true;
}
return $result;
}
}
if (!function_exists('generate_relationship_code')) {
function generate_relationship_code($arr)
{
$gender = [
'M' => 1,
'Male' => 1,
'male' => 1,
'F' => 2,
'Female' => 2,
'female' => 2,
];
$relationship = ['self' => 1, 'spouse' => 2, 'son' => 3, 'daughter' => 4, 'father' => 5, 'mother' => 6, 'father-in-law' => 7, 'mother-in-law' => 8];
$slug = \Config\Services::slug();
$relationship_code = $slug->slugify($arr['relationship']);
$emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03');
$relationship_code = $gender[trim($arr['gender'])] ?? "" . $relationship[trim($relationship_code)] ?? "";
return ['relationship_code' => $relationship_code, 'emp_type_code' => $emp_type_code];
}
}
if (!function_exists('calculate_premium')) {
// function calculate_premimum($family_data,$policy_terms,$slab_details,$fileArr,$default_si = null)
function calculate_premium(array $family_data, array $policy_terms, array $slab_details, array $fileArr, string $default_si = null, array $existing_units = [])
{
// dd($family_data);
$slug = \Config\Services::slug();
$result = [];
$primary_grid_type = $slab_details['grid_master']['ui_type'];
//gather detailes for additional rack info
$additional_grid_type = isset($slab_details['additional_slab_info']['grid_master']['ui_type']) ? $slab_details['additional_slab_info']['grid_master']['ui_type'] : null;
// dd(isset($slab_details['additional_slab_info']['grid_master']['ui_type']));
$policy_terms_json = ($policy_terms['policy_terms']);
$policy_terms_json = (array) json_decode($policy_terms_json);
// dd($policy_terms);
$primary_rack_rate_applicable_familiy_members = ['self'];
if (isset($policy_terms_json['family_floaters'])) {
$primary_rack_rate_applicable_familiy_members = generate_family_relationship_array((array)$policy_terms_json['family_floaters']);
}
$additional_grid_type_applicable_familiy_members = [];
if ($additional_grid_type != null) {
$additional_grid_type_applicable_familiy_members = (array)json_decode($slab_details['additional_slab_info']['slab_rates'][0]['additional_relationship']);
$additional_grid_type_applicable_familiy_members = generate_family_relationship_array($additional_grid_type_applicable_familiy_members);
}
// Kint::dump($primary_rack_rate_applicable_familiy_members);
// Kint::dump($additional_grid_type_applicable_familiy_members);
//remove common family members in primary array
$primary_rack_rate_applicable_familiy_members = array_diff($primary_rack_rate_applicable_familiy_members, $additional_grid_type_applicable_familiy_members);
// dd($primary_rack_rate_applicable_familiy_members);
//this variable for store emp id and their band for emp band level premium calculation for all famility members (especially for grid type 9) also store max age and max count of a familiy for grid type 10,11
$emp_details_with_empband_max_age_max_count = [];
//find max age and max count of family members for both primary and additional grid type
$max_age_and_count = (array_reduce($family_data, function ($max_age, $family_member) use ($primary_rack_rate_applicable_familiy_members, $slug) {
if (in_array($slug->slugify($family_member[5]), $primary_rack_rate_applicable_familiy_members)) {
$max_age['primary_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
$max_age['primary_rack_rate_max_count'] = $max_age['primary_rack_rate_max_count'] + 1;
} else {
$max_age['additional_rack_rate_max_age'][] = calculate_days_bw_dates(from_date: $family_member[3])->y;
$max_age['additional_rack_rate_max_count'] = $max_age['additional_rack_rate_max_count'] + 1;
}
return $max_age;
}, ['primary_rack_rate_max_age' => [], 'additional_rack_rate_max_age' => [], 'primary_rack_rate_max_count' => 0, 'additional_rack_rate_max_count' => 0]));
$get_max_age_or_count = function ($relationship, $flag) use ($slug, $primary_rack_rate_applicable_familiy_members, $max_age_and_count) {
if (in_array($slug->slugify($relationship), $primary_rack_rate_applicable_familiy_members)) {
return $flag == 'age' ? max($max_age_and_count['primary_rack_rate_max_age']) : $max_age_and_count['primary_rack_rate_max_count'];
}
return $flag == 'age' ? max($max_age_and_count['additional_rack_rate_max_age']) : $max_age_and_count['additional_rack_rate_max_count'];
};
$get_current_member_grid_type = function ($relationship) use ($slug, $primary_rack_rate_applicable_familiy_members, $primary_grid_type, $additional_grid_type) {
if (in_array($slug->slugify($relationship), $primary_rack_rate_applicable_familiy_members)) {
return ['type' => 'primary', 'grid_id' => $primary_grid_type];
}
return ['type' => 'additional', 'grid_id' => $additional_grid_type];
};
// Kint::dump($max_age_and_count);dd();
foreach ($family_data as $fkey => $member) {
//get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
$current_grid_info = $get_current_member_grid_type($member[5]);
$fileArr['grid_info'] = $current_grid_info;
//transform as db row column
$transformed_familiy_member_data = transform_excel_data_to_db($member, $fileArr);
// dd($transformed_familiy_member_data);
//store emp id and emp band and attach it to their familiy members where band is always empty
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] : NULL;
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] : NULL;
//get emp band and si from self and make it available for whole family
if (strtolower($transformed_familiy_member_data['relationship']) == 'self') {
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'] = $transformed_familiy_member_data['band'];
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] = $transformed_familiy_member_data['policy_details']['basic_cover_si'];
}
//end of store emp id and emp band and attach it to their familiy members where band is always empty
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxcount'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'], 'count');
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxage'] = $get_max_age_or_count($transformed_familiy_member_data['relationship'], 'age');
//set additional_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array
$transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = false;
if (!isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self']) && $current_grid_info['type'] == 'additional') {
if ($transformed_familiy_member_data['temp']['action'] != 'DA') {
$transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = true;
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self'] = true;
} else // if dependent addition then set employee from db is an acting self
{
if ($transformed_familiy_member_data['temp']['source'] == 'db' && $transformed_familiy_member_data['temp']['rata_premimum']) {
// echo 'SETTING';
$transformed_familiy_member_data['temp']['additional_rack_rate_acting_self'] = true;
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['additional_rack_rate_acting_self'] = true;
}
}
}
//set primary_rack_rate_acting_self in emp_details_with_empband_max_age_max_count array for policies where self not available and premium type is 1 (i.e.) GMC parents as dep addon policy
$transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = false;
if (!isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self']) && $current_grid_info['type'] == 'primary') {
if (strtolower($transformed_familiy_member_data['relationship']) == 'self') {
$transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self'] = true;
} else {
$transformed_familiy_member_data['temp']['primary_rack_rate_acting_self'] = true;
$emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['primary_rack_rate_acting_self'] = true;
}
}
//generate relationship code
if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
$temp_res = generate_relationship_code($transformed_familiy_member_data);
$transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
$transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
}
//calculate primimum based on grid type
if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
//before call premium_calculation_manager attach band,max age and max count into the array temporarly for grid 9,10 and 11
$transformed_familiy_member_data['temp']['band'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['band'];
$transformed_familiy_member_data['temp']['maxage'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxage'];
$transformed_familiy_member_data['temp']['maxcount'] = $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['maxcount'];
//set self si to all familiy members, except they've come from DB
// if(isset($emp_details_with_empband_max_age_max_count[ $transformed_familiy_member_data['emp_code'] ]['si']))
// {
if ($transformed_familiy_member_data['temp']['source'] != 'db') {
$transformed_familiy_member_data['policy_details']['basic_cover_si'] = isset($emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si']) ? $emp_details_with_empband_max_age_max_count[$transformed_familiy_member_data['emp_code']]['si'] : $transformed_familiy_member_data['policy_details']['basic_cover_si'];
}
// }
// this array hold conditions to allow calculate premium amt
$conditions = [
'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
'isPrimaryGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'primary',
'isAdditionalGridType' => $transformed_familiy_member_data['temp']['grid_type'] == 'additional',
'isPrimaryGridPremiumTypeSingle' => $slab_details['slab_rates'][0]['premium_type'] == 1,
'isAdditionalPremiumTypeSingle' => isset($slab_details['additional_slab_info']['slab_rates'][0]['premium_type']) ? ($slab_details['additional_slab_info']['slab_rates'][0]['premium_type'] == 1) : 0,
'isCurrentRelationshipSelf' => strtolower($transformed_familiy_member_data['relationship']) == 'self',
'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
];
// Kint::dump($transformed_familiy_member_data['policy_details']);
// echo ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0);
// echo ($conditions['isBasicCoverCalculatedToCurrentEmployee']);
// echo "<br>";
// same logic for both primay and additional grid type
$primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridType'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'];
$additionalGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isAdditionalGridType'] && $conditions['isAdditionalPremiumTypeSingle'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
// Final combined condition
if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition || $additionalGridTypeCondition) {
$transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data, $policy_terms, $slab_details, $default_si);
$result[] = $transformed_familiy_member_data;
}
}
}
// Kint::dump($emp_details_with_empband_max_age_max_count);
return $result;
}
}
if (!function_exists('calculate_premium_new')) {
function calculate_premium_new(array $family_data, array $policy_terms, array $slab_details, array $fileArr, array $existing_units, string $default_si = null,)
{
//grouping slab details by rack rate name
$temp_slab_rates = group_slab_rates_basedon_name($slab_details);
// dd($temp_slab_rates);
/* 1. construct available/incoming family members composition & count */
$incoming_familiy_composition = get_familiy_composition($family_data);
// dd($incoming_familiy_composition);
//2 .get applicable familiy members composition & count from slab details & constrcut an array
//3 in for another loop compare slab level applicable familiy composition with available family composition
$result = [];
foreach ($temp_slab_rates as $key => $slab) {
// dd($slab);
$res = compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition);
// kint::dump($key);
// kint::dump($res);
if ($res['is_applicable']) {
$temp_slab_rates[$key]['is_applicable'] = true;
$temp_slab_rates[$key]['members'] = $res['applicable_members'];
//get applicable members for current rack rate from over all familiy members and calculate max age and max count,self/acting self and grid type and set it in individual familiy member level
$applicable_members_from_familiy = get_applicable_familiy_members($family_data, $res['applicable_members']);
// dd( $applicable_members_from_familiy);
$is_self_acting_self_set = false;
foreach ($applicable_members_from_familiy['index'] as $val) {
$acting_self = false;
if (!$is_self_acting_self_set) {
if (strtolower($family_data[$val][5]) == 'self' || !$is_self_acting_self_set) $acting_self = true;
$is_self_acting_self_set = true;
}
//$family_data[$val]['temp'] = ['max_age' => max($applicable_members_from_familiy['max_age']),'max_count' => $applicable_members_from_familiy['max_count'],'grid_name' => $key,'grid_master' => $slab['grid_master'],'acting_self' => $acting_self,'premium_type' => $slab['slab_rates'][0]['premium_type']];
$family_data[$val]['temp'] = array_merge(
$family_data[$val]['temp'] ?? [], // existing 'temp' data or an empty array if it doesn't exist
[
'max_age' => max($applicable_members_from_familiy['max_age']),
'max_count' => $applicable_members_from_familiy['max_count'],
'grid_name' => $key,
'grid_master' => $slab['grid_master'],
'acting_self' => $acting_self,
'premium_type' => $slab['slab_rates'][0]['premium_type']
]
);
}
} else {
$temp_slab_rates[$key]['is_applicable'] = false;
}
}
// dd();
//4. if macthed then the current rack rate is applicable and find common variables link max age,max count,grade, basic pay,SI, self/acting self for current rack rate
foreach ($family_data as $fkey => $member) {
// dd($member);
//get grid type either primary or additional based on current member relationship available in primary_rack_rate_applicable_familiy_members or not. if yes then primaty grid type else additional grid type
$fileArr['grid_info'] = ['type' => isset($member['temp']['grid_name']) ? $member['temp']['grid_name'] : NULL, 'grid_id' => isset($member['temp']['grid_master']['ui_type']) ? $member['temp']['grid_master']['ui_type'] : NULL];
//set self (first index of familiy) SI and grade to rest of the familiy
$member[6] = $family_data[0][6];
$member[10] = $family_data[0][10];
$member[18] = $family_data[0][18];
//set default unit if unit is not available in self/members level
if (empty($member[18])) {
$member[18] = $existing_units[0];
}
//transform as db row column
$transformed_familiy_member_data = transform_excel_data_to_db($member, $fileArr);
//generate relationship code
if ($transformed_familiy_member_data['temp']['action'] != 'D' && $transformed_familiy_member_data['temp']['action'] != 'C' && $transformed_familiy_member_data['temp']['action'] != 'SI') {
$temp_res = generate_relationship_code($transformed_familiy_member_data);
$transformed_familiy_member_data['relationship_code'] = $temp_res['relationship_code'];
$transformed_familiy_member_data['emp_type'] = $temp_res['emp_type_code'];
}
// // this array hold conditions to allow calculate premium amt
$conditions = [
'isEmployeeSourceEnrollment' => $fileArr['id'] == null,
'isEmployeeSourceExcelFile' => $transformed_familiy_member_data['temp']['source'] == 'excel',
'isCurrentActionDependentAddition' => $fileArr['action'] == 'dependent_addition',
'isPrimaryGridPremiumTypeSingle' => isset($transformed_familiy_member_data['temp']['premium_type']) ? $transformed_familiy_member_data['temp']['premium_type'] == 1 : 0,
'isCurrentRelationshipSelf' => (strtolower($transformed_familiy_member_data['relationship']) == 'self' || (isset($transformed_familiy_member_data['temp']['acting_self']) && $transformed_familiy_member_data['temp']['acting_self'] === true)),
'isBasicCoverCalculatedToCurrentEmployee' => ($transformed_familiy_member_data['policy_details']['basic_cover_si'] != null && $transformed_familiy_member_data['policy_details']['basic_cover_si'] != 0)
];
$primaryGridTypeCondition = $conditions['isCurrentActionDependentAddition'] && $conditions['isPrimaryGridPremiumTypeSingle'] && $conditions['isCurrentRelationshipSelf'] && $conditions['isBasicCoverCalculatedToCurrentEmployee'];
// // Final combined condition
if ($conditions['isEmployeeSourceEnrollment'] || $conditions['isEmployeeSourceExcelFile'] || $primaryGridTypeCondition) {
// dd($transformed_familiy_member_data);
$transformed_familiy_member_data = premium_calculation_manager($transformed_familiy_member_data, $policy_terms, $temp_slab_rates, $default_si);
// dd($transformed_familiy_member_data);
$result[] = $transformed_familiy_member_data;
}
// $result[] = $transformed_familiy_member_data;
}
if($fileArr['action'] == 'dependent_addition') {
$result = validatet_family_floter_rata_premium($result);
}
// dd($result);
return ($result);
//
}
}
if (!function_exists('transform_excel_data_to_db')) {
function transform_excel_data_to_db($memArr, $actionArr)
{
$current_column_action = null;
if ($actionArr['action'] == 'inception') {
$current_column_action = 'I';
} else if ($actionArr['action'] == 'addition') {
$current_column_action = 'A';
} else if ($actionArr['action'] == 'dependent_addition') {
$current_column_action = 'DA';
} else if ($actionArr['action'] == 'deletion') {
$current_column_action = 'D';
} else if ($actionArr['action'] == 'correction') {
$current_column_action = 'C';
} else if ($actionArr['action'] == 'si_enhancement') {
$current_column_action = 'SI';
} else if ($actionArr['action'] == 'missed_inception') {
$current_column_action = 'MI';
}
if ($actionArr['action'] == 'inception' || $actionArr['action'] == 'missed_inception' || $actionArr['action'] == 'addition' || $actionArr['action'] == 'dependent_addition') {
$policy['basic_cover_si'] = $memArr[6];
$policy['pre_existing_alignments'] = $memArr[14];
// $policy['date_of_exit'] = isset($memArr[16]) ? change_date_format($memArr[16],'d-M-Y','Y-m-d') : NULL;
// $policy['reason_for_exit'] = $memArr[17];
$policy['client_policy_id'] = $actionArr['policy_id'];
$policy['date_coverage'] = isset($memArr[7]) && $memArr[7] != '' ? convert_string_to_date($memArr[7], 'Y-m-d') : NULL;
$policy['policy_end_date'] = null;
$policy['days'] = null;
$policy['premium'] = null;
$policy['rata_premimum'] = null;
$policy['gst'] = null;
$result['emp_code'] = $memArr[1];
$result['name'] = $memArr[2];
$result['dob'] = isset($memArr[3]) ? convert_string_to_date($memArr[3], 'Y-m-d') : NULL;
$result['gender'] = $memArr[4];
$result['relationship'] = $memArr[5];
$result['relationship_code'] = $memArr[5];
$result['doj'] = isset($memArr[8]) ? convert_string_to_date($memArr[8], 'Y-m-d') : NULL;
$result['basic_pay'] = $memArr[9];
$result['band'] = $memArr[10];
$result['designation'] = $memArr[11];
$result['mobile'] = $memArr[12];
$result['email_corporate'] = $memArr[13];
$result['file_id'] = isset($memArr['temp']['source']) && $memArr['temp']['source'] == 'db' && isset($memArr['temp']['file_id']) ? $memArr['temp']['file_id'] : $actionArr['id'];
$result['client_id'] = $actionArr['client_id'];
$result['change_event'] = $memArr[15];
$result['unit'] = $memArr[18];
$result['temp'] = [];
if (isset($memArr['temp'])) $result['temp'] = array_merge($result['temp'], $memArr['temp']);
$result['temp']['grid_type'] = $actionArr['grid_info']['type'];
$result['temp']['band'] = $result['band'];
$result['temp']['grid_id'] = $actionArr['grid_info']['grid_id'];
$result['temp']['action'] = isset($memArr['current_action']) ? $memArr['current_action'] : $current_column_action;
$result['temp']['source'] = isset($memArr['temp']['source']) ? $memArr['temp']['source'] : 'excel';
$result['temp']['emp_id'] = isset($memArr['temp']['emp_id']) ? $memArr['temp']['emp_id'] : null;
$result['temp']['emp_policy_id'] = isset($memArr['temp']['emp_policy_id']) ? $memArr['temp']['emp_policy_id'] : null;
$result['temp']['policy_status'] = isset($memArr['temp']['policy_status']) ? $memArr['temp']['policy_status'] : null;
$result['temp']['emp_status'] = isset($memArr['temp']['emp_status']) ? $memArr['temp']['emp_status'] : null;
$result['temp']['rata_premimum'] = isset($memArr['temp']['rata_premimum']) ? $memArr['temp']['rata_premimum'] : 0;
$result['policy_details'] = $policy;
if(isset($memArr['self_rata_premium'])){
$result['self_rata_premium'] = $memArr['self_rata_premium'] ?? 0;
}
if(isset($memArr['data_from'])){
$result['data_from'] = $memArr['data_from'] ?? 'excel';
}
return $result;
}
}
}
if (!function_exists('premium_calculation_manager_old')) {
function premium_calculation_manager_old($emp_data, $policy_terms, $slab_details, $default_si = null)
{
// dd($emp_data,$policy_terms,$slab_details,$default_si);
$myLogger = \Config\Services::mylogger();
// grid type
// 1 = premium => si
// Kint::dump($emp_data);
//check if the data comes from enrollment (DB) and status is draft then fetch original data of employee from
//audit history table then initiate calculation with it. so this data again get updated in emp table
//check emp records
if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
// $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']);
// if(is_array($original_emp_records))
// {
// // Kint::dump($original_emp_records);
// // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data);
// // Kint::dump($value);
// }
}
//check emp policy records
if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
// $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']);
// if(is_array($original_emp_policy_records))
// {
// // Kint::dump($original_emp_records);
// $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']);
// // Kint::dump($policy_data);
// }
} //end of fetching data from audit history table
//gird and calculation start
$slug = \Config\Services::slug();
$grid_type = $emp_data['temp']['grid_id'];
$slab_index = isset($emp_data['temp']['grid_name']) ? $emp_data['temp']['grid_name'] : false;
// echo $emp_data['name'];
// kint::dump($slab_index);
if ($slab_index === false) {
// echo 'not set';
return false;
}
$temp_slab_rates = $slab_details[$slab_index]['slab_rates'];
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel();
$insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
$emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) && $emp_data['policy_details']['date_coverage'] != '' && $emp_data['policy_details']['date_coverage'] != null ?
(new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d') : null;
}
}
// dd($emp_data);
$is_match_found = false;
$gst = isset($policy_terms['gst']) && $policy_terms['gst'] != 0 ? $policy_terms['gst'] : 18;
switch ($grid_type) {
case "1":
//GPA - Sum Insured (SI) * Multiplier
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_received_band = $emp_data['temp']['band'];
foreach ($temp_slab_rates as $skey => $slab_value) {
if (($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
//auto calculate of SI and premium for basic pay type
if (!$is_match_found) {
if ($temp_slab_rates[0]['si_or_bp'] == 2) {
$temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier'];
$temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000;
$emp_data['policy_details']['basic_cover_si'] = $temp_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $temp_premium;
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
$log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $temp_si . ' - ' . $temp_premium;
$myLogger->logme('error', $log_message);
}
}
break;
case "2":
//GPA - Flat Rate for all SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "3":
//GMC - SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "4":
//GMC - Employees Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
// dd($employee_received_si);
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// dd($slab_value);
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "5":
//GMC - Employees Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
// kint::dump($age);
foreach ($temp_slab_rates as $skey => $slab_value) {
// dd($slab_value);
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "6":
//GMC - Employees + Dependent Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// echo $emp_data['name']; die;
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "7":
//GMC - Employees + Dependent Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "8":
//GMC - SI as per Grade or Band
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
// $emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "9":
//GMC - Flat Rate for all
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "10":
//GMC - Maximum age of Dependents
$max_age = $emp_data['temp']['max_age'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
// echo $emp_data['name'].'-'.$employee_received_si.'<br>';
// echo $emp_data['temp']['grid_type'].'<br>';
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
// echo $slab_value['si'].'-'.$slab_value['age_from'].'-'.$slab_value['age_to'].'-'.$max_age.'<br>';
if (
$slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] &&
($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age) &&
(($slab_value['premium_type'] == 1 &&
(strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))
) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date'];
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "11":
//GMC - Maximum count per Family
$max_count = $emp_data['temp']['max_count'];
$employee_received_band = $emp_data['band'];
// echo $employee_received_band;
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && (($slab_value['premium_type'] == 1 &&
(strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3))) {
//calculate premium based on count
// echo $emp_data['name'];
$familiy_si_covered = $employee_received_si * $max_count;
$familiy_si_covered = ($familiy_si_covered >= $slab_value['max_si'] ? $slab_value['max_si'] : $familiy_si_covered);
$emp_data['policy_details']['basic_cover_si'] = $familiy_si_covered;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates, si_amount: $familiy_si_covered, band: $employee_received_band, unit: $emp_data['unit']);
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
}
break;
case "12":
//GMC - Employee + relationship
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])))) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
}
break;
case "13":
//GMC - Employee + relationship + age
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && ((($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null || $slab_value['premium_type'] == 3) && $slab_value['relationship'] == $employee_relationship) || ($slab_value['premium_type'] == 1 && (strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['acting_self'])))) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days);
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
default:
$myLogger->logme('error', ($emp_data['emp_code'] . '-' . $emp_data['name'] . ' - grid type not found'));
}
//this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self)
if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3 && $policy_terms['is_addon'] != 3) {
//set dependent si to 0
$emp_data['policy_details']['basic_cover_si'] = 0;
}
if (!$is_match_found) {
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
$log_message = '[ client_policy_id : ' . $emp_data['policy_details']['client_policy_id'] . ' - ' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $emp_data['policy_details']['basic_cover_si'] . ', Age : ' . $age . ' ]';
if ($temp_slab_rates[0]['premium_type'] == 1) {
$log_message .= ' - skipping, calculating only self..!';
//reset emp si and others policy level data if premium only for self
// $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0;
$emp_data['policy_details']['rata_premimum'] = 0;
$emp_data['policy_details']['gst'] = 0;
$emp_data['policy_details']['days'] = 0;
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
} else {
$log_message .= '- skipping, slab rate not found';
}
$myLogger->logme('error', $log_message);
// echo $log_message;
}
return $emp_data;
}
}
if (!function_exists('premium_calculation_manager')) {
function premium_calculation_manager($emp_data, $policy_terms, $slab_details, $default_si = null)
{
// dd($emp_data,$policy_terms,$slab_details,$default_si);
$myLogger = \Config\Services::mylogger();
// grid type
// 1 = premium => si
// Kint::dump($emp_data);
//check if the data comes from enrollment (DB) and status is draft then fetch original data of employee from
//audit history table then initiate calculation with it. so this data again get updated in emp table
//check emp records
if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
// $original_emp_records = get_emp_records_from_audit_history($emp_data['temp']['emp_id']);
// if(is_array($original_emp_records))
// {
// // Kint::dump($original_emp_records);
// // $emp_data = replace_original_data(original_data:$original_emp_records,current_data:$emp_data);
// // Kint::dump($value);
// }
}
//check emp policy records
if ($emp_data['file_id'] == null && $emp_data['temp']['emp_status'] == 'draft' && $emp_data['temp']['policy_status'] == 'draft') {
// $original_emp_policy_records = get_emp_policy_records_from_audit_history($emp_data['temp']['emp_policy_id']);
// if(is_array($original_emp_policy_records))
// {
// // Kint::dump($original_emp_records);
// $emp_data['policy_details'] = replace_original_data(original_data:$original_emp_policy_records,current_data:$emp_data['policy_details']);
// // Kint::dump($policy_data);
// }
} //end of fetching data from audit history table
//gird and calculation start
$slug = \Config\Services::slug();
$grid_type = $emp_data['temp']['grid_id'];
$slab_index = isset($emp_data['temp']['grid_name']) ? $emp_data['temp']['grid_name'] : false;
// echo $emp_data['name'];
// kint::dump($slab_index);
if ($slab_index === false) {
// echo 'not set';
return false;
}
$temp_slab_rates = $slab_details[$slab_index]['slab_rates'];
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel();
$insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
$emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) && $emp_data['policy_details']['date_coverage'] != '' && $emp_data['policy_details']['date_coverage'] != null ?
(new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d') : null;
}
}
// dd($emp_data);
$is_match_found = false;
$gst = isset($policy_terms['gst']) && $policy_terms['gst'] != 0 ? $policy_terms['gst'] : 18;
switch ($grid_type) {
case "1":
//GPA - Sum Insured (SI) * Multiplier
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_received_band = $emp_data['temp']['band'];
foreach ($temp_slab_rates as $skey => $slab_value) {
if (($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) || ($slab_value['grade'] != null && $slab_value['grade'] == $employee_received_band && $slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'])) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
//auto calculate of SI and premium for basic pay type
if (!$is_match_found) {
if ($temp_slab_rates[0]['si_or_bp'] == 2) {
$temp_si = $emp_data['basic_pay'] * $temp_slab_rates[0]['basic_multiplier'];
$temp_premium = ($temp_si * $temp_slab_rates[0]['multiplier']) / 1000;
$emp_data['policy_details']['basic_cover_si'] = $temp_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $temp_premium;
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
$log_message = 'Pre defined SI not found. auto calc SI & premium for -' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $temp_si . ' - ' . $temp_premium;
$myLogger->logme('error', $log_message);
}
}
break;
case "2":
//GPA - Flat Rate for all SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "3":
//GMC - SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "4":
//GMC - Employees Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
// dd($employee_received_si);
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) {
// dd($slab_value);
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "5":
//GMC - Employees Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
// kint::dump($age);
foreach ($temp_slab_rates as $skey => $slab_value) {
// dd($slab_value);
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "6":
//GMC - Employees + Dependent Age band
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) {
// echo $emp_data['name']; die;
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "7":
//GMC - Employees + Dependent Age + SI
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "8":
//GMC - SI as per Grade or Band
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit'] && $slab_value['si'] == $employee_received_si) {
// $emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "9":
//GMC - Flat Rate for all
$employee_received_band = $emp_data['temp']['band'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit']) {
$emp_data['policy_details']['basic_cover_si'] = $slab_value['si'];
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
$is_match_found = true;
break;
}
}
break;
case "10":
//GMC - Maximum age of Dependents
$max_age = $emp_data['temp']['max_age'];
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
// echo $emp_data['name'].'-'.$employee_received_si.'<br>';
// echo $emp_data['temp']['grid_type'].'<br>';
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
// echo $slab_value['si'].'-'.$slab_value['age_from'].'-'.$slab_value['age_to'].'-'.$max_age.'<br>';
if (
$slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $max_age && $slab_value['age_to'] >= $max_age)
) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date'];
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
case "11":
//GMC - Maximum count per Family
$max_count = $emp_data['temp']['max_count'];
$employee_received_band = $emp_data['band'];
// echo $employee_received_band;
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['grade'] == $employee_received_band && $slab_value['unit'] == $emp_data['unit']) {
//calculate premium based on count
// echo $emp_data['name'];
$familiy_si_covered = $employee_received_si * $max_count;
$familiy_si_covered = ($familiy_si_covered >= $slab_value['max_si'] ? $slab_value['max_si'] : $familiy_si_covered);
$emp_data['policy_details']['basic_cover_si'] = $familiy_si_covered;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = get_premium_for_si(slab_details: $temp_slab_rates, si_amount: $familiy_si_covered, band: $employee_received_band, unit: $emp_data['unit']);
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
}
break;
case "12":
//GMC - Employee + relationship
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && $slab_value['relationship'] == $employee_relationship) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], (calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days + 1));
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$is_match_found = true;
break;
}
}
break;
case "13":
//GMC - Employee + relationship + age
$employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si;
$employee_relationship = $slug->slugify($emp_data['relationship']);
$employee_relationship = ($employee_relationship == 'daughter' || $employee_relationship == 'son' ? $employee_relationship = 'child' : $employee_relationship);
$emp_data['policy_details']['basic_cover_si'] = null;
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
foreach ($temp_slab_rates as $skey => $slab_value) {
if ($slab_value['si'] == $employee_received_si && $slab_value['unit'] == $emp_data['unit'] && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && $slab_value['relationship'] == $employee_relationship) {
$emp_data['policy_details']['basic_cover_si'] = $employee_received_si;
$emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['days'] = (calculate_days_bw_dates($emp_data['policy_details']['date_coverage'], $policy_terms['policy_end_date'])->days + 1);
$emp_data['policy_details']['premium'] = $slab_value['premium'];
$emp_data['policy_details']['rata_premimum'] = calculate_pro_rata_premimum($emp_data['policy_details']['premium'], $emp_data['policy_details']['days'], calculate_days_bw_dates($policy_terms['policy_start_date'], $policy_terms['policy_end_date'])->days);
$emp_data['policy_details']['gst'] = ((float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', ''));
$emp_data['policy_details']['age_band'] = $slab_value['age_from'] . '-' . $slab_value['age_to'];
$is_match_found = true;
break;
}
}
break;
default:
$myLogger->logme('error', ($emp_data['emp_code'] . '-' . $emp_data['name'] . ' - grid type not found'));
}
//this if condition for premium calculated & premium type 3 (familiy floater but premium calculated every individual implemented later) then remove si amount only for dependents (not self)
if ($is_match_found && strtolower($emp_data['relationship']) != 'self' && $temp_slab_rates[0]['premium_type'] == 3 && $policy_terms['is_addon'] != 3) {
//set dependent si to 0
$emp_data['policy_details']['basic_cover_si'] = 0;
}
if (!$is_match_found) {
$temp_date = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']);
$age = calculate_days_bw_dates(from_date: $emp_data['dob'], to_date: $temp_date)->y;
$log_message = '[ client_policy_id : ' . $emp_data['policy_details']['client_policy_id'] . ' - ' . $emp_data['emp_code'] . ' - ' . $emp_data['name'] . ' - ' . $emp_data['policy_details']['basic_cover_si'] . ', Age : ' . $age . ' ]';
if ($temp_slab_rates[0]['premium_type'] == 1) {
$log_message .= ' - skipping, calculating only self..!';
//reset emp si and others policy level data if premium only for self
// $emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
$emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0;
$emp_data['policy_details']['rata_premimum'] = 0;
$emp_data['policy_details']['gst'] = 0;
$emp_data['policy_details']['days'] = 0;
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
} else {
$log_message .= '- skipping, slab rate not found';
}
$myLogger->logme('error', $log_message);
// echo $log_message;
}
// if the family floater case first self add first the process completed, after spouse or any dependent add the rata premium not added this change will handle this
if (strtolower($emp_data['relationship']) != 'self' && empty($emp_data['temp']['acting_self']) && $temp_slab_rates[0]['premium_type'] == 1 && $emp_data['temp']['action'] == 'DA') {
//set dependent si to 0
$emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0;
if(isset($emp_data['self_rata_premium']) && !empty($emp_data['self_rata_premium'])){
$self_rata_premium = (int)($emp_data['self_rata_premium'] ?? 0);
$dependent_rata_premium = (int)($emp_data['policy_details']['rata_premimum'] ?? 0);
$actual_rata_premium = abs($dependent_rata_premium - $self_rata_premium);
$emp_data['policy_details']['rata_premimum'] = $actual_rata_premium;
$emp_data['policy_details']['gst'] = (float) number_format(($emp_data['policy_details']['rata_premimum'] * ($gst / 100)), 2, '.', '');
}
}else if(strtolower($emp_data['relationship']) != 'self' && empty($emp_data['temp']['acting_self']) && $temp_slab_rates[0]['premium_type'] == 1 && ($emp_data['temp']['action'] == 'I' || $emp_data['temp']['action'] == 'A' || $emp_data['temp']['action'] == 'MI')){
$emp_data['policy_details']['basic_cover_si'] = 0;
$emp_data['policy_details']['premium'] = 0;
$emp_data['policy_details']['rata_premimum'] = 0;
$emp_data['policy_details']['gst'] = 0;
$emp_data['policy_details']['days'] = 0;
$emp_data['policy_details']['policy_end_date'] = $policy_terms['policy_end_date'];
}
return $emp_data;
}
}
if (!function_exists('calculate_pro_rata_premimum')) {
function calculate_pro_rata_premimum($premium, $employee_policy_coverage_days, $policy_coverage_days)
{
return (float) number_format(($premium / ($policy_coverage_days)) * $employee_policy_coverage_days, 2, '.', '');
}
}
if (!function_exists('no_of_days_in_current_fin_year')) {
function no_of_days_in_current_fin_year()
{
return true;
}
}
//transform db columns into excel rows with indexs
if (!function_exists('transform_db_data_to_excel')) {
function transform_db_data_to_excel($familiyArr, $actionArr = [])
{
// if($actionArr['action'] == 'dependent_addition')
// {
$return_data = [];
foreach ($familiyArr as $key => $value) {
// dd($value);
$row = [];
$row[0] = ($key + 1);
$row[6] = $value['basic_cover_si'];
$row[14] = $value['pre_existing_alignments'];
$row[16] = isset($value['date_of_exit']) ? change_date_format($value['date_of_exit'], 'Y-m-d', 'd-M-Y') : NULL;
$row[17] = $value['reason_for_exit'];
$row[18] = $value['unit'];
$row[7] = isset($value['date_coverage']) ? change_date_format($value['date_coverage'], 'Y-m-d', 'd-M-Y') : NULL;
$row[1] = $value['emp_code'];
$row[2] = $value['name'];
$row[3] = isset($value['dob']) ? change_date_format($value['dob'], 'Y-m-d', 'd-M-Y') : NULL;
$row[4] = $value['gender'];
$row[5] = $value['relationship'];
$row[8] = isset($value['doj']) ? change_date_format($value['doj'], 'Y-m-d', 'd-M-Y') : NULL;
$row[9] = $value['basic_pay'];
$row[10] = $value['band'];
$row[11] = $value['designation'];
$row[12] = $value['mobile'];
$row[13] = $value['email_corporate'];
// $actionArr['id'] = $value['file_id'];
// $actionArr['client_id'] = $value['client_id'];
$row[15] = $value['change_event'];
$row['current_action'] = 'DA';
$row['temp']['source'] = 'db';
$row['temp']['emp_id'] = $value['emp_id'];
$row['temp']['emp_policy_id'] = $value['emp_policy_id'];
$row['temp']['emp_status'] = $value['emp_status'];
$row['temp']['policy_status'] = $value['status'];
$row['temp']['rata_premimum'] = $value['rata_premimum'];
$row['temp']['premium'] = $value['premium'];
$row['temp']['file_id'] = $value['file_id'];
array_push($return_data, ($row));
}
return $return_data;
// }
}
}
//comparre excel cell names and return range of chars between them
if (!function_exists('compare_excel_cell_range')) {
function compare_excel_cell_range($highestColumnAllowed, $highestColumnReceivedInExcel)
{
$highestColumnAllowed = strtoupper($highestColumnAllowed);
$highestColumnReceivedInExcel = strtoupper($highestColumnReceivedInExcel);
if ($highestColumnAllowed < $highestColumnReceivedInExcel) {
$range = range($highestColumnAllowed, $highestColumnReceivedInExcel);
return $range;
}
return [];
}
}
if (!function_exists('get_emp_records_from_audit_history')) {
function get_emp_records_from_audit_history($employee_id)
{
$db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :employee_id: and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc";
$binds = ['employee_id'=>(int)$employee_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery();
$res = $res->getResultArray();
if (count($res)) {
$temp = [];
foreach ($res as $row) {
$temp[$row['field_name']] = $row['old_value'];
}
return $temp;
}
return false;
}
}
if (!function_exists('get_emp_policy_records_from_audit_history')) {
function get_emp_policy_records_from_audit_history($emp_policy_id)
{
$db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :emp_policy_id: and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc";
$binds = ['emp_policy_id'=>(int)$emp_policy_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery();
$res = $res->getResultArray();
if (count($res)) {
$temp = [];
foreach ($res as $row) {
$temp[$row['field_name']] = $row['old_value'];
}
return $temp;
}
return false;
}
}
if (!function_exists('replace_original_data')) {
function replace_original_data(array $original_data, array $current_data)
{
foreach ($original_data as $key => $data) {
if (array_key_exists($key, $current_data)) {
$current_data[$key] = $data;
}
}
return $current_data;
}
}
if (!function_exists('get_premium_for_si')) {
function get_premium_for_si(array $slab_details, string $si_amount, string $band, string $unit)
{
// dd($slab_details);
foreach ($slab_details as $skey => $slab_value) {
if ($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit) {
return $slab_value['premium'];
}
}
return 0;
}
}
if (!function_exists('remap_default_age_ratio_into_relationship')) {
function remap_default_age_ratio_into_relationship(array $general_relationships, array $default_age_ratio)
{
foreach ($default_age_ratio as $relationship => $age_ratio) {
switch ($relationship) {
case 'child':
if (isset($general_relationships['son'])) {
$general_relationships['son']['age_min'] = $age_ratio['min'];
$general_relationships['son']['age_max'] = $age_ratio['max'];
}
if (isset($general_relationships['daughter'])) {
$general_relationships['daughter']['age_min'] = $age_ratio['min'];
$general_relationships['daughter']['age_max'] = $age_ratio['max'];
}
break;
case 'elders':
if (isset($general_relationships['father'])) {
$general_relationships['father']['age_min'] = $age_ratio['min'];
$general_relationships['father']['age_max'] = $age_ratio['max'];
}
if (isset($general_relationships['mother'])) {
$general_relationships['mother']['age_min'] = $age_ratio['min'];
$general_relationships['mother']['age_max'] = $age_ratio['max'];
}
if (isset($general_relationships['father-in-law'])) {
$general_relationships['father-in-law']['age_min'] = $age_ratio['min'];
$general_relationships['father-in-law']['age_max'] = $age_ratio['max'];
}
if (isset($general_relationships['mother-in-law'])) {
$general_relationships['mother-in-law']['age_min'] = $age_ratio['min'];
$general_relationships['mother-in-law']['age_max'] = $age_ratio['max'];
}
break;
default:
if (isset($general_relationships[$relationship])) {
$general_relationships[$relationship]['age_min'] = $age_ratio['min'];
$general_relationships[$relationship]['age_max'] = $age_ratio['max'];
}
break;
}
}
return $general_relationships;
}
}
if (!function_exists('check_dup_mobileno_old')) {
function check_dup_mobileno_old(array $row, array $existing_mobilenos)
{
if(!empty($row['12'])){
foreach ($existing_mobilenos as $k => $value) {
if (strtolower($row['5']) == 'self' && $row['12'] == $value['mobile']) {
return array('status' => false, 'error' => "Duplicate Mobile No");
// break;
}
}
}
return array('status' => true);
}
}
if (!function_exists('check_dup_mobileno')) {
function check_dup_mobileno(array $row, array $existing_mobilenos, $excel_data = [], $row_key = null)
{
if(!empty($row['12'])){
$current_relation = strtolower(trim($row['5'] ?? ''));
$current_mobile = trim((string) $row['12']);
foreach ($existing_mobilenos as $k => $value) {
if ($current_relation == 'self' && $current_mobile == trim((string) ($value['mobile'] ?? ''))) {
return array('status' => false, 'error' => "Duplicate Mobile No");
// break;
}
}
foreach ($excel_data as $ed_row => $value) {
if ($row_key !== null && (string) $ed_row === (string) $row_key) {
continue;
}
$excel_relation = strtolower(trim($value['5'] ?? ''));
$excel_mobile = trim((string) ($value['12'] ?? ''));
if ($current_relation == 'self' && $excel_relation == 'self' && $excel_mobile !== '' && $current_mobile == $excel_mobile) {
$duplicate_row_no = is_numeric($ed_row) ? $ed_row + 1 : $ed_row;
$current_row_no = is_numeric($row_key) ? $row_key + 1 : $row_key;
return array('status' => false, 'error' => "This mobile number has already been used for another self in Excel at row no. " . ($duplicate_row_no) . " and " . ($current_row_no));
// break;
}
}
}
return array('status' => true);
}
}
// if (!function_exists('check_dup_email')) {
// function check_dup_email(array $row, array $existing_mobilenos)
// {
// is_valid_or_empty_email($row['13']);
// if(!empty($row['13'])){
// foreach ($existing_mobilenos as $k => $value) {
// if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
// return array('status' => false, 'error' => "Duplicate Email");
// // break;
// }
// }
// }
// return array('status' => true);
// }
// }
if (!function_exists('check_dup_email_old')) {
function check_dup_email_old(array $row, array $existing_mobilenos)
{
$errorMessages = [];
// Validate email
$emailCheck = is_valid_or_empty_email($row['13'] ?? "");
if (!$emailCheck) {
$errorMessages[] = 'Invalid email format';
}
// Check duplicate only if email is not empty
if (!empty($row['13'])) {
foreach ($existing_mobilenos as $value) {
if (strtolower(trim($row['5'])) === 'self' && trim($row['13']) === trim($value['email_corporate'])) {
$errorMessages[] = 'Duplicate Email';
break;
}
}
}
// Prepare final return
if (!empty($errorMessages)) {
return ['status' => false, 'error' => implode(' & ', $errorMessages)];
}
return ['status' => true, 'error' => ''];
}
}
if (!function_exists('check_dup_email')) {
function check_dup_email(array $row, array $existing_mobilenos, $excel_data = [], $row_key = null)
{
$errorMessages = [];
$current_relation = strtolower(trim($row['5'] ?? ''));
$current_email = trim((string) ($row['13'] ?? ''));
// Validate email
$emailCheck = is_valid_or_empty_email($current_email);
if (!$emailCheck) {
$errorMessages[] = 'Invalid email format';
}
// Check duplicate only if email is not empty
if (!empty($current_email)) {
foreach ($existing_mobilenos as $value) {
if ($current_relation === 'self' && strcasecmp($current_email, trim((string) ($value['email_corporate'] ?? ''))) === 0) {
$errorMessages[] = 'Duplicate Email';
break;
}
}
foreach ($excel_data as $ed_row => $value) {
if ($row_key !== null && (string) $ed_row === (string) $row_key) {
continue;
}
$excel_relation = strtolower(trim($value['5'] ?? ''));
$excel_email = trim((string) ($value['13'] ?? ''));
if ($current_relation === 'self' && $excel_relation === 'self' && $excel_email !== '' && strcasecmp($current_email, $excel_email) === 0) {
$duplicate_row_no = is_numeric($ed_row) ? $ed_row + 1 : $ed_row;
$current_row_no = is_numeric($row_key) ? $row_key + 1 : $row_key;
$errorMessages[] = "This email has already been used for another self in Excel at row no. " . ($duplicate_row_no) . " and " . ($current_row_no);
break;
}
}
}
// Prepare final return
if (!empty($errorMessages)) {
return ['status' => false, 'error' => implode(' & ', $errorMessages)];
}
return ['status' => true, 'error' => ''];
}
}
if (!function_exists('generate_family_relationship_array')) {
function generate_family_relationship_array($family_structure_from_policy_terms)
{
$family_relationships = [];
// Add self and spouse
if ($family_structure_from_policy_terms['self'] > 0) {
$family_relationships[] = 'self';
}
if ($family_structure_from_policy_terms['spouse'] > 0) {
$family_relationships[] = 'spouse';
}
// Add children
if ($family_structure_from_policy_terms['childrens'] > 0) {
$family_relationships[] = 'son';
$family_relationships[] = 'daughter';
}
// Add parents
if ($family_structure_from_policy_terms['parents'] > 0) {
$family_relationships[] = 'father';
$family_relationships[] = 'mother';
}
// Add parents-in-law
if ($family_structure_from_policy_terms['parents-in-law'] > 0) {
$family_relationships[] = 'father-in-law';
$family_relationships[] = 'mother-in-law';
}
// Add either parents or parents-in-law
if ($family_structure_from_policy_terms['either-parents-pil'] > 0) {
$family_relationships[] = 'father';
$family_relationships[] = 'mother';
$family_relationships[] = 'father-in-law';
$family_relationships[] = 'mother-in-law';
}
return $family_relationships;
}
}
if (!function_exists('convert_string_to_date')) {
function convert_string_to_date($dateString, $defaultFormat = 'd-M-Y')
{
$formats = [
'd-M-Y', // 03-APr-2024
'd M Y', // 03 Apr 2024
'd/M/Y', // 03/Apr/2024
'j M Y', // 3 Apr 2024
'j/M/Y', // 3/Apr/2024
'j-M-Y', // 3-Apr-2024
'Y-m-d' // 2024-04-04
];
foreach ($formats as $format) {
$date = DateTime::createFromFormat($format, $dateString);
if ($date && $date->format($format) == $dateString) {
return $date->format($defaultFormat);
}
}
return false;
}
}
if (!function_exists('transform_enrollment_row_to_inception_row')) {
function transform_enrollment_row_to_inception_row($row)
{
$res = [];
$res[0] = $row[0]; // inception: sno (S.No) -> enrollment: sno (Sno)
$res[1] = $row[1]; // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
$res[2] = $row[2]; // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
$res[3] = $row[6]; // inception: dob (DOB) -> enrollment: dob (DOB)
$res[4] = $row[4]; // inception: gender (Gender) -> enrollment: gender (Gender)
$res[5] = $row[5]; // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
$res[6] = $row[9]; // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
$res[7] = $row[13]; // inception: doc (Date of Coverage) -> No match in enrollment
$res[8] = $row[3]; // inception: doj (DOJ) -> enrollment: doj (DOJ)
$res[9] = $row[11]; // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
$res[10] = $row[10]; // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
$res[11] = null; // inception: designation (Designation) -> No match in enrollment
$res[12] = $row[8]; // inception: phone (Phone) -> enrollment: phone (Mobile)
$res[13] = $row[7]; // inception: email (Email) -> enrollment: email (Email)
$res[14] = 1; // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
$res[15] = null; // inception: change_event (Change event) -> No match in enrollment
$res[16] = null; // inception: date_of_exit (Date of exit) -> No match in enrollment
$res[17] = null; // inception: reason_for_exit (Reason for exit) -> No match in enrollment
return $res;
}
}
if (!function_exists('get_familiy_composition')) {
function get_familiy_composition($family_data)
{
// dd($family_data);
$family_composition = [];
$slug = \Config\Services::slug();
foreach ($family_data as $key => $row) {
// Kint::dump($row);
$relationship = $slug->slugify($row[5]);
// echo $relationship;
if ($relationship == 'self') {
$family_composition['self'] = 1;
} else if (!array_key_exists('self', $family_composition)) {
$family_composition['self'] = 0;
}
if ($relationship == 'spouse') {
$family_composition['spouse'] = 1;
} else if (!array_key_exists('spouse', $family_composition)) {
$family_composition['spouse'] = 0;
}
if ($relationship == 'son' || $relationship == 'daughter') {
$family_composition['childrens'] = (isset($family_composition['childrens']) ? $family_composition['childrens'] + 1 : 1);
} else if (!array_key_exists('childrens', $family_composition)) {
$family_composition['childrens'] = 0;
}
if ($relationship == 'father' || $relationship == 'mother') {
$family_composition['parents'] = (isset($family_composition['parents']) ? $family_composition['parents'] + 1 : 1);
} else if (!array_key_exists('parents', $family_composition)) {
$family_composition['parents'] = 0;
}
if ($relationship == 'father-in-law' || $relationship == 'mother-in-law') {
$family_composition['parents-in-law'] = (isset($family_composition['parents-in-law']) ? $family_composition['parents-in-law'] + 1 : 1);
} else if (!array_key_exists('parents-in-law', $family_composition)) {
$family_composition['parents-in-law'] = 0;
}
}
return ($family_composition);
}
}
if (!function_exists('compare_incoming_family_slab_with_configured_slab')) {
// function compare_incoming_family_slab_with_configured_slab($slab,$incoming_familiy_composition)
// {
// $relationship_mapping = [
// "self" => ["self"],
// "spouse" => ["spouse"],
// "childrens" => ["son", "daughter"],
// "parents" => ["father", "mother"],
// "parents-in-law" => ["father-in-law", "mother-in-law"],
// "either-parents-pil" => ["either-parents-pil"]
// ];
// $result = ['is_applicable' => false,'applicable_members' => []];
// $configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'],true);
// Kint::dump($incoming_familiy_composition);//die();
// Kint::dump($configured_familiy_composition);//die();
// unset($configured_familiy_composition['either-parents-pil']);
// unset($configured_familiy_composition['elders_count']);
// if(count($configured_familiy_composition))
// {
// foreach($configured_familiy_composition as $key => $value)
// {
// if($value != 'NA')
// {
// // echo 'OUTSIDE - ' . $value . $incoming_familiy_composition[$key];
// if(isset($incoming_familiy_composition[$key]) && ($incoming_familiy_composition[$key] == $value || $value == 'any') )
// {
// // echo 'INSIDE - ' . $value;
// $result['is_applicable'] = true;
// $result['applicable_members'] = array_merge($result['applicable_members'],$relationship_mapping[ $key ]);
// }
// else
// {
// $result['is_applicable'] = false;
// $result['applicable_members'] = [];
// // break;
// }
// }
// }
// }
// else
// {
// $result['is_applicable'] = false;
// $result['applicable_members'] = [];
// }
// // dd($result);
// return $result;
// }
function compare_incoming_family_slab_with_configured_slab($slab, $incoming_familiy_composition)
{
$relationship_mapping = [
"self" => ["self"],
"spouse" => ["spouse"],
"childrens" => ["son", "daughter"],
"parents" => ["father", "mother"],
"parents-in-law" => ["father-in-law", "mother-in-law"],
"either-parents-pil" => ["either-parents-pil"]
];
$result = ['is_applicable' => false, 'applicable_members' => []];
$configured_familiy_composition = json_decode($slab['slab_rates'][0]['additional_relationship'], true);
// Remove unnecessary keys
// kint::dump($incoming_familiy_composition);
// kint::dump($configured_familiy_composition);
unset($configured_familiy_composition['either-parents-pil']);
unset($configured_familiy_composition['elders_count']);
// foreach ($configured_familiy_composition as $key => $value) {
// if ($value === 0) {
// // If any relationship is zero, make the rack rate not applicable
// return $result;
// }
// }
if (count($configured_familiy_composition)) {
foreach ($configured_familiy_composition as $key => $value) {
if ($value != 'NA') {
if (isset($incoming_familiy_composition[$key])) {
if ($incoming_familiy_composition[$key] == $value || $value == 'any') {
$result['is_applicable'] = true;
$result['applicable_members'] = array_merge($result['applicable_members'], $relationship_mapping[$key]);
} else {
$result['is_applicable'] = false;
$result['applicable_members'] = [];
break;
}
} else {
$result['is_applicable'] = false;
$result['applicable_members'] = [];
break;
}
}
}
} else {
$result['is_applicable'] = false;
$result['applicable_members'] = [];
}
// dd($result);
return $result;
}
}
if (!function_exists('get_applicable_familiy_members')) {
function get_applicable_familiy_members($family_data, $applicable_members)
{
$slug = \Config\Services::slug();
$result = ['index' => [], 'max_age' => [], 'max_count' => 0];
foreach ($family_data as $index => $family_member) {
if (in_array($slug->slugify($family_member[5]), $applicable_members)) {
$result['index'] = array_merge($result['index'], [$index]);
$result['max_age'] = array_merge($result['max_age'], [calculate_days_bw_dates(from_date: $family_member[3])->y]);
}
}
$result['max_count'] = count($result['index']);
return $result;
}
}
if (!function_exists('check_unit')) {
function check_unit($row, $existing_units)
{
$temp = $row[18];
$temp = empty($row[18]) ? $row[18] : trim($row[18]);
if (in_array($row['current_action'], ['I', 'A', 'MI'])) {
if (count($existing_units) == 1) {
if (empty($temp)) {
return array('status' => true);
} else if ($temp != $existing_units[0]) {
return array('status' => false, 'error' => 'wrong unit name');
}
}
if (strtolower($row[5]) == 'self') {
if (in_array($temp, $existing_units)) //18 is unit name
{
return array('status' => true);
} else if (!empty($temp)) {
return array('status' => false, 'error' => 'wrong unit name');
} else {
return array('status' => false, 'error' => 'name of the unit is mandantory');
}
} else {
if (empty($temp)) {
return array('status' => true);
} else {
if (in_array($temp, $existing_units)) //18 is unit name
{
return array('status' => true);
} else {
return array('status' => false, 'error' => 'wrong unit name');
}
}
}
} else {
return array('status' => true);
}
}
}
if (!function_exists('transform_si_excel_row_to_calculatable_format')) {
function transform_si_excel_row_to_calculatable_format(array $employee, array $employee_policy, array $maxage_and_maxcount, array $slab_details, string $applicable_slab_name, string $augmented_si, array $grid_master)
{
$employee['temp'] = [];
$employee['temp']['max_age'] = $maxage_and_maxcount[0]['max_age'];
$employee['temp']['max_count'] = $maxage_and_maxcount[0]['family_member_count'];
$employee['temp']['grid_name'] = $applicable_slab_name;
$employee['temp']['grid_master'] = $grid_master;
$employee['temp']['acting_self'] = true;
$employee['temp']['premium_type'] = $slab_details['slab_rates'][0]['premium_type'];
$employee['temp']['grid_type'] = $applicable_slab_name;
$employee['temp']['grid_id'] = $grid_master['ui_type'];
$employee['temp']['action'] = 'SI';
$employee['temp']['source'] = 'excel';
$employee['temp']['emp_id'] = null;
$employee['temp']['emp_policy_id'] = null;
$employee['temp']['policy_status'] = null;
$employee['temp']['emp_status'] = null;
$employee['temp']['rata_premimum'] = null;
$employee['policy_details'] = $employee_policy;
return $employee;
}
}
if (!function_exists('group_slab_rates_basedon_name')) {
function group_slab_rates_basedon_name($slab_details)
{
// dd($slab_details);
//grouping slab details by rack rate name
$temp_slab_rates = [];
$pre_name = '';
$pre_grid_master = [];
foreach ($slab_details['slab_rates'] as $key => $value) {
$pre_grid_master = $value['grid_master'];
unset($value['grid_master']);
if ($value['rack_rate_name'] != $pre_name) {
$pre_name = $value['rack_rate_name'];
$temp_slab_rates[$value['rack_rate_name']]['slab_rates'][] = $value;
}
$temp_slab_rates[$value['rack_rate_name']]['slab_rates'][] = $value;
$temp_slab_rates[$value['rack_rate_name']]['grid_master'] = $pre_grid_master;
}
return $temp_slab_rates;
}
}
//this key generating mandantory for display employee info in enrolment app w/o error
if (!function_exists('generate_family_floater_key')) {
function generate_family_floater_key($relationship)
{
if (strtolower(trim($relationship)) === 'mother' || strtolower(trim($relationship)) === 'father') {
$relation = 'parent';
} else if (strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter') {
$relation = 'child';
} else if ((strtolower(trim($relationship)) === 'father in law' || strtolower(trim($relationship)) === 'mother in law') || (strtolower(trim($relationship)) === 'father-in-law' || strtolower(trim($relationship)) === 'mother-in-law')) {
$relation = 'parent_in_law';
} else if (strtolower(trim($relationship)) === 'spouse') {
$relation = 'spouse';
} else if (strtolower(trim($relationship)) === 'self') {
$relation = 'self';
} else {
$relation = '';
}
return $relation;
}
}
if (!function_exists('formatIndianCurrency')) {
function formatIndianCurrency($amount)
{
$amount = (string) $amount;
$decimal = '';
// Split decimal part if exists
if (strpos($amount, '.') !== false) {
list($amount, $decimal) = explode('.', $amount);
$decimal = '.' . substr($decimal, 0, 2); // Limit to 2 decimal places
}
$lastThree = substr($amount, -3);
$rest = substr($amount, 0, -3);
if ($rest != '') {
$rest = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $rest);
$formatted = $rest . ',' . $lastThree;
} else {
$formatted = $lastThree;
}
return $formatted . $decimal;
}
}
if (!function_exists('normalizeGender')) {
function normalizeGender($gender)
{
$gender = strtoupper(trim($gender));
if (in_array($gender, ['M', 'MALE'])) {
return 'M';
} elseif (in_array($gender, ['F', 'FEMALE'])) {
return 'F';
}
// Optional: return null or original if not recognized
return null;
}
}
if (!function_exists('check_change_event')) {
function check_change_event($row, $file)
{
$change_event = isset($row[15]) ? $row[15] : '';
$action = isset($file['action']) ? $file['action'] : '';
$allowed_values = [
'inception' => ['inception'],
'addition' => ['addition'],
'dependent_addition' => ['dependent addition', 'd-addition'],
'missed_inception' => ['missed inception'],
];
$normalize = function ($value) {
return strtolower(trim((string) $value)); // ✅ Added `return`
};
$change_event = $normalize($change_event);
// Allow inception with no change_event
if ($action === 'inception' && empty($change_event)) {
return ['status' => true];
}
// Validate change_event against allowed values for the given action
if (isset($allowed_values[$action]) && in_array($change_event, $allowed_values[$action])) {
return ['status' => true];
}
// Build error message
$expected_values = $allowed_values[$action] ?? [];
$expected_message = "'" . implode("' or '", array_map('strtoupper', $expected_values)) . "'";
if ($action === 'inception') {
$expected_message .= " or blank";
}
return [
'status' => false,
'error' => "Rule Conflict: Invalid Change Event for this action\n\n'{$action}'. Expected {$expected_message}", ];
}
}
if (!function_exists('normalize_file_action')) {
function normalize_file_action($file_action)
{
if($file_action == 'inception'){
return 'Inception';
}else if($file_action == 'addition'){
return 'Addition';
}else if($file_action == 'dependent_addition'){
return 'Dependent Addition';
}else if($file_action == 'deletion'){
return 'Deletion';
}else if($file_action == 'correction'){
return 'Correction';
}else if($file_action == 'si_enhancement'){
return 'SI Enhancement';
}else if($file_action == 'enrollment'){
return 'Enrollment';
}else if($file_action == 'missed_inception'){
return 'Missed Inception';
}
return '';
}
}
// ------------- FUNCTION FOR LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
if (!function_exists('check_columns_name_exist')) {
function check_columns_name_exist($definedColumns, $excelColumns)
{
$mismatchedColumns = [];
foreach ($definedColumns as $colKey => $definedCol) {
$definedColName = strtolower(trim($definedCol['col_name']));
// Normalize excel columns to lowercase for comparison
$excelColsLower = array_map('strtolower', array_map('trim', $excelColumns));
if (!in_array($definedColName, $excelColsLower)) {
$mismatchedColumns[] = "Missing column: <strong>" . $definedCol['col_name'] . "</strong> in Excel file.<br/>";
}
}
return $mismatchedColumns;
}
}
if (!function_exists('update_excel_column_indexes')) {
function update_excel_column_indexes($definedColumns, $excelColumns)
{
// $excelColumns is the first row of the Excel file (header row)
// Example: ['Emp Code', 'Name', 'Gender', 'DOB', 'SI']
foreach ($definedColumns as $key => &$definedCol) {
$definedColName = strtolower(trim($definedCol['col_name']));
$excelColsLower = array_map('strtolower', array_map('trim', $excelColumns));
// Find column index in Excel
$colIndex = array_search($definedColName, $excelColsLower);
if ($colIndex !== false) {
$definedCol['col_idx'] = $colIndex;
$definedCol['col_cell_name'] = chr(65 + $colIndex); // A=65, B=66...
} else {
// If column missing in Excel
$definedCol['col_idx'] = null;
$definedCol['col_cell_name'] = null;
}
}
return $definedColumns;
}
}
if (!function_exists('check_duplicate_rows_and_contacts')) {
function check_duplicate_rows_and_contacts($excel_data, $columns_to_check, $err_data)
{
$exl_col = $columns_to_check;
$keys = array_keys($columns_to_check);
unset($columns_to_check['sno'], $columns_to_check['si'], $columns_to_check['email'], $columns_to_check['mobile'], $columns_to_check['age']);
$seenRows = [];
$emailSeen = [];
$mobileSeen = [];
$duplicateRows = [];
foreach ($excel_data as $rowIndex => $row) {
// Build unique key from selected columns
$values = [];
foreach ($columns_to_check as $colIdx) {
$values[] = isset($row[$colIdx['col_idx']]) ? trim($row[$colIdx['col_idx']]) : '';
}
$rowKey = json_encode($values);
// =============== STEP 1: Main duplicate check ===============
if (!isset($seenRows[$rowKey])) {
$seenRows[$rowKey] = [$rowIndex];
} else {
// First duplicate occurrence — mark all related rows
$seenRows[$rowKey][] = $rowIndex;
$indexes = $seenRows[$rowKey];
$rows_str = implode(', ', array_map(fn($i) => $i + 1, $indexes));
$error_message = "Duplicate found in selected columns: Rows {$rows_str} are identical";
foreach ($indexes as $i) {
// Avoid re-adding duplicate errors
if (!in_array($i, $duplicateRows)) {
array_push($err_data['error_summary'], 1);
$err_data['error_data'][$i][$keys[0]]['col_name'] = 'Sl no';
$err_data['error_data'][$i][$keys[0]]['col_idx'] = 0;
$err_data['error_data'][$i][$keys[0]]['error'][] = $error_message;
$duplicateRows[] = $i;
}
}
// Skip email/mobile check for this duplicate row
continue;
}
// =============== STEP 2: Email & Mobile check (only if not duplicate) ===============
$email = isset($row[$exl_col['email']['col_idx']]) ? trim($row[$exl_col['email']['col_idx']]) : '';
$mobile = isset($row[$exl_col['mobile']['col_idx']]) ? trim($row[$exl_col['mobile']['col_idx']]) : '';
// Check email duplicates
if ($email !== '') {
if (isset($emailSeen[$email])) {
$firstIndex = $emailSeen[$email] + 1;
$currentRow = $rowIndex + 1;
$error_message = "Duplicate email found: Row {$currentRow} and Row {$firstIndex} have the same email '$email'";
array_push($err_data['error_summary'], 1);
$err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['col_name'] = $exl_col['email']['col_name'];
$err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['col_idx'] = $exl_col['email']['col_idx'];
$err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['error'][] = $error_message;
} else {
$emailSeen[$email] = $rowIndex;
}
}
// Check mobile duplicates
if ($mobile !== '') {
if (isset($mobileSeen[$mobile])) {
$firstIndex = $mobileSeen[$mobile] + 1;
$currentRow = $rowIndex + 1;
$error_message = "Duplicate mobile number found: Row {$currentRow} and Row {$firstIndex} have the same mobile '$mobile'";
array_push($err_data['error_summary'], 1);
$err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['col_name'] = $exl_col['mobile']['col_name'];
$err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['col_idx'] = $exl_col['mobile']['col_idx'];
$err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['error'][] = $error_message;
} else {
$mobileSeen[$mobile] = $rowIndex;
}
}
}
return $err_data;
}
}
if (!function_exists('check_relationship_for_member_data')) {
function check_relationship_for_member_data($row, $relationship, $columns_to_check)
{
$relation_col_idx = $columns_to_check['relationship']['col_idx'] ?? null;
$gender_col_idx = $columns_to_check['gender']['col_idx'] ?? null;
if ($relation_col_idx !== null && $gender_col_idx !== null && !empty($row[$relation_col_idx]) && !empty($row[$gender_col_idx])) { //$row[5] = relationship $row[4] = Gender
$slug = \Config\Services::slug();
$col = $slug->slugify($row[$relation_col_idx]);
if ($col != 'self' && $col != 'spouse') {
if (!isset($relationship[$col])) {
return array('status' => false, 'error' => 'Rule Conflict: Unknown Relationship');
}
if (isset($relationship[$col]) && $relationship[$col]['gender'] != $row[$gender_col_idx]) {
$error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[$gender_col_idx]";
return array('status' => false, 'error' => $error);
}
}
return array('status' => true);
} else {
return array('status' => false, 'error' => 'Rule Conflict: Both Relationship and Gender required for check relationship conflict');
}
}
}
if (!function_exists('member_data_group_by_family')) {
function member_data_group_by_family($member_data, $columns_to_check)
{
$result = [];
// Kint::dump($member_data);
foreach ($member_data as $rowIndex => $row) {
if (!check_row_is_empty_or_null($row)) {
$row['row_index'] = $rowIndex;
$relation_idx = $columns_to_check['relationship']['col_idx'];
$emp_code_idx = $columns_to_check['emp_code']['col_idx'];
if (isset($row[$relation_idx]) && strtolower($row[$relation_idx]) == 'self' && isset($result[$row[$emp_code_idx]])) {
array_unshift($result[$row[$emp_code_idx]], $row);
} else {
$result[$row[$emp_code_idx]][] = $row;
}
}
}
return $result;
}
}
if (!function_exists('validateFamily')) {
function validateFamily($familyData, $columns_to_check, $errors) {
$keys = array_keys($columns_to_check);
foreach ($familyData as $familyId => $members) {
$selfMember = null;
$spouseMember = null;
$selfCount = 0;
$row_index = null;
// Find Self and Spouse members
foreach ($members as $member) {
$relation = trim($member[3]); // Relationship field
if (strtolower($relation) == 'self') {
$selfCount++;
$selfMember = $member;
}
if (strtolower($relation) == 'spouse') {
$spouseMember = $member;
}
if($row_index == null){
if(strtolower($relation) == 'self'){
$row_index = $member['row_index'];
}else if(strtolower($relation) == 'spouse'){
$row_index = $member['row_index'];
}else{
$row_index = $member['row_index'];
}
}
}
// Validation 1: Check if Self exists
if ($selfCount === 0) {
$message = "Emp ID - {$familyId}: Missing 'Self' member";
array_push($errors['error_summary'], 4);
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message;
continue;
}
// Validation 2: Check if there's exactly one Self
if ($selfCount > 1) {
$message = "Emp ID - {$familyId}: Multiple 'Self' members found. Only one 'Self' is allowed per family";
array_push($errors['error_summary'], 5);
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message;
continue;
}
// Validation 3: Validate spouse gender if spouse exists
if ($spouseMember !== null) {
$selfGender = normalizeGender(trim($selfMember[4])); // Gender field
$spouseGender = normalizeGender(trim($spouseMember[4]));
$selfName = $selfMember[2]; // Name field
$spouseName = $spouseMember[2];
// Check gender compatibility
$message = '';
if ($selfGender === 'M' && $spouseGender !== 'F') {
$message = "Emp ID - {$familyId}: Self ('{$selfName}') is Male (M); spouse must be Female (F). Found spouse ('{$spouseName}') with gender '({$spouseGender})'.";
} elseif ($selfGender === 'F' && $spouseGender !== 'M') {
$message = "Emp ID - {$familyId}: Self ('{$selfName}') is Female (F); spouse must be Male (M). Found spouse ('{$spouseName}') with gender '({$spouseGender})'.";
} elseif (!in_array($selfGender, ['M', 'F'])) {
$message = "Emp ID - {$familyId}: Invalid gender for Self member ('{$selfName}'). Expected 'M' or 'F', found '({$selfGender})'.";
}
if(isset($message) && !empty($message)){
array_push($errors['error_summary'], 6);
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx'];
$errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message;
}
}
}
return $errors;
}
}
if (!function_exists('check_age_validation')) {
function check_age_validation($row, $family_composition)
{
if ($row[5] != null) {
$dateString = convert_string_to_date($row[5]);
if ($dateString === false) {
return array('status' => false, 'error' => 'Not a valid Date');
}
$relationships = $family_composition['age_ratio'];
$dob = $dateString;
$currentDateTime = new DateTime();
$passedDateTime = new DateTime($dob);
$interval = $currentDateTime->diff($passedDateTime);
$slug = \Config\Services::slug();
$relationship = $slug->slugify($row[3]);
if($relationship == 'son' || $relationship == 'daughter'){
$relationship = 'child';
}
if($relationship == 'father' || $relationship == 'mother' || $relationship == 'mother-in-law'|| $relationship == 'father-in-law' ){
$relationship = 'elders';
}
$age_min = isset($relationships[$relationship]['min']) ? $relationships[$relationship]['min'] : NULL;
$age_max = isset($relationships[$relationship]['max']) ? $relationships[$relationship]['max'] : NULL;
// Kint::dump($dob,$currentDateTime,$passedDateTime, $interval->y, $age_min, $age_max, $relationship, $relationships);
if ($age_min !== null && $age_min > $interval->y) {
return array('status' => false, 'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y");
}
if ($age_max !== null && $age_max < $interval->y) {
return array('status' => false, 'error' => "Age conflict : maximum $age_max yrs allowed, received $interval->y");
}
return array('status' => true);
} else {
return array('status' => false, 'error' => 'Rule Conflict: Both DOB and Relationship required for age check');
}
}
}
// ------------- END OF LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
if (!function_exists('is_valid_or_empty_email')) {
function is_valid_or_empty_email($email)
{
// If empty or null → return success
if (empty($email) && $email != 0) {
// return ['status' => true, 'error' => 'Value is empty'];
return true;
}
// If valid email → return success
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// return ['status' => true, 'error' => 'Valid email format'];
return true;
}
// If invalid email → return failure
// return ['status' => false, 'error' => 'Invalid email format'];
return false;
}
}
if (!function_exists('validatet_family_floter_rata_premium')) {
function validatet_family_floter_rata_premium($family)
{
// If only two members, skip
if (count($family) === 2) {
return $family;
}
// Count excel rows
$excelCount = count(array_filter($family, fn($r) =>
($r['data_from'] ?? '') === 'excel'
));
// Extract self row
$selfDataArr = array_filter($family, fn($r) =>
strtolower($r['relationship'] ?? '') === 'self'
);
$selfData = reset($selfDataArr);
$dependentRataGiven = false;
/**
* ---------------------------------------------------
* 1. RESET DEPENDENT PREMIUM IF SELF HAS SAME RATA
* ---------------------------------------------------
*/
if (
!empty($selfData['temp']) &&
!empty($selfData['policy_details']) &&
($selfData['temp']['premium'] ?? 0) == ($selfData['policy_details']['premium'] ?? 0)
) {
foreach ($family as &$row) {
if (strtolower($row['relationship'] ?? '') === 'self') {
continue;
}
if (
($row['temp']['premium_type'] ?? null) == 1 &&
($row['data_from'] ?? '') === 'excel'
) {
$row['policy_details']['rata_premimum'] = 0;
$row['policy_details']['gst'] = 0;
}
}
}
/**
* ---------------------------------------------------
* 2. APPLY FINAL PREMIUM ADJUSTMENT TO DEPENDENTS
* ---------------------------------------------------
*/
foreach ($family as &$row) {
if (strtolower($row['relationship'] ?? '') === 'self') {
continue;
}
if (($row['temp']['premium_type'] ?? null) == 1) {
// FIRST excel dependent keeps premium
if (!$dependentRataGiven && ($row['data_from'] ?? '') === 'excel') {
$dependentRataGiven = true;
} else if (($row['data_from'] ?? '') === 'excel') {
$row['policy_details']['rata_premimum'] = 0;
$row['policy_details']['gst'] = 0;
}
}
}
return $family;
}
}
if (!function_exists('validate_excel_value')) {
function validate_excel_value($value, $data_type, $format = null, $allowed_values = null)
{
switch ($data_type) {
case 'date':
return validate_date_value($value, $format);
case 'str':
return check_excel_date_format($value, $format);
case 'mobile':
return validate_mobile_value($value);
case 'email':
return validate_email_value($value);
case 'vehicle':
return validate_indian_vehicle_number($value);
case 'positive_number':
return validate_positive_number_value($value);
default:
return [
'status' => true,
'error' => null
];
}
}
}
if (!function_exists('validate_date_value')) {
function validate_date_value($value, $format)
{
if(empty($value)) {
return ['status' => true, 'error' => null]; // allow empty
}
$d = DateTime::createFromFormat($format, $value);
if ($d && $d->format($format) === $value) {
return ['status' => true, 'error' => null];
}
return [
'status' => false,
'error' => "Invalid date format. Expected format: {$format}"
];
}
}
if (!function_exists('validate_mobile_value')) {
function validate_mobile_value($value)
{
if(empty($value))
{
return ['status' => true, 'error' => null];
}
if (preg_match('/^[0-9]{10}$/', $value)) {
return ['status' => true, 'error' => null];
}
return [
'status' => false,
'error' => "Invalid mobile number. It must be exactly 10 digits, with no spaces and no +91 prefix."
];
}
}
if (!function_exists('validate_positive_number_value')) {
function validate_positive_number_value($value)
{
$value = cleanNumber($value);
if ($value === "" || $value === null) {
return ['status' => true, 'error' => null];
}
if (is_numeric($value) && $value >= 0) {
return ['status' => true, 'error' => null];
}
return [
'status' => false,
'error' => "Value must be a positive number"
];
}
}
if (!function_exists('validate_email_value')) {
function validate_email_value($value)
{
if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
return ['status' => true, 'error' => null];
}
return [
'status' => false,
'error' => "Invalid email address."
];
}
}
if (!function_exists('validate_indian_vehicle_number')) {
function validate_indian_vehicle_number($number)
{
$number = strtoupper(trim($number));
$new_vehicle = strtolower(trim($number));
if($new_vehicle == "new"){
return ['status' => true, 'error' => null];
}
// Normal Format:
// 2 letters (state) + 2 digits (district) + 1 or 2 letters (series) + 4 digits
$normalPattern = '/^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{4}$/';
// BH Series: 22BH1234AA
$bhPattern = '/^[0-9]{2}BH[0-9]{4}[A-Z]{2}$/';
if (preg_match($normalPattern, $number)) {
return ['status' => true, 'error' => null];
}
if (preg_match($bhPattern, $number)) {
return ['status' => true, 'error' => null];
}
return [
'status' => false,
'error' => "Invalid Vehicle Number"
];
}
}
if (!function_exists('check_user_exist')) {
function check_user_exist($row, $col_key, $user_data)
{
// Get the uploaded value from the column
$input_value = trim($row[$col_key]);
// Loop DB user list
foreach ($user_data as $user) {
// Check if DB has 'first_name' key and matches input
if (isset($user['first_name']) && strtolower(trim($user['first_name'])) === strtolower($input_value)) {
return [
'status' => true,
'error' => null,
'user' => $user,
];
}
}
// If no user matched
return [
'status' => false,
'error' => "User '{$input_value}' not found in database."
];
}
}
if (!function_exists('check_agent_exist')) {
function check_agent_exist($row, $agent_data)
{
// Get agent code from the uploaded row
$agent_code = trim($row[15]); // or use index if needed
// Loop agent data from DB
foreach ($agent_data as $agent) {
// Assuming DB keys: agent_code
if (isset($agent['pos_code']) && (strtolower($agent['pos_code']) == strtolower($agent_code))) {
return [
'status' => true,
'error' => null,
'agent' => $agent,
];
}
}
// If not matched
return [
'status' => false,
'error' => "Agent code '{$agent_code}' not found in database."
];
}
}
if (!function_exists('check_rto_data')) {
function check_rto_data($row, $rto_master)
{
// Vehicle number from uploaded row
$vehicle_no = strtoupper(trim($row[2])); // Example: TN10AB1234
$new_vehicle = strtolower(trim($row[2]));
if(!validate_indian_vehicle_number($vehicle_no)['status']){
return [
'status' => false,
'error' => 'Invalid Vehicle Number. Format should be like TN82AX2024 (no spaces or special characters).'
];
};
// BH Series: 22BH1234AA
$bhPattern = '/^[0-9]{2}BH[0-9]{4}[A-Z]{2}$/';
if (preg_match($bhPattern, $vehicle_no)) {
return [
'status' => true,
'error' => null,
'rto_data' => []
];
}
if($new_vehicle == "new"){
return [
'status' => true,
'error' => null,
'rto_data' => []
];
}
// Must be at least 4 characters to extract RTO
if (strlen($vehicle_no) < 4) {
return [
'status' => false,
'error' => "Invalid vehicle number format: '{$vehicle_no}'"
];
}
// Extract State (first 2 letters) and RTO Code (next 2 digits)
$state_code = substr($vehicle_no, 0, 2); // TN
$rto_code = substr($vehicle_no, 2, 2); // 10
// Validate they are correct format
if (!ctype_alpha($state_code) || !ctype_digit($rto_code)) {
return [
'status' => false,
'error' => "Vehicle number '{$vehicle_no}' has invalid state or RTO code."
];
}
// Loop RTO master data
foreach ($rto_master as $rto) {
// Expected DB fields: rto_state, rto_code
if (
isset($rto['rto_state']) &&
isset($rto['rto_code']) &&
strtoupper($rto['rto_state']) === $state_code &&
(string)$rto['rto_code'] === $rto_code
) {
return [
'status' => true,
'error' => null,
'rto_data' => $rto
];
}
}
// Not found in RTO master
return [
'status' => false,
'error' => "RTO '{$state_code} {$rto_code}' not found in RTO master."
];
}
}
if (!function_exists('check_vehicle_type')) {
function check_vehicle_type($row, $vehicle_type)
{
// Vehicle type from uploaded Excel row
$input_type = strtolower(trim($row[3])); // Example: CAR
// Loop vehicle type master
foreach ($vehicle_type as $vt) {
if (isset($vt['vehicle_type']) && strtolower($vt['vehicle_type']) == $input_type) {
return [
'status' => true,
'error' => null,
'vehicle_type' => $vt,
];
}
}
// Not found in master
return [
'status' => false,
'error' => "Vehicle type '{$input_type}' not found in master."
];
}
}
if (!function_exists('check_policy_no')) {
function check_policy_no($row, $pt_data)
{
// Get policy number from Excel row
$policy_no = strtolower(trim($row[4]));
// Empty policy number
if ($policy_no === '') {
return [
'status' => false,
'error' => "Policy number is empty."
];
}
// Loop all policy transactions (pt_data)
foreach ($pt_data as $pt) {
// Check policy_no exists in DB list
if (isset($pt['policy_no']) && strtolower($pt['policy_no']) == $policy_no) {
return [
'status' => false,
'error' => "Duplicate policy number '{$policy_no}' found in database."
];
}
}
// If no match found → not duplicate
return [
'status' => true,
'error' => null
];
}
}
if (!function_exists('check_insurer_exist')) {
function check_insurer_exist($row, $insurer_master)
{
// Get insurer short name from Excel row (col 7)
$short_name = strtolower(trim($row[7]));
foreach ($insurer_master as $insurer) {
if (
isset($insurer['short_name']) &&
strtolower($insurer['short_name']) === $short_name
) {
return [
'status' => true,
'error' => null,
'insurer' => $insurer // return entire insurer row for next validation
];
}
}
return [
'status' => false,
'error' => "Insurer '{$short_name}' not found in database."
];
}
}
if (!function_exists('check_insurer_branch_exist')) {
function check_insurer_branch_exist($row, $insurer_branch_master, $insurer)
{
// Get branch code from Excel row (col 8)
$branch_code = strtolower(trim($row[8]));
// Loop all branches
foreach ($insurer_branch_master as $branch) {
if (
isset($insurer['id']) && $branch['insurer_id'] == $insurer['id'] &&
strtolower($branch['branch_code']) == $branch_code
) {
return [
'status' => true,
'error' => null,
'branch' => $branch
];
}
}
return [
'status' => false,
'error' => "Branch code '{$branch_code}' not found in database."
];
}
}
if (!function_exists('check_nhance_branch')) {
function check_nhance_branch($row, $nhance_branch_master)
{
// Get branch name from Excel row (col 8)
$branch_name = strtolower(trim($row[1]));
// Loop all branches
foreach ($nhance_branch_master as $branch) {
if (
isset($branch['branch_name']) &&
strtolower($branch['branch_name']) == $branch_name
) {
return [
'status' => true,
'error' => null,
'branch' => $branch
];
}
}
return [
'status' => false,
'error' => "Branch '{$branch_name}' not found in database."
];
}
}
if (!function_exists('calculate_gst_amount')) {
function calculate_gst_amount($row) {
// Extract values
$base_premium = (float)trim($row[16]);
$non_commission_premium_amount = (float)trim($row[17]);
$tp_premium = (float)trim($row[18]);
$igst = (float)trim($row[19]);
$cgst = (float)trim($row[20]);
$sgst = (float)trim($row[21]);
// Total GST percentage
$gst_percentage = $igst + $cgst + $sgst;
// Step 1: Choose taxable amount
if ($non_commission_premium_amount > 0) {
// GST on non-commission premium
$taxable_amount = $non_commission_premium_amount;
} else {
// GST on base premium + TP premium
$taxable_amount = $base_premium + $tp_premium;
}
// Step 2: GST Amount calculation
$gst_amount = ($taxable_amount * $gst_percentage) / 100;
return round($gst_amount, 2);
}
}
if (!function_exists('check_gst_percentage')) {
function check_gst_percentage($row)
{
$igst = (float)trim($row[19]);
$cgst = (float)trim($row[20]);
$sgst = (float)trim($row[21]);
// CASE 1: IGST is entered → CGST & SGST must be zero
if ($igst > 0) {
if ($cgst > 0 || $sgst > 0) {
return [
'status' => false,
'error' => "Invalid GST configuration: When IGST is entered, CGST and SGST must be 0."
];
}
return [
'status' => true,
'error' => null,
'gst_type' => "IGST"
];
}
// CASE 2: IGST = 0 → CGST and SGST must be entered together
if ($cgst > 0 || $sgst > 0) {
if ($cgst == 0 || $sgst == 0) {
return [
'status' => false,
'error' => "Invalid GST configuration: CGST and SGST must both be entered when IGST is 0."
];
}
return [
'status' => true,
'error' => null,
'gst_type' => "CGST+SGST"
];
}
// CASE 3: No GST provided at all
return [
'status' => false,
'error' => "GST values missing: Enter either IGST or both CGST and SGST."
];
}
}
if (!function_exists('calculateMotorPolicyAmounts')) {
function calculateMotorPolicyAmounts(array $data)
{
try {
// Parse incoming values (fallback to 0)
$bp = floatval($data['base_premium'] ?? 0);
$ncpa = floatval($data['non_commission_premium_amount'] ?? 0);
$tp = floatval($data['tp_premium'] ?? 0);
$igst = floatval($data['igst'] ?? 0);
$cgst = floatval($data['cgst'] ?? 0);
$sgst = floatval($data['sgst'] ?? 0);
$stamp = floatval($data['stamp_duty'] ?? 0);
$agreed_amount = floatval($data['agreed_amount'] ?? 0);
$ag_bp_per = floatval($data['agreed_bp_percentage'] ?? 0);
$ag_tp_per = floatval($data['agreed_tp_percentage'] ?? 0);
$std_bp_per = floatval($data['standard_bp_percentage'] ?? 0);
$std_tp_per = floatval($data['standard_tp_percentage'] ?? 0);
// Determine GST %
$gst_per = ($igst > 0) ? $igst : ($cgst + $sgst);
// Motor Policy Premium Logic
$tpTotal = $bp + $tp;
// GST without NCPA
$gst_per_amt = ($tpTotal * $gst_per) / 100;
// GST with NCPA
$ncpaTotal = $tpTotal + $ncpa;
$ncpa_gst_per_amt = ($ncpaTotal * $gst_per) / 100;
// Choose correct GST amount
$gst_amount = ($ncpa != 0) ? $ncpa_gst_per_amt : $gst_per_amt;
// Total amount payable
$total_amount = $tpTotal + $gst_amount + $stamp;
// Expected Amount
$sum_agreed = $ag_bp_per + $ag_tp_per;
$expected_amount = 0;
if ($agreed_amount > 0) {
$expected_amount = $agreed_amount; // Formula 1
} elseif ($sum_agreed > 0) {
// Formula 2 Agreed %
$expected_amount =
(($bp * $ag_bp_per) / 100) +
(($tp * $ag_tp_per) / 100);
} else {
// Formula 3 Standard %
$expected_amount =
(($bp * $std_bp_per) / 100) +
(($tp * $std_tp_per) / 100);
}
// Final return array
return [
'gst_amount' => round($gst_amount, 2),
'total_amount' => round($total_amount, 2),
'expected_amount' => round($expected_amount, 2),
];
} catch (\Throwable $e) {
log_message('error', 'Motor Policy Calculation Error: ' . $e->getMessage());
return [];
}
}
}