diff --git a/app/Config/Routes.php b/app/Config/Routes.php index e94c6ad4..d1195ea6 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -308,7 +308,12 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("send_mail_for_individual_employee_ecard/(:any)", "EmployeeController::send_mail_for_individual_employee_ecard/$1"); $routes->post("update_emp_data", "EmployeeController::update_emp_data"); $routes->get("checkDeletionGetDataFunction", "EmployeeController::checkDeletionGetDataFunction"); - + $routes->get("download_import_excel/(:any)", "EmployeeController::downloadSampleImportExcelFile/$1"); + $routes->get("getInsurerBranchContacts/(:any)", "LeadsController::getInsurerBranchContacts/$1"); + $routes->get("download_import_file/(:any)", "EmployeeController::download_import_file/$1"); + $routes->get('log_list', 'EmployeeController::listLogs'); + $routes->get('view_log/(:any)', 'EmployeeController::viewLog/$1'); + $routes->get('download_log/(:any)', 'EmployeeController::downloadLog/$1'); }); $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index b937e835..e90f1e1b 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -120,7 +120,29 @@ class ClientController extends AdminController public function smapletest() { - $headers = ['S.No','EMP ID','EMP NAME','DOB','GENDER','RELATIONSHIP','SUM INSURED','Date of Leaving','Policy End Date','No Of Days','Premium','Pro Rata Premium','GST','Total','Claim Status','ENDORSEMENT_ID']; + $headers = [ + 'S.No', + 'NAME OF EMP/DEP', + 'EMP ID', + // 'EMP/DEP TYPE', + // 'RELATIONSHIP CODE', + 'DOB', + 'GENDER', + 'PRE EXISTING AILMENTS', + 'BASIC COVER SI', + 'DATE OF COVERAGE', + 'AGE', + 'RELATIONSHIP', + 'REMARKS', + 'POLICY END DATE', + 'NO OF DAYS', + 'TPA ID', + 'UHID', + // 'PREMIUM', + 'PRO RATA PREMIUM', + 'GST', + 'TOTAL AMOUNT' + ]; $filePath = generateExcelWithHeader($headers); echo "Excel file created at: $filePath"; } diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index ff8e0413..9ae9e2d1 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -225,93 +225,93 @@ class EmpDataServiceController extends BaseController 'column_name' => 'EMP ID', 'db_column_name' => 'emp_code' ], + // [ + // 'column_index' => 3, + // 'column_name' => 'EMP/DEP TYPE', + // 'db_column_name' => 'emp_type' + // ], + // [ + // 'column_index' => 4, + // 'column_name' => 'RELATIONSHIP CODE', + // 'db_column_name' => 'emp_relationship_code' + // ], [ 'column_index' => 3, - 'column_name' => 'EMP/DEP TYPE', - 'db_column_name' => 'emp_type' - ], - [ - 'column_index' => 4, - 'column_name' => 'RELATIONSHIP CODE', - 'db_column_name' => 'emp_relationship_code' - ], - [ - 'column_index' => 5, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob' ], [ - 'column_index' => 6, + 'column_index' => 4, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender' ], [ - 'column_index' => 7, + 'column_index' => 5, 'column_name' => 'PRE EXISTING AILMENTS', 'db_column_name' => 'pre_existing_alignments' ], [ - 'column_index' => 8, + 'column_index' => 6, 'column_name' => 'BASIC COVER SI', 'db_column_name' => 'basic_cover_si' ], [ - 'column_index' => 9, + 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', 'db_column_name' => 'date_coverage' ], [ - 'column_index' => 10, + 'column_index' => 8, 'column_name' => 'AGE', 'db_column_name' => 'emp_age' ], [ - 'column_index' => 11, + 'column_index' => 9, 'column_name' => 'RELATIONSHIP', 'db_column_name' => 'emp_relationship' ], [ - 'column_index' => 12, + 'column_index' => 10, 'column_name' => 'REMARKS', 'db_column_name' => 'remarks' ], [ - 'column_index' => 13, + 'column_index' => 11, 'column_name' => 'POLICY END DATE', 'db_column_name' => 'policy_end_date' ], [ - 'column_index' => 14, + 'column_index' => 12, 'column_name' => 'NO OF DAYS', 'db_column_name' => 'days' ], [ - 'column_index' => 15, + 'column_index' => 13, 'column_name' => 'TPA ID', 'db_column_name' => 'tpa_id' ], [ - 'column_index' => 16, + 'column_index' => 14, 'column_name' => 'UHID', 'db_column_name' => 'uhid' ], + // [ + // 'column_index' => 15, + // 'column_name' => 'PREMIUM', + // 'db_column_name' => 'premium' + // ], [ - 'column_index' => 17, - 'column_name' => 'PREMIUM', - 'db_column_name' => 'premium' - ], - [ - 'column_index' => 18, + 'column_index' => 15, 'column_name' => 'PRO RATA PREMIUM', 'db_column_name' => 'rata_premimum' ], [ - 'column_index' => 19, + 'column_index' => 16, 'column_name' => 'GST', 'db_column_name' => 'gst' ], [ - 'column_index' => 20, + 'column_index' => 17, 'column_name' => 'TOTAL AMOUNT', 'db_column_name' => 'total' ] @@ -335,93 +335,93 @@ class EmpDataServiceController extends BaseController 'column_name' => 'EMP ID', 'db_column_name' => 'emp_code' ], + // [ + // 'column_index' => 3, + // 'column_name' => 'EMP/DEP TYPE', + // 'db_column_name' => 'emp_type' + // ], + // [ + // 'column_index' => 4, + // 'column_name' => 'RELATIONSHIP CODE', + // 'db_column_name' => 'emp_relationship_code' + // ], [ 'column_index' => 3, - 'column_name' => 'EMP/DEP TYPE', - 'db_column_name' => 'emp_type' - ], - [ - 'column_index' => 4, - 'column_name' => 'RELATIONSHIP CODE', - 'db_column_name' => 'emp_relationship_code' - ], - [ - 'column_index' => 5, 'column_name' => 'DOB', 'db_column_name' => 'emp_dob' ], [ - 'column_index' => 6, + 'column_index' => 4, 'column_name' => 'GENDER', 'db_column_name' => 'emp_gender' ], [ - 'column_index' => 7, + 'column_index' => 5, 'column_name' => 'PRE EXISTING AILMENTS', 'db_column_name' => 'pre_existing_alignments' ], [ - 'column_index' => 8, + 'column_index' => 6, 'column_name' => 'BASIC COVER SI', 'db_column_name' => 'basic_cover_si' ], [ - 'column_index' => 9, + 'column_index' => 7, 'column_name' => 'DATE OF COVERAGE', 'db_column_name' => 'date_coverage' ], [ - 'column_index' => 10, + 'column_index' => 8, 'column_name' => 'AGE', 'db_column_name' => 'emp_age' ], [ - 'column_index' => 11, + 'column_index' => 9, 'column_name' => 'RELATIONSHIP', 'db_column_name' => 'emp_relationship' ], [ - 'column_index' => 12, + 'column_index' => 10, 'column_name' => 'REMARKS', 'db_column_name' => 'remarks' ], [ - 'column_index' => 13, + 'column_index' => 11, 'column_name' => 'POLICY END DATE', 'db_column_name' => 'policy_end_date' ], [ - 'column_index' => 14, + 'column_index' => 12, 'column_name' => 'NO OF DAYS', 'db_column_name' => 'no_of_days' ], [ - 'column_index' => 15, + 'column_index' => 13, 'column_name' => 'TPA ID', 'db_column_name' => 'tpa_id' ], [ - 'column_index' => 16, + 'column_index' => 14, 'column_name' => 'UHID', 'db_column_name' => 'uhid' ], + // [ + // 'column_index' => 17, + // 'column_name' => 'PREMIUM', + // 'db_column_name' => 'premium' + // ], [ - 'column_index' => 17, - 'column_name' => 'PREMIUM', - 'db_column_name' => 'premium' - ], - [ - 'column_index' => 18, + 'column_index' => 15, 'column_name' => 'PRO RATA PREMIUM', 'db_column_name' => 'pro_rata_premium' ], [ - 'column_index' => 19, + 'column_index' => 16, 'column_name' => 'GST', 'db_column_name' => 'gst' ], [ - 'column_index' => 20, + 'column_index' => 17, 'column_name' => 'TOTAL AMOUNT', 'db_column_name' => 'total' ] @@ -1283,7 +1283,29 @@ class EmpDataServiceController extends BaseController unset($excel_data[0]); // array_pop($excel_data); - $inceptionHeader = ['S.No', 'NAME OF EMP/DEP','EMP ID','EMP/DEP TYPE','RELATIONSHIP CODE','DOB','GENDER','PRE EXISTING AILMENTS','BASIC COVER SI','DATE OF COVERAGE','AGE','RELATIONSHIP','REMARKS','POLICY END DATE','NO OF DAYS','TPA ID','UHID','PREMIUM','PRO RATA PREMIUM','GST','TOTAL AMOUNT']; + $inceptionHeader = [ + 'S.No', + 'NAME OF EMP/DEP', + 'EMP ID', + // 'EMP/DEP TYPE', + // 'RELATIONSHIP CODE', + 'DOB', + 'GENDER', + 'PRE EXISTING AILMENTS', + 'BASIC COVER SI', + 'DATE OF COVERAGE', + 'AGE', + 'RELATIONSHIP', + 'REMARKS', + 'POLICY END DATE', + 'NO OF DAYS', + 'TPA ID', + 'UHID', + // 'PREMIUM', + 'PRO RATA PREMIUM', + 'GST', + 'TOTAL AMOUNT' + ]; foreach ($inceptionHeader as $key => $value) { if($excel_header[$key] != $value){ @@ -1427,14 +1449,14 @@ class EmpDataServiceController extends BaseController } if ($insurer_or_tpa == 'tpa') { - if ($excel_data[$key][15] === null) { + if ($excel_data[$key][13] === null) { $missing_id[$key][] = [ 'row' => $key, 'column' => 15, ]; } } else if ($insurer_or_tpa == 'insurer') { - if ($excel_data[$key][16] === null) { + if ($excel_data[$key][14] === null) { $missing_id[$key][] = [ 'row' => $key, 'column' => 16, @@ -1461,115 +1483,115 @@ class EmpDataServiceController extends BaseController ]; } - if ($emp_value['emp_dob'] != $excel_data[$key][5]) { + if ($emp_value['emp_dob'] != $excel_data[$key][3]) { + $errors[$key][] = [ + 'row' => $key, + 'column' => 3, + 'db_data' => $emp_value['emp_dob'], + 'excel_data' => $excel_data[$key][3] + ]; + } + + if ($emp_value['emp_gender'] != $excel_data[$key][4]) { + $errors[$key][] = [ + 'row' => $key, + 'column' => 4, + 'db_data' => $emp_value['emp_gender'], + 'excel_data' => $excel_data[$key][4] + ]; + } + + if ($emp_value['pre_existing_alignments'] != $excel_data[$key][5]) { $errors[$key][] = [ 'row' => $key, 'column' => 5, - 'db_data' => $emp_value['emp_dob'], + 'db_data' => $emp_value['pre_existing_alignments'], 'excel_data' => $excel_data[$key][5] ]; } - if ($emp_value['emp_gender'] != $excel_data[$key][6]) { + if ($emp_value['basic_cover_si'] != $excel_data[$key][6]) { $errors[$key][] = [ 'row' => $key, 'column' => 6, - 'db_data' => $emp_value['emp_gender'], + 'db_data' => $emp_value['basic_cover_si'], 'excel_data' => $excel_data[$key][6] ]; } - if ($emp_value['pre_existing_alignments'] != $excel_data[$key][7]) { + if ($emp_value['emp_relationship'] != $excel_data[$key][9]) { $errors[$key][] = [ 'row' => $key, - 'column' => 7, - 'db_data' => $emp_value['pre_existing_alignments'], - 'excel_data' => $excel_data[$key][7] + 'column' => 9, + 'db_data' => $emp_value['emp_relationship'], + 'excel_data' => $excel_data[$key][9] ]; } - if ($emp_value['basic_cover_si'] != $excel_data[$key][8]) { - $errors[$key][] = [ - 'row' => $key, - 'column' => 8, - 'db_data' => $emp_value['basic_cover_si'], - 'excel_data' => $excel_data[$key][8] - ]; - } - - if ($emp_value['emp_relationship'] != $excel_data[$key][11]) { + if ($emp_value['policy_end_date'] != $excel_data[$key][11]) { $errors[$key][] = [ 'row' => $key, 'column' => 11, - 'db_data' => $emp_value['emp_relationship'], + 'db_data' => $emp_value['policy_end_date'], 'excel_data' => $excel_data[$key][11] ]; } - if ($emp_value['policy_end_date'] != $excel_data[$key][13]) { + if ($emp_value['no_of_days'] != $excel_data[$key][12]) { $errors[$key][] = [ 'row' => $key, - 'column' => 13, - 'db_data' => $emp_value['policy_end_date'], - 'excel_data' => $excel_data[$key][13] - ]; - } - - if ($emp_value['no_of_days'] != $excel_data[$key][14]) { - $errors[$key][] = [ - 'row' => $key, - 'column' => 14, + 'column' => 12, 'db_data' => $emp_value['no_of_days'], - 'excel_data' => $excel_data[$key][14] + 'excel_data' => $excel_data[$key][12] ]; } - if ($emp_value['premium'] != $excel_data[$key][17]) { - $errors[$key][] = [ - 'row' => $key, - 'column' => 17, - 'db_data' => $emp_value['premium'], - 'excel_data' => $excel_data[$key][17] - ]; - } + // if ($emp_value['premium'] != $excel_data[$key][17]) { + // $errors[$key][] = [ + // 'row' => $key, + // 'column' => 17, + // 'db_data' => $emp_value['premium'], + // 'excel_data' => $excel_data[$key][17] + // ]; + // } - if ($emp_value['pro_rata_premium'] != $excel_data[$key][18]) { + if ($emp_value['pro_rata_premium'] != $excel_data[$key][15]) { $errors[$key][] = [ 'row' => $key, - 'column' => 18, + 'column' => 15, 'db_data' => $emp_value['pro_rata_premium'], - 'excel_data' => $excel_data[$key][18] + 'excel_data' => $excel_data[$key][15] ]; } - if ($emp_value['gst'] != $excel_data[$key][19]) { + if ($emp_value['gst'] != $excel_data[$key][16]) { $errors[$key][] = [ 'row' => $key, - 'column' => 19, + 'column' => 16, 'db_data' => $emp_value['gst'], - 'excel_data' => $excel_data[$key][19] + 'excel_data' => $excel_data[$key][16] ]; } if ($insurer_or_tpa == 'tpa') { - if ($emp_value['uhid'] != $excel_data[$key][16]) { + if ($emp_value['uhid'] != $excel_data[$key][14]) { $errors[$key][] = [ 'row' => $key, - 'column' => 16, + 'column' => 14, 'db_data' => $emp_value['uhid'], - 'excel_data' => $excel_data[$key][16] + 'excel_data' => $excel_data[$key][14] ]; } } else if ($insurer_or_tpa == 'insurer') { - if ($emp_value['tpa_id'] != $excel_data[$key][15]) { + if ($emp_value['tpa_id'] != $excel_data[$key][13]) { $errors[$key][] = [ 'row' => $key, - 'column' => 15, + 'column' => 13, 'db_data' => $emp_value['tpa_id'], - 'excel_data' => $excel_data[$key][15] + 'excel_data' => $excel_data[$key][13] ]; } } @@ -1735,9 +1757,9 @@ class EmpDataServiceController extends BaseController $name = $value[1]; $emp_code = $value[2]; - $tpa_id[] = $value[15]; - $uhid[] = $value[16]; - $amount = $value[20]; + $tpa_id[] = $value[13]; + $uhid[] = $value[14]; + $amount = $value[17]; if(!empty($name) && !empty($emp_code)){ @@ -1767,7 +1789,7 @@ class EmpDataServiceController extends BaseController $result = $query->get()->getRowArray(); if (isset($result['id']) && $result['id'] !== null) { $emp_policy_ids[] = $result['id']; //for cash deposite - $emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[15], 'uhid' => $value[16]); + $emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[13], 'uhid' => $value[14]); } } @@ -3954,22 +3976,75 @@ class EmpDataServiceController extends BaseController // print_r($arrayData); if (!empty($arrayData)) { + // dd($arrayData); + // echo '
';
             // print_r($arrayData); die;
 
             $client_branch_data = $this->clientBranchModel->where('id', $arrayData['client_branch_id'])->first();
             $units = json_decode($client_branch_data['units']);
 
+            // dd($client_branch_data, $units);
+
+            $get_insurer_id_from_client_policy = db_connect()->table('client_policy')
+                ->select('insurer_id')
+                ->where('id', $arrayData['client_policy_id'])
+                ->get()
+                ->getRowArray();
+
+            // dd($get_insurer_id_from_client_policy);
+
+            $add_one_day = 0;
+
+            if (!empty($get_insurer_id_from_client_policy)) {
+
+                $get_the_insurer_add_one_for_delete = db_connect()
+                    ->table('insurers')
+                    ->select('deletion_add_day')
+                    ->where('id', $get_insurer_id_from_client_policy['insurer_id'])
+                    ->get()
+                    ->getRowArray();
+
+                // dd($get_the_insurer_add_one_for_delete, $get_the_insurer_add_one_for_delete['deletion_add_day']);
+
+                if (!empty($get_the_insurer_add_one_for_delete) && $get_the_insurer_add_one_for_delete['deletion_add_day'] == 1) {
+                    $add_one_day = 1;
+                }
+            }
+
+            // dd($add_one_day);
+
             foreach($units as $unit) {
 
+                // $amount = $this->employeePolicyModel->query("
+                //     SELECT SUM(rata_premimum + gst) AS total_sum
+                //         FROM employee_polices
+                //         JOIN employees ON employees.id = employee_polices.employee_id
+                //         WHERE employees.unit = '$unit'
+                //         AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+                //     ")->getRow();
+
                 $amount = $this->employeePolicyModel->query("
-                    SELECT SUM(rata_premimum + gst) AS total_sum
-                        FROM employee_polices
-                        JOIN employees ON employees.id = employee_polices.employee_id
-                        WHERE employees.unit = '$unit'
-                        AND employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
-                    ")->getRow();
-                
+                    SELECT 
+                        SUM(ROUND(
+                            ((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, emp_endorsement.new_value) + '$add_one_day')) / 365) + 
+                            (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, emp_endorsement.new_value) + '$add_one_day')) / 365) * 0.18), 
+                            2
+                        )) AS total_sum
+                    FROM 
+                        employee_polices
+                    JOIN 
+                        employees ON employees.id = employee_polices.employee_id
+                    JOIN 
+                        emp_endorsement ON emp_endorsement.pk = employee_polices.id
+                    WHERE 
+                        employee_polices.id IN (" . implode(',', $arrayData['employeeIds']) . ")
+                        AND emp_endorsement.pk IN (" . implode(',', $arrayData['employeeIds']) . ")
+                        AND emp_endorsement.field_name = 'date_of_exit'
+                ")->getRow();
+
+                //  dd(db_connect()->getLastQuery(), $amount);
+
                 if($amount){
 
                     $insurer_id = $this->clientPolicyModel->where('id', $arrayData['client_policy_id'])->first();
@@ -3994,6 +4069,7 @@ class EmpDataServiceController extends BaseController
                     $response = DepositHelper::saveDeposit($data, $arrayData['user_id']);
                 }
             }
+
             $msg = "Deletion Cash Deposite Updated Successfully -- ";
             return [$msg];
             // print_r($response);
@@ -4233,136 +4309,103 @@ class EmpDataServiceController extends BaseController
 
     public function sendMailForDownloadingECard(array $ids, $single_mail = null)
     {
-        
-        $this->myLogger->logme('error', 'sendMailForDownloadingECard - function called');
-        if (count($ids) > 0) {
-
-            $temp_id = $ids[0];
-
-            $get_client_info_for_notification = $this->employeePolicyModel
-                ->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
-                ->join('employees', 'employees.id = employee_polices.employee_id')
-                ->where('employees.emp_status', 'active')
-                ->where('employees.is_active', '1')
-                ->where('employee_polices.status', 'active')
-                ->where('employee_polices.is_active', '1')
-                ->where('employee_polices.id', $ids[0])->first();
-
-            $client_data = $this->clientModel->where('id', $get_client_info_for_notification['client_id'])->first();
-            $notification = $this->notificationModel->where('client_id', $get_client_info_for_notification['client_id'])->where('template_name', 'member_ecard_mail')->first();
-
-            if ($notification != null && !empty($notification) && $notification['enabled'] == 1) {
-
-                try {
-
-                    $this->myLogger->logme('error', 'sendMailForDownloadingECard - inside try');
-                    $count = 0;
-                    $counts = 0;
-
-                    foreach ($ids as $key => $id) {
-
-                        $get_emp_email_and_other_details = $this->employeePolicyModel
-                            ->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate,employees.client_id as client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
-                            ->join('employees', 'employees.id = employee_polices.employee_id')
-                            ->where('employees.emp_status', 'active')
-                            ->where('employees.is_active', '1')
-                            ->where('employee_polices.status', 'active')
-                            ->where('employee_polices.is_active', '1')
-                            ->where('employee_polices.id', $id)->first();
-
-                        $this->myLogger->logme('error', 'sendMailForDownloadingECard - emp_policy_id : {id}', ['id' => $id]);
-
-                        if ($get_emp_email_and_other_details != null && !empty($get_emp_email_and_other_details)) {
-
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function inside if condition ',);
-
-                            $rand_string =  $get_emp_email_and_other_details['rand_string'];
-                            $tpa_id =  $get_emp_email_and_other_details['tpa_id'];
-
-                            $params['rand_string'] = $rand_string;
-                            $params['tpa_id'] = $tpa_id;
-                            $params['notification'] = $notification;
-                            $params['client_data'] = $client_data;
-                            $params['notification'] = $notification;
-                            $params['notification'] = $notification;
-                            $params['get_emp_email_and_other_details'] = $get_emp_email_and_other_details;
-                            // $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
-
-                            if (isset($get_emp_email_and_other_details['email_corporate']) && !empty($get_emp_email_and_other_details['email_corporate']) && $get_emp_email_and_other_details['relationship'] == 'Self') {
-                                $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
-                                // print_r($wholeData);die;
-                                $count++;
-                            }
-
-                            $counts++;
-
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - counts : {data}', ['data' => $counts]);
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - count : {data}', ['data' => $count]);
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - whole count : {data}', ['data' => count($wholeData)]);
-
-                            if ($count == 20 || $counts == count($ids) - 1) {
-
-                                $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
-
-                                if(count($wholeData) > 0){
-
-                                    $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job to bulk mail',);
-
-                                    $job_details  = new Jobs();
-                                    $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
-                                    $wholeData = [];
-                                    $count = 0;
-
-                                }
-                            }else{
-
-                                // for view member individual employee send self and self family ecard 
-                                if($single_mail){
-
-                                    if(count($wholeData) > 0){
-
-                                        $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job for single mail to bulk mail function',);
+        $this->myLogger->logme('info', 'sendMailForDownloadingECard - Function called');
     
-                                        $mail_send_return =  MailHelper::send_email($wholeData[0]);
-                                        $this->myLogger->logme("info", $mail_send_return);
-                                        return $mail_send_return;
-
-                                        // $job_details  = new Jobs();
-                                        // $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
-                                        // $wholeData = [];
-                                        // $count = 0;
-    
-                                    }
-
-                                }
-
-                            }
-
-                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function end ',);
-                        }
-                    }
-                    return true; // Email(s) sent successfully
-
-                } catch (\Exception $e) {
-
-                    // Log the error
-                    $this->myLogger->logme('error', 'sendMailForDownloadingECard : inside catch');
-                    $this->myLogger->logme('error', 'Error occurred while sending email: ' . $e->getMessage());
-                    return false; // Email(s) sending failed
-                }
-            } else {
-
-                $this->myLogger->logme('error', 'sendMailForDownloadingECard - the client notification setup not created or not enabled the E-Card Notification');
-                return false;
-            }
-
-        } else {
-
+        if (empty($ids)) {
             $this->myLogger->logme('error', 'sendMailForDownloadingECard - employee_policy_ids are empty');
             return false;
         }
+    
+        $temp_id = $ids[0];
+    
+        $get_client_info = $this->employeePolicyModel
+            ->select('employee_polices.client_policy_id, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
+            ->join('employees', 'employees.id = employee_polices.employee_id')
+            ->where('employees.emp_status', 'active')
+            ->where('employees.is_active', '1')
+            ->where('employee_polices.status', 'active')
+            ->where('employee_polices.is_active', '1')
+            ->where('employee_polices.id', $temp_id)
+            ->first();
+    
+        if (!$get_client_info) {
+            $this->myLogger->logme('error', 'sendMailForDownloadingECard - No client information found for the first ID');
+            return false;
+        }
+    
+        $client_data = $this->clientModel->where('id', $get_client_info['client_id'])->first();
+        $notification = $this->notificationModel
+            ->where('client_id', $get_client_info['client_id'])
+            ->where('template_name', 'member_ecard_mail')
+            ->first();
+    
+        if (empty($notification) || $notification['enabled'] != 1) {
+            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Notification setup not enabled or missing for E-Card Notification');
+            return false;
+        }
+    
+        try {
+            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Inside try block');
+    
+            $count = 0;
+            $processedCount = 0;
+            $wholeData = [];
+    
+            foreach ($ids as $id) {
+                $emp_details = $this->employeePolicyModel
+                    ->select('employee_polices.client_policy_id, employees.relationship, employees.emp_code, employees.email_corporate, employees.client_id, employees.name, employee_polices.rand_string, employee_polices.tpa_id')
+                    ->join('employees', 'employees.id = employee_polices.employee_id')
+                    ->where('employees.emp_status', 'active')
+                    ->where('employees.is_active', '1')
+                    ->where('employee_polices.status', 'active')
+                    ->where('employee_polices.is_active', '1')
+                    ->where('employee_polices.id', $id)
+                    ->first();
+    
+                if ($emp_details) {
+                    $this->myLogger->logme('error', 'sendMailForDownloadingECard - Processing employee_policy_id: {id}', ['id' => $id]);
+    
+                    if (!empty($emp_details['email_corporate']) && $emp_details['relationship'] === 'Self') {
+                        $params = [
+                            'rand_string' => $emp_details['rand_string'],
+                            'tpa_id' => $emp_details['tpa_id'],
+                            'notification' => $notification,
+                            'client_data' => $client_data,
+                            'get_emp_email_and_other_details' => $emp_details,
+                        ];
+                        $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
+                        $count++;
+                    }
+                    $processedCount++;
+    
+                    // Send batch emails or handle single email
+                    if ($count == 20 || $processedCount == count($ids)) {
+                        if (!empty($wholeData)) {
+                            if ($single_mail == 1) {
+                                $this->myLogger->logme('error', 'sendMailForDownloadingECard - Sending single mail');
+                                $mail_result = MailHelper::send_email($wholeData[0]);
+                                $this->myLogger->logme('info', 'sendMailForDownloadingECard - Single mail result: {result}', ['result' => $mail_result]);
+                                return $mail_result;
+                            } else {
+                                $this->myLogger->logme('error', 'sendMailForDownloadingECard - Creating a job for bulk mail');
+                                Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
+                                $wholeData = [];
+                                $count = 0;
+                            }
+                        }
+                    }
+                }
+            }
+    
+            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Email processing completed');
+            return true;
+    
+        } catch (\Exception $e) {
+            $this->myLogger->logme('error', 'sendMailForDownloadingECard - Exception occurred: {message}', ['message' => $e->getMessage()]);
+            return false;
+        }
     }
+    
 
     public function readExcelFileToArray($path)
     {
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 810798af..b79bde7d 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -212,6 +212,7 @@ class EmployeeController extends AdminController
 
             //validate uploaded file
             $filename = '';
+            $fileSize = '';
             $validated = $this->validate([
                 'emplist' => [
                     'uploaded[emplist]',
@@ -231,6 +232,8 @@ class EmployeeController extends AdminController
                     $is_moved = $avatar->move(WRITEPATH . 'uploads/excel/');
                     if ($is_moved) {
                         $filename = $avatar->getName();
+                        $fileSize = $avatar->getSize(); // File size in bytes
+                        $fileSize = $fileSize / (1024 * 1024); // Convert to MB
                         // Handle successful upload, e.g., log success or further processing
                         $this->myLogger->logme("error", 'File move successful');
                         
@@ -258,12 +261,21 @@ class EmployeeController extends AdminController
             $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]);
 
             //start validation process
-
-            $empServiceController = new EmployeeServiceController();
-            $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
-            //endof validation process
-            if (isset($result['error_summary']) && count($result['error_summary'])) {
-                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200);
+            if($fileSize < 1) // if file size less than 1
+            {
+                $empServiceController = new EmployeeServiceController();
+                $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
+                $this->myLogger->logme("error", '{file_id} is less than 1MB, validating on the fly', ['file_id' => $file_id]);
+                //endof validation process
+                if (isset($result['error_summary']) && count($result['error_summary'])) {
+                    return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200);
+                }
+            }
+            else //if file size greater than 1 add the file as job
+            {
+                $job_details  = new Jobs();
+                $r = Jobs::addJob(['job_name' => 'excelFileFormatValidation','payload' => ['file_id' => $file_id]]);
+                $this->myLogger->logme("error", '{file_id} is greather than 1MB, validating with job queue', ['file_id' => $file_id]);
             }
 
             return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
@@ -825,18 +837,18 @@ class EmployeeController extends AdminController
     // client_policy_id pull draft and enrolled status employees and proceed to calculatin and make entry in DB
     public function initiateManualEmployeesOnboardProcess($client_policy_id)
     {
-        $client_data = $this->clientPolicyModel->select('clients.client_name as client_name, policies.name as policy_name,client_branch_id')
+        $client_data = $this->clientPolicyModel->select('clients.client_name as client_name,client_branch_id')
             ->join('clients', 'clients.id = client_policy.client_id')
-            ->join('policies', 'policies.id = client_policy.policy_id')
+            // ->join('policies', 'policies.id = client_policy.policy_id')
             ->where('client_policy.id', $client_policy_id)
             ->first();
-
+        // dd($client_data);
         $empServiceController = new EmployeeServiceController();
         $res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => $client_policy_id,'client_branch_id' => $client_data['client_branch_id']]);
         // dd($res);
 
         $count = ($res);
-        $message =  $count . ' Employees are Initiate Onboard Process againts Client ' . $client_data['client_name'] . ' and the Policy is ' . $client_data['policy_name'];
+        $message =  $count . ' Employees are Initiate Onboard Process againts Client ' . $client_data['client_name'] . ' and the Policy is ' .$client_policy_id;
         session()->setFlashdata('success1',  $message);
         return redirect()->to(base_url('/employee/upload'));
     }
@@ -1062,6 +1074,7 @@ class EmployeeController extends AdminController
         
             // Step 1: Attempt to fetch employee code and client policy ID
             $this->myLogger->logme('error', 'Fetching employee code and client policy ID.');
+
             $get_emp_code_and_client_policy_id = $this->employeePolicyModel
                 ->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id')
                 ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
@@ -1074,6 +1087,10 @@ class EmployeeController extends AdminController
                 ->where('employee_polices.is_active', '1')
                 ->where('employee_polices.rand_string', $rand_string)
                 ->first();
+
+            // dd($this->employeePolicyModel->getLastQuery());
+
+            // dd($rand_string, $get_emp_code_and_client_policy_id);
         
             if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") {
                 $this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string);
@@ -1128,7 +1145,7 @@ class EmployeeController extends AdminController
                     '{SELF_NAME}' => $value['self'] ?? $value['name'],
                     '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
                     '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
-                    '{POLICY_NO}' => date('d-M-Y', strtotime($value['policy_start_date'])),
+                    '{POLICY_NO}' => $value['policy_no'],
                     '{INSURER_NAME}' => strtoupper($value['insurer_name']),
                     '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
                     '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
@@ -1210,7 +1227,8 @@ class EmployeeController extends AdminController
         // $file['action'] = 'si_enhancement';
         // $result = [];
         // !dd($file);
-        if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment') {
+        if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') {
+
 
             if($file['action'] == 'enrollment'){
                 $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']);
@@ -1430,9 +1448,9 @@ class EmployeeController extends AdminController
         //     array_pop($excel_data);
         // }
 
-        if($event_type == 'deletion'){
-            array_pop($excel_data);
-        }
+        // if($event_type == 'deletion'){
+        //     array_pop($excel_data);
+        // }
 
         $finalArray = [];
         foreach ($error_data as $key => $values) {
@@ -1773,17 +1791,151 @@ class EmployeeController extends AdminController
 
     public function checkDeletionGetDataFunction()
     {   
-        $batch_data = [
-            'client_id' => 77,
-            'client_policy_id' => 203,
-            'client_branch_id' => 53,
-            'insurer_or_tpa' => 'tpa',
-        ];
+        // $batch_data = [
+        //     'client_id' => 77,
+        //     'client_policy_id' => 203,
+        //     'client_branch_id' => 53,
+        //     'insurer_or_tpa' => 'tpa',
+        // ];
 
-        $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
+        // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
+
+        // print_rr($result); die;
+
+        //-------------------------------------------------------------------------------------------------------------
+    
+        // $ids = [
+        //     'employeeIds' => [20252, 20258, 20277, 20282, 20196, 20237, 20314, 20325, 20356],
+        //     'client_id' => 17,
+        //     'client_policy_id' => 30,
+        //     'client_branch_id' => 18,
+        //     'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+        //     'endorsement_no' => $endorsement_id ?? null,
+        //     'count' => 9,
+        //     // 'event_name' => $file['event_type'],
+        //     // 'policy_name' => $policy_name['policy_name'],
+        //     // 'user_id' => $user_id,
+        // ];
+        // $empDataServiceController = new EmpDataServiceController();
+        // $result = $empDataServiceController->cashDepositCalculationForDeletion($ids);
 
-        print_rr($result); die;
     }
     
+    // ---------- DOWNLOAD IMPORT BATCH FILE AND SAMPLE FILE ------------------------------------------------------------------------------------------------
+
+    public function downloadSampleImportExcelFile($actionType = null)
+    {
+        // $actionType = $this->request->getGet();
+        $filePath = '';
+        // Path to your file
+        if ($actionType == 'inception') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx';
+        } else if ($actionType == 'correction') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_correction.xlsx';
+        } else if ($actionType == 'si_enhancement') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_SI_Enhancement.xlsx';
+        } else if ($actionType == 'dependent_addition') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Dependent_Addition.xlsx';
+        } else if ($actionType == 'addition') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Addition.xlsx';
+        } else if ($actionType == 'deletion') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Deletion.xlsx';
+        }else if ($actionType == 'missed_inception') {
+            $filePath = ROOTPATH . 'public/sample_import_excel/sample_import_Inception.xlsx';
+        }
+
+        // Check if the file exists
+        if (file_exists($filePath)) {
+
+            // Set the appropriate MIME type
+            $mimeType = mime_content_type($filePath);
+
+            // Send the file to the client for download
+            return $this->response->download($filePath, null, $mimeType);
+        } else {
+            // File not found, show an error message or redirect
+            echo view('errors/html/production');
+        }
+    }
+
+    public function download_import_file($file_id)
+    {
+        // $actionType = $this->request->getGet();
+        $file_data = $this->batchFileModel->where('id', $file_id)->first();
+        $fileName = $file_data['file_name'];
+
+        $filePath = WRITEPATH . '/uploads/import_excel/' . $fileName;
+
+        try {
+
+            // Check if the file exists
+            if (file_exists($filePath)) {
+                // Set the appropriate MIME type
+                $mimeType = mime_content_type($filePath);
+
+                // Send the file to the client for download
+                return $this->response->download($filePath, null, $mimeType);
+            } else {
+
+                $data['message'] = 'The Physical File Not Found';
+                echo view('errors/404', $data);
+            }
+        } catch (\Exception $e) {
+            // Handle any exceptions
+            $errorMessage = $e->getMessage();
+            $this->myLogger->logme('error', $errorMessage);
+            // You can return an error response here
+            echo $errorMessage;
+        }
+    }
+
+    //--------- LOG FILE VIEW AND DOWNLOAD ---------------------------------------------------------------------------------------------
+
+    public function listLogs()
+    {
+        $logPath = WRITEPATH . 'logs/';
+        $logs = [];
+
+        // Check if the log directory exists
+        if (is_dir($logPath)) {
+            $files = array_diff(scandir($logPath), ['.', '..']); // Exclude '.' and '..'
+
+            foreach ($files as $file) {
+                if (is_file($logPath . $file)) {
+                    $logs[] = $file; // Add log files to the list
+                }
+            }
+        }
+
+        // Pass log files to the view
+        return view('log_view', ['logs' => $logs]);
+    }
+
+    public function downloadLog($fileName)
+    {
+        $logPath = WRITEPATH . 'logs/' . $fileName;
+
+        // Check if the requested file exists
+        if (file_exists($logPath)) {
+            return $this->response->download($logPath, null)->setFileName($fileName);
+        }
+
+        // Redirect back with an error if file doesn't exist
+        return redirect()->back()->with('error', 'Log file not found.');
+    }
+
+    public function viewLog($fileName)
+    {
+        $logPath = WRITEPATH . 'logs/' . $fileName;
+
+        if (file_exists($logPath)) {
+            $content = file_get_contents($logPath);
+
+            return view('log_content_view', ['fileName' => $fileName, 'content' => $content]);
+        }
+
+        return redirect()->back()->with('error', 'Log file not found.');
+    }
+
 
 }
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 0c43d7cd..0684f727 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -112,6 +112,12 @@ class EmployeeRestController extends AdminController
                                                 ->where('is_active', 1 )
                                                 ->where('relationship', $relationship)
                                                 ->first();
+                if (null !== $this->request->getGet('client_policy_id'))
+                {
+                  $date_coverage = $this->employeePolicyModel->where('employee_id',$employee['id'])->where('client_policy_id',$this->request->getGet('client_policy_id'))->get()->getRow()->date_coverage;
+                  $employee['date_coverage'] = $date_coverage;
+                }
+
                 $result = $employee;
                 $AccountManagerDetails =  $this->clientRMModel->select('client_rm.* , user_profiles.*')
                                                     ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left')
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index c4565c6c..2b6135aa 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1320,10 +1320,10 @@ class EmployeeServiceController extends AdminController
             $row[4] = change_date_format($row[4],'d-M-Y','Y-m-d');// date of exit from excel
             // Kint::dump($row[4]);
             // check if insurer configured with add one day for deletion
-            if($insurer['deletion_add_day'] == true)
-            {
-                $row[4] = (new \DateTime($row[4]))->modify('+1 day')->format('Y-m-d');
-            }
+            // if($insurer['deletion_add_day'] == true)
+            // {
+            //     $row[4] = (new \DateTime($row[4]))->modify('+1 day')->format('Y-m-d');
+            // }
             // dd($row[4]);
             //for emp table
             $this->empEndorsementModel->save(['pk' => (int)$data['emp_id'],'emp_code' => $data['emp_code'],'table_name' => 'employees','actions' => 'd','name' => $data['name'],'field_name' => 'emp_status','old_value' => $data['emp_status'],'new_value' => 'deactivate','created_by' => $file['created_by'],'remarks' => 'general deletion','group_key' => $group_key,'file_id' => $file['id'],'status' => 'pending']);
@@ -1355,6 +1355,7 @@ class EmployeeServiceController extends AdminController
                                                              ->where('emp_code',$employee['emp_code'])
                                                              ->where('name',$employee['name'])
                                                              ->where('field_name','emp_status')
+                                                             ->where('status !=','truncated')
                                                              ->findAll();
 
                     // dd($existing_endorsements);                                                             
@@ -1444,7 +1445,14 @@ class EmployeeServiceController extends AdminController
             $field_value = ($field_name == 'dob' ? change_date_format($row[4],'d-M-Y','Y-m-d') : $row[4] );
 
 
-            $employee = $this->employeeModel->where('emp_code', $row[1])->where('name',$row[2])->where('client_id',$file['client_id'])->where('client_branch_id',$file['client_branch_id'])->first();
+            $employee = $this->employeeModel
+                        ->where('emp_code', $row[1])
+                        ->where('name',$row[2])
+                        ->where('client_id',$file['client_id'])
+                        ->where('client_branch_id',$file['client_branch_id'])
+                        ->where('emp_status','active')
+                        ->where('is_active',1)
+                        ->first();
             $existing_endorsements = $this->empEndorsementModel->where('actions','c')
                                                      ->where('table_name','employees')
                                                      ->where('endorsement_id is null')
@@ -1959,7 +1967,8 @@ public function employeesEnrollmentInsert($params)
         $allowedHighestColumn = end($columns_to_check);
         $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']);
         // print_r($keys);die();
-
+         //get existing units in the current branch
+        $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $file['client_id'],client_branch_id: $file['client_branch_id']);
         //remove header
         unset($excel_data[0]);
         // dd($excel_data);
@@ -1975,6 +1984,11 @@ public function employeesEnrollmentInsert($params)
             // dd($key.'-'.count($excel_data));
             $value = [];
             $policy_data = [];
+            $temp_unit = '';
+            if(empty($row[12]))
+            {
+                $temp_unit = $existing_units[0];
+            }
            
             $value['emp_code'] = $row[1];
             $value['name'] = $row[2];
@@ -1986,7 +2000,7 @@ public function employeesEnrollmentInsert($params)
             $value['mobile'] = $row[8];
             $value['band'] = $row[10];
             $value['basic_pay'] = $row[11];
-            $value['unit'] = $row[12];
+            $value['unit'] = $temp_unit;
             $value['family_floater_key'] = null;
             $value['client_id'] = $file['client_id'];
             $value['client_branch_id'] = $file['client_branch_id'];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 9d2c246c..91c08094 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -5,6 +5,8 @@ namespace App\Controllers;
 use CodeIgniter\API\ResponseTrait;
 
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
 use App\Models\UserModel;
@@ -164,14 +166,27 @@ class LeadsController extends BaseController
     }
 
     private function prepareMultipleLeadData($data)
-    {
+    {   
+        // print_r($data); die;
         $processedData = [];
         foreach($data['policy_type_id'] as $index => $value){
 
-            // Separate the insurer and insurer branch
-            list($insurer_branch_id, $insurer_id) = explode('-',$data['insurer'][$index]);  
-            // Separate the tpa and tpa branch              
-            list($tpa_branch_id, $tpa_id) = explode('-',$data['tpa'][$index]);
+
+            // Separate the insurer and insurer branch, handle missing or invalid data
+            if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
+                list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
+            } else {
+                $insurer_branch_id = 0;
+                $insurer_id = 0;
+            }
+            // Separate the insurer and insurer branch, handle missing or invalid data
+            if (isset($data['tpa'][$index]) && strpos($data['tpa'][$index], '-') !== false) {
+                list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa'][$index]);
+            } else {
+                $tpa_branch_id = 0;
+                $tpa_id = 0;
+            }
+            
 
             // Separate the insurer and insurer branch, handle missing or invalid data
             if (isset($data['proposed_insurer'][$index]) && strpos($data['proposed_insurer'][$index], '-') !== false) {
@@ -337,16 +352,25 @@ class LeadsController extends BaseController
 
         $data['lead_id'] = $id;
         $lead_data = $this->leadsModel
-                ->select('policy_type.question_json')
+                ->select('leads.*, policy_type.question_json')
                 ->join('policy_type', 'leads.policy_type_id = policy_type.id')
                 ->where('leads.id', $id)
+                ->where('leads.is_active', 1)
                 ->first();
 
+        // dd($lead_data);
+
+        if($lead_data['lead_type'] == 2){
+            $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
+            $data['policy_terms'] = $client_policy_data['policy_terms'];
+        }
+
         $data['question_json'] = $lead_data['question_json'];
         $data['page_name'] = isset($data['rfq_data']['type']) && $data['rfq_data']['type'] == 2 ? 'QCR' : 'RFQ';
         $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+        $data['userList'] = $this->userModel->getUserListForRFQ();
+        $data['lead_data'] = $lead_data;
 
-        $data['lead_data'] = $this->leadsModel->where('leads.id', $id)->where('leads.is_active', 1)->first();
         // dd($data);
         $this->loadLayout('view_rfq.php', $data);
     }
@@ -401,12 +425,7 @@ class LeadsController extends BaseController
 
     //export main route function
     public function exportQCRandRFQ($lead_id, $type, $export_type){
-
-        if($export_type == 'mail'){
-            $this-> exportMailForQCRandRFQ($lead_id, $type);
-        }else{
-            $this-> exportExcelForQCRandRFQ($lead_id, $type);
-        }
+        $this-> exportExcelForQCRandRFQ($lead_id, $type);
     }
 
     //FOR EXCEL
@@ -435,53 +454,27 @@ class LeadsController extends BaseController
         }
     }
     
-    //FOR MAIL
-    public function exportMailForQCRandRFQ($lead_id, $type){
-
-        $filepath = $this->constructExcelToSaveTemp($lead_id, $type);
-
-        if ($filepath) {
-            return $this->respond(['status' => true, 'file_path' => $filepath, 'message' => 'Mail send successfully'], 200);
-        }
-
-        return $this->respond(['status' => false, 'file_path' => $filepath, 'message' => "Mail send failed"], 200);
-    }
-
     //Construct excel file and save the file to the folder and return file path
-    public function constructExcelToSaveTemp($lead_id, $type)
+    public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
     {
-        $rfq_data = $this->RFQModel
-            ->select('
-                    leads.client_name,
-                    leads.client_short_name,
-                    insurers.name as insurer_name,
-                    insurer_branch.branch_name as insurer_branch_name,
-                    tpa.name as tpa_name,
-                    tpa_branch.branch_name as tpa_branch_name,
-                    policy_type.policy_type,
-                    rfq.json
-            ')
-            ->join('leads', 'rfq.lead_id = leads.id')
-            ->join('policy_type', 'leads.policy_type_id = policy_type.id')
-            ->join('insurers', 'leads.insurer_id = insurers.id')
-            ->join('insurer_branch', 'leads.insurer_branch_id = insurer_branch.id')
-            ->join('tpa', 'leads.tpa_id = tpa.id')
-            ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id')
-            ->where('rfq.lead_id', $lead_id)
-            ->where('rfq.type', $type)
-            ->where('rfq.is_active', 1)
-            ->first();
+        $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
     
         $lead_data = [
             'Insured' => $rfq_data['client_name'],
             'Insurer' => $rfq_data['insurer_name'] . ' - ' . $rfq_data['insurer_branch_name'],
             'TPA' => $rfq_data['tpa_name'] . ' - ' . $rfq_data['tpa_branch_name'],
         ];
+        
+        $data = json_decode($rfq_data['json'], true);
+
+        if($type == 2){
+            $data = $this->convertJsonForQCR($data, 'stc');
+            if($propsal_and_insurer !== null){
+                list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
+                $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+            }
+        }
     
-        $jsonData = $rfq_data['json'];
-        $data = json_decode($jsonData, true);
-    
-        // Initialize PhpSpreadsheet
         $spreadsheet = new Spreadsheet();
         $sheet = $spreadsheet->getActiveSheet();
     
@@ -490,96 +483,173 @@ class LeadsController extends BaseController
         foreach ($lead_data as $key => $value) {
             $sheet->setCellValue("A{$rowNumber}", $key);
             $sheet->setCellValue("B{$rowNumber}", $value);
-
-            // Apply bold style to the key
-            $sheet->getStyle("A{$rowNumber}")->applyFromArray([
-                'font' => [
-                    'bold' => true,
-                ],
-            ]);
-
+            $sheet->getStyle("A{$rowNumber}")->applyFromArray(['font' => ['bold' => true]]);
             $rowNumber++;
         }
 
-        // Leave two blank rows
+        $leadRange = "A1:B" . (count($lead_data));
+        $sheet->getStyle($leadRange)->applyFromArray([
+            'borders' => [
+                'allBorders' => [
+                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+                    'color' => ['argb' => 'FF000000'], // Black color
+                ],
+            ],
+        ]);
+
+    
         $rowNumber += 2;
 
-        // Set headers and subheaders starting from current row
+        // Add headers and subheaders
         $headers = $data['table_data']['headers'];
         $subHeaderRow = $rowNumber + 1;
         $columnLetter = 'A';
-
-        // Set column width and apply word wrap to headers and subheaders
+        
         foreach ($headers as $header) {
-            if ($header['parentHeader'] === 'Item Key' || $header['parentHeader'] == 'Action') {
-                continue; // Skip "Item Key" and "Action" columns
+            if (in_array($header['parentHeader'], ['Item Key', 'Action'])) {
+                continue;
             }
-
+        
             if ($header['parentHeader'] === 'Sno') {
                 $header['parentHeader'] = 'S.No.';
             }
-
-            // Set the header cell value
-            $sheet->setCellValue("{$columnLetter}{$rowNumber}", $header['parentHeader']);
-            
-            // Set column width for header
-            $sheet->getColumnDimension($columnLetter)->setWidth(20); // Adjust width as needed
-            $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
-
-            // Apply bold style to the header
-            $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray([
-                'font' => [
-                    'bold' => true,
+        
+            $startColumn = $columnLetter; // Start of the current header range
+            $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
+        
+            // Set parent header value
+            $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+            $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
+                'font' => ['bold' => true],
+                'alignment' => [
+                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                 ],
             ]);
-            
-            // Add subheaders in the second row
+        
+            // Merge header cells if it spans multiple subheaders
+            if ($subHeaderCount > 1) {
+                $endColumn = chr(ord($startColumn) + $subHeaderCount - 1); // Calculate the end column
+                $sheet->mergeCells("{$startColumn}{$rowNumber}:{$endColumn}{$rowNumber}");
+            } else {
+                $endColumn = $startColumn; // No merge needed if only one subheader
+            }
+        
+            // Add subheaders
             foreach ($header['subHeaders'] as $subHeader) {
                 $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
-
-                // Enable word wrap for subheaders
-                $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->getAlignment()->setWrapText(true);
-
-                // Apply bold style to the subheader
                 $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
-                    'font' => [
-                        'bold' => true,
+                    'font' => ['bold' => true],
+                    'alignment' => [
+                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                     ],
                 ]);
-
-                $columnLetter++;
+                $columnLetter++; // Move to the next column for subheaders
             }
         }
+        
+        // Apply border to the header range
+        $headerRange = "A{$rowNumber}:" . chr(ord($columnLetter) - 1) . "{$subHeaderRow}";
+        $sheet->getStyle($headerRange)->applyFromArray([
+            'borders' => [
+                'allBorders' => [
+                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+                    'color' => ['argb' => 'FF000000'], // Black color
+                ],
+            ],
+        ]);
 
-        // Move to next row for data entries
-        $rowNumber = $subHeaderRow + 1;
+        // Increase row height for headers and subheaders
+        $sheet->getRowDimension($rowNumber)->setRowHeight(30); // Header row height
+        $sheet->getRowDimension($subHeaderRow)->setRowHeight(25); // Subheader row height
+        
+        $rowNumber = $subHeaderRow + 2;
+        $column_data = $data['table_data']['data'];
+        $serial_no = 1;
 
-        // Add data rows and enable word wrap for data cells
-        foreach ($data['table_data']['data'] as $dataRow) {
+        // Add table data rows
+        foreach ($column_data as $dataRow) {
             $columnLetter = 'A';
             foreach ($dataRow['data'] as $cellData) {
-                if ($cellData['parentth'] === 'Item Key' || $cellData['parentth'] == 'Action') {
-                    continue; // Skip "Item Key" data
+                if (in_array($cellData['parentth'], ['Item Key', 'Action'])) {
+                    continue;
                 }
-                $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['value']);
-                
-                // Enable word wrap for data cells
-                $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
-                
+
+                if ($cellData['parentth'] == 'Sno') {
+                    $sheet->setCellValue("{$columnLetter}{$rowNumber}", $serial_no);
+                } else {
+                    $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['value']);
+                }
+
                 $columnLetter++;
             }
             $rowNumber++;
+            $serial_no++;
         }
 
-        // Auto-size all columns after data is entered
+        $dataRange = "A" . ($subHeaderRow + 1) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+        $sheet->getStyle($dataRange)->applyFromArray([
+            'borders' => [
+                'allBorders' => [
+                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+                    'color' => ['argb' => 'FF000000'], // Black color
+                ],
+            ],
+        ]);
+        
+
+        if($type == 2){
+
+            $rowNumber += 2;
+        
+            // Add premium data
+            $premiumData = $data['premium_data']['data'];
+            $premium = ['Premium'];
+            $gst = ['GST'];
+            $total = ['Total'];
+        
+            foreach ($premiumData as $proposal => $insurers) {
+                foreach ($insurers as $insurer => $values) {
+                    $premium[] = $values['Premium'];
+                    $gst[] = $values['GST'];
+                    $total[] = $values['Total'];
+                }
+            }
+        
+            foreach ([$premium, $gst, $total] as $index => $rowData) {
+                $columnLetter = 'B';
+                foreach ($rowData as $key => $value) {
+                    $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value);
+                    if ($key === 0) {
+                        $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true,],]);
+                    }
+                    $columnLetter++;
+                }
+                $rowNumber++;
+            }
+
+            $premiumRange = "B" . ($rowNumber - 3) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1);
+            $sheet->getStyle($premiumRange)->applyFromArray([
+                'borders' => [
+                    'allBorders' => [
+                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
+                        'color' => ['argb' => 'FF000000'], // Black color
+                    ],
+                ],
+            ]);
+
+        }
+        
+        // Auto-size columns
         foreach ($sheet->getColumnIterator() as $column) {
             $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
         }
-
-        // Set filename based on type
+    
+        // Set filename
         $string = ($type == 2) ? 'QCR' : 'RFQ';
-        $filename = $string . '_' . $rfq_data['client_short_name'] . '_' . $rfq_data['policy_type'] . '_' . date('Ymdhis') . '.xlsx';
-        
+        $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx';
+    
         // Save to temporary location
         $uploadFilePath = WRITEPATH . 'tmp/' . $filename;
         $writer = new Xlsx($spreadsheet);
@@ -588,98 +658,150 @@ class LeadsController extends BaseController
         return [
             'filePath' => $uploadFilePath,
             'fileName' => $filename,
-        ]; // Return file path and file name
+        ];
     }
     
     //this funciton for send mail to insurer and client with either RFQ/QCR
     public function sendMailWithAttachement()
     {
-         helper('excel_util_helper');
-         helper('MailHelper');
+        helper('excel_util_helper');
+        helper('MailHelper');
 
-         $params = $this->request->getGet();
-         // dd($params);
-         $lead_id = $params['lead_id'];
-         $file_type  = $params['file_type']; //rfq or qcr
-         $recipient_type = $params['recipient_type'];//insurer or client  
-         $recipient_mail = $params['recipient_mail'];// - only primary key of contacts
-         $recipient_mail = json_decode($params['recipient_mail'], true);;// - only primary key of contacts
-        //  $cc = 'velz1990@gmail.com,vitvelz@gmail.com';
-        $cc = "";
-         
-         $result_data = []; 
-         // dd($recipient_mail);
-         if($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0))
-         {
-            return $this->respond(['status' => 'failed','code' => 400,'data' => '','messgae' => 'Recipient mail not found ! ' ], 200);
-         }
-         // dd();
-         //gather lead info
-         $lead_data = $this->leadsModel
-                ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email')
-                ->join('policy_type','leads.policy_type_id = policy_type.id')
-                ->join('user_profiles','leads.created_by = user_profiles.id')
-                ->where('leads.id', $lead_id)
-                ->first();
-         if( $recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null))
-         {
-            return $this->respond(['status' => 'failed','code' => 400,'data' => '','messgae' => 'Recipient mail not found ! ' ], 200);
-         }
-         // dd($lead_data);
-         $reply_to = $lead_data['created_person_email'];
-         //get file path to attach
-         $file_info = $this->constructExcelToSaveTemp($lead_id, ( $file_type == 'rfq' ? 1 : 2) );
-         // $file_path = WRITEPATH."uploads/excel/sample/correction.xls";
-         // $file_name = $file_type.'.xlsx';
-         // !dd($file_info);
-         $file_path = $file_info['filePath'];
-         $file_name = $file_info['fileName'];
-         $attachments = [['fileName' => $file_name,'filePath' => $file_path]];
-         
-         //get recipient address
-         if($recipient_type == 'insurer')
-         {
-                $recipient_data = $this->levelContactModel
-                                ->where(['contact_type' => $recipient_type, 'is_active' => 1])
-                                ->whereIn('id', $recipient_mail)
-                                ->findAll();
-         }
-         else
-         {
-            $recipient_data = [['name' => $lead_data['contact_person_name'],'email' => $lead_data['contact_person_email']] ];
-         }
-         // !dd($recipient_data);
+        $params = $this->request->getGet();
+        // print_r($params); die;
+        $lead_id = $params['lead_id'];
+        $file_type  = $params['file_type']; //rfq or qcr
+        $recipient_type = $params['recipient_type']; //insurer or client or internal or placement  
+        $recipient_mail = $params['recipient_mail']; // - only primary key of contacts
+        $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts
+        $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null;
 
-            $subject = $file_type == 'rfq' ? 'Request for Quotation from '. $lead_data['client_name'] . ' for '.$lead_data['policy_type'] : 'Quotation Comparison Report for ' .$lead_data['policy_type'];
-            $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; + $result_data = []; + // dd($recipient_mail); + if ($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0)) { + return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); + } + // dd(); + //gather lead info + $lead_data = $this->leadsModel + ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') + ->join('policy_type', 'leads.policy_type_id = policy_type.id') + ->join('user_profiles', 'leads.created_by = user_profiles.id') + ->where('leads.id', $lead_id) + ->first(); + + $cc_mails = []; + + //get CC Mails + if($recipient_type == 'internal' || $recipient_type == 'placement'){ + + $cc_data = isset($params['cc']) ? $params['cc'] : ""; + $param_cc_mail = json_decode($cc_data, true); + if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) { + // Fetch user data where ID is in the param_cc_mail array + $userData = $this->userModel + ->where('is_active', 1) + ->whereIn('id', $param_cc_mail) + ->findAll(); + + // print_r($userData); die; + + // Extract emails from the fetched user data + $cc_mails = array_column($userData, 'email'); + + // print_r(json_encode($cc_mails)); die; + // If no emails were found, return an error response + if (empty($cc_mails)) { + return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'No valid CC mail addresses found!'], 200); + } + + } else { + // Handle case where param_cc_mail is not valid + return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); + } + } - foreach($recipient_data as $recipient) - { + if ($recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null)) { + return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); + } + + // dd($lead_data); + $reply_to = $lead_data['created_person_email']; + + //get file path to attach + $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); + // $file_path = WRITEPATH."uploads/excel/sample/correction.xls"; + // $file_name = $file_type.'.xlsx'; + // !dd($file_info); + + $file_path = $file_info['filePath']; + $file_name = $file_info['fileName']; + $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; + + //get recipient address + if ($recipient_type == 'insurer' || $recipient_type == 'placement') { + + // print_r($recipient_mail); die; + + $recipient_data = $this->levelContactModel + ->where(['contact_type' => 'insurer', 'is_active' => 1]) + ->whereIn('id', $recipient_mail) + ->findAll(); + + // print_r($recipient_data); die; + + } else if($recipient_type == 'client') { + $recipient_data = [['name' => $lead_data['contact_person_name'], 'email' => $lead_data['contact_person_email']]]; + }else{ + $recipient_data = [['name' => "Team", 'email' => $params['to']]]; + } + // print_r($recipient_data); die; + + $subject = $file_type == 'rfq' ? 'Request for Quotation from ' . $lead_data['client_name'] . ' for ' . $lead_data['policy_type'] : 'Quotation Comparison Report for ' . $lead_data['policy_type']; + $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; + + if($recipient_data){ + foreach ($recipient_data as $recipient) { + $message = $original_message; $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'], $message); $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message); - $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'],'Y-m-d','d-m-Y'), $message); - $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'],$lead_data['policy_start_date'])->days, $message); - - // print_rr($message); - - $res = MailHelper::send_email(['mail' => $recipient['email'], 'subject' => $subject, 'message' => $message,'attachments' => $attachments,'reply_to' => $reply_to]); - // !dd($res); - - $result_data[] = ['mail' => $recipient['email'],'status' => $res]; - } - //delete attachment file - unlink($file_path); - return $this->respond(['status' => 'success','code' => 200,'data' => $result_data ], 200); + $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); + $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'], $lead_data['policy_start_date'])->days, $message); + // print_rr($message); + + $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc'=> $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to]); + // !dd($res); + $result_data[] = ['mail' => $recipient['email'], 'status' => $res]; + } + } + + if($recipient_type == 'placement'){ + + list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); + + $lead_update_data = [ + 'proposel_name' => $proposal_key, + 'insurer_name' => $insurer_key, + 'insurer' => $params['insurer_and_branch'], + ] ; + + $lead_update_data = json_encode($lead_update_data); + $this->leadsModel->where('id', $lead_id)->set('proposel_data', $lead_update_data)->update(); + } + + //delete attachment file + unlink($file_path); + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data], 200); } public function getLevelContects() { - $data = $this->levelContactModel->getContectForRFQ(); + $data = $this->levelContactModel->getContactForRFQ(); if($data){ return $this->respond(['status' => true, 'data' => $data], 200); @@ -689,11 +811,219 @@ class LeadsController extends BaseController } + public function getInsurerBranchContacts($insurer_and_branch_id) + { + if (strpos($insurer_and_branch_id, '-') === false) { + return $this->respond(['status' => false, 'message' => 'Invalid ID format'], 400); + } + + // Split the insurer_and_branch_id + list($insurerBranchId, $insurerId) = explode('-', $insurer_and_branch_id); + + $data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId); + + if (!empty($data)) { + return $this->respond(['status' => true, 'data' => $data], 200); + } else { + return $this->respond(['status' => false, 'data' => $data, 'message' => 'No contacts were found for the selected insurer.'], 200); + } + } + function transformProposelData($data, $proposel, $insurer){ + + // print_r($data['premium_data']['data']); die; + + $headerData = []; + + // Default headers: S. No and Particulars + $defaultHeaders = [ + [ + 'parentHeader' => 'Sno', + 'subHeaders' => ['-'] + ], + [ + 'parentHeader' => 'Particulars', + 'subHeaders' => ['-'] + ] + ]; + + // Add default headers to the result + $headerData = array_merge($headerData, $defaultHeaders); + + foreach ($data['table_data']['headers'] as $header) { + // Check if the parentHeader matches the target proposal + if ($header['parentHeader'] === $proposel) { + // Check if subHeaders contain the target insurer key + foreach ($header['subHeaders'] as $subHeader) { + if ($subHeader === $insurer) { + $headerData[] = [ + 'parentHeader' => $header['parentHeader'], + 'subHeaders' => [ + 'Quote Asked', // Default value + $subHeader // Matched insurer key + ] + ]; + break; + } + } + } + } + + $columnData = []; + + foreach ($data['table_data']['data'] as $entry) { + + $sno = $entry['SNO']; + $items = $entry['items']; + $dataEntry = $entry['data']; + + $result = [ + "SNO" => $sno, + "items" => $items, + "data" => [] + ]; + + foreach ($dataEntry as $item) { + + // Include Sno and Particulars by default + if (in_array($item['parentth'], ['Sno', 'Particulars'])) { + $result['data'][] = [ + "parentth" => $item['parentth'], + "subth" => $item['subth'], + "value" => $item['value'], + "input_value" => $item['input_value'] + ]; + } + + // Include Proposal with Quote Asked by default + if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") { + $result['data'][] = [ + "parentth" => $item['parentth'], + "subth" => $item['subth'], + "value" => $item['value'], + "input_value" => $item['input_value'] + ]; + } + + // Example of including matching specific proposals and insurers + if ($item['parentth'] === $proposel && $item['subth'] === $insurer) { + $result['data'][] = [ + "parentth" => $item['parentth'], + "subth" => $item['subth'], + "value" => $item['value'], + "input_value" => $item['input_value'] + ]; + } + } + + // Add to the final result + $columnData[] = $result; + } + + $premiumData = []; + + foreach ($data['premium_data']['data'] as $key => $value) { + if ($key === $proposel) { + $premiumData[$key]['Quote Asked'] = $value['Quote Asked']; + $premiumData[$key][$insurer] = $value[$insurer]; + } + } + + $data['table_data']['headers'] = $headerData; + $data['table_data']['data'] = $columnData; + $data['premium_data']['data'] = $premiumData; + + return $data; + + } + + function convertJsonForQCR($json, $type) + { + if ($json) { + // Deep copy of JSON + $first_json = json_decode(json_encode($json), true); + + // Column-wise Check: Remove headers and relevant data if qcr == 0 + foreach ($json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { + if ($proposalData['stc'] == 0 || $proposalData['stc'] === false) { + // Remove matching parentHeader in headers + foreach ($first_json['table_data']['headers'] as $index => $header) { + if ($header['parentHeader'] === $proposalKey) { + unset($first_json['table_data']['headers'][$index]); + } + } + + // Remove data entries with matching parentth + foreach ($first_json['table_data']['data'] as &$item) { + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($proposalKey) { + return $entry['parentth'] !== $proposalKey; + })); + } + + // Remove proposalKey from over_all_column_data + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]); + + if($type == 'stc'){ + // Remove proposalKey from premium_data + unset($first_json['premium_data']['data'][$proposalKey]); + } + } + + // Insurer Check: Remove subHeaders and relevant data for insurers with qcr == 0 + foreach ($proposalData['insurers'] as $insurerIndex => $insurer) { + if ($insurer['stc'] === 0 || $insurer['stc'] === false) { + foreach ($first_json['table_data']['headers'] as &$header) { + if (isset($header['subHeaders'])) { + $header['subHeaders'] = array_values(array_filter($header['subHeaders'], function ($sub) use ($insurer) { + return $sub !== $insurer['display_name']; + })); + } + } + + + foreach ($first_json['table_data']['data'] as &$item) { + $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { + return $entry['subth'] !== $insurer['display_name']; + })); + } + + // Remove insurer from proposal's insurers array + unset($first_json['proposal_data']['over_all_column_data'][$proposalKey]['insurers'][$insurerIndex]); + + if($type == 'stc'){ + unset($first_json['premium_data']['data'][$proposalKey][$insurer['display_name']]); + } + } + } + } + + // Row-wise Check: Remove rows if qcr == 0 for actions + foreach ($first_json['table_data']['data'] as $rowKey => $rowData) { + foreach ($rowData['data'] as $data) { + if ($data['parentth'] === "Action" && isset($data['input_value']['stc']) && $data['input_value']['stc'] == 0) { + unset($first_json['table_data']['data'][$rowKey]); + break; + } + } + } + + // Reindex arrays to maintain proper structure + $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); + $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); + $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { + $proposal['insurers'] = array_values($proposal['insurers']); + return $proposal; + }, $first_json['proposal_data']['over_all_column_data']); + + return $first_json; + } + + return null; + } + //----- Featch Lead data and insert Client ------------------------------------------------------------------------------------------- - public function featchLeadDataAndInsertClient($lead_id) { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 13305f50..1599bac2 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -173,7 +173,7 @@ class MasterController extends AdminController $editData['policy_type'] = $this->policyTypeModel->whereIn('id', [1,2,6,7])->findAll(); - $editData['events'] = ['inception' => 'Inception', 'addition' => 'Addition', 'dependent_addition' => 'Dependent Addition', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement', 'all' => 'All']; + $editData['events'] = ['inception' => 'Inception', 'missed_inception' => 'Missed Inception', 'addition' => 'Addition', 'dependent_addition' => 'Dependent Addition', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement', 'all' => 'All']; $editData['action'] = ['import' => 'Import', 'export' => 'Export']; $editData['db_column_name'] = [ @@ -1671,7 +1671,7 @@ class MasterController extends AdminController 'logo' => ROOTPATH . 'public/uploads/logo/', 'template_bg' => ROOTPATH . 'public/uploads/template_bg/', 'attachments' => WRITEPATH . 'uploads/attachments/', - + 'sample_import_excel' => ROOTPATH . 'public/sample_import_excel', ]; foreach ($folders as $folderName => $folderPath) { diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php index a65a5b31..0bc21c46 100755 --- a/app/Helpers/MailHelper.php +++ b/app/Helpers/MailHelper.php @@ -106,7 +106,9 @@ class MailHelper //check CC mail if (isset($params['cc'])) { $cc = $params['cc']; - $cc = explode(',', $cc); + if(!is_array($cc)){ + $cc = explode(',', $cc); + } }else{ $cc = []; } diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index ab6299ac..a371ed98 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -511,10 +511,10 @@ if (!function_exists('name_and_empid_check_in_db')) ->where("ep.is_active",1) ->where("ep.status",'active') // ->where("ep.client_id",$client_id) - ->where('name',$row[2])->where('emp_code',$row[1]) + ->where('name',trim($row[2]))->where('emp_code',trim($row[1])) ->findAll(); - // dd($employeeModel->getLastQuery()); + // kint::dump($employeeModel->getLastQuery()->getQuery()); if(($current_action == 'deletion' || $current_action == 'correction' || $current_action == 'si_enhancement') && !count($res)) @@ -2021,6 +2021,12 @@ if(!function_exists('check_unit')) { return array('status' => true); } + else if($temp != $existing_units[0]) + { + return array('status' => false,'error' => 'wrong unit name'); + } + + } if(strtolower($row[5]) == 'self') diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index 31114293..fbc374a8 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -151,6 +151,11 @@ class sendMailNotification $mail_content = $notification['mail_content']; $mail = $get_emp_email_and_other_details['email_corporate']; $subject = $notification['subject']; + + $cleanedText = mb_convert_encoding($subject, 'UTF-8', 'UTF-8'); // Normalize encoding + $cleanedText = preg_replace('/[^\x20-\x7E]/', '', $cleanedText); + + $subject = $cleanedText; $link = generate_download_link($rand_string); @@ -258,6 +263,7 @@ class sendMailNotification $si = ''; $premium = ''; $gst_forself = ''; + if(checkFamilyFloaters($policy_premium_data, $client_policy_data, $inner_item)){ $si = '₹ ' .format_indian_number($inner_item['basic_cover_si']); $premium = '₹ ' .format_indian_number(round($inner_item['premium'])); diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index 3b40a3fb..2151ec97 100755 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -55,14 +55,14 @@ class ClientModel extends Model ->where('is_active',1) ->findAll(); - if($role_id == 2 || $role_id == 3){ + // if($role_id == 2 || $role_id == 3){ - $clients = $this->select($columns) - ->join('client_rm', 'client_rm.client_id = clients.id') - ->where('client_rm.user_id', $user_id) - ->where('clients.is_active',1) - ->findAll(); - } + // $clients = $this->select($columns) + // ->join('client_rm', 'client_rm.client_id = clients.id') + // ->where('client_rm.user_id', $user_id) + // ->where('clients.is_active',1) + // ->findAll(); + // } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 688b8abf..75f8cd53 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -75,11 +75,11 @@ class EmployeePolicyModel extends Model return $data; } -// ---------------------------------------------------------------------------------------------------------- - public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=[], $branch_id=0, $emp_code="", $emp_name="") - { + // ---------------------------------------------------------------------------------------------------------- + public function getEmployeePolicy($client_id = 0, $policy_id = 0, $status = [], $branch_id = 0, $emp_code = "", $emp_name = "") + { // dd($status); - + $result = $this->select([ 'employee_polices.*', 'policy_type.policy_type as policy_name', @@ -91,7 +91,7 @@ class EmployeePolicyModel extends Model 'tpab.branch_code as tpa_branch_code', 'cm.client_name', 'cm.short_name as client_short_name', - 'emp.id as employee_primary_id', + // 'emp.id as employee_primary_id', 'emp.relationship', 'emp.relationship_code', 'emp.change_event', @@ -112,27 +112,27 @@ class EmployeePolicyModel extends Model 'client_branch.branch_code as client_branch_code', 'cp.policy_no', ]) - ->join('employees emp', 'employee_polices.employee_id = emp.id') - ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy - ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master - ->join('policy_type', 'policy_type.id = cp.policy_type_id') - ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master - ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch - ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master - ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch - ->join('clients cm', 'cp.client_id = cm.id') //cm - client master - ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master - ->orderBy('emp.emp_code', 'ASC') - ->orderBy('employee_polices.employee_id', 'ASC'); - + ->join('employees emp', 'employee_polices.employee_id = emp.id') + ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy + ->join('policies pm', 'cp.policy_id = pm.id', 'left') //pm - policy master + ->join('policy_type', 'policy_type.id = cp.policy_type_id') + ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master + ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch + ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master + ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch + ->join('clients cm', 'cp.client_id = cm.id') //cm - client master + ->join('client_branch', 'emp.client_branch_id = client_branch.id') //cm - client master + ->orderBy('emp.emp_code', 'ASC') + ->orderBy('employee_polices.employee_id', 'ASC'); + // Conditionally add where clauses - if ($client_id !=0 && !empty($client_id)) { + if ($client_id != 0 && !empty($client_id)) { $result->where('emp.client_id', $client_id); } - if ($branch_id !=0 && !empty($branch_id)) { + if ($branch_id != 0 && !empty($branch_id)) { $result->where('emp.client_branch_id', $branch_id); } - if ($policy_id !=0 && !empty($policy_id)) { + if ($policy_id != 0 && !empty($policy_id)) { $result->where('employee_polices.client_policy_id', $policy_id); } @@ -141,22 +141,20 @@ class EmployeePolicyModel extends Model $result->where('employee_polices.status !=', 'expired'); if (in_array("active", $status)) { - + $result->where('employee_polices.tpa_id IS NOT NULL'); $result->where('employee_polices.uhid IS NOT NULL'); $result->whereIn('employee_polices.status', $status); - } elseif (in_array("pending", $status)) { - + $result->where('employee_polices.tpa_id IS NULL'); $result->where('employee_polices.uhid IS NULL'); $result->whereIn('employee_polices.status', array_merge($status, ['active'])); - } else { - + $result->whereIn('employee_polices.status', $status); } - + // if($status == 'active'){ // $result->where('employee_polices.tpa_id IS NOT NULL'); // $result->where('employee_polices.uhid IS NOT NULL'); @@ -174,13 +172,13 @@ class EmployeePolicyModel extends Model if (!empty($emp_name)) { $result->like('emp.name', $emp_name); } - + // Always check these conditions $result->where('employee_polices.is_active', 1) - ->where('emp.is_active', 1); - + ->where('emp.is_active', 1); + return $result->findAll(); - } + } public function getEmployeePolicyForEcard($policy_id = 0) { @@ -575,6 +573,12 @@ class EmployeePolicyModel extends Model } } + $status_condition = "{$insurer_or_tpa}" === 'tpa' + ? "employee_polices.status = 'inactive' AND employees.emp_status = 'inactive'" + : "employee_polices.status = 'active' AND employees.emp_status = 'active'"; + + $endorsement_condition = "{$insurer_or_tpa}" === 'tpa' ? "AND (a.endorsement_id IS NOT NULL OR a.endorsement_id != '')" : "AND (a.endorsement_id IS NULL OR a.endorsement_id = '')"; + $query = $this->db->query(" SELECT DISTINCT a.id as endorsement_primarykey, @@ -627,19 +631,19 @@ class EmployeePolicyModel extends Model LEFT JOIN( - select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from + select aa.emp_code, aa.new_value as 'empstatus', bb.new_value as 'changeevent', cc.new_value as 'dateofexit', dd.new_value as 'reasonforexit', ee.new_value as 'status' from - ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status') aa + ( SELECT a1.emp_code, a1.field_name, a1.new_value from emp_endorsement as a1 where a1.field_name = 'emp_status' and a1.status != 'truncated') aa left join - ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event') bb on aa.emp_code = bb.emp_code + ( SELECT b1.emp_code, b1.field_name, b1.new_value from emp_endorsement as b1 where b1.field_name = 'change_event' and b1.status != 'truncated') bb on aa.emp_code = bb.emp_code left join - ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit') cc on aa.emp_code = cc.emp_code + ( SELECT c1.emp_code, c1.field_name, c1.new_value from emp_endorsement as c1 where c1.field_name = 'date_of_exit' and c1.status != 'truncated') cc on aa.emp_code = cc.emp_code left join - ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit') dd on aa.emp_code = dd.emp_code + ( SELECT d1.emp_code, d1.field_name, d1.new_value from emp_endorsement as d1 where d1.field_name = 'reason_for_exit' and d1.status != 'truncated') dd on aa.emp_code = dd.emp_code left JOIN - ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status') ee on aa.emp_code = ee.emp_code + ( SELECT e1.emp_code, e1.field_name, e1.new_value from emp_endorsement as e1 where e1.field_name = 'status' and e1.status != 'truncated') ee on aa.emp_code = ee.emp_code - ) as deletiondata on a.emp_code = deletiondata.emp_code + ) as deletiondata on a.emp_code = deletiondata.emp_code and a.status != 'truncated' LEFT JOIN ( @@ -659,23 +663,23 @@ class EmployeePolicyModel extends Model WHERE employee_polices.client_policy_id = {$client_policy_id} AND employees.client_branch_id = {$client_branch_id} - AND (a.endorsement_id IS NULL OR a.endorsement_id = '') + $endorsement_condition AND a.actions = 'd' + AND a.status != 'truncated' AND employee_polices.is_active = 1 - AND employee_polices.status = 'active' AND employees.is_active = 1 - AND employees.emp_status = 'active' + AND $status_condition group by group_key "); $result = $query->getResult(); + // dd($this->db->getLastQuery(), $result); return $result; } - public function fetchEmpEndorsementData($fetch_data) { // dd($fetch_data); @@ -861,21 +865,24 @@ class EmployeePolicyModel extends Model public function getEmployeePolicyForFileList($client_id, $policy_id) { - $result = $this->select(['employee_polices.*','pm.name as policy_name','im.short_name as insurer_short_name','ib.branch_name as insurer_branch_name','ib.branch_code as insurer_branch_code','tpam.name as tpa_name','tpam.short_name as tpa_short_name','tpab.branch_code as tpa_branch_code','cm.client_name','cm.short_name as client_short_name','emp.relationship','emp.relationship_code','emp.change_event','emp.emp_code','emp.name','emp.email_corporate','emp.dob','emp.gender','emp.emp_status','emp.is_active as emp_is_active','emp.mobile as mobile']) + $result = $this->select(['employee_polices.*','pt.policy_type','im.short_name as insurer_short_name','ib.branch_name as insurer_branch_name','ib.branch_code as insurer_branch_code','tpam.name as tpa_name','tpam.short_name as tpa_short_name','tpab.branch_code as tpa_branch_code','cm.client_name','cm.short_name as client_short_name','emp.relationship','emp.relationship_code','emp.change_event','emp.emp_code','emp.name','emp.email_corporate','emp.dob','emp.gender','emp.emp_status','emp.is_active as emp_is_active','emp.mobile as mobile']) ->join('employees emp', 'employee_polices.employee_id = emp.id') ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy - ->join('policies pm', 'cp.policy_id = pm.id') //pm - policy master + ->join('policy_type pt', 'cp.policy_type_id = pt.id') //pm - policy master ->join('insurers im', 'cp.insurer_id = im.id') //im - insurar master ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurar branch ->join('tpa tpam', 'cp.tpa_id = tpam.id') //tpam - tpa master ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id') //tpab - tpa brach ->join('clients cm', 'cp.client_id = cm.id') //cm - client master ->where('emp.client_id',$client_id) - ->where('employee_polices.client_policy_id',$policy_id); + ->where('employee_polices.client_policy_id',$policy_id) + ->where('employee_polices.is_active',1) + ->where('emp.is_active',1); $result->whereIn('employee_polices.status', ['enrolled']); $result->whereIn('emp.emp_status', ['enrolled']); - $result = $result->findAll(); + $result = $result->findAll(); + // print_r($this->db->getLastQuery()); return ($result); } diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 705f1587..7b7cc54a 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -43,6 +43,7 @@ class LeadsModel extends Model 'proposed_insurer_branch_id', 'proposed_tpa_id', 'proposed_tpa_branch_id', + 'proposel_data', 'status', 'notes', 'created_at', diff --git a/app/Models/LevelContactModel.php b/app/Models/LevelContactModel.php index 234db3aa..cf5d596d 100755 --- a/app/Models/LevelContactModel.php +++ b/app/Models/LevelContactModel.php @@ -26,27 +26,35 @@ class LevelContactModel extends Model ]; - public function getContectForRFQ(){ - - $result = $this - - ->select(' - level_contacts.id, - insurers.short_name as insurer_name, - insurer_branch.branch_code, - level_contacts.name as contect_person_name, - level_contacts.email as contect_person_email, - ') - ->join('insurer_branch', 'level_contacts.ref_id = insurer_branch.id') - ->join('insurers', 'insurer_branch.insurer_id = insurers.id') - ->where('level_contacts.contact_type', 'insurer') - ->where('level_contacts.is_active', 1) - ->where('insurer_branch.is_active', 1) - ->where('insurers.is_active', 1) - ->findAll(); - + public function getContactForRFQ($insurer_id = null, $insurer_branch_id = null) + { + $query = + $this->db->table('level_contacts') + ->select(' + level_contacts.id, + insurers.short_name as insurer_name, + insurer_branch.branch_code, + level_contacts.name as contact_person_name, + level_contacts.email as contact_person_email + ') + ->join('insurer_branch', 'level_contacts.ref_id = insurer_branch.id') + ->join('insurers', 'insurer_branch.insurer_id = insurers.id') + ->where('level_contacts.contact_type', 'insurer') + ->where('level_contacts.is_active', 1) + ->where('insurer_branch.is_active', 1) + ->where('insurers.is_active', 1); + + if ($insurer_branch_id) { + $query->where('insurer_branch.id', $insurer_branch_id); + } + if ($insurer_id) { + $query->where('insurer_branch.insurer_id', $insurer_id); + } + + $result = $query->get()->getResultArray(); return $result; - } + + } diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php index f74a1313..fa00c3a9 100644 --- a/app/Models/RFQModel.php +++ b/app/Models/RFQModel.php @@ -57,4 +57,29 @@ class RFQModel extends Model return $data; } + public function getRFQTableDataWithLeadIDAndType($lead_id, $type){ + + return $this->select(' + leads.client_name, + leads.client_short_name, + insurers.name as insurer_name, + insurer_branch.branch_name as insurer_branch_name, + tpa.name as tpa_name, + tpa_branch.branch_name as tpa_branch_name, + policy_type.policy_type, + rfq.json + ') + ->join('leads', 'rfq.lead_id = leads.id') + ->join('policy_type', 'leads.policy_type_id = policy_type.id') + ->join('insurers', 'leads.insurer_id = insurers.id') + ->join('insurer_branch', 'leads.insurer_branch_id = insurer_branch.id') + ->join('tpa', 'leads.tpa_id = tpa.id') + ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id') + ->where('rfq.lead_id', $lead_id) + ->where('rfq.type', $type) + ->where('rfq.is_active', 1) + ->first(); + + } + } diff --git a/app/Models/TPABranchModel.php b/app/Models/TPABranchModel.php index 9e528194..f811aa04 100755 --- a/app/Models/TPABranchModel.php +++ b/app/Models/TPABranchModel.php @@ -28,6 +28,8 @@ class TPABranchModel extends Model { $query = $this->select('tpa_branch.*, T.short_name as tpa_short_name, T.name as tpa_name') ->join('tpa T', 'tpa_branch.tpa_id = T.id', 'left') + ->where('T.is_active', 1) + ->where('tpa_branch.is_active', 1) ->find(); return $query; } diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index 8eb0e6f7..49b84400 100755 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -124,5 +124,15 @@ class UserModel extends Model } } + public function getUserListForRFQ(){ + + return $this->db->table('user_profiles') + ->select('user_profiles.*') + ->select('roles.role as user_role') + ->join('roles', 'roles.id = user_profiles.role') + ->get() + ->getResultArray(); + } + } ?> \ No newline at end of file diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index a2c371b2..b5747912 100755 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -71,36 +71,73 @@ - + + +   + + + +   + + failed +   + + + failed +   + + failed +   + + failed failed +   + + +   + diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 8ca32f6b..e023579b 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -142,7 +142,7 @@ - + + @@ -312,7 +327,7 @@ body { - + @@ -328,101 +343,288 @@ body { - - -