diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index be0e2476..62b24b8d 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -101,6 +101,6 @@ class Autoload extends AutoloadConfig * @phpstan-var list */ public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', - 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception' + 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception','sms_helper' ]; } diff --git a/app/Config/Routes.php b/app/Config/Routes.php index a9cd0ae2..31453be4 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -90,11 +90,13 @@ $routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) { $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->get("list", "ClientController::index"); + $routes->get("type/(:any)", "ClientController::type/$1"); $routes->get("create", "ClientController::clientOnboarding"); $routes->get('deposit/(:num)', 'ClientController::deposit/$1'); $routes->get('remove/(:num)', 'ClientController::removeClient/$1'); $routes->get("list/(:any)", "ClientController::editClientOnboarding/$1"); $routes->post('wipe', 'ClientController::wipeDemoClient'); + $routes->get("typeList/(:any)", "ClientController::typeList/$1"); // application/config/routes.php @@ -124,6 +126,8 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->post("edit", "ClientController::editClientBranch"); $routes->get("list/(:any)", "ClientController::getSingleBranchDataById/$1"); $routes->get("remove/(:any)", "ClientController::removeClientBranch/$1"); + $routes->post("auto_fetch_branch","ClientController::auto_fetch_branch"); + $routes->post("auto_fetch_branch_details","ClientController::auto_fetch_branch_details"); }); $routes->group("relation", ["filter" => "authMVC"], function ($routes) { @@ -168,6 +172,7 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->group("others", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "ClientController::createOtherTabContent"); + $routes->post('check-duplicate', 'ClientController::validateDuplicateByClientBranch'); }); }); @@ -384,6 +389,12 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('getClaimDumpFileErrorData', 'TicketController::getClaimDumpFileErrorData'); $routes->get("claim_dump_excel_error/(:any)", "TicketController::getClaimDumpExcelFileErrors/$1"); $routes->get("download_claim_dump_file/(:any)", "TicketController::downloadClaimDumpFile/$1"); + $routes->post('uploadMultiFileFromRfq', 'LeadsController::uploadMultiFileFromRfq'); + $routes->get('downloadMemberFile/(:any)', 'LeadsController::downloadMemberFile/$1'); + $routes->get('downloadFullMemberDataExcelErrorFile/(:any)', 'LeadsController::downloadFullMemberDataExcelErrorFile/$1'); + $routes->get('getMemberDataExcelFileErrors', 'LeadsController::getMemberDataExcelFileErrors'); + $routes->post('savePlacementDataAndValidateMemberDataFile', 'LeadsController::savePlacementDataAndValidateMemberDataFile'); + $routes->get('checkMemberDataFileValidationStatus', 'LeadsController::checkMemberDataFileValidationStatus'); }); $routes->post("policy_tranction/sendInstallmentRemainderMail","PolicyTransactionController::sendInstallmentRemainderMail"); @@ -516,6 +527,7 @@ $routes->post("employeeRest/updateMpin", "RestAuthenticationController::updateMp $routes->post("employeeRest/getPostEmployeeDataForAuth", "RestAuthenticationController::getPostEmployeeDataForAuth"); // $routes->post("logHrActivity", "RestAuthenticationController::logHrActivity"); +$routes->get("employeeRest/getClientDetails", "EmployeeRestController::getClientDetails"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { @@ -540,7 +552,7 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("deleteDependence", "EmployeeRestController::deleteDependence"); $routes->get("getEmployeeAndDependenceByClientId", "EmployeeRestController::getEmployeeAndDependenceByClientId"); $routes->get("getClientPolicy", "EmployeeRestController::getClientPolicy"); - $routes->get("getClientDetails", "EmployeeRestController::getClientDetails"); + $routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy"); $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn"); @@ -674,6 +686,7 @@ $routes->post('claimStatusCheck','VidalApiController::claimStatusCheck'); $routes->post('newClaim','VidalApiController::newClaim'); $routes->post('enrollment','VidalApiController::enrollment'); +// General Tickets $routes->post("ticketSave", "ThzController::ticketSave"); $routes->get("ticketList", "ThzController::ticketList"); @@ -692,6 +705,12 @@ $routes->group('test', function($routes) { $routes->get('viewPDF', 'TestingController::viewPDF'); $routes->get('generate-pdf-view', 'TestingController::generatePDFWithView'); $routes->get('param/(:any)', 'TestingController::ptedfitdata/$1'); + $routes->get('viewrfq', 'TestingController::viewRFQNonEb'); + $routes->get('exportexcel', 'TestingController::exportExcel'); + $routes->post('saverfq', 'TestingController::saverfq'); + $routes->get('mapping_client_id_and_branch_id','TestingController::mapping_client_id_and_branch_id'); + $routes->get('membervalidation', 'TestingController::membervalidation'); + $routes->get('generateExcel', 'TestingController::generateExcel'); }); $routes->cli('cli/testcli', 'TestingController::testcli'); diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php index 300036be..33d6ce1d 100755 --- a/app/Controllers/AppContentManagementController.php +++ b/app/Controllers/AppContentManagementController.php @@ -27,7 +27,8 @@ class AppContentManagementController extends AdminController public function add_image_index() { $this->myLogger->logme('error','Addvertisement Image list function called'); - $headerData['page_name'] = 'Addvertisement Image List'; + $headerData['tab_name'] = 'Addvertisement Images'; + $headerData['page_name'] = 'Addvertisement Images'; $data['addImageList'] = $this->addImgModel->findAll(); // dd($data); @@ -86,6 +87,7 @@ class AppContentManagementController extends AdminController public function frontend_content(){ $data['test'] = $this->feContentModel->findAll(); + $headerData['tab_name'] = 'Front-End Content'; $headerData['page_name'] = 'Front-End Content'; echo view('layout/header', $headerData); diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php index c3005aac..355df367 100644 --- a/app/Controllers/BDSReportController.php +++ b/app/Controllers/BDSReportController.php @@ -180,6 +180,9 @@ class BDSReportController extends AdminController 'BAP-Insurer' => 'bapInsurer', 'Client' => 'client' ]; + + $data['page_name'] = "IRBA Report"; + return $this->loadLayout('irba_report', $data); } else { @@ -914,6 +917,7 @@ class BDSReportController extends AdminController $data['default_end'] = $default_start->format('d-m-Y'); $data['default_start'] = $default_start->modify('-60 days')->format('d-m-Y'); $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['tab_name'] = "Renewal Report"; $data['page_name'] = "Renewal Report"; return $this->loadLayout('renewal_search', $data); } else { @@ -1013,6 +1017,7 @@ class BDSReportController extends AdminController public function accountMangerStatusBDSReport() { + $data['tab_name'] = "Account Manager BDS Report"; $data['page_name'] = "Account Manager BDS Report"; $sql = " @@ -1130,6 +1135,7 @@ class BDSReportController extends AdminController public function getMultiReport($report_type){ + $data['tab_name'] = "BDS Report"; $data['page_name'] = "BDS Report"; if ($report_type == 1){ diff --git a/app/Controllers/Chatbot/EcardDownloadConversation.php b/app/Controllers/Chatbot/EcardDownloadConversation.php index a0a644a0..e0d63294 100644 --- a/app/Controllers/Chatbot/EcardDownloadConversation.php +++ b/app/Controllers/Chatbot/EcardDownloadConversation.php @@ -14,11 +14,63 @@ class EcardDownloadConversation extends Conversation public function run() { $this->bot->types(); - sleep(0.5); + // sleep(0.5); $this->showEcardMenu(); } - protected function showEcardMenu() + protected function showEcardMenu() +{ +// Log entry for debugging +log_message('error', 'showEcardMenu function called'); + + +// Get chat session and policies +$chat_session_info = get_chatbot_session_info(); +$policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); + +// If policies found, build an HTML list of links (and raw URLs as fallback) +if (is_array($policy_list) && count($policy_list)) { + $parts = []; + foreach ($policy_list as $policy) { + // Resolve rand string (defensive) + $randString = ''; + if (isset($policy['rand_string']) && $policy['rand_string'] !== '') { + $randString = $policy['rand_string']; + } elseif (isset($policy['rand']) && $policy['rand'] !== '') { + $randString = $policy['rand']; + } elseif (isset($policy['emp_policy_id'])) { + // As a last resort, use emp_policy_id (not ideal but prevents broken links) + $randString = $policy['emp_policy_id']; + } + + // Build link; make sure base_url produces correct path + $link = base_url('/download-e-card/' . $randString . '/1'); + + // Escape policy name to avoid HTML injection + $safeName = isset($policy['policy_name']) ? htmlspecialchars($policy['policy_name'], ENT_QUOTES, 'UTF-8') : 'Policy'; + + // Add to parts; include anchor and raw URL fallback + $parts[] = "🔹 {$safeName}
"; + } + + $message = "Choose a policy to download (click the policy name below):

" . implode('

', $parts); + log_message('error', 'Ecard links displayed: ' . json_encode(array_column($policy_list, 'policy_name'))); + $this->say($message); +} else { + log_message('error', 'No policies found for ecard download'); + $this->say('No policy found.'); +} + +// After showing links, move to confirmation conversation (Do you want to continue?) +// This keeps the UX identical to previous flow where we asked the user if they want to continue. +$this->bot->startConversation(new doYouWantToContinueConversation()); + + +} + + + + protected function showEcardMenuOLD() { log_message('error', ('showEcardMenu function called')); @@ -27,17 +79,13 @@ class EcardDownloadConversation extends Conversation $buttons = []; $question = 'Choose Policy to Download Ecard:'; - // log_message('error', ('policy_list : ' . json_encode($policy_list))); + log_message('error', ('policy_list : ' . json_encode($policy_list))); if(is_array($policy_list) && count($policy_list)) { foreach($policy_list as $policy) { - // $question = Question::create("Choose Policy to Download Ecard:") - // ->addButtons([ - // Button::create("🔹 $policy['policy_name']")->value("$policy['emp_policy_id']"), - // Button::create("◀️ Go Back")->value("go_back"), - // ]); + $this->buttonsData[$policy['emp_policy_id'].'#'.$policy['rand_string']] = ['response_text' => "🔹 {$policy['policy_name']}"] ; $buttons[] = Button::create("{$policy['policy_name']}")->value($policy['emp_policy_id'].'#'.$policy['rand_string']); } @@ -63,10 +111,9 @@ class EcardDownloadConversation extends Conversation case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2: $link = base_url().'/download-e-card/' . explode('#',$answer->getValue())[1].'/1'; - $this->say('Click here to downlad: Ecard'); - + log_message('error', $link); + $this->say('Click here to downlad: GMC
Click here to downlad: GMC Parent'); $this->bot->startConversation(new doYouWantToContinueConversation()); // ✅ Restart the - break; default: @@ -76,4 +123,7 @@ class EcardDownloadConversation extends Conversation } }); } + + + } diff --git a/app/Controllers/Chatbot/MainMenuConversation.php b/app/Controllers/Chatbot/MainMenuConversation.php index f06fd078..e5bf7a3d 100644 --- a/app/Controllers/Chatbot/MainMenuConversation.php +++ b/app/Controllers/Chatbot/MainMenuConversation.php @@ -23,7 +23,7 @@ class MainMenuConversation extends Conversation { $this->bot->userStorage()->delete(); $this->bot->types(); // Typing indicator for the first message - sleep(0.5); // Delay + // sleep(0.5); // Delay $this->showMainMenu(); } diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php index 34e44f2b..57bb13de 100644 --- a/app/Controllers/Chatbot/NetworkHospitalConversation.php +++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php @@ -16,11 +16,11 @@ class NetworkHospitalConversation extends Conversation public function run() { $this->bot->types(); // Typing indicator for the first message - sleep(0.5); // Delay + // sleep(0.5); // Delay $this->showHospitalMenu(); } - protected function showHospitalMenu() + protected function showHospitalMenuOLD() { $chat_session_info = get_chatbot_session_info(); $policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); @@ -92,4 +92,54 @@ class NetworkHospitalConversation extends Conversation }); } + protected function showHospitalMenu() +{ +log_message('error', 'showHospitalMenu function called'); + + +// Get chat session and policies +$chat_session_info = get_chatbot_session_info(); +$policy_list = ChatbotHelper::getListOfPolicies($chat_session_info); + +if (is_array($policy_list) && count($policy_list)) { + $parts = []; + foreach ($policy_list as $policy) { + // Resolve rand string (defensive) + $randString = ''; + if (isset($policy['rand_string']) && $policy['rand_string'] !== '') { + $randString = $policy['rand_string']; + } elseif (isset($policy['rand']) && $policy['rand'] !== '') { + $randString = $policy['rand']; + } elseif (isset($policy['emp_policy_id'])) { + $randString = $policy['emp_policy_id']; + } + + $emp_policy_id = isset($policy['emp_policy_id']) ? $policy['emp_policy_id'] : ''; + $hospital_link = ChatbotHelper::getHospitalLink($emp_policy_id); + + $safeName = isset($policy['policy_name']) ? htmlspecialchars($policy['policy_name'], ENT_QUOTES, 'UTF-8') : 'Policy'; + + if ($hospital_link) { + $parts[] = "🔹 {$safeName}
"; + } else { + $parts[] = "🔹 {$safeName} — No Data found, please contact support team"; + } + + log_message('error', 'Hospital link for policy ' . $emp_policy_id . ': ' . $hospital_link); + } + + $message = "Access hospital details for your policies below:

" . implode('

', $parts); + $this->say($message); +} else { + log_message('error', 'No policies found for hospital menu'); + $this->say('No policy found.'); +} + +// After showing links, move to confirmation conversation +$this->bot->startConversation(new doYouWantToContinueConversation()); + + +} + + } diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 67d31c37..8b0a979b 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -111,7 +111,7 @@ class ChatbotControllerNew extends BaseController log_message("error","Inside Bot Type Function"); $bot->types(); // Typing indicator for the first message - sleep(0.1); // Delay + // sleep(0.5); // Delay }); // Start the Main Menu when user says "hi" or "start" $this->botman->hears('start|hi|hello|help|help me', function (BotMan $bot) { diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 164bee10..ee7ae376 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -132,6 +132,15 @@ class ClientController extends AdminController //-------------------------------------------------------------------------------------------------------- + public function validateDuplicateByClientBranch() + { + $value = $this->request->getPost('value'); + $clientId = $this->request->getPost('client_id'); + $branchId = $this->request->getPost('branch_id'); + $field = $this->request->getPost('field'); + $isDuplicate = $this->clientModel->isDuplicateByClientBranch($value, $field, $clientId, $branchId); + return $this->response->setJSON(['isDuplicate' => $isDuplicate]); + } public function checkDuplicateTableFieldValue() { $table = $this->request->getPost('table'); @@ -143,9 +152,9 @@ class ClientController extends AdminController // Perform the query $builder = $db->table($table); - if(is_array($value)){ + if (is_array($value)) { $isDuplicate = $builder->where($value)->where('is_active', 1)->countAllResults() > 0; - }else{ + } else { $isDuplicate = $builder->where($field, $value)->where('is_active', 1)->countAllResults() > 0; } @@ -154,9 +163,9 @@ class ClientController extends AdminController } public function smapletest() - { + { $headers = [ - 'S.No', + 'S.No', 'NAME OF EMP/DEP', 'EMP ID', // 'EMP/DEP TYPE', @@ -177,13 +186,13 @@ class ClientController extends AdminController 'PRO RATA PREMIUM', 'GST', 'TOTAL AMOUNT' - ]; + ]; $filePath = generateExcelWithHeader($headers); - echo "Excel file created at: $filePath"; + echo "Excel file created at: $filePath"; } public function testMailAttachments($email = 'venkateshraman786@gmail.com') - { + { $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

'; // $attachments = [ @@ -192,8 +201,8 @@ class ClientController extends AdminController // ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] // ]; $attachments = []; - $res = MailHelper::send_email(['mail' => $email, 'subject' => 'Mail Via Attachment Testing URL', 'message' => $message,'attachments' => $attachments]); - + $res = MailHelper::send_email(['mail' => $email, 'subject' => 'Mail Via Attachment Testing URL', 'message' => $message, 'attachments' => $attachments]); + print_rr($res); echo '------------------------------------------------------------------------------------------'; // print_rr($attachments); @@ -205,21 +214,20 @@ class ClientController extends AdminController // dd($client_id, $emp_code, $policy_id, $mail_active); - if(empty($policy_id)){ + if (empty($policy_id)) { $client_policy_ids = $this->employeeModel - ->select('employee_polices.client_policy_id') - ->join('employee_polices', 'employees.id = employee_polices.employee_id') - ->where('employees.client_id', $client_id ) - ->where('employees.emp_code', $emp_code ) - ->where('employee_polices.is_active', 1 ) - ->where('employees.is_active', 1 ) - ->findAll(); + ->select('employee_polices.client_policy_id') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.client_id', $client_id) + ->where('employees.emp_code', $emp_code) + ->where('employee_polices.is_active', 1) + ->where('employees.is_active', 1) + ->findAll(); $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id'); $client_policy_id = array_unique($client_policy_ids2); - - }else{ + } else { $client_policy_id = json_decode($policy_id, true); } @@ -233,39 +241,37 @@ class ClientController extends AdminController $mail_send_return1 = ''; $mail_send_return2 = ''; - if (!is_null($client_policy_id) && is_array($client_policy_id)) - { + if (!is_null($client_policy_id) && is_array($client_policy_id)) { - $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll(); + $empData = $this->employeeModel->where('emp_code', $emp_code)->where('client_id', $client_id)->where('is_active', 1)->findAll(); // dd($empData); $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); // dd($filteredEmpData); $array_list = []; - foreach ($client_policy_id as $key => $value) - { - $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,emp_code: $emp_code,client_id: $client_id,emp_status:['draft','enrolled'],policy_status:['draft','enrolled']); - if(count($find) > 0){ + foreach ($client_policy_id as $key => $value) { + $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']); + if (count($find) > 0) { $array_list[] = $find; } } // dd($array_list); - $notification = $this->notificationModel->where('client_id' ,$client_id)->where('template_name', 'member_review_and_summary_mail')->first(); + $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_review_and_summary_mail')->first(); if (isset($notification) && $notification['enabled'] == 1) { - $params ['array_list'] = $array_list; - $params ['client_policy_id'] = $client_policy_id; - $params ['emp_code'] = $emp_code; - $params ['client_id'] = $client_id; - $params ['notification'] = $notification; + $params['array_list'] = $array_list; + $params['client_policy_id'] = $client_policy_id; + $params['emp_code'] = $emp_code; + $params['client_id'] = $client_id; + $params['notification'] = $notification; $params['common'] = [ - 'client_id' => $filteredEmpData[0]['client_id'], - 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], + 'client_id' => $filteredEmpData[0]['client_id'], + 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], 'client_policy_id' => null, 'employee_policy_id' => null, 'employee_id' => $filteredEmpData[0]['id'], @@ -274,16 +280,16 @@ class ClientController extends AdminController // dd($params); - $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); + $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); // print_r($wholeData); die; - if($mail_active == 1){ + if ($mail_active == 1) { $mail_send_return = MailHelper::send_email($wholeData[0]); $this->myLogger->logme("error", $mail_send_return); } // if (isset($wholeData)) { - + // $params['common']['mail_type'] = 'account_maneger_summary_mail'; // $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); // // print_r($account_manager_wholeData); die; @@ -322,12 +328,11 @@ class ClientController extends AdminController // } // } - }else{ + } else { $this->myLogger->logme("error", 'Member Review Mail Configuration not Enable for this client'); } - } - + print_r($wholeData); echo '
';
@@ -346,26 +351,25 @@ class ClientController extends AdminController
     {
         // dd($client_id, $emp_code, $policy_id, $mail_active);
 
-        if(empty($policy_id)){
+        if (empty($policy_id)) {
 
             $client_policy_ids = $this->employeeModel
-                                ->select('employee_polices.client_policy_id')
-                                ->join('employee_polices', 'employees.id = employee_polices.employee_id')
-                                ->where('employees.client_id', $client_id ) 
-                                ->where('employees.emp_code', $emp_code )
-                                ->where('employee_polices.is_active', 1 )
-                                ->where('employees.is_active', 1 )
-                                ->findAll();
+                ->select('employee_polices.client_policy_id')
+                ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+                ->where('employees.client_id', $client_id)
+                ->where('employees.emp_code', $emp_code)
+                ->where('employee_polices.is_active', 1)
+                ->where('employees.is_active', 1)
+                ->findAll();
 
             $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id');
             $client_policy_id = array_unique($client_policy_ids2);
-
-        }else{
+        } else {
             $client_policy_id = json_decode($policy_id, true);
         }
 
         // dd($client_policy_id);
-    
+
         if (!is_null($client_policy_id) && is_array($client_policy_id)) {
 
             $empData = $this->employeeModel
@@ -373,9 +377,9 @@ class ClientController extends AdminController
                 ->where('client_id', $client_id)
                 ->where('is_active', 1)
                 ->findAll();
-    
+
             $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self');
-    
+
             if (empty($filteredEmpData)) {
                 return $this->respond([
                     'status' => 'error',
@@ -383,7 +387,7 @@ class ClientController extends AdminController
                     'message' => 'No active employee data found for the given criteria.',
                 ], 404);
             }
-    
+
             $array_list = [];
             foreach ($client_policy_id as $value) {
                 $find = $this->employeeModel->getEmpFamilybyEmpCode(
@@ -393,17 +397,17 @@ class ClientController extends AdminController
                     emp_status: ['draft', 'enrolled'],
                     policy_status: ['draft', 'enrolled']
                 );
-    
+
                 if (count($find) > 0) {
                     $array_list[] = $find;
                 }
             }
-    
+
             $notification = $this->notificationModel
                 ->where('client_id', $client_id)
                 ->where('template_name', 'member_review_and_summary_mail')
                 ->first();
-    
+
             if ($notification && $notification['enabled'] == 1) {
 
                 $params = [
@@ -421,14 +425,14 @@ class ClientController extends AdminController
                         'mail_type' => 'member_review_and_summary_mail',
                     ],
                 ];
-    
+
                 $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
-    
+
                 if ($mail_active == 0) {
 
                     // $mail_send_result = [];
                     $mail_send_result = MailHelper::send_email($wholeData[0]);
-    
+
                     if ($mail_send_result['status'] === 'success') {
                         return $this->respond([
                             'status' => 'success',
@@ -445,7 +449,7 @@ class ClientController extends AdminController
                         ], 500);
                     }
                 }
-    
+
                 return $this->respond([
                     'status' => 'success',
                     'code' => 200,
@@ -453,29 +457,30 @@ class ClientController extends AdminController
                     'data' => $wholeData,
                 ], 200);
             }
-    
+
             return $this->respond([
                 'status' => 'error',
                 'code' => 400,
                 'message' => 'Member Review Mail configuration is not enabled for this client.',
             ], 400);
         }
-    
+
         return $this->respond([
             'status' => 'error',
             'code' => 404,
             'message' => 'No active client policy IDs found.',
         ], 404);
     }
-    
+
 
     //--------------------------------------------------------------------------------------------------------
 
     public function index()
     {
         $this->myLogger->logme('error', 'Client list function called');
-        $headerData['page_name'] = 'Client List';
-        $data['clientList'] = $this->clientModel->getCreatedByUserName();
+        $headerData['tab_name'] = 'Client List';
+        $headerData['page_name'] = 'Clients'; // Both Browser Tab name And Page name are same. 
+        $data['clientList'] = $this->clientModel->getCreatedByUserName(1); // passing client_type 
         $data['client_rm'] = $this->clientRMModel->getAllClientRM();
         $data['lead_data'] = $this->leadsModel->getLeadForInsertClientList();
 
@@ -488,6 +493,29 @@ class ClientController extends AdminController
         // $this->loadLayout('client_onboarding', $data);
     }
 
+    
+    public function typeList($id = null)
+    {
+        try {
+            $data = $this->clientModel->getCreatedByUserName($id); // passing client_type 
+            if (empty($data)) {
+                return $this->response
+                    ->setJSON(['status' => 'error', 'message' => 'No Records found'])
+                    ->setStatusCode(404);
+            }
+
+            return $this->response
+                ->setJSON(['status' => 'success', 'data' => $data])
+                ->setStatusCode(200);
+
+        } catch (\Throwable $e) {
+            return $this->response
+                ->setJSON(['status' => 'error', 'message' => $e->getMessage()])
+                ->setStatusCode(500);
+        }
+    }
+
+
     public function updateEmpAndPolicyStatus()
     {
 
@@ -599,7 +627,8 @@ class ClientController extends AdminController
     public function clientOnboarding()
     {
         $this->myLogger->logme('error', 'Client Onboarding function called');
-        $headerData['page_name'] = 'Client Onboarding';
+        $headerData['tab_name'] = 'Client Onboarding';
+        $headerData['page_name'] = 'Clients';
 
         $data['entity']        = $this->kycEntityTypeModel->findAll();
         $data['kyc_docs']      = $this->kycDocsModel->findAll();
@@ -621,20 +650,24 @@ class ClientController extends AdminController
 
         // dd($data['placeHolders']);
 
+        // auto fetch client list and branch list from pre
+        $data['auto_fetch_client_list'] =  $this->getClientListFromPre();
+
+
         echo view('layout/header', $headerData);
         echo view('client_onboarding', $data);
         echo view('layout/footer');
     }
 
     // In your controller
-    public function deposit($id = null , $requestFrom = null , $policyId = null)
+    public function deposit($id = null, $requestFrom = null, $policyId = null)
     {
-       
-        $headerData['page_name'] = 'Client Deposit';
-        
+        $headerData['tab_name'] = 'Client Deposit';
+        $headerData['page_name'] = 'Clients';
+
         $data['clientName'] = $this->clientModel->where('id', $id)->find();
-        $data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id,$policyId);
-        
+        $data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id, $policyId);
+
         $data['depositsummary'] = $this->clientPolicyModel->getDepositlistsummary($id);
 
         // Fetch associated insurer names and balances
@@ -642,14 +675,16 @@ class ClientController extends AdminController
         $data['balances'] = $balances;
 
         // dd($data);
-        if($requestFrom == 'rest'){ return $data; }
+        if ($requestFrom == 'rest') {
+            return $data;
+        }
 
         echo view('layout/header', $headerData);
         echo view('client_deposit_list', $data);
         echo view('layout/footer');
     }
 
-    public function view_Deposit($insurerId , $requestFrom = null , $param = null)
+    public function view_Deposit($insurerId, $requestFrom = null, $param = null)
     {
         // Load your model to fetch data based on $clientId and $insurerId
         // $subTypeOptions = [
@@ -671,26 +706,28 @@ class ClientController extends AdminController
         ];
 
         $data['subTypeOptions'] = $subTypeOptions;
-        $headerData['page_name'] = 'Client Deposit';
+        $headerData['tab_name'] = 'Client Deposit';
+        $headerData['page_name'] = 'Clients';
         $loggedInUserID = get_session_userid();
         // $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId);
-        if($requestFrom == 'rest')
-        { 
+        if ($requestFrom == 'rest') {
             $clientId = $param['client_id'];
             $cd_ac_pk = $param['cd_ac_pk'];
-        }else{
+        } else {
             $clientId = $this->request->getGet('client_id');
             $cd_ac_pk = $this->request->getGet('cd_ac_pk');
         }
-        
+
         $data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId);
         $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk, $subTypeOptions);
         $data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
         $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId, $cd_ac_pk);
         $data['cd_ac_pk'] = $cd_ac_pk;
 
-        if($requestFrom == 'rest'){ return $data; }
-        
+        if ($requestFrom == 'rest') {
+            return $data;
+        }
+
         // Load the view for the new list page;
         echo view('layout/header', $headerData);
         echo view('view_deposit', $data);
@@ -712,12 +749,12 @@ class ClientController extends AdminController
             ->where('is_active', 1)
             ->first();
 
-        
-        if(!empty($record_date)){
+
+        if (!empty($record_date)) {
             // Prepare the array with data
             $date = \DateTime::createFromFormat('d/m/Y', $record_date);
             $record_date = $date->format('Y-m-d');
-        }else{
+        } else {
             $record_date = null;
         }
 
@@ -751,7 +788,8 @@ class ClientController extends AdminController
     {
 
         $this->myLogger->logme('error', 'Edit Client Onboarding function called');
-        $headerData['page_name'] = 'Edit Client Onboarding';
+        $headerData['tab_name'] = 'Edit Client Onboarding';
+        $headerData['page_name'] = 'Clients';
 
         $editData['RM']             = $this->userModel->where('is_active', 1)->findAll();
         $editData['tpa']            = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
@@ -792,8 +830,14 @@ class ClientController extends AdminController
         $editData['client_policy']['role'] = get_role_id();
         $editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll();
         $editData['placeHolders'] = ['member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
-        $editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active",1)->first();
+        $editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active", 1)->first();
         // dd($editData);
+
+        $edit['pre_branch_id'] =  $this->clientBranchModel->select('pre_branch_id')->where('client_id',$id)->get()->getResultArray()[0]['pre_branch_id']??"";
+
+        $editData['auto_fetch_client_list'] =  $this->getClientListFromPre();
+
+
         echo view('layout/header', $headerData);
         echo view('client_onboarding', $editData);
         echo view('layout/footer');
@@ -817,7 +861,7 @@ class ClientController extends AdminController
             $data['is_download_btn'] = 1;
         }
 
-        if(empty($data['parent_client_id'])){
+        if (empty($data['parent_client_id'])) {
             $data['parent_client_id'] = null;
         }
 
@@ -851,7 +895,7 @@ class ClientController extends AdminController
             $data['is_download_btn'] = 1;
         }
 
-        if(empty($data['parent_client_id'])){
+        if (empty($data['parent_client_id'])) {
             $data['parent_client_id'] = null;
         }
         // print_r($data);die;
@@ -890,9 +934,9 @@ class ClientController extends AdminController
         $insert = $this->clientKYCDocsModel->insert($data);
         if ($insert) {
             // $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll();
-            if($form_type == "others"){
+            if ($form_type == "others") {
                 $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id'));
-            }else{
+            } else {
                 $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id'));
             }
             return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200);
@@ -920,9 +964,9 @@ class ClientController extends AdminController
 
         if ($insert) {
             // $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id);
-            if($form_type == "others"){
+            if ($form_type == "others") {
                 $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id'));
-            }else{
+            } else {
                 $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id'));
             }
             return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs], 200);
@@ -1070,7 +1114,7 @@ class ClientController extends AdminController
 
         $this->myLogger->logme('error', 'Client branch CREATE function called');
         $data   = $this->request->getPost();
-        // var_dump($data); die;
+
         if (!isset($data['sez'])) {
             $data['sez'] = 0;
         } elseif ($data['sez']) {
@@ -1086,14 +1130,47 @@ class ClientController extends AdminController
         }
 
         $data['created_by'] = get_session_userid();
+
+        
+        // before updating check if pre_branch_id is already existing in the current db
+
+        if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
+        {
+            $existing_pre_branch = $this->clientBranchModel
+                                    ->where('pre_branch_id',$data['pre_branch_id'])
+                                    //->where('id !=',$post_branch_id)
+                                    ->first();
+
+            if($existing_pre_branch)
+            {
+                return $this->respond([
+                    'status' => false,
+                    'code' => 409,
+                    'message' => 'The  branch  is already mapped with another branch. Please check.',
+                ], 409);
+            }
+        }
+
+
+
         $insert = $this->clientBranchModel->insert($data);
 
+        $post_branch_id = $insert;
+
         if ($insert) {
             $level_contact_data = $this->request->getPost('level_contect_data');
             $level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null;
             $this->saveLevelContacts($level_contact_data, $insert);
         }
 
+        if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
+        {
+            // need to update the client_branch in the pre
+            $result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "create");
+
+            log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
+        }
+
         if ($insert) {
             $branchData = $this->clientBranchModel->where('client_id', $this->request->getPost('client_id'))->findAll();
             $branchData['role'] = get_role_id();
@@ -1118,13 +1195,17 @@ class ClientController extends AdminController
         $this->myLogger->logme('error', 'Client branch EDIT function called');
         $id     = $this->request->getPost('branch_id_primarykey');
         $client_id     = $this->request->getPost('client_id');
+        $pre_branch_id = $this->request->getPost('pre_branch_id') ?? '';
+
         $data   = $this->request->getPost();
+        $data['pre_branch_id']  = $pre_branch_id;
+
         $units   = $this->request->getPost('units');
 
         $emp_unit_count = 0;
-        $rr_unit_count = 0;
+        $rr_unit_count  = 0;
         $rr_unit_count2 = 0;
-        $total_count = 0;
+        $total_count    = 0;
 
         $list_of_branch_units = $this->clientBranchModel->find($id);
         $units = json_decode($list_of_branch_units['units']);
@@ -1177,7 +1258,41 @@ class ClientController extends AdminController
         }
 
         $data['updated_by'] = get_session_userid();
+
+        $post_branch_id = $id;
+
+        // before updating check if pre_branch_id is already existing in the current db
+
+        if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
+        {
+            $existing_pre_branch = $this->clientBranchModel
+                                    ->where('pre_branch_id',$data['pre_branch_id'])
+                                    ->where('id !=',$post_branch_id)
+                                    ->first();
+
+            if($existing_pre_branch)
+            {
+                return $this->respond([
+                    'status' => false,
+                    'code' => 409,
+                    'message' => 'The  branch  is already mapped with another branch. Please check.',
+                ], 409);
+            }
+        }
+
         $insert = $this->clientBranchModel->update($id, $data);
+
+
+
+        if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
+        {
+            // need to update the client_branch in the pre
+            $result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "update");
+
+            log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
+        }
+
+
         $this->myLogger->logme('error', 'Client branch EDITED by {data}', ['data' => get_session_userid()]);
 
 
@@ -1383,9 +1498,9 @@ class ClientController extends AdminController
         $data['insurer_id']        = $insurerId;
 
         $tpaValue                  = (string) $this->request->getPost('tpa');
-        if(!empty($tpaValue) || $tpaValue !== ''){
+        if (!empty($tpaValue) || $tpaValue !== '') {
             list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
-        }else{
+        } else {
             $tpaBranchId = null;
             $tpaId = null;
         }
@@ -1461,7 +1576,7 @@ class ClientController extends AdminController
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
             $clientPoliceData['role'] = get_role_id();
 
-            if($policy_transaction_data > 0){
+            if ($policy_transaction_data > 0) {
                 $r = Jobs::addJob(['job_name' => 'updatePolicyTransactionDataWhileClinetPolicyUpdate', 'payload' => [
                     'old_client_policy_data' => $old_client_policy_data ?? null,
                     'new_client_policy_data' => $new_client_policy_data ?? null,
@@ -1497,14 +1612,13 @@ class ClientController extends AdminController
             $update = $this->clientPolicyModel->where('id', $id)->set($data)->update();
 
             if ($update) {
-                
+
                 $policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id);
 
                 return $this->respond(['status' => true, 'code' => 200], 200);
             } else {
                 return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy'], 200);
             }
-
         } else {
 
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'The policy has active employees'], 200);
@@ -1536,7 +1650,7 @@ class ClientController extends AdminController
         }
     }
 
-    
+
 
     // Save Rack Rate function
     public function createClientPolicyPremium()
@@ -1990,8 +2104,15 @@ class ClientController extends AdminController
 
             // Check differences and prepare update data
             $fields_to_check = [
-                'client_branch_id', 'policy_type', 'insurer_id', 'insurer_branch_id',
-                'cd_ac_pk', 'policy_end_date', 'policy_start_date', 'tpa_id', 'tpa_branch_id'
+                'client_branch_id',
+                'policy_type',
+                'insurer_id',
+                'insurer_branch_id',
+                'cd_ac_pk',
+                'policy_end_date',
+                'policy_start_date',
+                'tpa_id',
+                'tpa_branch_id'
             ];
 
             foreach ($fields_to_check as $field) {
@@ -2039,18 +2160,16 @@ class ClientController extends AdminController
                 }
 
                 $this->myLogger->logme("error", "Policy transaction(s) updated successfully. Updated IDs: " . json_encode($updated_pt_ids));
-                
+
                 return [
                     'status' => "Success",
                     'message' => "Policy transaction(s) updated.",
                     'updated_ids' => $updated_pt_ids
                 ];
-
             } else {
                 $this->myLogger->logme("error", "No active policy_transaction records found for update.");
                 return ['status' => "Failed", 'message' => "No active policy_transaction records found."];
             }
-
         } catch (\Throwable $e) {
             $this->myLogger->logme("error", "Exception during policy_transaction update: " . $e->getMessage());
             return [
@@ -2096,7 +2215,6 @@ class ClientController extends AdminController
                         $errors[] = "No change or failed update for ID {$row['id']}";
                     }
                 }
-
             } catch (\Exception $e) {
                 $errors[] = "Error updating pt_id {$pt_id}: " . $e->getMessage();
             }
@@ -2185,7 +2303,8 @@ class ClientController extends AdminController
         }
     }
 
-    public function generateKycPrimaryTable($client_id){
+    public function generateKycPrimaryTable($client_id)
+    {
 
         $db = db_connect();
         $builder = $db->table('kyc_docs kd');
@@ -2210,16 +2329,17 @@ class ClientController extends AdminController
 
     }
 
-    public function generateKycOthersTable($client_id){
-        
+    public function generateKycOthersTable($client_id)
+    {
+
         $result['data'] = $this->clientKYCDocsModel
-                ->where('is_active', 1)
-                ->where('client_id', $client_id)
-                ->groupStart()
-                    ->where('kyc_doc_type_id', null)
-                    ->orWhere('kyc_doc_type_id', 0)
-                ->groupEnd()
-                ->findAll();
+            ->where('is_active', 1)
+            ->where('client_id', $client_id)
+            ->groupStart()
+            ->where('kyc_doc_type_id', null)
+            ->orWhere('kyc_doc_type_id', 0)
+            ->groupEnd()
+            ->findAll();
 
         $result['client_id'] = $client_id;
         $table = view('client_kyc_other_table', $result);
@@ -2647,7 +2767,7 @@ class ClientController extends AdminController
             // $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
             // $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
             // $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
-            
+
             $fields = [
                 'waiverofpreexistingdiseases' => false,
                 'waiverof1,2,3&4thyearexclusions' => false,
@@ -2694,17 +2814,17 @@ class ClientController extends AdminController
                 'special_condition_input' => true,
                 'multiple_sum_insured' => true,
             ];
-                       
+
             foreach ($fields as $field => $needsCleanup) {
                 $value = $this->request->getPost($field);
-            
+
                 if ($value !== null && $value !== '') {
                     $data[$field] = $needsCleanup ? str_replace(',', '', $value) : $value;
-                }else{
-                     $data[$field] = $value;
+                } else {
+                    $data[$field] = $value;
                 }
             }
-            
+
             $data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
             $this->myLogger->logme('error', "contructed post data : " . json_encode($data ?? []));
             // print_r($data);die;
@@ -2747,11 +2867,11 @@ class ClientController extends AdminController
     //     if ($this->request->getPost("waiverofpreexistingdiseases_display")) {
     //         $data['Waiver of Pre-existing Diseases'] = $this->request->getPost("waiverofpreexistingdiseases");
     //     }
-        
+
     //     if ($this->request->getPost("waiverof1234thyearexclusions_display")) {
     //         $data['Waiver of 1, 2, 3 & 4th year Exclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
     //     }
-        
+
     //     if ($this->request->getPost("waiverof30dayswaitingperiod_display")) {
     //         $data['Waiver of 30 days waiting period'] = $this->request->getPost("waiverof30dayswaitingperiod");
     //     }
@@ -2759,157 +2879,157 @@ class ClientController extends AdminController
     //     if ($this->request->getPost("suminsuredenhancement_display")) {
     //         $data['Sum Insured Enhancement'] = $this->request->getPost("suminsuredenhancement");
     //     }
-        
+
     //     if ($this->request->getPost("waiver_of_90_days_waiting_period_display")) {
     //         $data['Waiver of 90 Days Waiting Period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
     //     }
-        
+
     //     if ($this->request->getPost("waiver_of_other_waiting_periods_display")) {
     //         $data['Waiver of Other Waiting Periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
     //     }
-        
+
     //     if ($this->request->getPost("maternity_benefit_display")) {
     //         $data['Maternity Benefit'] = $this->request->getPost("maternity_benefit");
     //     }
-        
+
     //     if ($this->request->getPost("9monthwaitingperiodwaived_display")) {
     //         $data['9-month waiting Period - waived'] = $this->request->getPost("9monthwaitingperiodwaived");
     //     }
-        
+
     //     if ($this->request->getPost("maternitycoverage_display")) {
     //         $data['Maternity Coverage'] = $this->request->getPost("maternitycoverage");
     //     }
-        
+
     //     if ($this->request->getPost("twindelivery_display")) {
     //         $data['Twin Delivery'] = $this->request->getPost("twindelivery");
     //     }
-        
+
     //     if ($this->request->getPost("well_baby_well_mother_expenses_display")) {
     //         $data['Well baby / Well Mother Expenses'] = $this->request->getPost("well_baby_well_mother_expenses");
     //     }
-        
+
     //     if ($this->request->getPost("preandpostnatal_display")) {
     //         $data['Pre and Post natal'] = $this->request->getPost("preandpostnatal");
     //     }
-        
+
     //     if ($this->request->getPost("infertility_treatment_coverage_display")) {
     //         $data['Infertility Treatment Coverage'] = $this->request->getPost("infertility_treatment_coverage");
     //     }
-        
+
     //     if ($this->request->getPost("babyday1cover_display")) {
     //         $data['Baby Day 1 Cover'] = $this->request->getPost("babyday1cover");
     //     }
-        
+
     //     if ($this->request->getPost("coverfromthedateofjoining_display")) {
     //         $data['Cover from the date of Joining'] = $this->request->getPost("coverfromthedateofjoining");
     //     }
-        
+
     //     if ($this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse_display")) {
     //         $data['Mid Term Addition of New Born / Newly Wedded Spouse'] = $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse");
     //     }
-        
+
     //     if ($this->request->getPost("prehospitalizationcover_display")) {
     //         $data['Pre Hospitalization Cover'] = $this->request->getPost("prehospitalizationcover");
     //     }
-        
+
     //     if ($this->request->getPost("posthospitalizationcover_display")) {
     //         $data['Post Hospitalization Cover'] = $this->request->getPost("posthospitalizationcover");
     //     }
-        
+
     //     if ($this->request->getPost("congenitaldiseasesinternal_display")) {
     //         $data['Congenital Diseases - Internal'] = $this->request->getPost("congenitaldiseasesinternal");
     //     }
-        
+
     //     if ($this->request->getPost("congenitaldiseasesexternal_display")) {
     //         $data['Congenital Diseases - External'] = $this->request->getPost("congenitaldiseasesexternal");
     //     }
-        
+
     //     if ($this->request->getPost("copayzonewisecopay_display")) {
     //         $data['Co-Pay/Zone wise Co Pay'] = $this->request->getPost("copayzonewisecopay");
     //     }
-        
+
     //     if ($this->request->getPost("roomrentlimit_display")) {
     //         $data['Room Rent Limit'] = $this->request->getPost("roomrentlimit");
     //     }
-        
+
     //     if ($this->request->getPost("icu_limit_display")) {
     //         $data['ICU Limit'] = $this->request->getPost("icu_limit");
     //     }
-        
+
     //     if ($this->request->getPost("proportionatedeductionclause_display")) {
     //         $data['Proportionate Deduction Clause'] = $this->request->getPost("proportionatedeductionclause");
     //     }
-        
+
     //     if ($this->request->getPost("ailmentcapping_display")) {
     //         $data['Ailment capping'] = $this->request->getPost("ailmentcapping");
     //     }
-        
+
     //     if ($this->request->getPost("ailment_capping_details_display")) {
     //         $data['Ailment capping Details'] = $this->request->getPost("ailment_capping_details");
     //     }
-        
+
     //     if ($this->request->getPost("corporatebuffer_display")) {
     //         $data['Corporate Buffer'] = $this->request->getPost("corporatebuffer");
     //     }
-        
+
     //     if ($this->request->getPost("non_admissible_contingency_corporate_buffer_display")) {
     //         $data['Non-Admissible / Contingency Corporate Buffer'] = $this->request->getPost("non_admissible_contingency_corporate_buffer");
     //     }
-        
+
     //     if ($this->request->getPost("ambulancecharges_display")) {
     //         $data['Ambulance Charges'] = $this->request->getPost("ambulancecharges");
     //     }
-        
+
     //     if ($this->request->getPost("airambulance_display")) {
     //         $data['Air Ambulance'] = $this->request->getPost("airambulance");
     //     }
-        
+
     //     if ($this->request->getPost("reasonableandcustomarycharges_display")) {
     //         $data['Reasonable and Customary Charges'] = $this->request->getPost("reasonableandcustomarycharges");
     //     }
-        
+
     //     if ($this->request->getPost("daycaretreatment_display")) {
     //         $data['Day Care Treatment'] = $this->request->getPost("daycaretreatment");
     //     }
-        
+
     //     if ($this->request->getPost("lasiksurgery_display")) {
     //         $data['Lasik Surgery'] = $this->request->getPost("lasiksurgery");
     //     }
-        
+
     //     if ($this->request->getPost("ayushtreatmentcover_display")) {
     //         $data['AYUSH treatment cover'] = $this->request->getPost("ayudhtreatmentcover");
     //     }
-        
+
     //     if ($this->request->getPost("moderntreatmentsasperirdai_display")) {
     //         $data['Modern treatments as per IRDAI'] = $this->request->getPost("moderntreatmentsasperirdai");
     //     }
-        
+
     //     if ($this->request->getPost("opd_treatment_display")) {
     //         $data['OPD Treatment'] = $this->request->getPost("opd_treatment");
     //     }
-        
+
     //     if ($this->request->getPost("days_of_discharge_display")) {
     //         $data['Claim Intimation Clause'] = $this->request->getPost("days_of_discharge");
     //     }
-        
+
     //     if ($this->request->getPost("days_from_dod_display")) {
     //         $data['Claim Submission'] = $this->request->getPost("days_from_dod");
     //     }
-        
+
     //     if ($this->request->getPost("terrorism_display")) {
     //         $data['Terrorism'] = $this->request->getPost("terrorism");
     //     }
-        
+
     //     if ($this->request->getPost("widower_cover_display")) {
     //         $data['Widower Cover'] = $this->request->getPost("widower_cover");
     //     }
-        
+
     //     if ($this->request->getPost("breavement_cover_display")) {
     //         $data['Breavement Cover'] = $this->request->getPost("breavement_cover");
     //     }
 
     //     if ($this->request->getPost("special_condition_display_value")) {
-            
+
     //         $specialConditionKeyValue = $this->request->getPost("special_condition_display_value") ?? [];
     //         $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
 
@@ -2918,14 +3038,14 @@ class ClientController extends AdminController
     //             $data = array_merge($data, $mergedArray);
     //         }
     //     }
-        
+
     //     if(isset($data) && !empty($data)){
     //         return $data;
     //     }else{
     //         $data = [];
     //         return $data;
     //     }
-    
+
     // }
 
     public function enrollmentGMCDisplayValueTransform()
@@ -3092,7 +3212,7 @@ class ClientController extends AdminController
                 'gpa_special_condition_input',
                 'multiple_sum_insured',
             ];
-            
+
             $fieldsWithoutCommaRemoval = [
                 'permanentPartialDisablement',
                 'temporaryTotalDisablementBenefit',
@@ -3109,27 +3229,27 @@ class ClientController extends AdminController
                 'animalSnakeInsectBite',
                 'air_ambulance'
             ];
-            
+
             // Remove commas and assign if present
             foreach ($fieldsWithCommaRemoval as $field) {
                 $value = $this->request->getPost($field);
                 if ($value !== null) {
                     $data[$field] = str_replace(',', '', $value);
-                }else{
-                     $data[$field] = $value;
+                } else {
+                    $data[$field] = $value;
                 }
             }
-            
+
             // Direct assign if present
             foreach ($fieldsWithoutCommaRemoval as $field) {
                 $value = $this->request->getPost($field);
                 if ($value !== null) {
                     $data[$field] = $value;
-                }else{
-                     $data[$field] = $value;
+                } else {
+                    $data[$field] = $value;
                 }
             }
-            
+
             $data['enrollment_display_key'] = $this->enrollmentGPADisplayValueTransform();
 
             // print_r($data); die;
@@ -3819,10 +3939,10 @@ class ClientController extends AdminController
 
         $cd_data = array_merge($cd_data, $client_cd_data);
 
-        if($return_type == "internal"){
-            if(!empty($cd_data)){
+        if ($return_type == "internal") {
+            if (!empty($cd_data)) {
                 return $cd_data;
-            }else{
+            } else {
                 return [];
             }
         }
@@ -3850,7 +3970,7 @@ class ClientController extends AdminController
 
         $client_policy_id = $this->request->getPost("client_policy_id");
         $policy_terms = $this->request->getPost("policy_terms");
-        $policy_terms = json_decode($policy_terms, true); 
+        $policy_terms = json_decode($policy_terms, true);
 
         $data = [];
 
@@ -3858,12 +3978,11 @@ class ClientController extends AdminController
 
             if (str_ends_with($key, '_display')) {
 
-                $original_key = substr($key, 0, -8); 
+                $original_key = substr($key, 0, -8);
 
                 $newKey = implode(' ', array_map('ucfirst', explode('_', $original_key)));
 
                 $data['enrollment_display_key'][$newKey] = $policy_terms[$original_key] ?? " ";
-
             } else {
 
                 $data[$key] = $value;
@@ -3871,10 +3990,10 @@ class ClientController extends AdminController
         }
 
         if (!empty($data)) {
-            $policy_terms['is_payable_employee']['self'] = 0; 
-            $policy_terms = json_encode($data); 
+            $policy_terms['is_payable_employee']['self'] = 0;
+            $policy_terms = json_encode($data);
         }
-        
+
 
         $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
 
@@ -4296,9 +4415,9 @@ class ClientController extends AdminController
         // -----------for vehicle ---------------------------------------------------------------------------
 
         $vehicles = $this->vehicleModel
-        ->select('vehicle.*, clients.client_type')
-        ->join('clients', 'clients.id=vehicle.owner')
-        ->where('vehicle.is_active', 1)->findAll();
+            ->select('vehicle.*, clients.client_type')
+            ->join('clients', 'clients.id=vehicle.owner')
+            ->where('vehicle.is_active', 1)->findAll();
 
         // -----------for Insurer ---------------------------------------------------------------------------
 
@@ -4421,12 +4540,12 @@ class ClientController extends AdminController
         $cd_data = array_merge($cd_data, $client_cd_data);
 
         if (!empty($cd_data)) {
-            return $this->respond([ 'status' => true,'code' => 200, 'data' => $cd_data], 200);
+            return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200);
         } else {
-            return $this->respond(['status' => false,'code' => 404,'client_id' => $client_id,'insurer_id' => $insurer_id,'insurer_branch_id' => $insurer_branch_id ], 200);
+            return $this->respond(['status' => false, 'code' => 404, 'client_id' => $client_id, 'insurer_id' => $insurer_id, 'insurer_branch_id' => $insurer_branch_id], 200);
         }
     }
-    
+
     // public function getCDAccNoByClientAndInsurer($client, $insurer, $insurer_branch_id)
     // {
     //     $cdmData = $this->CDMasterModel
@@ -4461,7 +4580,7 @@ class ClientController extends AdminController
         // Add additional fields if client type is 2
         if ($client_type == 2) {
             $client_data = array_merge($client_data, [
-                'dob' => change_date_format($postData['dob'],'d/m/Y','Y-m-d'),
+                'dob' => change_date_format($postData['dob'], 'd/m/Y', 'Y-m-d'),
                 'aadhar' => $postData['aadhar'],
                 'phone' => $postData['phone'],
                 'entity_type_id' => 7
@@ -4519,7 +4638,7 @@ class ClientController extends AdminController
         $client_type = $postData['client_type'] ?? null;
 
         $client_insert = null;
-        if($client_type == 2){
+        if ($client_type == 2) {
 
             $client_data = [
                 'client_type' => $postData['client_type'],
@@ -4530,8 +4649,7 @@ class ClientController extends AdminController
             ];
 
             $client_insert = $this->clientModel->insert($client_data);
-
-        }else if($client_type == 1){
+        } else if ($client_type == 1) {
 
             $client_data = [
                 'client_type' => $postData['client_type'],
@@ -4539,10 +4657,10 @@ class ClientController extends AdminController
                 'short_name' => $postData['short_name'] ?? $postData['client_name'],
                 'client_code' => generate_client_code(),
                 'entity_type_id' => 2
-            ]; 
-        
-             $client_insert = $this->clientModel->insert($client_data);
-        }        
+            ];
+
+            $client_insert = $this->clientModel->insert($client_data);
+        }
 
         if (!$client_insert) {
             return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200);
@@ -4551,11 +4669,11 @@ class ClientController extends AdminController
         // Additional logic for non-individual clients (client_type != 2)
         $branch_insert = null;
         if ($client_type != 2) {
-            $unit[] = $postData['short_name'] . '-' . 001;
+            $unit[] = $postData['short_name'] . '-' . $postData['branch_code'] ?? 001;
             $branch_data = [
                 'client_id' => $client_insert,
                 'branch_name' => $postData['branch_name'],
-                'branch_code' => 001,
+                'branch_code' => $postData['branch_code'] ?? 001,
                 'gst' => $postData['gst'],
                 'units' => json_encode($unit) ?? null,
             ];
@@ -4567,6 +4685,7 @@ class ClientController extends AdminController
                     'contact_type' => 'client',
                     'name' => $postData['name'],
                     'email' => $postData['email'],
+                    'mobile' => $postData['mobile'] ?? null,
                 ];
                 $this->levelContactModel->insert($contact_data);
             }
@@ -4582,7 +4701,7 @@ class ClientController extends AdminController
             ->where('client_id', $client_insert)
             ->where('is_active', 1)
             ->findAll();
-            
+
         return $this->respond([
             'status' => true,
             'data' => $postData,
@@ -4613,12 +4732,12 @@ class ClientController extends AdminController
             $vehicle_insert = $this->vehicleModel->insert($data);
 
             if ($vehicle_insert) {
-                
+
                 // $vehicles = $this->vehicleModel->where('is_active', 1)->findAll();
                 $vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type')
-                            ->join('clients', 'clients.id=vehicle.owner')
-                            ->where('vehicle.is_active', 1)
-                            ->findAll();
+                    ->join('clients', 'clients.id=vehicle.owner')
+                    ->where('vehicle.is_active', 1)
+                    ->findAll();
 
                 return $this->respond([
                     'status' => true,
@@ -4656,7 +4775,6 @@ class ClientController extends AdminController
                 ];
 
                 $client_insert = $this->clientModel->insert($client_data);
-
             } else if ($client_type == 1) {
 
                 $client_data = [
@@ -4717,7 +4835,7 @@ class ClientController extends AdminController
                     ->where('is_active', 1)
                     ->findAll();
 
-                    // Fetch branches in a single query
+                // Fetch branches in a single query
                 $branches = $this->clientBranchModel
                     ->where('client_id', $client_insert)
                     ->where('is_active', 1)
@@ -4734,11 +4852,9 @@ class ClientController extends AdminController
                     'vehicles' => $vehicles,
                     'message' => 'Vehicle created successfully'
                 ], 200);
-
             } else {
                 return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
             }
-
         } else if (isset($data['owner']) && !empty($data['owner'])) {
 
             $vehicle_data = [
@@ -4750,7 +4866,7 @@ class ClientController extends AdminController
             ];
 
             $vehicle_insert = $this->vehicleModel->insert($vehicle_data);
-            
+
             $vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type')
                 ->join('clients', 'clients.id = vehicle.owner')
                 ->where('vehicle.is_active', 1)
@@ -4761,7 +4877,7 @@ class ClientController extends AdminController
                 ->where('is_active', 1)
                 ->findAll();
 
-                // Fetch branches in a single query
+            // Fetch branches in a single query
             $branches = $this->clientBranchModel
                 ->where('client_id', $data['owner'])
                 ->where('is_active', 1)
@@ -4780,7 +4896,6 @@ class ClientController extends AdminController
                     'vehicles' => $vehicles,
                     'message' => 'Vehicle created successfully'
                 ], 200);
-                
             } else {
                 return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
             }
@@ -4928,7 +5043,7 @@ class ClientController extends AdminController
     //                 return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200);
     //             }
     //         }
-            
+
     //     } else {
     //         return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200);
     //     }
@@ -4944,10 +5059,10 @@ class ClientController extends AdminController
         $client_type = $this->request->getGet('client_type');
 
         $data = $this->policyTransactionModel
-                        ->where('is_active', 1)
-                        ->where('action_type', 'inception')
-                        ->where('policy_no', $policy_no)
-                        ->countAllResults();
+            ->where('is_active', 1)
+            ->where('action_type', 'inception')
+            ->where('policy_no', $policy_no)
+            ->countAllResults();
 
         if ($data > 0) {
             return $this->respond(['status' => true, 'message' => 'This policy number is already linked to another client', 'data' => $data, 'code' => 409, 'received_data' => $received_data], 200);
@@ -4957,7 +5072,7 @@ class ClientController extends AdminController
     }
 
     public function get_client_policy_data_using_policy_no_and_endo_no()
-    {   
+    {
         $policy_no = $this->request->getGet('policy_no');
         $endorsement_no = $this->request->getGet('endorsement_no');
 
@@ -4980,10 +5095,10 @@ class ClientController extends AdminController
     {
         if ($id) {
             $branch_data = $this->clientBranchModel
-                    ->select('client_branch.*, clients.pan')
-                    ->join('clients', 'client_branch.client_id = clients.id')
-                    ->where(['client_branch.id' => $id, 'client_branch.is_active' => 1])
-                    ->first();
+                ->select('client_branch.*, clients.pan')
+                ->join('clients', 'client_branch.client_id = clients.id')
+                ->where(['client_branch.id' => $id, 'client_branch.is_active' => 1])
+                ->first();
             $branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->findAll();
             // print_rr($branch_contact_data);die();
             return $this->respond(['status' => true, 'code' => 200, 'data' => $branch_data, 'contact' => $branch_contact_data], 200);
@@ -4993,7 +5108,7 @@ class ClientController extends AdminController
     }
 
     public function getClientData()
-    {   
+    {
         $client_id = $this->request->getGet('client_id') ?? null;
         $result = $this->clientModel->getClientData($client_id);
         dd($result);
@@ -5010,17 +5125,17 @@ class ClientController extends AdminController
             ->where("policy_terms IS NOT NULL AND policy_terms <> ''")
             ->where('is_active', 1);
 
-        
+
         if (!empty($client_id)) {
             $query->where('client_id', $client_id);
         }
-        
+
         if (!empty($policy_type_id)) {
             $query->where('policy_type_id', $policy_type_id);
         }
-        
+
         $data = $query->findAll();
-        
+
         for ($i = 0; $i < count($data); $i++) {
 
             // dd($data[$i]);
@@ -5036,30 +5151,28 @@ class ClientController extends AdminController
             $is_addon = $data[$i]['is_addon'];
 
             $payable_arr = [];
-            if (in_array($data[$i]['policy_type_id'], [2,3]) && $is_addon == 1) {
-
-                $payable_arr = [ "self" => 0, "spouse" => 0, "childern" => 0, "elders" => 0, ];
+            if (in_array($data[$i]['policy_type_id'], [2, 3]) && $is_addon == 1) {
 
+                $payable_arr = ["self" => 0, "spouse" => 0, "childern" => 0, "elders" => 0,];
             } else if ($data[$i]['policy_type_id'] == 3 && $is_addon == 3) {
 
-                $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,];
-
+                $payable_arr = ["self" => 1, "spouse" => 1, "childern" => 1, "elders" => 1,];
             } else if (in_array($data[$i]['policy_type_id'], [4, 5])) {
 
-                $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,];
+                $payable_arr = ["self" => 1, "spouse" => 1, "childern" => 1, "elders" => 1,];
             }
 
             // Initialize an empty array for the ordered policy terms
             $orderedPolicyTerms = [];
 
-            if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){
+            if (in_array($data[$i]['policy_type_id'], [2, 3, 4, 5])) {
 
                 // Set default value of copayzonewisecopay to "empty"
                 // $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty';
 
                 // add is_payable_employee for the GMC Policy
                 if (isset($policyTerms['age_ratio'])) {
-                    if(!isset($policyTerms['is_payable_employee'])){
+                    if (!isset($policyTerms['is_payable_employee'])) {
                         $aliment_index = array_search('age_ratio', array_keys($policyTerms));
                         $orderedPolicyTerms[] = [
                             "key" => "is_payable_employee",
@@ -5097,7 +5210,7 @@ class ClientController extends AdminController
 
                 // Add ailmentcapping and ailmentcappingdata if they exist
                 if (isset($policyTerms['ailmentcapping'])) {
-                    if(!isset($policyTerms['ailment_capping_details'])){
+                    if (!isset($policyTerms['ailment_capping_details'])) {
                         $aliment_index = array_search('ailmentcapping', array_keys($policyTerms));
                         $orderedPolicyTerms[] = [
                             "key" => "ailment_capping_details",
@@ -5106,12 +5219,11 @@ class ClientController extends AdminController
                         ];
                     }
                 }
-
-            }else {
+            } else {
 
                 // add is_payable_employee for the GMC Policy
                 if (isset($policyTerms['age_ratio'])) {
-                    if(!isset($policyTerms['is_payable_employee'])){
+                    if (!isset($policyTerms['is_payable_employee'])) {
                         $aliment_index = array_search('age_ratio', array_keys($policyTerms));
                         $orderedPolicyTerms[] = [
                             "key" => "is_payable_employee",
@@ -5121,9 +5233,9 @@ class ClientController extends AdminController
                             "position" => $aliment_index + 1,
                         ];
                     }
-                }else{
+                } else {
 
-                    if(!isset($policyTerms['is_payable_employee'])){
+                    if (!isset($policyTerms['is_payable_employee'])) {
                         $orderedPolicyTerms[] = [
                             "key" => "is_payable_employee",
                             "value" => [
@@ -5133,7 +5245,6 @@ class ClientController extends AdminController
                         ];
                     }
                 }
-
             }
 
             foreach ($orderedPolicyTerms as $term) {
@@ -5155,12 +5266,12 @@ class ClientController extends AdminController
                 }
             }
 
-            if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){
+            if (in_array($data[$i]['policy_type_id'], [2, 3, 4, 5])) {
 
                 if (!isset($policyTerms['waiver_of_90_days_waiting_period'])) {
                     $policyTerms['waiver_of_90_days_waiting_period'] = "";
                 }
-                
+
                 if (!isset($policyTerms['waiver_of_other_waiting_periods'])) {
                     $policyTerms['waiver_of_other_waiting_periods'] = "";
                 }
@@ -5168,7 +5279,7 @@ class ClientController extends AdminController
                 if (!isset($policyTerms['maternity_benefit'])) {
                     $policyTerms['maternity_benefit'] = "";
                 }
-                
+
                 if (!isset($policyTerms['well_baby_well_mother_expenses'])) {
                     $policyTerms['well_baby_well_mother_expenses'] = "";
                 }
@@ -5196,61 +5307,59 @@ class ClientController extends AdminController
                 if (!isset($policyTerms['widower_cover'])) {
                     $policyTerms['widower_cover'] = "";
                 }
-                
+
                 if (!isset($policyTerms['breavement_cover'])) {
                     $policyTerms['breavement_cover'] = "";
                 }
-                
+
                 if (!isset($policyTerms['enrollment_display_key'])) {
                     $policyTerms['enrollment_display_key'] = $this->existingGMCDisplayValueTransform($policyTerms);
                 }
-
-            } else if($data[$i]['policy_type_id'] == 1){
+            } else if ($data[$i]['policy_type_id'] == 1) {
 
                 if (!isset($policyTerms['medical_expenses_medical_extension'])) {
                     $policyTerms['medical_expenses_medical_extension'] = "";
                 }
-                
+
                 if (!isset($policyTerms['opd_treatment_cover'])) {
                     $policyTerms['opd_treatment_cover'] = "";
                 }
-                
+
                 if (!isset($policyTerms['repatriation_of_mortal_remains'])) {
                     $policyTerms['repatriation_of_mortal_remains'] = "";
                 }
-                
+
                 if (!isset($policyTerms['family_transportation_benefits'])) {
                     $policyTerms['family_transportation_benefits'] = "";
                 }
-                
+
                 if (!isset($policyTerms['fractures_dislocation_burns'])) {
                     $policyTerms['fractures_dislocation_burns'] = "";
                 }
-                
+
                 if (!isset($policyTerms['coma'])) {
                     $policyTerms['coma'] = "";
                 }
-                
+
                 if (!isset($policyTerms['travel_expenses_for_medical_treatment'])) {
                     $policyTerms['travel_expenses_for_medical_treatment'] = "";
                 }
-                
+
                 if (!isset($policyTerms['daily_cash_allowance'])) {
                     $policyTerms['daily_cash_allowance'] = "";
                 }
-                
+
                 if (!isset($policyTerms['artifical_limb_and_prosthesis'])) {
                     $policyTerms['artifical_limb_and_prosthesis'] = "";
                 }
-                
+
                 if (!isset($policyTerms['air_ambulance'])) {
                     $policyTerms['air_ambulance'] = "";
                 }
-                                
+
                 if (!isset($policyTerms['enrollment_display_key'])) {
                     $policyTerms['enrollment_display_key'] = $this->existingGPADisplayValueTransform($policyTerms);
                 }
-                
             }
 
             // dd($policyTerms);
@@ -5431,7 +5540,7 @@ class ClientController extends AdminController
     }
 
     public function existingGPADisplayValueTransform($data)
-    {   
+    {
         $transformedData = [];
 
         if (isset($data["accidentalDeathBenefit"])) {
@@ -5474,7 +5583,7 @@ class ClientController extends AdminController
             $transformedData['Fractures / Dislocation / Burns'] = $data["fractures_dislocation_burns"];
         }
         if (isset($data["coma"])) {
-            $transformedData['Coma'] = $data["coma"]; 
+            $transformedData['Coma'] = $data["coma"];
         }
         if (isset($data["carriageofDeadBody"])) {
             $transformedData['Carriage of Dead Body'] = $data["carriageofDeadBody"];
@@ -5509,24 +5618,24 @@ class ClientController extends AdminController
             ->where('is_active', 1)
             ->get()
             ->getResultArray();
-    
+
         $days = [];
         foreach ($data as $value) {
 
             $reminderDate = strtotime($value['reminder_date']);
             if ($reminderDate) {
                 $date_of_date = date('d', $reminderDate);
-                $days[] = $date_of_date; 
+                $days[] = $date_of_date;
                 $days[] = $value['reminder_date'];
                 db_connect()->table('client_policy')->where('id', $value['id'])->set('reminder_date', $date_of_date)->update();
-            } 
+            }
         }
-    
+
         dd($days);
     }
 
     public function sendextraparam()
-    {   
+    {
         //     $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
         //     // dd($data);
         //    $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true));
@@ -5557,7 +5666,7 @@ class ClientController extends AdminController
         // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']);
         // $res = $empServiceController->employeeDisembark(['file_id' => '1681']); 
         // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']); 
-        dd( $res); 
+        dd($res);
 
         $EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController();
         // $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']); 
@@ -5588,7 +5697,7 @@ class ClientController extends AdminController
             'event_type' => "correction",
             'actions' => "export",
             'file_name' => "deletion_enhancement_test_file.xlsx",
-        ]; 
+        ];
 
         // $batch_data = [
         //     'client_id' => 20,
@@ -5610,7 +5719,7 @@ class ClientController extends AdminController
 
         // $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard(12);
         // $ids = array_column($emp_data, 'id');
-        
+
         $EmpDataServiceController = new EmpDataServiceController();
         // $res = $EmpDataServiceController->generateExcelForDeletion($batch_data); dd($return); die;
         // $res = $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die;
@@ -5636,7 +5745,7 @@ class ClientController extends AdminController
         // ];
         // $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction($params);
         // dd($res);
-        
+
         // $array = [
         //         "employeeIds" => ["12800", "12798", "12797", "12799"],
         //         "client_id" => "159",
@@ -5649,7 +5758,7 @@ class ClientController extends AdminController
         //         "policy_name" => "GMC",
         //         "user_id" => "1"
         // ];
-        
+
         // $EmpDataServiceController->cashDepositCalculationForDeletion($array);
 
         // $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data);
@@ -5679,11 +5788,11 @@ class ClientController extends AdminController
         // dd($res);
 
         // -----------BDS REPORT CONTROLLER---------------------------------------------------------------------------------
-        
+
         // $BDSReportController = new BDSReportController();
 
         // $data['data'] = $BDSReportController->getBAPInsurerData();
-        
+
         // return $this->loadLayout('irda_bap_insurer_report_list', $data);
 
         // $data['data'] = $BDSReportController->getBAPClientData();
@@ -5700,7 +5809,7 @@ class ClientController extends AdminController
         // $email_id = 'venkateshraman786@gmail.com';
         // $common = ['mail_type'=>'test_mail_cli'];
         // $bcc = "vitvelz@gmail.com";
-        
+
         // $data = db_connect()
         // ->table('jobs')
         // ->where('id', 2264)
@@ -5708,7 +5817,7 @@ class ClientController extends AdminController
         // ->getResultArray();
 
         // $data = json_decode($data[0]['payload'], true);
-        
+
         // // dd($data);
         // // Send email and get response
         // $result = MailHelper::send_email($data[0]);
@@ -5722,7 +5831,7 @@ class ClientController extends AdminController
         // print_rr($reportData);
         // $this->loadLayout('tat_report_band_wise_list', $reportData);
         // $data = $ticketModel->getTATReport(1);
-        
+
         // $empmodel = new EmployeeModel();
         // $data = $empmodel->getEmployeePolicy(348);
         // dd($data);
@@ -5786,7 +5895,7 @@ class ClientController extends AdminController
         // $return_value = check_cd_entry_exist($baseWhere);
         // dd($return_value);
 
-        
+
 
 
         // $param = 9715454901;
@@ -5807,7 +5916,7 @@ class ClientController extends AdminController
     }
 
     // -------------------------------------------------------------------------------------------------------
-    
+
 
     public function createOtherTabContent()
     {
@@ -5830,20 +5939,16 @@ class ClientController extends AdminController
     // -------------------------------------------------------------------------------------------------------
 
     public function enrollmentAddonSIAmountDropdown($client_policy_id)
-    {   
-        if(!empty($client_policy_id)){
+    {
+        if (!empty($client_policy_id)) {
             $client_policy_details = $this->clientPolicyModel->where('id', $client_policy_id)->where('policy_status', 1)->where('is_active', 1)->first();
 
-            if(!empty($client_policy_details) && $client_policy_details['policy_type_id'] == 3 && $client_policy_details['is_addon'] == 3){
+            if (!empty($client_policy_details) && $client_policy_details['policy_type_id'] == 3 && $client_policy_details['is_addon'] == 3) {
 
                 $base_policy_id = $client_policy_details['base_policy'] ?? 0;
 
-                if(!empty($base_policy_id)){
-
-                    
-                    
+                if (!empty($base_policy_id)) {
                 }
-
             }
         }
     }
@@ -5853,12 +5958,12 @@ class ClientController extends AdminController
         $cd_ac_pk = $this->request->getGet('cd_ac_pk');
 
         $cd_amount = $this->clientDepositModel
-                ->where('is_active', 1)
-                ->where('cd_ac_pk', $cd_ac_pk)
-                ->orderBy('id', 'desc')
-                ->first();
+            ->where('is_active', 1)
+            ->where('cd_ac_pk', $cd_ac_pk)
+            ->orderBy('id', 'desc')
+            ->first();
 
-        if($cd_amount){
+        if ($cd_amount) {
             return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_amount], 200);
         } else {
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -5907,9 +6012,9 @@ class ClientController extends AdminController
             ->getResultArray();
 
         // print_r(db_connect()->getLastQuery()); die;
-       
+
         $dataForClientAndInsurer = $this->clientPolicyModel
-                ->select("
+            ->select("
                         clients.id AS client_id,
                         clients.client_name,
                         insurers.id AS insurer_id,
@@ -5917,12 +6022,12 @@ class ClientController extends AdminController
                         tpa.id AS tpa_id,
                         tpa.name AS tpa_name,
                     ")
-                ->join('clients', 'client_policy.client_id = clients.id', 'left')
-                ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
-                ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
-                ->where('client_policy.id', $param)
-                ->first();
-                
+            ->join('clients', 'client_policy.client_id = clients.id', 'left')
+            ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
+            ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
+            ->where('client_policy.id', $param)
+            ->first();
+
         $memberData = [];
 
         // Respond based on the query result
@@ -6097,9 +6202,9 @@ class ClientController extends AdminController
     {
         $db = db_connect();
         $renewalData = $db->table('old_renewal_data_copy')
-        ->where('client_id IS NOT NULL')
-        ->where('is_inserted != 1')
-        ->get()
+            ->where('client_id IS NOT NULL')
+            ->where('is_inserted != 1')
+            ->get()
             ->getResultArray();
         // dd($renewalData);
 
@@ -6123,8 +6228,8 @@ class ClientController extends AdminController
 
             // Update is_inserted field in DB
             $db->table('old_renewal_data_copy')
-            ->where('id', $value['id'])
-            ->set(['is_inserted' => 1])
+                ->where('id', $value['id'])
+                ->set(['is_inserted' => 1])
                 ->update();
 
             $successData[] = ['id' => $value['id'], 'client' => $value['insured']];
@@ -6137,8 +6242,8 @@ class ClientController extends AdminController
     {
         $db = db_connect();
         $renewalData = $db->table('old_renewal_data_copy')
-        ->where('insurer_id IS NULL')
-        ->get()
+            ->where('insurer_id IS NULL')
+            ->get()
             ->getResultArray();
         // dd($renewalData);
 
@@ -6165,11 +6270,11 @@ class ClientController extends AdminController
 
             // Update is_inserted field in DB
             $db->table('old_renewal_data_copy')
-            ->where('id', $value['id'])
-            ->set([
-                'insurer_id' => $value['insurer_id'],
-                'insurer_branch_id' => $value['insurer_branch_id'],
-            ])
+                ->where('id', $value['id'])
+                ->set([
+                    'insurer_id' => $value['insurer_id'],
+                    'insurer_branch_id' => $value['insurer_branch_id'],
+                ])
                 ->update();
 
             $successData[] = ['id' => $value['id'], 'insurer' => $value['insurer_name'], 'insurer_id' => $value['insurer_id'], 'insurer_branch_id' => $value['insurer_branch_id'],];
@@ -6184,9 +6289,9 @@ class ClientController extends AdminController
         $group = $this->request->getGet('group') ?? 2;
         $db = db_connect();
         $renewalData = $db->table('old_renewal_data_copy')
-        ->where('client_id IS NULL')
-        ->where('is_inserted = 0')
-        ->where('client_type_id', $group)
+            ->where('client_id IS NULL')
+            ->where('is_inserted = 0')
+            ->where('client_type_id', $group)
             // ->limit($limit)
             ->get()
             ->getResultArray();
@@ -6221,8 +6326,8 @@ class ClientController extends AdminController
 
             // Update is_inserted field in DB
             $db->table('old_renewal_data_copy')
-            ->where('id', $value['id'])
-            ->set(['is_inserted' => 1])
+                ->where('id', $value['id'])
+                ->set(['is_inserted' => 1])
                 ->update();
 
             $successData[] = ['id' => $value['id'], 'client' => $value['insured'], 'vehicle_id' => $value['vehicle_id']];
@@ -6313,8 +6418,8 @@ class ClientController extends AdminController
         }
 
         $vehicleData = $VehicleModel->where('owner', $renewalData['client_id'])
-        ->where('is_active', 1)
-        ->findAll();
+            ->where('is_active', 1)
+            ->findAll();
 
         if (!empty($vehicleData)) {
             $increment = count($vehicleData);
@@ -6554,17 +6659,17 @@ class ClientController extends AdminController
         return $id;
     }
 
-    private function reorderProposalsByInsurerTotal(array $data): array 
+    private function reorderProposalsByInsurerTotal(array $data): array
     {
 
         Kint::dump($data);
         if (!isset($data['premium_data']['data'])) return $data;
-    
+
         $original = $data['premium_data']['data'];
         $proposals = [];
         $others = [];
         $emptyKeyData = [];
-    
+
         foreach ($original as $key => $value) {
             // Match only keys that look like 'Proposal X'
             if (preg_match('/^Proposal\s+\d+$/', $key)) {
@@ -6573,7 +6678,7 @@ class ClientController extends AdminController
                     if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
                         $proposals[$key] = $value;
                         break;
-                    }else{
+                    } else {
                         $proposals[$key] = $value;
                     }
                 }
@@ -6582,51 +6687,50 @@ class ClientController extends AdminController
                 if ($key === '' && isset($value['']) && is_array($value[''])) {
                     // Capture empty key to push it later
                     $emptyKeyData[$key] = $value;
-                }else{
+                } else {
                     $others[$key] = $value;
-
                 }
             }
         }
-    
+
         // dd($proposals, $others, $emptyKeyData);
         // Sort proposals by their insurer's total
-        uasort($proposals, function($a, $b) {
+        uasort($proposals, function ($a, $b) {
             $totalA = 0;
             $totalB = 0;
-    
+
             foreach ($a as $key => $val) {
                 if ($key !== 'Quote Asked' && isset($val['Total'])) {
                     $totalA = floatval($val['Total']);
                     break;
                 }
             }
-    
+
             foreach ($b as $key => $val) {
                 if ($key !== 'Quote Asked' && isset($val['Total'])) {
                     $totalB = floatval($val['Total']);
                     break;
                 }
             }
-    
+
             return $totalA <=> $totalB;
         });
-    
+
         // Merge back the sorted proposals into the full structure
         $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
         $data = $this->reorderProposalDataByPremiumOrder($data);
         return $data;
     }
 
-    private function reorderProposalDataByPremiumOrder(array $data): array 
+    private function reorderProposalDataByPremiumOrder(array $data): array
     {
         if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
             return $data;
         }
-    
+
         $premiumProposals = array_keys($data['premium_data']['data']);
         $filteredProposals = [];
-    
+
         // Collect proposal keys that match the pattern "Proposal X"
         foreach ($premiumProposals as $key) {
             if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
@@ -6635,13 +6739,13 @@ class ClientController extends AdminController
         }
 
         // dd($premiumProposals, $filteredProposals);
-    
+
         $data['proposal_data']['over_all_column_data'] = $filteredProposals;
         $data = $this->reorderProposalInHeaderAndData($data);
         return $data;
     }
-    
-    private function reorderProposalInHeaderAndData(array $data): array 
+
+    private function reorderProposalInHeaderAndData(array $data): array
     {
 
         // Kint::dump($data);
@@ -6649,7 +6753,7 @@ class ClientController extends AdminController
         $sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
         $headers = $tableData['headers'] ?? [];
         $dataRows = $tableData['data'] ?? [];
-    
+
         // Step 1: Separate static and proposal headers
         $staticHeaders = [];
         $proposalHeaders = [];
@@ -6658,16 +6762,16 @@ class ClientController extends AdminController
             if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
                 $proposalHeaders[$header['parentHeader']] = $header;
             } else {
-                if($header['parentHeader'] == "Action"){
+                if ($header['parentHeader'] == "Action") {
                     $actionHeader[] = $header;
-                }else{
+                } else {
                     $staticHeaders[] = $header;
                 }
             }
         }
-    
+
         // dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
-        
+
         // Step 2: Reorder headers
         $reorderedHeaders = [];
         foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
@@ -6681,29 +6785,29 @@ class ClientController extends AdminController
             $value['parentHeader'] = 'Proposal ' . ($key + 1);
         }
         unset($value);
-        
+
 
         $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
 
-    
+
         // Step 3: Reorder each row's `data` by matching parentth
         foreach ($dataRows as $dataRowIndex => &$row) {
             $staticData = [];
             $proposalData = [];
             $actionData = [];
-    
+
             foreach ($row['data'] as $entry) {
                 if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
                     $proposalData[$entry['parentth']][] = $entry;
                 } else {
-                    if($entry['parentth'] == "Action"){
+                    if ($entry['parentth'] == "Action") {
                         $actionData[] = $entry;
-                    }else{
+                    } else {
                         $staticData[] = $entry;
                     }
                 }
             }
-    
+
             $reorderedProposalData = [];
             foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
                 if (isset($proposalData[$proposalKey])) {
@@ -6717,19 +6821,19 @@ class ClientController extends AdminController
             $increament = 0;
             foreach ($reorderedProposalData as $key => &$value) {
 
-                if($dubParTh == $value['parentth']){
+                if ($dubParTh == $value['parentth']) {
                     $value['parentth'] = 'Proposal ' . ($increament);
-                }else{
+                } else {
                     $dubParTh = $value['parentth'];
                     $increament = $increament + 1;
                     $value['parentth'] = 'Proposal ' . ($increament);
                 }
             }
             unset($value);
-    
+
             $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
         }
-    
+
         $data['table_data']['headers'] = $reorderedHeaders;
         $data['table_data']['data'] = $dataRows;
 
@@ -6738,15 +6842,15 @@ class ClientController extends AdminController
         $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
         $data['proposal_data']['over_all_column_data'] =  !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
         $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
-        
+
         return $data;
     }
-     
-    private function renumberProposalKeys(array $input): array 
+
+    private function renumberProposalKeys(array $input): array
     {
         $result = [];
         $counter = 1;
-    
+
         foreach ($input as $key => $value) {
             if (strpos($key, 'Proposal') === 0) {
                 $newKey = 'Proposal ' . $counter++;
@@ -6755,7 +6859,7 @@ class ClientController extends AdminController
                 $result[$key] = $value;
             }
         }
-    
+
         return $result;
     }
 
@@ -6764,20 +6868,18 @@ class ClientController extends AdminController
 
         $receivedData = $this->request->getPost();
 
-        if (!empty($receivedData['id'])){
+        if (!empty($receivedData['id'])) {
             $status = $this->clientApi->save($receivedData);
-
-        }else{
+        } else {
             $status = $this->clientApi->insert($receivedData);
         }
 
 
-        if ($status){
-            return $this->respond(['status'=>"Sucesss",'message'=>"Submitted Successfully"],200);
-        }else{
-            return $this->respond(['status'=>"Failed",'message'=>"Submission Faild"],500);
+        if ($status) {
+            return $this->respond(['status' => "Sucesss", 'message' => "Submitted Successfully"], 200);
+        } else {
+            return $this->respond(['status' => "Failed", 'message' => "Submission Faild"], 500);
         }
-
     }
 
     public function sendToken()
@@ -6787,17 +6889,17 @@ class ClientController extends AdminController
 
         $token = ClientTokenHelper::generateKey($client_id);
 
-        if ($token){
-            return $this->respond(['status' => 'success', 'token' => $token,'message' => "Token Generated Successfully"],200);
-        }else{
-            return $this->respond(['status' => "Failed","message"=>"Token Generation Failed, Try Again After some time"],500);
+        if ($token) {
+            return $this->respond(['status' => 'success', 'token' => $token, 'message' => "Token Generated Successfully"], 200);
+        } else {
+            return $this->respond(['status' => "Failed", "message" => "Token Generation Failed, Try Again After some time"], 500);
         }
     }
-    
+
     // ---------------- HR ACCESS CONTROL -----------------------------------------------------------------------------------
 
     public function viewHrAccessData()
-    {   
+    {
         $client_id = $this->request->getGet('client_id');
         $data = $this->getHrAccessData($client_id);
         // $data = [];
@@ -6817,7 +6919,8 @@ class ClientController extends AdminController
         $post_client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first();
 
         $hrAccessData['post_hr_data'] = $this->clientBranchModel
-            ->select('lc.id as post_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail')
+            ->select('lc.id as post_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail , 
+            client_branch.id as post_branch_id , client_branch.branch_name as post_branch_name')
             ->join('level_contacts lc', 'client_branch.id = lc.ref_id')
             ->where('client_branch.is_active', 1)
             ->where('lc.is_active', 1)
@@ -6826,7 +6929,7 @@ class ClientController extends AdminController
             ->findAll();
 
         $hrAccessData['post_policy_data'] = $this->clientPolicyModel
-            ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status')
+            ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status , client_policy.client_branch_id as branch_id')
             ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
             ->where('client_policy.is_active', 1)
             ->where('client_policy.client_id', $client_id)
@@ -6855,22 +6958,31 @@ class ClientController extends AdminController
 
             $hrAccessData['pre_hr_data'] = [];
             $hrAccessData['pre_policy_data'] = [];
-            $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id);
+            $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id , $pre_client_data['id']??'');
             return $combinedHrAccessData;
         }
 
-        $pre_client_data = $db2->table('clients')->where('is_active', 1)->where('short_name', $post_client_data['short_name'])->get()->getRowArray();
+        $post_branch = $this->clientBranchModel->select('pre_branch_id')->where('client_id',$client_id)->get()->getResultArray()[0]??[];
+        
+        $pre_client_data = $db2->table('client_branch cb')
+                                ->join('clients c', "c.id = cb.client_id")
+                                ->where('c.is_active',1)
+                                ->where('cb.is_active', 1)
+                                ->where('cb.id', $post_branch['pre_branch_id']??'')
+                                ->get()->getRowArray();  
 
-        if(empty($pre_client_data)){
+
+        if (empty($pre_client_data)) {
 
             $hrAccessData['pre_hr_data'] = [];
             $hrAccessData['pre_policy_data'] = [];
-            $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id);
+            $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id , $pre_client_data['id']??'');
             return $combinedHrAccessData;
         }
 
         $hrAccessData['pre_hr_data'] = $db2->table('client_branch')
-            ->select('lc.id as pre_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail')
+            ->select('lc.id as pre_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail 
+            , client_branch.id as pre_branch_id , client_branch.branch_name as pre_branch_name ' )
             ->join('level_contacts lc', 'client_branch.id = lc.ref_id')
             ->where('client_branch.is_active', 1)
             ->where('lc.is_active', 1)
@@ -6878,9 +6990,9 @@ class ClientController extends AdminController
             ->where('client_branch.client_id', $pre_client_data['id'])
             ->get()
             ->getResultArray();
-
+        
         $hrAccessData['pre_policy_data'] = $db2->table('client_policy')
-            ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status')
+            ->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status , client_policy.client_branch_id as branch_id')
             ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
             ->where('client_policy.is_active', 1)
             ->where('client_policy.client_id',  $pre_client_data['id'])
@@ -6888,16 +7000,16 @@ class ClientController extends AdminController
             ->orderBy('client_policy.policy_status', 'desc')
             ->get()
             ->getResultArray();
-
         // dd($hrAccessData);
 
-        $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id);
+        $combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id ,$pre_client_data['id']);
         return $combinedHrAccessData;
     }
 
-    public function constructHrAccessData($data, $client_id)
-    {   
-        // dd($data);
+    public function constructHrAccessData($data, $client_id , $pre_client_id)
+    {
+        // print_rr($data);die;
+
         $preHrs = $data['pre_hr_data'];
         $postHrs = $data['post_hr_data'];
         $hrAccessTableData = $data['hr_access_table_data'];
@@ -6907,13 +7019,18 @@ class ClientController extends AdminController
         foreach ($postHrs as $post) {
             $found = false;
             foreach ($preHrs as $index => $pre) {
-                if ($post['hr_mobile'] === $pre['hr_mobile'] && $post['hr_mail'] === $pre['hr_mail']) {
+
+                if ( trim($post['hr_mobile']) == trim($pre['hr_mobile'])  &&  trim($post['hr_mail']) == trim($pre['hr_mail']) ) {
+
                     $merged[] = [
                         'pre_hr_id' => $pre['pre_hr_id'],
                         'post_hr_id' => $post['post_hr_id'],
                         'hr_name' => $post['hr_name'],
                         'hr_mobile' => $post['hr_mobile'],
-                        'hr_mail' => $post['hr_mail']
+                        'hr_mail' => $post['hr_mail'],
+                        'pre_branch_id' => $pre['pre_branch_id'] ?? null,
+                        'post_branch_id'   => $post['post_branch_id'] ?? null,
+                        'post_branch_name' => $post['post_branch_name'] ?? null 
                     ];
                     unset($preHrs[$index]); // remove matched pre_hr
                     $found = true;
@@ -6927,19 +7044,32 @@ class ClientController extends AdminController
                     'post_hr_id' => $post['post_hr_id'],
                     'hr_name' => $post['hr_name'],
                     'hr_mobile' => $post['hr_mobile'],
-                    'hr_mail' => $post['hr_mail']
+                    'hr_mail' => $post['hr_mail'],
+                    'pre_branch_id' => $pre['pre_branch_id'] ?? null,
+                    'post_branch_id' => $post['post_branch_id'] ?? null ,
+                    'post_branch_name' => $post['post_branch_name'] ?? null
                 ];
             }
         }
 
         // Remaining preHrs (not matched)
         foreach ($preHrs as $pre) {
+
+            foreach ($merged as $value) {
+                if ( trim($pre['hr_mobile']) == trim($value['hr_mobile'])  &&  trim($pre['hr_mail']) == trim($value['hr_mail']) ) {
+                    continue 2; // Skip adding this pre_hr as it's already matched
+                }
+            }
+            
             $merged[] = [
                 'pre_hr_id' => $pre['pre_hr_id'],
                 'post_hr_id' => null,
                 'hr_name' => $pre['hr_name'],
                 'hr_mobile' => $pre['hr_mobile'],
-                'hr_mail' => $pre['hr_mail']
+                'hr_mail' => $pre['hr_mail'],
+                'pre_branch_id' => $pre['pre_branch_id'] ?? null,
+                'post_branch_id' => $post['post_branch_id'] ?? null ,
+                'post_branch_name' => $post['post_branch_name'] ?? null
             ];
         }
 
@@ -6964,81 +7094,90 @@ class ClientController extends AdminController
                     'hr_name' => $hr['hr_name'] ?? null,
                     'hr_mobile' => $hr['hr_mobile'] ?? null,
                     'hr_mail' => $hr['hr_mail'] ?? null,
+                    'pre_branch_id' => $hr['pre_branch_id'] ?? null,
+                    'post_branch_id' => $hr['post_branch_id'] ?? null ,
+                    'post_branch_name' => $hr['post_branch_name'] ?? null ,
+                    'pre_client_id'    => $pre_client_id ?? null
                 ];
             }
-
         } else {
-                    // First create a map of HR data by post_hr_id for quick lookup
-                    $hrMap = [];
-                    foreach ($merged as $hr) {
-                        $hrMap[$hr['post_hr_id']] = $hr;
-                    }
-                    
-                    // Process access data first
-                    foreach ($hrAccessTableData as $access) {
-                        $post_hr_id = $access['post_hr_id'];
-                        
-                        // Check if this HR exists in our merged data
-                        if (isset($hrMap[$post_hr_id])) {
-                            $hr = $hrMap[$post_hr_id];
-                            $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
-                            
-                            // Parse allowed modules
-                            $allowed_modules = json_decode($access['allowed_modules'], true) ?? null;
-                            $allowed_pre_modules = $allowed_modules['pre'] ?? [];
-                            $allowed_post_modules = $allowed_modules['post'] ?? [];
-                            
-                            $result[$temp_arr_key] = [
-                                'hr_access_table_pk' => $access['id'] ?? null,
-                                'post_client_id' => $access['post_client_id'] ?? null,
-                                'pre_hr_id' => $hr['pre_hr_id'] ?? null,
-                                'post_hr_id' => $hr['post_hr_id'] ?? null,
-                                'allowed_pre_modules' => $allowed_pre_modules,
-                                'allowed_post_modules' => $allowed_post_modules,
-                                'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [],
-                                'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [],
-                                'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [],
-                                'hr_name' => $hr['hr_name'],
-                                'hr_mobile' => $hr['hr_mobile'],
-                                'hr_mail' => $hr['hr_mail']
-                            ];
-                            
-                            // Remove from map so we know it's been processed
-                            unset($hrMap[$post_hr_id]);
-                        }
-                    }
-                    
-                    // Now process any remaining HRs that didn't have access records
-                    foreach ($hrMap as $hr) {
-                        $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
-                        
-                        $result[$temp_arr_key] = [
-                            'hr_access_table_pk' => null,
-                            'post_client_id' => $client_id ?? null,
-                            'pre_hr_id' => $hr['pre_hr_id'] ?? null,
-                            'post_hr_id' => $hr['post_hr_id'] ?? null,
-                            'allowed_pre_modules' => [],
-                            'allowed_post_modules' => [],
-                            'allowed_pre_policies' => [],
-                            'allowed_active_policies' => [],
-                            'allowed_cd' => [],
-                            'hr_name' => $hr['hr_name'] ?? null,
-                            'hr_mobile' => $hr['hr_mobile'] ?? null,
-                            'hr_mail' => $hr['hr_mail'] ?? null,
-                        ];
-                    }
-        }
-        
+            // First create a map of HR data by post_hr_id for quick lookup
+            $hrMap = [];
+            foreach ($merged as $hr) {
+                $hrMap[$hr['post_hr_id']] = $hr;
+            }
 
-        $resultData['hr_access_data'] = array_values($result);
-        $resultData['pre_policy_data'] = $data['pre_policy_data'];
+            // Process access data first
+            foreach ($hrAccessTableData as $access) {
+                $post_hr_id = $access['post_hr_id'];
+
+                // Check if this HR exists in our merged data
+                if (isset($hrMap[$post_hr_id])) {
+                    $hr = $hrMap[$post_hr_id];
+                    $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
+
+                    // Parse allowed modules
+                    $allowed_modules = json_decode($access['allowed_modules'], true) ?? null;
+                    $allowed_pre_modules = $allowed_modules['pre'] ?? [];
+                    $allowed_post_modules = $allowed_modules['post'] ?? [];
+
+                    $result[$temp_arr_key] = [
+                        'hr_access_table_pk' => $access['id'] ?? null,
+                        'post_client_id' => $access['post_client_id'] ?? null,
+                        'pre_hr_id' => $hr['pre_hr_id'] ?? null,
+                        'post_hr_id' => $hr['post_hr_id'] ?? null,
+                        'allowed_pre_modules' => $allowed_pre_modules,
+                        'allowed_post_modules' => $allowed_post_modules,
+                        'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [],
+                        'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [],
+                        'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [],
+                        'hr_name' => $hr['hr_name'],
+                        'hr_mobile' => $hr['hr_mobile'],
+                        'hr_mail' => $hr['hr_mail'],
+                        'pre_branch_id' => $hr['pre_branch_id'] ?? null,
+                        'post_branch_id' => $hr['post_branch_id'] ?? null ,
+                        'post_branch_name' => $hr['post_branch_name'] ?? null ,
+                        'pre_client_id'    => $pre_client_id ?? null
+                    ];
+
+                    // Remove from map so we know it's been processed
+                    unset($hrMap[$post_hr_id]);
+                }
+            }
+
+            // Now process any remaining HRs that didn't have access records
+            foreach ($hrMap as $hr) {
+                $temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
+
+                $result[$temp_arr_key] = [
+                    'hr_access_table_pk' => null,
+                    'post_client_id' => $client_id ?? null,
+                    'pre_hr_id' => $hr['pre_hr_id'] ?? null,
+                    'post_hr_id' => $hr['post_hr_id'] ?? null,
+                    'allowed_pre_modules' => [],
+                    'allowed_post_modules' => [],
+                    'allowed_pre_policies' => [],
+                    'allowed_active_policies' => [],
+                    'allowed_cd' => [],
+                    'hr_name' => $hr['hr_name'] ?? null,
+                    'hr_mobile' => $hr['hr_mobile'] ?? null,
+                    'hr_mail' => $hr['hr_mail'] ?? null,
+                    'pre_branch_id' => $hr['pre_branch_id'] ?? null,
+                    'post_branch_id' => $hr['post_branch_id'] ?? null ,
+                    'post_branch_name' => $hr['post_branch_name'] ?? null ,
+                    'pre_client_id'    => $pre_client_id ?? null
+                ];
+            }
+        }
+
+
+        $resultData['hr_access_data']   = array_values($result);
+        $resultData['pre_policy_data']  = $data['pre_policy_data'];
         $resultData['post_policy_data'] = $data['post_policy_data'];
-        $resultData['post_cd_data'] = $data['post_cd_data'];
-        // echo '**********************************************';
-        // print_rr($resultData);die();
+        $resultData['post_cd_data']     = $data['post_cd_data'];
 
         return $resultData;
-    }
+    }       
 
     public function saveHrAccessData()
     {
@@ -7076,8 +7215,23 @@ class ClientController extends AdminController
                     $post = array_values(array_filter($allowed_modules, fn($v) => $v !== 1));
                     $value['allowed_modules'] = json_encode(['pre' => $pre, 'post' => $post]);
 
+                    $post_client_id = $value['post_client_id'];
+                    $post_branch_id = $value['post_branch_id'];
+                    $post_hr_id     = $value['post_hr_id'];
+
+                    $preBranchId = $this->getPreBranchIdByPostBranchId($post_branch_id);
+
+                    if (!empty($preBranchId)) {
+                        $value['pre_branch_id']  = $preBranchId;
+                        $value['pre_client_id']  = $this->getPreClientIdByPreBranchId($preBranchId);
+                        $value["pre_hr_id"]      = $this->getPreHrIdByPreBranchId($preBranchId);
+                    }
+                    
+
+
                     // INSERT or UPDATE
                     if (empty($value['pk']) || (int)$value['pk'] === 0) {
+
                         unset($value['pk']); // Prevent insert error
                         $insertedId = $this->HRAccessControlModel->insert($value);
                         if ($insertedId === false) {
@@ -7086,6 +7240,7 @@ class ClientController extends AdminController
                         $success[] = "Inserted row at index {$index} with ID {$insertedId}.";
                     } else {
                         $update = $this->HRAccessControlModel->update($value['pk'], $value);
+
                         if ($update === false) {
                             throw new \Exception('Update failed for ID ' . $value['pk'] . ': ' . json_encode($this->HRAccessControlModel->errors()));
                         }
@@ -7119,7 +7274,6 @@ class ClientController extends AdminController
                     'details' => $success,
                     'data' => $html,
                 ], 200);
-
             } else {
                 return $this->respond([
                     'status' => false,
@@ -7140,6 +7294,28 @@ class ClientController extends AdminController
         }
     }
 
+    private function getPreClientIdByPreBranchId($pre_branch_id){
+        $db2 = \Config\Database::connect('preDB');
+        $pre_client_id = $db2->table('client_branch')->where('id',$pre_branch_id)->where('is_Active',1)->get()->getResultArray()[0]['client_id']??"";
+        return $pre_client_id;
+    }
+
+    private function getPreHrIdByPreBranchId($pre_branch_id){
+        $db2 = \Config\Database::connect('preDB');
+        $pre_hr_id = $db2->table('client_branch cb')
+        ->select('lc.id')
+        ->join('level_contacts lc','lc.ref_id = cb.id')
+        ->where('cb.id',$pre_branch_id)->where('cb.is_Active',1)->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??"";
+        return $pre_hr_id;
+    }
+
+    private function getPreBranchIdByPostBranchId($post_branch_id){
+        $db = \Config\Database::connect();
+        $pre_branch_id = $db->table('client_branch')->where('id',$post_branch_id)->where('is_Active',1)->get()->getResultArray()[0]['pre_branch_id']??"";
+        return $pre_branch_id;
+    }
+
+
     // ------------------- DEMO CLIENT FUNCTION --------------------------------------------------------------------------------
 
     public function wipeDemoClient()
@@ -7457,6 +7633,104 @@ class ClientController extends AdminController
 
         return $this->respond(['status' => true, 'message' => 'Demo client data wiped successfully'], 200);
     }
+
+    private function getClientlistFromPre (){
+        $db2 = \Config\Database::connect('preDB');
+
+        $auto_fetch_client_list = $db2->table('clients')
+        ->select('id,client_name')
+        ->where('is_active',1)
+        ->get()->getResultArray()??[];
+
+        return $auto_fetch_client_list;
+
+    }
+
+    public function auto_fetch_branch(){
+
+        $data = $this->request->getPost();
+
+        $db2 = \Config\Database::connect('preDB');
+
+        $auto_fetch_branch_list = $db2->table('client_branch')
+        ->select('id,branch_name')
+        ->where('client_id',$data['client_id'])
+        ->where('is_active',1)
+        ->get()->getResultArray()??[];
+
+        return 
+
+        empty($auto_fetch_branch_list)
+
+        ? $this->response->setJSON([
+                'status' => false,
+                'message' => 'branch list is empty',
+                'data' => []
+            ])->setStatusCode(400)
+        
+        :   $this->response->setJSON([
+                'status' => true,
+                'message' => 'branch list is found' ,
+                 'data' => $auto_fetch_branch_list
+            ])->setStatusCode(200);
+    }
+
+    public function auto_fetch_branch_details(){
+
+        $data = $this->request->getPost();
+
+        $db2 = \Config\Database::connect('preDB');
+
+        $auto_fetch_branch_details = $db2->table('client_branch')
+                                        ->where('client_id',$data['client_id'])
+                                        ->where('id',$data['branch_id'])
+                                        ->where('is_active',1)
+                                        ->get()->getResultArray()??[];
+
+        return empty($auto_fetch_branch_details)
+
+                    ? $this->response->setJSON([
+                            'status' => false,
+                            'message' => 'branch details is empty',
+                            'data' => []
+                        ])->setStatusCode(400)
+                    
+                    :   $this->response->setJSON([
+                            'status' => true,
+                            'message' => 'branch details found' ,
+                            'data' => $auto_fetch_branch_details
+                        ])->setStatusCode(200);
+
+    }
+
+
+    private function updatePreClientBranch($pre_branch_id,$post_branch_id ,$operation)
+    {
+
+
+
+        $preDB = \Config\Database::connect('preDB');
+
+        if($operation != 'create'){
+
+            $builder = $preDB->table('client_branch');
+            $builder->where('post_branch_id', $post_branch_id);
+            $builder->update(['post_branch_id' => null]);
+        }
+
+        $builder = $preDB->table('client_branch');
+        $builder->where('id', $pre_branch_id);
+        $builder->update(['post_branch_id' => $post_branch_id]);
+
+        return true;
+    }
+
+
+
+
+
+
+
+
+
 }
-
-
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index b9ed11a4..73c2e31a 100755
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -259,7 +259,7 @@ class DashboardController extends AdminController
 
         // dd(get_role_id(),user_team());
         // dd($data);
-        
+        $data['tab_name'] = 'Dashboard';
         $data['page_name'] = 'Dashboard';
 
         echo view('layout/header',  $data);
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 3751da86..a4666518 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -135,6 +135,9 @@ class EmployeeController extends AdminController
 
         // dd($this->request->getGet());
         $this->myLogger->logme('error', 'list called');
+
+        $data['page_name'] = "Members";
+
         $this->loadLayout('employee_list', $data);
     }
 
@@ -307,6 +310,7 @@ class EmployeeController extends AdminController
             return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
         }
 
+        $data['tab_name'] = 'View Inception';
         $data['page_name'] = 'View Inception';
 
         //for TPA/insurer upload
@@ -786,6 +790,9 @@ class EmployeeController extends AdminController
         }
 
         $this->myLogger->logme('error', 'list called');
+        
+        $data['page_name'] = "Endorsement";
+
         $this->loadLayout('endorsement_list', $data);
     }
 
@@ -830,6 +837,9 @@ class EmployeeController extends AdminController
         // dd($data);
 
         $this->myLogger->logme('error', 'list called');
+
+        $data['page_name'] = "Enrollment";
+
         return $this->loadLayout('enrollment_list', $data);
     
      }
@@ -3039,6 +3049,8 @@ class EmployeeController extends AdminController
             // print_r($data); die;
         // }
 
+        $data['page_name'] = "Retail Endorsement";
+
         $this->loadLayout('retail_endorsement_list', $data);
     }
 
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 341bfcf2..1b7310b6 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -2868,14 +2868,14 @@ class EmployeeRestController extends AdminController
 
                 }else if($ClientPolicyValue['policy_type_id'] == 6)
                 { 
-                    $policyGroup = 'gpa';
+                    $policyGroup = 'other';
                     $data['ticket_type_id'] = 3;
                     $data['claim_subject'] = "Claim EDLI";
                     $data['sum_insured_label'] = "Sum Assured";
 
                 }else if($ClientPolicyValue['policy_type_id'] == 7)
                 { 
-                    $policyGroup = 'gpa';
+                    $policyGroup = 'other';
                     $data['ticket_type_id'] = 4;
                     $data['claim_subject'] = "Claim GTLI";
                     $data['sum_insured_label'] = "Sum Assured";
@@ -2969,9 +2969,6 @@ class EmployeeRestController extends AdminController
 
     function policyTermsFiter($terms , $type)
     {
-
-      
-    
         $gpa = [
             "sumInsured2" => "Sum Insured",
             "totalSumInsured" => "Total Sum Assured",
@@ -3021,8 +3018,6 @@ class EmployeeRestController extends AdminController
             "moderntreatmentsasperirdai" => "Modern Treatment "
         ];
 
-
-        
         $finalarray = [];
         if($type == 'gpa'){
             foreach ($gpa as $key => $value) {
@@ -3046,6 +3041,18 @@ class EmployeeRestController extends AdminController
                     $finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i];
                 }
             }
+        }else if($type == 'other'){
+            foreach ($terms as $key => $value) {
+                if($key != "multiple_sum_insured" && $value != ""){
+                    $result = ucwords(str_replace('_', ' ', $key));
+                    $finalarray[$result] = $value;
+                }
+            }
+            if(isset(($terms->gpa_special_condition_label)) && is_array($terms->gpa_special_condition_label) && is_array($terms->gpa_special_condition_input)){
+                for ($i=0; $i < count($terms->gpa_special_condition_label); $i++) { 
+                    $finalarray[$terms->gpa_special_condition_label[$i]] = $terms->gpa_special_condition_input[$i];
+                }
+            }
         }else{
             foreach ($gmc as $key => $value) {
                 if(isset($terms->$key))
@@ -3070,9 +3077,7 @@ class EmployeeRestController extends AdminController
             }
         }
 
-
         return $finalarray;
-        
     }
 
 
diff --git a/app/Controllers/ICICILombardController.php b/app/Controllers/ICICILombardController.php
index 928fbc2f..5c5bc627 100644
--- a/app/Controllers/ICICILombardController.php
+++ b/app/Controllers/ICICILombardController.php
@@ -67,24 +67,57 @@ class ICICILombardController extends AdminController
 
 
         //Prepare body data
-        $db = \Config\Database::connect();
-        $data = $db->table('employee_polices ep')
-                    ->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber,
-                            e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship,
-                            e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId
-                            ')
-                    ->join('employees e', 'e.id = ep.employee_id')
-                    ->join('client_policy cp', 'ep.client_policy_id = cp.id')
-                    ->where('ep.client_policy_id', $policy_id)
-                    ->where('ep.status', 'active')
-                    ->where('ep.is_active', 1)
-                    // ->where('ep.uhid', null)
-                    ->get()
-                    ->getResultArray();
+        // $db = \Config\Database::connect();
+        // $data = $db->table('employee_polices ep')
+        //             ->select('cp.policy_no as policyNumber, cp.cd_ac_no as CDBGAccountNumber,
+        //                     e.id,e.emp_code as MemberEmpId, e.doj as DOJ, e.name as InsuredName, e.dob as DOB, e.relationship as Relationship,
+        //                     e.gender as Gender, ep.date_coverage as DOC,ep.basic_cover_si as SumInsured, e.email_corporate as EmailId
+        //                     ')
+        //             ->join('employees e', 'e.id = ep.employee_id')
+        //             ->join('client_policy cp', 'ep.client_policy_id = cp.id')
+        //             ->where('ep.client_policy_id', $policy_id)
+        //             ->where('ep.status', 'active')
+        //             ->where('ep.is_active', 1)
+        //             // ->where('ep.uhid', null)
+        //             ->get()
+        //             ->getResultArray();
     
-        $body = $this->formatPolicyData($data);       
+        // $body = $this->formatPolicyData($data);       
         // dd($body); 
 
+
+          $body = [
+            "PolicyNumber" => "4016/A/O/53130557/00/000",
+            "CDBGAccountNumber" => "CD-MUM-0026",
+            "CorrelationId" => "550e8400-e29b-41d4-a716-446655440010",
+            "MemberDetails" => [
+                [
+                    "MemberEmpId" => "EMPID3625557",
+                    "DOJ" => "21-MAR-2019",
+                    "InsuredName" => "Kumar",
+                    "DOB" => "7-JUL-1983",
+                    "Relationship" => "SELF",
+                    "Gender" => "MALE",
+                    "DOC" => "05-SEP-2025",
+                    "SumInsured" => "400000",
+                    "EmailId" => "KUMAR@GMAIL.COM",
+                    "FlagStatus" => "A"
+                ],
+                [
+                    "MemberEmpId" => "EMPID3625557",
+                    "DOJ" => "21-MAR-2019",
+                    "InsuredName" => "Saranya",
+                    "DOB" => "8-AUG-1970",
+                    "Relationship" => "MOTHER",
+                    "Gender" => "FEMALE",
+                    "DOC" => "05-SEP-2025",
+                    "SumInsured" => "400000",
+                    "EmailId" => "Saranya@GMAIL.COM",
+                    "FlagStatus" => "A"
+                ],
+            ]
+        ];
+
         $response = call_third_party_api($url, 'POST', $headers, $body, true); // true = raw body mode
         //  print_rr(json_encode($response));die();
         return $this->response->setJSON($response);
@@ -115,9 +148,9 @@ class ICICILombardController extends AdminController
         // dd($headers);
 
          $body = [
-            "PolicyNumber" => "4016/A/O/53077718/00/000",
-            "BatchId" => "3646145",
-            "CorrelationId" => "550e8400-e29b-41d4-a716-446655440001"
+            "PolicyNumber" => "4016/A/O/53130557/00/000",
+            "BatchId" => "3658147",
+            "CorrelationId" => "550e8400-e29b-41d4-a716-446655440010"
         ];
 
         $response = call_third_party_api($url, 'POST', $headers, $body, true);
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index 1f322c84..50c9820b 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -167,6 +167,10 @@ class JobWorker extends AdminController
         'type' => 'CC', // Handler Category
         'handler' => 'App\Controllers\EmployeeMultiEventServiceController',
     ],
+    'memberDataListExcelFileFormatValidation' => [
+        'type' => 'CC', // Handler Category
+        'handler' => 'App\Controllers\LeadsController',
+    ],
 ];
 
     
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index d5f8ea12..59608e7e 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -81,11 +81,13 @@ class LeadsController extends BaseController
     protected $claim_type_for_gpa;
     protected $cause_of_death;
     protected $buisnessType;
+    protected $member_data_excel_columns;
+    protected $general_relationships;
 
 
     public function __construct()
     {
-        set_session_context('Leads');
+        set_session_context('LEAD CONTROLLER');
         $this->myLogger = \Config\Services::mylogger();
 
         $this->clientModel        = new ClientModel();
@@ -136,12 +138,171 @@ class LeadsController extends BaseController
         $this->cause_of_death = [
             'natural_death' => 'Natural Death',
             'suicide'       => 'Suicide',
-            'accident'      => 'Accident'
+            'accident'      => 'Accident',
+            'cardiac_arrest' => 'Cardiac Arrest',
+            'septic_shock' => 'Septic shock',
+            'heart_attack' => 'Heart Attack',
         ];
+
+        $this->member_data_excel_columns = [
+            'sno' => [
+                'col_idx' => 0,
+                'col_cell_name' => 'A',
+                'col_name' => 'Sl no',
+                'is_mandatory' => false,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'emp_code' => [
+                'col_idx' => 1,
+                'col_cell_name' => 'B',
+                'col_name' => 'Emp Code',
+                'is_mandatory' => true,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'name' => [
+                'col_idx' => 2,
+                'col_cell_name' => 'C',
+                'col_name' => 'Name',
+                'is_mandatory' => true,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'relationship' => [
+                'col_idx' => 3,
+                'col_cell_name' => 'D',
+                'col_name' => 'Relationship',
+                'is_mandatory' => true,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => [
+                    'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother',
+                    'Father-in-law', 'Mother-in-law',
+                    'self', 'spouse', 'son', 'daughter', 'father', 'mother',
+                    'father-in-law', 'mother-in-law'
+                ],
+                'custom' => 'check_relationship_for_member_data',
+                'params' => ['row', 'relationship', 'columns_to_check']
+            ],
+            'gender' => [
+                'col_idx' => 4,
+                'col_cell_name' => 'E',
+                'col_name' => 'Gender',
+                'is_mandatory' => true,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => ['M', 'F']
+            ],
+            'dob' => [
+                'col_idx' => 5,
+                'col_cell_name' => 'F',
+                'col_name' => 'DOB',
+                'is_mandatory' => true,
+                'data_type' => 'str',
+                'format' => 'd-M-Y',
+                'allowed_values' => null,
+                'age_validation' => true,
+                // 'custom' => 'check_dob_diff',
+                // 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details']
+            ],
+            'age' => [
+                'col_idx' => 6,
+                'col_cell_name' => 'G',
+                'col_name' => 'Age',
+                'is_mandatory' => true,
+                'data_type' => 'int',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'email' => [
+                'col_idx' => 7,
+                'col_cell_name' => 'H',
+                'col_name' => 'Email',
+                'is_mandatory' => false,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'mobile' => [
+                'col_idx' => 8,
+                'col_cell_name' => 'I',
+                'col_name' => 'Mobile',
+                'is_mandatory' => false,
+                'data_type' => 'str',
+                'format' => null,
+                'allowed_values' => null
+            ],
+            'si' => [
+                'col_idx' => 9,
+                'col_cell_name' => 'J',
+                'col_name' => 'SI',
+                'is_mandatory' => false,
+                'data_type' => 'int',
+                'format' => null,
+                'allowed_values' => null,
+            ]
+        ];
+
+        $this->general_relationships = [
+            'self' => [
+                'name' => 'Self',
+                'gender' => 'M',
+                'age_min' => 18,
+                'age_max' => null
+            ],
+            'spouse' => [
+                'name' => 'Spouse',
+                'gender' => 'F',
+                'age_min' => 18,
+                'age_max' => null
+            ],
+            'son' => [
+                'name' => 'Son',
+                'gender' => 'M',
+                'age_min' => null,
+                'age_max' => 25
+            ],
+            'daughter' => [
+                'name' => 'Daughter',
+                'gender' => 'F',
+                'age_min' => null,
+                'age_max' => 25
+            ],
+            'father' => [
+                'name' => 'Father',
+                'gender' => 'M',
+                'age_min' => 18,
+                'age_max' => null
+            ],
+            'mother' => [
+                'name' => 'Mother',
+                'gender' => 'F',
+                'age_min' => 18,
+                'age_max' => null
+            ],
+            'father-in-law' => [
+                'name' => 'Father in Law',
+                'gender' => 'M',
+                'age_min' => 18,
+                'age_max' => null
+            ],
+            'mother-in-law' => [
+                'name' => 'Mother in Law',
+                'gender' => 'F',
+                'age_min' => 18,
+                'age_max' => null
+            ]
+        ];
+                
     }
 
     public function viewLeadsList()
     {
+        $data['tab_name'] = 'Leads';
         $data['page_name'] = 'Leads';
 
         // Set basic data
@@ -504,7 +665,7 @@ class LeadsController extends BaseController
             if ($value['lead_form_type'] == 1) {
                 //for this push the job to the  calculateMembersDemography() function
                 $job_details  = new Jobs();
-                $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
+                $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
                     'lead_id' => $insert,
                 ]]);
             }
@@ -528,7 +689,7 @@ class LeadsController extends BaseController
         return $this->respond(['status' => false, 'lead_id' => $id, 'message' => "Failed to update Lead", 'data' => $data], 200);
     }
 
-    // Get the Single Lead data for edit uisng ajax ( do not delete)
+    // Get the Single Lead data for edit uisng ajax (do not delete)
     public function getLeadDataForEdit($id)
     {
 
@@ -567,7 +728,11 @@ class LeadsController extends BaseController
         //     $data['premium_date'] = null;
         // }
 
-        $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->first() ?? null;
+        $data['multi_file_data'] = $this->leadFilesModel
+                        ->where('lead_id', $id)
+                        ->where('type !=', 2)
+                        ->where('is_active', 1)
+                        ->first() ?? null;
 
         $data['lastFiveYears'] = $this->getLastFiveFinancialYears();
         $data['gpaClaimType'] = $this->claim_type_for_gpa;
@@ -603,7 +768,7 @@ class LeadsController extends BaseController
     }
 
     public function uploadMultiFiles($files, $docs_names, $primaryKey)
-    {
+    {   
         $uploadFilePath = WRITEPATH . 'uploads/lead_files/';
 
         $multi_file_data = [];
@@ -644,7 +809,7 @@ class LeadsController extends BaseController
                         if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) {
                             //for this push the job to the  calculateMembersDemography() function
                             $job_details  = new Jobs();
-                            $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => [
+                            $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [
                                 'lead_id' => $lead_id,
                             ]]);
                             log_message('info', "calculateMembersDemography JOB PUSHED");
@@ -696,63 +861,299 @@ class LeadsController extends BaseController
 
     //--------RFQ-----------------------------------------------------------------------------------------------
 
+    // public function viewRFQ($id, $type = 1)
+    // {
+
+    //     $data['rfq_data'] = $this->RFQModel
+    //         ->where('lead_id', $id)
+    //         // ->where('type', $type)
+    //         ->where('is_active', 1)
+    //         ->orderBy('id', 'desc')
+    //         ->first();
+    //     // dd($data);
+
+    //     $data['rfq_count'] = $this->RFQModel
+    //         ->where('lead_id', $id)
+    //         // ->where('type', 1)
+    //         ->where('is_active', 1)
+    //         ->countAllResults();
+
+    //     $data['qcr_count'] = $this->RFQModel
+    //         ->where('lead_id', $id)
+    //         ->where('type', 2)
+    //         ->where('is_active', 1)
+    //         ->countAllResults();
+
+    //     // dd(count($data['rfq_data']));
+
+    //     $data['lead_id'] = $id;
+    //     $lead_data = $this->leadsModel
+    //         ->select('
+    //                 leads.*, 
+    //                 policy_type.question_json, 
+    //                 policy_type.policy_type,
+    //                 policy_type.long_name, 
+    //                 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', 'left')
+    //         ->where('leads.id', $id)
+    //         ->where('leads.is_active', 1)
+    //         ->first();
+
+    //     // dd($lead_data);
+
+    //     if ($lead_data['lead_type'] != 1) {
+    //         $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first();
+    //         if (isset($client_policy_data)) {
+    //             $data['policy_terms'] = $client_policy_data['policy_terms'];
+    //         }
+    //     }
+
+    //     $data['question_json'] = $lead_data['question_json'];
+    //     $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ';
+    //     $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+    //     $data['userList'] = $this->userModel->getUserListForRFQ();
+    //     $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ();
+    //     $data['lead_data'] = $lead_data;
+    //     $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
+    //     $data['account_manager'] = $this->userModel->where('is_active', 1)->where('role', 3)->findAll();
+
+
+    //     $mail_content = '
+    //         

Dear Sir,

+ //

Greetings From Nhance India!

+ //

Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.

+ //

Kindly request you to share the competitive quotes at the earliest.

+ //

In case of any query, please feel free to contact us.

+ //

Thank You!


+ //

Best regards,

+ + //
+ //
{{LOGGED_USER_NAME}}
+ //
Mobile: {{LOGGED_USER_MOBILE}}
+ //
+ + // Nhance Logo + // '; + + // if ($data['lead_data']['policy_end_date'] != null) { + // $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}"; + // } else { + // $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; + // } + + // if ($lead_data['policy_type_id'] == 1) { + // $data['totalSumAssured'] = $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]); + // } else { + // $data['totalSumAssured'] = []; + // } + + // $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); + // $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); + + // $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement'); + // $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); + + // $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; + // $installment_data['installments'] = $this->leadInstallmentPaymentDetails->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; + // $data['lead_data']['installment_data'] = view('rfq/installment_fields', $installment_data) ?? null; + // $data['attachment_html'] = view('rfq/attachment_files', $data) ?? ""; + // $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut", "ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active", 1)->first()['team_id']; + // $data['multi_file_data_html'] = $this->renderFileFields($data['multi_file_data']); + // // dd($data); + + // if ($data['lead_data']['lead_form_type'] == 1) { + // $data['demogrphy_html_data'] = $this->generateDemographyDataTable(['lead_id' => $id]); + // $this->loadLayout('view_rfq.php', $data); + // } else if ($data['lead_data']['lead_form_type'] == 2) { + + // $data['occupancy'] = $this->occupancyModel->findAll(); + // // dd($data['occupancy']); + + // if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) { + // $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); + // if (isset($client_policy_data)) { + + // $data['rfq_data']['json'] = $client_policy_data['placement_json']; + // } + // } + + // if (!empty($data['question_json'])) { + // $data['policies'] = json_decode($data['question_json'], true)['policies']; + // $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data']; + // } + + // $data['product'] = $this->leadsModel->select("policy_type.policy_type")->join('policy_type', 'leads.policy_type_id = policy_type.id')->where('leads.id', $id)->first()['policy_type']; + // // $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']); + // // dd($data['lead_register_data']); + // // $data['entity_type'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); + // $data['buisness_type'] = $this->buisnessType; + + // // dd($data); + // $data['client_type'] = $this->clientType; + // $this->loadLayout('view_rfq_non_eb', $data); + // } + // } + public function viewRFQ($id, $type = 1) { + // 1. Combine RFQ queries into a single query + $rfqStats = $this->RFQModel + ->select(' + COUNT(*) as total_count, + SUM(CASE WHEN type != 2 THEN 1 ELSE 0 END) as rfq_count, + SUM(CASE WHEN type = 2 THEN 1 ELSE 0 END) as qcr_count + ') + ->where('lead_id', $id) + ->where('is_active', 1) + ->first(); + $data['rfq_count'] = $rfqStats['rfq_count'] ?? 0; + $data['qcr_count'] = $rfqStats['qcr_count'] ?? 0; + + // 2. Get RFQ data separately (only if needed) $data['rfq_data'] = $this->RFQModel ->where('lead_id', $id) - // ->where('type', $type) ->where('is_active', 1) ->orderBy('id', 'desc') ->first(); - // dd($data); - - $data['rfq_count'] = $this->RFQModel - ->where('lead_id', $id) - // ->where('type', 1) - ->where('is_active', 1) - ->countAllResults(); - - $data['qcr_count'] = $this->RFQModel - ->where('lead_id', $id) - ->where('type', 2) - ->where('is_active', 1) - ->countAllResults(); - - // dd(count($data['rfq_data'])); $data['lead_id'] = $id; + + // 3. Optimize lead data query with specific field selection $lead_data = $this->leadsModel ->select(' - leads.*, - policy_type.question_json, - policy_type.policy_type, - policy_type.long_name, - user_profiles.email as created_person_email - ') + leads.id, + leads.policy_type_id, + leads.lead_type, + leads.source_policy_id, + leads.policy_end_date, + leads.lead_form_type, + leads.created_by, + leads.client_name, + lead_files.status as demography_file_status, + policy_type.question_json, + policy_type.policy_type, + policy_type.long_name, + 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', 'left') + ->join('lead_files', 'leads.id = lead_files.lead_id AND lead_files.type = 2 AND lead_files.is_active = 1', 'left') ->where('leads.id', $id) ->where('leads.is_active', 1) ->first(); - // dd($lead_data); + if (!$lead_data) { + // Handle case where lead doesn't exist + throw new \Exception('Lead not found'); + } + // 4. Conditional query - only fetch if needed if ($lead_data['lead_type'] != 1) { - $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); - if (isset($client_policy_data)) { + $client_policy_data = $this->clientPolicyModel + ->select('policy_terms, placement_json') + ->where('is_active', 1) + ->where('id', $lead_data['source_policy_id']) + ->first(); + + if ($client_policy_data) { $data['policy_terms'] = $client_policy_data['policy_terms']; + + // Store for later use in lead_form_type == 2 condition + if ($lead_data['lead_form_type'] == 2 && $data['rfq_count'] == 0) { + $data['rfq_data']['json'] = $client_policy_data['placement_json']; + } } } + // 5. Cache decoded JSON to avoid multiple decodes + $question_json_decoded = !empty($lead_data['question_json']) + ? json_decode($lead_data['question_json'], true) + : null; + $data['question_json'] = $lead_data['question_json']; + $data['tab_name'] = $type == 2 ? 'QCR' : 'RFQ'; $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; + $data['lead_data'] = $lead_data; + + // 6. Parallel/batch data fetching for independent queries $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['userList'] = $this->userModel->getUserListForRFQ(); $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ(); - $data['lead_data'] = $lead_data; + $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + $data['account_manager'] = $this->userModel + ->where('is_active', 1) + ->where('role', 3) + ->findAll(); - $mail_content = ' + // 7. Define mail templates as constants or config + $mail_content = $this->getMailTemplate(); + $subject = $this->getSubjectTemplate($lead_data); + + // 8. Pre-calculate sum assured only for GPA + $data['totalSumAssured'] = ($lead_data['policy_type_id'] == 1) ? $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]) : []; + + // 9. Transform mail content once + $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); + $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); + $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement'); + $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); + + // 10. Combine related queries + $data['multi_file_data'] = $this->leadFilesModel + ->where('lead_id', $id) + ->where('type !=', 2) + ->where('is_active', 1) + ->findAll(); + + $installment_data['installments'] = $this->leadInstallmentPaymentDetails + ->where('lead_id', $id) + ->where('is_active', 1) + ->findAll(); + + // 11. Generate views efficiently + $data['lead_data']['installment_data'] = !empty($installment_data['installments']) + ? view('rfq/installment_fields', $installment_data) + : null; + + $data['attachment_html'] = view('rfq/attachment_files', $data); + + $user_team = $this->userModel + ->select("ut.team_id") + ->join("user_teams ut", "ut.user_id = user_profiles.id and ut.is_active = 1") + ->where("user_profiles.is_active", 1) + ->first(); + $data['user_team'] = $user_team['team_id'] ?? null; + + $data['multi_file_data_html'] = $this->renderFileFields($data['multi_file_data']); + + // 12. Conditional rendering based on lead_form_type + if ($lead_data['lead_form_type'] == 1) { + $data['demogrphy_html_data'] = $this->generateDemographyDataTable(['lead_id' => $id]); + $this->loadLayout('view_rfq.php', $data); + } else if ($lead_data['lead_form_type'] == 2) { + $data['occupancy'] = $this->occupancyModel->findAll(); + + // Use cached decoded JSON + if ($question_json_decoded) { + $data['policies'] = $question_json_decoded['policies'] ?? []; + $data["child_table_data"] = $question_json_decoded['child_table_data'] ?? []; + } + + $data['product'] = $lead_data['policy_type']; + $data['buisness_type'] = $this->buisnessType; + $data['client_type'] = $this->clientType; + + $this->loadLayout('view_rfq_non_eb', $data); + } + } + + // 13. Extract mail template to separate method for reusability + private function getMailTemplate() + { + return '

Dear Sir,

Greetings From Nhance India!

Please find attached the {{RFQ_OR_QCR}} for {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}}.

@@ -761,70 +1162,21 @@ class LeadsController extends BaseController

Thank You!


Best regards,

-
+
{{LOGGED_USER_NAME}}
Mobile: {{LOGGED_USER_MOBILE}}
- Nhance Logo + Nhance Logo '; + } - if ($data['lead_data']['policy_end_date'] != null) { - $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}"; - } else { - $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; - } - - if ($lead_data['policy_type_id'] == 1) { - $data['totalSumAssured'] = $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]); - } else { - $data['totalSumAssured'] = []; - } - - $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); - $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); - - $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement'); - $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); - - $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; - $installment_data['installments'] = $this->leadInstallmentPaymentDetails->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; - $data['lead_data']['installment_data'] = view('rfq/installment_fields', $installment_data) ?? null; - $data['attachment_html'] = view('rfq/attachment_files', $data) ?? ""; - $data['user_team'] = $this->userModel->select("ut.team_id")->join("user_teams ut", "ut.user_id = user_profiles.id and ut.is_active = 1")->where("user_profiles.is_active", 1)->first()['team_id']; - // dd($data); - - if ($data['lead_data']['lead_form_type'] == 1) { - $data['demogrphy_html_data'] = $this->generateDemographyDataTable(['lead_id' => $id]); - $this->loadLayout('view_rfq.php', $data); - } else if ($data['lead_data']['lead_form_type'] == 2) { - - $data['occupancy'] = $this->occupancyModel->findAll(); - // dd($data['occupancy']); - - if ($lead_data['lead_type'] != 1 && $data['rfq_count'] == 0) { - $client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $lead_data['source_policy_id'])->first(); - if (isset($client_policy_data)) { - - $data['rfq_data']['json'] = $client_policy_data['placement_json']; - } - } - - if (!empty($data['question_json'])) { - $data['policies'] = json_decode($data['question_json'], true)['policies']; - $data["child_table_data"] = json_decode($data['question_json'], true)['child_table_data']; - } - - $data['product'] = $this->leadsModel->select("policy_type.policy_type")->join('policy_type', 'leads.policy_type_id = policy_type.id')->where('leads.id', $id)->first()['policy_type']; - // $data['lead_register_data'] = json_decode($data['lead_data']['custom_fields']); - // dd($data['lead_register_data']); - // $data['entity_type'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); - $data['buisness_type'] = $this->buisnessType; - - // dd($data); - $data['client_type'] = $this->clientType; - $this->loadLayout('view_rfq_non_eb', $data); - } + // 14. Extract subject template to separate method + private function getSubjectTemplate($lead_data) + { + return $lead_data['policy_end_date'] != null + ? "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}} {{POLICY_END_DATE}}" + : "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; } public function savePolicyInfo() @@ -1452,20 +1804,22 @@ class LeadsController extends BaseController 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", ]; } + } else { + if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", - 'No of Employees at Inception' => $rfq_data['incept_emp_count'], - 'No of Dependents at Inception' => $rfq_data['incept_dept_count'], - 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'], + // 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + // 'No of Dependents at Inception' => $rfq_data['incept_dept_count'], + // 'Total Lives at Inception ' => $rfq_data['incept_no_of_lives'], - 'No of Employees at Expiry' => $rfq_data['exp_emp_count'], - 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'], - 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'], + // 'No of Employees at Expiry' => $rfq_data['exp_emp_count'], + // 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'], + // 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'], 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], @@ -1474,30 +1828,32 @@ class LeadsController extends BaseController 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", 'Insurer' => $rfq_data['insurer_name'] ?? " - ", 'TPA' => $rfq_data['tpa_name'] ?? " - ", - 'Policy Run Days' => $rfq_data['policy_run_days'], - 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']), - 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']), - 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])), - 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']), - 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])), - 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %", - 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %", + + // 'Policy Run Days' => $rfq_data['policy_run_days'], + // 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']), + // 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['premium_date']), + // 'Earned Premium' => formatIndianCurrency(intval($rfq_data['earned_premium'])), + // 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => formatIndianCurrency($rfq_data['incurred_claims']), + // 'Annualised Claims' => formatIndianCurrency(intval($rfq_data['annualised_claims'])), + // 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %", + // 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %", ]; } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) { + $lead_data = [ 'Insured' => $rfq_data['client_name'], 'No of Employees at Inception' => $rfq_data['incept_emp_count'], - 'Total Lives at Inception' => $rfq_data['total_lives_at_incept'], 'Total Sum Insured at Inception' => $rfq_data['total_si_at_incept'], 'Premium at inception' => $rfq_data['premium_at_incept'], - 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], - 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", - // 'TPA' => $rfq_data['tpa_name'] ?? " - ", 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", 'Existing Insurer' => $rfq_data['insurer_name'], - // 'TPA ' => $rfq_data['tpa_name'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'Total Sum Insured at Renewal' => $rfq_data['total_si_at_renewal'], + 'Claims Experience for last 3 years' => "Mentioned in Claims sheet", + // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + // 'TPA' => $rfq_data['tpa_name'] ?? " - ", + // 'Total Lives at Inception' => $rfq_data['total_lives_at_incept'], ]; } } @@ -2055,8 +2411,11 @@ class LeadsController extends BaseController $row = 2; foreach ($claim_details['finyear'] as $record) { $col = 'A'; - foreach ($record as $value) { + foreach ($record as $array_key => $value) { $label = ucwords(str_replace('_', ' ', ($value ?? ""))); + if(in_array($array_key, ['sum_insured', 'claim_amount', 'settled'])){ + $label = formatIndianCurrency(intval($label)); + } $sheet->setCellValue($col . $row, $label); $col++; } @@ -2074,19 +2433,27 @@ class LeadsController extends BaseController } // Enable wrap text for all cells - $maxColLetter = chr(64 + count($headers)); // Last column letter - $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true); + // $maxColLetter = chr(64 + count($headers)); // Last column letter + // $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true); - // Optional: center vertically for neatness - $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + // // Optional: center vertically for neatness + // $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - // Optional: Make row height auto (helps when wrap text is on) - for ($i = 2; $i < $row; $i++) { - $sheet->getRowDimension($i)->setRowHeight(-1); - } + $maxColLetter = chr(64 + count($headers)); + $dataRange = "A1:{$maxColLetter}" . ($row - 1); - } - } + $sheet->getStyle($dataRange)->getAlignment() + ->setWrapText(true) + ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER) + ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + + // Optional: Make row height auto (helps when wrap text is on) + for ($i = 2; $i < $row; $i++) { + $sheet->getRowDimension($i)->setRowHeight(-1); + } + + } + } // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; @@ -2825,6 +3192,22 @@ class LeadsController extends BaseController } } + if($recipient_type == 'placement' && isset($params['acm_email']) && !empty($params['acm_email'])){ + + $common['mail_type'] = "internal acm"; + $acm_mail_content = ' +

Dear Sir,

+

The placement for the {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} has been successfully won.

+

Please proceed with the next steps accordingly.

+

Thank You!


+

Best regards,

+ + Nhance Logo + '; + $acm_mail_content = $this->transformMailContent($lead_data, $acm_mail_content, $data['page_name'] = 'QCR'); + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $params['acm_email'], 'subject' => $subject, 'message' => $acm_mail_content, 'attachments' => $attachments, 'common' => $common]); + } + $is_placement = false; if ($recipient_type == 'placement') { @@ -2850,8 +3233,15 @@ class LeadsController extends BaseController 'cd_amount' => $params['cd_amount'] ?? null, 'no_of_installment' => $params['no_of_installment'] ?? null, 'is_installment' => $params['is_installment'] ?? null, + 'acm_id' => $params['acm_pk'] ?? null, ]; + if(isset($params['tpa_id']) && !empty($params['tpa_id'])){ + list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']); + $data['tpa_branch_id'] = $tpaBranchId; + $data['tpa_id'] = $tpaId; + } + $this->leadsModel->where('id', $lead_id)->set($data)->update(); if (isset($params['installments']) && !empty($params['installments'])) { @@ -3404,6 +3794,13 @@ class LeadsController extends BaseController $input_value = $cellData['input_value'] != "" ? $cellData['input_value'] : ($cellData['value'] ?? ''); $value = $cellData['value'] ?? ''; + if( $item == "family_composition" && $subth == $insurer_name && $policy_type == 2){ + $age_ratio_array = json_decode($input_value, true)['age_ratio'] ?? null; + if(!empty($age_ratio_array)){ + $age_ratio = $age_ratio_array; + } + } + // Skip unwanted keys if (in_array($parentth, ['Sno', 'Item Key', 'Particulars', 'Action']) || in_array($subth, ['Quote Asked'])) { continue; @@ -3565,7 +3962,6 @@ class LeadsController extends BaseController return json_encode($placement_json_data); } - //------------------------------------------------------------------------------------------------ @@ -3609,7 +4005,6 @@ class LeadsController extends BaseController } } - public function getLastFiveFinancialYears() { $currentYear = date('Y'); @@ -3639,7 +4034,7 @@ class LeadsController extends BaseController $this->loadLayout('view_rfq_non_eb'); } - // get lead data for edit bot EB and NON-EB + // get lead data for edit both EB and NON-EB public function getLeadNonEB($type, $id = null) { // Set basic data @@ -3673,7 +4068,11 @@ class LeadsController extends BaseController $data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? []; - $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null; + $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel + ->where('lead_id', $id) + ->where('type !=', 2) + ->where('is_active', 1) + ->findAll() ?? null; $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']); // Decode and merge custom fields if present @@ -4819,6 +5218,7 @@ class LeadsController extends BaseController $lead_file = $this->leadFilesModel ->where('lead_id', $lead_id) ->where('id', $id) + ->where('type !=', 2) ->where('is_active', 1) ->first(); @@ -4856,7 +5256,6 @@ class LeadsController extends BaseController return $attachments; } - public function handleMemberDataGPATotalSumInsurerFromExcel($params) { $lead_id = $params['lead_id']; @@ -4899,7 +5298,7 @@ class LeadsController extends BaseController $lower_headers = array_map('strtolower', $members_heading); foreach ($lower_headers as $index => $header) { - if (preg_match('/^sa\s*-\s*option\s*\d*$/i', $header)) { + if (preg_match('/^(sa\s*-\s*option|proposed\s+sum\s+insured)\s+\d+$/i', $header)) { $column_name = $members_heading[$index]; $sum = 0; @@ -4924,7 +5323,6 @@ class LeadsController extends BaseController return []; } - public function generateDemographyDataTable($param) { $returnData = $this->calculateMembersDemography($param, "internal"); @@ -5166,5 +5564,867 @@ class LeadsController extends BaseController return ['status' => true, "data" => $reminder_sended_lead]; } + public function uploadMultiFileFromRfq() + { + try { + + $this->myLogger->logme('error', "uploadMultiFileFromRfq START"); + $this->myLogger->logme('error', "Files received: " . json_encode($this->request->getPost() ?? [])); + + $lead_id = $this->request->getPost('lead_id'); + $lead_form_type = $this->request->getPost('lead_form_type'); + $leads_file_primary_key = $this->request->getPost('leads_file_id') ?? []; + $docs_name = $this->request->getPost('docs_name') ?? []; + $files = $this->request->getFileMultiple('file_name'); + + if (empty($files) || empty($docs_name)) { + $this->myLogger->logme('error', "No files or document names provided"); + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'No files or document names provided' + ], 400); + } + + // Upload process + $multi_file_data = $this->uploadMultiFiles($files, $docs_name, $leads_file_primary_key) ?? []; + + $this->myLogger->logme('error', "uploadMultiFiles result: " . json_encode($multi_file_data ?? [])); + + if (!empty($multi_file_data)) { + $this->insertMultiFilesData($multi_file_data, $lead_id, $lead_form_type); + $this->myLogger->logme('error', "Files inserted successfully into DB"); + + // update lead file name if change + if(isset($multi_file_data[0]['file_name']) && !empty($multi_file_data[0]['file_name'])){ + $this->leadsModel->where('id', $lead_id)->set('file_name', $multi_file_data[0]['file_name'])->update(); + } + + } else { + $this->myLogger->logme('error', "uploadMultiFiles returned empty"); + } + + + // Get the updated lead file data + $lead_file_data = $this->leadFilesModel + ->where('is_active', 1) + ->where('type !=', 2) + ->where('lead_id', $lead_id) + ->findAll(); + + $this->myLogger->logme('error', "Fetched " . count($lead_file_data) . " lead file records"); + + $document_data = $this->renderFileFields($lead_file_data); + $attch_data['multi_file_data'] = $lead_file_data; + $attachment_html = view('rfq/attachment_files', $attch_data) ?? ""; + + $this->myLogger->logme('error', "uploadMultiFileFromRfq END"); + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'message' => "File uploaded Successfully", + 'document_data' => $document_data, + 'attachment_html' => $attachment_html, + ], 200); + + } catch (\Throwable $e) { + + $errorDetails = [ + 'error_message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'stack_trace' => $e->getTraceAsString(), + ]; + + // Catch any error/exception and log with trace + $this->myLogger->logme('error', "Exception in uploadMultiFileFromRfq: " . json_encode($errorDetails)); + + return $this->respond([ + 'status' => false, + 'code' => 500, + 'message' => "File upload failed: " . $e->getMessage(), + 'errorDetails' => $errorDetails, + ], 500); + } + } + + public function renderFileFields($multi_file_data = []) + { + $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; + $html = ''; + + // If data exists (edit mode) + if (!empty($multi_file_data)) { + + foreach ($multi_file_data as $index => $value) { + + $sample_dwn_link = ' [ Download ]'; + $isFirstField = ($index === 0); + $placeholder = $isFirstField ? 'First file must be Demography.' : ''; + $first_file_name = $isFirstField ? 'Member List' : ''; + $member_data_link = $isFirstField ? $sample_dwn_link : ''; + $read_only = $isFirstField ? 'readonly' : ''; + $accept = $isFirstField ? '.xls,.xlsx' : ''; + $displayIndex = $index + 1; + + $html .= ' +
+ + +
+ + +
+ +
+ + +
+ +
+ + +
+
'; + } + } else { + // Default (add mode) + $html .= ' +
+ + +
+ + +
+ +
+ + +
+ +
+ + +
+
'; + } + + return $html; + } + + public function downloadMemberFile($fileName) + { + $filePath = WRITEPATH . 'uploads/lead_files/' . $fileName; + + if (!file_exists($filePath)) { + $data['message'] = 'The Physical File Not Found'; + echo view('errors/404', $data); + } + + // force download + return $this->response->download($filePath, null); + } + + // ----------- MEMBER DATA VALIDAATION ------------------------------------------------------------------------------------------------------ + + public function memberDataListValidation() + { + $lead_id = $this->request->getPost('lead_id'); + $this->memberDataListExcelFileFormatValidation(['lead_id' => $lead_id]); + } + + public function memberDataListExcelFileFormatValidation($params) + { + helper('excel_util_helper'); + + $this->myLogger->logme('error', 'Start memberDataListExcelFileFormatValidation'); + $this->myLogger->logme('error', "Received params: " . json_encode($params)); + + $lead_id = $params['lead_id']; + $age_validation_check = $params['age_validation'] ?? null; + $lead_data = $this->leadsModel->where('id', $lead_id)->first(); + // dd($lead_data); + + $return = []; + if (!isset($lead_data)) { + $this->myLogger->logme('error', "Lead not found for lead_id: {$lead_id}"); + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([12]),'error_data' => 'file not found in DB'])])->update(); + return array('status' => false, 'msg' => 'file not found in DB'); + } + + //get the lead files data + $lead_file_data = $this->leadFilesModel->where('is_active', 1)->where('type', 2)->first(); + + //check the lead file table has the error data entry if not than create new entry + if(empty($lead_file_data)){ + $data['type'] = 2; + $data['file_name'] = $lead_data['file_name']; + $data['docs_name'] = "Member List"; + $data['lead_id'] = $lead_id; + $lead_file_last_insert_id = $this->leadFilesModel->insert($data); + $this->myLogger->logme('error', "New lead file entry created for store the error data, insert_id : '{$lead_file_last_insert_id}'"); + } + + $family_composition = []; + if($age_validation_check && !empty($lead_data['proposel_data'])){ + $family_composition = $this->getAgeRatioFromRfqJson($lead_id, $lead_data['proposel_data']); + $this->myLogger->logme('info', 'Family composition :',json_encode($family_composition)); + } + // dd($family_composition); + + // get the file path + $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; + $this->myLogger->logme('error', "File path: {$file_name_with_path}"); + + //check physical file + if (!file_exists($file_name_with_path)) { + //file not found update status and reason + $message = "Physcial file not found"; + $this->myLogger->logme('error', ($message . ' for lead id ' . $lead_id)); + $this->leadFilesModel + ->where('lead_id', $lead_id) + ->where('type', 2) + ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])]) + ->update(); + return array('error_summary' => [5], 'error_data' => $message); + } + + $this->myLogger->logme('info', 'File exists, starting validation process'); + + //start validation process + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // dd($highestRowAndColumn); + + $columns_to_check = $this->member_data_excel_columns; + + $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []]; + $keys = array_keys($columns_to_check); + $allowedHighestColumn = end($columns_to_check); + $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data); + $this->myLogger->logme('error', 'Excel data sanitized count : {row_count}', ['row_count' => count($excel_data)]); + // dd($excel_data); + + //check number of columns in excel + $excel_columns = ($excel_data[0]); + + //check columns order in excel + $column_count_res = check_columns_name_exist($columns_to_check, $excel_columns); + // dd($column_count_res); + + if (isset($column_count_res) && count($column_count_res)) { + //columns count mismatch + $message = implode("\n", $column_count_res); + // echo $message; + $this->myLogger->logme('error', ($message . ' for lead id ' . $lead_id)); + $this->leadFilesModel + ->where('lead_id', $lead_id) + ->where('type', 2) + ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([6]),'error_data' => $message])]) + ->update(); + return array('error_summary' => [6], 'error_data' => $message); + } + + $relationship = $this->general_relationships; + + $column_count_res = update_excel_column_indexes($columns_to_check, $excel_columns); + // dd($column_count_res); + + //remove header + unset($excel_data[0]); + $member_family_data = []; + foreach ($excel_data as $row_key => $row) { + + //1. avoid empty rows + if (check_row_is_empty_or_null($row)) { + $this->myLogger->logme('error', "Empty row found at index {$row_key}, stopping row iteration"); + break; + } + + //iterate each row for columns validations + foreach ($row as $col_key => $col) { + + $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory']; + $format = $columns_to_check[$keys[$col_key]]['format']; + $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values']; + $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null; + $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null; + + $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name']; + $column_index = $columns_to_check[$keys[$col_key]]['col_idx']; + $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name']; + + + //mandatory check + if (is_bool($is_mandatory) && $is_mandatory === true) { + if ($col == "" || $col == NULL) { + array_push($result['error_summary'], 1); //push error code for summary + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc + } + } + + //if is_mandatory is array (action based mandatory check) + if (is_array($is_mandatory)) { + $allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory']; + if ($col == "" || $col == NULL) { + array_push($result['error_summary'], 1); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event'; + } + } + + //format check + if (isset($format)) { + $format_error = check_excel_date_format($col, $format); + if (!$format_error['status']) { + array_push($result['error_summary'], 2); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error']; + } + } + + //allowed values check + if (($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values)))) { + if (!in_array((trim($col)), $allowed_values)) { + array_push($result['error_summary'], 3); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col"; + } + } + + //custom function check + if (isset($custom_function)) { + //convert string params into PHP variables + // Create an array of variables to pass custom helper funcitons + $param_values = []; + foreach ($binding_params as $bkey => $bparam) { + $param_values[] = ($$bparam); + } + // dd(($param_values));//die(); + $res = call_user_func_array($custom_function, $param_values); + if ($res['status'] === false) { + array_push($result['error_summary'], 4); + $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error']; + } + } + } + + //age validation + $age_validation = isset($columns_to_check['dob']['age_validation']) ?? null; + if (isset($age_validation) && $age_validation && $age_validation_check && !empty($family_composition)) { + $format_error = check_age_validation($row, $family_composition); + if (!$format_error['status']) { + array_push($result['error_summary'], 2); + $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_name'] = $columns_to_check['dob']['col_name']; //push column name + $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_idx'] = $columns_to_check['dob']['col_idx']; //push column index + $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['error'][] = $format_error['error']; + } + } + + $row['row_index'] = $row_key; + $relation_idx = $columns_to_check['relationship']['col_idx']; + $emp_code_idx = $columns_to_check['emp_code']['col_idx']; + + if (isset($row[$relation_idx]) && strtolower($row[$relation_idx]) == 'self' && isset($member_family_data[$row[$emp_code_idx]])) { + array_unshift($member_family_data[$row[$emp_code_idx]], $row); + } else { + $member_family_data[$row[$emp_code_idx]][] = $row; + } + } + // dd($member_family_data); + + $this->myLogger->logme('info', 'Row validation completed, starting duplicate check'); + $check_row_dublicate = check_duplicate_rows_and_contacts($excel_data, $columns_to_check, $result); + // dd($check_row_dublicate); + + if(count($check_row_dublicate)){ + $result = $check_row_dublicate; + } + + $this->myLogger->logme('info', 'Starting family validation'); + $result = validateFamily($member_family_data, $columns_to_check, $result); + // dd($family_validation); + + if (isset($result['error_summary']) && count($result['error_summary'])) { + $result['error_summary'] = array_count_values($result['error_summary']); + $status = 'failed'; + $failure_reason = ((json_encode($result))); + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => $status,'error_data' => $failure_reason])->update(); + $this->myLogger->logme("error", '{lead_id} uploaded failed for this lead id', ['lead_id' => $lead_id]); + } else { + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'success','error_data' => ''])->update(); + $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => ['lead_id' => $lead_id]]); + } + + return $result; + } + + public function getAgeRatioFromRfqJson($lead_id, $porposel_data) + { + $age_ratio = []; + $rfq_data = $this->RFQModel->where('is_active', 1)->where('lead_id', $lead_id)->orderBy('id', 'desc')->first(); + if(empty($rfq_data) || empty($rfq_data['json'])){ + return $age_ratio; + } + + $data = json_decode($rfq_data['json'], true); + $proposal_and_insurer = json_decode($porposel_data, true); + $insurer_key = $proposal_and_insurer['insurer_name'] ?? null; + + if(isset($data['table_data']['data'])){ + foreach ($data['table_data']['data'] as $key => $value) { + if($value['items'] == 'family_composition'){ + foreach ($value['data'] as $family_composition) { + if($family_composition['subth'] == $insurer_key){ + $age_ratio = json_decode($family_composition['input_value'] ?? "", true) ?? []; + } + } + } + } + } + + return $age_ratio; + } + + public function getMemberDataExcelFileErrors() + { + $lead_id = $this->request->getGet('lead_id'); + // $lead_id = 329; + + // Render views and capture output + $result = $this->getMemberDataListExcelErrorData($lead_id); + + if ($result != 0) { + + $result['lead_id'] = $lead_id; + echo view('excel_errors', $result); + } else if ($result == 0) { + + $data['message'] = 'File Not Found Physically'; + return view('errors/404', $data); + } else { + + echo view('errors/html/production'); + } + } + + public function getMemberDataListExcelErrorData($lead_id) + { + try { + $file = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first(); + $error_data = json_decode($file['error_data']); + // dd($error_data); + // return $error_data; + + $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $file['file_name']; + + //check the file exist or not + if (!file_exists($file_name_with_path)) { + $error_message = "File not found"; + $this->myLogger->logme('error', ($error_message . ' for file id ' . $lead_id)); + return 0; + } + + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $excelErrorData['excel_header'] = $excel_data[0]; + unset($excel_data[0]); + // Kint::dump($excel_data); + + if ($error_data->error_type == 1) { + + $finalArray = []; + foreach ($error_data->error_data as $key => $value) { + + foreach ($value as $key2 => $value2) { + $error_data = $value2->error; + $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data,]; + $excel_data[$key][$value2->col_idx] = $data; + } + array_push($finalArray, $excel_data[$key]); + } + + foreach ($finalArray as $fkey => $value) { + foreach ($value as $vkey => $arrayData) { + if (!is_array($arrayData)) { + $data = ['value' => $arrayData]; + $finalArray[$fkey][$vkey] = $data; + } + } + } + + $excelErrorData['excel_data'] = $finalArray; + return $excelErrorData; + } else if ($error_data->error_type == 2) { + + + $allErrors = []; + $typeTowArray = []; + + foreach ($error_data->error_data as $index => $item) { + + foreach ($item as $field) { + if (!isset($allErrors[$index])) { + $allErrors[$index] = []; + } + $allErrors[$index] = array_merge($allErrors[$index], $field->error); + } + } + + // dd(array_keys($allErrors)); + foreach ($allErrors as $key => $value) { + // echo $key; + // print_r($value); + foreach ($excel_data as $excel_data_index => $excel_data_value) { + if ($excel_data_value[0] == $key) { + $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,]; + $excel_data[$excel_data_index][1] = $data; + array_push($typeTowArray, $excel_data[$excel_data_index]); + break; + } + } + } + // dd($data); + foreach ($typeTowArray as $fkey => $value) { + foreach ($value as $vkey => $arrayData) { + if (!is_array($arrayData)) { + $data = ['value' => $arrayData]; + $typeTowArray[$fkey][$vkey] = $data; + } + } + } + + $excelErrorData['excel_data'] = $typeTowArray; + return $excelErrorData; + } + } catch (\Exception $e) { + // Handle any exceptions + $errorMessage = $e->getMessage(); //die(); + $this->myLogger->logme('error', $errorMessage); + return false; // You can return an error response here + } + } + + public function downloadFullMemberDataExcelErrorFile($lead_id, $rowIndex = 1, $colIndex = 1) + { + // Get file data from the database + $file_data = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first(); + + $error = json_decode($file_data['error_data']); + + // Check if the file exists + if (!$file_data) { + $error_message = "File not found"; + $this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id); + return $error_message; + } + + $fileName = $file_data['file_name']; + $filePath = WRITEPATH . '/uploads/lead_files/' . $fileName; + + // Check if the file exists + if (!file_exists($filePath)) { + $error_message = "File not found"; + $this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id); + $data['message'] = 'Physical File Not Found'; + return view('errors/404', $data); + } + + // Load the Excel file + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath); + $sheet = $spreadsheet->getActiveSheet(); + + foreach ($error->error_data as $index => $error_data) { + + $rowIndex = $index + 1; + + if ($error->error_type == 1) { + + foreach ($error_data as $key => $value) { + + $colIndex = $value->col_idx + 1; + + $originalValue = $sheet->getCell([$colIndex, $rowIndex])->getValue(); + + $newValue = implode(', ', $value->error); + $val = $originalValue . ' ( ' . $newValue . ' )'; + $sheet->setCellValue([$colIndex, $rowIndex], $val); + + $style = [ + 'fill' => [ + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'ffad99'] // Red color + ] + ]; + + $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style); + } + } else if ($error->error_type == 2) { + + + foreach ($error_data as $key => $value) { + + + $originalValue = $sheet->getCell([1, $rowIndex])->getValue(); + + $newValue = implode(', ', $value->error); + $val = $originalValue . ' ( ' . $newValue . ' )'; + $sheet->setCellValue([$colIndex, $rowIndex], $val); + + $style = [ + 'fill' => [ + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'ffad99'] // Red color + ] + ]; + $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style); + } + } + } + + // Create a new filename for the modified Excel file + $newFileName = 'error_with_highlight_' . $fileName; + + // Save the modified Excel file to a new location + $newFilePath = WRITEPATH . '/uploads/lead_files/' . $newFileName; + $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); + $writer->save($newFilePath); + + // Set headers to force download + $response = service('response'); + $response->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $response->setHeader('Content-Disposition', 'attachment;filename="' . $newFileName . '"'); + $response->setHeader('Cache-Control', 'max-age=0'); + $response->setHeader('Content-Length', filesize($newFilePath)); + $response->setBody(file_get_contents($newFilePath)); + + // Delete the temporary file + unlink($newFilePath); + + // Return the response + return $response; + } + + public function savePlacementDataAndValidateMemberDataFile() + { + try { + + $this->myLogger->logme('error', '--- savePlacementDataAndValidateMemberDataFile START ---'); + + $params = $this->request->getPost(); + $this->myLogger->logme('error', 'Received params: ' . json_encode($params)); + + if (empty($params['lead_id'])) { + $this->myLogger->logme('error', 'Lead ID missing'); + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'Lead ID is required' + ], 400); + } + + $lead_id = $params['lead_id']; + $proposal_insurer = $params['proposal_insurer'] ?? ''; + + // Handle proposal and insurer details + if (!empty($proposal_insurer) && strpos($proposal_insurer, '-') !== false) { + list($proposal_key, $insurer_key) = explode('-', $proposal_insurer, 2); + $lead_update_data = json_encode([ + 'proposel_name' => $proposal_key, + 'insurer_name' => $insurer_key, + 'insurer' => $params['insurer_and_branch'] ?? null, + ]); + $this->myLogger->logme('error', "Proposal/Insurer parsed successfully: $proposal_key - $insurer_key"); + } else { + $lead_update_data = null; + $this->myLogger->logme('error', 'Proposal/Insurer not provided or invalid format'); + } + + $data = [ + 'proposel_data' => $lead_update_data, + 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, + 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, + 'utr_no' => $params['utr_no'] ?? null, + 'is_cd' => $params['is_cd'] ?? null, + 'premium_amount' => $params['premium_amount'] ?? null, + 'total_amount' => $params['total_amount'] ?? null, + 'cd_amount' => $params['cd_amount'] ?? null, + 'no_of_installment' => $params['no_of_installment'] ?? null, + 'is_installment' => $params['is_installment'] ?? null, + 'acm_id' => $params['acm_pk'] ?? null, + ]; + + // get lead data + $lead_data = $this->leadsModel->where('id', $lead_id)->first(); + + // Compare and update only if changed the start and end date + if (!empty($params['policy_start_date'])) { + $converted_start = change_date_format($params['policy_start_date']); + if ($converted_start !== $lead_data['policy_start_date']) { + $data['policy_start_date'] = $converted_start; + $this->myLogger->logme('error', "Policy start date updated: $converted_start"); + } + } + + if (!empty($params['policy_end_date'])) { + $converted_end = change_date_format($params['policy_end_date']); + if ($converted_end !== $lead_data['policy_end_date']) { + $data['policy_end_date'] = $converted_end; + $this->myLogger->logme('error', "Policy end date updated: $converted_end"); + } + } + + // Handle TPA details + if (!empty($params['tpa_id']) && strpos($params['tpa_id'], '-') !== false) { + list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']); + $data['tpa_branch_id'] = $tpaBranchId; + $data['tpa_id'] = $tpaId; + $this->myLogger->logme('error', "TPA details added: branch=$tpaBranchId, id=$tpaId"); + } + + $this->myLogger->logme('error', 'Prepared lead update data: ' . json_encode($data)); + + // Update main lead record + $this->leadsModel->update($lead_id, $data); + $this->myLogger->logme('error', "Lead updated successfully for ID: $lead_id"); + + // Save installment details + if (!empty($params['installments'])) { + $installments = json_decode($params['installments'], true); + $this->myLogger->logme('error', "Installments data received: " . json_encode($installments)); + + if (is_array($installments) && !empty($installments)) { + foreach ($installments as $installment) { + $installment['payment_date'] = !empty($installment['payment_date']) && strtotime($installment['payment_date']) + ? date('Y-m-d', strtotime($installment['payment_date'])) + : null; + + $installment['lead_id'] = $lead_id; + + if (!empty($installment['id'])) { + $this->leadInstallmentPaymentDetails->update($installment['id'], $installment); + $this->myLogger->logme('error', "Installment updated: " . json_encode($installment)); + } else { + $this->leadInstallmentPaymentDetails->insert($installment); + $this->myLogger->logme('error', "Installment inserted: " . json_encode($installment)); + } + } + } + } else { + $this->myLogger->logme('error', "No installments provided"); + } + + // Update lead file status to pending + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'pending'])->update(); + + // Queue job after save + $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => ['lead_id' => $lead_id, 'age_validation' => true]]); + $this->myLogger->logme('error', "Job queued successfully: " . json_encode($r)); + + $this->myLogger->logme('error', "--- savePlacementDataAndValidateMemberDataFile END (SUCCESS) ---"); + + return $this->respond([ + 'status' => true, + 'code' => 200, + 'message' => 'Placement data saved successfully. File being validated', + 'lead_id' => $lead_id, + 'data' => $data, + 'params' => $params + ], 200); + + } catch (\Exception $e) { + $errorDetails = [ + 'error_message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'stack_trace' => $e->getTraceAsString(), + ]; + $this->myLogger->logme('error', "--- savePlacementDataAndValidateMemberDataFile ERROR --- " . json_encode($errorDetails)); + return $this->respond([ + 'status' => false, + 'code' => 500, + 'message' => 'Error while validating the member data', + 'error' => $errorDetails + ], 500); + } + } + + public function checkMemberDataFileValidationStatus() + { + $lead_id = $this->request->getVar('lead_id'); + if (empty($lead_id)) { + return $this->respond([ + 'status' => false, + 'code' => 400, + 'message' => 'lead_id is required' + ], 400); + } + + // Fetch file validation status + $lead_file = $this->leadFilesModel + ->select('id, lead_id, status') + ->where('lead_id', $lead_id) + ->where('type', 2) + ->first(); + + if (!$lead_file) { + return $this->respond([ + 'status' => false, + 'code' => 404, + 'message' => 'No file found for this lead_id' + ], 404); + } + + // If validation is still running + if ($lead_file['status'] === 'pending' || $lead_file['status'] === null) { + return $this->respond([ + 'status' => true, + 'code' => 202, // Accepted - still processing + 'message' => 'Validation in progress', + 'data' => ['status' => $lead_file['status']] + ], 200); + } + + // If validation finished (success or failed) + return $this->respond([ + 'status' => true, + 'code' => 200, + 'message' => 'Validation completed', + 'data' => $lead_file + ], 200); + } + + + // ----------- END OF MEMBER DATA VALIDAATION ------------------------------------------------------------------------------------------------------ + } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index c26d6fb8..013a9324 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -107,7 +107,8 @@ class MasterController extends AdminController public function insurerList() { $this->myLogger->logme('error','Insurer list function called'); - $headerData['page_name'] = 'Insurer List'; + $headerData['tab_name'] = 'Insurer List'; + $headerData['page_name'] = 'Insurers'; $data['insurerList'] = $this->insurerModel->where('is_active',1)->findAll(); $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM(); // echo '
';
@@ -154,7 +155,8 @@ class MasterController extends AdminController
     {
 
         $this->myLogger->logme('error','Edit Insurer Onboarding function called');
-        $headerData['page_name'] = 'Edit Insurer Master';
+        $headerData['tab_name'] = 'Edit Insurer Master';
+        $headerData['page_name'] = 'Insurers';
 
         $types = array(
             (object) array('id' => 'pvt', 'name' => 'PVT'),
@@ -245,7 +247,8 @@ class MasterController extends AdminController
     {
         
         $this->myLogger->logme('error','Insurer Onboarding function called');
-        $headerData['page_name'] = 'Insurer Master';
+        $headerData['tab_name'] = 'Insurer Master';
+        $headerData['page_name'] = 'Insurers';
 
         $types = array(
             (object) array('id' => 'pvt', 'name' => 'PVT'),
@@ -504,7 +507,8 @@ class MasterController extends AdminController
     public function tpaList()
     {   
         $this->myLogger->logme('error','TPA list function called');
-        $headerData['page_name'] = 'TPA List';
+        $headerData['tab_name'] = 'TPA List';
+        $headerData['page_name'] = 'TPA';
         $data['tpaList'] = $this->tpaModel->where('is_active',1)->findAll();
         // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
         // echo '
';
@@ -550,7 +554,8 @@ class MasterController extends AdminController
     {
         
         $this->myLogger->logme('error','TPA Onboarding function called');
-        $headerData['page_name'] = 'TPA Master';
+        $headerData['tab_name'] = 'TPA Master';
+        $headerData['page_name'] = 'TPA';
 
 
         // print_r($data['types']);die();
@@ -664,7 +669,8 @@ class MasterController extends AdminController
     {
 
         $this->myLogger->logme('error','Edit TPA Onboarding function called');
-        $headerData['page_name'] = 'Edit TPA Master';
+        $headerData['tab_name'] = 'Edit TPA Master';
+        $headerData['page_name'] = 'TPA';
 
         $tpa_data = $this->tpaModel->where(['id' => $id, 'is_active' => 1])->first();
 
@@ -833,7 +839,8 @@ class MasterController extends AdminController
     public function kycList()
     {   
         $this->myLogger->logme('error','KYC list function called');
-        $headerData['page_name'] = 'KYC List';
+        $headerData['tab_name'] = 'KYC List';
+        $headerData['page_name'] = 'KYC';
         $data['kycList'] = $this->kycEntityTypeModel->where('is_active',1)->findAll();
         // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
         // echo '
';
@@ -879,7 +886,8 @@ class MasterController extends AdminController
     {
         
         $this->myLogger->logme('error','KYC Onboarding function called');
-        $headerData['page_name'] = 'KYC Master';
+        $headerData['tab_name'] = 'KYC Master';
+        $headerData['page_name'] = 'KYC';
 
 
         // print_r($data['types']);die();
@@ -944,7 +952,8 @@ class MasterController extends AdminController
     {
 
         $this->myLogger->logme('error','Edit KYC Onboarding function called');
-        $headerData['page_name'] = 'Edit KYC Master';
+        $headerData['tab_name'] = 'Edit KYC Master';
+        $headerData['page_name'] = 'KYC';
 
         $editData['kyc']           = $this->kycEntityTypeModel->where(['id' => $id, 'is_active' => 1])->first();
         $editData['kyc_docs']    = $this->kycDocsModel->where(['kyc_type_id' => $id, 'is_active' => 1])->findAll();
@@ -1022,7 +1031,8 @@ class MasterController extends AdminController
     public function policyTypeList()
     {   
         $this->myLogger->logme('error','Policy Type list function called');
-        $headerData['page_name'] = 'Policy Type List';
+        $headerData['tab_name'] = 'Policy Type List';
+        $headerData['page_name'] = 'Policy Type';
         $data['policyList'] = $this->policyTypeModel->where('is_active',1)->findAll();
         // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
         // echo '
';
@@ -1068,7 +1078,8 @@ class MasterController extends AdminController
     {
         
         $this->myLogger->logme('error','Policy Type Onboarding function called');
-        $headerData['page_name'] = 'Policy Type Master';
+        $headerData['tab_name'] = 'Policy Type Master';
+        $headerData['page_name'] = 'Policy Type';
 
 
         // print_r($data['types']);die();
@@ -1130,7 +1141,8 @@ class MasterController extends AdminController
     {
 
         $this->myLogger->logme('error','Edit KYC Onboarding function called');
-        $headerData['page_name'] = 'Edit Policy Type';
+        $headerData['tab_name'] = 'Edit Policy Type';
+        $headerData['page_name'] = 'Policy Type';
 
         $editData['policytype']   = $this->policyTypeModel->where(['id' => $id, 'is_active' => 1])->first();
         $editData['policies']     = $this->policesModel->select('policies.*, insurers.name as insurer_name')
@@ -1222,7 +1234,8 @@ class MasterController extends AdminController
     //start CD Master list
     public function CDMasterList()
     {   
-        $data['page_name'] = 'CD Master List';
+        $data['tab_name'] = 'CD Master List';
+        $data['page_name'] = 'CD Master';
         $data['CD_Master_Data'] = $this->CDMasterModel->getCDMasterList();
         $data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
         $data['insurer_branch'] = $this->insurerBranchModel->where('is_active', 1)->findAll();
@@ -1605,8 +1618,8 @@ class MasterController extends AdminController
     //Vehicle Master data Function
 
     public function VehicleMasterList()
-    {   
-        $data['page_name'] = 'Vehicle Master List';
+    {   $data['tab_name'] = 'Vehicle Master';
+        $data['page_name'] = 'Vehicles';
         $data['vehicle_type'] = [
             'two_wheeler' => 'Two Wheeler',
             'four_wheeler' => 'Four Wheeler',
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index 8b2a80bb..db8be45b 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -114,6 +114,7 @@ class PolicyTransactionController extends BaseController
     // Policy Transaction Inception
     public function viewInception()
     {
+        $data['tab_name'] = 'Policy';
         $data['page_name'] = 'Policy';
 
         // Static arrays for dropdowns
@@ -1075,6 +1076,7 @@ class PolicyTransactionController extends BaseController
         // echo '
';
         // !dd($this->getEndorsementDataForEdit(17));
 
+        $data['tab_name'] = 'Endorsement';
         $data['page_name'] = 'Endorsement';
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
         $data['issuer_branch'] = $this->nhanceBranchModel->where('is_active', 1)->findAll();
@@ -1241,7 +1243,8 @@ class PolicyTransactionController extends BaseController
         $issue_type = $this->policyTransactionModel
             ->where('action_type', 'inception')
             ->where('client_id', $this->request->getPost('client_id'))
-            ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+            // ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+            ->where('id', $this->request->getPost('client_policy_id'))
             ->where('policy_transaction.is_active', 1)
             ->first();
 
@@ -1770,7 +1773,7 @@ class PolicyTransactionController extends BaseController
     //get BDS Reports data old function
     public function reportBDSOld()
     {
-
+        $data['tab_name'] = 'BDS Report';
         $data['page_name'] = 'BDS Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1832,6 +1835,7 @@ class PolicyTransactionController extends BaseController
     public function reportBDS()
     {
 
+        $data['tab_name'] = 'BDS Report';
         $data['page_name'] = 'BDS Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1925,6 +1929,7 @@ class PolicyTransactionController extends BaseController
 
     public function reportVarience()
     {
+        $data['tab_name'] = 'Variance Report';
         $data['page_name'] = 'Variance Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -1974,6 +1979,7 @@ class PolicyTransactionController extends BaseController
 
     public function reportBusinessList()
     {
+        $data['tab_name'] = 'Business Report';
         $data['page_name'] = 'Business Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -2014,6 +2020,7 @@ class PolicyTransactionController extends BaseController
 
     public function reportFinanceList()
     {
+        $data['tab_name'] = 'Finance Report';
         $data['page_name'] = 'Finance Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -2054,6 +2061,7 @@ class PolicyTransactionController extends BaseController
 
     public function reportOutstanding()
     {
+        $data['tab_name'] = 'Outstanding Report';
         $data['page_name'] = 'Outstanding Report';
 
         $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
@@ -2132,6 +2140,7 @@ class PolicyTransactionController extends BaseController
             ->findAll();
 
         // dd( $this->insurerStatements->getLastQuery());
+        $data['tab_name'] = 'Statement Upload';
         $data['page_name'] = 'Statement Upload';
 
         $this->loadLayout('insurer_statement_list',  $data);
@@ -2709,8 +2718,8 @@ class PolicyTransactionController extends BaseController
             $data['files'] = array_merge($pt_files, $kyc_files, $batch_files, $files);
             //  dd($data['files']);
         }
-
-        $data['page_name'] = 'Documents Search';
+        $data['tab_name'] = 'Documents Search';
+        $data['page_name'] = 'Documents';
 
         $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active', 1)->get()->getResultarray();
         $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value")
@@ -3054,9 +3063,28 @@ class PolicyTransactionController extends BaseController
 
         $clientIds = array_column($clients, 'id');
 
-        $policies = $this->clientPolicyModel
+        // $policies = $this->clientPolicyModel
+        //     ->select("
+        //             client_policy.*, 
+        //             policy_type.policy_type,
+        //             policy_type.ebp,
+        //             policy_type.etp,
+        //             policy_type.iep,
+        //             policy_type.itp,
+        //             policy_type.bap,
+        //             policy_type.allocg,
+        //             DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
+        //             DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
+        //         ")
+        //     ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+        //     ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null')
+        //     ->whereIn('client_policy.client_id', $clientIds)
+        //     ->where('client_policy.is_active', 1)
+        //     ->findAll();
+
+        $policies = $this->policyTransactionModel
             ->select("
-                    client_policy.*, 
+                    policy_transaction.*, 
                     policy_type.policy_type,
                     policy_type.ebp,
                     policy_type.etp,
@@ -3064,14 +3092,14 @@ class PolicyTransactionController extends BaseController
                     policy_type.itp,
                     policy_type.bap,
                     policy_type.allocg,
-                    DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
-                    DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
+                    DATE_FORMAT(policy_transaction.policy_start_date, '%d/%m/%Y') as policy_start_date,
+                    DATE_FORMAT(policy_transaction.policy_end_date, '%d/%m/%Y') as policy_end_date
                 ")
-            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
-            ->join('policy_transaction pt', 'pt.client_policy_id = client_policy.id and pt.action_type = "inception" and pt.is_active = 1 and pt.client_policy_id is not null')
-            ->whereIn('client_policy.client_id', $clientIds)
-            ->where('client_policy.is_active', 1)
-            ->findAll();
+            ->join('policy_type', 'policy_type.id = policy_transaction.policy_type_id')
+            ->whereIn('policy_transaction.client_id', $clientIds)
+            ->where('policy_transaction.is_active', 1)
+            ->where('policy_transaction.action_type', "inception")
+        ->findAll();
 
         foreach ($policies as $policy) {
             $policyList[$policy['client_branch_id']][] = $policy;
diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php
index b2567d9c..24f22283 100755
--- a/app/Controllers/RestAuthenticationController.php
+++ b/app/Controllers/RestAuthenticationController.php
@@ -79,10 +79,6 @@ class RestAuthenticationController extends AdminController
 
 
 
-
-
-
-
     public function verifyEmployeeWithMobileNumber()
     {   
         log_message('error', '  ');
@@ -93,6 +89,7 @@ class RestAuthenticationController extends AdminController
 
         try {
             $mobile_number = $this->request->getJSON()->mobile_number;
+            $otp = $this->request->getJSON()->otp;
             $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Received mobile_number = " . $mobile_number);
           
 
@@ -112,12 +109,49 @@ class RestAuthenticationController extends AdminController
         
             if (isset($employeeData['employee_id'])) 
             {
-                $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee found: employee_id = " . $employeeData['employee_id']);
+                $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee verified with ID = " . $employeeData['employee_id']);
                 log_message('error', '  ');
-                log_message('error', ' ************************************* POST END **************************************** ');
-                log_message('error', '  ');
-                $result = ['user_verification' => true ,'message' => "Verified Successfully"];
-                return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
+                log_message('error', '************************ POST END ********************************');
+
+               
+                $sql = "
+                    UPDATE employees
+                    INNER JOIN employee_polices ON employee_polices.employee_id = employees.id
+                    SET employees.otp = ?
+                    WHERE employees.id = ?
+                    AND employees.relationship = 'self'
+                    AND employees.is_active = 1
+                    AND employee_polices.is_active = 1
+                    AND employee_polices.status IN ('active')
+                ";
+
+                $db = db_connect();
+                $update = $db->query($sql, [$otp, $employeeData['employee_id']]);
+
+                $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: OTP update query executed. SQL = " . $db->getLastQuery());
+
+                if($update)
+                {
+                    //send sms 
+                    $SMSResult = sendOtpSms($mobile_number, $otp);
+                    if ($SMSResult['status'] == 'success') 
+                    {
+                        $result = ['user_verification' => true ,'message' => "Verified Successfully" ];
+                        return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
+                    }else{
+                        $result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
+                        return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
+                    }
+
+                }else{
+
+                    $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: OTP update query Failed. SQL = " . $db->getLastQuery());
+
+                    $result = ['user_verification' => false, 'message' => "Try again. , try again"];
+                    return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
+
+                }
+
             } else {
                 $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: No matching employee found");
                 log_message('error', '  ');
@@ -148,6 +182,7 @@ class RestAuthenticationController extends AdminController
         try {
 
             $email = $this->request->getJSON()->email;
+            $otp = $this->request->getJSON()->otp;
             $client_id = $this->request->getJSON()->client_id ?? null;
 
 
@@ -181,11 +216,6 @@ class RestAuthenticationController extends AdminController
 
             if (isset($employeeData['employee_id'])) {
 
-                $otp = random_int(100000, 999999);
-
-                // $update  = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'Self')
-                //     ->where('is_active', 1)->set(array('otp' => $otp))
-                //     ->update();
 
                 $builder = $this->employeeModel
                     ->where('email_corporate', $email)
@@ -265,24 +295,23 @@ class RestAuthenticationController extends AdminController
         $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateEmpOTP: Received payload = " . json_encode($this->request->getJSON() ?? []));
 
         
-        $email = $this->request->getJSON()->email;
+        $email = $this->request->getJSON()->email ?? null;
+        $mobile_number = $this->request->getJSON()->mobile_number ?? null;
         $otp = $this->request->getJSON()->otp;
         $client_id = $this->request->getJSON()->client_id ?? null;
         $employee_id = $this->request->getJSON()->employee_id ?? null;
 
         $builder = $this->employeeModel
-            ->where('email_corporate', $email)
             ->where('relationship', 'Self')
             ->where('is_active', 1);
 
-        // $builder = $this->employeeModel
-        //     ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
-        //     ->where('employees.email_corporate', $email)
-        //     ->where('employees.relationship', 'Self')
-        //     ->where('employees.is_active', 1)
-        //     ->whereIn('employees.emp_status', ['active', 'expired'])
-        //     ->where('EP.is_active', 1)
-        //     ->whereIn('EP.status', ['active', 'expired']);
+        if (!empty($email)) {
+            $builder->where('email_corporate', $email);
+        }
+
+        if (!empty($mobile_number)) {
+            $builder->where('mobile', $mobile_number);
+        }
 
 
         if (!empty($client_id)) {
@@ -306,58 +335,7 @@ class RestAuthenticationController extends AdminController
 
     }
 
-    // public function updateEmpMPIN()
-    // {
-    //     $requestData = $this->request->getJSON();
-    //     print_r($requestData); die;
-    //     $mobile_number = $requestData->mobile_number ?? null;
-    //     $email_id = $requestData->email_id ?? null;
-    //     $new_mpin = $requestData->new_mpin ?? $requestData->mpin ?? null;
-    //     $old_mpin = $requestData->old_mpin ?? null;
-    //     $is_mpin_skipped = $requestData->is_mpin_skipped ?? null;
-    //     $is_biometric_enabled = $requestData->is_biometric_enabled ?? null;
-
-    //     if (!$new_mpin) {
-    //         return $this->response->setJSON(['status' => false, 'message' => 'MPIN is required.']);
-    //     }
-
-    //     $query = $this->employeeModel->where('relationship', 'self');
-
-    //     if ($mobile_number) {
-    //         $query->where('mobile', $mobile_number);
-    //     } elseif ($email_id) {
-    //         $query->where('email_corporate', $email_id);
-    //     } else {
-    //         return $this->response->setJSON(['status' => false, 'message' => 'Mobile number or Email ID is required.']);
-    //     }
-
-    //     if (!empty($old_mpin)) {
-    //         $query->where('mpin', $old_mpin);
-    //     }
-
-    //     // Fetch employee data
-    //     $employeeData = $query->first();
-
-    //     if (!$employeeData) {
-    //         return $this->response->setJSON(['status' => false, 'message' => 'Employee not found or invalid MPIN.']);
-    //     }
-
-    //     if(!empty($is_mpin_skipped) && !empty($is_biometric_enabled)){
-    //         $mpin_data_to_updata = [
-    //             'mpin' => $new_mpin,
-    //             'is_mpin_skipped' => $is_mpin_skipped,
-    //             'is_biometric_enabled' => $is_biometric_enabled
-    //         ];
-    //     }else{
-    //         $mpin_data_to_updata = ['mpin' => $new_mpin];
-    //     }
-
-    //     // Update MPIN
-    //     $updated = $this->employeeModel->update($employeeData['id'], $mpin_data_to_updata);
-
-    //     return true;
-    // }
-
+ 
     public function updateEmpMPIN()
     {
         try {
@@ -415,17 +393,11 @@ class RestAuthenticationController extends AdminController
 
         try {
            
-            $otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null;
             $mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
-
-            $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
             $email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
+            $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
             $client_id = $this->request->getJSON()->client_id ?? null;
 
-            if (isset($this->request->getJSON()->login_by_hr)) 
-            {
-                $employeeData = $this->employeeModel->where('id', $this->request->getJSON()->employee_id)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
-            }else{
                 if (isset($mobile_number)) 
                 {
                     // $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
@@ -437,7 +409,8 @@ class RestAuthenticationController extends AdminController
                         ->where('employee_polices.is_active', 1)
                         ->whereIn('employee_polices.status', ['active', 'expired'])
                         ->where('employees.is_active', 1)
-                        ->whereIn('employees.emp_status', ['active', 'expired']);
+                        ->whereIn('employees.emp_status', ['active', 'expired'])
+                        ->where('otp', $otp);
 
                     if (!empty($client_id)) {
                         $builder->where('employees.client_id', $client_id);
@@ -464,14 +437,15 @@ class RestAuthenticationController extends AdminController
 
                     $employeeData = $builder->orderBy('employees.id', 'desc')->first();
                 }   
-            }
+            
 
             $lastQuery = $this->employeeModel->db->getLastQuery();
             $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Last Executed Query: " . $lastQuery);        
             $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: employeeData: " . json_encode($employeeData ?? []));        
 
             
-            if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr) || $employeeData && isset($this->request->getJSON()->otp) ) {
+            if ($employeeData && isset($this->request->getJSON()->otp) ) 
+            {
                 $auth =  HttpRequestHelper::getRequestInfo();
                 if ($auth) {
                     $data = [
@@ -503,14 +477,14 @@ class RestAuthenticationController extends AdminController
                 log_message('error', '  '); 
                 log_message('error', '************************ POST END ********************************');
                 log_message('error', '  '); 
-                return $this->respond(['status' => 'failed','code' => 404,'data' => []],200);
+                return $this->respond(['status' => 'failed','code' => 404,'data' => "", 'message' => 'Invalid OTP'],200);
             }
         } catch (\Exception $e) {
             $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - getVerifiedUserData: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() .  " --- Trace: " . $e->getTraceAsString());
             log_message('error', '  ');
             log_message('error', ' ************************************* POST END **************************************** ');
             log_message('error', '  ');
-            return $this->respond(['status' => 'failed','code' => 500,'data' =>[], 'error' => $e->getMessage()],500);
+            return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => "Invalid OTP", 'error' =>  $e->getMessage()],500);
         }
     }
 
@@ -524,17 +498,43 @@ class RestAuthenticationController extends AdminController
     public function verifyHrWithMobileNumber()
     {
         try {
-            $mobile_number = $this->request->getJSON()->mobile_number;
-           
+            $data = $this->request->getJSON();
+
+            $mobile_number = $data->mobile_number;
+            $otp = $data->otp;
+
             $HrData = $this->hrModel->where('mobile', $mobile_number)
                                     ->where('contact_type', 'client')
                                     ->where('is_active', 1)
                                     ->first();
-            
+
+
             if ($HrData) {
                 
-                $result = ['user_verification' => true ,'message' => "Verified Successfully"];
-                return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
+                    $sql = "UPDATE level_contacts SET otp = ? WHERE mobile = ? AND contact_type = 'client' AND is_active = 1";
+
+                    $db = db_connect();
+                    $update = $db->query($sql, [$otp, $mobile_number]);
+
+                    if($update)
+                    {
+                        
+                        //send sms 
+                        $SMSResult = sendOtpSms($mobile_number, $otp);
+                        if ($SMSResult['status'] == 'success') 
+                        {
+                            $result = ['user_verification' => true, 'message' => "Verified Successfully"];
+                            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
+                        } else {
+                            $result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
+                            return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
+                        }
+
+                    }else {
+                        $result = ['user_verification' => false, 'message' => "SMS sending failed , try again"];
+                        return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
+                    }
+
             } else {
                 $result = ['user_verification' => false , 'message' => "User not found"];
                 return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
@@ -552,6 +552,7 @@ class RestAuthenticationController extends AdminController
             $data = $this->request->getJSON();
 
             $email = $data->email;
+            $otp = $data->otp;
            
             $HrData = $this->hrModel->where('email', $email)
                                     ->where('contact_type', 'client')
@@ -559,8 +560,6 @@ class RestAuthenticationController extends AdminController
                                     ->first();
           
             if ($HrData) {
-                
-                $otp = random_int(100000, 999999);
 
                 $sql = "
                         UPDATE level_contacts
@@ -575,7 +574,7 @@ class RestAuthenticationController extends AdminController
 
                 if($update)
                 {
-                    $data->otp = $otp; 
+                   
                    
                     $common = [
                         'login_type' => 'HR login',
@@ -608,39 +607,53 @@ class RestAuthenticationController extends AdminController
             return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
         }
     }
-    
+
     public function updateHROTP()
     {
-        
-        $email = $this->request->getJSON()->email;
-        $otp = $this->request->getJSON()->otp;
-        
-        $this->hrModel->where('email', $email) ->where('contact_type', 'client')
-        ->where('is_active', 1)->set(array('otp' => $otp))
-        ->update();
+       
+        $email = $this->request->getJSON()->email ?? null;
+        $mobile_number = $this->request->getJSON()->mobile_number ?? null;
+        $otp = $this->request->getJSON()->otp ?? null;
 
-        return true;
+       
 
+        $builder = $this->hrModel
+            ->where('contact_type', 'client')
+            ->where('is_active', 1);
+
+        if (!empty($email)) {
+            $builder->where('email', $email);
+        } elseif (!empty($mobile_number)) {
+            $builder->where('mobile', $mobile_number);
+        }
+
+        $builder->set(['otp' => $otp])->update();
+
+        if ($this->hrModel->db->affectedRows() > 0) {
+            return true;
+        }
+
+      
     }
 
+    
+
     public function getVerifiedHrData()
     {
         try {
-            // mobile number 
-            $otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null;
-            $mobile_number = isset($this->request->getJSON()->mobile_no) ? $this->request->getJSON()->mobile_no : null;
-            // email id
+
             $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
             $email = isset($this->request->getJSON()->email) ? $this->request->getJSON()->email : null;
+            $mobile_number = isset($this->request->getJSON()->mobile_no) ? $this->request->getJSON()->mobile_no : null;
 
             if (isset($mobile_number)) 
             {
-                $hrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->first();
+                $hrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->where('otp', $otp)->first();
             }else{
                 $hrData = $this->hrModel->where('email', $email)->where('contact_type', 'client')->where('otp', $otp)->first();
             }
 
-            if ($hrData && $otp_verification == true || $hrData && isset($this->request->getJSON()->otp) ) 
+            if ($hrData) 
             {
 
                 $auth =  HttpRequestHelper::getRequestInfo();
@@ -656,41 +669,73 @@ class RestAuthenticationController extends AdminController
                     $this->authHistoryModel->insert($data);
                                         
                 }
-              
+
 
                 if(isset($this->request->getJSON()->mobile_no)){ 
 
-                    $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id')
+                    $getAllhrData = $this->hrModel->select('level_contacts.id ,level_contacts.mobile , level_contacts.email , clients.id as client_id, clients.client_name, clients.short_name , client_branch.id as client_branch_id,client_branch.branch_name , client_branch.pre_branch_id')
                                             ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left')
+                                            ->join('clients', 'client_branch.client_id = clients.id', 'left')
                                             ->where('level_contacts.mobile', $mobile_number )
                                             ->where('level_contacts.contact_type', 'client')
-                                            ->find();
+                                            ->findAll();
+                    //set otp value null
+                    $this->hrModel->where('mobile', $mobile_number)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update();
 
-                }else if(isset($this->request->getJSON()->otp)){ 
+                }else if(isset($this->request->getJSON()->email)){ 
 
+                    $getAllhrData = $this->hrModel->select('level_contacts.id ,level_contacts.mobile , level_contacts.email , clients.id as client_id, clients.client_name, clients.short_name , client_branch.id as client_branch_id,client_branch.branch_name , client_branch.pre_branch_id')
+                                            ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left')
+                                            ->join('clients', 'client_branch.client_id = clients.id', 'left')
+                                            ->where('level_contacts.email', $email )
+                                            ->where('level_contacts.contact_type', 'client')
+                                            ->findAll();
+                    //set otp value null
                     $this->hrModel->where('email', $email)->where('otp', $otp)->where('contact_type', 'client')->set(['otp'=>null])->update();
-
-                    $hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id')
-                                        ->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left')
-                                        ->where('level_contacts.email', $email )
-                                        ->where('level_contacts.contact_type', 'client')
-                                        ->find();
                 }
 
-                $HRAccessData = $this->getHRAccessData( $hrData['0']['id'] , 'post_enrollment');
+                if(count($getAllhrData))
+                {
+                    
+                    foreach ($getAllhrData as $key => $value) {
 
-                if(isset($HRAccessData['allowed_modules'])){ $hrData['0']['allowed_modules'] =  json_decode($HRAccessData['allowed_modules'],true)['post']; }else{ $hrData['0']['allowed_modules'] = []; }
+                        $HRAccessData = $this->hrAccessControlModel
+                                ->where('post_client_id',$value['client_id'])
+                                ->where('post_branch_id', $value['client_branch_id'])
+                                ->where('post_hr_id', $value['id'])
+                                ->get()->getRowArray();
+
+                       
+                        if (!empty($HRAccessData) && isset($HRAccessData['allowed_modules'])) {
+
+                            $decoded = json_decode($HRAccessData['allowed_modules'], true);
+                            $getAllhrData[$key]['allowed_modules'] = $decoded;
+
+                            $token = JWTToken::encode($HRAccessData);
+                            $getAllhrData[$key]['token'] = $token;
+                            
+                        } else {
+                            $getAllhrData[$key]['allowed_modules'] = [];
+                            $getAllhrData[$key]['token'] = "";
+                        }
+                       
+                    }
+
+                    return $this->respond(['status' => 'success','code' => 200,'data' => $getAllhrData ],200);
+
+                }else {
+
+                    return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'User not found' ],200);
+                }
 
-                $hrData['0']['token_type'] = 'post';
-                $result = JWTToken::encode($hrData['0']);
                
-                
-                return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
+
+              
 
 
             } else {
 
-                return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP" ],200);
+                return $this->respond(['status' => 'failed','code' => 404,'data' => "" , 'message' => 'User not found' ],200);
             }
         } catch (\Exception $e) {
             return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
@@ -829,7 +874,7 @@ class RestAuthenticationController extends AdminController
             log_message('error', '  ');
             log_message('error', ' ************************************* POST END **************************************** ');
             log_message('error', '  ');
-            return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
+            return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => $th],500);
         }
     }
 
@@ -933,7 +978,7 @@ class RestAuthenticationController extends AdminController
             log_message('error', '  ');
             log_message('error', ' ************************************* POST END **************************************** ');
             log_message('error', '  ');
-            return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
+            return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => $th],500);
         }
     }
 
@@ -991,7 +1036,7 @@ class RestAuthenticationController extends AdminController
     //             // $result = $employeeData;
     //             return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
     //         } else {
-    //             return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200);
+    //             return $this->respond(['status' => 'failed','code' => 404,'data' => ""],200);
     //         }
     //     } catch (\Exception $e) {
     //         return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
@@ -1016,7 +1061,7 @@ class RestAuthenticationController extends AdminController
             // print_r($mpin);
 
             if (!$mpin) {
-                return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'MPIN is required'], 400);
+                return $this->respond(['status' => 'failed', 'code' => 400, 'data'   => "", 'message' => 'MPIN is required'], 400);
             }
 
             if ($mobile_number) {
@@ -1057,7 +1102,7 @@ class RestAuthenticationController extends AdminController
                 $employeeData = $builder->orderBy('employees.id', 'desc')->first();
 
             } else {
-                return $this->respond(['status' => 'failed', 'code' => 400, 'data' => 'Mobile number or Email ID is required'], 400);
+                return $this->respond(['status' => 'failed', 'code' => 400, 'data'   => "", 'message' => 'Mobile number or Email ID is required'], 400);
             }
 
             $lastQuery = $this->employeeModel->db->getLastQuery();
@@ -1095,14 +1140,14 @@ class RestAuthenticationController extends AdminController
                 log_message('error', ' ************************************* POST END **************************************** ');
                 log_message('error', '  ');
 
-                return $this->respond(['status' => 'failed','code'   => 404,'data'   => 'Invalid MPIN'], 200);
+                return $this->respond(['status' => 'failed','code'   => 404, 'data'   => "", 'message'   => 'Invalid MPIN'], 200);
             }
         } catch (\Exception $e) {
             $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyMpin: Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() .  " --- Trace: " . $e->getTraceAsString());
             log_message('error', '  ');
             log_message('error', ' ************************************* POST END **************************************** ');
             log_message('error', '  ');
-            return $this->respond(['status' => 'failed','code'   => 500, 'data'   => $e->getMessage()], 500);
+            return $this->respond(['status' => 'failed','code'   => 500, 'data'   => "", 'message'  => $e->getMessage()], 500);
         }
     }
 
@@ -1167,13 +1212,13 @@ class RestAuthenticationController extends AdminController
                 log_message('error', '  ');
                 log_message('error', ' ************************************* POST END **************************************** ');
                 log_message('error', '  ');
-                return $this->respond(['status' => 'success','code' => 200,'data' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'], 'is_biometric_enabled' => $employeeData['is_biometric_enabled']],200);
+                return $this->respond(['status' => 'success','code' => 200,'data' => "", 'message' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'], 'is_biometric_enabled' => $employeeData['is_biometric_enabled']],200);
             } else {
                 $this->myLogger->logme("error", "REST-AUTH-CONTROLLER - checkMpin: Mpin - not found");
                 log_message('error', '  ');
                 log_message('error', ' ************************************* POST END **************************************** ');
                 log_message('error', '  ');
-                return $this->respond(['status' => 'failed','code' => 404,'data' => "Mpin - not found", 'Mpin' =>null],200);
+                return $this->respond(['status' => 'failed','code' => 404,'data' => "", 'message' => "Mpin - not found", 'Mpin' =>null],200);
             }
 
         } catch (\Exception $e) {
@@ -1182,7 +1227,7 @@ class RestAuthenticationController extends AdminController
             log_message('error', ' ************************************* POST END **************************************** ');
             log_message('error', '  ');
 
-            return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
+            return $this->respond(['status' => 'failed','code' => 500,'data' => "", 'message' => $e->getMessage()],500);
         }
     }
 
@@ -1361,6 +1406,10 @@ class RestAuthenticationController extends AdminController
                 ->where('employees.mobile', $mobile_number)
                 ->where('EP.is_active', 1)
                 ->whereIn('EP.status', ['active', 'expired']);
+
+            if (!empty($otp)) {
+                $builder->where('employees.otp', $otp);
+            }
                 
             if (!empty($old_mpin)) {
                 $builder->where('employees.mpin', $old_mpin);
diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php
index cb432d24..e6f377c7 100644
--- a/app/Controllers/TestingController.php
+++ b/app/Controllers/TestingController.php
@@ -5,11 +5,18 @@ namespace App\Controllers;
 use App\Controllers\BaseController;
 use App\Models\EmployeePolicyModel;
 use App\Models\InsurerBranchModel;
+use App\Models\RFQModel;
 use CodeIgniter\HTTP\ResponseInterface;
 use CodeIgniter\API\ResponseTrait;
 use Dompdf\Dompdf;
 use Dompdf\Options;
 
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+
 class TestingController extends BaseController
 {
     use ResponseTrait;
@@ -19,7 +26,7 @@ class TestingController extends BaseController
     {
         $this->myLogger = \Config\Services::mylogger();
     }
-    
+
     public function saveForm()
     {
         // Get JSON input
@@ -34,7 +41,7 @@ class TestingController extends BaseController
     }
 
     public function testcli()
-    {   
+    {
         echo "hi";
         $this->myLogger->logme('error', "test log");
         echo "hi 2";
@@ -78,19 +85,19 @@ class TestingController extends BaseController
         $options->set('debugLayoutBlocks', false);
         $options->set('debugLayoutInline', false);
         $options->set('debugLayoutPaddingBox', false);
-        
+
         // Initialize DomPDF
         $dompdf = new Dompdf($options);
-        
+
         // Load HTML content
         $dompdf->loadHtml($html);
-        
+
         // Set paper size and orientation
         $dompdf->setPaper('A4', 'landscape'); // or 'portrait'
-        
+
         // Render PDF
         $dompdf->render();
-        
+
         // Output PDF to browser
         $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
         $dompdf->stream($filename, ['Attachment' => true]); // Set to false for inline view
@@ -110,7 +117,7 @@ class TestingController extends BaseController
             'POLICY_DATE' => '31/12/2024',
             'INSURER_NAME' => 'ZURICH KOTAK GTNERAL INSURANCE COIIPANY lNDlA LIMITED',
             'TPA_NAME' => 'HealthIndia Insurance TPA Services Pvt. Ltd.',
-            'FRONT_CARD' => base_url() .('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
+            'FRONT_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
             'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
             'LEVELS' => 'Level 1: 1800-XXX-XXXX
Level 2: support@company.com' ]; @@ -126,7 +133,7 @@ class TestingController extends BaseController 'POLICY_DATE' => '31/12/2024', 'INSURER_NAME' => 'ABC Insurance Co.', 'TPA_NAME' => 'XYZ TPA Ltd.', - 'FRONT_CARD' => base_url() .('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'), + 'FRONT_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'), 'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'), 'LEVELS' => 'Level 1: 1800-XXX-XXXX
Level 2: support@company.com' ]; @@ -156,12 +163,12 @@ class TestingController extends BaseController { // Load your HTML template $template = file_get_contents(WRITEPATH . 'e_card_template/common.html'); - + // Replace placeholders with actual data foreach ($data as $key => $value) { $template = str_replace('{' . $key . '}', $value, $template); } - + return $template; } @@ -224,21 +231,21 @@ class TestingController extends BaseController $employeePolicy = new EmployeePolicyModel(); $data = $employeePolicy - ->select('client_policy.policy_type_id') - ->join('employees', 'employee_polices.employee_id = employees.id') - ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id') - ->where('employees.is_active', 1) - ->where('employees.emp_status', ['active', 'expired']) - ->where('employee_polices.is_active', 1) - ->where('employee_polices.status', ['active', 'expired']) - ->where('employees.client_id', $client_id) - ->where('employees.emp_code', $emp_code) - ->groupBy('employee_polices.client_policy_id') - ->findAll(); - + ->select('client_policy.policy_type_id') + ->join('employees', 'employee_polices.employee_id = employees.id') + ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id') + ->where('employees.is_active', 1) + ->where('employees.emp_status', ['active', 'expired']) + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', ['active', 'expired']) + ->where('employees.client_id', $client_id) + ->where('employees.emp_code', $emp_code) + ->groupBy('employee_polices.client_policy_id') + ->findAll(); } - public function ptedfitdata($id){ + public function ptedfitdata($id) + { $policy_transaction = new PolicyTransactionController(); $data = $policy_transaction->getInceptionDataForEdit($id); // dd($data); @@ -248,7 +255,7 @@ class TestingController extends BaseController $dataArray = $data['pt_co_share_details']; // Example $cd_ac_pk = 'CD12345'; $role_id = 1; - $team_id = ['6']; + $team_id = ['6']; $insurer_branch = $insurer_branch; return view('pt_calc_table', [ @@ -313,4 +320,357 @@ class TestingController extends BaseController return $html; } + public function viewRFQNonEb() + { + $insurerBranchModel = new InsurerBranchModel(); + $data['page_name'] = "RFQ NON EB"; + $data['insurer'] = $insurerBranchModel->getInsurerBranchesWithInsurerNames(); + // dd($data); + return $this->loadLayout('view_rfq_non_eb_new', $data); + } + + public function saverfq() + { + $json = $this->request->getPost('json'); + $json = json_encode($json); + print_r($json); + + // $data['lead_id'] = 10000; + // $data['json'] = $json; + // $rfq = new RFQModel(); + + // $rfq->insert($data); + } + + public function exportExcel() + { + $rfq = new RFQModel(); + $policy_data = $rfq->where('lead_id', 10000)->first(); + // print_rr($policy_data['json']); die; + $policy_data = json_decode($policy_data['json'], true); + $policy_data = array_slice($policy_data, 0, -2); + print_rr($policy_data); + die; + dd($policy_data); + } + + + public function mapping_client_id_and_branch_id() + { + + $post_clients_list = $this->getNonDuplicatePostClients(); + + $pre_clients_list = $this->getNonDuplicatePreClients(); + + + + if ( + !empty($pre_clients_list) && + !empty($post_clients_list) + ) { + + $postDB = \Config\Database::connect(); + $preDB = \Config\Database::connect('preDB'); + + foreach ($post_clients_list as $post_client) { + + foreach ($pre_clients_list as $pre_client) { + + if (trim($post_client['short_name']) == trim($pre_client['short_name'])) { + + $postDB->table('clients')->where('id', $post_client['id'])->update(['pre_client_id' => $pre_client['id']]); + + $preDB->table('clients')->where('id', $pre_client['id'])->update(['post_client_id' => $post_client['id']]); + + // upto here we updated client_id in both dbs. + + $post_branches = $postDB->table('client_branch') + ->where('client_id', $post_client['id']) + ->get() + ->getResultArray() ?? []; + + $pre_branches = $preDB->table('client_branch') + ->where('client_id', $pre_client['id']) + ->get() + ->getResultArray() ?? []; + + if (!empty($post_branches) && !empty($pre_branches)) { + + + foreach ($post_branches as $post_branch) { + + $pre_branch = $preDB->table('client_branch') + ->where('client_id', $pre_client['id']) + ->where('branch_code', $post_branch['branch_code']) + ->get() + ->getRowArray() ?? []; + + if (!empty($pre_branch)) { + $postDB->table('client_branch')->where('id', $post_branch['id'])->update(['pre_branch_id' => $pre_branch['id']]); + } + } + + foreach ($pre_branches as $pre_branch) { + + $post_branch = $postDB->table('client_branch') + ->where('client_id', $post_client['id']) + ->where('branch_code', $pre_branch['branch_code']) + ->get() + ->getRowArray() ?? []; + + if (!empty($post_branch)) { + $preDB->table('client_branch')->where('id', $pre_branch['id'])->update(['post_branch_id' => $post_branch['id']]); + } + } + } + } + } + } + } + } + + + private function getNonDuplicatePostClients() + { + + + $postDB = \Config\Database::connect(); + + $sql = "SELECT * + FROM clients AS post_clients + WHERE post_clients.client_type = 1 + AND post_clients.is_active = 1 + AND (post_clients.short_name NOT IN + ( + SELECT ir_post_clients.short_name + FROM clients as ir_post_clients + WHERE ir_post_clients.client_type = 1 + AND ir_post_clients.short_name IS NOT NULL + AND TRIM(ir_post_clients.short_name) <> '' + AND ir_post_clients.is_active = 1 + GROUP BY ir_post_clients.short_name + HAVING COUNT(*) > 1) + ) + ORDER BY post_clients.short_name"; + + $binds = []; + + $query = $postDB->query($sql, $binds); + + $results = $query->getResultArray() ?? []; + + return $results; + } + + private function getNonDuplicatePreClients() + { + + $preDB = \Config\Database::connect('preDB'); + + $sql = "SELECT * + FROM clients AS pre_clients + WHERE pre_clients.client_type = 1 + AND pre_clients.is_active = 1 + AND (pre_clients.short_name NOT IN + ( + SELECT ir_pre_clients.short_name + FROM clients as ir_pre_clients + WHERE ir_pre_clients.client_type = 1 + AND ir_pre_clients.short_name IS NOT NULL + AND TRIM(ir_pre_clients.short_name) <> '' + AND ir_pre_clients.is_active = 1 + GROUP BY ir_pre_clients.short_name + HAVING COUNT(*) > 1) + ) + ORDER BY pre_clients.short_name"; + + $binds = []; + + $query = $preDB->query($sql, $binds); + + $results = $query->getResultArray() ?? []; + + return $results; + } + public function membervalidation($lead_id = 329) + { + $lead_controll = new LeadsController(); + // $lead_controll->getMemberDataExcelFileErrors(); + $res = $lead_controll->memberDataListExcelFileFormatValidation(['lead_id' => $lead_id]); + dd($res); + } + + private $firstNames = [ + 'Rajesh', 'Priya', 'Amit', 'Sneha', 'Vikram', 'Anjali', 'Rahul', 'Deepika', + 'Sanjay', 'Kavita', 'Arun', 'Pooja', 'Manoj', 'Nisha', 'Suresh', 'Meera', + 'Karthik', 'Divya', 'Ravi', 'Lakshmi', 'Anand', 'Swathi', 'Vijay', 'Rekha', + 'Ashok', 'Sangeetha', 'Prakash', 'Uma', 'Ramesh', 'Vani', 'Kumar', 'Radha', + 'Dinesh', 'Shanti', 'Ganesh', 'Parvati', 'Mohan', 'Sita', 'Arjun', 'Geetha' + ]; + + private $lastNames = [ + 'Kumar', 'Sharma', 'Singh', 'Patel', 'Reddy', 'Nair', 'Iyer', 'Krishnan', + 'Rao', 'Gupta', 'Verma', 'Agarwal', 'Joshi', 'Mehta', 'Desai', 'Pillai', + 'Menon', 'Bhat', 'Naidu', 'Varma', 'Malhotra', 'Kapoor', 'Chopra', 'Saxena', + 'Pandey', 'Mishra', 'Tiwari', 'Dubey', 'Sinha', 'Jain', 'Shah', 'Thakur' + ]; + + private $relationships = ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother']; + private $genders = ['M', 'F']; + private $domains = ['gmail.com', 'yahoo.com', 'outlook.com', 'company.com', 'example.com']; + + public function generateExcel() + { + // Increase execution time and memory for large files + ini_set('max_execution_time', 600); + ini_set('memory_limit', '1024M'); + + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + + // Define headers + $headers = [ + 'Sl no', + 'Emp Code', + 'Name', + 'Relationship', + 'Gender', + 'DOB', + 'Age', + 'Email', + 'Mobile', + 'SI', + 'SI Enhancement', + 'Proposed Sum Insured 1', + 'Proposed Sum Insured 2', + 'Proposed Sum Insured 3', + 'Proposed Sum Insured 4' + ]; + + // Set headers in row 1 + $col = 'A'; + foreach ($headers as $header) { + $sheet->setCellValue($col . '1', $header); + $col++; + } + + // Style the header row + $headerStyle = [ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4472C4']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + 'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]] + ]; + $sheet->getStyle('A1:O1')->applyFromArray($headerStyle); + + // Generate 70,000 sample records + $totalRecords = 1000; + $batchSize = 1000; + + for ($i = 1; $i <= $totalRecords; $i++) { + $row = $i + 1; // Start from row 2 (row 1 is header) + + $record = $this->generateSampleRecord($i); + + $sheet->setCellValue('A' . $row, $record['sl_no']); + $sheet->setCellValue('B' . $row, $record['emp_code']); + $sheet->setCellValue('C' . $row, $record['name']); + $sheet->setCellValue('D' . $row, $record['relationship']); + $sheet->setCellValue('E' . $row, $record['gender']); + $sheet->setCellValue('F' . $row, $record['dob']); + $sheet->setCellValue('G' . $row, $record['age']); + $sheet->setCellValue('H' . $row, $record['email']); + $sheet->setCellValue('I' . $row, $record['mobile']); + $sheet->setCellValue('J' . $row, $record['si']); + $sheet->setCellValue('K' . $row, $record['si_enhancement']); + $sheet->setCellValue('L' . $row, $record['proposed_si_1']); + $sheet->setCellValue('M' . $row, $record['proposed_si_2']); + $sheet->setCellValue('N' . $row, $record['proposed_si_3']); + $sheet->setCellValue('O' . $row, $record['proposed_si_4']); + + // Clear memory every batch + if ($i % $batchSize == 0) { + $sheet->garbageCollect(); + } + } + + // Auto-size columns + foreach (range('A', 'O') as $col) { + $sheet->getColumnDimension($col)->setAutoSize(true); + } + + // Generate filename + $filename = 'employee_data_70k_' . date('Y-m-d_His') . '.xlsx'; + + // Set headers for download + header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment;filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + + // Write file to output + $writer = new Xlsx($spreadsheet); + $writer->save('php://output'); + + // Clean up + $spreadsheet->disconnectWorksheets(); + unset($spreadsheet); + exit; + } + + private function generateSampleRecord($index) + { + $firstName = $this->firstNames[array_rand($this->firstNames)]; + $lastName = $this->lastNames[array_rand($this->lastNames)]; + $name = $firstName . ' ' . $lastName; + + $relationship = $this->relationships[array_rand($this->relationships)]; + $gender = $this->genders[array_rand($this->genders)]; + + // Generate random age between 18 and 65 + $age = rand(18, 65); + + // Calculate DOB based on age + $year = date('Y') - $age; + $month = str_pad(rand(1, 12), 2, '0', STR_PAD_LEFT); + $day = str_pad(rand(1, 28), 2, '0', STR_PAD_LEFT); + $dob = "{$day}-{$month}-{$year}"; + + // Generate employee code + $empCode = 'EMP' . str_pad($index, 6, '0', STR_PAD_LEFT); + + // Generate email + $email = strtolower($firstName . '.' . $lastName . $index) . '@' . $this->domains[array_rand($this->domains)]; + + // Generate mobile number (Indian format) + $mobile = '+91' . rand(7000000000, 9999999999); + + // Generate insurance amounts + $siOptions = [100000, 200000, 300000, 500000, 1000000]; + $si = $siOptions[array_rand($siOptions)]; + $si_enhancement = rand(0, 1) ? rand(50000, 200000) : 0; + + $proposed_si_1 = $si + rand(100000, 500000); + $proposed_si_2 = $proposed_si_1 + rand(100000, 500000); + $proposed_si_3 = $proposed_si_2 + rand(100000, 500000); + $proposed_si_4 = $proposed_si_3 + rand(100000, 500000); + + return [ + 'sl_no' => $index, + 'emp_code' => $empCode, + 'name' => $name, + 'relationship' => $relationship, + 'gender' => $gender, + 'dob' => $dob, + 'age' => $age, + 'email' => $email, + 'mobile' => $mobile, + 'si' => $si, + 'si_enhancement' => $si_enhancement, + 'proposed_si_1' => $proposed_si_1, + 'proposed_si_2' => $proposed_si_2, + 'proposed_si_3' => $proposed_si_3, + 'proposed_si_4' => $proposed_si_4 + ]; + } + } diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php index c1896be4..b0c893da 100644 --- a/app/Controllers/ThzController.php +++ b/app/Controllers/ThzController.php @@ -1,654 +1,654 @@ -thzMasterModel = new ThzMasterModel(); - $this->thzMasterNotesModel = new ThzMasterNotesModel(); - $this->thzTypeModel = new thzTypeModel(); - $this->thzHistoryModel = new ThzHistoryModel(); - $this->thzControllerCleaner = new ThzControllerCleaner(); - $this->userModel = new UserModel(); - $this->clientPolicyModel = new ClientPolicyModel(); - $this->clientModel = new ClientModel(); - $this->cientRmModel = new ClientRMModel(); - $this->ticketMailTemplateModel = new TicketMailTemplateModel(); - $this->myLogger = \Config\Services::mylogger(); - } - - public function index() - { - // - } - - public function ticketSave() - { - try { - $data = $this->request->getPost(); - $references = ""; - if (!empty($data['thz_id'])) { - - $text = "update"; - // here insert history Status. - $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); - $result = $this->updateTicket($data); - - $references = ($old && isset($data['status'])) ? $this->handleTicketHistory($old, $data) : "No Details" ; - - $updateID = $data['thz_id']; - } else { - - $text = "create"; - $insertID = $this->insertTicket($data); - $result = true; - $references = ""; - } - - $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; - - $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); - - $this->myLogger->logme('error', 'emailNotificationResult: ' . json_encode($emailNotificationResult)); - - return $this->response->setJSON([ - 'status' => $result ? 'success' : 'error', - 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.", - 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!', - 'ref' => $references - ])->setStatusCode($result ? 200 : 400); - - - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - public function ticketList() - { - - $data['tab_name'] = "Tickets"; - $data['page_name'] = "Tickets"; - try { - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - - - $data = $this->request->getGet(); - - if ($returnType === 'web' && in_array(get_role_id(), [3, 4])) { - $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); - } - - - $tickets = $this->fetchTicketsBasedOnrole($data); - - - if ($returnType === 'api') { - if (empty($tickets)) { - $this->myLogger->logme('error', 'empty tickets in ticket list: ' . json_encode($tickets)); - return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); - } - } else { - $data['ticket_data'] = $tickets; - $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['3', '4'])->findAll(); - // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu , 2-"manager l2 " - ivangalum assign pannalam - // 3,4 remain person varannum. - $data['client_list'] = $this->clientModel->getCreatedByUserName(); - $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); - - return $this->loadLayout('thz_list', $data); - } - - - return $this->response->setJSON([ - 'status' => 'success', - 'data' => $tickets, - ])->setStatusCode(200); - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - public function ticketConversationSave() - { - - try { - $data = $this->request->getPost(); - - $data['notes_type'] = $data['notes_type'] ?? 'External'; - - $result = $this->thzMasterNotesModel->insert($data); - - if (empty($result)) { - $this->myLogger->logme('error', 'Ticket conversation insert failed..!!: ' . json_encode($result)); - throw new \RuntimeException('No tickets found', 404); - } - - $emailNotificationResult = ($data['notes_type'] === "External") - ? $this->ticketConversationSaveNotification($data) - : false; - - return $this->response->setJSON([ - 'status' => $result ? 'success' : 'error', - 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.", - 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' - ])->setStatusCode($result ? 200 : 400); - - - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - public function ticketAutoFetchDetails() - { - try { - $data = $this->request->getPost(); - - $client_id = $data['client_id'] ?? null; - $mobile = $data['mobile'] ?? null; - - if ($client_id && $mobile) { - $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); - - if (empty($details)) { - $this->myLogger->logme('error', 'empty AutoFetchDetails for client_id : ' . json_encode($client_id)); - throw new \RuntimeException('No Data found', 400); - } - - $policyIds = array_filter(array_column($details, 'policy_id')); - $clientPolicy = !empty($policyIds) - ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() - : []; - - $result['client_details'] = $details; - $result['policy_details'] = $clientPolicy ?? []; - } else { - throw new \RuntimeException('Client and Mobile Not found', 400); - } - - return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - public function ticketConversationList() - { - $data = $this->request->getGet(); - - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - - $thz_id = $data['thz_id'] ?? null; - - $ticketType = $data['notes_type'] ?? 'External'; - - if ($thz_id) { - $result['master'] = $this->thzMasterModel - ->select('thz_master.*, user_profiles.first_name as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.thz_id', $thz_id) - ->findAll(); - - if (!empty($result['master'])) { - $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); - $result['notes'] = !empty($notes) ? $notes : []; - } else { - $this->myLogger->logme('error', 'No tickets found for ticket id ' . json_encode($thz_id)); - throw new \RuntimeException('No tickets found', 400); - } - } else { - // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); - throw new \RuntimeException('No tickets found', 404); - } - - if ($returnType === 'api') { - try { - return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } else { - - $assign_to = $result['master'][0]['assign_to']; - $mobile = $result['master'][0]['mobile']; - - $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') - ? $result['master'][0]['policy_id'] - : ''; - - $result['related_tickets'] = $this->thzMasterModel - ->select('thz_master.*, user_profiles.first_name as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.assign_to', $assign_to) - ->where('thz_master.mobile', $mobile) - ->where('thz_master.thz_id !=', $thz_id) - ->where('thz_master.status !=', 'Closed') - ->where('thz_master.status !=', 'Resolved') - ->findAll(); - - $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu - // 2,3,4 remain person varannum. - $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; - - $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); - - return $this->loadLayout('thz_notes', $result); - } - } - - public function ticketType() - { - $method = $this->request->getMethod(); // get, post - try { - if ($method === 'get') { - $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); - if (empty($types)) { - $this->myLogger->logme('error', 'No ticket types found '); - return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); - } - return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); - } - - if ($method === 'post') { - - $data = $this->request->getPost(); - if (!empty($data['id'])) { - $text = "update"; - $result = $this->thzTypeModel->update($data['id'], $data); - $updateID = $data['id']; - } else { - $text = "create"; - $insertID = $this->thzTypeModel->insert($data); - $result = true; - } - - $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); - - return $this->response->setJSON([ - 'status' => $id ? 'success' : 'error', - 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", - 'id' => $id - ])->setStatusCode($id ? 200 : 400); - } - return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - public function ticketHistoryList() - { - try { - $data = $this->request->getGet(); - $thz_id = $data['thz_id']; - // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); - $details = $this->thzHistoryModel->select('thz_history.*, user_profiles.first_name as created_name') - ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') - ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) - ->orderBy('thz_history.created_at', 'desc') - ->get()->getResultArray(); - - - - if (empty($details)) { - $this->myLogger->logme('error', 'No history details found for ticket id ' . json_encode($thz_id)); - throw new \RuntimeException('No History found', 404); - } - - - return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); - } catch (\Throwable $e) { - return handle_exception($e, $this->myLogger, $this->response); - } - } - - - /************************************************** PRIVATE FUNCTIONS ********************************************************/ - - - private function fetchTicketsBasedOnrole(array $data): array - { - // $id = $data['thz_id'] ?? null; - $assign_to = $data['assign_to'] ?? null; - $mobile = $data['mobile'] ?? null; - - if (!empty($assign_to)) { - // Tickets assigned to a staff - return $this->thzMasterModel - ->select('thz_master.*, user_profiles.first_name as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.assign_to', $assign_to) - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - // if (!empty($id) && !empty($mobile)) { - if (!empty($mobile)) { - // Specific ticket by ID and mobile - return $this->thzMasterModel - ->select('thz_master.*, user_profiles.first_name as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - // ->where('thz_id', $id) - ->where('thz_master.mobile', $mobile) - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - // All tickets (e.g., for managers) - return $this->thzMasterModel - ->select('thz_master.*, user_profiles.first_name as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->orderBy('thz_master.created_at', 'desc') - ->findAll(); - } - - - - private function ticketSaveNotification($data, $insertOrUpdate, $id) - { - - $user_email = $data['email'] ?? null; - - $assignee_id = $data['assign_to'] ?? null; - - $assignee_email = $this->findAssigneeEmail($assignee_id); - - $client_id = $data['client_id'] ?? null; - - $emailToNotified = [ - 'user_email' => $user_email, - 'assignee_email' => $assignee_email - ]; - - $ticketId = $id; - - $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); - - return $result; - } - - private function ticketConversationSaveNotification($data) - { - - $thz_id = $data['thz_id']; // thz is alias of ticket - - $data['subject'] = $this->findSubject($data['thz_id']); - - $assignee_id = $this->findAssigneeId($data['thz_id']); - - $user_email = $this->findUserEmail($data['thz_id']); - - $assignee_email = $this->findAssigneeEmail($assignee_id) ?? ''; - - $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email; - $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email; - - $templateName = "ticket_conversation_save_notification"; - - $to_email = $receiver_mail; - - $ticketId = $thz_id; - - // $message = $data['notes'] ?? ''; - - $this->sendEmail($templateName, $data, $to_email, $ticketId); - - return true; - } - - - private function findAssigneeEmail($assignee_id) - { - - $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); - $assigneeEmail = $row ? $row->email : null; - return $assigneeEmail ? $assigneeEmail : ""; - } - - private function findAssigneeId($ticketId) - { - $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); - $assigneeId = $row ? $row->assign_to : null; - return $assigneeId ? $assigneeId : 0; - } - - private function findUserEmail($ticket_id) - { - $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); - $email = $row ? $row->email : null; - return $email ? $email : " "; - } - - private function findSubject($ticketId) - { - $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); - $subject = $row ? $row->subject : null; - return $subject ? $subject : " "; - } - - private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) - { - - $user_email = $emailToNotified['user_email'] ?? null; - $assignee_email = $emailToNotified['assignee_email'] ?? null; - - - if (!empty($assignee_email)) { - - switch ($insertOrUpdate) { - - case 'update': - - $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); - - break; - - case 'create': - - $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); - - break; - - default: - # code... - break; - } - } - - if (!empty($user_email)) { - - switch ($insertOrUpdate) { - - case 'update': - - $data['assigneeAndStatus'] = empty($assignee_email) - ? "Not Yet Assigned" - : "Assigned With {$assignee_email}"; - - $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); - - - break; - - case 'create': - - $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); - - $cc = getenv('G_ticketing_system_cc'); - - $this->myLogger->logme('error', "env for cc G_ticketing_system_cc " . $cc); - - $template = empty($assignee_email) - ? 'ticket_save_create_user_unassigned' - : 'ticket_save_create_user_assigned'; - - if (!empty($assignee_email)) { - $data['assignee_email'] = $assignee_email; - } - - $this->sendEmail($template, $data, $user_email, $ticketId); - - // send to account manager and if it is more than one email also no problem we send to all account managers - if (!empty($account_manager_email)) { - $this->myLogger->logme('error', "mail sent for account manager " . json_encode($account_manager_email)); - $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); - } else { - $this->myLogger->logme('error', "mail not sent for account manager "); - } - - break; - - default: - # code... - break; - } - } - - return true; - } - - private function updateTicket($data) - { - - $data['updated_by'] = get_session_userid(); - $ticket_id = $data['thz_id']; - $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update(); - - return $result; - } - - private function insertTicket($data) - { - $data['created_by'] = get_session_userid(); - $this->thzMasterModel->insert($data); - - return $this->thzMasterModel->insertID(); // returns the inserted row's ID - } - - - private function sendEmail($templateName, $data, $to_email, $ticketId, $cc = "", $bcc = "") - { - - $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; - - if (empty($mailTemplate)) { - $this->myLogger->logme('error', 'No Mail Template Found To send email in ticketing system'); - return; - } - - if (empty($cc)) { - $this->myLogger->logme('error', 'empty cc attached for template name : ' . json_encode($templateName)); - } else { - $this->myLogger->logme('error', "cc attached for template name : " . json_encode($templateName)); - } - - $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); - - $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%message%', $data['notes'] ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); - - $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); - - $from_mail = ""; - $to_mail = $to_email; - $cc_string = $cc; - $subject = $mailTemplate['subject']; - $message = $mailTemplate['mail_content']; - $attachments = ""; - $reply_to = ""; - $bcc_string = $bcc; - - $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); - - $this->myLogger->logme('error', 'Mail Response : ' . json_encode($res)); - } - - - public function getPolicyTerms($client_policy_id) - { - $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first(); - - $policy_terms = []; - if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) { - - $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? []; - - $ticketController = new TicketController(); - $policy_terms = $ticketController->convertTermsToDisplay($raw_terms); - } - - $data['policy_terms'] = $policy_terms; - return view('view_policy_terms', $data); - } - - - private function handleTicketHistory(array $old, array $data): string - { - if ($old['status'] != $data['status']) { - $history = [ - 'thz_id' => $data['thz_id'], - 'field_name' => 'status', - 'display_name' => 'Status', - 'old_value' => $old['status'], - 'new_value' => $data['status'], - 'is_active' => 1 - ]; - - if (!empty(get_session_userid())) { - $history['created_by'] = get_session_userid(); - } - - $hist_id = $this->thzHistoryModel->insert($history); - - return $old['status'] . " - " . $data['status'] . " - " . $hist_id; - } - - return $old['status'] . " - " . $data['status']; - } - - - - - -} +thzMasterModel = new ThzMasterModel(); + $this->thzMasterNotesModel = new ThzMasterNotesModel(); + $this->thzTypeModel = new thzTypeModel(); + $this->thzHistoryModel = new ThzHistoryModel(); + $this->thzControllerCleaner = new ThzControllerCleaner(); + $this->userModel = new UserModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->clientModel = new ClientModel(); + $this->cientRmModel = new ClientRMModel(); + $this->ticketMailTemplateModel = new TicketMailTemplateModel(); + $this->myLogger = \Config\Services::mylogger(); + } + + public function index() + { + // + } + + public function ticketSave() + { + try { + $data = $this->request->getPost(); + $references = ""; + if (!empty($data['thz_id'])) { + + $text = "update"; + // here insert history Status. + $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); + $result = $this->updateTicket($data); + + $references = ($old && isset($data['status'])) ? $this->handleTicketHistory($old, $data) : "No Details" ; + + $updateID = $data['thz_id']; + } else { + + $text = "create"; + $insertID = $this->insertTicket($data); + $result = true; + $references = ""; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; + + $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); + + $this->myLogger->logme('error', 'emailNotificationResult: ' . json_encode($emailNotificationResult)); + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket {$text}d successfully " : "Unable to {$text} ticket. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed..!!', + 'ref' => $references + ])->setStatusCode($result ? 200 : 400); + + + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketList() + { + + $data['tab_name'] = "Tickets"; + $data['page_name'] = "Tickets"; + try { + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + + $data = $this->request->getGet(); + + if ($returnType === 'web' && in_array(get_role_id(), [3, 4])) { + $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); + } + + + $tickets = $this->fetchTicketsBasedOnrole($data); + + + if ($returnType === 'api') { + if (empty($tickets)) { + $this->myLogger->logme('error', 'empty tickets in ticket list: ' . json_encode($tickets)); + return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + } + } else { + $data['ticket_data'] = $tickets; + $data['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['3', '4'])->findAll(); + // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu , 2-"manager l2 " - ivangalum assign pannalam + // 3,4 remain person varannum. + $data['client_list'] = $this->clientModel->getCreatedByUserName(); + $data['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_list', $data); + } + + + return $this->response->setJSON([ + 'status' => 'success', + 'data' => $tickets, + ])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketConversationSave() + { + + try { + $data = $this->request->getPost(); + + $data['notes_type'] = $data['notes_type'] ?? 'External'; + + $result = $this->thzMasterNotesModel->insert($data); + + if (empty($result)) { + $this->myLogger->logme('error', 'Ticket conversation insert failed..!!: ' . json_encode($result)); + throw new \RuntimeException('No tickets found', 404); + } + + $emailNotificationResult = ($data['notes_type'] === "External") + ? $this->ticketConversationSaveNotification($data) + : false; + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again.", + 'notification' => $emailNotificationResult ? 'Email Notification Success..!!' : 'Email Notification Failed Or No Need..!!' + ])->setStatusCode($result ? 200 : 400); + + + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketAutoFetchDetails() + { + try { + $data = $this->request->getPost(); + + $client_id = $data['client_id'] ?? null; + $mobile = $data['mobile'] ?? null; + + if ($client_id && $mobile) { + $details = $this->thzMasterModel->ticketAutoFetchDetails($client_id, $mobile); + + if (empty($details)) { + $this->myLogger->logme('error', 'empty AutoFetchDetails for client_id : ' . json_encode($client_id)); + throw new \RuntimeException('No Data found', 400); + } + + $policyIds = array_filter(array_column($details, 'policy_id')); + $clientPolicy = !empty($policyIds) + ? $this->clientPolicyModel->whereIn('id', $policyIds)->where('is_active', 1)->get()->getResultArray() + : []; + + $result['client_details'] = $details; + $result['policy_details'] = $clientPolicy ?? []; + } else { + throw new \RuntimeException('Client and Mobile Not found', 400); + } + + return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketConversationList() + { + $data = $this->request->getGet(); + + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + + $thz_id = $data['thz_id'] ?? null; + + $ticketType = $data['notes_type'] ?? 'External'; + + if ($thz_id) { + $result['master'] = $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.thz_id', $thz_id) + ->findAll(); + + if (!empty($result['master'])) { + $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType); + $result['notes'] = !empty($notes) ? $notes : []; + } else { + $this->myLogger->logme('error', 'No tickets found for ticket id ' . json_encode($thz_id)); + throw new \RuntimeException('No tickets found', 400); + } + } else { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); + throw new \RuntimeException('No tickets found', 404); + } + + if ($returnType === 'api') { + try { + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } else { + + $assign_to = $result['master'][0]['assign_to']; + $mobile = $result['master'][0]['mobile']; + + $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') + ? $result['master'][0]['policy_id'] + : ''; + + $result['related_tickets'] = $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->where('thz_master.mobile', $mobile) + ->where('thz_master.thz_id !=', $thz_id) + ->where('thz_master.status !=', 'Closed') + ->where('thz_master.status !=', 'Resolved') + ->findAll(); + + $result['assignee'] = $this->userModel->where('is_active', 1)->whereIn('role', ['2', '3', '4'])->findAll(); // enga 5-"head" and 1-"admin" assign pannvaga so dropdown la varakudhathu + // 2,3,4 remain person varannum. + $result['policy_terms'] = $toGetPolicyId ? $this->getPolicyTerms($toGetPolicyId) : ''; + + $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); + + return $this->loadLayout('thz_notes', $result); + } + } + + public function ticketType() + { + $method = $this->request->getMethod(); // get, post + try { + if ($method === 'get') { + $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); + if (empty($types)) { + $this->myLogger->logme('error', 'No ticket types found '); + return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); + } + + if ($method === 'post') { + + $data = $this->request->getPost(); + if (!empty($data['id'])) { + $text = "update"; + $result = $this->thzTypeModel->update($data['id'], $data); + $updateID = $data['id']; + } else { + $text = "create"; + $insertID = $this->thzTypeModel->insert($data); + $result = true; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); + + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "Ticket Type {$text}d successfully" : "Unable to {$text} ticket type. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + public function ticketHistoryList() + { + try { + $data = $this->request->getGet(); + $thz_id = $data['thz_id']; + // $details = $this->thzHistoryModal->whereIn('thz_id', $thz_id)->where('is_active', 1)->get()->getResultArray(); + $details = $this->thzHistoryModel->select('thz_history.*, user_profiles.first_name as created_name') + ->join('user_profiles', 'user_profiles.id = thz_history.created_by', 'left') + ->where('thz_history.thz_id', $thz_id)->where('thz_history.is_active', 1) + ->orderBy('thz_history.created_at', 'desc') + ->get()->getResultArray(); + + + + if (empty($details)) { + $this->myLogger->logme('error', 'No history details found for ticket id ' . json_encode($thz_id)); + throw new \RuntimeException('No History found', 404); + } + + + return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); + } catch (\Throwable $e) { + return handle_exception($e, $this->myLogger, $this->response); + } + } + + + /************************************************** PRIVATE FUNCTIONS ********************************************************/ + + + private function fetchTicketsBasedOnrole(array $data): array + { + // $id = $data['thz_id'] ?? null; + $assign_to = $data['assign_to'] ?? null; + $mobile = $data['mobile'] ?? null; + + if (!empty($assign_to)) { + // Tickets assigned to a staff + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->where('thz_master.assign_to', $assign_to) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // if (!empty($id) && !empty($mobile)) { + if (!empty($mobile)) { + // Specific ticket by ID and mobile + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + // ->where('thz_id', $id) + ->where('thz_master.mobile', $mobile) + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + // All tickets (e.g., for managers) + return $this->thzMasterModel + ->select('thz_master.*, user_profiles.first_name as assignee_name') + ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') + ->orderBy('thz_master.created_at', 'desc') + ->findAll(); + } + + + + private function ticketSaveNotification($data, $insertOrUpdate, $id) + { + + $user_email = $data['email'] ?? null; + + $assignee_id = $data['assign_to'] ?? null; + + $assignee_email = $this->findAssigneeEmail($assignee_id); + + $client_id = $data['client_id'] ?? null; + + $emailToNotified = [ + 'user_email' => $user_email, + 'assignee_email' => $assignee_email + ]; + + $ticketId = $id; + + $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); + + return $result; + } + + private function ticketConversationSaveNotification($data) + { + + $thz_id = $data['thz_id']; // thz is alias of ticket + + $data['subject'] = $this->findSubject($data['thz_id']); + + $assignee_id = $this->findAssigneeId($data['thz_id']); + + $user_email = $this->findUserEmail($data['thz_id']); + + $assignee_email = $this->findAssigneeEmail($assignee_id) ?? ''; + + $sender_mail = $data['notes_by'] == "User" ? $user_email : $assignee_email; + $receiver_mail = $data['notes_by'] == "User" ? $assignee_email : $user_email; + + $templateName = "ticket_conversation_save_notification"; + + $to_email = $receiver_mail; + + $ticketId = $thz_id; + + // $message = $data['notes'] ?? ''; + + $this->sendEmail($templateName, $data, $to_email, $ticketId); + + return true; + } + + + private function findAssigneeEmail($assignee_id) + { + + $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); + $assigneeEmail = $row ? $row->email : null; + return $assigneeEmail ? $assigneeEmail : ""; + } + + private function findAssigneeId($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $assigneeId = $row ? $row->assign_to : null; + return $assigneeId ? $assigneeId : 0; + } + + private function findUserEmail($ticket_id) + { + $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); + $email = $row ? $row->email : null; + return $email ? $email : " "; + } + + private function findSubject($ticketId) + { + $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); + $subject = $row ? $row->subject : null; + return $subject ? $subject : " "; + } + + private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) + { + + $user_email = $emailToNotified['user_email'] ?? null; + $assignee_email = $emailToNotified['assignee_email'] ?? null; + + + if (!empty($assignee_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); + + break; + + case 'create': + + $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); + + break; + + default: + # code... + break; + } + } + + if (!empty($user_email)) { + + switch ($insertOrUpdate) { + + case 'update': + + $data['assigneeAndStatus'] = empty($assignee_email) + ? "Not Yet Assigned" + : "Assigned With {$assignee_email}"; + + $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); + + + break; + + case 'create': + + $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); + + $cc = getenv('G_ticketing_system_cc'); + + $this->myLogger->logme('error', "env for cc G_ticketing_system_cc " . $cc); + + $template = empty($assignee_email) + ? 'ticket_save_create_user_unassigned' + : 'ticket_save_create_user_assigned'; + + if (!empty($assignee_email)) { + $data['assignee_email'] = $assignee_email; + } + + $this->sendEmail($template, $data, $user_email, $ticketId); + + // send to account manager and if it is more than one email also no problem we send to all account managers + if (!empty($account_manager_email)) { + $this->myLogger->logme('error', "mail sent for account manager " . json_encode($account_manager_email)); + $this->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); + } else { + $this->myLogger->logme('error', "mail not sent for account manager "); + } + + break; + + default: + # code... + break; + } + } + + return true; + } + + private function updateTicket($data) + { + + $data['updated_by'] = get_session_userid(); + $ticket_id = $data['thz_id']; + $result = $this->thzMasterModel->where('thz_id', $ticket_id)->set($data)->update(); + + return $result; + } + + private function insertTicket($data) + { + $data['created_by'] = get_session_userid(); + $this->thzMasterModel->insert($data); + + return $this->thzMasterModel->insertID(); // returns the inserted row's ID + } + + + private function sendEmail($templateName, $data, $to_email, $ticketId, $cc = "", $bcc = "") + { + + $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; + + if (empty($mailTemplate)) { + $this->myLogger->logme('error', 'No Mail Template Found To send email in ticketing system'); + return; + } + + if (empty($cc)) { + $this->myLogger->logme('error', 'empty cc attached for template name : ' . json_encode($templateName)); + } else { + $this->myLogger->logme('error', "cc attached for template name : " . json_encode($templateName)); + } + + $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); + + $mailTemplate['mail_content'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%ticketId%', $ticketId ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%message%', $data['notes'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); + + $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); + + $from_mail = ""; + $to_mail = $to_email; + $cc_string = $cc; + $subject = $mailTemplate['subject']; + $message = $mailTemplate['mail_content']; + $attachments = ""; + $reply_to = ""; + $bcc_string = $bcc; + + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $to_mail, 'cc' => $cc_string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); + + $this->myLogger->logme('error', 'Mail Response : ' . json_encode($res)); + } + + + public function getPolicyTerms($client_policy_id) + { + $policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $client_policy_id)->first(); + + $policy_terms = []; + if (isset($policy_data['policy_terms']) && !empty($policy_data['policy_terms'])) { + + $raw_terms = json_decode($policy_data['policy_terms'] ?? [], true) ?? []; + + $ticketController = new TicketController(); + $policy_terms = $ticketController->convertTermsToDisplay($raw_terms); + } + + $data['policy_terms'] = $policy_terms; + return view('view_policy_terms', $data); + } + + + private function handleTicketHistory(array $old, array $data): string + { + if ($old['status'] != $data['status']) { + $history = [ + 'thz_id' => $data['thz_id'], + 'field_name' => 'status', + 'display_name' => 'Status', + 'old_value' => $old['status'], + 'new_value' => $data['status'], + 'is_active' => 1 + ]; + + if (!empty(get_session_userid())) { + $history['created_by'] = get_session_userid(); + } + + $hist_id = $this->thzHistoryModel->insert($history); + + return $old['status'] . " - " . $data['status'] . " - " . $hist_id; + } + + return $old['status'] . " - " . $data['status']; + } + + + + + +} diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 5d930c71..eb7e894b 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -362,6 +362,7 @@ class TicketController extends BaseController $data['modeOFIntimate'] = $this->modeOFIntimate; $data['priorityType'] = $this->priorityType; $data['claimType'] = $this->claimType; + $data['tab_name'] = "Claims"; if ($this->request->is('get')) { $data['page_name'] = "Claims"; $data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll(); @@ -1123,6 +1124,9 @@ class TicketController extends BaseController // dd($data['ticket_data']); $data['ticket_type'] = $this->ticketType; $data['trigger_type'] = $this->triggerType; + + $data['page_name'] = "Claims"; + return $this->loadLayout('ticket_mail_template', $data); } @@ -1744,6 +1748,8 @@ class TicketController extends BaseController 'tat_band_wise' => 'TAT Wise Status Report' ]; // + $data['tab_name'] = "Claim Reports"; + $data['page_name'] = "Claims"; $this->loadLayout('ticket_reports', $data); } else { $received_data = $this->request->getPost(); @@ -2187,6 +2193,8 @@ class TicketController extends BaseController $data['viewer'] = !empty($empView) ? $empView : 0; + + // dd($data); return view('ticket_feedback_form', $data); }else{ @@ -2217,7 +2225,7 @@ class TicketController extends BaseController public function feedbackList(){ $data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll(); - + $data['page_name'] = "Claims"; // dd($data); $this->loadLayout("ticket_feedback_list",$data); } @@ -2610,7 +2618,8 @@ class TicketController extends BaseController public function claimDumpUpload() { - $data['page_name'] = "Claim Dupm Upload"; + $data['tab_name'] = "Claim Dupm Upload"; + $data['page_name'] = "Claims"; if($this->request->is('get')){ diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 255b6507..b4d391dc 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -55,7 +55,8 @@ class UserController extends AdminController public function list() { - $data['page_name'] = 'User'; + $data['tab_name'] = 'Users'; + $data['page_name'] = 'Users'; $this->myLogger->logme('error','User list function called'); $data['UserList'] = $this->userModel->getUserList(); // echo '
';
@@ -588,6 +589,7 @@ class UserController extends AdminController
                 $data = $this->request->getPost();
                 if (!empty($data['id'])) {
                     $text   = "update";            
+                    $data['updated_by'] =  get_session_userid();
                     $result = $this->partnerStaffModel->update($data['id'], $data);
                     $updateID = $data['id'];
                 } else {
@@ -595,6 +597,11 @@ class UserController extends AdminController
                     $data['role_id'] = 1;
                     $data['created_by'] =  get_session_userid();
                     $insertID  = $this->partnerStaffModel->insert($data);
+                    if($insertID){
+                        $details['manager_id'] = $insertID;
+                        $details['updated_by'] =  get_session_userid();
+                        $this->partnerStaffModel->update($insertID, $details);
+                    }
                     $result = true;
                 }
 
@@ -620,17 +627,24 @@ class UserController extends AdminController
                     if (!$staff) {
                         return $this->response->setJSON(['status'  => 'error','message' => 'Staff not found'])->setStatusCode(404);
                     }
+                    $role = $staff['role_id'];
+                    $text = $role == 1 ? "Manager" : "Staff";
 
                     if ($staff['is_active'] == 1) {
+                      if($role == 1){  // manager 
+                        $result = $this->partnerStaffModel->updateByKey($id);
+                        $message = $result;
+                      }else{ // staff
                         $result = $this->partnerStaffModel->update($id, ['is_active' => 0]);
-                        $message = "Staff deleted successfully";
+                        $message = $text." deleted successfully";
+                      }
                     } else {
-                        return $this->response->setJSON(['status'  => 'error','message' => 'Staff already deleted'])->setStatusCode(400);
+                        return $this->response->setJSON(['status'  => 'error','message' => $text.' already deleted'])->setStatusCode(400);
                     }
 
                     return $this->response->setJSON([
                         'status'  => $result ? 'success' : 'error',
-                        'message' => $result ? $message : "Unable to delete staff. Please try again.",
+                        'message' => $result ? $message : "Unable to delete ".$text.". Please try again.",
                         'id'      => $id
                     ])->setStatusCode($result ? 200 : 400);
             }
diff --git a/app/Helpers/ChatbotHelper.php b/app/Helpers/ChatbotHelper.php
index db0e2e3e..72632251 100644
--- a/app/Helpers/ChatbotHelper.php
+++ b/app/Helpers/ChatbotHelper.php
@@ -32,7 +32,7 @@ class ChatbotHelper
         $client_branch_id =  $chat_session_info['client_branch_id'];
         $relationship ='Self';
         $EmployeeModel = new EmployeeModel();
-        return $EmployeeModel->getEmpFamilybyEmpCode(emp_code: $emp_code,client_id: $client_id,emp_status: ['active'],policy_status:['active'],client_branch_id:[ $client_branch_id ],relationship:[$relationship]);//,relationship:[$relationship];
+        return $EmployeeModel->getEmpFamilybyEmpCode(emp_code: $emp_code,client_id: $client_id,emp_status: ['active'],policy_status:['active'],client_branch_id:[ $client_branch_id ],relationship:[$relationship],policy_type_id:[2,3,4,5]);//,relationship:[$relationship];
     }
 
     public static function getHospitalLink($emp_policy_id){
diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php
index 9c72c973..c7ba2982 100755
--- a/app/Helpers/excel_import_export_helper.php
+++ b/app/Helpers/excel_import_export_helper.php
@@ -666,12 +666,12 @@ if(!function_exists('generate_insurer_based_excel')){
             foreach ($excel_header_array as $header) {
 
                 $fieldName = $header['db_column_name'];
-                $defaultValue = isset($header['default_value']) ? $header['default_value'] : null;
+                $defaultValue = isset($header['default_value']) ? $header['default_value'] : "";
 
                 if ($fieldName === 'index') {
                     $value = $serialNumber;
                 } else {
-                    if(empty($fieldName) && !empty($defaultValue)){
+                    if(empty($fieldName) && $defaultValue != ""){
                         $value = $defaultValue;
                     }else{
                         $value = $row->$fieldName ?? '';
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index 932e53c8..e608b013 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -1993,7 +1993,6 @@ if (!function_exists('group_slab_rates_basedon_name')) {
     }
 }
 
-
 //this key generating mandantory for display employee info in enrolment app w/o error
 if (!function_exists('generate_family_floater_key')) {
     function generate_family_floater_key($relationship)
@@ -2002,7 +2001,7 @@ if (!function_exists('generate_family_floater_key')) {
             $relation = 'parent';
         } else if (strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter') {
             $relation = 'child';
-        } else if ((strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law') || (strtolower(trim($relationship)) === 'father-in-Law' || strtolower(trim($relationship)) === 'mother-in-Law')) {
+        } else if ((strtolower(trim($relationship)) === 'father in law' || strtolower(trim($relationship)) === 'mother in law') || (strtolower(trim($relationship)) === 'father-in-law' || strtolower(trim($relationship)) === 'mother-in-law')) {
             $relation = 'parent_in_law';
         } else if (strtolower(trim($relationship)) === 'spouse') {
             $relation = 'spouse';
@@ -2041,3 +2040,331 @@ if (!function_exists('formatIndianCurrency')) {
         return $formatted . $decimal;
     }
 }
+
+// ------------- FUNCTION FOR LEAD MEMBER DATA LIST VALIDATIONS --------------------------------------
+
+if (!function_exists('check_columns_name_exist')) {
+    function check_columns_name_exist($definedColumns, $excelColumns)
+    {
+        $mismatchedColumns = [];
+
+        foreach ($definedColumns as $colKey => $definedCol) {
+            $definedColName = strtolower(trim($definedCol['col_name']));
+
+            // Normalize excel columns to lowercase for comparison
+            $excelColsLower = array_map('strtolower', array_map('trim', $excelColumns));
+
+            if (!in_array($definedColName, $excelColsLower)) {
+                $mismatchedColumns[] = "Missing column: " . $definedCol['col_name'] . " in Excel file.
"; + } + } + + return $mismatchedColumns; + } +} + +if (!function_exists('update_excel_column_indexes')) { + function update_excel_column_indexes($definedColumns, $excelColumns) + { + // $excelColumns is the first row of the Excel file (header row) + // Example: ['Emp Code', 'Name', 'Gender', 'DOB', 'SI'] + + foreach ($definedColumns as $key => &$definedCol) { + $definedColName = strtolower(trim($definedCol['col_name'])); + $excelColsLower = array_map('strtolower', array_map('trim', $excelColumns)); + + // Find column index in Excel + $colIndex = array_search($definedColName, $excelColsLower); + + if ($colIndex !== false) { + $definedCol['col_idx'] = $colIndex; + $definedCol['col_cell_name'] = chr(65 + $colIndex); // A=65, B=66... + } else { + // If column missing in Excel + $definedCol['col_idx'] = null; + $definedCol['col_cell_name'] = null; + } + } + + return $definedColumns; + } +} + +if (!function_exists('check_duplicate_rows_and_contacts')) { + function check_duplicate_rows_and_contacts($excel_data, $columns_to_check, $err_data) + { + $exl_col = $columns_to_check; + $keys = array_keys($columns_to_check); + unset($columns_to_check['sno'], $columns_to_check['si'], $columns_to_check['email'], $columns_to_check['mobile'], $columns_to_check['age']); + + $seenRows = []; + $emailSeen = []; + $mobileSeen = []; + $duplicateRows = []; + + foreach ($excel_data as $rowIndex => $row) { + + // Build unique key from selected columns + $values = []; + foreach ($columns_to_check as $colIdx) { + $values[] = isset($row[$colIdx['col_idx']]) ? trim($row[$colIdx['col_idx']]) : ''; + } + $rowKey = json_encode($values); + + // =============== STEP 1: Main duplicate check =============== + if (!isset($seenRows[$rowKey])) { + $seenRows[$rowKey] = [$rowIndex]; + } else { + // First duplicate occurrence — mark all related rows + $seenRows[$rowKey][] = $rowIndex; + $indexes = $seenRows[$rowKey]; + + $rows_str = implode(', ', array_map(fn($i) => $i + 1, $indexes)); + $error_message = "Duplicate found in selected columns: Rows {$rows_str} are identical"; + + foreach ($indexes as $i) { + // Avoid re-adding duplicate errors + if (!in_array($i, $duplicateRows)) { + array_push($err_data['error_summary'], 1); + $err_data['error_data'][$i][$keys[0]]['col_name'] = 'Sl no'; + $err_data['error_data'][$i][$keys[0]]['col_idx'] = 0; + $err_data['error_data'][$i][$keys[0]]['error'][] = $error_message; + $duplicateRows[] = $i; + } + } + + // Skip email/mobile check for this duplicate row + continue; + } + + // =============== STEP 2: Email & Mobile check (only if not duplicate) =============== + $email = isset($row[$exl_col['email']['col_idx']]) ? trim($row[$exl_col['email']['col_idx']]) : ''; + $mobile = isset($row[$exl_col['mobile']['col_idx']]) ? trim($row[$exl_col['mobile']['col_idx']]) : ''; + + // Check email duplicates + if ($email !== '') { + if (isset($emailSeen[$email])) { + $firstIndex = $emailSeen[$email] + 1; + $currentRow = $rowIndex + 1; + $error_message = "Duplicate email found: Row {$currentRow} and Row {$firstIndex} have the same email '$email'"; + array_push($err_data['error_summary'], 1); + $err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['col_name'] = $exl_col['email']['col_name']; + $err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['col_idx'] = $exl_col['email']['col_idx']; + $err_data['error_data'][$rowIndex][$keys[$exl_col['email']['col_idx']]]['error'][] = $error_message; + } else { + $emailSeen[$email] = $rowIndex; + } + } + + // Check mobile duplicates + if ($mobile !== '') { + if (isset($mobileSeen[$mobile])) { + $firstIndex = $mobileSeen[$mobile] + 1; + $currentRow = $rowIndex + 1; + $error_message = "Duplicate mobile number found: Row {$currentRow} and Row {$firstIndex} have the same mobile '$mobile'"; + array_push($err_data['error_summary'], 1); + $err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['col_name'] = $exl_col['mobile']['col_name']; + $err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['col_idx'] = $exl_col['mobile']['col_idx']; + $err_data['error_data'][$rowIndex][$keys[$exl_col['mobile']['col_idx']]]['error'][] = $error_message; + } else { + $mobileSeen[$mobile] = $rowIndex; + } + } + } + + return $err_data; + } +} + +if (!function_exists('check_relationship_for_member_data')) { + function check_relationship_for_member_data($row, $relationship, $columns_to_check) + { + $relation_col_idx = $columns_to_check['relationship']['col_idx'] ?? null; + $gender_col_idx = $columns_to_check['gender']['col_idx'] ?? null; + + if ($relation_col_idx !== null && $gender_col_idx !== null && !empty($row[$relation_col_idx]) && !empty($row[$gender_col_idx])) { //$row[5] = relationship $row[4] = Gender + + $slug = \Config\Services::slug(); + $col = $slug->slugify($row[$relation_col_idx]); + + if ($col != 'self' && $col != 'spouse') { + if (!isset($relationship[$col])) { + return array('status' => false, 'error' => 'Rule Conflict: Unknown Relationship'); + } + + if (isset($relationship[$col]) && $relationship[$col]['gender'] != $row[$gender_col_idx]) { + $error = "Gender relationship conflict: Expected " . $relationship[$col]['gender'] . ", received $row[$gender_col_idx]"; + return array('status' => false, 'error' => $error); + } + } + + return array('status' => true); + } else { + return array('status' => false, 'error' => 'Rule Conflict: Both Relationship and Gender required for check relationship conflict'); + } + } +} + +if (!function_exists('member_data_group_by_family')) { + function member_data_group_by_family($member_data, $columns_to_check) + { + $result = []; + // Kint::dump($member_data); + foreach ($member_data as $rowIndex => $row) { + if (!check_row_is_empty_or_null($row)) { + + $row['row_index'] = $rowIndex; + + $relation_idx = $columns_to_check['relationship']['col_idx']; + $emp_code_idx = $columns_to_check['emp_code']['col_idx']; + + if (isset($row[$relation_idx]) && strtolower($row[$relation_idx]) == 'self' && isset($result[$row[$emp_code_idx]])) { + array_unshift($result[$row[$emp_code_idx]], $row); + } else { + $result[$row[$emp_code_idx]][] = $row; + } + } + } + return $result; + } +} + +if (!function_exists('validateFamily')) { + function validateFamily($familyData, $columns_to_check, $errors) { + + $keys = array_keys($columns_to_check); + foreach ($familyData as $familyId => $members) { + + $selfMember = null; + $spouseMember = null; + $selfCount = 0; + $row_index = null; + + // Find Self and Spouse members + foreach ($members as $member) { + $relation = trim($member[3]); // Relationship field + + if (strtolower($relation) == 'self') { + $selfCount++; + $selfMember = $member; + } + + if (strtolower($relation) == 'spouse') { + $spouseMember = $member; + } + + if($row_index == null){ + if(strtolower($relation) == 'self'){ + $row_index = $member['row_index']; + }else if(strtolower($relation) == 'spouse'){ + $row_index = $member['row_index']; + }else{ + $row_index = $member['row_index']; + } + } + + } + + // Validation 1: Check if Self exists + if ($selfCount === 0) { + + $message = "Emp ID - {$familyId}: Missing 'Self' member"; + array_push($errors['error_summary'], 4); + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message; + + continue; + } + + // Validation 2: Check if there's exactly one Self + if ($selfCount > 1) { + $message = "Emp ID - {$familyId}: Multiple 'Self' members found. Only one 'Self' is allowed per family"; + array_push($errors['error_summary'], 5); + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message; + + continue; + } + + // Validation 3: Validate spouse gender if spouse exists + if ($spouseMember !== null) { + + $selfGender = strtoupper(trim($selfMember[4])); // Gender field + $spouseGender = strtoupper(trim($spouseMember[4])); + $selfName = $selfMember[2]; // Name field + $spouseName = $spouseMember[2]; + + // Check gender compatibility + $message = ''; + if ($selfGender === 'M' && $spouseGender !== 'F') { + $message = "Emp ID - {$familyId}: Self ('{$selfName}') is Male (M); spouse must be Female (F). Found spouse ('{$spouseName}') with gender '({$spouseGender})'."; + } elseif ($selfGender === 'F' && $spouseGender !== 'M') { + $message = "Emp ID - {$familyId}: Self ('{$selfName}') is Female (F); spouse must be Male (M). Found spouse ('{$spouseName}') with gender '({$spouseGender})'."; + } elseif (!in_array($selfGender, ['M', 'F'])) { + $message = "Emp ID - {$familyId}: Invalid gender for Self member ('{$selfName}'). Expected 'M' or 'F', found '({$selfGender})'."; + } + + if(isset($message) && !empty($message)){ + array_push($errors['error_summary'], 6); + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_name'] = $columns_to_check['emp_code']['col_name']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['col_idx'] = $columns_to_check['emp_code']['col_idx']; + $errors['error_data'][$row_index][$keys[$columns_to_check['emp_code']['col_idx']]]['error'][] = $message; + } + } + } + + return $errors; + } +} + +if (!function_exists('check_age_validation')) { + function check_age_validation($row, $family_composition) + { + if ($row[5] != null) { + + $dateString = convert_string_to_date($row[5]); + if ($dateString === false) { + return array('status' => false, 'error' => 'Not a valid Date'); + } + + $relationships = $family_composition['age_ratio']; + + $dob = $dateString; + $currentDateTime = new DateTime(); + + $passedDateTime = new DateTime($dob); + $interval = $currentDateTime->diff($passedDateTime); + + $slug = \Config\Services::slug(); + $relationship = $slug->slugify($row[3]); + if($relationship == 'son' || $relationship == 'daughter'){ + $relationship = 'child'; + } + if($relationship == 'father' || $relationship == 'mother' || $relationship == 'mother-in-law'|| $relationship == 'father-in-law' ){ + $relationship = 'elders'; + } + + $age_min = isset($relationships[$relationship]['min']) ? $relationships[$relationship]['min'] : NULL; + $age_max = isset($relationships[$relationship]['max']) ? $relationships[$relationship]['max'] : NULL; + + // Kint::dump($dob,$currentDateTime,$passedDateTime, $interval->y, $age_min, $age_max, $relationship, $relationships); + + if ($age_min !== null && $age_min > $interval->y) { + return array('status' => false, 'error' => "Age conflict : minimum $age_min yrs allowed, received $interval->y"); + } + if ($age_max !== null && $age_max < $interval->y) { + return array('status' => false, 'error' => "Age conflict : maximum $age_max yrs allowed, received $interval->y"); + } + return array('status' => true); + + } else { + return array('status' => false, 'error' => 'Rule Conflict: Both DOB and Relationship required for age check'); + } + } +} + +// ------------- END OF LEAD MEMBER DATA LIST VALIDATIONS -------------------------------------- + + diff --git a/app/Helpers/sms_helper.php b/app/Helpers/sms_helper.php new file mode 100644 index 00000000..0045a61c --- /dev/null +++ b/app/Helpers/sms_helper.php @@ -0,0 +1,44 @@ + $apiKey, + 'MobileNo' => $mobile, + 'SenderID' => $senderId, + 'Message' => $message, + 'ServiceName' => $serviceName, + 'DLTTemplateID' => $templateId, + ]); + + // Send request + $response = @file_get_contents($url); + + log_message('info' , 'SMS - Response '.$response); + + // If response failed + if ($response === FALSE) { + return ['status' => 'failed', 'message' => 'Failed to send SMS.']; + } + + + return ['status' => 'success', 'message' => 'OTP sent successfully', 'api_response' => $response]; + } +} diff --git a/app/Models/ClientBranchModel.php b/app/Models/ClientBranchModel.php index 100f503d..a813221a 100755 --- a/app/Models/ClientBranchModel.php +++ b/app/Models/ClientBranchModel.php @@ -25,6 +25,7 @@ class ClientBranchModel extends Model "gst", "sez", "units", + "pre_branch_id" ]; public function getBranchAndContactByBranchId($branch_id){ diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index e1407c2c..b84bfae1 100755 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -108,7 +108,7 @@ class ClientModel extends Model } - public function getCreatedByUserName(){ + public function getCreatedByUserName($client_type = null){ $role_id = get_role_id(); $user_id = get_session_userid(); @@ -118,6 +118,10 @@ class ClientModel extends Model ->join('client_rm', 'client_rm.client_id = clients.id','left') ->where('clients.is_active', 1); + if (!empty($client_type)) { + $query->where('clients.client_type', $client_type); + } + if (in_array($role_id, [2, 3])) { // If the user is a Account Manager or Manager, filter by user_id @@ -222,5 +226,18 @@ class ClientModel extends Model return $result; } + public function isDuplicateByClientBranch($value, $field, $clientId, $branchId) + { + $builder = $this->db->table('level_contacts lc') + ->select('lc.id') + ->join('client_branch cb', 'lc.ref_id = cb.id', 'left') + ->where('lc.'.$field, $value) + ->where('lc.contact_type', 'client') + ->where('cb.client_id', $clientId) + ->where('lc.ref_id', $branchId) + ->get(); + + return $builder->getNumRows() > 0 ? true : false; + } } diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index 1bc55f06..1416c082 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -106,9 +106,9 @@ class EmployeeModel extends Model } - public function getEmpFamilybyEmpCode(string $client_policy_id = null,string $emp_code = null,string $client_id = null,array $emp_status = [],array $policy_status = [],array $relationship = [],array $client_branch_id = []) + public function getEmpFamilybyEmpCode(string $client_policy_id = null,string $emp_code = null,string $client_id = null,array $emp_status = [],array $policy_status = [],array $relationship = [],array $client_branch_id = [],array $policy_type_id = []) { - $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employees.file_id','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.is_addon', 'employee_polices.payable_employee','employee_polices.rand_string','employee_polices.claim_status']) + $result = $this->select(['employees.id as emp_id', 'employees.client_id','employees.client_branch_id', 'employees.relationship', 'employees.relationship_code', 'employees.change_event', 'employees.emp_code', 'employees.name', 'employees.email_personal', 'employees.email_corporate', 'employees.mobile', 'employees.gender', 'employees.dob', 'employees.doj', 'employees.basic_pay', 'employees.band', 'employees.designation', 'employees.emp_status','employees.unit','employees.file_id','employee_polices.id as emp_policy_id', 'employee_polices.employee_id', 'employee_polices.client_policy_id', 'employee_polices.tpa_id', 'employee_polices.uhid', 'employee_polices.batch_code', 'employee_polices.status', 'employee_polices.pre_existing_alignments', 'employee_polices.basic_cover_si', 'employee_polices.date_coverage', 'employee_polices.policy_end_date', 'employee_polices.days', 'employee_polices.premium', 'employee_polices.rata_premimum', 'employee_polices.gst', 'employee_polices.date_of_exit', 'employee_polices.reason_for_exit','policy_type.long_name as policy_name','client_policy.policy_type_id','client_policy.is_addon', 'employee_polices.payable_employee','employee_polices.rand_string','employee_polices.claim_status']) ->join('employee_polices', 'employee_polices.employee_id = employees.id') ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id','left') @@ -135,6 +135,9 @@ class EmployeeModel extends Model }) ->when(count($policy_status), function($query) use ($policy_status){ return $query->whereIn('employee_polices.status', $policy_status); + }) + ->when(count($policy_type_id), function($query) use ($policy_type_id){ + return $query->whereIn('client_policy.policy_type_id', $policy_type_id); }) ->when($client_id, function($query) use ($client_id){ return $query->where('employees.client_id',$client_id); diff --git a/app/Models/HRAccessControlModel.php b/app/Models/HRAccessControlModel.php index a9a4e2c7..a754536d 100644 --- a/app/Models/HRAccessControlModel.php +++ b/app/Models/HRAccessControlModel.php @@ -13,6 +13,9 @@ class HRAccessControlModel extends Model 'pre_hr_id', 'post_hr_id', 'post_client_id', + 'pre_client_id', + 'pre_branch_id', + 'post_branch_id', 'allowed_modules', 'allowed_pre_policies', 'allowed_active_policies', diff --git a/app/Models/LeadFilesModel.php b/app/Models/LeadFilesModel.php index 37db8e16..f3532d1f 100644 --- a/app/Models/LeadFilesModel.php +++ b/app/Models/LeadFilesModel.php @@ -17,7 +17,10 @@ class LeadFilesModel extends Model 'updated_by', 'created_at', 'updated_at', - 'is_active' + 'is_active', + 'error_data', + 'status', + 'type', ]; // Callbacks diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 67a354b1..7cc56602 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -105,6 +105,7 @@ class LeadsModel extends Model 'next_reminder_date', 'is_insurer_auto_mail', 'quote_received_insurer', + 'acm_id', ]; @@ -146,6 +147,7 @@ class LeadsModel extends Model $data = $this->select(' leads.*, + lead_files.status as demography_file_status, kyc_entity_type.name as entity_type, policy_type.policy_type, user_profiles.first_name as salse_person_name, @@ -168,6 +170,7 @@ class LeadsModel extends Model ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('lead_files', 'leads.id = lead_files.lead_id AND lead_files.type = 2 AND lead_files.is_active = 1', 'left') ->where('leads.is_active', 1); if (!empty($where)) { diff --git a/app/Models/PartnerStaffModel.php b/app/Models/PartnerStaffModel.php index 474f14d1..340a0ec5 100755 --- a/app/Models/PartnerStaffModel.php +++ b/app/Models/PartnerStaffModel.php @@ -47,4 +47,55 @@ class PartnerStaffModel extends Model // ]; // protected $skipValidation = false; +public function updateByKey($key) +{ + $db = \Config\Database::connect(); + $message = ""; + + // Start transaction + $db->transStart(); + + try { + // 1. Update manager + $db->table('partner_staff') + ->where('id', $key) + ->set('is_active', 0) + ->update(); + $managerRows = $db->affectedRows(); + $message = "{$managerRows} manager(s), "; + + // 2. Update agents under manager + $db->table('partner_agent') + ->where('manager_id', $key) + ->set('is_active', 0) + ->update(); + $agentRows = $db->affectedRows(); + $message .= "{$agentRows} agent(s), "; + + // 3. Update staff under manager + $db->table('partner_staff') + ->where('manager_id', $key) + ->set('is_active', 0) + ->update(); + $staffRows = $db->affectedRows(); + $message .= "{$staffRows} staff(s)"; + + // Complete transaction + $db->transComplete(); + + // Check transaction status + if ($db->transStatus() === false) { + return "Transaction failed. No updates were applied."; + } + + return $message . " are deleted successfully"; + + } catch (\Exception $e) { + // Rollback in case of exception + $db->transRollback(); + return "Error: " . $e->getMessage(); + } +} + + } diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php index 6acad55b..ba72d495 100755 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -182,21 +182,20 @@ -

Dashboard

-
+
-