diff --git a/.gitignore b/.gitignore index e0e9251f..1ab80e5d 100755 --- a/.gitignore +++ b/.gitignore @@ -22,8 +22,8 @@ writable/debugbar/* writable/**/*.db writable/**/*.sqlite -writable/e_card_template/* -!writable/e_card_template/.gitkeep +# writable/e_card_template/* +# !writable/e_card_template/.gitkeep writable/tmp/* !writable/tmp/.gitkeep diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 2b253b31..c217dd5b 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -59,6 +59,7 @@ $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyS $routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1'); $routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1'); $routes->get('claim-form-download/(:any)', 'TicketController::downloadClaimForm/$1'); +$routes->get('downloadClaimFile/(:any)', 'TicketController::downloadClaimFile/$1'); $routes->match (['get','post'],"claims-feedback-form/(:any)/(:any)", "TicketController::viewClaimFeedbackForm/$1/$2"); $routes->match (['get','post'],"claims-feedback-form/(:any)", "TicketController::viewClaimFeedbackForm/$1"); @@ -73,6 +74,9 @@ $routes->group("/user", ["filter" => "authMVC"], function ($routes) { $routes->get("deactive/(:hash)", "UserController::deactive/$1"); $routes->get("rolesandteams", "UserController::getRolesAndTeams"); $routes->get("getUserActivityHistory", "UserController::getUserActivityHistory"); + $routes->match(['get','post','put'], 'partner', 'UserController::partner'); + $routes->match(['get','post','put'], 'partnerIncentive', 'UserController::partnerIncentive'); + $routes->get("download-incentive-file/(:any)", "UserController::downloadIncentivesFile/$1"); }); $routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) { @@ -181,6 +185,8 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->post("test-rack-rate", "EmployeeController::testRackRate"); $routes->get('test_members_list', 'EmployeeController::test_members_list'); $routes->post('get_emp_history','EmployeeController::getEmpHistory'); + $routes->get("retail-endorsement-list", "EmployeeController::retailendorsementlist"); + $routes->post("retail-endorsement-save", "EmployeeController::retailendorsementsave"); }); @@ -364,7 +370,8 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get('transformMailContent', 'LeadsController::transformMailContent'); $routes->get('getCDAmount', 'ClientController::getCDAmount'); $routes->get('getTheEmpDataForClaim/(:any)', 'ClientController::getTheEmpDataForClaim/$1'); - $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1'); + // $routes->get('getTheEmpDataForClaimSearchByMobile/(:any)', 'ClientController::getTheEmpDataForClaimSearchByMobile/$1'); + $routes->get('getTheEmpDataForClaimSearchByMobile', 'ClientController::getTheEmpDataForClaimSearchByMobile'); $routes->get('getLeadNonEB/(:any)', 'LeadsController::getLeadNonEB/$1'); $routes->get('getPolicyTypeFields', 'LeadsController::getPolicyTypeFields'); $routes->get('removeMultiFile', 'LeadsController::removeMultiFile'); @@ -498,11 +505,9 @@ $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); //api $routes->group("/api", ["filter" => "authJWT"], function ($routes) { + $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type"); $routes->post("logined", "RestAuthenticationController::logined"); $routes->post("getId", "RestAuthenticationController::getUserIdFromToken"); - $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); - $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type"); - $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); }); $routes->post("employeeRest/saveMpin", "RestAuthenticationController::saveMpin"); @@ -575,6 +580,12 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("hrFileUpload", "EmployeeRestController::hrFileUpload"); $routes->post("updateHrFileUploadData", "EmployeeRestController::updateHrFileUploadData"); + //claims + $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); + $routes->get('get_ticket_type',"EmployeeRestController::get_ticket_type"); + $routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); + + }); $routes->get("hrFileDownload", "EmployeeRestController::hrFileDownload"); $routes->post("hrFileList", "EmployeeRestController::hrFileList"); @@ -624,6 +635,8 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { $routes->post('upload_url',"TicketController::upload_url"); $routes->post('getUrlDataByTicketId',"TicketController::getUrlDataByTicketId"); $routes->get('remove_url',"TicketController::remove_url"); + $routes->get('fetchVehiclePolicy/(:any)','TicketController::fetchVehiclePolicy/$1'); + }); $routes->group("clientApi",["filter" => "AuthClientApi"], function ($routes){ @@ -674,4 +687,9 @@ $routes->get("ticketHistoryList", "ThzController::ticketHistoryList"); $routes->group('test', function($routes) { $routes->post('api/saveForm', 'TestingController::saveForm'); $routes->get('insurerRFQRemainder', 'LeadsController::remainderForQcr'); + $routes->get('generatePDF', 'TestingController::generatePDF'); + $routes->get('viewPDF', 'TestingController::viewPDF'); + $routes->get('generate-pdf-view', 'TestingController::generatePDFWithView'); }); +$routes->cli('cli/testcli', 'TestingController::testcli'); + diff --git a/app/Controllers/Chatbot/NetworkHospitalConversation.php b/app/Controllers/Chatbot/NetworkHospitalConversation.php index 4a1e991c..34e44f2b 100644 --- a/app/Controllers/Chatbot/NetworkHospitalConversation.php +++ b/app/Controllers/Chatbot/NetworkHospitalConversation.php @@ -52,25 +52,27 @@ class NetworkHospitalConversation extends Conversation // }); $this->bot->ask($question, function ($answer) { - $path = $this->bot->userStorage()->get('path'); + $path = $this->bot->userStorage()->get('path'); array_push($path, $answer->getValue() ); $this->bot->userStorage()->save([ 'path' => $path ]); - log_message('error', ('user_reponse : ' . $answer->getValue())); - + // log_message('error', ('user_reponse : ' . $answer->getValue())); + // log_message('error', ('user_reponse : ' . json_encode(explode('#',$answer->getValue())))); switch ($answer->getValue()) { case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2: - $client_poilicy_id = explode('#',$answer->getValue())[1]; - $hospital_link = ChatbotHelper::getHospitalLink($client_poilicy_id); + $emp_poilicy_id = explode('#',$answer->getValue()); + $emp_poilicy_id = array_shift($emp_poilicy_id); + log_message('error','EMP POL ID FOR HOSPITAL' . $emp_poilicy_id); + $hospital_link = ChatbotHelper::getHospitalLink($emp_poilicy_id); if($hospital_link) { - $this->say('Click here for hospital details'); + $this->say('Click here for hospital details'); } else { diff --git a/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php b/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php index fd6e3337..0c3374e4 100644 --- a/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php +++ b/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php @@ -24,10 +24,19 @@ class ReimbursementClaimStatusConversation extends Conversation $chat_session_info = get_chatbot_session_info(); $data = ChatbotHelper::getReimbursementClaimStatus($chat_session_info); - + log_message('error','Claim Number - ' . json_encode($data['claim_number'])); $this->bot->types(); if ($data){ - $this->say("The claim status for the claim Number {$data['claim_number']} is currently in {$data['client_status']} status.
More Detailed Information is sent to your mail"); + if(isset($data['claim_number']) && $data['claim_number'] !== null) + { + log_message('error','Claim Number YES- ' . json_encode($data['claim_number'])); + $this->say("The claim status for the claim Number {$data['claim_number']} is currently in {$data['client_status']} status.
More Detailed Information is sent to your mail"); + } + else + { + log_message('error','Claim Number NO- ' . json_encode($data['claim_number'])); + $this->say("The claim status for your latest claim (ID not generated) is currently in {$data['client_status']} status.
More Detailed Information is sent to your mail"); + } $this->bot->startConversation(new doYouWantToContinueConversation()); }else{ $this->say("No Claim Raised against the user."); diff --git a/app/Controllers/Chatbot/doYouWantToContinueConversation.php b/app/Controllers/Chatbot/doYouWantToContinueConversation.php index 31bcf174..d7160bb7 100644 --- a/app/Controllers/Chatbot/doYouWantToContinueConversation.php +++ b/app/Controllers/Chatbot/doYouWantToContinueConversation.php @@ -77,6 +77,7 @@ class doYouWantToContinueConversation extends Conversation $this->say("Thank you for your time! If you need anything else, feel free to reach out. Goodbye!"); + $this->say("Say Hi or Help or Hello to start conversation again!"); break; default: $this->say("Invalid selection. Please choose an option."); diff --git a/app/Controllers/Chatbot/vehicleFormConversation.php b/app/Controllers/Chatbot/vehicleFormConversation.php index 3bcf39fd..70cb5d7a 100644 --- a/app/Controllers/Chatbot/vehicleFormConversation.php +++ b/app/Controllers/Chatbot/vehicleFormConversation.php @@ -196,7 +196,7 @@ class vehicleFormConversation extends Conversation // $cityName = $response->getText(); $sent_staus = ChatbotHelper::sendQuotationRequestMail($vehicle_info); if ($sent_staus){ - $this->say('Our Executive will contact you with the quotation soon.'); + $this->say('Thanks.Our Executive will contact you with the quotation soon.'); $this->bot->startConversation(new doYouWantToContinueConversation()); }else{ $this->say("There was a problem while requesting for a quotation please try again later."); diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 544c40d4..67d31c37 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -116,7 +116,7 @@ class ChatbotControllerNew extends BaseController // Start the Main Menu when user says "hi" or "start" $this->botman->hears('start|hi|hello|help|help me', function (BotMan $bot) { if ($this->isMemberLoggedIn){ - $bot->reply('Hi how can i assist?'); + // $bot->reply('Hi how can i assist?'); $bot->startConversation(new MainMenuConversation()); }else { $bot->startConversation(new LoginToContiueConversation()); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 4a73bb1b..2e9e11c9 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -772,6 +772,8 @@ class ClientController extends AdminController $editData['client'] = $this->clientModel->where(['id' => $id])->first(); $editData['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $id)->findAll(); + $editData['client_kyc_primary_table'] = $this->generateKycPrimaryTable($id); + $editData['client_kyc_other_table'] = $this->generateKycOthersTable($id); $editData['client_branch'] = $this->clientBranchModel->where(['client_id' => $id, 'is_active' => 1])->findAll(); $editData['client_relation'] = $this->clientRMModel->where(['client_id' => $id, 'is_active' => 1])->findAll(); $editData['client_branch']['role'] = get_role_id(); @@ -870,6 +872,8 @@ class ClientController extends AdminController { $this->myLogger->logme('error', 'create Client kyc function called'); $data = $this->request->getPost(); + $form_type = $this->request->getPost('form_type') ?? null; + // print_r($data); die; unset($data['file_name']); $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; @@ -885,8 +889,12 @@ class ClientController extends AdminController $data['created_by'] = get_session_userid(); $insert = $this->clientKYCDocsModel->insert($data); if ($insert) { - - $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll(); + // $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll(); + if($form_type == "others"){ + $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id')); + }else{ + $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id')); + } return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); @@ -899,6 +907,8 @@ class ClientController extends AdminController $this->myLogger->logme('error', 'edit client kyc function called'); $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath); + $form_type = $this->request->getPost('form_type') ?? null; + if (!empty($File)) { $data['file_name'] = $File; } @@ -907,8 +917,14 @@ class ClientController extends AdminController $data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id'); $data['updated_by'] = get_session_userid(); $insert = $this->clientKYCDocsModel->insert($data); + if ($insert) { - $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id); + // $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id); + if($form_type == "others"){ + $kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id')); + }else{ + $kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id')); + } return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); @@ -2148,6 +2164,50 @@ class ClientController extends AdminController } } + public function generateKycPrimaryTable($client_id){ + + $db = db_connect(); + $builder = $db->table('kyc_docs kd'); + $builder->select('kd.*, ck.file_name AS upload_doc_name'); + $builder->join('clients c', 'kd.kyc_type_id = c.entity_type_id'); + $builder->join( + 'client_kyc_documents ck', + 'kd.id = ck.kyc_doc_type_id AND ck.client_id = c.id AND ck.is_active = 1', + 'left' + ); + $builder->where('c.id', $client_id); + $builder->groupBy(['kd.id', 'ck.file_name']); + + $query = $builder->get(); + $result['data'] = $query->getResultArray(); + $result['client_id'] = $client_id; + + $table = view('client_kyc_primary_table', $result); + + return $table; + // print_r($table); die; + + } + + 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(); + + $result['client_id'] = $client_id; + $table = view('client_kyc_other_table', $result); + + return $table; + // print_r($table); die; + + } + public function getPolicesByInsurerId($id = null) { $this->myLogger->logme('error', 'getPolicesByInsurerId function called'); @@ -2423,6 +2483,7 @@ class ClientController extends AdminController // echo "
";
             // print_r($this->request->getPost());die;
+            $this->myLogger->logme('error', "post data : " . json_encode($this->request->getPost() ?? []));
             $this->myLogger->logme('error', 'Terms CREATE function called');
 
             /*** Client Policy Table Primary Key(ID) ***/
@@ -2624,7 +2685,7 @@ class ClientController extends AdminController
             }
             
             $data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
-
+            $this->myLogger->logme('error', "contructed post data : " . json_encode($data ?? []));
             // print_r($data);die;
 
             $jsonData = json_encode($data);
@@ -2658,194 +2719,269 @@ class ClientController extends AdminController
         }
     }
 
+    // public function enrollmentGMCDisplayValueTransform()
+    // {
+    //     $data = [];
+
+    //     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");
+    //     }
+
+    //     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);
+
+    //         if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+    //             $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+    //             $data = array_merge($data, $mergedArray);
+    //         }
+    //     }
+        
+    //     if(isset($data) && !empty($data)){
+    //         return $data;
+    //     }else{
+    //         $data = [];
+    //         return $data;
+    //     }
+    
+    // }
+
     public function enrollmentGMCDisplayValueTransform()
     {
         $data = [];
 
-        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");
-        }
+        // Mapping of POST keys to display labels
+        $fields = [
+            'waiverofpreexistingdiseases' => 'Waiver of Pre-existing Diseases',
+            'waiverof1,2,3&4thyearexclusions' => 'Waiver of 1, 2, 3 & 4th year Exclusions',
+            'waiverof30dayswaitingperiod' => 'Waiver of 30 days waiting period',
+            'suminsuredenhancement' => 'Sum Insured Enhancement',
+            'waiver_of_90_days_waiting_period' => 'Waiver of 90 Days Waiting Period',
+            'waiver_of_other_waiting_periods' => 'Waiver of Other Waiting Periods',
+            'maternity_benefit' => 'Maternity Benefit',
+            '9monthwaitingperiodwaived' => '9-month waiting Period - waived',
+            'maternitycoverage' => 'Maternity Coverage',
+            'twindelivery' => 'Twin Delivery',
+            'well_baby_well_mother_expenses' => 'Well baby / Well Mother Expenses',
+            'preandpostnatal' => 'Pre and Post natal',
+            'infertility_treatment_coverage' => 'Infertility Treatment Coverage',
+            'babyday1cover' => 'Baby Day 1 Cover',
+            'coverfromthedateofjoining' => 'Cover from the date of Joining',
+            'mid_term_addition_of_new_born_newly_wedded_spouse' => 'Mid Term Addition of New Born / Newly Wedded Spouse',
+            'prehospitalizationcover' => 'Pre Hospitalization Cover',
+            'posthospitalizationcover' => 'Post Hospitalization Cover',
+            'congenitaldiseasesinternal' => 'Congenital Diseases - Internal',
+            'congenitaldiseasesexternal' => 'Congenital Diseases - External',
+            'copayzonewisecopay' => 'Co-Pay/Zone wise Co Pay',
+            'roomrentlimit' => 'Room Rent Limit',
+            'icu_limit' => 'ICU Limit',
+            'proportionatedeductionclause' => 'Proportionate Deduction Clause',
+            'ailmentcapping' => 'Ailment capping',
+            'ailment_capping_details' => 'Ailment capping Details',
+            'corporatebuffer' => 'Corporate Buffer',
+            'non_admissible_contingency_corporate_buffer' => 'Non-Admissible / Contingency Corporate Buffer',
+            'ambulancecharges' => 'Ambulance Charges',
+            'airambulance' => 'Air Ambulance',
+            'reasonableandcustomarycharges' => 'Reasonable and Customary Charges',
+            'daycaretreatment' => 'Day Care Treatment',
+            'lasiksurgery' => 'Lasik Surgery',
+            'ayudhtreatmentcover' => 'AYUSH treatment cover',
+            'moderntreatmentsasperirdai' => 'Modern treatments as per IRDAI',
+            'opd_treatment' => 'OPD Treatment',
+            'days_of_discharge' => 'Claim Intimation Clause',
+            'days_from_dod' => 'Claim Submission',
+            'terrorism' => 'Terrorism',
+            'widower_cover' => 'Widower Cover',
+            'breavement_cover' => 'Breavement Cover'
+        ];
 
-        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);
-
-            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
-                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
-                $data = array_merge($data, $mergedArray);
+        foreach ($fields as $postKey => $label) {
+            $displayKey = $postKey . '_display';
+            $value = $this->request->getPost($postKey);
+            if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
+                $data[$label] = $value;
             }
         }
-        
-        if(isset($data) && !empty($data)){
-            return $data;
-        }else{
-            $data = [];
-            return $data;
+
+        // Handle special conditions
+        if ($this->request->getPost("special_condition_display_value")) {
+            $specialConditionKeyValue = json_decode($this->request->getPost("special_condition_display_value"), true);
+            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+                // Only add non-empty values
+                foreach ($mergedArray as $k => $v) {
+                    if ($v !== null && $v !== '') {
+                        $data[$k] = $v;
+                    }
+                }
+            }
         }
-    
+
+        return $data;
     }
 
+
     public function getterms()
     {
         $client_policy_id = $this->request->getVar('client_policy_id');
@@ -3005,92 +3141,145 @@ class ClientController extends AdminController
         }
     }
 
+    // public function enrollmentGPADisplayValueTransform()
+    // {   
+    //     $data = [];
+
+    //     if ($this->request->getPost("accidentalDeathBenefit_display")) {
+    //         $data['Accidental Death Benefit'] = $this->request->getPost("accidentalDeathBenefit");
+    //     }
+    //     if ($this->request->getPost("permanentTotalDisablement_display")) {
+    //         $data['Permanent Total Disablement'] = $this->request->getPost("permanentTotalDisablement");
+    //     }
+    //     if ($this->request->getPost("permanentPartialDisablement_display")) {
+    //         $data['Permanent Partial Disablement'] = $this->request->getPost("permanentPartialDisablement");
+    //     }
+    //     if ($this->request->getPost("temporaryTotalDisablementBenefit_display")) {
+    //         $data['Temporary Total Disablement Benefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
+    //     }
+    //     if ($this->request->getPost("medical_expenses_medical_extension_display")) {
+    //         $data['Medical Expenses / Medical Extension (IPD)'] = $this->request->getPost("medical_expenses_medical_extension");
+    //     }
+    //     if ($this->request->getPost("opd_treatment_cover_display")) {
+    //         $data['OPD Treatment Cover'] = $this->request->getPost("opd_treatment_cover");
+    //     }
+    //     if ($this->request->getPost("ambulanceCharges_display")) {
+    //         $data['Ambulance Charges'] = $this->request->getPost("ambulanceCharges");
+    //     }
+    //     if ($this->request->getPost("repatriation_of_mortal_remains_display")) {
+    //         $data['Repatriation of Mortal Remains'] = $this->request->getPost("repatriation_of_mortal_remains");
+    //     }
+    //     if ($this->request->getPost("childrenEducationWelfareFund_display")) {
+    //         $data['Children Education Welfare Fund'] = $this->request->getPost("childrenEducationWelfareFund");
+    //     }
+    //     if ($this->request->getPost("terrorism_display")) {
+    //         $data['Terrorism'] = $this->request->getPost("terrorism");
+    //     }
+    //     if ($this->request->getPost("worldwideCover_display")) {
+    //         $data['Worldwide Cover'] = $this->request->getPost("worldwideCover");
+    //     }
+    //     if ($this->request->getPost("family_transportation_benefits_display")) {
+    //         $data['Family Transportation Benefits'] = $this->request->getPost("family_transportation_benefits");
+    //     }
+    //     if ($this->request->getPost("fractures_dislocation_burns_display")) {
+    //         $data['Fractures / Dislocation / Burns'] = $this->request->getPost("fractures_dislocation_burns");
+    //     }
+    //     if ($this->request->getPost("coma_display")) {
+    //         $data['Coma'] = $this->request->getPost("coma");
+    //     }
+    //     if ($this->request->getPost("carriageofDeadBody_display")) {
+    //         $data['Carriage of Dead Body'] = $this->request->getPost("carriageOfDeadBody");
+    //     }
+    //     if ($this->request->getPost("compassionateVisitExpenses_display")) {
+    //         $data['Compassionate Visit Expenses'] = $this->request->getPost("compassionateVisitExpenses");
+    //     }
+    //     if ($this->request->getPost("travel_expenses_for_medical_treatment_display")) {
+    //         $data['Travel expenses for Medical Treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
+    //     }
+    //     if ($this->request->getPost("daily_cash_allowance_display")) {
+    //         $data['Daily cash Allowance'] = $this->request->getPost("daily_cash_allowance");
+    //     }
+    //     if ($this->request->getPost("artifical_limb_and_prosthesis_display")) {
+    //         $data['Artifical Limb and Prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
+    //     }
+    //     if ($this->request->getPost("animalSnakeInsectBite_display")) {
+    //         $data['Animal/Snake/Insect Bite'] = $this->request->getPost("animalSnakeInsectBite");
+    //     }
+    //     if ($this->request->getPost("air_ambulance_display")) {
+    //         $data['Air Ambulance'] = $this->request->getPost("air_ambulance");
+    //     }
+
+    //     if ($this->request->getPost("gpa_special_condition_display_value")) {
+
+    //         $specialConditionKeyValue = $this->request->getPost("gpa_special_condition_display_value") ?? [];
+    //         $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
+
+    //         if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+    //             $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+    //             $data = array_merge($data, $mergedArray);
+    //         }
+    //     }
+    //     // print_r($data); die;
+
+    //     if (isset($data) && !empty($data)) {
+    //         return $data;
+    //     } else {
+    //         $data = [];
+    //         return $data;
+    //     }
+    // }
+
     public function enrollmentGPADisplayValueTransform()
-    {   
+    {
         $data = [];
 
-        if ($this->request->getPost("accidentalDeathBenefit_display")) {
-            $data['Accidental Death Benefit'] = $this->request->getPost("accidentalDeathBenefit");
-        }
-        if ($this->request->getPost("permanentTotalDisablement_display")) {
-            $data['Permanent Total Disablement'] = $this->request->getPost("permanentTotalDisablement");
-        }
-        if ($this->request->getPost("permanentPartialDisablement_display")) {
-            $data['Permanent Partial Disablement'] = $this->request->getPost("permanentPartialDisablement");
-        }
-        if ($this->request->getPost("temporaryTotalDisablementBenefit_display")) {
-            $data['Temporary Total Disablement Benefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
-        }
-        if ($this->request->getPost("medical_expenses_medical_extension_display")) {
-            $data['Medical Expenses / Medical Extension (IPD)'] = $this->request->getPost("medical_expenses_medical_extension");
-        }
-        if ($this->request->getPost("opd_treatment_cover_display")) {
-            $data['OPD Treatment Cover'] = $this->request->getPost("opd_treatment_cover");
-        }
-        if ($this->request->getPost("ambulanceCharges_display")) {
-            $data['Ambulance Charges'] = $this->request->getPost("ambulanceCharges");
-        }
-        if ($this->request->getPost("repatriation_of_mortal_remains_display")) {
-            $data['Repatriation of Mortal Remains'] = $this->request->getPost("repatriation_of_mortal_remains");
-        }
-        if ($this->request->getPost("childrenEducationWelfareFund_display")) {
-            $data['Children Education Welfare Fund'] = $this->request->getPost("childrenEducationWelfareFund");
-        }
-        if ($this->request->getPost("terrorism_display")) {
-            $data['Terrorism'] = $this->request->getPost("terrorism");
-        }
-        if ($this->request->getPost("worldwideCover_display")) {
-            $data['Worldwide Cover'] = $this->request->getPost("worldwideCover");
-        }
-        if ($this->request->getPost("family_transportation_benefits_display")) {
-            $data['Family Transportation Benefits'] = $this->request->getPost("family_transportation_benefits");
-        }
-        if ($this->request->getPost("fractures_dislocation_burns_display")) {
-            $data['Fractures / Dislocation / Burns'] = $this->request->getPost("fractures_dislocation_burns");
-        }
-        if ($this->request->getPost("coma_display")) {
-            $data['Coma'] = $this->request->getPost("coma");
-        }
-        if ($this->request->getPost("carriageofDeadBody_display")) {
-            $data['Carriage of Dead Body'] = $this->request->getPost("carriageOfDeadBody");
-        }
-        if ($this->request->getPost("compassionateVisitExpenses_display")) {
-            $data['Compassionate Visit Expenses'] = $this->request->getPost("compassionateVisitExpenses");
-        }
-        if ($this->request->getPost("travel_expenses_for_medical_treatment_display")) {
-            $data['Travel expenses for Medical Treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
-        }
-        if ($this->request->getPost("daily_cash_allowance_display")) {
-            $data['Daily cash Allowance'] = $this->request->getPost("daily_cash_allowance");
-        }
-        if ($this->request->getPost("artifical_limb_and_prosthesis_display")) {
-            $data['Artifical Limb and Prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
-        }
-        if ($this->request->getPost("animalSnakeInsectBite_display")) {
-            $data['Animal/Snake/Insect Bite'] = $this->request->getPost("animalSnakeInsectBite");
-        }
-        if ($this->request->getPost("air_ambulance_display")) {
-            $data['Air Ambulance'] = $this->request->getPost("air_ambulance");
-        }
+        // Map POST keys to display labels
+        $fields = [
+            'accidentalDeathBenefit' => 'Accidental Death Benefit',
+            'permanentTotalDisablement' => 'Permanent Total Disablement',
+            'permanentPartialDisablement' => 'Permanent Partial Disablement',
+            'temporaryTotalDisablementBenefit' => 'Temporary Total Disablement Benefit',
+            'medical_expenses_medical_extension' => 'Medical Expenses / Medical Extension (IPD)',
+            'opd_treatment_cover' => 'OPD Treatment Cover',
+            'ambulanceCharges' => 'Ambulance Charges',
+            'repatriation_of_mortal_remains' => 'Repatriation of Mortal Remains',
+            'childrenEducationWelfareFund' => 'Children Education Welfare Fund',
+            'terrorism' => 'Terrorism',
+            'worldwideCover' => 'Worldwide Cover',
+            'family_transportation_benefits' => 'Family Transportation Benefits',
+            'fractures_dislocation_burns' => 'Fractures / Dislocation / Burns',
+            'coma' => 'Coma',
+            'carriageOfDeadBody' => 'Carriage of Dead Body',
+            'compassionateVisitExpenses' => 'Compassionate Visit Expenses',
+            'travel_expenses_for_medical_treatment' => 'Travel expenses for Medical Treatment',
+            'daily_cash_allowance' => 'Daily cash Allowance',
+            'artifical_limb_and_prosthesis' => 'Artifical Limb and Prosthesis',
+            'animalSnakeInsectBite' => 'Animal/Snake/Insect Bite',
+            'air_ambulance' => 'Air Ambulance'
+        ];
 
-        if ($this->request->getPost("gpa_special_condition_display_value")) {
-
-            $specialConditionKeyValue = $this->request->getPost("gpa_special_condition_display_value") ?? [];
-            $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);
-
-            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
-                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
-                $data = array_merge($data, $mergedArray);
+        foreach ($fields as $postKey => $label) {
+            $displayKey = $postKey . '_display';
+            $value = $this->request->getPost($postKey);
+            if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
+                $data[$label] = $value;
             }
         }
-        // print_r($data); die;
 
-        if (isset($data) && !empty($data)) {
-            return $data;
-        } else {
-            $data = [];
-            return $data;
+        // Handle GPA special conditions
+        if ($this->request->getPost("gpa_special_condition_display_value")) {
+            $specialConditionKeyValue = json_decode($this->request->getPost("gpa_special_condition_display_value"), true);
+            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
+                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
+                foreach ($mergedArray as $k => $v) {
+                    if ($v !== null && $v !== '') {
+                        $data[$k] = $v;
+                    }
+                }
+            }
         }
+
+        return $data;
     }
 
     public function getPolicyGPATerms()
@@ -5404,7 +5593,8 @@ class ClientController extends AdminController
                 employees.mobile AS emp_mobile,
                 employees.email_corporate AS emp_email,
                 employees.relationship AS emp_relationship,
-                employee_polices.uhid AS policy_no
+                employee_polices.uhid AS policy_no,
+                employee_polices.client_policy_id
             ")
             ->join('clients', 'client_policy.client_id = clients.id', 'left')
             ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
@@ -5417,9 +5607,15 @@ class ClientController extends AdminController
             ->where('employees.is_active', 1)
             ->where('employees.relationship', "Self")
             ->where('employee_polices.is_active', 1)
+            ->whereIn('employees.emp_status', ['active'])
+            ->whereIn('employee_polices.status', ['active'])
+            ->where('employees.is_active', 1)
             ->where('client_policy.id', $param)
+            ->groupBy('employees.emp_code')
             ->get()
             ->getResultArray();
+
+        // print_r(db_connect()->getLastQuery()); die;
        
         $dataForClientAndInsurer = $this->clientPolicyModel
                 ->select("
@@ -5461,20 +5657,39 @@ class ClientController extends AdminController
                 'memberData' => $memberData
             ], 404);
         }
-    } 
-    
-    public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null, $ticket_type_id = null)
-    {   
+    }
+
+    // public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null, $ticket_type_id = null)
+    public function getTheEmpDataForClaimSearchByMobile()
+    {
+
+        $request = $this->request;
+
+        // Get parameters from GET request
+        $param = $request->getGet('param');
+        $type = $request->getGet('type') ?? 'mobile';
+        $client_policy_id = $request->getGet('client_policy_id');
+        $client_id = $request->getGet('client_id');
+        $ticket_type_id = $request->getGet('ticket_type_id');
+
+        // Validate required parameter
+        if (empty($param)) {
+            return $this->response->setJSON([
+                'status' => false,
+                'message' => 'Parameter is required'
+            ])->setStatusCode(400);
+        }
+
         $field_name = 'employees.' . $type;
 
         $policy_type_id = [];
-        if($ticket_type_id == 1){
+        if ($ticket_type_id == 1) {
             $policy_type_id = [2, 3, 4, 5];
-        }else if($ticket_type_id == 2){
+        } else if ($ticket_type_id == 2) {
             $policy_type_id = [1];
-        }else if($ticket_type_id == 3){
+        } else if ($ticket_type_id == 3) {
             $policy_type_id = [6];
-        }else if($ticket_type_id == 4){
+        } else if ($ticket_type_id == 4) {
             $policy_type_id = [7];
         }
 
@@ -5512,24 +5727,24 @@ class ClientController extends AdminController
             ->where('employee_polices.status', "active")
             ->where($field_name, $param);
 
-            if (!empty($client_id)) {
-                $query->where('employees.client_id', $client_id);
-            }
+        if (!empty($client_id)) {
+            $query->where('employees.client_id', $client_id);
+        }
 
-            if (!empty($client_policy_id)) {
-                $query->where('employee_polices.client_policy_id', $client_policy_id);
-            }
+        if (!empty($client_policy_id)) {
+            $query->where('employee_polices.client_policy_id', $client_policy_id);
+        }
 
-            if($policy_type_id != null){
-                $query->whereIn('client_policy.policy_type_id', $policy_type_id);
-            }
-            
-            $query->groupBy('employees.id')
-                ->orderBy('employees.id', 'DESC');
-            
-            $data = $query->get()->getRowArray();
+        if ($policy_type_id != null) {
+            $query->whereIn('client_policy.policy_type_id', $policy_type_id);
+        }
 
-            // print_r(db_connect()->getLastQuery()); die;
+        $query->groupBy('employees.id')
+            ->orderBy('employees.id', 'DESC');
+
+        $data = $query->get()->getRowArray();
+
+        // print_r(db_connect()->getLastQuery()); die;
 
         $memberData = [];
         $dataForClientAndInsurer = [];
@@ -5540,15 +5755,15 @@ class ClientController extends AdminController
         // ->where('user_profiles.role', 3)
         // ->get()
         // ->getResultArray();
-            
-        if(!empty($data) && count($data) > 0){
+
+        if (!empty($data) && count($data) > 0) {
 
             $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $client_policy_id, $client_id);
             $acms_datas = $this->employeeModel->getAcmUsingClientID($data['client_id']);
             // if(!empty($acms_datas)){
             //     $acms = $acms_datas;
             // }
-        }else{
+        } else {
             $acms_datas = "";
         }
 
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 285207f4..1aec089e 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -2088,6 +2088,7 @@ class EmpDataServiceController extends BaseController
                 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
                 'gst' => $base_bremium_and_gst['gst'] ?? null,
                 'policy_issue_date' => $policy_issue_date ?? null,
+                'created_by' => $file['created_by'] ?? null,
             ]]);
 
             // $this->cashDepositCalculationForInception($depositeData);
@@ -2523,6 +2524,7 @@ class EmpDataServiceController extends BaseController
             'emp_count' => $emp_count ?? null,
             'action_type' => $file['event_type'] ?? null,
             'policy_issue_date' => $policy_issue_date ?? null,
+            'created_by' => $file['created_by'] ?? null,
         ]]);
 
 
@@ -3185,6 +3187,7 @@ class EmpDataServiceController extends BaseController
                 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
                 'gst' => $base_bremium_and_gst['gst'] ?? null,
                 'policy_issue_date' => $policy_issue_date ?? null,
+                'created_by' => $file['created_by'] ?? null,
             ]]);
 
         }
@@ -3695,6 +3698,7 @@ class EmpDataServiceController extends BaseController
                 'base_premium' => $base_bremium_and_gst['base_premium'] ?? null,
                 'gst' => $base_bremium_and_gst['gst'] ?? null,
                 'policy_issue_date' => $policy_issue_date ?? null,
+                'created_by' => $file['created_by'] ?? null,
             ]]);
         }
 
@@ -4989,7 +4993,7 @@ class EmpDataServiceController extends BaseController
             'policy_no' => $policy_data['policy_no'] ?? null,
             'cd_ac_no' => $policy_data['cd_ac_no'] ?? null,
             'cd_ac_pk' => $policy_data['cd_ac_pk'] ?? null,
-            'policy_issue_date' => $policy_data['policy_issue_date'] ?? null,
+            'policy_issue_date' => $params['policy_issue_date'] ?? null,
             'policy_start_date' => $policy_data['policy_start_date'] ?? null,
             'policy_end_date' => $policy_data['policy_end_date'] ?? null,
             'data_received_date' => $policy_data['data_received_date'] ?? null,
@@ -5000,7 +5004,7 @@ class EmpDataServiceController extends BaseController
             'co_share' => $policy_data['co_share'] ?? 0,
             'pre_payable_by' => $policy_data['pre_payable_by'] ?? 1,
             'renewal_date' => $policy_data['policy_end_date'] ?? null,
-            'month' => date('Y-m-01', strtotime($policy_data['policy_issue_date'] ?? "")) ?? null,
+            'month' => date('Y-m-01', strtotime($params['policy_issue_date'] ?? "")) ?? null,
             'ct_type' => 1,
             'is_cd_reduce_from_bds' => 0,
             'client_type_id' => 0,
@@ -5015,6 +5019,7 @@ class EmpDataServiceController extends BaseController
             'source_client_policy_id' => $lead_data['source_policy_id'] ?? null,
             'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
             'installment' => $lead_data['no_of_installment'] ?? null,
+            'created_by' => $params['created_by'] ?? null,
         ];
 
         $this->myLogger->logme("error", "Constructed policy transaction data: " . json_encode($policyTransactionData));
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 5a5039f6..b97bd1b0 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -27,6 +27,7 @@ use App\Models\ClientDepositModel;
 use App\Models\PolicyPremium2Model;
 use App\Models\AuditHistoryModel;
 use App\Models\UserModel;
+use App\Models\PartnerEndorsementRequestModel;
 
 
 use App\Controllers\Jobs;
@@ -68,6 +69,7 @@ class EmployeeController extends AdminController
     protected $PolicyPremium2Model;
     protected $auditHistory;
     protected $userModel;
+    protected $partnerEndorsementRequestModel;
 
     public function __construct()
     {
@@ -90,6 +92,7 @@ class EmployeeController extends AdminController
         $this->PolicyPremium2Model = new PolicyPremium2Model();
         $this->auditHistory = new AuditHistoryModel();
         $this->userModel = new userModel();
+        $this->partnerEndorsementRequestModel  = new PartnerEndorsementRequestModel();
     }
 
     public function list()
@@ -1180,8 +1183,10 @@ class EmployeeController extends AdminController
         return $response;
     }
 
-    //E-CARD DOWNLOAD FUNCTION
-    public function generateIDCardForEmployee($rand_string, $people = 0)
+    // --------------- For E-Card Download -----------------------------------------------------------------------------------------------------
+
+    //E-CARD DOWNLOAD FUNCTION USING HTML PRINT
+    public function generateIDCardForEmployeeUsingHtml($rand_string, $people = 0)
     {    
         // dd($rand_string, $people);
         try {
@@ -1316,6 +1321,258 @@ class EmployeeController extends AdminController
         
     }
 
+    // Preview E-Card Template function
+    public function previewTemplate($id = null)
+    {
+        $value = [
+            'tpa_id' => 'TPA12345',
+            'name' => 'John Doe',
+            'uhid' => 'UHID67890',
+            'gender' => 'Male',
+            'dob' => '1985-05-15',
+            'self' => 'John Doe',
+            'policy_end_date' => '2024-12-31',
+            'policy_start_date' => '2023-01-01',
+            'policy_no' => 'POL1234567890',
+            'insurer_name' => 'Example Insurance Company',
+            'emp_code' => 'EMP001122',
+            'client_name' => 'Corporate Client Inc.',
+            'emp_age' => 39,
+            'tpa_name' => 'Example TPA',
+            'insurer_branch_city' => 'New York',
+            'relationship' => 'Self',
+            'basic_cover_si' => '5,00,000',
+        ];
+        
+        $tpa_id = $this->TPAModel->where('id', $id)->first();
+
+        $template_data_path =  WRITEPATH . 'e_card_template/';
+        $tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html';
+        $final_path =  $template_data_path . $tpa_short_name;
+
+        if (!file_exists($final_path)) {
+
+            $data['message'] = 'Record Not Found';
+            return view('errors/404', $data);
+        }
+
+        $tmplt_data = file_get_contents($final_path);
+
+        $placeholders = [
+            '{TPA_ID}' => $value['tpa_id'],
+            '{NAME}' => $value['name'],
+            '{UHID}' => $value['uhid'],
+            '{GENDER}' => $value['gender'],
+            '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
+            '{SELF_NAME}' => $value['self'] ?? $value['name'],
+            '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
+            '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
+            '{POLICY_NO}' => $value['policy_no'], 
+            '{INSURER_NAME}' => strtoupper($value['insurer_name']),
+            '{EMP_ID}' => $value['emp_code'],
+            '{SI_AMT}' => $value['basic_cover_si'], 
+            '{CORPORATE_NAME}' => $value['client_name'],
+            '{AGE}' => $value['emp_age'],
+            '{TPA_NAME}' => $value['tpa_name'],
+            '{INSURER_BRANCH}' => $value['insurer_branch_city'],
+            '{RELATION}' => $value['relationship'],
+            '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'],
+            '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'],
+            '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'],
+            '{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png',
+            '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
+            '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
+            '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
+            '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
+            '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png', 
+            '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
+            '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
+
+        ];
+
+        $placeholders['{LEVELS}'] = '                   
+                    Level 1

+ 1. Gowtham / 8754081806 / gowtham@gmail.com
+ 2. Gowtham / 8754081806 / gowtham@gmail.com

'; + + // dd($placeholders); + + // Get the values to replace the placeholders + $replaceValues = array_values($placeholders); + + // Get the placeholders to search for + $searchPlaceholders = array_keys($placeholders); + + // Replace placeholders with values in HTML content + $htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data); + + + echo $htmlContent; + } + + //E-CARD DOWNLOAD FUNCTION USING DOM PDF ( CURRENTLY USING THIS ) + public function generateIDCardForEmployee($rand_string, $people = 0, $mode = 0) + { + // dd($rand_string, $people); + $this->myLogger->logme('error', 'generateIDCardForEmployee params .' . json_encode(["rand_string" => $rand_string, "people" => $people, "mode" => $mode])); + try { + $this->myLogger->logme('error', 'generateIDCardForEmployee function started.'); + + // Step 1: Attempt to fetch employee code and client policy ID + $this->myLogger->logme('error', 'Fetching employee code and client policy ID.'); + + $get_emp_code_and_client_policy_id = $this->employeePolicyModel + ->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id') + ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') + ->join('employees', 'employees.id = employee_polices.employee_id') + ->join('tpa', 'tpa.id = client_policy.tpa_id') + ->where('employees.emp_status', 'active') + ->where('employees.is_active', '1') + ->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''") + ->where('employee_polices.status', 'active') + ->where('employee_polices.is_active', '1') + ->where('employee_polices.rand_string', $rand_string) + ->first(); + + // dd($this->employeePolicyModel->getLastQuery()); + + // dd($rand_string, $get_emp_code_and_client_policy_id); + + if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") { + $this->myLogger->logme('error', 'Member not found in this rand_string: ' . $rand_string); + $data['message'] = 'Record Not Found'; + return view('errors/404', $data); + } + + $this->myLogger->logme('error', 'Member found. Client policy ID: ' . $get_emp_code_and_client_policy_id['client_policy_id']); + + $client_policy_id = $get_emp_code_and_client_policy_id['client_policy_id']; + $emp_code = $get_emp_code_and_client_policy_id['emp_code']; + $client_id = $get_emp_code_and_client_policy_id['client_id']; + + // Step 2: Fetch ECard data + $this->myLogger->logme('error', 'Fetching ECard data using client_policy_id: ' . $client_policy_id . ' and emp_code: ' . $emp_code); + $data = $this->employeePolicyModel->getECardDataUsingMd5($client_policy_id, $emp_code,$client_id); + + if ($people == 0) { + $this->myLogger->logme('error', 'Fetching single ECard data using rand_string: ' . $rand_string . ' and emp_code: ' . $emp_code); + $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code,$client_id); + } + + // Step 3: Prepare template path + $template_data_path = WRITEPATH . 'e_card_template/'; + // $tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html'; + $tpa_short_name = 'common.html'; + $final_path = $template_data_path . $tpa_short_name; + + $this->myLogger->logme('error', 'Checking if template file exists at: ' . $final_path); + + if (!file_exists($final_path)) { + $this->myLogger->logme('error', 'Template file not found: ' . $final_path); + $data['message'] = 'Template File Not Found'; + return view('errors/404', $data); + } + + $this->myLogger->logme('error', 'Template file found. Reading template data.'); + $tmplt_data = file_get_contents($final_path); + + // Step 4: Generate HTML content + $this->myLogger->logme('error', 'Generating HTML content from template.'); + $html = ""; + foreach ($data as $key => $value) { + $htmlContent = $tmplt_data; + + $value['front_card'] = "Nhance_Ecard_working_1_front.png"; + $value['back_card'] = "Nhance_Ecard_working_1_Back.png"; + + $placeholders = [ + '{CLIENT_NAME}' => $value['client_name'], + '{TPA_ID}' => $value['tpa_id'], + '{NAME}' => $value['name'], + '{UHID}' => $value['uhid'], + '{GENDER}' => $value['gender'], + '{DOB}' => date('d-M-Y', strtotime($value['dob'])), + '{SELF_NAME}' => $value['self'] ?? $value['name'], + '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])), + '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])), + '{POLICY_NO}' => $value['policy_no'], + '{INSURER_NAME}' => strtoupper($value['insurer_name']), + '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'], + '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'], + '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'], + '{EMP_ID}' => $value['emp_code'], + '{SI_AMT}' => $value['basic_cover_si'], + '{CORPORATE_NAME}' => $value['client_name'], + '{AGE}' => $value['emp_age'], + '{TPA_NAME}' => $value['tpa_name'], + '{INSURER_BRANCH}' => $value['insurer_branch_city'], + '{RELATION}' => $value['relationship'], + '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'], + '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg', + '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png', + '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg', + '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png', + '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png', + '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png', + '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png', + ]; + + $placeholders['{LEVELS}'] = $this->generateAcmAndMForEcard($client_id); + + foreach ($placeholders as $placeholder => $replaceValue) { + $htmlContent = str_replace($placeholder, $replaceValue, $htmlContent); + } + + $html .= $htmlContent; + } + + // DomPdf + $options = new Options(); + $options->set('isRemoteEnabled', true); + $options->set('isHtml5ParserEnabled', true); + + $dompdf = new Dompdf($options); + $dompdf->loadHtml('' . $html); // remove the margin + $dompdf->setPaper('A4', 'portrait'); + $dompdf->render(); + + // Set document title + $dompdf->addInfo("Title", "E-Card"); + + $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf'; + + // if($mode == 1){ + // $dompdf->stream($filename, ['Attachment' => false]); // Inline view + // }else{ + // $dompdf->stream($filename, ['Attachment' => true]); // Force download + // } + + if ($mode == 1) { + // Inline view + return $this->response + ->setHeader('Content-Type', 'application/pdf') + ->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"') + ->setBody($dompdf->output()); + } else { + // Force download + return $this->response + ->setHeader('Content-Type', 'application/pdf') + ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"') + ->setBody($dompdf->output()); + } + + $this->myLogger->logme('error', 'generateIDCardForEmployee function completed successfully.'); + + } catch (\Exception $e) { + $this->myLogger->logme('error', 'Exception occurred: ' . $e->getMessage()); + $data['message'] = 'Record Not Found'; + return view('errors/404', $data); + } + + } + + // -------------------------------------------------------------------------------------------------------------------- + public function viewECard() { @@ -1883,95 +2140,6 @@ class EmployeeController extends AdminController } } - // Preview E-Card Template function - public function previewTemplate($id = null) - { - $value = [ - 'tpa_id' => 'TPA12345', - 'name' => 'John Doe', - 'uhid' => 'UHID67890', - 'gender' => 'Male', - 'dob' => '1985-05-15', - 'self' => 'John Doe', - 'policy_end_date' => '2024-12-31', - 'policy_start_date' => '2023-01-01', - 'policy_no' => 'POL1234567890', - 'insurer_name' => 'Example Insurance Company', - 'emp_code' => 'EMP001122', - 'client_name' => 'Corporate Client Inc.', - 'emp_age' => 39, - 'tpa_name' => 'Example TPA', - 'insurer_branch_city' => 'New York', - 'relationship' => 'Self', - 'basic_cover_si' => '5,00,000', - ]; - - $tpa_id = $this->TPAModel->where('id', $id)->first(); - - $template_data_path = WRITEPATH . 'e_card_template/'; - $tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html'; - $final_path = $template_data_path . $tpa_short_name; - - if (!file_exists($final_path)) { - - $data['message'] = 'Record Not Found'; - return view('errors/404', $data); - } - - $tmplt_data = file_get_contents($final_path); - - $placeholders = [ - '{TPA_ID}' => $value['tpa_id'], - '{NAME}' => $value['name'], - '{UHID}' => $value['uhid'], - '{GENDER}' => $value['gender'], - '{DOB}' => date('d-M-Y', strtotime($value['dob'])), - '{SELF_NAME}' => $value['self'] ?? $value['name'], - '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])), - '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])), - '{POLICY_NO}' => $value['policy_no'], - '{INSURER_NAME}' => strtoupper($value['insurer_name']), - '{EMP_ID}' => $value['emp_code'], - '{SI_AMT}' => $value['basic_cover_si'], - '{CORPORATE_NAME}' => $value['client_name'], - '{AGE}' => $value['emp_age'], - '{TPA_NAME}' => $value['tpa_name'], - '{INSURER_BRANCH}' => $value['insurer_branch_city'], - '{RELATION}' => $value['relationship'], - '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'], - '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'], - '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'], - '{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png', - '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg', - '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png', - '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg', - '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png', - '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png', - '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png', - '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png', - - ]; - - $placeholders['{LEVELS}'] = ' - Level 1

- 1. Gowtham / 8754081806 / gowtham@gmail.com
- 2. Gowtham / 8754081806 / gowtham@gmail.com

'; - - // dd($placeholders); - - // Get the values to replace the placeholders - $replaceValues = array_values($placeholders); - - // Get the placeholders to search for - $searchPlaceholders = array_keys($placeholders); - - // Replace placeholders with values in HTML content - $htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data); - - - echo $htmlContent; - } - public function errorListExportImport($file_id) { @@ -2842,4 +3010,80 @@ class EmployeeController extends AdminController } + /** + * Below function displays the endorsement list page. + * + * This method retrieves filter data from the request and fetches the endorsement list + * based on the provided filters such as client ID, policy ID, and status. + */ + public function retailendorsementlist() + { + + $data = []; + $data['status'] = ['open' => 'Open', 'inprogress' => 'In-Progress', 'complete' => 'Complete']; + $data['client'] = $this->clientModel->select('clients.id,client_name,short_name') + ->where('clients.is_active',1) + ->where('clients.client_type',2) + ->findAll(); + $data['insurer'] = $this->insurerModel->select('insurers.id,name,short_name') + ->where('insurers.is_active',1) + ->findAll(); + // if (count($this->request->getGet())) { + $filterData = $this->request->getGet(); + $data['employees'] = $this->partnerEndorsementRequestModel->getRetailEndorsementList( + client_id: $filterData['client_id'] ?? null, + insurers_id: $filterData['insurer_id'] ?? null, + status: $filterData['status'] ?? null + ); + + $data['getData'] = $filterData; + // echo "
";
+            // print_r($data); die;
+        // }
+
+        $this->loadLayout('retail_endorsement_list', $data);
+    }
+
+    public function retailendorsementsave()
+    {
+        try {
+            $data = $this->request->getPost();
+            if (!empty($data['id'])) {
+                $text   = "update";
+                $updateID = $data['id'];
+                $result = $this->partnerEndorsementRequestModel->where('id', $updateID)->set($data)->update();
+            } else {
+                $text   = "create";
+                $data['created_by'] = get_session_userid();
+                $this->thzMasterModel->insert($data);
+                $insertID = $this->partnerEndorsementRequestModel->insertID();
+                $result = true;
+            }
+
+            $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID;
+
+            return $this->response->setJSON([
+                'status' => $result ? 'success' : 'error',
+                'message' => $result ? "Partner Endorsement Request {$text}d successfully " : "Unable to {$text} Partner Endorsement Request. Please try again.",
+            ])->setStatusCode($result ? 200 : 400);
+        } catch (\Throwable $e) {
+            $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
+
+            $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException
+                || $e instanceof \mysqli_sql_exception
+                || $e instanceof \PDOException;
+
+            $context = ['title'   => get_class($e), 'type'    => get_class($e), 'code'    => $code, 'message' => $e->getMessage(), 'file'    => $e->getFile(), 'line'    => $e->getLine()];
+
+            $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0);
+
+            return $this->response->setJSON([
+                'status'  => 'error',
+                'message' => $isDbError ? 'Data Access Error' : $e->getMessage(),
+                'ref'     => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine()
+            ])->setStatusCode($code);
+        }
+    }
+
+
 }
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 4fc7d1c4..1dd19735 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -51,7 +51,7 @@ use CodeIgniter\API\ResponseTrait;
 use Illuminate\Http\Request;
 
 use App\Controllers\EmployeeServiceController;
-
+use App\Models\ClaimFilesModel;
 use Kreait\Firebase\Factory;
 use Kreait\Firebase\Messaging\CloudMessage;
 use Kreait\Firebase\Messaging\Notification;
@@ -2622,9 +2622,38 @@ class EmployeeRestController extends AdminController
             }
         }
 
-        
 
-        return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data ], 200);
+        $ticketMesssageModel = new TicketMessageModel();
+        $ticket_message = $ticketMesssageModel
+            ->where('is_active', 1)
+            ->where('sender', "user")
+            ->where('ticket_id', $ticket_id)
+            ->orderBy('id', "desc")
+            ->first();
+
+        $claim_file_urls = [];
+
+        if (isset($ticket_message['id'])) { 
+
+            $claimFiles = new ClaimFilesModel();
+            $claim_files_data = $claimFiles
+                ->select('id as claim_file_id, doc_name as claim_file_name')
+                ->where('is_active', 1)
+                ->where('file_type', 2)
+                ->where('ticket_id', $ticket_id)
+                ->where('ticket_message_id', $ticket_message['id'])
+                ->findAll();
+
+            foreach ($claim_files_data as &$value) {
+                $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id'];
+                $claim_file_urls[] = $value;
+            }
+            unset($value);
+        }
+
+        $data['claim_files'] = $claim_file_urls;
+        
+        return $this->respond(['status' => (count($data) ? 'success' : 'failed'),'code' => (count($data) ? 200 : 404),'data' => $data,  ], 200);
     }
     
 
@@ -2820,18 +2849,29 @@ class EmployeeRestController extends AdminController
                 { 
                     $policyGroup = 'gpa';
                     $data['ticket_type_id'] = 2;
+                    $data['claim_subject'] = "Claim GPA";
+                    $data['sum_insured_label'] = "Sum Assured";
+
                 }else if($ClientPolicyValue['policy_type_id'] == 6)
                 { 
                     $policyGroup = 'gpa';
                     $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';
                     $data['ticket_type_id'] = 4;
+                    $data['claim_subject'] = "Claim GTLI";
+                    $data['sum_insured_label'] = "Sum Assured";
+
                 }else
                 {
                     $policyGroup = 'gmc';
                     $data['ticket_type_id'] = 1;
+                    $data['claim_subject'] = "Claim GMC";
+                    $data['sum_insured_label'] = "Sum Insured";
                 }
 
                 $terms = json_decode($ClientPolicyValue['policy_terms'] , true);
@@ -3406,11 +3446,20 @@ class EmployeeRestController extends AdminController
     {
 
         $received_data = $this->request->getPost();
-        // print_r($received_data); die;
+        $this->myLogger->logme('error', 'API claim initiate Recevied Params :' . json_encode($received_data ?? []));
+        $get_file_data = $this->request->getFiles('claim_docs');
+        // print_r($get_file_data); die;
         $employee_id = $received_data['emp_id'];
         $client_policy_id = $received_data['client_policy_id'];
         $insured_emp_id = $received_data['insured_emp_id'];
 
+        $file_data = [];
+        if(isset($get_file_data) && !empty($get_file_data)){
+            $file_path =   WRITEPATH . 'uploads/claim_files/';
+            $file_data = multi_file_Upload($get_file_data, $file_path);
+        }
+
+
         if (empty($received_data['doa'])) {
             $received_data['doa'] = null;
         } else{
@@ -3503,11 +3552,14 @@ class EmployeeRestController extends AdminController
                     'mail_content' => $fetchData['message'] ?? "New Claim",
                 ];
 
+                $ticket_message_id = null;
                 if (!empty($messagesData['ticket_id'])) {
                     $TicketMessageModel = new TicketMessageModel();
-                    $TicketMessageModel->insert($messagesData);
+                    $ticket_message_id = $TicketMessageModel->insert($messagesData);
                 }
 
+                $this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id);
+
                 $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
                 if (gettype($mail_sent_status) == 'array') {
                     $message = 'Claim Iniated Successfully';
@@ -3544,15 +3596,132 @@ class EmployeeRestController extends AdminController
         }
     }
 
+    public function handleCliamFiles($data, $ticket_id, $ticket_message_id)
+    {
+        if(!empty($data) && !empty($ticket_id))
+        {   
+            $insert_ids = [];
+            $claim_file = new ClaimFilesModel();
+            foreach ($data as $key => $value) {
+
+                $data = [
+                    'ticket_id' => $ticket_id,
+                    'doc_name' => $value['file_name'],
+                    'url' => $value['file_path'],
+                    'file_type' => 2,
+                    'ticket_message_id' => $ticket_message_id,
+                ];
+
+                $insert_ids[] = $claim_file->insert($data);
+            }
+
+            return $insert_ids;
+        }
+
+        return [];
+    }
+
     //department
+    // public function get_ticket_type()
+    // {
+    //     $ticket_type = $this->ticketController->ticketType;
+    //     $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
+    //     // print_r($ticket_type); die;
+    //     return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+    // }
+
     public function get_ticket_type()
     {
-        $ticket_type = $this->ticketController->ticketType;
-        $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
-        // print_r($ticket_type); die;
-        return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+        try {
+
+            $client_id = $this->request->getGet('client_id');
+            $emp_code  = $this->request->getGet('emp_code');
+
+            if (empty($client_id) || empty($emp_code)) {
+
+                $this->myLogger->logme('error', "Missing required parameters: client_id={$client_id}, emp_code={$emp_code}");
+                // return $this->response->setJSON([
+                //     'status'  => false,
+                //     'code'    => 400,
+                //     'message' => 'client_id and emp_code are required'
+                // ])->setStatusCode(400);
+
+                $ticket_type = $this->ticketController->ticketType;
+                $ticket_type = array_map(fn($value, $key) => (object) ['id' => $key, 'name' => $value], array_values($ticket_type), array_keys($ticket_type));
+                return $this->response->setJSON(['ticket_type' => $ticket_type])->setStatusCode(200);
+            }
+
+            // Get policy type ids
+            $policy_type_ids = $this->employeePolicyModel
+                ->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)
+                ->whereIn('employees.emp_status', ['active', 'expired'])
+                ->where('employee_polices.is_active', 1)
+                ->whereIn('employee_polices.status', ['active', 'expired'])
+                ->where('employees.client_id', $client_id)
+                ->where('employees.emp_code', $emp_code)
+                ->groupBy('employee_polices.client_policy_id')
+                ->findAll();
+
+            if (!$policy_type_ids) {
+                $this->myLogger->logme('error', "No policy types found for client_id={$client_id}, emp_code={$emp_code}");
+                return $this->response->setJSON([
+                    'status'  => false,
+                    'code'    => 404,
+                    'message' => 'No policy types found'
+                ])->setStatusCode(404);
+            }
+
+            $this->myLogger->logme('info', "Policy type IDs fetched: " . json_encode($policy_type_ids));
+
+            $ticket_type = $this->ticketController->ticketType;
+            $filtered    = [];
+
+            $mapping = [
+                2 => 1,
+                3 => 1,
+                4 => 1,
+                5 => 1,
+                1 => 2,
+                6 => 3,
+                7 => 4,
+            ];
+
+            foreach ($policy_type_ids as $value) {
+                $ticketTypeId = $value['policy_type_id'] ?? null;
+
+                if (isset($mapping[$ticketTypeId]) && isset($ticket_type[$mapping[$ticketTypeId]])) {
+                    $mappedId   = $mapping[$ticketTypeId];
+                    $mappedName = $ticket_type[$mappedId];
+
+                    // Use mappedId as key to avoid duplicates
+                    $filtered[$mappedId] = [
+                        'id'   => $mappedId,
+                        'name' => $mappedName
+                    ];
+
+                    $this->myLogger->logme('info', "Ticket type resolved: ID={$ticketTypeId}, Name={$mappedName}");
+                } else {
+                    $this->myLogger->logme('warning', "No valid ticket type mapping for policy_type_id={$ticketTypeId}");
+                }
+            }
+
+            $filtered = array_values($filtered);
+            return $this->response->setJSON(['status' => true,'code' => 200, 'ticket_type' => $filtered ])->setStatusCode(200);
+
+        } catch (\Throwable $e) {
+            $this->myLogger->logme('error', "Error in get_ticket_type: " . $e->getMessage() . " Trace: " . $e->getTraceAsString());
+            return $this->response->setJSON([
+                'status'  => false,
+                'code'    => 500,
+                'message' => 'Internal Server Error'
+            ])->setStatusCode(500);
+        }
     }
 
+
     //ticket data
     public function get_ticket_data()
     {
@@ -3566,6 +3735,10 @@ class EmployeeRestController extends AdminController
         $emp_id = $this->request->getGet('emp_id');
         $ticket_type = $this->request->getGet('ticket_type') ?? null;
         $ticket_id = $this->request->getGet('ticket_id') ?? null;
+        $request = \Config\Services::request();
+        $uri = $request->uri->getPath(); 
+        $returnType = "";
+        // $returnType = (strpos($uri, 'api') !== false) ? 'api' : 'web';
         // dd($emp_id);
 
         if (empty($emp_id)) {
@@ -3573,7 +3746,7 @@ class EmployeeRestController extends AdminController
         }
 
         $TicketMasterModel = new TicketMasterModel();
-        $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $ticket_type, $ticket_id);
+        $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $returnType, $ticket_type, $ticket_id);
 
         if (!empty($ticket_data)) {
 
@@ -3589,6 +3762,7 @@ class EmployeeRestController extends AdminController
             ];
 
             foreach ($ticket_data as $key => $value) {
+
                 foreach ($client_claim_status as $claim_key => $claim_value) {
                     if (in_array($value['claim_status_id'], $claim_value)) { // Corrected argument order
                         $ticket_data[$key]['claim_status'] = $claim_key ?? null; // Assign back to the main array
@@ -3603,6 +3777,29 @@ class EmployeeRestController extends AdminController
                 }
                 $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null;  
                 $ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null;
+                
+                $claim_file_urls = [];
+
+                if (isset($value['ticket_message_id'])) {
+
+                    $claimFiles = new ClaimFilesModel();
+                    $claim_files_data = $claimFiles
+                        ->select('id as claim_file_id, doc_name as claim_file_name')
+                        ->where('is_active', 1)
+                        ->where('file_type', 2)
+                        ->where('ticket_id', $value['id'])
+                        ->where('ticket_message_id', $value['ticket_message_id'])
+                        ->findAll();
+
+                    foreach ($claim_files_data as &$value) {
+                        $value['url'] = base_url('downloadClaimFile/') . $value['claim_file_id']; 
+                        $claim_file_urls[] = $value;
+                    }
+                    unset($value);
+                }
+
+                // always set the key (empty if no files found)
+                $ticket_data[$key]['claim_files'] = $claim_file_urls;
 
             }
         }
@@ -3653,6 +3850,11 @@ class EmployeeRestController extends AdminController
         ], 200);
     }
 
+    public function getClaimFiles()
+    {
+        $ticket_id = $this->request->getGet('ticket_id');
+    }
+
     // public function getPreEmployeePolicyCount($mobile_no, $clientId = null)
     // {
     //     log_message('error', 'getPreEmployeePolicyCount called with params : ' . json_encode(['mobile_no' => $mobile_no, 'client_id' => $clientId], true));
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 2cc47520..a80ec116 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1702,6 +1702,15 @@ class EmployeeServiceController extends AdminController
                                 $value['relationship'] =  ucfirst(trim($value['relationship']));
                                 if(count($employee))
                                 {
+                                        if (isset($employee[0]['email_corporate']) && $employee[0]['email_corporate'] != '') 
+                                        {
+                                          unset($value['email_corporate']);
+                                        }
+
+                                        if (isset($employee[0]['mobile']) && $employee[0]['mobile'] != '') 
+                                        {
+                                          unset($value['mobile']);
+                                        }
                                     $value['updated_by'] = $file['created_by'];
                                     $value['id'] = $employee[0]['id'];
                                     $value['emp_status'] = 'active';
diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php
index eb0133d1..68eb0402 100755
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -57,8 +57,8 @@ class Home extends PublicController
                         $data['gemini_response'] = 'An error occurred: ' . $e->getMessage();
                     }
 
-                    print_rr($data);
-                }
+                    //print_rr($data);
+    }
 
     public function check_gemini_2()
     {
@@ -78,8 +78,9 @@ class Home extends PublicController
             $filePath = 'C:/Users/Venba/Desktop/ins stmts/NIC MDU June-2025 (1).pdf';
             $filePath = 'C:/Users/Venba/Desktop/ins stmts/UIIC GR June-2025.pdf';
             $filePath = 'C:/Users/Venba/Desktop/ins stmts/UIIC VLR June-2025 (2).xlsx';
-            $filePath = 'C:/Users/Venba/Desktop/ins stmts/pdf/2.pdf';
-            $filePath = 'C:\Users\Venba\Downloads\Raheja June-2025.csv';
+            $filePath = 'C:/Users/Venba/Desktop/ins stmts/pdf/1.pdf';
+            $filePath = 'C:/Users/Venba/Desktop/ins stmts/output.csv';
+            // $filePath = 'C:\Users\Venba\Downloads\Raheja June-2025.csv';
             // $filePath = 'C:/Users/Venba/Downloads/Raheja June-2025.pdf';
             // $filePath = 'C:/Users/Venba/Desktop/ins stmts/ICICI Pru June-2025 (1).xlsx';
             // $filePath = 'C:/Users/Venba/Desktop/ins stmts/Digit Life June-2025.xlsx';
@@ -102,7 +103,7 @@ class Home extends PublicController
             $base64Content = base64_encode($fileContent);
             // The prompt you want to send to the model
             $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
-            $prompt = "Read the following insurer monthly statement file and convert into JSON format as sample specified.attach statement items in 'items' key and if any other data available put it in 'meta'. Give me only JSON,not any explanations. If you find the same details like insured name, policy number,endorsement no,policy start date,policy end date group it as single policy and identify base premium, third party premium and terrorism premium.";
+            $prompt = "Read the following insurer monthly statement file and convert into JSON format as sample specified.attach statement items in 'items' key and if any other data available put it in 'meta'. Give me only JSON,not any explanations. If you find the same details like insured name, policy number,endorsement no,policy start date,policy end date group it as single policy and identify base premium, third party premium and terrorism premium.All brokerage amount may in the same name as brokerage or commission, so pick accordingly";
             $prompt .= "{\'items\': [{\'sno\': 1, \'policy_no\': \'\', \'insured_name\': \'\', \'endorsement_no\': \'\', \'policy_start_date\': \'\', \'policy_end_date\': \'\', \'actual_base_premium_amount\': \'\', \'actual_third_party_premium_amount\': \'\', \'actual_terrorism_premium_amount\': \'\', \'actual_base_premium_percentage\': \'\', \'actual_third_party_premium_percentage\': \'\', \'actual_terrorism_premium_percentage\': \'\', \'actual_bp_brokerage_amount\': \'\', \'actual_tp_brokerage_amount\': \'\', \'actual_tep_brokerage_amount\': \'\', \'reward_amount\': \'\'}]}";
 
             $payloadPart = null;
@@ -270,6 +271,7 @@ public function convertToPdf($inputFile = null)
     {
         // 1. Load your Excel file
         $inputFile = 'C:/Users/Venba/Desktop/ins stmts/Raheja June-2025.xlsx';
+        $inputFile = 'C:/Users/Venba/Desktop/ins stmts/ICICI Lom June-2025.xlsx';
         // $inputFile = 'C:/Users/Venba/Desktop/ins stmts/pdf/sample.pdf';
         $spreadsheet = IOFactory::load($inputFile);
         
@@ -293,7 +295,7 @@ public function convertToPdf($inputFile = null)
             $mpdf->AddPage();
             $mpdf->WriteHTML($html);
         }
-        $pdfPath = 'C:/Users/Venba/Desktop/ins stmts/pdf/2.pdf';
+        $pdfPath = 'C:/Users/Venba/Desktop/ins stmts/pdf/1.pdf';
         // $pdfPath = WRITEPATH.'tmp';
         $mpdf->Output($pdfPath, \Mpdf\Output\Destination::FILE); // Save file on server
         // 4. Output
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 9838492c..60d3b955 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1894,6 +1894,8 @@ class MasterController extends AdminController
             'cache' => WRITEPATH . 'cache',
             'sample_import_excel' => ROOTPATH . 'public/sample_import_excel',
             'lead_files' => WRITEPATH . 'uploads/lead_files/',
+            'claim_files' => WRITEPATH . 'uploads/claim_files/',
+            'claim_dump_excel' => WRITEPATH . 'uploads/claim_dump_excel/',
             'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/',
         ];
 
diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php
index efdc2571..b497e958 100755
--- a/app/Controllers/NotificationController.php
+++ b/app/Controllers/NotificationController.php
@@ -87,6 +87,8 @@ class NotificationController extends AdminController
             'client_hr_summary_mail_btn'
         ];
         $data = [];
+        $emptyTemplate = [];
+        $updatedTemplate = [];
 
         foreach ($checkboxNames as $checkboxName) 
         {
@@ -111,9 +113,31 @@ class NotificationController extends AdminController
                 $id = $find['id'];
                 $changeData['enabled']= $value;
                 $update = $notificationModel->update($id, $changeData);
+                $updatedTemplate [] = $key;
+            }
+            
+            if(!$find && $value == 1){
+                $emptyTemplate [] = $key;
             }
         }
-        return json_encode("true");
+
+        if(count($emptyTemplate) > 0){
+            return $this->response->setJSON([
+            'status' => false,
+            'code' => 400,
+            'message' => 'Notification settings updation Failed.',
+            'updated_templates' => $updatedTemplate,
+            'empty_templates'   => $emptyTemplate
+        ]);
+        }
+
+        return $this->response->setJSON([
+            'status' => true,
+            'code' => 200,
+            'message' => 'Notification settings updated successfully.',
+            'updated_templates' => $updatedTemplate,
+            'empty_templates'   => $emptyTemplate
+        ]);
     }
 
     // This for Load the Template Data for in View Page  
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
index cada5a8f..2b9afb78 100644
--- a/app/Controllers/PolicyTransactionController.php
+++ b/app/Controllers/PolicyTransactionController.php
@@ -383,7 +383,12 @@ class PolicyTransactionController extends BaseController
             }
 
             $client_data = $this->clientModel->where('id', $data['client_id'])->first();
-            $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
+            $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
+            
+            $clientController = new ClientController();
+            $data['client_kyc_primary_table']  =  $clientController->generateKycPrimaryTable($data['client_id']);
+            $data['client_kyc_other_table']  =  $clientController->generateKycOthersTable($data['client_id']);
+
             $data['entity_type_id'] =  $client_data['entity_type_id'];
 
             return $this->respondSuccess($insert, "Policy transaction created successfully", $data);
@@ -433,6 +438,11 @@ class PolicyTransactionController extends BaseController
 
             $client_data = $this->clientModel->where('id', $data['client_id'])->first();
             $data['client_kyc']       = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
+            
+            $clientController = new ClientController();
+            $data['client_kyc_primary_table']  =  $clientController->generateKycPrimaryTable($data['client_id']);
+            $data['client_kyc_other_table']  =  $clientController->generateKycOthersTable($data['client_id']);
+
             $data['entity_type_id'] =  $client_data['entity_type_id'];
 
             return $this->respondSuccess($id, "Policy transaction updated successfully", $data);
@@ -977,7 +987,12 @@ class PolicyTransactionController extends BaseController
             ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
             ->where('employees.client_id', $data['client_id'])
             ->where('employees.is_active', 1)->findAll();
-        $data['client_kyc']   = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
+        // $data['client_kyc']   = $this->clientKYCDocsModel->where('client_id',  $data['client_id'])->findAll();
+
+        $clientController = new ClientController();
+        $data['client_kyc_primary_table']  =  $clientController->generateKycPrimaryTable($data['client_id']);
+        $data['client_kyc_other_table']  =  $clientController->generateKycOthersTable($data['client_id']);
+
         $data['vehicle_docs'] = $this->clientKYCDocsModel
             ->where('client_id',  $data['client_id'])
             ->where('vehicle_id', $data['vehicle_id'])
diff --git a/app/Controllers/TestingController.php b/app/Controllers/TestingController.php
index 8fe06352..d866cb7f 100644
--- a/app/Controllers/TestingController.php
+++ b/app/Controllers/TestingController.php
@@ -3,12 +3,21 @@
 namespace App\Controllers;
 
 use App\Controllers\BaseController;
+use App\Models\EmployeePolicyModel;
 use CodeIgniter\HTTP\ResponseInterface;
 use CodeIgniter\API\ResponseTrait;
+use Dompdf\Dompdf;
+use Dompdf\Options;
 
 class TestingController extends BaseController
 {
     use ResponseTrait;
+    protected $myLogger;
+
+    public function __construct()
+    {
+        $this->myLogger = \Config\Services::mylogger();
+    }
     
     public function saveForm()
     {
@@ -22,4 +31,209 @@ class TestingController extends BaseController
             'data' => $data
         ]);
     }
+
+    public function testcli()
+    {   
+        echo "hi";
+        $this->myLogger->logme('error', "test log");
+        echo "hi 2";
+        log_message('error', 'test message for log_message_function');
+        echo "hi 3";
+    }
+
+
+    public function generatePDF()
+    {
+        // Sample data - replace with your actual data source
+        $data = [
+            'NAME' => 'John Doe',
+            'GENDER' => 'Male',
+            'DOB' => '01/01/1990',
+            'RELATION' => 'Self',
+            'POLICY_NO' => 'POL123456789',
+            'TPA_ID' => 'TPA987654321',
+            'POLICY_START_DATE' => '01/01/2024',
+            'POLICY_DATE' => '31/12/2024',
+            'INSURER_NAME' => 'ABC Insurance Co.',
+            'TPA_NAME' => 'XYZ TPA Ltd.',
+            'FRONT_CARD' => base_url('assets/images/front-card.jpg'), // Your card images
+            'BACK_CARD' => base_url('assets/images/back-card.jpg'),
+            'LEVELS' => 'Level 1: 1800-XXX-XXXX
Level 2: support@company.com' + ]; + + // Load the HTML template + $html = $this->loadTemplate($data); + + // Configure DomPDF options + $options = new Options(); + $options->set('isRemoteEnabled', true); // Enable loading of remote images + $options->set('isHtml5ParserEnabled', true); + $options->set('isPhpEnabled', true); + $options->set('debugPng', false); + $options->set('debugKeepTemp', false); + $options->set('debugCss', false); + $options->set('debugLayout', false); + $options->set('debugLayoutLines', false); + $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 + } + + public function viewPDF() + { + // Same as generatePDF but with inline view + $data = [ + 'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari', + 'GENDER' => 'Male', + 'DOB' => '01/01/1990', + 'RELATION' => 'Self', + 'POLICY_NO' => '97000034230400000109_EX_Parental', + 'TPA_ID' => 'TPA987654321', + 'POLICY_START_DATE' => '01/01/2024', + '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'), + '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' + ]; + + $data2 = [ + 'NAME' => 'John Doe', + 'GENDER' => 'Male', + 'DOB' => '01/01/1990', + 'RELATION' => 'Self', + 'POLICY_NO' => 'POL123456789', + 'TPA_ID' => 'TPA987654321', + 'POLICY_START_DATE' => '01/01/2024', + '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'), + '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' + ]; + + $employeeController = new EmployeeController(); + // $html = $employeeController->generateIDCardForEmployeeUsingDom('LfpH3R'); + $html = $this->loadTemplate($data2); + // print_r($html); die; + $options = new Options(); + $options->set('isRemoteEnabled', true); + $options->set('isHtml5ParserEnabled', true); + + $dompdf = new Dompdf($options); + // $dompdf->loadHtml($html); + $dompdf->loadHtml('' . $html); + $dompdf->setPaper('A4', 'portrait'); + // $dompdf->setPaper('A4', 'landscape'); + $dompdf->render(); + + $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf'; + // $dompdf->stream($filename, ['Attachment' => true]); // Inline view + $dompdf->stream($filename, ['Attachment' => false]); // Force download + + } + + private function loadTemplate($data) + { + // 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; + } + + // not using and not working + public function viewPdfUsingMpdf() + { + $data = [ + 'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari', + 'GENDER' => 'Male', + 'DOB' => '01/01/1990', + 'RELATION' => 'Self', + 'POLICY_NO' => '97000034230400000109_EX_Parental', + 'TPA_ID' => 'TPA987654321', + 'POLICY_START_DATE' => '01/01/2024', + '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'), + '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' + ]; + + $html = $this->loadTemplate($data); + + // Load mPDF + $mpdf = ""; + + // $mpdf = new \Mpdf\Mpdf([ + // 'mode' => 'utf-8', + // 'format' => 'A4', + // 'margin_left' => 0, + // 'margin_right' => 0, + // 'margin_top' => 0, + // 'margin_bottom' => 0, + // 'tempDir' => __DIR__ . '/writable/mpdf' + // ]); + + // Optional: Stretch background or images fully + // $html = ' + // ' . $html; + + // $mpdf->WriteHTML($html); + + // // Output inline (no download prompt) + // $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf'; + // $mpdf->Output($filename, 'D'); + /* + 'I' = inline view in browser (no download prompt). + 'D' = force download. + 'F' = save to file. + 'S' = return as string. + */ + } + + public function getEmployeePolicyTypes($client_id, $emp_code, $emp_id) + { + $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(); + + } } diff --git a/app/Controllers/ThzController.php b/app/Controllers/ThzController.php index 645b3ea6..0dea90c1 100644 --- a/app/Controllers/ThzController.php +++ b/app/Controllers/ThzController.php @@ -15,6 +15,7 @@ use App\Models\UserModel; use App\Models\ClientPolicyModel; use App\Models\ClientModel; use App\Models\TicketMailTemplateModel; +use App\Models\ClientRMModel; class ThzController extends BaseController @@ -31,6 +32,8 @@ class ThzController extends BaseController protected $clientModel; protected $ticketMailTemplateModel; + + protected $cientRmModel; protected $myLogger; public function __construct() @@ -43,6 +46,7 @@ class ThzController extends BaseController $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(); } @@ -52,170 +56,181 @@ class ThzController extends BaseController // } - public function ticketSave(){ - try - { - $data = $this->request->getPost(); + public function ticketSave() + { + try { + $data = $this->request->getPost(); + $references = ""; + if (!empty($data['thz_id'])) { - 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); - $text = "update"; - $result = $this->updateTicket($data); - // here insert history Status. - $old = $this->thzMasterModel->where('thz_id', $data['thz_id'])->get()->getRowArray(); - - if ($old && isset($data['status'])) { - 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 ($old && isset($data['status'])) { - if (!empty(get_session_userid())) { - $history['created_by'] = get_session_userid(); - } + 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 + ]; - $this->thzHistoryModel->insert($history); + if (!empty(get_session_userid())) { + $history['created_by'] = get_session_userid(); + } + + $hist_id = $this->thzHistoryModel->insert($history); + $references = $old['status'] . " - " . $data['status'] . " - " . $hist_id; + } else { + $references = $old['status'] . " - " . $data['status']; + } + } else { + $references = "No Details"; } + + $updateID = $data['thz_id']; + } else { + + $text = "create"; + $insertID = $this->insertTicket($data); + $result = true; + $references = ""; } - - $updateID = $data['thz_id']; - } else { + $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID; - $text = "create"; - $insertID = $this->insertTicket($data); - $result = true; + $emailNotificationResult = $this->ticketSaveNotification($data, $insertOrUpdate = $text, $id); - } - - $id = isset($insertID) && !empty($insertID) ? $insertID : $updateID ; - - $emailNotificationResult = $this->ticketSaveNotification($data , $insertOrUpdate = $text , $id); - - return $this->response->setJSON([ + 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..!!' - ])->setStatusCode($result ? 200 : 400); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + '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) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); } } - + public function ticketList() { - try{ - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - - - $data = $this->request->getGet(); - if ($returnType === 'web' && in_array(get_role_id(), [2,3,4])) { - $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); - } + try { + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - $tickets = $this->fetchTicketsBasedOnrole($data); - - if ($returnType === 'api') { - if (empty($tickets)) { - // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); - throw new \RuntimeException('No tickets found', 400); + $data = $this->request->getGet(); + if ($returnType === 'web' && in_array(get_role_id(), [2, 3, 4])) { + $data['assign_to'] = $data['assign_to'] ?? get_session_userid(); } - }else{ - - $data['page_name'] = "Tickets"; - $data['ticket_data'] = $tickets; - $data['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. - $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) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + $tickets = $this->fetchTicketsBasedOnrole($data); - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + if ($returnType === 'api') { + if (empty($tickets)) { + // return $this->response->setJSON([ 'status' => 'error','message' => 'No tickets found'])->setStatusCode(404); + throw new \RuntimeException('No tickets found', 400); + } + } else { - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); - } + $data['page_name'] = "Tickets"; + $data['ticket_data'] = $tickets; + $data['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. + $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) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } } - public function ticketConversationSave(){ + public function ticketConversationSave() + { - try { + try { $data = $this->request->getPost(); - $data['notes_type'] = $data['notes_type'] ?? 'External' ; + $data['notes_type'] = $data['notes_type'] ?? 'External'; $result = $this->thzMasterNotesModel->insert($data); - if(empty($result)){ + if (empty($result)) { // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(404); - throw new \RuntimeException('No tickets found', 404); + throw new \RuntimeException('No tickets found', 404); } - if($data['notes_type'] == "External"){ + if ($data['notes_type'] == "External") { $emailNotificationResult = $this->ticketConversationSaveNotification($data); - }else{ - $emailNotificationResult = false ; + } else { + $emailNotificationResult = false; } - - - return $this->response->setJSON([ + + + return $this->response->setJSON([ 'status' => $result ? 'success' : 'error', - 'message' => $result ? "Ticket Notes created successfully" : "Unable to create ticket notes. Please try again." , + '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) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + ])->setStatusCode($result ? 200 : 400); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); } } @@ -246,190 +261,193 @@ class ThzController extends BaseController } return $this->response->setJSON(['status' => 'success', 'data' => $result])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - } - catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); } } public function ticketConversationList() { - $data = $this->request->getGet(); + $data = $this->request->getGet(); - $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); + $returnType = strtolower($this->request->getGet('return_type') ?? 'api'); - $thz_id = $data['thz_id'] ?? null; - - $ticketType = $data['notes_type'] ?? 'External' ; + $thz_id = $data['thz_id'] ?? null; - if($thz_id){ - $result['master'] = $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->where('thz_master.thz_id', $thz_id) - ->findAll(); + $ticketType = $data['notes_type'] ?? 'External'; - if(!empty($result['master'])){ - $notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType ); - $result['notes'] = !empty($notes) ? $notes : []; - }else{ - // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); - 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 ($thz_id) { + $result['master'] = $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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 { + // return $this->response->setJSON((['status' => 'error', 'message' => 'No tickets found']))->setStatusCode(400); + 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) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + if ($returnType === 'api') { + try { + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); - } - }else{ + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - $assign_to = $result['master'][0]['assign_to']; - $mobile = $result['master'][0]['mobile']; + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } else { - $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') - ? $result['master'][0]['policy_id'] - : ''; + $assign_to = $result['master'][0]['assign_to']; + $mobile = $result['master'][0]['mobile']; - $result['related_tickets'] = $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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) : ''; + $toGetPolicyId = (!empty($result['master'][0]['policy_id']) && strtolower($result['master'][0]['policy_id']) !== 'null') + ? $result['master'][0]['policy_id'] + : ''; - $result['ticket_type'] = $this->thzTypeModel->where('is_active', 1)->findAll(); - - return $this->loadLayout('thz_notes', $result); - - } + $result['related_tickets'] = $this->thzMasterModel + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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') { + try { + if ($method === 'get') { $types = $this->thzTypeModel->select('id,name,is_active')->where('is_active', 1)->findAll(); if (empty($types)) { - return $this->response->setJSON(['status' => 'error','message' => 'No ticket types found'])->setStatusCode(404); + return $this->response->setJSON(['status' => 'error', 'message' => 'No ticket types found'])->setStatusCode(404); } - return $this->response->setJSON(['status' => 'success','data' => $types])->setStatusCode(200); - } - + return $this->response->setJSON(['status' => 'success', 'data' => $types])->setStatusCode(200); + } + if ($method === 'post') { - + $data = $this->request->getPost(); if (!empty($data['id'])) { - $text = "update"; + $text = "update"; $result = $this->thzTypeModel->update($data['id'], $data); $updateID = $data['id']; } else { - $text = "create"; + $text = "create"; $insertID = $this->thzTypeModel->insert($data); $result = true; } $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); - return $this->response->setJSON([ + 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) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + return $this->response->setJSON(['status' => 'error', 'message' => 'Invalid request method'])->setStatusCode(405); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database' : 'application' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); - } + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } } 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.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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(); + 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.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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)) { // return $this->response->setJSON([ 'status' => 'error','message' => 'No History found'])->setStatusCode(404); throw new \RuntimeException('No History found', 404); } - - return $this->response->setJSON(['status' => 'success','data' => $details])->setStatusCode(200); - } catch (\Throwable $e) { - $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException - || $e instanceof \mysqli_sql_exception - || $e instanceof \PDOException; + return $this->response->setJSON(['status' => 'success', 'data' => $details])->setStatusCode(200); + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; - $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; - $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); - - return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), - 'ref' => $isDbError ? 'database / ' : 'application / ' . $code . ' / ' . $e->getLine() - ])->setStatusCode($code); + $context = ['title' => get_class($e), 'type' => get_class($e), 'code' => $code, 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); } } @@ -446,70 +464,73 @@ class ThzController extends BaseController if (!empty($assign_to)) { // Tickets assigned to a staff return $this->thzMasterModel - ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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(); + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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(); + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_name) as assignee_name') - ->join('user_profiles', 'user_profiles.id = thz_master.assign_to', 'left') - ->orderBy('thz_master.created_at','desc') - ->findAll(); + ->select('thz_master.*, CONCAT(user_profiles.first_name, " ", user_profiles.last_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){ - + 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 + 'assignee_email' => $assignee_email ]; $ticketId = $id; - $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified , $insertOrUpdate , $ticketId , $data); - - return $result; + $result = $this->ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id); + return $result; } - private function ticketConversationSaveNotification($data){ + private function ticketConversationSaveNotification($data) + { - $thz_id = $data['thz_id'] ; // thz is alias of ticket + $thz_id = $data['thz_id']; // thz is alias of ticket $data['subject'] = $this->findSubject($data['thz_id']); - $assignee_id = $this->findAssigneeId($data['thz_id']) ; + $assignee_id = $this->findAssigneeId($data['thz_id']); + + $user_email = $this->findUserEmail($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 ; + $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"; @@ -519,40 +540,43 @@ class ThzController extends BaseController $message = $data['notes'] ?? ''; - $this->sendEmail( $templateName, $data , $to_email , $ticketId , $message); + $this->sendEmail($templateName, $data, $to_email, $ticketId, $message); return true; - } - private function findAssigneeEmail($assignee_id){ + private function findAssigneeEmail($assignee_id) + { $row = $this->userModel->where('id', $assignee_id)->get()->getRow(); $assigneeEmail = $row ? $row->email : null; - return $assigneeEmail ? $assigneeEmail : ""; - + return $assigneeEmail ? $assigneeEmail : ""; } - private function findAssigneeId($ticketId){ + private function findAssigneeId($ticketId) + { $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); $assigneeId = $row ? $row->assign_to : null; - return $assigneeId ? $assigneeId : 0 ; + return $assigneeId ? $assigneeId : 0; } - private function findUserEmail($ticket_id){ + private function findUserEmail($ticket_id) + { $row = $this->thzMasterModel->where('thz_id', $ticket_id)->get()->getRow(); $email = $row ? $row->email : null; - return $email ? $email : " " ; + return $email ? $email : " "; } - private function findSubject($ticketId){ + private function findSubject($ticketId) + { $row = $this->thzMasterModel->where('thz_id', $ticketId)->get()->getRow(); $subject = $row ? $row->subject : null; - return $subject ? $subject : " " ; + return $subject ? $subject : " "; } - private function ticketSaveEmailNotificationBasedOnRole($emailToNotified , $insertOrUpdate , $ticketId , $data){ + private function ticketSaveEmailNotificationBasedOnRole($emailToNotified, $insertOrUpdate, $ticketId, $data, $client_id) + { $user_email = $emailToNotified['user_email'] ?? null; $assignee_email = $emailToNotified['assignee_email'] ?? null; @@ -564,21 +588,20 @@ class ThzController extends BaseController case 'update': - $this->sendEmail( 'ticket_save_update_assignee', $data ,$assignee_email , $ticketId ) ; + $this->sendEmail('ticket_save_update_assignee', $data, $assignee_email, $ticketId); break; - + case 'create': - $this->sendEmail( 'ticket_save_create_assignee', $data ,$assignee_email , $ticketId ) ; - + $this->sendEmail('ticket_save_create_assignee', $data, $assignee_email, $ticketId); + break; - + default: # code... break; } - } if (!empty($user_email)) { @@ -587,47 +610,55 @@ class ThzController extends BaseController case 'update': - if(empty($assignee_email)){ - $data['assigneeAndStatus'] = "Not Yet Assigned"; - $this->sendEmail( 'ticket_save_update_user', $data ,$user_email , $ticketId ) ; - }else{ - $data['assigneeAndStatus'] = "Assigned With {$assignee_email}"; - $this->sendEmail( 'ticket_save_update_user', $data ,$user_email , $ticketId ) ; - } + $data['assigneeAndStatus'] = empty($assignee_email) + ? "Not Yet Assigned" + : "Assigned With {$assignee_email}"; + + $this->sendEmail('ticket_save_update_user', $data, $user_email, $ticketId); + + + break; - break; - case 'create': - if(empty($assignee_email)){ - $this->sendEmail( 'ticket_save_create_user_unassigned', $data ,$user_email , $ticketId ) ; - }else{ - $data['assignee_email'] = $assignee_email ; - $this->sendEmail( 'ticket_save_create_user_assigned', $data , $user_email , $ticketId ) ; + $account_manager_email = $this->cientRmModel->findAccountManagerEmail($client_id); + + $cc = getenv(' G_ticketing_system_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->sendEmail($template, $data, $account_manager_email, $ticketId, $cc); + } + break; - + default: # code... break; } - } return true; - - } - private function updateTicket($data){ + 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) @@ -639,12 +670,13 @@ class ThzController extends BaseController } - private function sendEmail( $templateName, $data , $to_email , $ticketId , $message = ""){ - - $mailTemplate = $this->ticketMailTemplateModel->where('template_name',$templateName )->findAll()[0] ?? []; + private function sendEmail($templateName, $data, $to_email, $ticketId , $cc = "", $message = "", $bcc = "") + { - if(empty($mailTemplate)){ - return ; + $mailTemplate = $this->ticketMailTemplateModel->where('template_name', $templateName)->findAll()[0] ?? []; + + if (empty($mailTemplate)) { + return; } $mailTemplate['subject'] = str_replace('%subject%', $data['subject'] ?? '', $mailTemplate['subject']); @@ -657,39 +689,35 @@ class ThzController extends BaseController $mailTemplate['mail_content'] = str_replace('%assignee_email%', $data['assignee_email'] ?? '', $mailTemplate['mail_content']); - $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%',$data['assigneeAndStatus'] ?? '' ,$mailTemplate['mail_content']); + $mailTemplate['mail_content'] = str_replace('%assigneeAndStatus%', $data['assigneeAndStatus'] ?? '', $mailTemplate['mail_content']); $from_mail = ""; $to_mail = $to_email; - $cc_string = ""; - $subject = $mailTemplate['subject'] ; - $message = $mailTemplate['mail_content'] ; + $cc_string = $cc; + $subject = $mailTemplate['subject']; + $message = $mailTemplate['mail_content']; $attachments = ""; $reply_to = ""; - $bcc_string = ""; - - $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]); + $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]); } 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); + $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); } - - } - diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 0fe8752b..5d930c71 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -22,6 +22,8 @@ use App\Models\EmployeeModel; use App\Models\TPAModel; use App\Models\ClaimFilesModel; use App\Models\ClaimDumpFileModel; +use App\Models\VehicleModel; +use App\Models\PartnerPolicyModel; use DOMDocument; use Psr\Log\LoggerInterface; @@ -62,6 +64,8 @@ class TicketController extends BaseController protected $TPAModel; protected $claimFilesModel; protected $claimDumpFileModel; + protected $vehicleModel; + protected $partnerPolicyModel; public function __construct() { @@ -71,7 +75,7 @@ class TicketController extends BaseController $this->ticketMasterModel = new TicketMasterModel(); - $this->ticketType = [1 => "Claim-GMC", 2 => "Claim-GPA", 3 => "EDLI", 4 => "GTLI"]; + $this->ticketType = [1 => "Claim-GMC", 2 => "Claim-GPA", 3 => "EDLI", 4 => "GTLI", 8 => "Motor"]; $this->priorityType = [ 1 => "Low", 2 => "Medium", @@ -348,6 +352,8 @@ class TicketController extends BaseController $this->TPAModel = new TPAModel(); $this->claimFilesModel = new ClaimFilesModel(); $this->claimDumpFileModel = new ClaimDumpFileModel(); + $this->vehicleModel = new VehicleModel(); + $this->partnerPolicyModel = new PartnerPolicyModel(); } public function ticketList() @@ -684,6 +690,9 @@ class TicketController extends BaseController case 4: $data['ticket_form'] = 'GTLI'; break; + case 8: + $data['ticket_form'] = 'Motor'; + break; } // Fetch ACM Users @@ -704,7 +713,10 @@ class TicketController extends BaseController $claim_status_id = 25; }else if($ticket_type == 4){ $claim_status_id = 35; - }else{ + }else if($ticket_type == 8){ + $claim_status_id = 62; + } + else{ $claim_status_id = 1; } } @@ -719,11 +731,79 @@ class TicketController extends BaseController $data['claim_type'] = $this->claimType[2]; } + $data['client_for_motor'] = $this->clientModel->select('id,client_name,phone')->where('client_type', 2)->where('is_active', 1)->findAll(); + $this->myLogger->logme('error', "Ticket form data fetched successfully for Ticket Type: $ticket_type"); return $data; } + public function fetchVehiclePolicy($id) + { + $method = $this->request->getMethod(); + + try { + if (!$id) { + throw new \Exception('Invalid ID', 400); + } + + if ($method === 'get') { + $data['vehicle_list'] = $this->vehicleModel + ->where('is_active', 1) + ->where('owner', $id) + ->findAll(); + + // $data['partner_policy_list'] = $this->partnerPolicyModel + // ->where('is_active', 1) + // ->findAll(); + $data['partner_policy_list'] = $this->partnerPolicyModel->partnerPolicyList(); + + $client = $this->clientModel + ->where('is_active', 1) + ->where('id', $id) + ->first(); + + $data['email'] = !empty($client) ? $client['email'] : null; + $data['phone'] = !empty($client) ? $client['phone'] : null; + + if (empty($data['vehicle_list']) && empty($data['partner_policy_list'])) { + throw new \Exception('No Records found', 404); + } + + return $this->response + ->setJSON(['status' => 'success', 'data' => $data]) + ->setStatusCode(200); + } + + throw new \Exception('Invalid request method', 405); + + } catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = [ + 'title' => get_class($e), + 'type' => get_class($e), + 'code' => $code, + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine() + ]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ + 'status' => 'error', + 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => ($isDbError ? 'database - ' : 'application - ') . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + //transform the claim status public function transFormClaimStatus($claimStatusId, $ticket_type) { @@ -792,9 +872,10 @@ class TicketController extends BaseController } public function view_ticket($ticket_id) - { + { // $ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first(); $ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id); + $ticket_data = $this->formatDateForClaim($ticket_data, 'd/m/Y'); if (in_array($ticket_data['claim_status_id'], [15, 25, 35])) { @@ -853,6 +934,14 @@ class TicketController extends BaseController // print_rr($data); die; } + // 8TH TYPE is Motor - so do not remove it.... + if($ticket_data['ticket_type_id'] == 8){ + $claim_status_id = $ticket_data['claim_status_id']; + $ticket_type = $ticket_data['ticket_type_id']; + $data['claim_status'] = $this->transFormClaimStatus($claim_status_id, $ticket_type); + $data['client_for_motor'] = $this->clientModel->select('id,client_name,phone')->where('client_type', 2)->where('is_active', 1)->findAll(); + } + return $this->loadLayout('ticket_edit_onbording', $data); } @@ -1157,13 +1246,23 @@ class TicketController extends BaseController ->orderBy('ticket_messages.created_at', 'DESC') ->findAll(); - foreach ($dataToSend['messages'] as $message) { + foreach ($dataToSend['messages'] as &$message) { $mail_content_converted = $this->convertHtmlToText($message['mail_content']); $message['mail_content'] = $mail_content_converted; + + $claimFiles = new ClaimFilesModel(); + $message["files_data"] = $claimFiles->where('is_active', 1) + ->where('file_type', 2)->where('ticket_id', $ticket_master_id) + ->where('ticket_message_id', $message['id']) + ->findAll(); + } + unset($message); + $dataToSend['emp_name'] = $this->ticketMasterModel->select('emp_name') ->where('id', $ticket_master_id)->where('is_active', 1) ->first()['emp_name']; + // dd($dataToSend); if ($dataToSend) { return $dataToSend; @@ -1173,6 +1272,38 @@ class TicketController extends BaseController } } + public function downloadClaimFile($claim_file_id = null) + { + // $actionType = $this->request->getGet(); + $claimFiles = new ClaimFilesModel(); + $file_data = $claimFiles->where('id', $claim_file_id)->first(); + $fileName = $file_data['doc_name']; + + $filePath = WRITEPATH . '/uploads/claim_files/' . $fileName; + + try { + + // Check if the file exists + if (file_exists($filePath)) { + // Set the appropriate MIME type + $mimeType = mime_content_type($filePath); + + // Send the file to the client for download + return $this->response->download($filePath, null, $mimeType); + } else { + + $data['message'] = 'The Physical File Not Found'; + echo view('errors/404', $data); + } + } catch (\Exception $e) { + // Handle any exceptions + $errorMessage = $e->getMessage(); + $this->myLogger->logme('error', $errorMessage); + // You can return an error response here + echo $errorMessage; + } + } + public function convertHtmlToText($html) { if(!empty($html)){ @@ -2198,7 +2329,8 @@ class TicketController extends BaseController 'url' => $data['url'][$key]??'', 'ticket_id'=> $data['ticket_id_url']??'', 'created_by' => get_session_userid(), - 'is_active' => 1 + 'is_active' => 1, + 'file_type' => 1 ]; $insertArr[] = $insertData; @@ -2235,6 +2367,7 @@ class TicketController extends BaseController $urlData = $this->claimFilesModel ->where('ticket_id', $ticket_id) ->where('is_active',1) + ->where('file_type',1) ->findAll(); return $this->response->setJSON([ diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 78d3a6c0..255b6507 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -18,6 +18,8 @@ use App\Models\UserTeamsModel; use App\Helpers\BookStackUserHelper; use App\Models\AuthHistoryModel; use App\Models\UserActivityHistoryModel; +use App\Models\PartnerStaffModel; +use App\Models\PartnerManagerIncentiveFileModel; class UserController extends AdminController @@ -32,6 +34,8 @@ class UserController extends AdminController protected $bookStack; protected $authHistoryModel; protected $userActivityHistoryModel; + protected $partnerStaffModel; + protected $partnerManagerIncentiveFileModel; public function __construct() { @@ -45,6 +49,8 @@ class UserController extends AdminController $this->bookStack = new BookStackUserHelper(); $this->authHistoryModel = new AuthHistoryModel(); $this->userActivityHistoryModel = new UserActivityHistoryModel(); + $this->partnerStaffModel = new PartnerStaffModel(); + $this->partnerManagerIncentiveFileModel = new PartnerManagerIncentiveFileModel(); } public function list() @@ -563,4 +569,226 @@ class UserController extends AdminController } } + public function partner() + { + $method = $this->request->getMethod(); // get, post + try{ + // Listing + if ($method === 'get') { + $types = $this->partnerStaffModel->findAll(); + if (empty($types)) { + return $this->response->setJSON(['status' => 'error','message' => 'No Staff found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success','data' => $types])->setStatusCode(200); + } + + // add/update + if ($method === 'post') { + + $data = $this->request->getPost(); + if (!empty($data['id'])) { + $text = "update"; + $result = $this->partnerStaffModel->update($data['id'], $data); + $updateID = $data['id']; + } else { + $text = "create"; + $data['role_id'] = 1; + $data['created_by'] = get_session_userid(); + $insertID = $this->partnerStaffModel->insert($data); + $result = true; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); + + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "Staff {$text}d successfully" : "Unable to {$text} staff. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + + // delete + if ($method === 'put') { + $data = $this->request->getRawInput(); + $id = $data['id'] ?? null; + + if (!$id) { + return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400); + } + + $staff = $this->partnerStaffModel->find($id); + if (!$staff) { + return $this->response->setJSON(['status' => 'error','message' => 'Staff not found'])->setStatusCode(404); + } + + if ($staff['is_active'] == 1) { + $result = $this->partnerStaffModel->update($id, ['is_active' => 0]); + $message = "Staff deleted successfully"; + } else { + return $this->response->setJSON(['status' => 'error','message' => 'Staff already deleted'])->setStatusCode(400); + } + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? $message : "Unable to delete staff. Please try again.", + 'id' => $id + ])->setStatusCode($result ? 200 : 400); + } + return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request method' ])->setStatusCode(405); + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function partnerIncentive() + { + $method = $this->request->getMethod(); // get, post + try{ + // Listing + if ($method === 'get') { + $manager_id = $this->request->getGet('manager_id'); + $files = $this->partnerManagerIncentiveFileModel->where('manager_id', $manager_id)->findAll(); + if (empty($files)) { + return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404); + } + return $this->response->setJSON(['status' => 'success','data' => $files])->setStatusCode(200); + } + + // add/update + if ($method === 'post') { + + $file = $this->request->getFile('incentive_file_name'); + $month = $this->request->getPost('incentive_month'); + $managerId = $this->request->getPost('manager_id'); + $fileId = $this->request->getPost('id'); + + if ($file && $file->isValid() && !$file->hasMoved()) { + + $originalName = $file->getClientName(); + $extension = $file->getExtension(); + + $fileName = pathinfo($originalName, PATHINFO_FILENAME) . '_' . date('Ymd_His') . '.' . $extension; + + $path = WRITEPATH . 'uploads/incentives'; + $file->move($path, $fileName); + $data = [ + 'manager_id' => $managerId, + 'incentive_month' => date('M Y', strtotime($month)), + 'incentive_file_name' => $fileName, + 'created_by' => get_session_userid() + ]; + + if ($fileId) { + $text = "update"; + $this->partnerManagerIncentiveFileModel->update($fileId, $data); + $updateID = $data['id']; + } else { + $text = "create"; + $insertID = $this->partnerManagerIncentiveFileModel->insert($data); + $result = true; + } + + $id = isset($insertID) && !empty($insertID) ? $insertID : ($updateID ?? null); + + return $this->response->setJSON([ + 'status' => $id ? 'success' : 'error', + 'message' => $id ? "File {$text}d successfully" : "Unable to {$text} file. Please try again.", + 'id' => $id + ])->setStatusCode($id ? 200 : 400); + } + return $this->response->setJSON([ + 'status' => 'error', + 'message' => "Unable to Upload file. Please try again.", + 'id' => '' + ])->setStatusCode(400); + } + + // delete + if ($method === 'put') { + $data = $this->request->getRawInput(); + $id = $data['id'] ?? null; + + if (!$id) { + return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400); + } + + $files = $this->partnerManagerIncentiveFileModel->find($id); + if (!$files) { + return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404); + } + + if ($files['is_active'] == 1) { + $result = $this->partnerManagerIncentiveFileModel->update($id, ['is_active' => 0]); + $message = "Files deleted successfully"; + } else { + return $this->response->setJSON(['status' => 'error','message' => 'files already deleted'])->setStatusCode(400); + } + + return $this->response->setJSON([ + 'status' => $result ? 'success' : 'error', + 'message' => $result ? $message : "Unable to delete staff. Please try again.", + 'id' => $id + ])->setStatusCode($result ? 200 : 400); + } + return $this->response->setJSON([ 'status' => 'error', 'message' => 'Invalid request method' ])->setStatusCode(405); + } + catch (\Throwable $e) { + $code = ($e->getCode() && $e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500; + + $isDbError = $e instanceof \CodeIgniter\Database\Exceptions\DatabaseException + || $e instanceof \mysqli_sql_exception + || $e instanceof \PDOException; + + $context = ['title' => get_class($e),'type' => get_class($e),'code' => $code,'message' => $e->getMessage(),'file' => $e->getFile(),'line' => $e->getLine()]; + + $this->myLogger->logme('error', "Exception: {message} in {file} on line {line}", $context, 0); + + return $this->response->setJSON([ 'status' => 'error', 'message' => $isDbError ? 'Data Access Error' : $e->getMessage(), + 'ref' => $isDbError ? 'database - ' : 'application - ' . $code . ' - ' . $e->getLine() + ])->setStatusCode($code); + } + } + + public function downloadIncentivesFile($file_id) + { + try { + $result = $this->partnerManagerIncentiveFileModel->where('id', $file_id)->first(); + + if (!$result || empty($result['incentive_file_name'])) { + throw new \Exception("File Name Not Found"); + } + + $incentive_file_name = $result['incentive_file_name']; + $file_name = basename($incentive_file_name); + $filePath = WRITEPATH . 'uploads/incentives/' . $file_name; + + if (file_exists($filePath)) { + return $this->response->download($filePath, null); + } else { + throw new \Exception("File Not Found"); + } + + } catch (\Exception $e) { + + $this->myLogger->logme('error', $e->getMessage()); + + // Show 404 error view + $data['message'] = $e->getMessage(); + return view('errors/404', $data); + } + } + } \ No newline at end of file diff --git a/app/Helpers/ChatbotHelper.php b/app/Helpers/ChatbotHelper.php index b17161c2..db0e2e3e 100644 --- a/app/Helpers/ChatbotHelper.php +++ b/app/Helpers/ChatbotHelper.php @@ -30,16 +30,16 @@ class ChatbotHelper $emp_code = $chat_session_info['emp_code']; $client_id = $chat_session_info['client_id']; $client_branch_id = $chat_session_info['client_branch_id']; - // $relationship ='Father'; + $relationship ='Self'; $EmployeeModel = new EmployeeModel(); - return $EmployeeModel->getEmpFamilybyEmpCode(emp_code: $emp_code,client_id: $client_id,emp_status: ['draft'],policy_status:['draft'],client_branch_id:[ $client_branch_id ]);//,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]);//,relationship:[$relationship]; } - public static function getHospitalLink($client_policy_id){ + public static function getHospitalLink($emp_policy_id){ // $client_policy_id = 336; // $emp_id = 12288; $EmployeePolicyModel = new EmployeePolicyModel(); - $res = $EmployeePolicyModel->getHospitalLinkByPolicyandEmp($client_policy_id); + $res = $EmployeePolicyModel->getHospitalLinkByPolicyandEmp($emp_policy_id); return is_array($res) && count($res) ? $res[0]['network_hospitals'] : null; } @@ -64,16 +64,18 @@ class ChatbotHelper { $message = SELF::ReimbursementProcessMailTemplate(); - $attachments = [ - ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], - ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], - ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] - ]; + // $attachments = [ + // ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], + // ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], + // ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] + // ]; $common = ['mail_type'=>'reimbursement_mail_process_bot']; $email_id = $data['email_corporate']; - $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments,'common'=>$common]); + // $email_id = 'vitvelz@gmail.com'; + // $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Claim Reimbursement Process', 'message' => $message,'attachments' => $attachments,'common'=>$common]); + $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Claim Reimbursement Process', 'message' => $message,'common'=>$common]); $res = json_decode($res); if($res->status == 'success') @@ -166,7 +168,7 @@ class ChatbotHelper
  1. Gather Documents: Collect all required documents such as bills, invoices, and medical reports.
  2. -
  3. Complete the Claim Form: Fill out the insurance claim form accurately.
  4. +
  5. Complete the Claim Form: Fill out the insurance claim form in the portal.
  6. Attach Supporting Documents: Attach all necessary documents to support your claim.
  7. Submit Your Claim: Send the completed form and documents via email or through our online portal.
  8. Track Your Claim: Use our tracking system to monitor the status of your claim.
  9. @@ -174,12 +176,10 @@ class ChatbotHelper
- Submit Your Claim -

If you have any questions, feel free to contact our support team.

@@ -202,7 +202,8 @@ class ChatbotHelper $common = ['mail_type'=>'request_quotation_bot']; $email_id = getenv('email.enquiryMail'); - $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Quotation Request Received from bot.', 'message' => $message,'common'=>$common]); + // $res = MailHelper::send_email(['mail' => $email_id, 'bcc' => 'vitvelz@gmail.com','subject' => '(TESTING)Quotation Request Received from bot.', 'message' => $message,'common'=>$common]); + $res = MailHelper::send_email(['mail' => $email_id,'subject' => 'Quotation Request Received from bot.', 'message' => $message,'common'=>$common]); $res = json_decode($res); log_message('error','res: '.json_encode($res)); @@ -218,7 +219,7 @@ class ChatbotHelper } public static function quotationRequestMailTemplate($data){ - $message = 'A customer has requested for a quotation using bot,Here are all the details for it: + $message = 'A customer has requested for a quotation using bot,Here are all the details for it:
'.$data; return $message; } @@ -266,7 +267,8 @@ class ChatbotHelper $mail_content = Self::ReimbursementStatusMailTemplate($data['emp_name'],$data['claim_number'],$matched_key); $common = ['mail_type'=>'Claim Status']; $email_id = $data['emp_mail']; - $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Here is your claim status you requested in bot.', 'message' => $mail_content,'common'=>$common]); + // $email_id = 'vitvelz@gmail.com'; + $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Claim status as you requested in bot.', 'message' => $mail_content,'common'=>$common]); $res = json_decode($res); log_message('error','res: '.json_encode($res)); diff --git a/app/Helpers/header.php b/app/Helpers/header.php index fb9e215c..f696e91b 100755 --- a/app/Helpers/header.php +++ b/app/Helpers/header.php @@ -73,7 +73,7 @@ body[data-sidebar-size=condensed]:not([data-layout=compact]):not(.auth-fluid-pages) { - min-height: 0; + max-height:100vh !important; } .navbar-custom { diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php index eae819ea..c03ffcc9 100755 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -64,6 +64,79 @@ if (!function_exists('file_Upload')) { } } +// if (!function_exists('multi_file_Upload')) { +// function multi_file_Upload($fileToUpload, $filepath) +// { +// $uploadedFiles = []; + +// // Handle multiple files +// if (is_array($fileToUpload)) { +// foreach ($fileToUpload as $file) { +// if ($file !== null && $file->isValid() && !$file->hasMoved()) { +// $file->move($filepath); +// $fileName = $file->getName(); // safer unique name +// $uploadedFiles[] = [ +// 'file_name' => $fileName, +// 'file_path' => $filepath . $fileName +// ]; +// } +// } +// } +// // Handle single file +// else { +// if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { +// $fileToUpload->move($filepath); +// $fileName = $fileToUpload->getName(); +// $uploadedFiles[] = [ +// 'file_name' => $fileName, +// 'file_path' => $filepath . $fileName +// ]; +// } +// } + +// return $uploadedFiles; // always return array of files +// } +// } + +if (!function_exists('multi_file_Upload')) { + function multi_file_Upload($fileToUpload, $filepath) + { + $uploadedFiles = []; + + // Normalize: always work with an array of UploadedFile objects + $files = is_array($fileToUpload) ? $fileToUpload : [$fileToUpload]; + + foreach ($files as $file) { + // If file is itself an array (multiple under same input name) + if (is_array($file)) { + foreach ($file as $f) { + if ($f !== null && $f->isValid() && !$f->hasMoved()) { + $fileName = $f->getRandomName(); // safer unique name + $f->move($filepath, $fileName); + $uploadedFiles[] = [ + 'file_name' => $fileName, + 'file_path' => $filepath . $fileName + ]; + } + } + } else { + // Single file + if ($file !== null && $file->isValid() && !$file->hasMoved()) { + $fileName = $file->getRandomName(); + $file->move($filepath, $fileName); + $uploadedFiles[] = [ + 'file_name' => $fileName, + 'file_path' => $filepath . $fileName + ]; + } + } + } + + return $uploadedFiles; // always return array + } +} + + if (!function_exists('file_unlink')) { function file_unlink($filepath) { diff --git a/app/Models/ClaimFilesModel.php b/app/Models/ClaimFilesModel.php index 2a5ec138..8e22ae01 100644 --- a/app/Models/ClaimFilesModel.php +++ b/app/Models/ClaimFilesModel.php @@ -11,6 +11,8 @@ class ClaimFilesModel extends Model protected $allowedFields = [ 'id', 'ticket_id', + 'ticket_message_id', + 'file_type', 'doc_name', 'url', 'created_by', diff --git a/app/Models/ClientRMModel.php b/app/Models/ClientRMModel.php index 799649e5..ee02782c 100755 --- a/app/Models/ClientRMModel.php +++ b/app/Models/ClientRMModel.php @@ -21,22 +21,38 @@ class ClientRMModel extends Model public function checkExistenceOfClientRelation($id, $user_id, $level) { $query = $this->where('client_id', $id) - ->where('user_id', $user_id) - ->where('level', $level) - ->countAllResults(); + ->where('user_id', $user_id) + ->where('level', $level) + ->countAllResults(); return ($query > 0) ? true : false; } - public function getAllClientRM(){ + public function getAllClientRM() + { return $this->db->table('client_rm') - ->select('client_rm.client_id, client_rm.level,') - ->select('user_profiles.first_name as account_manager') - ->join('user_profiles', 'user_profiles.id = client_rm.user_id') - ->where('level', 3) - ->get() - ->getResult(); - + ->select('client_rm.client_id, client_rm.level,') + ->select('user_profiles.first_name as account_manager') + ->join('user_profiles', 'user_profiles.id = client_rm.user_id') + ->where('level', 3) + ->get() + ->getResult(); } + public function findAccountManagerEmail($client_id) + { + $builder = $this->db->table('client_rm'); + $builder->select('user_profiles.email'); + $builder->join('user_profiles', 'user_profiles.id = client_rm.user_id'); + $builder->where('client_rm.client_id', $client_id); + $builder->where('client_rm.level', 3); // Assuming level 3 is for account managers + $result = $builder->get()->getResultArray(); + + if (count($result) > 0) { + // Extract just the email values into a simple string array + return array_column($result, 'email'); + } else { + return null; // or [] + } + } } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 82a8cb3b..bf34881a 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -2089,11 +2089,15 @@ class EmployeePolicyModel extends Model return $result[0]; } - public function getHospitalLinkByPolicyandEmp($client_policy_id){ - $data = $this->db->table('client_policy') + public function getHospitalLinkByPolicyandEmp($emp_policy_id){ + $data = $this->db->table('employee_polices') ->select('tpa.network_hospitals') - ->where('client_policy.id', $client_policy_id) + ->where('employee_polices.id', $emp_policy_id) + ->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + // ->where('client_policy.id', $client_policy_id) // ->where('employee_polices.is_active', 1) + ->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1') ->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1') // ->join('employees', 'employees.id = employee_polices.employee_id AND employees.id = ' . (int) $emp_id) ->get()->getResultArray(); diff --git a/app/Models/PartnerEndorsementRequestModel.php b/app/Models/PartnerEndorsementRequestModel.php new file mode 100755 index 00000000..083c832d --- /dev/null +++ b/app/Models/PartnerEndorsementRequestModel.php @@ -0,0 +1,89 @@ +db->table('partner_endorsement_request per') + ->distinct() + ->select(' + per.id, + per.client_id, + per.client_policy_id, + per.insurer_id, + per.insurer_branch_id, + per.policy_number, + per.endorsement_no, + per.endorsement_type, + per.endorsement_description, + per.created_at, + per.updated_by, + per.updated_at, + per.is_active, + per.created_by, + per.manager_id, + per.agent_id, + per.status, + i.name as insurer_name, + i.short_name as insurer_short_name, + c.client_name, + c.short_name as client_short_name, + ps.name as manager_name, + pa.name as agent_name + ') + ->join('insurers as i', 'i.id = per.insurer_id', 'left') + ->join('clients as c', 'c.id = per.client_id AND c.client_type = 2', 'left') + ->join('partner_staff as ps', 'ps.id = per.manager_id AND ps.role_id = 1', 'left') + ->join('partner_agent as pa', 'pa.id = per.agent_id', 'left'); + + if (!empty($status)) { + $query->where('per.status', $status); + } + if (!empty($client_id)) { + $query->where('per.client_id', $client_id); + } + if (!empty($insurers_id)) { + $query->where('per.insurer_id', $insurers_id); + } + + $query->orderBy('per.id', 'desc'); + + return $query->get()->getResultArray(); + } + +} diff --git a/app/Models/PartnerManagerIncentiveFileModel.php b/app/Models/PartnerManagerIncentiveFileModel.php new file mode 100755 index 00000000..32e59444 --- /dev/null +++ b/app/Models/PartnerManagerIncentiveFileModel.php @@ -0,0 +1,56 @@ + 'required|integer', + // 'incentive_month' => 'required|valid_date', + // 'incentive_file_name'=> 'required|string|max_length[150]', + // ]; + + // protected $validationMessages = [ + // 'manager_id' => [ + // 'required' => 'Manager ID is required', + // 'integer' => 'Manager ID must be a number', + // ], + // 'incentive_month' => [ + // 'required' => 'Incentive Month is required', + // 'valid_date' => 'Incentive Month must be a valid date (Y-m-d)', + // ], + // 'incentive_file_name' => [ + // 'required' => 'File name is required', + // 'max_length' => 'File name cannot exceed 150 characters', + // ], + // ]; + + // protected $skipValidation = false; +} diff --git a/app/Models/PartnerPolicyModel.php b/app/Models/PartnerPolicyModel.php new file mode 100755 index 00000000..71d1550f --- /dev/null +++ b/app/Models/PartnerPolicyModel.php @@ -0,0 +1,72 @@ +db->table('partner_policy as pp') + ->select(' + pp.id, + pp.id as partner_policy_id, + pp.enquiry_id, + pp.insured_name, + pp.policy_number, + pp.agent_id, + pp.manager_id, + pp.client_id, + pp.client_policy_id, + pp.is_active as partner_policy_is_active, + pe.insurer_id, + pe.is_active as partner_enquiry_is_active, + i.name as insurer_name, + i.short_name as insurer_short_name, + i.is_active as insurer_is_active + ') + ->join('partner_enquiry as pe', 'pe.id = pp.enquiry_id', 'left') + ->join('insurers as i', 'i.id = pe.insurer_id', 'left') + ->where('pp.is_active', 1) + ->get() + ->getResultArray(); + } + // $data['partner_policy_list'] = $this->partnerPolicyModel + // ->where('is_active', 1) + // ->findAll(); +} diff --git a/app/Models/PartnerStaffModel.php b/app/Models/PartnerStaffModel.php new file mode 100755 index 00000000..474f14d1 --- /dev/null +++ b/app/Models/PartnerStaffModel.php @@ -0,0 +1,50 @@ + 'required|min_length[2]|max_length[150]', + // 'email' => 'permit_empty|valid_email|max_length[150]', + // 'mobile' => 'permit_empty|regex_match[/^[0-9]{10,20}$/]', + // ]; + + // protected $validationMessages = [ + // 'name' => [ + // 'required' => 'Name is required', + // 'min_length' => 'Name must have at least 2 characters', + // 'max_length' => 'Name cannot exceed 150 characters' + // ], + // 'email' => [ + // 'valid_email' => 'Please provide a valid email address', + // 'max_length' => 'Email cannot exceed 150 characters' + // ], + // 'mobile' => [ + // 'regex_match' => 'Mobile number must be 10–20 digits only' + // ] + // ]; + + // protected $skipValidation = false; +} diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index ab733a4b..05196827 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -79,7 +79,10 @@ class TicketMasterModel extends Model 'approved_description', 'file_id', 'denial_letter', - + + 'manager_id', + 'agent_id' , + 'vehicle_id', ]; @@ -788,13 +791,13 @@ class TicketMasterModel extends Model } //api - public function get_ticket_data($emp_id, $ticket_type = null, $ticket_id = null) + public function get_ticket_data($emp_id, $returnType,$ticket_type = null, $ticket_id = null) { - $query = $this->select('ticket_master.*, tms.mail_subject as subject') + $query = $this->select('ticket_master.*, tms.mail_subject as subject, tms.id as ticket_message_id') ->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left') - ->where('ticket_master.is_active', 1) - ->where('tms.sender', "user") - ->where('ticket_master.emp_id', $emp_id); + ->where('ticket_master.is_active', 1); + $query->whereIn('sender', ['staff', 'user']); + $query->where('ticket_master.emp_id', $emp_id); if (!empty($ticket_id)) { $query->where('ticket_master.id', $ticket_id); @@ -804,8 +807,10 @@ class TicketMasterModel extends Model $query->where('ticket_master.ticket_type_id', $ticket_type); } + $query->groupBy('ticket_master.id'); $data = $query->findAll(); - // dd($data, db_connect()->getLastQuery()); + // dd($data, db_connect()->getLastQuery()); + // print_r($this->db->getLastQuery());die; return $data; } diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php index 4aa74f18..6acad55b 100755 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -167,28 +167,10 @@ } } - .navtab-bg .nav-link { - margin: 0 5px 10px!important; - } - - .nav-link{ - color:black !important; - background-color: #D4F5F6 !important; - font-size: small; - padding:8px; - border-radius: 10px !important; - } - .nav-link.active-tab { - color: white !important; - background-color: #00999E !important; - font-size: small; - padding:8px; - border-radius: 10px !important; - - } - .tab-content-styles{ + #client_add .tab-content-styles{ background-color:#F4F4F4; margin-right:20px; + margin-top:0px !important; border-radius:25px!important; min-height: 70vh !important; } @@ -200,7 +182,7 @@ -

Dashboard

+

Dashboard

@@ -208,8 +190,6 @@
- -
-
+
diff --git a/app/Views/UserList.php b/app/Views/UserList.php index d9d73f2a..544b544b 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -42,6 +42,17 @@ table.dataTable tbody td { padding: 20px; } + #mobile::placeholder, + #mobile_no::placeholder { + font-size: 13px; + } + + .custom-select{ + border-radius: 10px !important ; + background-color: #ECECEC !important ; + box-shadow: 0px 2px 4px 0px #00000024 !important; + } + .multiselect-native-select { position: relative; } @@ -236,20 +247,113 @@ table.dataTable tbody td { border:1px solid rgba(41, 139, 142, 1); } + .dt-buttons.btn-group{ + display: grid; + grid-template-columns: 1fr .4fr .5fr .2fr; + } + + #user-table_filter input{ width:100%; } + + button.dt-button, + button.dt-button:focus, + button.dt-button:active, + button.dt-button:hover { + background: none !important; + border: none !important; + box-shadow: none !important; + padding: 0 !important; + margin: 0 !important; + } + + + /* main button wrapper */ + .tab-button { + width: 201px; + height: 37px; + border-radius: 10px !important; + font-weight: 700; + font-size: 14px; + line-height: 100%; + border: 1px solid #BAF1F3; + background: #F5FFFF; + cursor: pointer; + transition: all 0.2s ease-in-out; + display: flex; + justify-content: center; + align-items: center; + gap: 6px; + } + + /* divider style */ + .divider-line { + color: #DBDBDB; + font-weight: 400; + } + + /* active state */ + .highlight-link.active { + color: #00999E; + } + + /* inactive state */ + .highlight-link:not(.active) { + color: #707070; + } + + .no-files-message { + width: 900px; + height: 300px; + background: #ECECEC; + opacity: 1; + + display: flex; + align-items: center; + justify-content: center; + + font-weight: 500; /* Medium */ + font-size: 18px; + line-height: 100%; + letter-spacing: 0; + color: #333; /* Adjust text color if needed */ + text-align: center; + + border-radius: 8px; /* optional for smooth edges */ + margin: 13px; /* center horizontally */ + } + + #container { + max-height: 400px; /* set fixed height */ + overflow-y: auto; /* enable vertical scroll */ + overflow-x: hidden; /* prevent horizontal scroll */ + } + + + .file-icon-box { + /* width: 40px; + height: 50px; + display: flex; + align-items: center; + justify-content: center; */ + border-radius: 10px; + background: #F4F6F8; + border: 1px solid #ddd; /* matches border-width:1px */ + padding: 3px; + } +
-
+
-

User List

+

Users

- +
@@ -268,7 +372,7 @@ table.dataTable tbody td { @@ -286,6 +390,67 @@ table.dataTable tbody td {
Namemobile; ?> user_role; ?> - + is_active == 1){ echo 'Active'; }else{ echo 'In-Active'; } ?>
+ +
@@ -297,8 +462,9 @@ table.dataTable tbody td { -