diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 77b01b3d..ee9ad2c0 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -30,6 +30,8 @@ $routes->get("updateRemainderDate", "ClientController::updateRemainderDate"); $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); $routes->get("sendextraparam", "ClientController::sendextraparam"); $routes->get("updateRenewalData", "ClientController::updateRenewalData"); +$routes->get("updateRenewalDataNotExistingClient", "ClientController::updateRenewalDataNotExistingClient"); +$routes->get("updateRenewalInsurerData", "ClientController::updateRenewalInsurerData"); // $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn"); // $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail"); // $routes->post("employeeUpload", "EmployeeRestController::employeeUpload"); @@ -49,7 +51,7 @@ $routes->get('/auth/google', 'LoginController::initiateGoogleOAuth'); $routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus'); $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->group("/user", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "UserController::create"); @@ -161,6 +163,7 @@ $routes->group("/employee", ["filter" => "authMVC"], function ($routes) { $routes->get("test-rack-rate", "EmployeeController::testRackRate"); $routes->post("test-rack-rate", "EmployeeController::testRackRate"); $routes->get('test_members_list', 'EmployeeController::test_members_list'); + $routes->post('get_emp_history','EmployeeController::getEmpHistory'); }); $routes->group("/master", ["filter" => "authMVC"], function ($routes) { @@ -387,21 +390,21 @@ $routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { $routes->group("leads", ["filter" => "authMVC"], function ($routes) { - $routes->get("list", "LeadsController::viewLeadsList"); + $routes->match(['get', 'post'],"list", "LeadsController::viewLeadsList"); $routes->post("create", "LeadsController::createLead"); $routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1"); $routes->get("sendMail", "LeadsController::sendMailWithAttachement"); $routes->post("sendMail", "LeadsController::sendMailWithAttachement"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); $routes->get("featchLeadDataAndInsertClient/(:any)", "LeadsController::featchLeadDataAndInsertClient/$1"); - $routes->get("featchClientPolicyFromLead/(:any)", "LeadsController::featchClientPolicyFromLead/$1"); - + $routes->get("featchClientPolicyFromLead/(:any)", "LeadsController::featchClientPolicyFromLead/$1"); }); $routes->group("rfq", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "LeadsController::createRFQ"); $routes->post("createQCR", "LeadsController::createQCR"); $routes->get("list/(:any)", "LeadsController::viewRFQ/$1"); + $routes->get("nonEB","LeadsController::rfqNonEB"); }); @@ -440,13 +443,19 @@ $routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController:: // Test initiate Claim $routes->post('initiateClaim',"EmployeeRestController::initiateClaim"); +$routes->get('departments',"EmployeeRestController::get_ticket_type"); +$routes->get('get_ticket_data',"EmployeeRestController::get_ticket_data"); + +//api $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $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->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy"); $routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { @@ -522,6 +531,8 @@ $routes->group("/ticket", ["filter" => "authMVC"], function ($routes) { $routes->post('note/(:any)','TicketController::crudNote/$1'); $routes->post('reply','TicketController::saveReply'); $routes->match( ['get', 'post'], 'ticket_reports','TicketController::ticketReports'); + $routes->post('getPolicyStartDate','TicketController::getPolicyStartDate'); + $routes->post("getPoliciesbyEmpID","TicketController::getPoliciesbyEmpID"); // $routes->post('ticket_messages','TicketController::getTicketMessage'); }); diff --git a/app/Controllers/BDSReportController.php b/app/Controllers/BDSReportController.php index 67634315..54abf46f 100644 --- a/app/Controllers/BDSReportController.php +++ b/app/Controllers/BDSReportController.php @@ -91,7 +91,7 @@ class BDSReportController extends AdminController ins.id, ins.name AS insurers, COALESCE(SUM(CASE WHEN pt.action_type = 'inception' AND pt.insurer_id = ins.id AND ptp.policy_category = $insurerCategory THEN 1 ELSE 0 END), 0) AS Policies, - COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium, + COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium, COALESCE(SUM(CASE WHEN stmt.co_share_id = pt_co.id AND ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN stmt.reward + stmt.actual_bp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.actual_tp_brokerage_amt ELSE 0 END), 0) AS Revenue, COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN pt_co.exp_amt ELSE 0 END), 0) AS Expected_amt FROM @@ -131,7 +131,7 @@ class BDSReportController extends AdminController SELECT pot.bap AS bap, COALESCE(COUNT(DISTINCT pt.id), 0) AS Policies, - COALESCE(SUM((pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt)), 0) AS Premium, + COALESCE(SUM((pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt)), 0) AS Premium, COALESCE(SUM(co.reward + co.actual_bp_brokerage_amt + co.actual_tep_brokerage_amt + co.actual_tp_brokerage_amt), 0) AS Revenue, COALESCE(SUM(pt_co.exp_amt), 0) AS Expected_amt FROM policy_type AS pot @@ -267,26 +267,26 @@ class BDSReportController extends AdminController -- Health Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Health' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS health_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS health_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS health_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS health_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN pt_co.exp_amt ELSE 0 END), 0) AS health_exp_amt, -- Misc Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS misc_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS misc_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS misc_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS misc_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN pt_co.exp_amt ELSE 0 END), 0) AS misc_exp_amt, -- Motor Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS motor_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS motor_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS motor_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS motor_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN pt_co.exp_amt ELSE 0 END), 0) AS motor_exp_amt, -- Engineering Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS engineering_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS engineering_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS engineering_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS engineering_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN pt_co.exp_amt ELSE 0 END), 0) AS engineering_exp_amt, @@ -294,35 +294,35 @@ class BDSReportController extends AdminController -- Fire Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS fire_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS fire_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS fire_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS fire_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN pt_co.exp_amt ELSE 0 END), 0) AS fire_exp_amt, -- Liability Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS liability_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS liability_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS liability_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS liability_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN pt_co.exp_amt ELSE 0 END), 0) AS liability_exp_amt, -- Life Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Life' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS life_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS life_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS life_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS life_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN pt_co.exp_amt ELSE 0 END), 0) AS life_exp_amt, -- Marine Cargo Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS marine_cargo_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_cargo_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_cargo_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS marine_cargoe_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN pt_co.exp_amt ELSE 0 END), 0) AS marine_cargo_exp_amt, -- Marine Hull Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS marine_hull_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_hull_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_hull_premium, COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN stmt.actual_bp_brokerage_amt + stmt.actual_tp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.reward ELSE 0 END), 0) AS marine_hull_revenue, COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN pt_co.exp_amt ELSE 0 END), 0) AS marine_hull_exp_amt, @@ -341,15 +341,15 @@ class BDSReportController extends AdminController ) AS total_policy_count, COALESCE( - SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + - SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END)+ - SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END)+ - SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), + SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END) + + SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END)+ + SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END)+ + SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0 ) AS total_premium, @@ -429,43 +429,43 @@ class BDSReportController extends AdminController -- Health Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Health' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS health_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS health_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Health' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS health_premium, -- Misc Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS misc_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS misc_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Misc' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS misc_premium, -- Motor Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS motor_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS motor_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Motor' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS motor_premium, -- Engineering Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS engineering_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS engineering_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Engineering' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS engineering_premium, -- Fire Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS fire_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS fire_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Fire' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS fire_premium, -- Liability Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS liability_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS liability_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Liability' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS liability_premium, -- Life Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Life' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS life_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS life_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Life' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS life_premium, -- Marine Cargo Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS marine_cargo_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_cargo_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Cargo' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_cargo_premium, -- Marine Hull Policies COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' AND pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS marine_hull_policy_count, - COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_hull_premium, + COALESCE(SUM(CASE WHEN ptp.bap = 'Marine Hull' THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS marine_hull_premium, -- Grand Totals COALESCE(SUM(CASE WHEN pt.action_type = 'inception' THEN 1 ELSE 0 END), 0) AS total_policy_count, - COALESCE(SUM(pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt), 0) AS total_premium + COALESCE(SUM(pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt), 0) AS total_premium FROM clients c LEFT JOIN policy_transaction pt ON pt.client_id = c.id AND pt.is_active = 1 AND pt.policy_issue_date >= '$fromDate' AND pt.policy_issue_date <= '$toDate' @@ -542,7 +542,7 @@ class BDSReportController extends AdminController COALESCE(( select - sum(pt_co.bp_amt + pt_co.tp_amt + pt_co.tep_amt + pt_co.non_comm_per_amt) as premium + sum(pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) as premium from co_share_stmt_details stmt left join pt_co_share_details pt_co on stmt.co_share_id = pt_co.id left join policy_transaction pt on pt_co.pt_id = pt.id diff --git a/app/Controllers/Chatbot/BotService.php b/app/Controllers/Chatbot/BotService.php deleted file mode 100644 index ee3b57ad..00000000 --- a/app/Controllers/Chatbot/BotService.php +++ /dev/null @@ -1,110 +0,0 @@ -reply('Welcome! Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Card Download'], - ['Network Hospital'], - ['Reimbursement Claim Process'], - ['Reimbursement Claim Status'], - ['New Policy'], - ['Renew Policy'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleCardDownload(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Download Card'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleNetworkHospital(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Find Hospital'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleReimbursementClaimProcess(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Submit Claim'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleReimbursementClaimStatus(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Check Status'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleNewPolicy(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Get Quote'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } - - public static function handleRenewPolicy(BotMan $bot) - { - $bot->reply('Please choose an option:', [ - 'reply_markup' => json_encode([ - 'keyboard' => [ - ['Renew Now'], - ['Go Back'] - ], - 'resize_keyboard' => true, - 'one_time_keyboard' => true - ]) - ]); - } -} \ No newline at end of file diff --git a/app/Controllers/Chatbot/ClaimHandler.php b/app/Controllers/Chatbot/ClaimHandler.php deleted file mode 100644 index b1839734..00000000 --- a/app/Controllers/Chatbot/ClaimHandler.php +++ /dev/null @@ -1,34 +0,0 @@ - "Reimbursement Claim Process: Here is a dummy response.", - 'reimbursement_claim_status' => "Reimbursement Claim Status: Here is a dummy response." - ]; - - if (isset($responses[$option])) { - $bot->reply($responses[$option]); - } else { - $bot->reply("Unknown claim option."); - } - - // Send Back Button - self::sendBackButton($bot); - } - - private static function sendBackButton(BotMan $bot) - { - $bot->reply(ButtonTemplate::create("Would you like to return?") - ->addButton(ElementButton::create("Go Back")->type('postback')->payload("main_menu")) - ); - } -} diff --git a/app/Controllers/Chatbot/LoginToContiueConversation.php b/app/Controllers/Chatbot/LoginToContiueConversation.php new file mode 100644 index 00000000..74a28a6c --- /dev/null +++ b/app/Controllers/Chatbot/LoginToContiueConversation.php @@ -0,0 +1,26 @@ +bot->userStorage()->delete(); + $this->bot->types(); // Typing indicator for the first message + sleep(0.5); // Delay + $this->showLoginMessage(); + } + + protected function showLoginMessage() + { + $this->say("Kindly Login to use the chatbot"); + } +} diff --git a/app/Controllers/Chatbot/PolicyHandler.php b/app/Controllers/Chatbot/PolicyHandler.php deleted file mode 100644 index 9491ef9d..00000000 --- a/app/Controllers/Chatbot/PolicyHandler.php +++ /dev/null @@ -1,36 +0,0 @@ - "Ecard Download: Here is a dummy response.", - 'network_hospital' => "Network Hospital: Here is a dummy response.", - 'new_policy' => "New Policy: Here is a dummy response.", - 'renew_policy' => "Renew Policy: Here is a dummy response." - ]; - - if (isset($responses[$option])) { - $bot->reply($responses[$option]); - } else { - $bot->reply("Unknown policy option."); - } - - // Send Back Button - self::sendBackButton($bot); - } - - private static function sendBackButton(BotMan $bot) - { - $bot->reply(ButtonTemplate::create("Would you like to return?") - ->addButton(ElementButton::create("Go Back")->type('postback')->payload("main_menu")) - ); - } -} diff --git a/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php b/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php index db8831bc..fd6e3337 100644 --- a/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php +++ b/app/Controllers/Chatbot/ReimbursementClaimStatusConversation.php @@ -27,7 +27,7 @@ class ReimbursementClaimStatusConversation extends Conversation $this->bot->types(); if ($data){ - $this->say("The claim status for the claim Number {$data['claim_number']} is currently in {$data['claim_status']} status.
More Detailed Information is sent to your mail"); + $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"); $this->bot->startConversation(new doYouWantToContinueConversation()); }else{ $this->say("No Claim Raised against the user."); diff --git a/app/Controllers/Chatbot/TypingMiddleware.php b/app/Controllers/Chatbot/TypingMiddleware.php deleted file mode 100644 index 047d246b..00000000 --- a/app/Controllers/Chatbot/TypingMiddleware.php +++ /dev/null @@ -1,27 +0,0 @@ -myLogger = \Config\Services::mylogger(); - $this->myLogger->logme('error', 'MIDDLEWARE'); - - // Simulate typing indicator - $bot->types(); - sleep(0.1); // Cap delay at 5 seconds (convert to microseconds) - // Proceed to the next middleware or response - return $next($bot); - } -} diff --git a/app/Controllers/Chatbot/medicalClaimFormConversations.php b/app/Controllers/Chatbot/medicalClaimFormConversations.php index d0d21e7e..da6bf3c5 100644 --- a/app/Controllers/Chatbot/medicalClaimFormConversations.php +++ b/app/Controllers/Chatbot/medicalClaimFormConversations.php @@ -246,7 +246,8 @@ class medicalClaimFormConversations extends Conversation $question = Question::create("Confirm all details:") ->addButtons([ Button::create("✅ Confirm")->value("confirm"), - Button::create("❌ Start Over")->value("restart"), + Button::create("🔁 Start Over")->value("restart"), + Button::create("❌ Cancel")->value('cancel') ]); $this->ask($question, function ($answer) use ($finalSummary) { @@ -271,6 +272,9 @@ class medicalClaimFormConversations extends Conversation ]); $this->run(); break; + case "cancel": + $this->bot->startConversation(new MainMenuConversation()); + break; default: $this->say("Invalid selection. Please choose an option."); $this->showSummary(); diff --git a/app/Controllers/Chatbot/vehicleFormConversation.php b/app/Controllers/Chatbot/vehicleFormConversation.php index 1595ae52..3bcf39fd 100644 --- a/app/Controllers/Chatbot/vehicleFormConversation.php +++ b/app/Controllers/Chatbot/vehicleFormConversation.php @@ -180,7 +180,8 @@ class vehicleFormConversation extends Conversation $question = Question::create("Confim your Details:") ->addButtons([ Button::create("✅ Confirm")->value("confirm"), - Button::create("❌ No")->value("no"), + Button::create("🔁 Start Over")->value("restart"), + Button::create("❌ Cancel")->value('cancel') ]); $this->bot->ask($question, function ($answer) use($vehicle_info) { $path = $this->bot->userStorage()->get('path'); @@ -201,8 +202,12 @@ class vehicleFormConversation extends Conversation $this->say("There was a problem while requesting for a quotation please try again later."); } break; - case "no": - $this->askVehicleName(); + case "restart": + $this->bot->startConversation(new vehicleFormConversation()); + break; + case "cancel": + $this->say("Redirecting you to main menu..."); + $this->bot->startConversation(new MainMenuConversation()); break; default: $this->say("Invalid selection. Please choose an option."); diff --git a/app/Controllers/ChatbotControllerNew.php b/app/Controllers/ChatbotControllerNew.php index 9fc9be36..610f2bda 100644 --- a/app/Controllers/ChatbotControllerNew.php +++ b/app/Controllers/ChatbotControllerNew.php @@ -2,6 +2,7 @@ namespace App\Controllers; +use App\Controllers\Chatbot\LoginToContiueConversation; use BotMan\BotMan\BotMan; use BotMan\BotMan\BotManFactory; use BotMan\BotMan\Drivers\DriverManager; @@ -19,6 +20,7 @@ class ChatbotControllerNew extends BaseController protected $myLogger; protected $session; protected $botman; + protected $isMemberLoggedIn; public function __construct() { @@ -90,6 +92,12 @@ class ChatbotControllerNew extends BaseController // $this->myLogger->logme('error', ('TEST' . $id)); $this->session->set('CHATBOT_RANDOM_USER_ID', $id); } + + $this->isMemberLoggedIn = false; + $chat_session_info = get_chatbot_session_info(); + if (!empty($chat_session_info['emp_id']) && !empty($chat_session_info['emp_code'] )){ + $this->isMemberLoggedIn = true; + } $this->botman->hears('.*', function ($bot) { @@ -98,8 +106,13 @@ class ChatbotControllerNew extends BaseController }); // Start the Main Menu when user says "hi" or "start" $this->botman->hears('start|hi|hello', function (BotMan $bot) { - $bot->reply('Hi how can i assit?'); - $bot->startConversation(new MainMenuConversation()); + if ($this->isMemberLoggedIn){ + $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 d7a06cf5..fffbcbd8 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -187,23 +187,28 @@ class ClientController extends AdminController } //Function for Testing Member Review and Summery Confirmation Mail - public function testingForReviewMail($client_id = 77, $emp_code = 'EMP001-K1', $mail_active = 0) //this function for only tsesting some logics not use for business logic + public function testingForReviewMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0) //this function for only tsesting some logics not use for business logic { - // dd($client_id, $emp_code, $mail_active); + // dd($client_id, $emp_code, $policy_id, $mail_active); - $client_policy_ids = $this->employeeModel - ->select('employee_polices.client_policy_id') - ->join('employee_polices', 'employees.id = employee_polices.employee_id') - ->where('employees.client_id', $client_id ) - ->where('employees.emp_code', $emp_code ) - ->where('employee_polices.is_active', 1 ) - ->where('employees.is_active', 1 ) - ->findAll(); + if(empty($policy_id)){ - $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id'); + $client_policy_ids = $this->employeeModel + ->select('employee_polices.client_policy_id') + ->join('employee_polices', 'employees.id = employee_polices.employee_id') + ->where('employees.client_id', $client_id ) + ->where('employees.emp_code', $emp_code ) + ->where('employee_polices.is_active', 1 ) + ->where('employees.is_active', 1 ) + ->findAll(); - $client_policy_id = array_unique($client_policy_ids2); + $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id'); + $client_policy_id = array_unique($client_policy_ids2); + + }else{ + $client_policy_id = json_decode($policy_id, true); + } // echo '
';
         // dd($client_policy_id);
@@ -259,7 +264,7 @@ class ClientController extends AdminController
                 $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
                 // print_r($wholeData); die;
 
-                if($mail_active > 0){
+                if($mail_active == 1){
                     $mail_send_return =  MailHelper::send_email($wholeData[0]);
                     $this->myLogger->logme("info", $mail_send_return);
                 }
@@ -324,19 +329,29 @@ class ClientController extends AdminController
     }
 
     //Function for Send Member Review and Summery Confirmation Mail
-    public function sendMemberReviewConfirmationMail($client_id = 77, $emp_code = 'EMP001-K1', $mail_active = 0)
+    public function sendMemberReviewConfirmationMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0)
     {
-        $client_policy_ids = $this->employeeModel
-            ->select('employee_polices.client_policy_id')
-            ->join('employee_polices', 'employees.id = employee_polices.employee_id')
-            ->where('employees.client_id', $client_id)
-            ->where('employees.emp_code', $emp_code)
-            ->where('employee_polices.is_active', 1)
-            ->where('employees.is_active', 1)
-            ->findAll();
-    
-        $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id');
-        $client_policy_id = array_unique($client_policy_ids2);
+        // dd($client_id, $emp_code, $policy_id, $mail_active);
+
+        if(empty($policy_id)){
+
+            $client_policy_ids = $this->employeeModel
+                                ->select('employee_polices.client_policy_id')
+                                ->join('employee_polices', 'employees.id = employee_polices.employee_id')
+                                ->where('employees.client_id', $client_id ) 
+                                ->where('employees.emp_code', $emp_code )
+                                ->where('employee_polices.is_active', 1 )
+                                ->where('employees.is_active', 1 )
+                                ->findAll();
+
+            $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id');
+            $client_policy_id = array_unique($client_policy_ids2);
+
+        }else{
+            $client_policy_id = json_decode($policy_id, true);
+        }
+
+        // dd($client_policy_id);
     
         if (!is_null($client_policy_id) && is_array($client_policy_id)) {
 
@@ -396,8 +411,9 @@ class ClientController extends AdminController
     
                 $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
     
-                if ($mail_active > 0) {
+                if ($mail_active == 0) {
 
+                    // $mail_send_result = [];
                     $mail_send_result = MailHelper::send_email($wholeData[0]);
     
                     if ($mail_send_result['status'] === 'success') {
@@ -644,7 +660,7 @@ class ClientController extends AdminController
         $data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
         $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId);
 
-        // dd($data['insurerName']);
+        // dd($data);
 
         // print_r($data['depositdata'] );die;
         // Load the view for the new list page;
@@ -660,25 +676,31 @@ class ClientController extends AdminController
 
         $client_id = $this->request->getPost('client_id');
         $insurer_id = $this->request->getPost('insurer_id');
+        $record_date = $this->request->getPost('record_date');
 
         $CD_Account_Number = $this->CDMasterModel
             ->where('client_id', $client_id)
             ->where('insurer_id', $insurer_id)
             ->first();
-
         // Prepare the array with data
+        $date = \DateTime::createFromFormat('d/m/Y', $record_date);
+        $record_date = $date->format('Y-m-d');
         $data = [
             'amount' => $this->request->getPost('amount'),
             'sub_type_id' => $this->request->getPost('sub_type_id'),
             'client_id' => $this->request->getPost('client_id'),
             'client_policy_id' => null,
             'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+            'cd_ac_pk' => $CD_Account_Number['id'] ?? null,
             'endorsement_no' => null,
             'insurer_id' => $this->request->getPost('insurer_id'),
             'description' => $this->request->getPost('description'),
             'transaction_type' => $this->request->getPost('transaction_type') ?: 'Credit',
             'updated_by' => 1,
+            'record_date' => $record_date
         ];
+        // log_message('error','data for insert'.json_encode($data));die();
+        // print_rr($data);die();
 
 
         // Call the saveDeposit function from DepositHelper
@@ -1980,8 +2002,16 @@ class ClientController extends AdminController
                 ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                 ->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])
                 ->findAll();
+
             $client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
             $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();
+            // $client_policy_data['policy_end_date'] = date('d/m/Y', strtotime($client_policy_data['policy_end_date']));
+            $fromDate = new \DateTime($client_policy_data['policy_end_date']);
+            $fromDate->modify('+1 year');
+            $newDate = $fromDate->format('d/m/Y');
+
+
+            // print_rr($client_policy_data['policy_end_date']);die();
 
             return $this->respond([
                 'status' => true,
@@ -1990,7 +2020,9 @@ class ClientController extends AdminController
                 'cd_data' => $cd_data,
                 "insurer_id" => $client_policy_data['insurer_id'],
                 'policy' => $polices,
-                'client_policy_list' =>  $client_policy_list
+                'client_policy_list' =>  $client_policy_list,
+                'end_date'  => $newDate,
+                'new_start_date'  => date('d/m/Y', strtotime($client_policy_data['policy_end_date']))
             ], 200);
         } else {
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -2186,6 +2218,7 @@ class ClientController extends AdminController
     public function policyGMCTerms()
     {
         try {
+
             // echo "
";
             // print_r($this->request->getPost());die;
             $this->myLogger->logme('error', 'Terms CREATE function called');
@@ -2195,7 +2228,6 @@ class ClientController extends AdminController
 
             $data['sum_insured']   = str_replace(',', '', $this->request->getPost("sum_insured"));
             $data['family_floater']   = $this->request->getPost("family_floater") ? $this->request->getPost("family_floater") : 0;
-            // $data['corporatebuffer'] = $this->request->getPost("corporatebuffer") ? $this->request->getPost("corporatebuffer") : 0;
             $data['family_floaters'] = $this->request->getPost("family_floaters") ?? [];
 
             $data['age_ratio']['self']['min'] =  $this->request->getPost("self_min_age") ? $this->request->getPost("self_min_age") : 0;
@@ -2213,12 +2245,9 @@ class ClientController extends AdminController
             $data['is_payable_employee']['elders'] = $this->request->getPost("is_payable_employee_for_elders") ? 1 : 0;
 
 
-
-            // if (!in_array("self", $data['family_floaters'])) {
-            //     array_unshift($data['family_floaters'], "self");
-            // }
             $temp_family_floaters = $data['family_floaters'];
             $data['family_floaters'] = [];
+
             if (in_array("self", $temp_family_floaters) == 1) {
                 $data['family_floaters']['self'] = 1;
             } else {
@@ -2231,8 +2260,6 @@ class ClientController extends AdminController
                 $data['family_floaters']['spouse'] = 0;
             }
 
-            // $data['family_floaters']['either-parents-pil'] =0;
-
             if (count($temp_family_floaters)) {
                 $children_value = 0;
                 $value = 0;
@@ -2291,79 +2318,55 @@ class ClientController extends AdminController
             // print_r($data);die;
 
             $data['waiverofpreexistingdiseases']   = $this->request->getPost("waiverofpreexistingdiseases");
-            if ($data['waiverofpreexistingdiseases'] == 1) {
-                $data['maternitycoverage']   = str_replace(',', '', $this->request->getPost("maternitycoverage"));
-                $data['twindelivery']   = str_replace(',', '', $this->request->getPost("twindelivery"));
-                $data['preandpostnatal']   = str_replace(',', '', $this->request->getPost("preandpostnatal"));
-                $data['babyday1cover']   = str_replace(',', '', $this->request->getPost("babyday1cover"));
-            } else {
-                $data['maternitycoverage']   = "";
-                $data['twindelivery']   = "";
-                $data['preandpostnatal']   = "";
-                $data['babyday1cover']   = "";
-            }
-
-            $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
-            $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
             $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
             $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
+            $data['waiver_of_90_days_waiting_period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
+            $data['waiver_of_other_waiting_periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
+            $data['maternity_benefit'] = $this->request->getPost("maternity_benefit");
+            $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
+            $data['maternitycoverage']   = str_replace(',', '', $this->request->getPost("maternitycoverage"));
+            $data['twindelivery']   = str_replace(',', '', $this->request->getPost("twindelivery"));
+            $data['well_baby_well_mother_expenses']   = str_replace(',', '', $this->request->getPost("well_baby_well_mother_expenses"));
+            $data['preandpostnatal']   = str_replace(',', '', $this->request->getPost("preandpostnatal"));
+            $data['infertility_treatment_coverage']   = str_replace(',', '', $this->request->getPost("infertility_treatment_coverage"));
+            $data['babyday1cover']   = str_replace(',', '', $this->request->getPost("babyday1cover"));
+            $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
+            $data['mid_term_addition_of_new_born_newly_wedded_spouse'] = str_replace(',', '', $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse"));
             $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
-            // $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
+            $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
             $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
-            // $data['congenitaldiseasesexternal'] =$this->request->getPost("congenitaldiseasesexternal");
+            $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
             $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
-            $data['co_pay_details'] = str_replace(',', '', $this->request->getPost("co_pay_details"));
-
-            $data['bioabsorbablestenttoriclensmultifocallens'] = $this->request->getPost("bioabsorbablestenttoriclensmultifocallens");
             $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
+            $data['icu_limit'] = str_replace(',', '', $this->request->getPost("icu_limit"));
             $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
-            // $data['nursingallowance'] =str_replace(',', '',$this->request->getPost("nursingallowance"));
             $data['ailmentcapping'] = $this->request->getPost("ailmentcapping");
             $data['ailment_capping_details'] = str_replace(',', '', $this->request->getPost("ailment_capping_details"));
-
+            $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
+            $data['non_admissible_contingency_corporate_buffer'] = str_replace(',', '', $this->request->getPost("non_admissible_contingency_corporate_buffer"));
             $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
             $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
-            $data['familytransportationbenefit'] = str_replace(',', '', $this->request->getPost("familytransportationbenefit"));
             $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
             $data['daycaretreatment'] = str_replace(',', '', $this->request->getPost("daycaretreatment"));
-            $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
-
-            $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
-            // $data['optionalparentalcopay'] = str_replace(',', '', $this->request->getPost("optionalparentalcopay"));
-            $data['posthospitalizationcover'] = str_replace(',', '', $this->request->getPost("posthospitalizationcover"));
-            $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
-            $data['sublimitofcorporatebuffer'] = str_replace(',', '', $this->request->getPost("sublimitofcorporatebuffer"));
-
-            if ($data['ayudhtreatmentcover'] == 1) {
-                $data['ayushTreatmentCoverData']   = str_replace(',', '', $this->request->getPost("ayushTreatmentCoverData"));
-            } else {
-                $data['ayushTreatmentCoverData']   = "";
-            }
-
-            $data['armdcovered'] = str_replace(',', '', $this->request->getPost("armdcovered"));
-            $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
-            $data['automaticsuminsuredreinstatement'] = str_replace(',', '', $this->request->getPost("automaticsuminsuredreinstatement"));
-            $data['additionalsicknessbenefit'] = str_replace(',', '', $this->request->getPost("additionalsicknessbenefit"));
             $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
-            $data['midterminclusion'] = str_replace(',', '', $this->request->getPost("midterminclusion"));
-            $data['capd'] = str_replace(',', '', $this->request->getPost("capd"));
-            $data['organdonorexpenses'] = str_replace(',', '', $this->request->getPost("organdonorexpenses"));
+            $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
             $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
-            $data['Wellness'] = str_replace(',', '', $this->request->getPost("Wellness"));
+            $data['opd_treatment'] = str_replace(',', '', $this->request->getPost("opd_treatment"));
             $data['days_of_discharge'] = str_replace(',', '', $this->request->getPost("days_of_discharge"));
             $data['days_from_dod'] = str_replace(',', '', $this->request->getPost("days_from_dod"));
+            $data['terrorism'] = str_replace(',', '', $this->request->getPost("terrorism"));
+            $data['widower_cover'] = str_replace(',', '', $this->request->getPost("widower_cover"));
+            $data['breavement_cover'] = str_replace(',', '', $this->request->getPost("breavement_cover"));
+
+            $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
+
             $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
             $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
             $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
 
-            $data['cataract'] = str_replace(',', '', $this->request->getPost("cataract"));
-
-            if ($data['cataract'] == 1) {
-                $data['cataractData']   = str_replace(',', '', $this->request->getPost("cataractData"));
-            } else {
-                $data['cataractData']   = "";
-            }
+            $data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
 
+            // print_r($data);die;
 
             $jsonData = json_encode($data);
             $dataa = array(
@@ -2372,7 +2375,6 @@ class ClientController extends AdminController
 
             $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
 
-
             // print_r($data);die;
             if ($record) {
                 $update = $this->clientPolicyModel->update($client_policy_id, $dataa);
@@ -2397,6 +2399,190 @@ 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("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 getterms()
     {
         $client_policy_id = $this->request->getVar('client_policy_id');
@@ -2449,52 +2635,32 @@ class ClientController extends AdminController
             $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement"));
             $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement");
             $data['temporaryTotalDisablementBenefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
-            $data['accidentalHospitalizationExpenses'] = str_replace(',', '', $this->request->getPost("accidentalHospitalizationExpenses"));
-            $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
-
-            $data['compassionateVisitExpenses']   = $this->request->getPost("compassionateVisitExpenses");
-            if ($data['compassionateVisitExpenses'] == 1) {
-                $data['compassionateVisitExpensesData']   = $this->request->getPost("compassionateVisitExpensesData");
-            } else {
-                $data['compassionateVisitExpensesData']   = "";
-            }
-
-            $data['brokenBoneExpenses']   = str_replace(',', '', $this->request->getPost("brokenBoneExpenses"));
-            if ($data['brokenBoneExpenses'] == 1) {
-                $data['brokenBoneExpensesData']   = str_replace(',', '', $this->request->getPost("brokenBoneExpensesData"));
-            } else {
-                $data['brokenBoneExpensesData']   = "";
-            }
-
+            $data['medical_expenses_medical_extension'] = str_replace(',', '', $this->request->getPost("medical_expenses_medical_extension"));
+            $data['opd_treatment_cover'] = str_replace(',', '', $this->request->getPost("opd_treatment_cover"));
             $data['ambulanceCharges']   = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
-            if ($data['ambulanceCharges'] == 1) {
-                $data['ambulanceChargesData']   = str_replace(',', '', $this->request->getPost("ambulanceChargesData"));
-            } else {
-                $data['ambulanceChargesData']   = "";
-            }
-
-            $data['burnExpenses']   = $this->request->getPost("burnExpenses");
-            if ($data['burnExpenses'] == 1) {
-                $data['burnExpensesData']   = $this->request->getPost("burnExpensesData");
-            } else {
-                $data['burnExpensesData']   = "";
-            }
-
-            $data['carriageOfDeadBody']   = $this->request->getPost("carriageOfDeadBody");
-            if ($data['carriageOfDeadBody'] == 1) {
-                $data['carriageOfDeadBodyData']   = $this->request->getPost("carriageOfDeadBodyData");
-            } else {
-                $data['carriageOfDeadBodyData']   = "";
-            }
-
-            $data['animalSnakeInsectBite'] = $this->request->getPost("animalSnakeInsectBite");
+            $data['repatriation_of_mortal_remains']   = str_replace(',', '', $this->request->getPost("repatriation_of_mortal_remains"));
+            $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
             $data['terrorism']             = $this->request->getPost("terrorism");
             $data['worldwideCover']        = $this->request->getPost("worldwideCover");
+            $data['family_transportation_benefits']        = $this->request->getPost("family_transportation_benefits");
+            $data['fractures_dislocation_burns']        = $this->request->getPost("fractures_dislocation_burns");
+            $data['coma']        = $this->request->getPost("coma");
+            $data['carriageOfDeadBody']   = $this->request->getPost("carriageOfDeadBody");
+            $data['compassionateVisitExpenses']   = $this->request->getPost("compassionateVisitExpenses");
+            $data['travel_expenses_for_medical_treatment']        = $this->request->getPost("travel_expenses_for_medical_treatment");
+            $data['daily_cash_allowance']        = $this->request->getPost("daily_cash_allowance");
+            $data['artifical_limb_and_prosthesis']        = $this->request->getPost("artifical_limb_and_prosthesis");
+            $data['animalSnakeInsectBite']        = $this->request->getPost("animalSnakeInsectBite");
+            $data['air_ambulance']        = $this->request->getPost("air_ambulance");
+
+
             $data['gpa_special_condition_label'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_label")) ?? [];
             $data['gpa_special_condition_input'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_input")) ?? [];
             $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
 
+            $data['enrollment_display_key'] = $this->enrollmentGPADisplayValueTransform();
 
+            // print_r($data); die;
 
             $jsonData = json_encode($data);
             $dataa = array(
@@ -2524,6 +2690,94 @@ 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 getPolicyGPATerms()
     {
 
@@ -3131,7 +3385,6 @@ class ClientController extends AdminController
 
     public function createPolicyTermsHtmlAsJSON()
     {
-
         echo 'hi';
     }
 
@@ -3790,25 +4043,35 @@ class ClientController extends AdminController
     public function updatePolicyTermsKey()
     {
         $client_id = $this->request->getGet('client_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
 
         $query = $this->clientPolicyModel
             ->where("policy_terms IS NOT NULL AND policy_terms <> ''")
             ->where('is_active', 1);
+
         
         if (!empty($client_id)) {
             $query->where('client_id', $client_id);
         }
         
+        if (!empty($policy_type_id)) {
+            $query->where('policy_type_id', $policy_type_id);
+        }
+        
         $data = $query->findAll();
         
         for ($i = 0; $i < count($data); $i++) {
 
+            // dd($data[$i]);
+
             if (isset($data[$i]['policy_terms']) && !empty($data[$i]['policy_terms'])) {
                 $policyTerms = json_decode($data[$i]['policy_terms'], true);
             } else {
                 continue;
             }
 
+            // dd($policyTerms);
+
             $is_addon = $data[$i]['is_addon'];
 
             $payable_arr = [];
@@ -3831,7 +4094,7 @@ class ClientController extends AdminController
             if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){
 
                 // Set default value of copayzonewisecopay to "empty"
-                $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty';
+                // $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty';
 
                 // add is_payable_employee for the GMC Policy
                 if (isset($policyTerms['age_ratio'])) {
@@ -3845,31 +4108,31 @@ class ClientController extends AdminController
                     }
                 }
 
-                // Add copayzonewisecopay and copayzonewisecopaydata if they exist_
-                if (isset($policyTerms['copayzonewisecopay'])) {
+                // // Add copayzonewisecopay and copayzonewisecopaydata if they exist_
+                // if (isset($policyTerms['copayzonewisecopay'])) {
 
-                    if(!isset($policyTerms['co_pay_details'])){
+                //     if(!isset($policyTerms['co_pay_details'])){
 
-                        $co_pay_details_value = "";
-                        if (strtolower($ans) == "nil" || $ans == 0) {
-                            $policyTerms['copayzonewisecopay'] = 0;
-                            $co_pay_details_value = "";
-                        } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) {
-                            $policyTerms['copayzonewisecopay'] = 1;
-                            $co_pay_details_value = $ans;
-                        }
+                //         $co_pay_details_value = "";
+                //         if (strtolower($ans) == "nil" || $ans == 0) {
+                //             $policyTerms['copayzonewisecopay'] = 0;
+                //             $co_pay_details_value = "";
+                //         } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) {
+                //             $policyTerms['copayzonewisecopay'] = 1;
+                //             $co_pay_details_value = $ans;
+                //         }
 
-                        $co_pay_index = array_search('copayzonewisecopay', array_keys($policyTerms));
-                        $orderedPolicyTerms[] = [
-                            "key" => "co_pay_details",
-                            "value" =>  $co_pay_details_value,
-                            "position" => $co_pay_index + 2,
-                        ];
+                //         $co_pay_index = array_search('copayzonewisecopay', array_keys($policyTerms));
+                //         $orderedPolicyTerms[] = [
+                //             "key" => "co_pay_details",
+                //             "value" =>  $co_pay_details_value,
+                //             "position" => $co_pay_index + 2,
+                //         ];
 
-                        unset($policyTerms['optionalparentalcopay']);
+                //         unset($policyTerms['optionalparentalcopay']);
 
-                    }
-                }
+                //     }
+                // }
 
                 // Add ailmentcapping and ailmentcappingdata if they exist
                 if (isset($policyTerms['ailmentcapping'])) {
@@ -3878,7 +4141,7 @@ class ClientController extends AdminController
                         $orderedPolicyTerms[] = [
                             "key" => "ailment_capping_details",
                             "value" => "",
-                            "position" => $aliment_index + 3,
+                            "position" => $aliment_index + 2,
                         ];
                     }
                 }
@@ -3912,8 +4175,6 @@ class ClientController extends AdminController
 
             }
 
-
-
             foreach ($orderedPolicyTerms as $term) {
                 $position = $term['position'];
                 $key = $term['key'];
@@ -3925,14 +4186,360 @@ class ClientController extends AdminController
                 );
             }
 
+            foreach ($policyTerms as $key => $term) {
+                if ($term == "0") {
+                    $policyTerms[$key] = "No";  // Use = for assignment
+                } elseif ($term == "1") {
+                    $policyTerms[$key] = "Yes"; // Use = for assignment
+                }
+            }
+
+            if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){
+
+                if (!isset($policyTerms['waiver_of_90_days_waiting_period'])) {
+                    $policyTerms['waiver_of_90_days_waiting_period'] = "";
+                }
+                
+                if (!isset($policyTerms['waiver_of_other_waiting_periods'])) {
+                    $policyTerms['waiver_of_other_waiting_periods'] = "";
+                }
+
+                if (!isset($policyTerms['maternity_benefit'])) {
+                    $policyTerms['maternity_benefit'] = "";
+                }
+                
+                if (!isset($policyTerms['well_baby_well_mother_expenses'])) {
+                    $policyTerms['well_baby_well_mother_expenses'] = "";
+                }
+
+                if (!isset($policyTerms['icu_limit'])) {
+                    $policyTerms['icu_limit'] = "";
+                }
+
+                if (!isset($policyTerms['infertility_treatment_coverage'])) {
+                    $policyTerms['infertility_treatment_coverage'] = "";
+                }
+
+                if (!isset($policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'])) {
+                    $policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'] = "";
+                }
+
+                if (!isset($policyTerms['non_admissible_contingency_corporate_buffer'])) {
+                    $policyTerms['non_admissible_contingency_corporate_buffer'] = "";
+                }
+
+                if (!isset($policyTerms['terrorism'])) {
+                    $policyTerms['terrorism'] = "";
+                }
+
+                if (!isset($policyTerms['widower_cover'])) {
+                    $policyTerms['widower_cover'] = "";
+                }
+                
+                if (!isset($policyTerms['breavement_cover'])) {
+                    $policyTerms['breavement_cover'] = "";
+                }
+                
+                if (!isset($policyTerms['enrollment_display_key'])) {
+                    $policyTerms['enrollment_display_key'] = $this->existingGMCDisplayValueTransform($policyTerms);
+                }
+
+            } else if($data[$i]['policy_type_id'] == 1){
+
+                if (!isset($policyTerms['medical_expenses_medical_extension'])) {
+                    $policyTerms['medical_expenses_medical_extension'] = "";
+                }
+                
+                if (!isset($policyTerms['opd_treatment_cover'])) {
+                    $policyTerms['opd_treatment_cover'] = "";
+                }
+                
+                if (!isset($policyTerms['repatriation_of_mortal_remains'])) {
+                    $policyTerms['repatriation_of_mortal_remains'] = "";
+                }
+                
+                if (!isset($policyTerms['family_transportation_benefits'])) {
+                    $policyTerms['family_transportation_benefits'] = "";
+                }
+                
+                if (!isset($policyTerms['fractures_dislocation_burns'])) {
+                    $policyTerms['fractures_dislocation_burns'] = "";
+                }
+                
+                if (!isset($policyTerms['coma'])) {
+                    $policyTerms['coma'] = "";
+                }
+                
+                if (!isset($policyTerms['travel_expenses_for_medical_treatment'])) {
+                    $policyTerms['travel_expenses_for_medical_treatment'] = "";
+                }
+                
+                if (!isset($policyTerms['daily_cash_allowance'])) {
+                    $policyTerms['daily_cash_allowance'] = "";
+                }
+                
+                if (!isset($policyTerms['artifical_limb_and_prosthesis'])) {
+                    $policyTerms['artifical_limb_and_prosthesis'] = "";
+                }
+                
+                if (!isset($policyTerms['air_ambulance'])) {
+                    $policyTerms['air_ambulance'] = "";
+                }
+                                
+                if (!isset($policyTerms['enrollment_display_key'])) {
+                    $policyTerms['enrollment_display_key'] = $this->existingGPADisplayValueTransform($policyTerms);
+                }
+                
+            }
+
+            // dd($policyTerms);
             // Re-encode the ordered policy terms
             $updatedPolicyTerms = json_encode($policyTerms);
+            // dd($updatedPolicyTerms);
 
             // dd($orderedPolicyTerms, $updatedPolicyTerms);
             $this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]);
         }
     }
 
+    public function existingGMCDisplayValueTransform($data)
+    {
+        $transformedData = [];
+
+        if (isset($data["waiverofpreexistingdiseases"])) {
+            $transformedData['Waiver of Pre-existing Diseases'] = $data["waiverofpreexistingdiseases"];
+        }
+
+        if (isset($data["waiverof1,2,3&4thyearexclusions"])) {
+            $transformedData['Waiver of 1, 2, 3 & 4th year Exclusions'] = $data["waiverof1,2,3&4thyearexclusions"];
+        }
+
+        if (isset($data["waiverof30dayswaitingperiod"])) {
+            $transformedData['Waiver of 30 days waiting period'] = $data["waiverof30dayswaitingperiod"];
+        }
+
+        if (isset($data["waiver_of_90_days_waiting_period"])) {
+            $transformedData['Waiver of 90 Days Waiting Period'] = $data["waiver_of_90_days_waiting_period"];
+        }
+
+        if (isset($data["waiver_of_other_waiting_periods"])) {
+            $transformedData['Waiver of Other Waiting Periods'] = $data["waiver_of_other_waiting_periods"];
+        }
+
+        if (isset($data["maternity_benefit"])) {
+            $transformedData['Maternity Benefit'] = $data["maternity_benefit"];
+        }
+
+        if (isset($data["9monthwaitingperiodwaived"])) {
+            $transformedData['9-month waiting Period - waived'] = $data["9monthwaitingperiodwaived"];
+        }
+
+        if (isset($data["maternitycoverage"])) {
+            $transformedData['Maternity Coverage'] = $data["maternitycoverage"];
+        }
+
+        if (isset($data["twindelivery"])) {
+            $transformedData['Twin Delivery'] = $data["twindelivery"];
+        }
+
+        if (isset($data["well_baby_well_mother_expenses"])) {
+            $transformedData['Well baby / Well Mother Expenses'] = $data["well_baby_well_mother_expenses"];
+        }
+
+        if (isset($data["preandpostnatal"])) {
+            $transformedData['Pre and Post natal'] = $data["preandpostnatal"];
+        }
+
+        if (isset($data["infertility_treatment_coverage"])) {
+            $transformedData['Infertility Treatment Coverage'] = $data["infertility_treatment_coverage"];
+        }
+
+        if (isset($data["babyday1cover"])) {
+            $transformedData['Baby Day 1 Cover'] = $data["babyday1cover"];
+        }
+
+        if (isset($data["coverfromthedateofjoining"])) {
+            $transformedData['Cover from the date of Joining'] = $data["coverfromthedateofjoining"];
+        }
+
+        if (isset($data["mid_term_addition_of_new_born_newly_wedded_spouse"])) {
+            $transformedData['Mid Term Addition of New Born / Newly Wedded Spouse'] = $data["mid_term_addition_of_new_born_newly_wedded_spouse"];
+        }
+
+        if (isset($data["prehospitalizationcover"])) {
+            $transformedData['Pre Hospitalization Cover'] = $data["prehospitalizationcover"];
+        }
+
+        if (isset($data["posthospitalizationcover"])) {
+            $transformedData['Post Hospitalization Cover'] = $data["posthospitalizationcover"];
+        }
+
+        if (isset($data["congenitaldiseasesinternal"])) {
+            $transformedData['Congenital Diseases - Internal'] = $data["congenitaldiseasesinternal"];
+        }
+
+        if (isset($data["congenitaldiseasesexternal"])) {
+            $transformedData['Congenital Diseases - External'] = $data["congenitaldiseasesexternal"];
+        }
+
+        if (isset($data["copayzonewisecopay"])) {
+            $transformedData['Co-Pay/Zone wise Co Pay'] = $data["copayzonewisecopay"];
+        }
+
+        if (isset($data["roomrentlimit"])) {
+            $transformedData['Room Rent Limit'] = $data["roomrentlimit"];
+        }
+
+        if (isset($data["icu_limit"])) {
+            $transformedData['ICU Limit'] = $data["icu_limit"];
+        }
+
+        if (isset($data["proportionatedeductionclause"])) {
+            $transformedData['Proportionate Deduction Clause'] = $data["proportionatedeductionclause"];
+        }
+
+        if (isset($data["ailmentcapping"])) {
+            $transformedData['Ailment capping'] = $data["ailmentcapping"];
+        }
+
+        if (isset($data["ailment_capping_details"])) {
+            $transformedData['Ailment capping Details'] = $data["ailment_capping_details"];
+        }
+
+        if (isset($data["corporatebuffer"])) {
+            $transformedData['Corporate Buffer'] = $data["corporatebuffer"];
+        }
+
+        if (isset($data["non_admissible_contingency_corporate_buffer"])) {
+            $transformedData['Non-Admissible / Contingency Corporate Buffer'] = $data["non_admissible_contingency_corporate_buffer"];
+        }
+
+        if (isset($data["ambulancecharges"])) {
+            $transformedData['Ambulance Charges'] = $data["ambulancecharges"];
+        }
+
+        if (isset($data["airambulance"])) {
+            $transformedData['Air Ambulance'] = $data["airambulance"];
+        }
+
+        if (isset($data["reasonableandcustomarycharges"])) {
+            $transformedData['Reasonable and Customary Charges'] = $data["reasonableandcustomarycharges"];
+        }
+
+        if (isset($data["daycaretreatment"])) {
+            $transformedData['Day Care Treatment'] = $data["daycaretreatment"];
+        }
+
+        if (isset($data["lasiksurgery"])) {
+            $transformedData['Lasik Surgery'] = $data["lasiksurgery"];
+        }
+
+        if (isset($data["ayushtreatmentcover"])) {
+            $transformedData['AYUSH treatment cover'] = $data["ayushtreatmentcover"];
+        }
+
+        if (isset($data["moderntreatmentsasperirdai"])) {
+            $transformedData['Modern treatments as per IRDAI'] = $data["moderntreatmentsasperirdai"];
+        }
+
+        if (isset($data["opd_treatment"])) {
+            $transformedData['OPD Treatment'] = $data["opd_treatment"];
+        }
+
+        if (isset($data["days_of_discharge"])) {
+            $transformedData['Claim Intimation Clause'] = $data["days_of_discharge"];
+        }
+
+        if (isset($data["days_from_dod"])) {
+            $transformedData['Claim Submission'] = $data["days_from_dod"];
+        }
+
+        if (isset($data["terrorism"])) {
+            $transformedData['Terrorism'] = $data["terrorism"];
+        }
+
+        if (isset($data["widower_cover"])) {
+            $transformedData['Widower Cover'] = $data["widower_cover"];
+        }
+
+        if (isset($data["breavement_cover"])) {
+            $transformedData['Breavement Cover'] = $data["breavement_cover"];
+        }
+
+        return !empty($transformedData) ? $transformedData : [];
+    }
+
+    public function existingGPADisplayValueTransform($data)
+    {   
+        $transformedData = [];
+
+        if (isset($data["accidentalDeathBenefit"])) {
+            $transformedData['Accidental Death Benefit'] = $data["accidentalDeathBenefit"];
+        }
+        if (isset($data["permanentTotalDisablement"])) {
+            $transformedData['Permanent Total Disablement'] = $data["permanentTotalDisablement"];
+        }
+        if (isset($data["permanentPartialDisablement"])) {
+            $transformedData['Permanent Partial Disablement'] = $data["permanentPartialDisablement"];
+        }
+        if (isset($data["temporaryTotalDisablementBenefit"])) {
+            $transformedData['Temporary Total Disablement Benefit'] = $data["temporaryTotalDisablementBenefit"];
+        }
+        if (isset($data["medical_expenses_medical_extension"])) {
+            $transformedData['Medical Expenses / Medical Extension (IPD)'] = $data["medical_expenses_medical_extension"];
+        }
+        if (isset($data["opd_treatment_cover"])) {
+            $transformedData['OPD Treatment Cover'] = $data["opd_treatment_cover"];
+        }
+        if (isset($data["ambulanceCharges"])) {
+            $transformedData['Ambulance Charges'] = $data["ambulanceCharges"];
+        }
+        if (isset($data["repatriation_of_mortal_remains"])) {
+            $transformedData['Repatriation of Mortal Remains'] = $data["repatriation_of_mortal_remains"];
+        }
+        if (isset($data["childrenEducationWelfareFund"])) {
+            $transformedData['Children Education Welfare Fund'] = $data["childrenEducationWelfareFund"];
+        }
+        if (isset($data["terrorism"])) {
+            $transformedData['Terrorism'] = $data["terrorism"];
+        }
+        if (isset($data["worldwideCover"])) {
+            $transformedData['Worldwide Cover'] = $data["worldwideCover"];
+        }
+        if (isset($data["family_transportation_benefits"])) {
+            $transformedData['Family Transportation Benefits'] = $data["family_transportation_benefits"];
+        }
+        if (isset($data["fractures_dislocation_burns"])) {
+            $transformedData['Fractures / Dislocation / Burns'] = $data["fractures_dislocation_burns"];
+        }
+        if (isset($data["coma"])) {
+            $transformedData['Coma'] = $data["coma"]; 
+        }
+        if (isset($data["carriageofDeadBody"])) {
+            $transformedData['Carriage of Dead Body'] = $data["carriageofDeadBody"];
+        }
+        if (isset($data["compassionateVisitExpenses"])) {
+            $transformedData['Compassionate Visit Expenses'] = $data["compassionateVisitExpenses"];
+        }
+        if (isset($data["travel_expenses_for_medical_treatment"])) {
+            $transformedData['Travel expenses for Medical Treatment'] = $data["travel_expenses_for_medical_treatment"];
+        }
+        if (isset($data["daily_cash_allowance"])) {
+            $transformedData['Daily cash Allowance'] = $data["daily_cash_allowance"];
+        }
+        if (isset($data["artifical_limb_and_prosthesis"])) {
+            $transformedData['Artifical Limb and Prosthesis'] = $data["artifical_limb_and_prosthesis"];
+        }
+        if (isset($data["animalSnakeInsectBite"])) {
+            $transformedData['Animal/Snake/Insect Bite'] = $data["animalSnakeInsectBite"];
+        }
+        if (isset($data["air_ambulance"])) {
+            $transformedData['Air Ambulance'] = $data["air_ambulance"];
+        }
+
+        return !empty($transformedData) ? $transformedData : [];
+    }
+
     public function updateRemainderDate()
     {
         // Connect to the database and fetch the data
@@ -3959,12 +4566,17 @@ class ClientController extends AdminController
 
     public function sendextraparam()
     {   
+
+        // $employeeController = new EmployeeController();
+        // $employeeController->truncateFileData('633');
         
         // ---------- EMP SERVICE CONTROLLER --------------------------------------------------------------------------------
 
         $employeeRestController = new EmployeeServiceController();
         // $employeeRestController->excelFileDataValidation(['file_id' => 823]);
-        // $employeeRestController->employeesOnboardPreprocess(['file_id' => 823]);
+        // $employeeRestController->employeesOnboardPreprocess(['file_id' => 726]);
+        // $employeeRestController->employeesOnboardProcess(['file_id' => 835]);
+        // $employeeRestController->employeesEnrollmentInsert(['file_id' => 836]);
         // $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]);
 
 
@@ -4093,6 +4705,9 @@ class ClientController extends AdminController
         // $this->loadLayout('tat_report_band_wise_list', $reportData);
         // $data = $ticketModel->getTATReport(1);
         
+        // $empmodel = new EmployeeModel();
+        // $data = $empmodel->getEmployeePolicy(348);
+        // dd($data);
     }
 
     // -------------------------------------------------------------------------------------------------------
@@ -4222,7 +4837,7 @@ class ClientController extends AdminController
             return $this->respond([
                 'status' => false,
                 'code' => 404,
-                'message' => 'No data found',
+                'message' => 'No Employee found',
                 'param' => $param,
                 'type' => $type,
                 'dataForClientAndInsurer' => $dataForClientAndInsurer,
@@ -4231,12 +4846,12 @@ class ClientController extends AdminController
         }
     } 
     
-    public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile')
+    public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null)
     {   
         $field_name = 'employees.' . $type;
 
         // Construct the base query
-        $data = $this->clientPolicyModel
+        $query = $this->clientPolicyModel
             ->select("
                 clients.id AS client_id,
                 clients.client_name,
@@ -4251,24 +4866,37 @@ class ClientController extends AdminController
                 employees.email_corporate AS emp_email,
                 employees.relationship AS emp_relationship,
                 employee_polices.uhid AS policy_no,
-                employee_polices.tpa_id AS tpa_no
+                employee_polices.tpa_id AS tpa_no,
+                employee_polices.client_policy_id AS policy_id
             ")
-            ->join('clients', 'client_policy.client_id = clients.id', 'left')
-            ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
+            ->join('clients', 'client_policy.client_id = clients.id')
+            ->join('insurers', 'client_policy.insurer_id = insurers.id')
             ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
-            ->join('employees', 'clients.id = employees.client_id', 'left')
-            ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
+            ->join('employees', 'clients.id = employees.client_id')
+            ->join('employee_polices', 'employees.id = employee_polices.employee_id')
             ->where('client_policy.is_active', 1)
             ->where('insurers.is_active', 1)
             ->where('tpa.is_active', 1)
             ->where('employees.is_active', 1)
             ->where('employees.relationship', "Self")
             ->where('employee_polices.is_active', 1)
-            ->where($field_name, $param)
-            ->groupBy('employees.id')
-            ->orderBy('employees.id', 'DESC')
-            ->first();
-        
+            ->where($field_name, $param);
+
+            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);
+            }
+            
+            $query->groupBy('employees.id')
+                ->orderBy('employees.id', 'DESC');
+            
+            $data = $query->get()->getRowArray();
+
+            // print_r(db_connect()->getLastQuery()); die;
+
         $memberData = [];
         $dataForClientAndInsurer = [];
 
@@ -4281,17 +4909,11 @@ class ClientController extends AdminController
 
         if(!empty($data) && count($data) > 0){
 
-            $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code']);
-
-            $acms = $this->clientRMModel
-                ->select('user_profiles.id, user_profiles.first_name')
-                ->join('clients', 'client_rm.client_id = clients.id', 'left')
-                ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left')
-                ->where('clients.is_active', 1)
-                ->where('client_rm.is_active', 1)
-                ->where('user_profiles.is_active', 1)
-                ->where('clients.id', $data['client_id'])    
-                ->findAll();
+            $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $data['policy_id'], $client_id);
+            $acms_datas = $this->employeeModel->getAcmUsingClientID($data['client_id']);
+            if(!empty($acms_datas)){
+                $acms = $acms_datas;
+            }
         }
 
 
@@ -4304,6 +4926,7 @@ class ClientController extends AdminController
                 'message' => 'Data found',
                 'data' => $data,
                 'param' => $param,
+                'client_policy_id' => $client_policy_id,
                 'type' => $type,
                 'dataForClientAndInsurer' => $dataForClientAndInsurer,
                 'memberData' => $memberData,
@@ -4313,8 +4936,9 @@ class ClientController extends AdminController
             return $this->respond([
                 'status' => false,
                 'code' => 404,
-                'message' => 'No data found',
+                'message' => 'No Employee found',
                 'param' => $param,
+                'client_policy_id' => $client_policy_id,
                 'type' => $type,
                 'dataForClientAndInsurer' => $dataForClientAndInsurer,
                 'memberData' => $memberData,
@@ -4328,137 +4952,159 @@ class ClientController extends AdminController
 
 
     public function updateRenewalData()
-    {   
+    {
         $db = db_connect();
         $renewalData = $db->table('old_renewal_data_copy')
-                          ->where('client_id IS NOT NULL')
-                          ->where('is_inserted != 1')
-                          ->get()
-                          ->getResultArray();
-    
+        ->where('client_id IS NOT NULL')
+        ->where('is_inserted != 1')
+        ->get()
+            ->getResultArray();
+        // dd($renewalData);
+
         $successData = [];
         foreach ($renewalData as $key => $value) {
             // Get branch_id properly
             $branch = $this->clientBranchModel->where('client_id', $value['client_id'] ?? 0)->first();
-            $value['branch_id'] = $branch['branch_id'] ?? null;
-    
+            // kint::dump($branch);
+            $value['branch_id'] = $branch['id'] ?? null;
+
             // Fix vehicle_id key (previously "vehicel_id")
             $value['vehicle_id'] = null;
             if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) {
                 $value['vehicle_id'] = $this->prepareVehicleData($value);
             }
-    
+
             // Process client policy, policy transaction, and co-share details
             $value['client_policy_id'] = $this->prepareClientPolicy($value);
             $value['pt_id'] = $this->preparePolicyData($value);
             $value['pt_co_id'] = $this->preparePtCoShareDetails($value);
-    
+
             // Update is_inserted field in DB
             $db->table('old_renewal_data_copy')
-               ->where('id', $value['id'])
-               ->set(['is_inserted' => 1])
-               ->update();
-    
+            ->where('id', $value['id'])
+            ->set(['is_inserted' => 1])
+                ->update();
+
             $successData[] = ['id' => $value['id'], 'client' => $value['insured']];
-        } 
-    
+        }
+
+        kint::dump($successData);
+    }
+
+    public function updateRenewalInsurerData()
+    {
+        $db = db_connect();
+        $renewalData = $db->table('old_renewal_data_copy')
+        ->where('insurer_id IS NULL')
+        ->get()
+            ->getResultArray();
+        // dd($renewalData);
+
+        $successData = [];
+        foreach ($renewalData as $key => $value) {
+
+            $insurer_data = $this->insurerModel->where('name', $value['insurer_name'])->where('is_active', 1)->first();
+
+            if (!empty($insurer_data)) {
+
+                $insurer_branch_data = $this->insurerBranchModel->where('branch_name', $value['insurer_branch'])->first();
+                if (!empty($insurer_branch_data)) {
+                    $branch = $this->insurerBranchModel->where('insurer_id', $insurer_data['id'] ?? 0)->first();
+                    $value['insurer_id'] = $insurer_data['id'] ?? null;
+                    $value['insurer_branch_id'] = $branch['id'] ?? null;
+                } else {
+                    $value['insurer_id'] = $insurer_data['id'] ?? null;
+                    $value['insurer_branch_id'] = $this->prepareInsurerBranch($value);
+                }
+            } else {
+                $value['insurer_id'] = $this->prepareinsurer($value);
+                $value['insurer_branch_id'] = $this->prepareInsurerBranch($value);
+            }
+
+            // Update is_inserted field in DB
+            $db->table('old_renewal_data_copy')
+            ->where('id', $value['id'])
+            ->set([
+                'insurer_id' => $value['insurer_id'],
+                'insurer_branch_id' => $value['insurer_branch_id'],
+            ])
+                ->update();
+
+            $successData[] = ['id' => $value['id'], 'insurer' => $value['insurer_name'], 'insurer_id' => $value['insurer_id'], 'insurer_branch_id' => $value['insurer_branch_id'],];
+        }
+
+        kint::dump($successData);
+    }
+
+    public function updateRenewalDataNotExistingClient()
+    {
+        $limit = $this->request->getGet('limit') ?? 10;
+        $group = $this->request->getGet('group') ?? 2;
+        $db = db_connect();
+        $renewalData = $db->table('old_renewal_data_copy')
+        ->where('client_id IS NULL')
+        ->where('is_inserted = 0')
+        ->where('client_type_id', $group)
+            // ->limit($limit)
+            ->get()
+            ->getResultArray();
+        // dd($renewalData);
+
+        $successData = [];
+        foreach ($renewalData as $key => $value) {
+
+            $client_data = $this->clientModel->where('client_name', $value['insured'])->where('is_active', 1)->first();
+            if (!empty($client_data)) {
+                $branch = $this->clientBranchModel->where('client_id', $client_data['id'] ?? 0)->first();
+                $value['branch_id'] = $branch['id'] ?? null;
+                $value['client_id'] = $client_data['id'] ?? null;
+            } else {
+                $value['client_id'] = $this->prepareClient($value);
+                if ($value['client_type_id'] == 1) {
+                    $value['branch_id'] = $this->prepareClientBranch($value);
+                }
+            }
+
+            // Fix vehicle_id key (previously "vehicel_id")
+            if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) {
+                $value['vehicle_id'] = $this->prepareVehicleData($value);
+            } else {
+                $value['vehicle_id'] = 0;
+            }
+
+            // Process client policy, policy transaction, and co-share details
+            $value['client_policy_id'] = $this->prepareClientPolicy($value);
+            $value['pt_id'] = $this->preparePolicyData($value);
+            $value['pt_co_id'] = $this->preparePtCoShareDetails($value);
+
+            // Update is_inserted field in DB
+            $db->table('old_renewal_data_copy')
+            ->where('id', $value['id'])
+            ->set(['is_inserted' => 1])
+                ->update();
+
+            $successData[] = ['id' => $value['id'], 'client' => $value['insured'], 'vehicle_id' => $value['vehicle_id']];
+        }
+
         kint::dump($successData);
     }
-    
-    // private function preparePolicyData($renewalData)
-    // {   
-    //     $data = [
-    //         'issuer' => $renewalData['issuer_type_id'],
-    //         'client_id' => $renewalData['client_id'],
-    //         'client_branch_id' => $renewalData['branch_id'] ?? null,
-    //         'vehicle_id' => $renewalData['vehicle_id'],
-    //         'insurer_id' => $renewalData['insurer_id'],
-    //         'insurer_branch_id' => $renewalData['insurer_branch_id'],
-    //         'policy_type_id' => $renewalData['policy_type_id'],
-    //         'client_policy_id' => $renewalData['client_policy_id'] ?? null,
-    //         'policy_no' => $renewalData['policy_no'],
-    //         'policy_issue_date' => $renewalData['date_date_of_issue'],
-    //         'policy_start_date' => $renewalData['date_policy_start_date'],
-    //         'policy_end_date' => $renewalData['date_policy_end_date'],
-    //         'policy_holder_name' => $renewalData['insured'],
-    //         'status' => 'completed',
-    //         'is_active' => 1,
-    //         'tsi' => '500000',
-    //         'month' => '2025-02-01',
-    //         'ct_type' => 1,
-    //         'cd_ac_pk' => $renewalData['cd_ac_pk'] ?? null,
-    //     ];
-    
-    //     $policyTransactionModel = new PolicyTransactionModel();
-    //     return $policyTransactionModel->insert($data);
-    // }
-    
-    // private function prepareVehicleData($renewalData)
-    // {   
-    //     $vehicleData = [
-    //         'vehicle_no' => $renewalData['veh_no'],
-    //         'owner' => $renewalData['client_id'],
-    //         'branch_id' => ($renewalData['client_type_id'] == 1) ? $renewalData['branch_id'] : null,
-    //     ];
-    
-    //     $vehicleModel = new VehicleModel();
-    //     return $vehicleModel->insert($vehicleData);
-    // }
-    
-    // private function preparePtCoShareDetails($renewalData)
-    // {   
-    //     $ptCoShareDetails = [
-    //         'pt_id' => $renewalData['pt_id'],
-    //         'insurer_id' => $renewalData['insurer_id'],
-    //         'insurer_branch_id' => $renewalData['insurer_branch_id'],
-    //         'co_share_type' => 0,
-    //         'co_share_per' => 0.00,
-    //         'bp_amt' => 0.00,
-    //         'tp_amt' => 0.00,
-    //         'tep_amt' => 0.00,
-    //         'follower_policy_no' => $renewalData['policy_no'],
-    //     ];
-    
-    //     $ptCoShareDetailsModel = new PTCOShareDetailsModel();
-    //     return $ptCoShareDetailsModel->insert($ptCoShareDetails);
-    // }
-    
-    // private function prepareClientPolicy($renewalData)
-    // {
-    //     $clientPolicy = [
-    //         'client_id' => $renewalData['client_id'],
-    //         'client_branch_id' => $renewalData['branch_id'],
-    //         'policy_type_id' => $renewalData['policy_type_id'],
-    //         'insurer_id' => $renewalData['insurer_id'],
-    //         'insurer_branch_id' => $renewalData['insurer_branch_id'],
-    //         'policy_no' => $renewalData['policy_no'],
-    //         'policy_start_date' => $renewalData['date_policy_start_date'],
-    //         'policy_end_date' => $renewalData['date_policy_end_date'],
-    //         'policy_status' => 1,
-    //         'gst' => 18.00,
-    //         'cd_ac_pk' => $renewalData['cd_ac_pk'],
-    //     ];
-    
-    //     $clientPolicyModel = new ClientPolicyModel();
-    //     return $clientPolicyModel->insert($clientPolicy);
-    // }
 
     private function preparePolicyData($renewalData)
-    {   
+    {
         $data = [
-            'issuer' => $renewalData['issuer_type_id'],
-            'client_id' => $renewalData['client_id'],
+            'issuer' => $renewalData['issuer_type_id'] ?? null,
+            'client_id' => $renewalData['client_id'] ?? null,
             'client_branch_id' =>  $renewalData['branch_id'] ?? 0,
-            'vehicle_id' => $renewalData['vehicel_id'],
-            'insurer_id' => $renewalData['insurer_id'],
+            'vehicle_id' => $renewalData['vehicle_id'] ?? null,
+            'insurer_id' => $renewalData['insurer_id'] ?? null,
             'insurer_branch_id' => $renewalData['insurer_branch_id'],
             'tpa_id' => null,
             'tpa_branch_id' => null,
-            'policy_type_id' => $renewalData['policy_type_id'],
+            'policy_type_id' => $renewalData['policy_type_id'] ?? null,
             'client_policy_id' => $renewalData['client_policy_id'] ?? null,
             'issue_type' => 1,
             'source_client_policy_id' => null,
-            'policy_no' => $renewalData['policy_no'],
+            'policy_no' => $renewalData['policy_no'] ?? null,
             'cd_ac_no' => null,
             'policy_issue_date' => $renewalData['date_date_of_issue'],
             'policy_start_date' => $renewalData['date_policy_start_date'],
@@ -4471,8 +5117,8 @@ class ClientController extends AdminController
             'dependent_count' => null,
             'revenue_type' => $renewalData['revenue_type'] ?? null,
             'co_share' => 0,
-            'pre_payable_by' => 1, 
-            'bro_payable_by' => 1, 
+            'pre_payable_by' => 1,
+            'bro_payable_by' => 1,
             'tsi' => '500000',
             'status' => 'completed',
             'ct_status' => 0,
@@ -4499,39 +5145,58 @@ class ClientController extends AdminController
             'month' => '2025-02-01',
             'sales_generated_by' => null,
             'serviced_by' => null,
-            'ct_type' => 1, 
+            'ct_type' => 1,
             'ct_tran_id' => null,
             'remarks' => null,
-            'cd_ac_pk' =>$renewalData['cd_ac_pk'] ?? null,
+            'cd_ac_pk' => $renewalData['cd_ac_pk'] ?? null,
             'install_due_date' => null,
             'policy_with_corr' => 0
         ];
-                
+
         // kint::dump($data);
+        // dd($data);
         $policyTransactionModel = new PolicyTransactionModel();
         $id = $policyTransactionModel->insert($data);
         return $id;
     }
 
     private function prepareVehicleData($renewalData)
-    {   
+    {
+        $VehicleModel = new VehicleModel();
+
+        if ($renewalData['client_type_id'] == 1) {
+            $veh_no = explode(" ", $renewalData['insured'])[0] . "_veh_no";
+        } else {
+            $veh_no = $renewalData['insured'] . "_veh_no";
+        }
+
+        $vehicleData = $VehicleModel->where('owner', $renewalData['client_id'])
+        ->where('is_active', 1)
+        ->findAll();
+
+        if (!empty($vehicleData)) {
+            $increment = count($vehicleData);
+            $veh_no = $increment . "_" . $veh_no;
+        }
+
+
         $vehicleData = [
-            'vehicle_no' => $renewalData['veh_no'],
+            'vehicle_no' => $veh_no,
             'type' => null,
             'description' => null,
             'owner' => $renewalData['client_id'], // client_id
-            'branch_id' => $renewalData['client_type_id'] == 1 ? $renewalData['branch_id'] : null, // client_branch_id
+            'branch_id' => $renewalData['client_type_id'] == 1 ? $renewalData['branch_id'] : 0, // client_branch_id
             'old_owner' => null,
             'rc' => null,
         ];
-        
-        $VehicleModel = new VehicleModel();
+
+        // dd($vehicleData);
         $id = $VehicleModel->insert($vehicleData);
         return $id;
     }
 
     private function preparePtCoShareDetails($renewalData)
-    {   
+    {
         $pt_co_share_details = [
 
             'pt_id' => $renewalData['pt_id'],
@@ -4587,14 +5252,13 @@ class ClientController extends AdminController
         $PTCOShareDetailsModel = new PTCOShareDetailsModel();
         $id = $PTCOShareDetailsModel->insert($pt_co_share_details);
         return $id;
-        
     }
 
     private function prepareClientPolicy($renewalData)
     {
         $client_policy = [
             'client_id' => $renewalData['client_id'],
-            'client_branch_id' => $renewalData['branch_id'],
+            'client_branch_id' => $renewalData['branch_id'] ?? 0,
             'policy_type_id' => $renewalData['policy_type_id'],
             'insurer_id' => $renewalData['insurer_id'],
             'insurer_branch_id' => $renewalData['insurer_branch_id'],
@@ -4625,6 +5289,128 @@ class ClientController extends AdminController
         $id = $ClientPolicyModel->insert($client_policy);
         return $id;
     }
-    
 
+    private function prepareClientBranch($renewalData)
+    {
+        $branch_code = "BRANCH001";
+        $short_name = explode(" ", $renewalData['insured'])[0];
+        $unit = $short_name . " - " . $branch_code;
+
+        $clientBranchData = [
+            'client_id' => $renewalData['client_id'],
+            'branch_name' => "Branch 1",
+            'branch_code' => $branch_code,
+            'city' => null,
+            'district' => null,
+            'state' => null,
+            'pincode' => null,
+            'address1' => null,
+            'address2' => null,
+            'gst' => null,
+            'sez' => 0,
+            'is_active' => 1,
+            'units' => $unit
+        ];
+
+
+        $ClientBranchModel = new ClientBranchModel();
+        $id = $ClientBranchModel->insert($clientBranchData);
+        return $id;
+    }
+
+    private function prepareClient($renewalData)
+    {
+
+        if ($renewalData['client_type_id'] == 1) {
+            $short_name = explode(" ", $renewalData['insured'])[0];
+        } else {
+            $short_name = $renewalData['insured'];
+        }
+
+        $clientData = [
+            'client_type' => $renewalData['client_type_id'],
+            'entity_type_id' => null,
+            'client_name' => $renewalData['insured'],
+            'short_name' => $short_name,
+            'cost_center' => null,
+            'client_code' => null, // Auto-generated
+            'pan' => null,
+            'gst' => null,
+            'address1' => null,
+            'address2' => null,
+            'city' => null,
+            'state' => null,
+            'pincode' => null,
+            'is_download_btn' => 0, // Assuming a default value if not specified
+            'client_logo' => null,
+            'created_by' => null,
+            'created_at' => null, // Will be set automatically by MySQL
+            'updated_by' => null,
+            'updated_at' => null, // Will be set automatically by MySQL
+            'is_active' => 1, // Default value is 1
+            'common_mails' => null,
+            'hr_mails' => null,
+            'mail_domain' => null,
+            'reply_to' => null,
+            'dob' => null,
+            'aadhar' => null,
+            'reference' => null,
+            'phone' => null,
+            'email' => null,
+            'addon_subheading' => null
+        ];
+
+
+
+        $ClientModel = new ClientModel();
+        $id = $ClientModel->insert($clientData);
+        return $id;
+    }
+
+    private function prepareInsurerBranch($renewalData)
+    {
+
+        $insurerBranchData = [
+            'insurer_id' =>  $renewalData['insurer_id'],
+            'branch_name' =>  $renewalData['insurer_branch'],
+            'branch_code' =>  $renewalData['insurer_branch'],
+            'address1' => null,
+            'address2' => null,
+            'city' => null,
+            'district' => null,
+            'state' => null,
+            'pincode' => null,
+        ];
+
+
+
+        $InsurerBranchModel = new InsurerBranchModel();
+        $id = $InsurerBranchModel->insert($insurerBranchData);
+        return $id;
+    }
+
+    private function prepareinsurer($renewalData)
+    {
+
+        $short_name1 = explode(" ", $renewalData['insurer_name'])[0];
+        $short_name2 = explode(" ", $renewalData['insurer_name'])[1];
+        $short_name = $short_name1 . ' ' . $short_name2;
+
+        $insurerData = [
+            'type' => "pvt",
+            'category' => "general",
+            'addition_add_day' => 0,
+            'deletion_add_day' => 0,
+            'name' => $renewalData['insurer_name'],
+            'short_name' =>  $short_name,
+            'insurer_logo' => null,
+            'is_multi_event' => 0, // Default is 0
+        ];
+
+        $InsurerModel = new InsurerModel();
+        $id = $InsurerModel->insert($insurerData);
+        return $id;
+    }
+    
+    
 }
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index 8ee7765d..d1a48afb 100755
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -100,16 +100,52 @@ class DashboardController extends AdminController
 
         $data = [];
 
-        $results = $this->clientModel->select('clients.id as client_id, clients.client_name, clients.short_name,
-                                              client_branch.id as client_branch_id, client_branch.branch_name, 
-                                              client_branch.branch_code, employees.id as employee_id, 
-                                              employees.name as employee_name, employees.relationship,
-                                              employees.emp_code, employees.emp_status, auth_history.user_type, client_policy.policy_type_id, client_policy.id as client_policy_id')
-        ->join('client_branch', 'clients.id = client_branch.client_id', 'left')
-        ->join('client_policy', 'client_branch.id = client_policy.client_branch_id', 'left')
-        ->join('employees', 'client_branch.id = employees.client_branch_id', 'left')
-        ->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left')
-        ->findAll();
+        $db = db_connect();
+        $sql = "SELECT 
+                    clients.id AS client_id, 
+                    clients.client_name, 
+                    clients.short_name,
+                    client_branch.id AS client_branch_id, 
+                    client_branch.branch_name, 
+                    client_branch.branch_code,
+                    
+                    COUNT(employees.id) AS total_employees,  
+                    SUM(CASE WHEN employees.emp_status = 'draft' THEN 1 ELSE 0 END) AS draft_count,  
+                    SUM(CASE WHEN employees.emp_status IN ('enrolled', 'active') THEN 1 ELSE 0 END) AS enrolled_count,  
+
+                    SUM(CASE WHEN auth_history.user_id IS NOT NULL THEN 1 ELSE 0 END) AS logged_in_count,  
+                    SUM(CASE WHEN auth_history.user_id IS NULL THEN 1 ELSE 0 END) AS not_logged_in_count,
+
+                    CASE 
+                        WHEN EXISTS (
+                            SELECT 1 FROM client_policy 
+                            WHERE client_policy.client_branch_id = client_branch.id 
+                            AND client_policy.is_active = 1 
+                            AND client_policy.open_for_enrollment = 1
+                        ) THEN 1 
+                        ELSE 0 
+                    END AS open_or_close_enrollment  
+
+                FROM clients
+                LEFT JOIN client_branch ON clients.id = client_branch.client_id
+                LEFT JOIN employees ON client_branch.id = employees.client_branch_id
+                LEFT JOIN (
+                    SELECT user_id, user_type 
+                    FROM auth_history 
+                    WHERE user_type = 'employee' 
+                    GROUP BY user_id
+                ) AS auth_history ON employees.id = auth_history.user_id
+
+                WHERE employees.relationship = 'Self'
+                AND employees.emp_status IN ('draft', 'enrolled', 'active')
+                AND employees.is_active = 1
+                AND clients.is_active = 1
+                AND client_branch.is_active = 1
+
+                GROUP BY clients.id, client_branch.id";
+
+        $query = $db->query($sql);
+        $results = $query->getResultArray();
 
         $pendingActionsController = new PendingActionsController;
         $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
@@ -118,94 +154,11 @@ class DashboardController extends AdminController
         $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
         $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
 
-        $groupedData = [];
 
-        foreach ($results as $row) {
-            $clientId = $row['client_id'];
-            $clientName = $row['client_name'];
-            $shortName = $row['short_name'];
-            $branchId = $row['client_branch_id'];
-            $branchName = $row['branch_name'];
-            $branchCode = $row['branch_code'];
-
-            $clientPolicyId = $row['client_policy_id'];
-            $policyTypeId = $row['policy_type_id'];
-            $employeeId = '';
-            if ($employeeId != $row['employee_id']) {
-                $employeeId = $row['employee_id'];
-            } else {
-                $employeeId = null;
-            }
-            $employeeName = $row['employee_name'];
-            $employeeRelationship = $row['relationship'];
-            $employeeEmpCode =  $row['emp_code'];
-            $employeeEmpStatus = $row['emp_status'];
-            $employeeUserType = $row['user_type'];
-
-            // Initialize the client entry if it doesn't exist
-            if (!isset($groupedData[$clientId])) {
-                $groupedData[$clientId] = [
-                    'client_id' => $clientId,
-                    'client_name' => $clientName,
-                    'short_name' => $shortName,
-                    'branches' => []
-                ];
-            }
-
-            // Initialize the branch entry if it doesn't exist
-            if (!isset($groupedData[$clientId]['branches'][$branchId])) {
-                $groupedData[$clientId]['branches'][$branchId] = [
-                    'client_branch_id' => $branchId,
-                    'branch_name' => $branchName,
-                    'branch_code' => $branchCode,
-                    'emp_login' => 0,
-                    'emp_enroll' => 0,
-                    'client_policies' => [],
-                    'employees' => []
-                ];
-            }
-
-            // Add the client policy to the branch's policies list if it exists, not already added, and policyTypeId is not equal to 1
-            if ($clientPolicyId !== null && $policyTypeId != 1 && !in_array(['client_policy_id' => $clientPolicyId, 'policy_type_id' => $policyTypeId], $groupedData[$clientId]['branches'][$branchId]['client_policies'])) {
-                $groupedData[$clientId]['branches'][$branchId]['client_policies'][] = [
-                    'client_policy_id' => $clientPolicyId,
-                    'policy_type_id' => $policyTypeId
-                ];
-            }
-
-            // Append employee error to the branch's employees list if relationship is 'Self' and not already added
-            $employeeKey = $employeeId . '-' . $employeeName; // unique key to identify an employee
-            if ($employeeId !== null && $employeeRelationship == 'Self' && !isset($groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey])) {
-                $groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey] = [
-                    'employee_id' => $employeeId,
-                    'employee_name' => $employeeName,
-                    'relationship' => $employeeRelationship,
-                    'emp_code' => $employeeEmpCode,
-                    'emp_status' => $employeeEmpStatus,
-                    'user_type' => $employeeUserType
-                ];
-                if (!empty($employeeUserType)) {
-                    $groupedData[$clientId]['branches'][$branchId]['emp_login']++;
-                }
-
-                // Increment emp_enroll if emp_status is not 'draft'
-                if ($employeeEmpStatus !== 'draft') {
-                    $groupedData[$clientId]['branches'][$branchId]['emp_enroll']++;
-                }
-            }
-        }
-
-        // Re-index the arrays to match the expected structure
-        foreach ($groupedData as &$client) {
-            foreach ($client['branches'] as &$branch) {
-                $branch['employees'] = array_values($branch['employees']);
-            }
-            $client['branches'] = array_values($client['branches']);
-        }
-
-        $data['client_branch_emp_list'] = $groupedData;
+        $data['client_branch_emp_list'] = $results;
         $session = \Config\Services::session();
-        $session->set('enrollment_data', json_encode($data));
+        $session->set('enrollment_data', json_encode($data));  
+        
         // echo "
";
         $data['pendingActionsData'] = $pendingActionsData;
         $data['businessTeamCount'] = count($businessTeamData) ?? 0;
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 856ef118..76d44b73 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -975,7 +975,7 @@ class EmpDataServiceController extends BaseController
                 $balance = $this->CDMasterModel
                     ->where('client_id', $export_data['client_id'])
                     ->where('insurer_id', $policy_details['insurer_id'])
-                    ->where('cd_ac_no', $policy_details['cd_ac_no'])
+                    ->where('id', $policy_details['cd_ac_pk'])
                     ->first();
 
                 $cash_balance['balance'] = $balance['opening_bal'];
@@ -1011,14 +1011,33 @@ class EmpDataServiceController extends BaseController
         // dd($inceptionData, $additionData, $dependentAdditionData, $correctionData, $enhancementData,  $deletionData, $mergedData);
 
 
-        $template_json = $this->clientPolicyModel
-            ->select('insurer_excel_export_template.jsoncolumns')
-            ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id')
-            ->where('client_policy.id', $export_data['client_policy_id'])
-            ->where('insurer_excel_export_template.event_name', 'all')
-            ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024
-            ->where('insurer_excel_export_template.type_name', $export_data['actions'])
-            ->first();
+        // $template_json = $this->clientPolicyModel
+        //     ->select('insurer_excel_export_template.jsoncolumns')
+        //     ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = client_policy.insurer_id and insurer_excel_export_template.policy_type_id = client_policy.policy_type_id')
+        //     ->where('client_policy.id', $export_data['client_policy_id'])
+        //     ->where('insurer_excel_export_template.event_name', 'all')
+        //     ->where('insurer_excel_export_template.is_active', 1) //Live issue changes 17-10-2024
+        //     ->where('insurer_excel_export_template.type_name', $export_data['actions'])
+        //     ->first();
+
+        $sql = "
+            SELECT `insurer_excel_export_template`.`jsoncolumns`
+            FROM `client_policy`
+            JOIN `insurer_excel_export_template` 
+            ON `insurer_excel_export_template`.`insurer_id` = `client_policy`.`insurer_id`
+            AND `insurer_excel_export_template`.`policy_type_id` = 
+                CASE 
+                    WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2
+                    ELSE `client_policy`.`policy_type_id`
+                END
+            WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."'
+            AND `insurer_excel_export_template`.`event_name` = 'all'
+            AND `insurer_excel_export_template`.`is_active` = 1
+            AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."'
+            LIMIT 1";
+        
+        $query = db_connect()->query($sql);
+        $template_json = $query->getRowArray();
 
 
         if(!empty($template_json) && $template_json != null){
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index e81684f7..6857487a 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -25,6 +25,8 @@ use App\Models\InsurerExcelExportTemplateModel;
 use App\Models\InsurerModel;
 use App\Models\ClientDepositModel;
 use App\Models\PolicyPremium2Model;
+use App\Models\AuditHistoryModel;
+use App\Models\UserModel;
 
 
 use App\Controllers\Jobs;
@@ -64,6 +66,8 @@ class EmployeeController extends AdminController
     protected $insurerModel;
     protected $cashDepositModel;
     protected $PolicyPremium2Model;
+    protected $auditHistory;
+    protected $userModel;
 
     public function __construct()
     {
@@ -84,6 +88,8 @@ class EmployeeController extends AdminController
         $this->insurerModel = new InsurerModel();
         $this->cashDepositModel = new ClientDepositModel();
         $this->PolicyPremium2Model = new PolicyPremium2Model();
+        $this->auditHistory = new AuditHistoryModel();
+        $this->userModel = new userModel();
     }
 
     public function list()
@@ -372,7 +378,7 @@ class EmployeeController extends AdminController
         ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
         ->join('clients', 'clients.id = client_policy.client_id')
         ->orderBy('batch_files.id', 'desc')
-        ->limit(100)
+        ->limit(1000)
         ->find();
 
 
@@ -1295,7 +1301,7 @@ class EmployeeController extends AdminController
             ->orderBy('id', 'desc')            
             ->first();
 
-        // print_r($file); die;
+        // dd($cd_tranction, db_connect()->getLastQuery());
         if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment' || $file['action'] == 'missed_inception') {
 
 
@@ -1452,6 +1458,7 @@ class EmployeeController extends AdminController
                 ->get()
                 ->getResult();
 
+            // dd($res);
             // print_r($this->empEndorsementModel->getLastQuery());
             // echo $res[0]->count;die();
 
@@ -1461,14 +1468,15 @@ class EmployeeController extends AdminController
                 $this->myLogger->logme('error', 'Event Type : -- {data} --', ['data' => $file['action']]);
 
                 $transaction_type = 'Credit';
-                $cd_amount = $cd_tranction['amount'];
+                $cd_amount = 0;
 
-                if($file['action'] == 'deletion'){
+                if($file['action'] == 'deletion' && $res[0]->count > 0){
+                    
                     $transaction_type = 'Debit';
                      //get cd amount for the particular file id to reverse entry to the cash deposite for only deletion
                     $cd_amount_total = $this->employeePolicyModel->getDeletionDataForTruncated($file['id']);
                     $totalSum = array_sum(array_column($cd_amount_total, 'total'));
-                    $cd_amount =  $totalSum;  
+                    $cd_amount =  $totalSum ?? 0;  
                     
                     $this->myLogger->logme('error', 'Deletion CD Amount : {data}', ['data' => $cd_amount]);
                 }
@@ -1485,7 +1493,7 @@ class EmployeeController extends AdminController
                 $this->myLogger->logme('error', 'emp_endorsement table updated');
 
                 //STEP 2:
-                if($file['action'] == 'deletion') {
+                if($file['action'] == 'deletion' && $res[0]->count > 0) {
                     //update the employee policy table reverse the data
                     $this->employeePolicyModel->updateEmployeePolicyTruncateReverse($file_id);
                     $this->myLogger->logme('error', 'employee_polices table updated for deletion');
@@ -1501,7 +1509,7 @@ class EmployeeController extends AdminController
                 $this->myLogger->logme('error', 'files table updated');
 
 
-                if($cd_tranction && $file['action'] != 'correction'){
+                if(!empty($cd_amount) && $file['action'] != 'correction'){
                     
                     $cd_data = [
                         'amount' => $cd_amount,
@@ -1605,9 +1613,8 @@ class EmployeeController extends AdminController
                     $db = db_connect();
                     $query = "
                                 UPDATE employee_polices 
-                                JOIN employees ON employees.id = employee_polices.employee_id
                                 SET employee_polices.status = 'truncated', employee_polices.is_active = 0 
-                                WHERE employees.file_id = $file_id
+                                WHERE employee_polices.file_id = $file_id
                             ";
                 
                     $db->query($query);
@@ -2726,4 +2733,46 @@ class EmployeeController extends AdminController
         }
     }
 
+    public function getEmpHistory(){
+
+        $emp_id = $this->request->getPost('emp_id');
+
+        $data['emp_history'] = $this->auditHistory->select('field_name,old_value,new_value,created_by,created_at')->where('pk',$emp_id)->where('table_name','employees')->orderBy('created_at', 'DESC')->findAll();
+
+        foreach ($data['emp_history'] as &$emp_history) { 
+            $emp_history['field_name'] = $this->formatFieldName($emp_history['field_name']);
+            $user = $emp_history['created_by'];
+            if ($user != null && $user != ''){
+                $userData = $this->userModel->select('first_name, last_name')->where('id', $user)->where('is_active', 1)->first();
+                $emp_history['created_by'] = ucwords($userData['first_name'] . ' ' . $userData['last_name']);
+            }else{
+                $emp_history['created_by'] = '-';
+            }
+
+            $emp_history['created_at'] =  date("d-m-Y H:i:s", strtotime($emp_history['created_at']));
+        }
+        unset($emp_history); 
+        
+        $emp_pol_pk = $this->employeePolicyModel->select('id')->where('employee_id',$emp_id)->first()['id'];
+        $data['emp_pol_history'] = $this->auditHistory->select('field_name,old_value,new_value,created_by,created_at')->where('pk',$emp_pol_pk)->where('table_name','employee_polices')->findAll();
+
+        return $this->respond(['status' => true, 'data' => $data],200);
+
+        
+    }   
+
+    public function formatFieldName($unformattedString){
+
+        if (str_contains($unformattedString, '_')) {
+            $data = str_replace('_', ' ', $unformattedString);
+        }else{
+            $data = $unformattedString;
+        }
+        
+        $format = ucwords($data);
+
+        return $format;
+
+    }
+
 }
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 0b26b442..94a28fb6 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -2502,7 +2502,7 @@ class EmployeeRestController extends AdminController
     function getEmployeeActiveOrInactivePolicy()
     {
         if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
-        $ClientPolicyData =  $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url')
+        $ClientPolicyData =  $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name,tpa.network_hospitals as network_hospitals_url,  policy_type.long_name as policy_long_name')
                                                     ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
                                                     ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
                                                     ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
@@ -2534,17 +2534,34 @@ class EmployeeRestController extends AdminController
 
 
 
-                $terms = json_decode($ClientPolicyValue['policy_terms']);
+               
 
                 if($ClientPolicyValue['policy_type_id'] == 1)
                 { 
-                    $data['policy_terms'] =  $this->policyTermsFiter($terms,'gpa'); 
-                    $data['department_id'] = 3;
-                }else{ 
-                    $data['policy_terms'] =  $this->policyTermsFiter($terms,'gmc'); 
-                    $data['department_id'] = 4;
+                    $policyGroup = 'gpa';
+                    $data['ticket_type_id'] = 2;
+                }else if($ClientPolicyValue['policy_type_id'] == 6)
+                { 
+                    $policyGroup = 'gpa';
+                    $data['ticket_type_id'] = 3;
+                }else if($ClientPolicyValue['policy_type_id'] == 7)
+                { 
+                    $policyGroup = 'gpa';
+                    $data['ticket_type_id'] = 4;
+                }else
+                {
+                    $policyGroup = 'gmc';
+                    $data['ticket_type_id'] = 1;
                 }
-            
+
+                $terms = json_decode($ClientPolicyValue['policy_terms'] , true);
+                $data['policy_terms'] = isset($terms['enrollment_display_key']) 
+                && !empty($terms['enrollment_display_key']) 
+                ? $terms['enrollment_display_key'] 
+                : $this->policyTermsFiter($terms, $policyGroup);
+                $terms = json_decode($ClientPolicyValue['policy_terms']);
+                
+
                 $data['client_id'] = $ClientPolicyValue['client_id'];
                 $data['client_policy_id'] = $ClientPolicyValue['id'];
                 $data['policy_name'] = $ClientPolicyValue['policy_type'];
@@ -2555,13 +2572,15 @@ class EmployeeRestController extends AdminController
                 $data['network_hospitals_url'] = $ClientPolicyValue['network_hospitals_url'];
                 $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']);
                 $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']);
+                $data['heading'] = $ClientPolicyValue['policy_long_name'];
                 // $data['policy_terms'] = $terms;
 
-                if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else
-                if($ClientPolicyValue['policy_type_id'] == 2){ $data['heading'] = 'Group Medical Coverage'; }else
-                if($ClientPolicyValue['policy_type_id'] == 3){ $data['heading'] = 'Group Medical Coverage - Parents'; }else
-                if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else
-                if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; }
+                // if($ClientPolicyValue['policy_type_id'] == 1){ $data['heading'] = 'Group Personal Accident Coverage'; }else
+                // if($ClientPolicyValue['policy_type_id'] == 2){ $data['heading'] = 'Group Medical Coverage'; }else
+                // if($ClientPolicyValue['policy_type_id'] == 3){ $data['heading'] = 'Group Medical Coverage - Parents'; }else
+                // if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else
+                // if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; }else
+                // if($ClientPolicyValue['policy_type_id'] == 7){ $data['heading'] = 'Group Term Life Insurance'; }
 
                 if($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7)
                 { 
@@ -2718,9 +2737,7 @@ class EmployeeRestController extends AdminController
         }
 
 
-       
-    
-    return $finalarray;
+        return $finalarray;
         
     }
 
@@ -3101,90 +3118,195 @@ class EmployeeRestController extends AdminController
         return false;
 
     }
+
     //Get Data from post for inserting ticket and message
     public function initiateClaim()
     {
 
         $received_data = $this->request->getPost();
+        // print_r($received_data); die;
         $employee_id = $received_data['emp_id'];
         $client_policy_id = $received_data['client_policy_id'];
         $insured_emp_id = $received_data['insured_emp_id'];
 
-        $sql = "select cp.policy_type_id as ticket_type_id,
-        cl_rm.user_id as acm_id,
-        cp.insurer_id as insurer_id,
-        cp.tpa_id as tpa_id,
-        emp.client_id ,
-        emp.id as emp_id,
-        emp_pol.uhid as policy_no,
-        emp.emp_code,
-        emp_pol.tpa_id as tpa_no,
-        emp.name as emp_name,
-        emp.email_corporate as emp_mail,
-        emp.mobile as emp_mobile,
-        empl.id as insured_emp_id,
-        empl.name as insured_name,
-        empl.relationship
+        $sql = "
+            select 
+                cp.policy_type_id,
+                cl_rm.user_id as acm_id,
+                cp.insurer_id as insurer_id,
+                cp.tpa_id as tpa_id,
+                emp.client_id ,
+                emp.id as emp_id,
+                emp_pol.uhid as policy_no,
+                emp.emp_code,
+                emp_pol.tpa_id as tpa_no,
+                emp.name as emp_name,
+                emp.email_corporate as emp_mail,
+                emp.mobile as emp_mobile,
+                empl.id as insured_emp_id,
+                empl.name as insured_name,
+                empl.relationship,
+                
+                CASE 
+                    WHEN cp.policy_type_id IN (2, 3, 4, 5) THEN 1
+                    WHEN cp.policy_type_id = 1 THEN 2
+                    WHEN cp.policy_type_id = 6 THEN 3
+                    WHEN cp.policy_type_id = 7 THEN 4
+                    ELSE NULL 
+                END AS ticket_type_id
 
+            from employees emp 
 
-
-        from employees emp 
-
-        left join employees empl on empl.id = $insured_emp_id and empl.is_active = 1 and empl.emp_status = 'active'
-        left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = $client_policy_id and emp_pol.is_active = 1 
-        left join client_policy cp on cp.id = emp_pol.client_policy_id and cp.is_active = 1
-        left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3 
+            left join employees empl on empl.id = $insured_emp_id and empl.is_active = 1 and empl.emp_status = 'active'
+            left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = $client_policy_id and emp_pol.is_active = 1 
+            left join client_policy cp on cp.id = emp_pol.client_policy_id and cp.is_active = 1
+            left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3 
 
         where emp.id = $employee_id and emp.is_active = 1 and emp.emp_status = 'active'
         limit 1 ";
 
-        $fetchData = $this->employeeModel->query($sql)->getResultArray()[0];
-        $fetchData['claim_status_id'] = $this->claimStatusModel->select('id')->where('ticket_type', $fetchData['ticket_type_id'])->first()['id'];
-        $fetchData['priority'] = 1;
-        $fetchData['mode_of_intimation'] = 1;
-        $fetchData['hospital_name'] = $received_data['hospital_name'];
+        $emp_ticket_data = $this->employeeModel->query($sql)->getResultArray();
+        // print_r(db_connect()->getLastQuery()); die;
 
-        $insert_status = $this->ticketMaster->insert($fetchData);
-        $ticket_id = $this->ticketMaster->insertID();
+        if(!empty($emp_ticket_data)){
 
-        if ($insert_status && !empty($ticket_id)) {
-            $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
-            if (gettype($mail_sent_status) == 'array') {
-                $message = 'Claim Iniated Successfully';
-                return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
-            } else {
-                $mail_sent_status = json_decode($mail_sent_status);
-            }
-            // dd(gettype($mail_sent_status));
+            $fetchData = $emp_ticket_data[0];
+            $fetchData['claim_status_id'] =  $this->claimStatusModel
+                ->select('id')
+                ->where('ticket_type', $fetchData['ticket_type_id'])
+                ->orderBy('id', 'asc')
+                ->first()['id'];
 
-            if ($mail_sent_status->status == 'success') {
-                $sent_message_data['ticket_id'] = $ticket_id;
-                $sent_message_data['sender'] = 'staff';
-                $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail;
-                $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
-                $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+            $fetchData['priority'] = 1;
+            $fetchData['mode_of_intimation'] = 1;
+            $fetchData = array_merge($fetchData, $received_data);
 
-                $message_insert_status = $this->ticketMessage->insert($sent_message_data);
+            // print_r($fetchData); die;
+            $insert_status = $this->ticketMaster->insert($fetchData);
+            $ticket_id = $this->ticketMaster->insertID();
 
-                if ($message_insert_status) {
-                    $message = 'Claim Initiated Successfully';
+            if ($insert_status && !empty($ticket_id)) {
+
+                $messagesData = [
+                    'ticket_id' => $ticket_id ?? null,
+                    'sender' => 'user',
+                    'claim_status' => $fetchData['claim_status_id'] ?? null,
+                    'emp_mail' => $fetchData['emp_mail'] ?? null,
+                    'mail_subject' => $fetchData['subject'] ?? null,
+                    'mail_content' => $fetchData['message'] ?? null,
+                ];
+
+                if (!empty($messagesData['ticket_id'])) {
+                    $TicketMessageModel = new TicketMessageModel();
+                    $TicketMessageModel->insert($messagesData);
+                }
+
+                $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id));
+                if (gettype($mail_sent_status) == 'array') {
+                    $message = 'Claim Iniated Successfully';
                     return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
                 } else {
-                    $message = 'Claim Initiated, Mail Sent Successfully';
-                    $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
+                    $mail_sent_status = json_decode($mail_sent_status);
+                }
+                // dd(gettype($mail_sent_status));
+
+                if ($mail_sent_status->status == 'success') {
+                    $sent_message_data['ticket_id'] = $ticket_id;
+                    $sent_message_data['sender'] = 'staff';
+                    $sent_message_data['emp_mail'] = $mail_sent_status->data->params->mail;
+                    $sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
+                    $sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
+
+                    $message_insert_status = $this->ticketMessage->insert($sent_message_data);
+
+                    if ($message_insert_status) {
+                        $message = 'Claim Initiated Successfully';
+                        return $this->respond(['status' => true, 'code' => 200, 'message' => $message], 200);
+                    } else {
+                        $message = 'Claim Initiated, Mail Sent Successfully';
+                        $this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
+                        return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
+                    }
+                } else {
+
+                    $message = 'Claim Initiated, Failed to send Mail ';
+                    $this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
                     return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
                 }
             } else {
-
-                $message = 'Claim Initiated, Failed to send Mail ';
-                $this->myLogger->logme('error', "Claim initiated, Failed to send Mail :$ticket_id ");
+                $message = 'Something Went Wrong';
                 return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
             }
-        } else {
-            $message = 'Something Went Wrong';
-            return $this->respond(['status' => false, 'code' => 400, 'message' => $message], 200);
+
+        }else{
+            return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'The employee is not active.'])->setStatusCode(404);
         }
     }
-    
+
+    //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);
+    }
+
+    //ticket data
+    public function get_ticket_data()
+    {
+        $priorityType = $this->ticketController->priorityType;
+        $modeOFIntimate = $this->ticketController->modeOFIntimate;
+        $claimType = $this->ticketController->claimType;
+        $relationshipType = $this->ticketController->relationshipType;
+        $ticketTypeArray = $this->ticketController->ticketType;
+
+
+        $emp_id = $this->request->getGet('emp_id');
+        $ticket_type = $this->request->getGet('ticket_type') ?? null;
+        $ticket_id = $this->request->getGet('ticket_id') ?? null;
+        // dd($emp_id);
+
+        if (empty($emp_id)) {
+            return $this->response->setJSON(['status' => false, 'code' => 200, 'message' => 'emp_id is required.'])->setStatusCode(404);
+        }
+
+        $TicketMasterModel = new TicketMasterModel();
+        $ticket_data = $TicketMasterModel->get_ticket_data($emp_id, $ticket_type, $ticket_id);
+
+        if (!empty($ticket_data)) {
+
+            $client_claim_status = [
+                'Received' => [1, 2, 3, 4, 15, 16, 17, 18, 25, 26, 27, 28, 35, 36, 37, 38],
+                'Rejected' => [8, 49, 55, 60],
+                'Cancelled' => [13, 47, 53, 58],
+                'Returned' => [14, 48, 54, 59],
+                'Closed' => [12, 22, 32, 42],
+                'Approved' => [9, 20, 30, 40],
+                'Settled' => [11, 24, 34],
+                'Under Process' => [5, 6, 7, 10, 19, 23, 45, 50, 29, 33, 51, 39, 43, 56],
+            ];
+
+            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
+                    }
+                }
+                $ticket_data[$key]['priority_type'] = $priorityType[$value['priority']] ?? null;
+                $ticket_data[$key]['mode_of_intimate_type'] = $modeOFIntimate[$value['mode_of_intimation']] ?? null;
+                $ticket_data[$key]['relationship_type'] = ucfirst($value['relationship']) ?? null;
+                $claimPrimaryTypey = "1";
+                if (in_array($value['claim_type'], [2, 3, 4])) {
+                    $claimPrimaryTypey = "2";
+                }
+                $ticket_data[$key]['claim_type_value'] = $claimType[$claimPrimaryTypey][$value['claim_type']] ?? null;  
+                $ticket_data[$key]['ticket_policy_type'] = $ticketTypeArray[$value['ticket_type_id']] ?? null;
+
+            }
+        }
+
+        return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200);
+    }
 
 }
\ No newline at end of file
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 4c305c2e..61e0af4a 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1648,7 +1648,7 @@ class EmployeeServiceController extends AdminController
                                     // echo 'insert emp';
                                 }
                                 else
-                                {
+                                {   
                                     $value['emp_status'] = 'active';
                                     $value['created_by'] = $file['created_by'];
                                     $value['client_branch_id'] = $file['client_branch_id'];
@@ -2057,6 +2057,8 @@ public function getFileMetaDataByFileId($file_id, $status = 'success'){
                             }
                             $value['family_floater_key'] = $relation;
 
+                            // dd($value['family_floater_key']);
+
                             $policy_data['basic_cover_si'] = $row[9];
                             $policy_data['date_coverage'] = $row[13] != "" && $row[13] != null ? change_date_format($row[13],'d-M-Y','Y-m-d') : null;
                             $policy_data['client_policy_id'] = $file['policy_id'];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 0a9c444c..f0f1cc7b 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -12,6 +12,8 @@ use PhpOffice\PhpSpreadsheet\Style\Border;
 use PhpOffice\PhpSpreadsheet\Style\Alignment;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
 
 use App\Models\UserModel;
 use App\Models\ClientModel;
@@ -31,7 +33,7 @@ use App\Helpers\MailHelper;
 use App\Helpers\ExcelMergeHelper;
 use App\Helpers\ExcelSanitizeHelper;
 use Google\Service\CloudSearch\PushItem;
-use Kint;
+use Kint\Kint;
 
 use App\Controllers\Jobs;
 use App\Controllers\JobWorker;
@@ -64,6 +66,9 @@ class LeadsController extends BaseController
     protected $clientType;
     protected $leadType;
     protected $leadsStatus;
+    protected $claim_type_for_gpa;
+    protected $cause_of_death;
+
 
     public function __construct()
     {
@@ -96,6 +101,19 @@ class LeadsController extends BaseController
             'completed_with_corrections' => 'Completed with Corrections',
             'completed_without_corrections' => 'Completed w/o Corrections',
         ];
+        $this->claim_type_for_gpa = [
+            'accident_death' => 'Accident Death',
+            'permanent_total_disablement' => 'Permanent Total Disablement',
+            'permanent_partial_disablement' => 'Permanent Partial Disablement',
+            'temporary_total_disablement_benefit' => 'Temporary Total Disablement benefit'
+        ];
+
+        $this->cause_of_death = [
+            'natural_death' => 'Natural Death',
+            'suicide'       => 'Suicide',
+            'accident'      => 'Accident'
+        ];
+
     }
 
     public function viewLeadsList()
@@ -107,6 +125,7 @@ class LeadsController extends BaseController
         // $d = $this->calculateMembersDemography(['lead_id' => 24]);
         //$this->mergeQuoteExcelFileWithMembersListExcelFile(24, 1, $propsal_and_insurer = null);
         // dd($d);
+            
         $data['page_name'] = 'Leads';
 
         // Set basic data
@@ -122,7 +141,7 @@ class LeadsController extends BaseController
         // Fetch insurer and TPA branch data
         $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
         $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
-
+        // print_r($data['tpa']);die();
         // Fetch sales team members who are active in team 5
         $data['salse_team'] = $this->userModel
             ->select('user_profiles.*')
@@ -133,12 +152,31 @@ class LeadsController extends BaseController
             ->findAll();
 
         // dd($data);
+        $data['lastFiveYears'] = $this->getLastFiveFinancialYears();
+        $data['gpaClaimType'] = $this->claim_type_for_gpa;
+        $data['causeOfDeath'] = $this->cause_of_death;
+        // dd($lastFiveYears);        
+        if ($this->request->is('get')) {
+            // Fetch leads data
+            $data   ['lead_data_list'] = $this->leadsModel->getLeadDataForLising();
+            // Load layout and pass data
+            $this->loadLayout('lead_filter', $data);
+        }else{
 
-        // Fetch leads data
-        $data   ['lead_data_list'] = $this->leadsModel->getLeadDataForLising();
-        
-        // Load layout and pass data
-        $this->loadLayout('leads_list', $data);
+            $search_data = $this->request->getPost();
+            // print_r($search_data); 
+
+            $where = [];
+            foreach ($search_data as $search_objects => $key) {
+                if ($key != null && $key != '' && $key != 0) {
+                    $where[$search_objects] = $key;
+                }
+            }
+            
+            $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising($where);
+            $html = view('leads_list', $data);
+            return $this->respond(['status' => true, 'html' => $html], 200);
+        }
     }
 
     public function createLead()
@@ -198,6 +236,8 @@ class LeadsController extends BaseController
             // Separate the insurer and insurer branch, handle missing or invalid data
             if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) {
                 list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]);
+                
+            }else{
                 $insurer_branch_id = 0;
                 $insurer_id = 0;
             }
@@ -253,7 +293,18 @@ class LeadsController extends BaseController
 
             $last_3_years_claims = null;
             if($value != 2){
-                $last_3_years_claims = $data['finyear'];
+                $last_3_years_claims = [];
+                $finyear = json_decode($data['finyear']);
+
+                foreach ($finyear as $year){
+                    $received_policy_type = ($year->finyear[0]->policy_type);
+                    if ($value == $received_policy_type){
+                        array_push($last_3_years_claims,$year);
+                    }else{
+                        continue;
+                    }
+                }
+                $last_3_years_claims = json_encode($last_3_years_claims);
             }
                         
             $processedData[] = [
@@ -321,7 +372,7 @@ class LeadsController extends BaseController
                 'notes'                  => $data['notes'] ?? null,
             ];
         }
-
+        // print_r($processedData);die();
         return $processedData;
     }
 
@@ -418,7 +469,9 @@ class LeadsController extends BaseController
                 ->where('lead_id', $id)
                 // ->where('type', $type)
                 ->where('is_active', 1)
+                ->orderBy('id', 'desc')
                 ->first();
+        // dd($data);
 
         $data['rfq_count'] = $this->RFQModel
                 ->where('lead_id', $id)
@@ -436,8 +489,15 @@ class LeadsController extends BaseController
 
         $data['lead_id'] = $id;
         $lead_data = $this->leadsModel
-                ->select('leads.*, policy_type.question_json, policy_type.policy_type')
+                ->select('
+                    leads.*, 
+                    policy_type.question_json, 
+                    policy_type.policy_type,
+                    policy_type.long_name, 
+                    user_profiles.email as created_person_email
+                ')
                 ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+                ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left')
                 ->where('leads.id', $id)
                 ->where('leads.is_active', 1)
                 ->first();
@@ -455,7 +515,21 @@ class LeadsController extends BaseController
         $data['userList'] = $this->userModel->getUserListForRFQ();
         $data['lead_data'] = $lead_data;
 
-        $data['mail_content'] = $this->transformMailContent($id);
+        $mail_content = "
+            

Dear Sir,

+

Greetings From Nhance India!

+

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

+

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

+

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

+

Thank You!

+ "; + + + $subject = "{{CLIENT_NAME}} _ {{POLICY_TYPE}} _ {{RFQ_OR_QCR}} _ {{POLICY_YEAR}}"; + + $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); + $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); + // dd($data); $this->loadLayout('view_rfq.php', $data); @@ -574,13 +648,13 @@ class LeadsController extends BaseController public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); - + // dd($rfq_data, $lead_id, $type, $propsal_and_insurer); // print_r($propsal_and_insurer); die; - if($rfq_data['lead_type'] == 1){ + if ($rfq_data['lead_type'] == 1) { - if($rfq_data['policy_type_id'] == 2){ + if ($rfq_data['policy_type_id'] == 2) { $lead_data = [ 'Insured' => $rfq_data['client_name'], @@ -590,23 +664,22 @@ class LeadsController extends BaseController 'No of Dependents' => $rfq_data['incept_dept_count'], 'Total Lives' => $rfq_data['incept_no_of_lives'], - 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])), 'Policy Run Days' => $rfq_data['policy_run_days'], ]; - }else if($rfq_data['policy_type_id'] == 1){ + } else if ($rfq_data['policy_type_id'] == 1) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'No of Employees at Inception' => $rfq_data['incept_emp_count'], 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], - 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])), 'Policy Status' => $rfq_data['status'], 'Existing Insurer' => $rfq_data['insurer_name'], 'TPA ' => $rfq_data['tpa_name'], ]; } - - }else{ - if($rfq_data['policy_type_id'] == 2){ + } else { + if ($rfq_data['policy_type_id'] == 2) { $lead_data = [ 'Insured' => $rfq_data['client_name'], @@ -624,7 +697,7 @@ class LeadsController extends BaseController 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], - 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Period of Insurance ' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])), 'Policy Run Days' => $rfq_data['policy_run_days'], 'Inception Premium' => $rfq_data['premium_at_inception'], 'Premium as on (Date - DD MM YYYY should be entered based on the claims dump report)' => $rfq_data['premium_date'], @@ -634,12 +707,12 @@ class LeadsController extends BaseController 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'], 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'], ]; - }else if($rfq_data['policy_type_id'] == 1){ + } else if ($rfq_data['policy_type_id'] == 1) { $lead_data = [ 'Insured' => $rfq_data['client_name'], 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'Total Sum Insured at Renewal ' => $rfq_data['total_si_at_renewal'], - 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])).' to '. date('d/m/Y', strtotime($rfq_data['policy_end_date'])), + 'Policy Period' => date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])), 'Policy Status' => $rfq_data['status'], 'Existing Insurer' => $rfq_data['insurer_name'], 'TPA ' => $rfq_data['tpa_name'], @@ -648,14 +721,15 @@ class LeadsController extends BaseController } $data = json_decode($rfq_data['json'], true); + // dd($data); - if($type == 2){ + if ($type == 2) { $data = $this->convertJsonForQCR($data, $type); - if($propsal_and_insurer !== null){ + if ($propsal_and_insurer !== null) { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); $data = $this->transformProposelData($data, $proposal_key, $insurer_key); } - }else if($type == 1){ + } else if ($type == 1) { $data = $this->convertJsonForQCR($data, $type); // dd($data); } @@ -663,17 +737,123 @@ class LeadsController extends BaseController $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); + // Start with lead_data at the top $rowNumber = 1; + + $mergeRange1 = "A{$rowNumber}:C{$rowNumber}"; + $sheet->mergeCells($mergeRange1); + $sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd"); + $sheet->getStyle("A{$rowNumber}")->applyFromArray([ + 'font' => [ + 'bold' => true, + 'size' => 20 + ], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ], + ]); + + // Set column width to fit the image properly + $sheet->getColumnDimension('D')->setWidth(20); // Adjust as needed + $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed + + $drawing = new Drawing(); + $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path + $drawing->setPath($path); + $drawing->setCoordinates("D{$rowNumber}"); // Set position in column B + $drawing->setHeight(35); // Adjust image height + + // Center align the image in the cell + $drawing->setOffsetX(30); // Adjust horizontal offset + $drawing->setOffsetY(5); // Adjust vertical offset + + $drawing->setWorksheet($sheet); + + // Apply center alignment to the cell + $sheet->getStyle("D{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + $sheet->getStyle("D{$rowNumber}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); + + + $rowNumber = $rowNumber + 1; + + // Initialize max width tracking variables + $maxWidthA = 0; + $maxWidthB = 0; + foreach ($lead_data as $key => $value) { + + // Merge A:B for key and C:D for value + $mergeRangeKey = "A{$rowNumber}:B{$rowNumber}"; + $mergeRangeValue = "C{$rowNumber}:D{$rowNumber}"; + $sheet->mergeCells($mergeRangeKey); + $sheet->mergeCells($mergeRangeValue); + + // Set values in merged cells $sheet->setCellValue("A{$rowNumber}", $key); - $sheet->setCellValue("B{$rowNumber}", $value); - $sheet->getStyle("A{$rowNumber}")->applyFromArray(['font' => ['bold' => true]]); + $sheet->setCellValue("C{$rowNumber}", $value); + + // Apply styles for alignment and bold text in A:B + $sheet->getStyle($mergeRangeKey)->applyFromArray([ + 'font' => ['bold' => true], + 'alignment' => [ + 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + ], + ]); + + // Apply bold style to B column if the key is "Insured" + if ($key == "Insured") { + $sheet->getStyle("C{$rowNumber}")->applyFromArray([ + 'font' => ['bold' => true], + ]); + } + + // Track max width needed for columns + $maxWidthA = max($maxWidthA, mb_strlen($key)); + $maxWidthB = max($maxWidthB, mb_strlen($value)); + $rowNumber++; } - $leadRange = "A1:B" . (count($lead_data)); - $sheet->getStyle($leadRange)->applyFromArray([ + // Set column width based on max content length (adjusted for padding) + $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); + $sheet->getColumnDimension('B')->setWidth($maxWidthA * 1.2); + $sheet->getColumnDimension('C')->setWidth($maxWidthB * 1.2); + $sheet->getColumnDimension('D')->setWidth($maxWidthB * 1.2); + + // $rowNumber += 2; + + // Add headers and subheaders + $headers = $data['table_data']['headers']; + + $sheet->setCellValue("A{$rowNumber}", "Details of Coverage"); + $sheet->getStyle("A{$rowNumber}")->applyFromArray([ + 'font' => [ + 'bold' => true, + ], + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'ADD8E6'], + ], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, + 'color' => ['argb' => 'FF000000'], // Black color + ], + ], + ]); + $subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers'])); + $subheader_count = $subheader_count - 2; + $headerCount = count($data['table_data']['headers']); + $lastColumn = Coordinate::stringFromColumnIndex($subheader_count); + // dd( $headerCount, $lastColumn); + + // Merge cells from A to the last column + $mergeRange = "A{$rowNumber}:{$lastColumn}{$rowNumber}"; + + $sheet->getStyle($mergeRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, @@ -682,21 +862,25 @@ class LeadsController extends BaseController ], ]); + $sheet->mergeCells($mergeRange); + $rowNumber = $rowNumber + 1; - $rowNumber += 2; - - // Add headers and subheaders - $headers = $data['table_data']['headers']; $subHeaderRow = $rowNumber + 1; $columnLetter = 'A'; foreach ($headers as $header) { + if (in_array($header['parentHeader'], ['Item Key', 'Action'])) { continue; } if ($header['parentHeader'] === 'Sno') { $header['parentHeader'] = 'S.No.'; + $sheet->getColumnDimension('A')->setWidth(10); + } + + if ($header['parentHeader'] === 'Particulars') { + $sheet->getColumnDimension('B')->setWidth(40); } $startColumn = $columnLetter; // Start of the current header range @@ -723,6 +907,13 @@ class LeadsController extends BaseController // Add subheaders foreach ($header['subHeaders'] as $subHeader) { $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); + + if ($columnLetter != "A" && $columnLetter != "B" && $columnLetter != "C" && $columnLetter != "D") { + $sheet->getColumnDimension($columnLetter)->setWidth(35); + } else { + $sheet->getColumnDimension('A')->setWidth(10); + } + $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([ 'font' => ['bold' => true], 'alignment' => [ @@ -746,12 +937,13 @@ class LeadsController extends BaseController ]); // Increase row height for headers and subheaders - $sheet->getRowDimension($rowNumber)->setRowHeight(30); // Header row height - $sheet->getRowDimension($subHeaderRow)->setRowHeight(25); // Subheader row height + $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height + $sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height $rowNumber = $subHeaderRow + 2; $column_data = $data['table_data']['data']; $serial_no = 1; + $maxColumnWidths = []; // Add table data rows foreach ($column_data as $dataRow) { @@ -789,6 +981,7 @@ class LeadsController extends BaseController $rowNumber += 2; // Add premium data + // dd($data); $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; $premiumData = $data['premium_data']['data']; $premium = [$labelArray[0]]; @@ -797,7 +990,7 @@ class LeadsController extends BaseController $total = [$labelArray[3]]; foreach ($premiumData as $proposal => $insurers) { - if($proposal != 'Particulars'){ + if ($proposal != 'Particulars') { foreach ($insurers as $insurer => $values) { $premium[] = $values[$labelArray[0]]; $gst[] = $values[$labelArray[1]]; @@ -819,7 +1012,8 @@ class LeadsController extends BaseController $rowNumber++; } - $premiumRange = "B" . ($rowNumber - 3) . ":" . chr(ord($columnLetter) - 1) . ($rowNumber - 1); + $premiumRange = "B" . ($rowNumber - 4) . ":" . chr(ord($columnLetter) - 2) . ($rowNumber - 1); + // dd($premiumRange); $sheet->getStyle($premiumRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ @@ -831,10 +1025,53 @@ class LeadsController extends BaseController } // Auto-size columns - foreach ($sheet->getColumnIterator() as $column) { - $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true); + // foreach ($sheet->getColumnIterator() as $column) { + // $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true); + // } + + $dataRange = $sheet->calculateWorksheetDimension(); + + $sheet->getStyle($dataRange)->getAlignment() + ->setHorizontal(Alignment::HORIZONTAL_CENTER) + ->setVertical(Alignment::VERTICAL_CENTER) + ->setWrapText(true); + + $sheet->getStyle('A1')->applyFromArray([ + 'alignment' => [ + 'wrapText' => false, // Disables text wrapping for A1 + ], + ]); + + // Apply border to the entire sheet + preg_match('/([A-Z]+)(\d+):([A-Z]+)(\d+)/', $dataRange, $matches); + + if ($matches) { + $startColumn = $matches[1]; // A + $startRow = $matches[2]; // 1 + $endColumn = $matches[3]; // G + $endRow = $matches[4]; // 75 + + // Convert column letter to index, reduce by 1, and convert back + $endColumnIndex = Coordinate::columnIndexFromString($endColumn) - 1; + $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex); + + // Generate the new range (e.g., "A1:F75" instead of "A1:G75") + $newDataRange = "{$startColumn}{$startRow}:{$newEndColumn}{$endRow}"; + // $sheet->getStyle($newDataRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); } + $lastRow = count($lead_data) + 1; + $leadRange = "A1:D{$lastRow}"; + + $sheet->getStyle($leadRange)->applyFromArray([ + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, + 'color' => ['argb' => 'FF000000'], // Black color + ], + ], + ]); + // Set filename $string = ($type == 2) ? 'QCR' : 'RFQ'; $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx'; @@ -1405,10 +1642,11 @@ class LeadsController extends BaseController } // dd($lead_data); - $reply_to = $lead_data['created_person_email']; + $reply_to = $lead_data['created_person_email'] ?? ""; //get file path to attach $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); + log_message('error','File Info'.json_encode($file_info)); if ($lead_data['file_name'] != null && $lead_data['file_name'] != '') { $temp_file_path = $file_info['filePath']; $temp_file_name = $file_info['fileName']; @@ -1422,8 +1660,11 @@ class LeadsController extends BaseController $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); // print_rr($result); } + }else{ + $result = $file_info['filePath']; + // return $this->respond(['status' => 'fail', 'code' => 200, 'messgae' => 'File Not Found'], 200); } - // print_rr($lead_data); + // print_rr($result); die; // print_rr($file_info); // $file_path = WRITEPATH."uploads/excel/sample/correction.xls"; // $file_name = $file_type.'.xlsx'; @@ -1478,8 +1719,10 @@ class LeadsController extends BaseController $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; // print_rr($message);calculate_days_bw_dates + $string = implode(", ", $cc_mails); + $bcc_string = implode(", ", $bcc_mails); - $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $cc_mails, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_mails]); + $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]); // !dd($res); $result_data[] = ['mail' => $recipient['email'], 'status' => $res]; } @@ -2036,54 +2279,117 @@ class LeadsController extends BaseController //------------------------------------------------------------------------------------------------ - public function transformMailContent($lead_id) + // public function transformMailContent($lead_id, $page_name) + // { + // helper('excel_util_helper'); + // // $params = $this->request->getGet(); + + // // print_r($params); die; + // // $lead_id = $params['lead_id']; + // // $file_type = $params['file_type']; //rfq or qcr + // // $recipient_type = $params['recipient_type']; //insurer or client or internal or placement + // // $recipient_mail = $params['recipient_mail']; // - only primary key of contacts + // // $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + + // // if ($recipient_type == 'insurer' && empty($recipient_mail)) { + // // return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); + // // } + + // //gather lead info + // $lead_data = $this->leadsModel + // ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') + // ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + // ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') + // ->where('leads.id', $lead_id) + // ->first(); + + // // dd($lead_data); + + // if($lead_data){ + + // $recipient_data = ['name' => "Team"]; + // // $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

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

RFQ Details

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

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

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; + // $original_message = `Dear Sir, + + // Greetings From Nhance India! + + // Please find attached the RFQ for {{POLICY_TYPE}} policy pertaining to {{RECIPIENT_NAME}} + // Kindly request you to share the competitive quotes at the earliest + // In case of any query, Please feel free to contact us. + // Thank You !`; + + // $message = $original_message; + // $message = str_replace("{{RECIPIENT_NAME}}", $lead_data['client_name'], $message); + // $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'] ?? $lead_data['policy_type'], $message); + // $message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'], $message); + // $message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message); + + // $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); + // $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); + // $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; + + // dd($message); + // // return $this->respond(['status' => true, 'code' => 200, 'data' => $message], 200); + // return $message; + + // }else{ + + // // return $this->respond(['status' => false, 'code' => 404, 'message' => "This lead has not data"], 200); + // return ''; + // } + + + + // } + + public function transformMailContent($lead_data, $mail_content, $page_name) { - helper('excel_util_helper'); - // $params = $this->request->getGet(); + $current_year = date('Y'); + $next_year = $current_year + 1; + $policy_year = "$current_year-$next_year"; - // print_r($params); die; - // $lead_id = $params['lead_id']; - // $file_type = $params['file_type']; //rfq or qcr - // $recipient_type = $params['recipient_type']; //insurer or client or internal or placement - // $recipient_mail = $params['recipient_mail']; // - only primary key of contacts - // $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; + if ($lead_data) { + + // Replacing placeholders with actual values + $message = $mail_content; + $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] ?? "Valued Client", $message); + $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'] ?? $lead_data['policy_type'] ?? "Insurance Policy", $message); + $message = str_replace("{{POLICY_TYPE}}", $lead_data['policy_type'] ?? "Insurance Policy", $message); + $message = str_replace("{{RFQ_OR_QCR}}", $page_name, $message); + $message = str_replace("{{POLICY_YEAR}}", $policy_year, $message); - // if ($recipient_type == 'insurer' && empty($recipient_mail)) { - // return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); - // } - - //gather lead info - $lead_data = $this->leadsModel - ->select('leads.*,policy_type.long_name,policy_type.policy_type,user_profiles.email as created_person_email') - ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') - ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') - ->where('leads.id', $lead_id) - ->first(); - - // dd($lead_data); - - if($lead_data){ - - $recipient_data = ['name' => "Team"]; - $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

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

RFQ Details

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

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

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; - - $message = $original_message; - $message = str_replace("{{RECIPIENT_NAME}}", $recipient_data['name'], $message); - $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); - $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message); - $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'], 'Y-m-d', 'd-m-Y'), $message); - $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; - - // return $this->respond(['status' => true, 'code' => 200, 'data' => $message], 200); return $message; - }else{ - - // return $this->respond(['status' => false, 'code' => 404, 'message' => "This lead has not data"], 200); - return ''; + } else { + return ''; // Return empty if no lead data found } - - - } + + function getLastFiveFinancialYears() { + $currentYear = date('Y'); + $currentMonth = date('m'); + + // In India, the financial year starts from April (04) + if ($currentMonth < 4) { + $currentYear--; // Adjust year if it's Jan-Mar + } + + $financialYears = []; + + for ($i = 0; $i < 5; $i++) { + $startYear = $currentYear - $i - 1; + $endYear = $currentYear - $i; + $financialYears[] = "$startYear-$endYear"; + } + + return $financialYears; + } + + public function rfqNonEB(){ + + $this->loadLayout('view_rfq_non_eb'); + } + + + } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 9cf89d53..4e1271f8 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -287,6 +287,10 @@ class MasterController extends AdminController $data['deletion_add_day'] = 1; } + if($this->request->getPost('is_multi_event')){ + $data['is_multi_event'] = 1; + } + $data['created_by'] = get_session_userid(); $data['insurer_logo'] = $file_name; @@ -371,6 +375,12 @@ class MasterController extends AdminController $data['deletion_add_day'] = 0; } + if($this->request->getPost('is_multi_event')){ + $data['is_multi_event'] = 1; + }else{ + $data['is_multi_event'] = 0; + } + $update = $this->insurerModel->update($id,$data); if($update){ echo json_encode(array("status" => true , 'data' => $data)); @@ -1723,7 +1733,8 @@ class MasterController extends AdminController 'excel' => WRITEPATH . 'uploads/excel/', 'statements' => WRITEPATH . 'uploads/statements/', 'import_excel' => WRITEPATH . 'uploads/import_excel/', - 'logs' => WRITEPATH . 'uploads/logs/', + 'logs' => WRITEPATH . 'logs', + 'session' => WRITEPATH . 'session', 'client_kyc_documents' => WRITEPATH . 'uploads/client_kyc_documents/', 'tmp' => WRITEPATH . 'tmp/', 'e_card_imgs' => ROOTPATH . 'public/e_card_imgs', @@ -1732,8 +1743,10 @@ class MasterController extends AdminController 'logo' => ROOTPATH . 'public/uploads/logo/', 'template_bg' => ROOTPATH . 'public/uploads/template_bg/', 'attachments' => WRITEPATH . 'uploads/attachments/', + 'cache' => WRITEPATH . 'cache', 'sample_import_excel' => ROOTPATH . 'public/sample_import_excel', 'lead_files' => WRITEPATH . 'uploads/lead_files/', + 'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/', ]; foreach ($folders as $folderName => $folderPath) { diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php index 69852bca..4a2a59d6 100644 --- a/app/Controllers/PolicyTransactionController.php +++ b/app/Controllers/PolicyTransactionController.php @@ -274,7 +274,7 @@ class PolicyTransactionController extends BaseController // Separate Insurer and TPA Branch IDs and IDs if(isset($data['insurer_id']) && !empty($data['insurer_id'])){ list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']); - if (isset($data['tpa'])) { + if (isset($data['tpa']) && !empty($data['tpa'])) { list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']); } } @@ -414,9 +414,13 @@ class PolicyTransactionController extends BaseController // Prepare data for insertion and updating $coShareDetails = []; - // print_r($data); + // print_r($data); die; // die; + if(isset($data['co_share_id']) && !empty($data['co_share_id'])){ + $this->removePtCoShareRecords($data['co_share_id']); + } + if(isset($data['follow_insurer_id'])){ foreach ($data['follow_insurer_id'] as $index => $insurer) { @@ -429,7 +433,7 @@ class PolicyTransactionController extends BaseController 'pt_id' => $pt_id, 'insurer_id' => $insurer_id ?? 0, 'insurer_branch_id' => $insurer_branch_id ?? 0, - 'co_share_type' => $data['co_share_type'][$index] ?? null, + 'co_share_type' => $data['co_share_type'][$index] ?? 1, 'co_share_per' => $data['co_share_per'][$index] ?? 0, 'bp_amt' => $data['base_premium'][$index] ?? 0, 'bp_gst_amt' => $data['gst_amount'][$index] ?? 0, @@ -438,6 +442,8 @@ class PolicyTransactionController extends BaseController 'bp_cgst' => $data['cgst'][$index] ?? 0, 'tp_amt' => $data['tp_premium'][$index] ?? 0, 'tep_amt' => $data['ter_premium'][$index] ?? 0, + 'cotp_amt' => $data['co_tp_premium'][$index] ?? 0, + 'cotep_amt' => $data['co_ter_premium'][$index] ?? 0, 'agreed_amt' => $data['agreed_amount'][$index] ?? 0, 'agreed_bp_per' => $data['agreed_bp'][$index] ?? 0, 'agreed_tp_per' => $data['agreed_tp'][$index] ?? 0, @@ -499,7 +505,7 @@ class PolicyTransactionController extends BaseController return true; } - + // print_r($data); // die; } @@ -949,6 +955,23 @@ class PolicyTransactionController extends BaseController } } + //function for soft delete for pt_co_share_details records + public function removePtCoShareRecords($primaryKeys) + { + // print_r($primaryKeys); die; + if (empty($primaryKeys)) { + return false; + } + + // Convert array to a comma-separated string for query binding + $placeholders = implode(',', array_fill(0, count($primaryKeys), '?')); + + $sql = "UPDATE pt_co_share_details SET is_active = 0 WHERE id NOT IN ($placeholders)"; + + return db_connect()->query($sql, $primaryKeys); + } + + //------------------------------------------------------------------------------------------------ // Policy Transaction Endorsement @@ -1040,6 +1063,7 @@ class PolicyTransactionController extends BaseController { $id = $this->request->getPost('id'); $data = $this->preparePolicyTransactionData(); + // print_r($data); die; if (!$id) { return $this->insertEndorsementTransaction($data); @@ -1056,25 +1080,12 @@ class PolicyTransactionController extends BaseController // print_r($data); // die; - // $data_received_date = (string)$this->request->getPost('data_received_date'); - // $closure_date = (string)$this->request->getPost('closure_date'); - // $endorse_eff_date = (string)$this->request->getPost('endorse_eff_date'); - // $month = (string)$this->request->getPost('month'); - - // $data['data_received_date'] = empty($data['data_received_date']) ? null : date('Y-m-d', strtotime($data_received_date)); - // $data['closure_date'] = empty($data['closure_date']) ? null : date('Y-m-d', strtotime($closure_date)); - // $data['endorse_eff_date'] = empty($data['endorse_eff_date']) ? null : date('Y-m-d', strtotime($endorse_eff_date)); - - // $month = '01-'.$data['month']; - // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month)); - if (!isset($data['policy_with_corr'])) { $data['policy_with_corr'] = 0; } elseif ($data['policy_with_corr']) { $data['policy_with_corr'] = 1; } - if(empty($data['data_received_date'])){ $data['data_received_date'] = null; }else{ @@ -1117,7 +1128,7 @@ class PolicyTransactionController extends BaseController // Separate Insurer and TPA Branch IDs and IDs if(isset($data['insurer_id']) && !empty($data['insurer_id'])){ list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']); - if (isset($data['tpa'])) { + if (isset($data['tpa']) && !empty($data['tpa'])) { list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']); } } @@ -1246,7 +1257,7 @@ class PolicyTransactionController extends BaseController public function getEndorsementDataForEdit($id) { $data = $this->policyTransactionModel - ->select(' + ->select(' policy_transaction.*, clients.short_name as client_short_name, clients.client_type, @@ -1260,52 +1271,43 @@ class PolicyTransactionController extends BaseController ) as last_action_date ') - ->join('clients', 'clients.id = policy_transaction.client_id') - ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') - ->where('policy_transaction.id', $id) - ->where('policy_transaction.is_active', 1) - ->first(); - - // $data['policy_start_date'] = empty($data['policy_start_date']) ? '' : date('d/m/Y', strtotime($data['s_date'])); - // $data['policy_end_date'] = empty($data['policy_end_date']) ? '' : date('d/m/Y', strtotime($data['e_date'])); - // $data['data_received_date'] = empty($data['data_received_date']) ? '' : date('d/m/Y', strtotime($data['data_received_date'])); - // $data['closure_date'] = empty($data['closure_date']) ? '' : date('d/m/Y', strtotime($data['closure_date'])); - // $data['endorse_eff_date'] = empty($data['endorse_eff_date']) ? '' : date('d/m/Y', strtotime($data['endorse_eff_date'])); - - // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') - // ? date('M/Y', strtotime($data['month'])) - // : null; + ->join('clients', 'clients.id = policy_transaction.client_id') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->where('policy_transaction.id', $id) + ->where('policy_transaction.is_active', 1) + ->orderBy('id', 'asc') + ->first(); - if(!empty($data['policy_start_date'])){ + if (!empty($data['policy_start_date'])) { $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['policy_end_date'])){ + if (!empty($data['policy_end_date'])) { $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['data_received_date'])){ + if (!empty($data['data_received_date'])) { $data['data_received_date'] = change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['policy_issue_date'])){ + if (!empty($data['policy_issue_date'])) { $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['endorse_eff_date'])){ + if (!empty($data['endorse_eff_date'])) { $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['install_due_date'])){ + if (!empty($data['install_due_date'])) { $data['install_due_date'] = change_date_format($data['install_due_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['last_action_date'])){ + if (!empty($data['last_action_date'])) { $data['last_action_date'] = change_date_format($data['last_action_date'], 'Y-m-d', 'd/m/Y'); } - if(!empty($data['month'])){ + if (!empty($data['month'])) { $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y'); } @@ -1314,7 +1316,7 @@ class PolicyTransactionController extends BaseController //get PT Co-Share Details $data['pt_co_share_details'] = $this->PTCOShareDetailsModel - ->select(" + ->select(" pt_co_share_details.*, ( @@ -1430,19 +1432,18 @@ class PolicyTransactionController extends BaseController ) AS actual_tep_brokerage_amount ") - ->where('pt_id', $id) - ->where('is_active', 1) - ->orderBy('id', 'asc') - ->findAll(); + ->where('pt_id', $id) + ->where('is_active', 1) + ->orderBy('id', 'asc') + ->findAll(); // print_r($data['endorse_eff_date']); die; - if($data){ + if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); - }else{ + } else { return $this->respond(['status' => false], 200); } - } //------------------------------------------------------------------------------------------------ @@ -1584,8 +1585,15 @@ class PolicyTransactionController extends BaseController ->where('policy_transaction.action_type', 'inception') ->findAll(); + $is_copay_yes = $this->policyTransactionModel + ->where('client_id', $client_id) + ->where('client_policy_id', $client_policy_id) + ->where('action_type', 'inception') + ->where('is_active', 1) + ->first(); + if ($totalCount) { - return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount], 200); + return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount, 'is_copay_yes' => $is_copay_yes], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200); } @@ -2700,7 +2708,7 @@ class PolicyTransactionController extends BaseController // Build query $db = db_connect(); $builder = $db->table("cash_deposit") - ->where('cd_ac_no', $cd_ac_no) + ->where('cd_ac_pk', $cd_ac_no) ->where('is_active', 1) ->orderBy('id', 'desc') ->limit(1); @@ -2715,6 +2723,8 @@ class PolicyTransactionController extends BaseController 'status' => true, 'code' => 200, 'data' => $result, + 'base_premium' => $base_premium, + 'cd_ac_no' => $cd_ac_no, 'base_premium_greater_than_balance' => $base_premium_greater_than_balance, ], 200); } diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php index 56c65ff8..616a69cd 100755 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -71,13 +71,20 @@ class RestAuthenticationController extends AdminController $mobile_number = $this->request->getJSON()->mobile_number; - $employeeData = $this->employeeModel->where('mobile', $mobile_number) - ->where('relationship', 'self') - ->where('emp_status !=', 'truncated') - ->where('is_active', 1) - ->first(); + $employeeData = $this->employeeModel->select('employees.relationship,EP.employee_id') + ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') + ->where('employees.is_active', 1) + ->where('employees.relationship', 'self') + ->where('employees.emp_status !=', 'truncated') + ->where('employees.mobile', $mobile_number) + ->where('EP.is_active', 1) + ->whereIn('EP.status', ['active']) + ->first(); + + - if ($employeeData) { + if (isset($employeeData['employee_id'])) + { $result = ['user_verification' => true ,'message' => "Verified Successfully"]; return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); @@ -95,63 +102,68 @@ class RestAuthenticationController extends AdminController { try { $email = $this->request->getJSON()->email; - - $employeeData = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self') - ->where('emp_status !=', 'truncated')->where('is_active', 1) - ->first(); - - if ($employeeData) { + + $employeeData = $this->employeeModel->select(' + employees.relationship, + EP.employee_id, + employees.client_id, + employees.client_branch_id, + employees.email_corporate + + ') + ->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner') + ->where('employees.is_active', 1) + ->where('employees.relationship', 'Self') + ->where('employees.emp_status !=', 'truncated') + ->where('employees.email_corporate', $email) + ->where('EP.is_active', 1) + ->whereIn('EP.status', ['draft', 'enrolled']) + ->first(); + + if (isset($employeeData['employee_id'])) { $otp = random_int(100000, 999999); - $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self') - ->where('is_active', 1)->set(array('otp' => $otp )) - ->update(); - if($update) - { + $update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'Self') + ->where('is_active', 1)->set(array('otp' => $otp)) + ->update(); + if ($update) { $common = [ 'client_id' => $employeeData['client_id'], 'client_branch_id' => $employeeData['client_branch_id'], 'client_policy_id' => null, 'employee_policy_id' => null, - 'employee_id' => $employeeData['id'], + 'employee_id' => $employeeData['employee_id'], 'mail_type' => 'otp_mail', - ]; + ]; $subject = 'Nhance user verification - OTP'; - $mail_content = $otp.' is your verification code for Nhance.'; - $res = MailHelper::send_email(['mail' => $employeeData['email_corporate'], 'subject' => $subject ,'common'=>$common ,'message' => $mail_content]); + $mail_content = $otp . ' is your verification code for Nhance.'; + $res = MailHelper::send_email(['mail' => $employeeData['email_corporate'], 'subject' => $subject, 'common' => $common, 'message' => $mail_content]); $this->myLogger->logme("info", $res); - if(json_decode($res)->status == 'success') - { - $result = ['user_verification' => true ,'message' => "Verified Successfully"]; - return $this->respond(['status' => 'success','code' => 200,'data' => $result],200); - - }else{ - $result = ['user_verification' => false , 'message' => "Mail sending failed , try again"]; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); + if (json_decode($res)->status == 'success') { + $result = ['user_verification' => true, 'message' => "Verified Successfully"]; + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + $result = ['user_verification' => false, 'message' => "Mail sending failed , try again"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); } + } else { - }else{ - - $result = ['user_verification' => false , 'message' => "Verification failed , try again"]; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); - + $result = ['user_verification' => false, 'message' => "Verification failed , try again"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); } - - } else { - $result = ['user_verification' => false , 'message' => "User not found"]; - return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200); - + $result = ['user_verification' => false, 'message' => "User not found"]; + return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200); } } catch (\Throwable $th) { - return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500); } } - + public function getVerifiedUserData() { diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 53ae3c5b..5974714a 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -12,13 +12,16 @@ use App\Models\TicketMailTemplateModel; use App\Models\TicketMessageModel; use App\Models\TicketNoteModel; use App\Models\UserModel; +use App\Models\ClientPolicyModel; +use App\Models\EmployeePolicyModel; + use DOMDocument; use Psr\Log\LoggerInterface; use Kint\Kint; use App\Models\EmployeeModel; use App\Helpers\MailHelper; - +use App\Models\InsurerModel; use CodeIgniter\API\ResponseTrait; class TicketController extends BaseController @@ -26,13 +29,15 @@ class TicketController extends BaseController use ResponseTrait; protected $myLogger; - protected $ticketType; - protected $priorityType; - protected $relationshipType; - protected $modeOFIntimate; - protected $claimType; - protected $claimStatus; - protected $placeHolders; + public $ticketType; + public $priorityType; + public $relationshipType; + public $modeOFIntimate; + public $claimType; + public $claimStatus; + public $placeHolders; + public $extraFields; + public $nonIDReason; protected $clientModel; protected $ticketMasterModel; @@ -43,6 +48,8 @@ class TicketController extends BaseController protected $triggerType; protected $userModel; protected $employeeModel; + protected $clientPolicyModel; + protected $employeePolicyModel; public function __construct() { @@ -73,14 +80,15 @@ class TicketController extends BaseController 1 => "In Person", 2 => "Courier", 3 => "Online Mode - Email", - 4 => "Online Mode - To TPA" + 4 => "Smart Service Desk", + 5 => "Direct to TPA" ]; $this->claimType = [ 1 => [ - 1 => "Main", + 1 => "Main Hospitalization", + 3 => "Pre / Post", 2 => "OPD", - 3 => "Pre ReOpen", - 4 => "Post ReOpen", + 4 => "ReOpen", ], 2 => [ 1 => "TTD", @@ -96,7 +104,8 @@ class TicketController extends BaseController 4 => "Trigger 4", 5 => "Trigger 5", 6 => "Trigger 6", - 7 => "Trigger 7" + 7 => "Trigger 7", + 8 => "Trigger 8", ]; $this->placeHolders = [ @@ -110,6 +119,39 @@ class TicketController extends BaseController '((RELATIONSHIP))' => 'relationship', '((POLICY_TYPE))' => 'policy_type', '((AUTO_QUERY_CONTENT))' => 'auto_query_content', + '((CLAIM_FORM_LINK))' => 'claim_form_link', + ]; + $this->extraFields = [ + 1 => ['non_id_reason'], + 10 => ['pay_initiate_date'], + 3 => ['raised_date'], + 4 => ['raised_date'], + 5 => ['claim_number', 'registration_date'], + 7 => ['query_received_date'], + 8 => ['denial_reason','denial_date'], + 9 => ['approved_amount','approved_date', 'approved_letter'], + 11 => ['utr_details', 'settled_date', 'settle_letter'], + 40 => ['approved_amount','approved_date', 'approved_letter'], + 44 => ['utr_details', 'settled_date', 'settle_letter'], + 30 => ['approved_amount','approved_date', 'approved_letter'], + 34 => ['utr_details', 'settled_date', 'settle_letter'], + 20 => ['approved_amount','approved_date', 'approved_letter'], + 24 => ['utr_details', 'settled_date', 'settle_letter'], + 14 => ['return_remark', 'awb_no_courier_name'], + 48 => ['return_remark', 'awb_no_courier_name'], + 59 => ['return_remark', 'awb_no_courier_name'], + 54 => ['return_remark', 'awb_no_courier_name'], + 13 => ['cancel_remark'], + 47 => ['cancel_remark'], + 53 => ['cancel_remark'], + 58 => ['cancel_remark'], + ]; + $this->nonIDReason = [ + "Newborn Baby" => "Newborn Baby", + "Newly Wedded Spouse" => "Newly Wedded Spouse", + "Policy Pending" => "Policy Pending", + "New Joinee" => "New Joinee", + "Exceptional Case" => "Exceptional Case" ]; $this->ticketMasterModel = new TicketMasterModel(); @@ -121,6 +163,8 @@ class TicketController extends BaseController $this->ticketMessageModel = new TicketMessageModel(); $this->userModel = new UserModel(); $this->employeeModel = new EmployeeModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->employeePolicyModel = new EmployeePolicyModel(); } public function ticketList() @@ -260,7 +304,7 @@ class TicketController extends BaseController return $this->loadLayout('ticket_form_handler', $data); } - public function ticket_form_data($ticket_type) + public function ticket_form_data($ticket_type, $claim_status_id = null) { $this->myLogger->logme('error', "Fetching ticket form data for Ticket Type: $ticket_type"); @@ -270,7 +314,8 @@ class TicketController extends BaseController 'ticket_type' => $this->ticketType, 'priorityType' => $this->priorityType, 'relationshipType' => $this->relationshipType, - 'modeOFIntimate' => $this->modeOFIntimate + 'modeOFIntimate' => $this->modeOFIntimate, + 'nonIDReason' => $this->nonIDReason ]; switch ($ticket_type) { @@ -294,11 +339,23 @@ class TicketController extends BaseController ->getResultArray(); // Fetch Claim Status - $data['claim_status'] = $this->claimStatus - ->select('*') - ->where(['is_active' => 1, 'ticket_type' => $ticket_type]) - ->get() - ->getResultArray(); + + if(empty($claim_status_id)){ + + if($ticket_type == 2){ + $claim_status_id = 15; + }else if($ticket_type == 3){ + $claim_status_id = 25; + }else if($ticket_type == 4){ + $claim_status_id = 35; + }else{ + $claim_status_id = 1; + } + } + + $data['claim_status'] = $this->transFormClaimStatus($claim_status_id, $ticket_type); + $data['extra_fields'] = $this->getExtraFields($data['claim_status']); + $data['extra_fields_array_for_validate'] = $this->getExtraFields($data['claim_status'], 1); if ($ticket_type == 1) { $data['claim_type'] = $this->claimType[1]; @@ -311,19 +368,90 @@ class TicketController extends BaseController return $data; } + //transform the claim status + public function transFormClaimStatus($claimStatusId, $ticket_type) + { + // Fetch the main claim status by ID + $claimStatusData = $this->claimStatus + ->select('*') + ->where(['is_active' => 1, 'ticket_type' => $ticket_type]) + ->where('id', $claimStatusId) + ->first(); + // dd($claimStatusData); + + // Initialize the filtered claim status array + $filteredClaimStatus = []; + + if (!empty($claimStatusData)) { + // Add the main claim status to the result + $filteredClaimStatus[] = $claimStatusData; + + // Decode the allowed_status JSON field + $filterClaimStatusIds = json_decode($claimStatusData['allowed_status'], true); + + // Fetch additional claim statuses if IDs exist + if (!empty($filterClaimStatusIds) && is_array($filterClaimStatusIds)) { + $additionalClaimStatuses = $this->claimStatus + ->select('*') + ->where(['is_active' => 1, 'ticket_type' => $ticket_type]) + ->whereIn('id', $filterClaimStatusIds) + ->get() + ->getResultArray(); + + // Merge additional claim statuses into the result + $filteredClaimStatus = array_merge($filteredClaimStatus, $additionalClaimStatuses); + } + } + + return $filteredClaimStatus; + } + + public function getExtraFields(array $claimStatus, $nonFilterArray = 0): array + { + $extra_fields = []; + + if($nonFilterArray == 1){ + + foreach ($claimStatus as $value) { + if (isset($this->extraFields[$value['id']])) { + if (!isset($extra_fields[$value['id']])) { + $extra_fields[$value['id']] = []; + } + $extra_fields[$value['id']] = array_merge($extra_fields[$value['id']], $this->extraFields[$value['id']]); + } + } + + }else{ + + foreach ($claimStatus as $value) { + if (isset($this->extraFields[$value['id']])) { + $extra_fields[] = $this->extraFields[$value['id']]; + } + } + + $extra_fields = array_values(array_unique(array_merge(...$extra_fields))); + } + + return $extra_fields; + } + 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])) { + $ticket_data['auto_query_content'] = $this->getCheckListAndConvertArrayToString($ticket_data); + } + // dd($ticket_data); $template_data = $this->ticketMasterModel->getTemplateDataByTicketID($ticket_id); if (!empty($template_data)) { $template_data['mail_content'] = $this->replacePlaceholders($template_data['mail_content'], $ticket_data); $template_data['subject'] = $this->replacePlaceholders($template_data['subject'], $ticket_data); } - $data = $this->ticket_form_data($ticket_data['ticket_type_id']); - $data['ticket_data'] = $ticket_data; + $data = $this->ticket_form_data($ticket_data['ticket_type_id'], $ticket_data['claim_status_id']); $data['reply_data'] = $template_data; $data['placeHolders'] = $this->placeHolders; $data['message_data'] = $this->getTicketMessage($ticket_id); @@ -331,6 +459,13 @@ class TicketController extends BaseController $data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']); $data['ticket_history'] = $this->ticketHistory($ticket_id); $data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray(); + if (!empty($ticket_data['client_policy_id'])){ + $ticket_data['client_policy_id_text'] = $this->clientPolicyModel->select('concat(policy_type.policy_type,"-",client_policy.policy_no) as client_policy_name')->join('policy_type','policy_type.id = client_policy.policy_type_id and policy_type.is_active = 1')->where('client_policy.id',$ticket_data['client_policy_id'])->first()['client_policy_name']; + } + // dd($data); + $data['ticket_data'] = $ticket_data; + $data['acms'] = $this->employeeModel->getAcmUsingClientID($ticket_data['client_id']); + // dd($data); return $this->loadLayout('ticket_edit_onbording', $data); @@ -423,6 +558,12 @@ class TicketController extends BaseController $ticket_data['settled_date'] = change_date_format($ticket_data['settled_date'], null, $out_put_format); } + if (empty($ticket_data['pay_initiate_date'])) { + $ticket_data['pay_initiate_date'] = null; + } else { + $ticket_data['pay_initiate_date'] = change_date_format($ticket_data['pay_initiate_date'], null, $out_put_format); + } + return $ticket_data; } @@ -430,6 +571,7 @@ class TicketController extends BaseController { $ticket_data = $this->request->getPost(); $ticket_data = $this->formatDateForClaim($ticket_data); + // $ticket_data = $this->getLastMatchedStatus($ticket_data, ); // print_rr($ticket_data); die; if ($ticket_data) { @@ -451,6 +593,7 @@ class TicketController extends BaseController $ticket_id = $this->request->getPost('ticket_master_id'); $ticket_data = $this->request->getPost(); $ticket_data = $this->formatDateForClaim($ticket_data); + $ticket_data['claim_status_id'] = $this->getLastMatchedStatus($ticket_data); // print_rr($ticket_data); die; $old_ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first(); @@ -462,8 +605,12 @@ class TicketController extends BaseController $mail_responce = $this->sendAutoMailTrigger($ticket_id); //send mail to the head for rejected ticket approvel - if($ticket_data['claim_status_id'] == 8){ + if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){ $this->sendMailToTheHead($ticket_data); + }else{ + $this->myLogger->logme('error', "Head Mail can't be sent"); + $this->myLogger->logme('error', "CLAIM STATUS ID : {data}", ['data' => $ticket_data['claim_status_id']]); + $this->myLogger->logme('error', "IS HEAD APPROVED : {data}", ['data' => $ticket_data['is_head_approved']]); } return $this->respond(['status' => true, 'code' => 200, 'data' => $ticket_data, "message" => "Claim updated successfully", 'mail_responce' => $mail_responce], 200); @@ -482,6 +629,17 @@ class TicketController extends BaseController $data['policy_type'] = $this->ticketType; $data['placeHolders'] = $this->placeHolders; $data['ticket_data'] = $this->ticketMailTemplateModel->where('is_active', 1)->findAll(); + + foreach ($data['ticket_data'] as $key => $ticket_data) { + + $tooltip_array = $this->claimStatus->select('claim_status')->where('ticket_type',$data['ticket_data'][$key]['ticket_type'])->where('trigger_type',$data['ticket_data'][$key]['trigger_type'])->where('is_active',1)->first(); + if (isset($tooltip_array) && $tooltip_array != null){ + $data['ticket_data'][$key]['tool_tip'] = $tooltip_array['claim_status']; + }else{ + $data['ticket_data'][$key]['tool_tip'] =$data['ticket_data'][$key]['template_name']; + } + } + // dd($data['ticket_data']); $data['ticket_type'] = $this->ticketType; $data['trigger_type'] = $this->triggerType; return $this->loadLayout('ticket_mail_template', $data); @@ -510,6 +668,21 @@ class TicketController extends BaseController } elseif ($action == 2) { $table_id = (int)$this->request->getPost('id'); $data = $this->ticketMailTemplateModel->where('id', $table_id)->where('is_active', 1)->first(); + if ($data && isset($data['ticket_type']) && isset($data['trigger_type'])) { + $tooltip_array = $this->claimStatus->select('claim_status') + ->where('ticket_type', $data['ticket_type']) + ->where('trigger_type', $data['trigger_type']) + ->where('is_active', 1) + ->first(); + + $data['tool_tip'] = (isset($tooltip_array['claim_status'])) + ? $tooltip_array['claim_status'] + : $data['template_name']; + } else { + // Handle case where $data is null or missing required fields + $data = $data ?: []; // Ensure $data is an array if null + $data['tool_tip'] = $data['template_name']; + } if ($data) { return $this->respond(['status' => true, 'data' => $data], 200); } else { @@ -635,6 +808,13 @@ class TicketController extends BaseController return null; } + if (in_array($ticket_data['claim_status_id'], [15, 25, 35])) { + $ticket_data['auto_query_content'] = $this->getCheckListAndConvertArrayToString($ticket_data); + } + + // print_r($ticket_data); die; + + $this->myLogger->logme('error', "Fetched email template: " . json_encode($template_data)); // Generate Email Content @@ -687,8 +867,10 @@ class TicketController extends BaseController $replaceData = $ticket_data[$value] ?? ''; } else if ($value == "policy_type") { $replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? ""); - } else { - $replaceData = isset($ticket_data[$value]) ? strtoupper($ticket_data[$value]) : ''; + } else if ($value == "claim_form_link"){ + $replaceData = 'Click here to download Claim Form'; + }else { + $replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : ''; } $content = str_replace($key, $replaceData, $content); @@ -1054,136 +1236,7 @@ class TicketController extends BaseController } } - // public function accountManagerWiseReport($policy_type = null ,$start_date = null, $end_date = null){ - - // if ($policy_type == 1) { - // $sql = "SELECT - // u.first_name AS acc_manager_name, - // COUNT(CASE WHEN tcs.claim_status = 'ID NOT GENERATED' AND master.ticket_type_id = 1 THEN master.id END) AS id_not_generated, - // COUNT(CASE WHEN tcs.claim_status = 'NON ID' AND master.ticket_type_id = 1 THEN master.id END) AS non_id, - // COUNT(CASE WHEN tcs.claim_status = 'CDA' AND master.ticket_type_id = 1 THEN master.id END) AS cda, - // COUNT(CASE WHEN tcs.claim_status = 'INFORMATION REQUIRED' AND master.ticket_type_id = 1 THEN master.id END) AS information_required, - // COUNT(CASE WHEN tcs.claim_status LIKE '%UNDER PROCESS%' AND master.ticket_type_id = 1 THEN master.id END) AS under_process, - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = 1 THEN master.id END) AS approved, - // COUNT(CASE WHEN tcs.claim_status = 'PAYMENT INITIATED' AND master.ticket_type_id = 1 THEN master.id END) AS payment_initiated, - // ( - // COUNT(CASE WHEN tcs.claim_status = 'ID NOT GENERATED' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'NON ID' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'CDA' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'INFORMATION REQUIRED' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status LIKE '%UNDER PROCESS%' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = 1 THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'PAYMENT INITIATED' AND master.ticket_type_id = 1 THEN master.id END) - // ) AS total - // FROM - // ticket_master master - // JOIN - // user_profiles u ON master.acm_id = u.id and u.is_active = 1 - // JOIN - // ticket_claim_status tcs ON tcs.id = master.claim_status_id and tcs.is_active = 1 - // WHERE - // master.created_at <= '$end_date' and master.created_at >= '$start_date' and master.is_active = 1 - // GROUP BY - // u.id; - // "; - // $result = $this->ticketMasterModel->query($sql)->getResultArray(); - // // dd($result); - - // return $result; - - - // }else{ - // $sql = "SELECT u.first_name AS acc_manager_name, - // COUNT(CASE WHEN tcs.claim_status = 'CLAIM INTIMATION' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS claim_intimation, - // COUNT(CASE WHEN tcs.claim_status = 'INTIMATION TO INSURER' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS int_to_insurer, - // COUNT(CASE WHEN tcs.claim_status = 'CLIENT PENDING' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS client_pending, - // COUNT(CASE WHEN tcs.claim_status = 'INSURER PENDING' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS information_required, - // COUNT(CASE WHEN tcs.claim_status = 'INVESTIGATION' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS investigation, - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS approved, - // COUNT(CASE WHEN tcs.claim_status = 'ON HOLD' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS on_hold, - - // ( - // COUNT(CASE WHEN tcs.claim_status = 'CLAIM INTIMATION' AND master.ticket_type_id = '$policy_type' THEN master.id END)+ - // COUNT(CASE WHEN tcs.claim_status = 'INTIMATION TO INSURER' AND master.ticket_type_id = '$policy_type' THEN master.id END)+ - // COUNT(CASE WHEN tcs.claim_status = 'CLIENT PENDING' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'INSURER PENDING' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'INVESTIGATION' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'ON HOLD' AND master.ticket_type_id = '$policy_type' THEN master.id END) - // ) AS total1, - // COUNT(CASE WHEN tcs.claim_status = 'NOT COVERED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS not_covered, - // COUNT(CASE WHEN tcs.claim_status = 'CLOSED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS closed, - // COUNT(CASE WHEN tcs.claim_status = 'SETTLED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS settled, - // ( - // COUNT(CASE WHEN tcs.claim_status = 'NOT COVERED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'CLOSED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'SETTLED' AND master.ticket_type_id = '$policy_type' THEN master.id END) - // ) AS total2 - // FROM - // ticket_master master - // JOIN - // user_profiles u ON master.acm_id = u.id and u.is_active = 1 - // JOIN - // ticket_claim_status tcs ON tcs.id = master.claim_status_id and tcs.is_active = 1 - // WHERE - // master.created_at <= '$end_date' and master.created_at >= '$start_date' and master.is_active = 1 and master.ticket_type_id = '$policy_type' - // GROUP BY - // u.id; - // "; - // $result = $this->ticketMasterModel->query($sql)->getResultArray(); - - // return $result; - // } - // } - - // public function tpaWiseReport($policy_type = null ,$start_date = null,$end_date = null ){ - // // $policy_type = 1; - // $sql = "SELECT - // tpa.name AS tpa_name, - // COUNT(CASE WHEN tcs.claim_status = 'ID NOT GENERATED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS id_not_generated, - // COUNT(CASE WHEN tcs.claim_status = 'NON ID' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS non_id, - // COUNT(CASE WHEN tcs.claim_status = 'CDA' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS cda, - // COUNT(CASE WHEN tcs.claim_status = 'INFORMATION REQUIRED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS information_required, - // COUNT(CASE WHEN tcs.claim_status LIKE '%UNDER PROCESS%' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS under_process, - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS approved, - // COUNT(CASE WHEN tcs.claim_status = 'PAYMENT INITIATED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS payment_initiated, - // ( - // COUNT(CASE WHEN tcs.claim_status = 'ID NOT GENERATED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'NON ID' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'CDA' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'INFORMATION REQUIRED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status LIKE '%UNDER PROCESS%' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'APPROVED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'PAYMENT INITIATED' AND master.ticket_type_id = '$policy_type' THEN master.id END) - // ) AS total, - // COUNT(CASE WHEN tcs.claim_status = 'CLOSED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS closed, - // COUNT(CASE WHEN tcs.claim_status = 'SETTLED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS settled, - // COUNT(CASE WHEN tcs.claim_status = 'RETURNED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS returned, - // COUNT(CASE WHEN tcs.claim_status = 'REJECTED' AND master.ticket_type_id = '$policy_type' THEN master.id END) AS denied, - // ( - // COUNT(CASE WHEN tcs.claim_status = 'CLOSED' AND master.ticket_type_id = '$policy_type'THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'SETTLED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'RETURNED' AND master.ticket_type_id = '$policy_type' THEN master.id END) + - // COUNT(CASE WHEN tcs.claim_status = 'REJECTED' AND master.ticket_type_id = '$policy_type' THEN master.id END) - // ) AS total2 - // FROM - // ticket_master master - // JOIN - // tpa ON master.tpa_id = tpa.id and tpa.is_active = 1 - // JOIN - // ticket_claim_status tcs ON tcs.id = master.claim_status_id and tcs.is_active = 1 - // WHERE - // master.created_at <= '$end_date' and master.created_at >= '$start_date' and master.is_active = 1 - // GROUP BY - // tpa.id; - - - // "; - // $result = $this->ticketMasterModel->query($sql)->getResultArray(); - - // return $result; - // } - + // ------------------------------------------------------------------------------------------------------------------------- // function for Reject ticket Head Approvel mail sent function public function sendMailToTheHead($ticket_data) @@ -1238,4 +1291,154 @@ class TicketController extends BaseController $this->myLogger->logme('error', "Head Mail can't be sent because ticket data is empty"); } } + + public function getLastMatchedStatus($incoming_form_values) + { + if (empty($incoming_form_values) || !isset($incoming_form_values['claim_status_id']) || !isset($incoming_form_values['extra_fields_array_for_validate'])) { + return null; + } + + $lastMatchedStatus = $incoming_form_values['claim_status_id']; + + // Use the provided `extra_fields_array_for_validate` from the incoming data + $statusMapping = json_decode($incoming_form_values['extra_fields_array_for_validate']); + + foreach ($statusMapping as $status => $requiredFields) { + // Ensure requiredFields is an array + if (!is_array($requiredFields)) { + $requiredFields = [$requiredFields]; + } + + // Check if all required fields exist and are not empty in the incoming form values + $allFieldsMatched = true; + foreach ($requiredFields as $field) { + if (!isset($incoming_form_values[$field]) || empty($incoming_form_values[$field])) { + $allFieldsMatched = false; + break; + } + } + + // Update the last matched status if all fields are validated + if ($allFieldsMatched) { + $lastMatchedStatus = $status; + } + } + + if($lastMatchedStatus == 1){ + if(!empty($incoming_form_values['tpa_no'])){ + $lastMatchedStatus = 2; + } + } + + return $lastMatchedStatus; + } + + public function getPolicyStartDate() + { + + $data = $this->request->getPost(); + $client_policy_id = $data['policy_id']; + $policy_start_date = $this->clientPolicyModel->select('policy_start_date')->where('id', $client_policy_id)->first()['policy_start_date']; + // dd($data); + if (isset($data['employeeId']) && $data['employeeId'] != "" && $data['employeeId'] != null) { + // dd($data); + $emp_id = $data['employeeId']; + $empData = $this->employeeModel->select('dob,doj')->where('id',$emp_id)->findAll(); + + if (!empty($empData) && $empData != "" && $empData != null ) { + foreach ($empData as &$emp) { // Loop through the data + $emp['dob'] = date('d/m/Y', strtotime($emp['dob'])); + $emp['doj'] = date('d/m/Y', strtotime($emp['doj'])); + } + } + + if ($empData){ + return $this->respond(['status' => true, 'minDate' => $policy_start_date,'empData'=> $empData], 200); + }else{ + return $this->respond(['status' => false, 'message' => "Policy Not Found"]); + } + + } else { + // dd($policy_start_date); + if ($policy_start_date) { + return $this->respond(['status' => true, 'minDate' => $policy_start_date], 200); + } else { + return $this->respond(['status' => false, 'message' => "Policy Not Found"]); + } + } + } + + public function getPoliciesbyEmpID() { + $received_data = $this->request->getPost(); + $emp_id = $received_data['emp_id']; + + // Get all client policy IDs for the given employee + $policies = $this->employeePolicyModel + ->select('client_policy_id') + ->where('employee_id', $emp_id) + ->findAll(); + + if (empty($policies)) { + return []; // Return empty if no policies found + } + + // Extract client policy IDs into an array + $policy_ids = array_column($policies, 'client_policy_id'); + + // Fetch all policy names and IDs in one query + $policyNameandID = $this->clientPolicyModel + ->select('CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name, client_policy.id as client_policy_value,client_policy.policy_type_id') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id AND policy_type.is_active = 1') + ->whereIn('client_policy.id', $policy_ids) + ->findAll(); + + // dd($policyNameandID); + if ($policyNameandID){ + + return $this->respond(['status'=>true,'policy_data'=> $policyNameandID]); + }else{ + return $this->respond(['status'=>false,'message'=> "Policy Not Found"]); + } + } + + public function getCheckListAndConvertArrayToString($ticket_data) + { + $data = db_connect()->table('ticket_check_list') + ->where('is_active', 1) + ->where('ticket_type_id', $ticket_data['ticket_type_id']) + ->get()->getResultArray(); + + $data = !empty($data) ? implode("", array_map(fn($doc) => "

{$doc['document']}

", $data)) : ""; + // $data = !empty($data) ? implode(", ", array_column($data, 'document')) : ""; + // print_r($data); die; + + return $data; + } + + public function downloadClaimForm($insurer_id) + { + $insurerModel = new InsurerModel(); + $insurer_data = $insurerModel->where('MD5(id)', $insurer_id)->where('is_active', 1)->first(); + + if (!$insurer_data) { + $data['message'] = 'The Physical File Not Found'; + echo view('errors/404', $data); + } + + $fileName = $insurer_data['short_name'] . '.pdf'; + $filePath = ROOTPATH . 'public/claim_sample_forms/' . $fileName; + + try { + if (file_exists($filePath)) { + return $this->response->download($filePath, null); + } else { + $data['message'] = 'The Physical File Not Found'; + echo view('errors/404', $data); + } + } catch (\Exception $e) { + $this->myLogger->logme('error', $e->getMessage()); + return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.'); + } + } + } diff --git a/app/Helpers/ChatbotHelper.php b/app/Helpers/ChatbotHelper.php index 6dff5c6c..e1f213d3 100644 --- a/app/Helpers/ChatbotHelper.php +++ b/app/Helpers/ChatbotHelper.php @@ -201,7 +201,7 @@ class ChatbotHelper $message = SELF::quotationRequestMailTemplate($data); $common = ['mail_type'=>'request_quotation_bot']; - $email_id = 'no-reply-otp@nhanceindia.in'; + $email_id = getenv('email.enquiryMail'); $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Quotation Request Received from bot.', 'message' => $message,'common'=>$common]); $res = json_decode($res); @@ -224,13 +224,22 @@ class ChatbotHelper } public static function getReimbursementClaimStatus($chat_session_info){ + + $client_claim_status = [ + 'Received' => [1,2,3,4], + 'Under Process' => [5,6,7,10], + 'Finished' => [9,11,12], + 'Rejected' => [8], + 'Cancelled' => [13,14] + ]; $emp_id = $chat_session_info['emp_id']; + log_message('error','emp_id'.$emp_id); $emp_code = $chat_session_info['emp_code']; $client_id = $chat_session_info['client_id']; $client_branch_id = $chat_session_info['client_branch_id']; $ticketMaster = new TicketMasterModel(); - $data = $ticketMaster->select('tcs.claim_status,ticket_master.claim_number,ticket_master.id') + $data = $ticketMaster->select('tcs.id as tcs_id,tcs.claim_status,ticket_master.claim_number,ticket_master.id,ticket_master.emp_name,ticket_master.emp_mail') // ->join('client_policy cp',"cp.client_id = {$client_id} and cp.client_branch_id = {$client_branch_id} and cp.policy_id = {$policy_id} and cp.is_active = 1") ->join('ticket_claim_status tcs',"ticket_master.claim_status_id = tcs.id and tcs.is_active = 1") ->where('ticket_master.emp_id',$emp_id) @@ -238,14 +247,38 @@ class ChatbotHelper ->where('ticket_master.is_active',1) ->orderBy('ticket_master.created_at', 'DESC') ->first(); + $server_claim_status = $data['tcs_id']; + $matched_key = null; + foreach ($client_claim_status as $key => $statuses) { + if (in_array($server_claim_status, $statuses)) { + $matched_key = $key; + break; // Stop loop once found + } + } + log_message('error','Data from ticket master'.json_encode($data)); + // print_r($data); + // die(); $ticket_controller = new TicketController(); - if (!empty($data)){ + if (!empty($data) && !empty($matched_key)){ $ticket_id = $data['id']; - $mail_content = $ticket_controller->constructMailContent($ticket_id); - $mail_response = $ticket_controller->sendTrigger($mail_content); - return $data; + $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]); + + $res = json_decode($res); + log_message('error','res: '.json_encode($res)); + if($res->status == 'success') + { + $data['client_status'] = $matched_key; + return $data; + } + else + { + return false; + } }else{ return false; @@ -253,6 +286,283 @@ class ChatbotHelper } + public static function ReimbursementStatusMailTemplate($emp_name, $claim_number, $client_status) { + $template = ' + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+
+
+ + + +
+
+ +
+ + + + + + + +
+ + + + + +
+ + + +
+ +
+ + +
+
+
+ + +
+
+
+ + + + + +
+
+
+ + + +
+
+ +
+ + + + + + + +
+ +
+

 

+

Dear [[member_name]],

+

Your Claim Number [[claim_number]] is currently in the [[status]] status with us.

+

 

+

 

+
+ +
+ + +
+
+
+ + +
+
+
+ + + + + +
+
+
+ + + +
+
+ +
+ + + + + + + +
+ +
+ Alternate image text +
+ +
+ + + + + + + +
+ +
+

ⓒ2024 Nhance India Insurance Broking Pvt Ltd

+
+ +
+ + +
+
+
+ + +
+
+
+ + + + +
+ + + + + + '; + + // Replace placeholders with actual values + $replacedTemplate = str_replace( + ['[[member_name]]', '[[claim_number]]', '[[status]]'], + [$emp_name, $claim_number, $client_status], + $template + ); + + return $replacedTemplate; + } + + } diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php index 0ee54530..d225f71f 100755 --- a/app/Helpers/DepositHelper.php +++ b/app/Helpers/DepositHelper.php @@ -63,6 +63,7 @@ class DepositHelper 'updated_by' => $data['updated_by'], 'balance' => $newBalance, // Include the new balance in the data array 'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null, + 'record_date' => $data['record_date'] ?? null ]; // Insert data and get the insert ID diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index 31bb0f1b..c90eebb3 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -682,7 +682,7 @@ if (!function_exists('generate_relationship_code')) $slug = \Config\Services::slug(); $relationship_code = $slug->slugify($arr['relationship']); $emp_type_code = ($relationship_code == 'self' ? 'EMP_TYP_01' : 'EMP_TYP_03'); - $relationship_code = $gender[ $arr['gender'] ] . $relationship[ $relationship_code ] ; + $relationship_code = $gender[ trim($arr['gender']) ] . $relationship[ trim($relationship_code) ]; return ['relationship_code' => $relationship_code,'emp_type_code' => $emp_type_code]; } } @@ -2173,20 +2173,21 @@ if(!function_exists('group_slab_rates_basedon_name')) //this key generating mandantory for display employee info in enrolment app w/o error -if(!function_exists('generate_family_floater_key')) -{ +if (!function_exists('generate_family_floater_key')) { function generate_family_floater_key($relationship) { if (strtolower(trim($relationship)) === 'mother' || strtolower(trim($relationship)) === 'father') { - $relation = 'parent'; - } else if(strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter'){ - $relation = 'child'; - }else if(strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law'){ - $relation = 'parent_in_law'; - }else if(strtolower(trim($relationship)) === 'spouse'){ - $relation = 'spouse'; - }else{ - $relation = 'self'; - } + $relation = 'parent'; + } else if (strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter') { + $relation = 'child'; + } else if (strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law') { + $relation = 'parent_in_law'; + } else if (strtolower(trim($relationship)) === 'spouse') { + $relation = 'spouse'; + } else { + $relation = 'self'; + } + + return $relation; } } \ No newline at end of file diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index 44bea402..bd66c776 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -1247,7 +1247,7 @@ class sendMailNotification $subject = $notification['subject']; $rand_string = 'HX3kUh'; - $link = generate_download_link($rand_string); + $link = generate_download_link($rand_string).'/1'; $name = 'John Doe'; $mobile = 9080706050; diff --git a/app/Models/ClientDepositModel.php b/app/Models/ClientDepositModel.php index 91bdf1c4..9d45f38f 100755 --- a/app/Models/ClientDepositModel.php +++ b/app/Models/ClientDepositModel.php @@ -27,7 +27,8 @@ class ClientDepositModel extends Model "endorsement_no", "event_name", "unit", - "cd_ac_pk" + "cd_ac_pk", + "record_date" ]; diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index 3f0d7a43..c8fcb855 100755 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -259,6 +259,7 @@ class ClientPolicyModel extends Model ->select('SUM(CASE WHEN sub_type = 3 THEN amount ELSE 0 END) AS total_refund') ->where('client_id', $clientId) ->where('insurer_id', $insurerId) + ->where('cash_deposit.is_active', 1) ->get() ->getRow(); } diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php index d8fd4894..524eb18b 100755 --- a/app/Models/EmployeeModel.php +++ b/app/Models/EmployeeModel.php @@ -149,7 +149,21 @@ class EmployeeModel extends Model { return $this->db->table('employee_polices') - ->select(' policy_type.long_name as Policy_Name , client_policy.policy_terms as Policy_Terms, client_policy.client_id as ClientId, client_policy.policy_id as PolicyId,client_policy.id as ClientPolicyId, client_policy.open_for_enrollment as OpenForEnrollment,client_policy.disclaimer,client_policy.policy_type_id , employee_polices.tpa_id as tpa_id , employee_polices.rand_string as rand_string') // Select all columns from both tables + ->select(' + policy_type.long_name as Policy_Name , + client_policy.policy_terms as Policy_Terms, + client_policy.client_id as ClientId, + client_policy.policy_id as PolicyId, + client_policy.id as ClientPolicyId, + CASE + WHEN client_policy.open_for_enrollment IS NULL THEN 0 + ELSE client_policy.open_for_enrollment + END AS OpenForEnrollment, + client_policy.disclaimer, + client_policy.policy_type_id , + employee_polices.tpa_id as tpa_id , + employee_polices.rand_string as rand_string + ', FALSE) // Select all columns from both tables ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.policy_status', 1) @@ -240,9 +254,9 @@ class EmployeeModel extends Model return $results; } - public function getEmployeeByEmployeeCode($emp_code) + public function getEmployeeByEmployeeCode($emp_code, $client_policy_id = null, $client_id = null) { - return $this->select(" + $query = $this->select(" employees.id AS emp_id, employees.name AS emp_name, employees.emp_code, @@ -255,10 +269,39 @@ class EmployeeModel extends Model ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') ->where('employees.is_active', 1) ->where('employee_polices.is_active', 1) - ->where('employees.emp_code', $emp_code) - ->groupBy('employees.id') - ->findAll(); + ->where('employees.emp_code', $emp_code); + + 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); + } + + $query->groupBy('employees.id'); + $data = $query->findAll(); + + return $data; + + } + public function getAcmUsingClientID($client_id) + { + return $this->db->table('client_rm') + ->select('user_profiles.id, user_profiles.first_name') + ->join('user_profiles', 'client_rm.user_id = user_profiles.id') + ->where([ + 'client_rm.level' => 3, + 'user_profiles.role' => 3, + 'client_rm.is_active' => 1, + 'user_profiles.is_active' => 1, + 'client_rm.client_id' => $client_id + ]) + ->get() + ->getResultArray(); + } + } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 0f030dae..960f37d0 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -886,7 +886,6 @@ class EmployeePolicyModel extends Model LEFT JOIN ( SELECT - emp_code, group_key, MAX(CASE WHEN field_name = 'emp_status' THEN new_value END) AS empstatus, MAX(CASE WHEN field_name = 'change_event' THEN new_value END) AS changeevent, @@ -902,7 +901,7 @@ class EmployeePolicyModel extends Model group_key ) AS deletiondata - ON a.emp_code = deletiondata.emp_code AND a.status != 'truncated' + ON a.group_key = deletiondata.group_key AND a.status != 'truncated' LEFT JOIN ( @@ -1682,7 +1681,10 @@ class EmployeePolicyModel extends Model // reverse the employee policy table data for the truncated the deletion file public function updateEmployeePolicyTruncateReverse($file_id) - { + { + log_message('error', 'updateEmployeePolicyTruncateReverse model function called'); + log_message('error', 'FILE ID : {data}', ['data' => $file_id]); + $this->db->query(" UPDATE employee_polices SET @@ -1690,7 +1692,7 @@ class EmployeePolicyModel extends Model status = 'active', date_of_exit = NULL, reason_for_exit = NULL, - claim_status = 0, + claim_status = 0 WHERE id IN ( SELECT pk diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 5867a5d0..bc47a3ff 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -120,10 +120,10 @@ class LeadsModel extends Model return $data; } - public function getLeadDataForLising() + public function getLeadDataForLising($where = null) { - return $this->select(' + $data = $this->select(' leads.*, kyc_entity_type.name as entity_type, policy_type.policy_type, @@ -144,13 +144,16 @@ class LeadsModel extends Model ) AS rfq_count ') - ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') - ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') - ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') - ->where('leads.is_active', 1) - ->orderBy('id', 'desc') - ->findAll(); + ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') + ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->where('leads.is_active', 1); + if (!empty($where)) { + $data->where($where); + } + + return $data->orderBy('leads.id', 'desc')->findAll(); } public function getLeadForInsertClientList($type = null, $client_id = null) diff --git a/app/Models/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php index dc6b2cec..1b2c84fd 100644 --- a/app/Models/PTCOShareDetailsModel.php +++ b/app/Models/PTCOShareDetailsModel.php @@ -66,6 +66,8 @@ class PTCOShareDetailsModel extends Model 'statement_id', 'follower_policy_no', 'non_comm_per_amt', + 'cotp_amt', + 'cotep_amt', ]; public function getNonReconcileredPolicyTransactions(string $insurer_id,string $insurer_branch_id) diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php index 246609cd..136529d6 100644 --- a/app/Models/PolicyTransactionModel.php +++ b/app/Models/PolicyTransactionModel.php @@ -318,6 +318,280 @@ class PolicyTransactionModel extends Model // BDS Report NEW Functin for QUERY // public function getBDSReportList($client_id, $policy_id, $branch_id, $issuer) + + // public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) + // { + + // $date_condition = ''; + // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + // $date_condition = " + // AND insurer_statements.month >= '".$start_date ."' + // AND insurer_statements.month <= '".$end_date ."' + // "; + // } + + // $builder = $this->db->table('policy_transaction') + // ->select(" + // policy_transaction.*, + // DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + // DATE_FORMAT( + // IF(policy_transaction.month IS NULL, + // policy_transaction.policy_issue_date, + // policy_transaction.month), + // '%b %Y') AS policy_issue_month, + // CASE + // WHEN clients.client_type = 1 THEN 'Group' + // WHEN clients.client_type = 2 THEN 'Retail' + // ELSE '-' + // END AS client_type, + // CASE + // WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' + // ELSE 'Renewal' + // END AS revenue_type, + // CASE + // WHEN policy_transaction.action_type = 'inception' THEN 'Policy' + // ELSE 'Endorsement' + // END AS action_type, + // clients.client_name AS client_name, + // clients.short_name AS client_short_name, + // client_branch.branch_name AS client_branch_name, + // client_branch.address1 AS client_address, + // policy_type.policy_type, + // policy_type.bap, + // insurers.name AS insurer_name, + // insurers.short_name AS insurer_short_name, + // insurer_branch.branch_name AS insurer_branch_name, + // insurer_branch.branch_code AS insurer_branch_code, + // user_profiles.first_name as user_name, + // vehicle.vehicle_no, + // tpa.name as tpa_name, + // pt_co_share_details.remark as remarks, + // pt_co_share_details.bp_amt, + // pt_co_share_details.exp_amt, + // pt_co_share_details.id as pt_id, + // sales_user.first_name as salse_person_name, + // service_user.first_name as service_person_name, + + // ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, + + // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, + + // ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, + + // ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, + + // DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, + + // (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, + + // pt_co_share_details.agreed_bp_per, + // ROUND( + // ( + // SELECT + // ( + // SUM(co_share_stmt_details.actual_bp_brokerage_amt) + + // SUM(co_share_stmt_details.actual_tp_brokerage_amt) + + // SUM(co_share_stmt_details.actual_tep_brokerage_amt) + + // SUM(co_share_stmt_details.reward) + + // ) AS total_irda_amt + // FROM + // co_share_stmt_details + // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + // WHERE + // co_share_stmt_details.co_share_id = pt_co_share_details.id + // AND co_share_stmt_details.is_active = 1 + // AND insurer_statements.is_active = 1 + // $date_condition + // ), + // 2 + // ) AS total_irda_amt, + // ROUND( + // ( + // SELECT + // ( + // SUM(co_share_stmt_details.reward) + + // ) AS reward + // FROM + // co_share_stmt_details + // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + // WHERE + // co_share_stmt_details.co_share_id = pt_co_share_details.id + // AND co_share_stmt_details.is_active = 1 + // AND insurer_statements.is_active = 1 + // $date_condition + // ), + // 2 + // ) AS reward, + + // ROUND( + // ( + // SELECT + // SUM( + // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + + // COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + + // COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + + // COALESCE(co_share_stmt_details.reward, 0) + // ) AS total_irda_amt + // FROM + // co_share_stmt_details + // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id + // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + // WHERE + // co_share_stmt_details.co_share_id = pt_co_share_details.id + // AND co_share_stmt_details.is_active = 1 + // AND pt_table.is_active = 1 + // AND insurer_statements.is_active = 1 + // AND insurer_statements.invoice_status IS NOT NULL + // $date_condition + + // ), + // 2 + // ) AS billed_amt, + + // ROUND( + // ( + // ( + // SELECT + // SUM( + // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.reward, 0) + // ) + // FROM + // co_share_stmt_details + // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + // WHERE + // co_share_stmt_details.co_share_id = pt_co_share_details.id + // AND co_share_stmt_details.is_active = 1 + // $date_condition + // ) + // - + // ( + // SELECT + // SUM( + // COALESCE(co_share_stmt_details.actual_bp_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.actual_tp_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.actual_tep_brokerage_amt, 0) + // + COALESCE(co_share_stmt_details.reward, 0) + // ) + // FROM + // co_share_stmt_details + // JOIN pt_co_share_details AS pt_table ON co_share_stmt_details.co_share_id = pt_table.id + // JOIN insurer_statements ON co_share_stmt_details.statement_id = insurer_statements.id + // WHERE + // co_share_stmt_details.co_share_id = pt_co_share_details.id + // AND co_share_stmt_details.is_active = 1 + // AND pt_table.is_active = 1 + // AND insurer_statements.is_active = 1 + // AND insurer_statements.invoice_status IS NULL + // $date_condition + // ) + // ), + // 2 + // ) AS unbilled_amt + + // ") + // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + // // ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') + // ->join('clients', 'clients.id = policy_transaction.client_id') + // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + // ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') + // ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') + // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + // ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') + // ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') + // ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') + // ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') + // ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') + // ->where('policy_transaction.is_active', 1) + // ->where('pt_co_share_details.is_active', 1); + + // // Check if the start date and end date are provided + // if ($start_date != 0 && $end_date != 0 && $date_type != 0 && $date_type != 'statement_month') { + + // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + // $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + // ->where('policy_transaction.'.$date_type.'<=', $endDate); + + // } + + // // if($date_type == 'statement_month' && $start_date != 0 && $end_date != 0){ + + // // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + // // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + // // $builder->where('policy_transaction.month >=', $startDate) + // // ->where('policy_transaction.month <=', $endDate); + // // } + + // // Conditionally join insurer_statements if $date_type == 'statement_month' + // if ($date_type == 'statement_month' && $start_date != 0 && $end_date != 0) { + // $startDate = date('Y-m-d', strtotime($start_date)); + // $endDate = date('Y-m-d', strtotime($end_date)); + + // $builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left') + // ->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id','left') + // ->where('insurer_statements.is_active', 1) + // ->where('insurer_statements.month >=', $startDate) + // ->where('insurer_statements.month <=', $endDate) + // ->groupBy('co_share_stmt_details.co_share_id'); + // } + + // if ($client_id != 0) { + // $builder->where('policy_transaction.client_id', $client_id); + // } + + // if ($insurer_id != 0) { + // $builder->where('policy_transaction.insurer_id', $insurer_id); + // } + + // if ($client_branch_id != 0) { + // $builder->where('policy_transaction.client_branch_id', $client_branch_id); + // } + + // if ($insurer_branch_id != 0) { + // $builder->where('policy_transaction.insurer_branch_id', $insurer_branch_id); + // } + + // if ($client_policy_id != 0) { + // $builder->where('policy_transaction.client_policy_id', $client_policy_id); + // } + + + + // if ($policy_type_id != 0) { + // $builder->where('client_policy.policy_type_id', $policy_type_id); + // } + + // if ($issuer != 0) { + // $builder->where('policy_transaction.issuer', $issuer); + // } + + // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + + // } + + // $builder->orderBy('policy_transaction.id', 'desc'); + + // $result = $builder->get()->getResultArray(); + + // // dd($this->db->getLastQuery()); + + // return $result; + // } + public function getBDSReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $client_branch_id = 0, $insurer_branch_id = 0, $client_policy_id = 0) { @@ -365,19 +639,19 @@ class PolicyTransactionModel extends Model vehicle.vehicle_no, tpa.name as tpa_name, pt_co_share_details.remark as remarks, - pt_co_share_details.bp_amt, + pt_co_share_details.cop_amt as bp_amt, pt_co_share_details.exp_amt, pt_co_share_details.id as pt_id, sales_user.first_name as salse_person_name, service_user.first_name as service_person_name, - ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, + ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS premium_wo_gst, - ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2) AS gst_amount, - ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) + ROUND((ROUND((pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, - ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, + ROUND((pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 2) AS tp_or_ter, DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, @@ -501,8 +775,8 @@ class PolicyTransactionModel extends Model ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') - ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left') - ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('insurer_branch', 'pt_co_share_details.insurer_branch_id = insurer_branch.id', 'left') ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') @@ -591,9 +865,89 @@ class PolicyTransactionModel extends Model return $result; } + // public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + // { + // // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); + // $builder = $this->db->table('policy_transaction') + // ->select(' + // policy_transaction.*, + // clients.short_name AS client_short_name, + // clients.client_code, + // clients.client_type, + // clients.client_name, + // client_branch.branch_name AS client_branch_name, + // insurers.name AS insurer_name, + // insurers.short_name AS insurer_short_name, + // policy_type.policy_type, + // pt_co_share_details.agreed_amt AS amount, + // pt_co_share_details.bp_amt AS bp, + // pt_co_share_details.tp_amt AS tp + // ') + // ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + // ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + // ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + // ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + // ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + // ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + // ->where('policy_transaction.is_active', 1) + // ->where('policy_transaction.action_type', 'inception'); + + // if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + // $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + // $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + // $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + // ->where('policy_transaction.'.$date_type.'<=', $endDate); + // }else{ + + // // $fromDate = date('Y-m-d', strtotime('-30 days')); + // // $toDate = date('Y-m-d 23:59:59'); + + // // $builder->where('policy_transaction.created_at >=', $fromDate) + // // ->where('policy_transaction.created_at <=', $toDate); + // } + + // if ($client_id != 0) { + // $builder->where('policy_transaction.client_id', $client_id); + // } + + // if ($insurer_id != 0) { + // $builder->where('policy_transaction.insurer_id', $insurer_id); + // } + + // if ($policy_type_id != 0) { + // $builder->where('client_policy.policy_type_id', $policy_type_id); + // } + + // if ($issuer != 0) { + // $builder->where('policy_transaction.issuer', $issuer); + // } + // if ($status != 0) { + // $builder->where('policy_transaction.status', $status); + // } + + // if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + + // } + + // $builder->orderBy('policy_transaction.id', 'desc')->limit(10); + + // $result = $builder->get()->getResultArray(); + + // // dd($this->db->getLastQuery()); + + // return $result; + // } + public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { - // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); $builder = $this->db->table('policy_transaction') ->select(' policy_transaction.*, @@ -607,7 +961,8 @@ class PolicyTransactionModel extends Model policy_type.policy_type, pt_co_share_details.agreed_amt AS amount, pt_co_share_details.bp_amt AS bp, - pt_co_share_details.tp_amt AS tp + pt_co_share_details.tp_amt AS tp, + clients.pan ') ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') ->join('clients', 'clients.id = policy_transaction.client_id', 'left') @@ -618,59 +973,44 @@ class PolicyTransactionModel extends Model ->where('policy_transaction.is_active', 1) ->where('policy_transaction.action_type', 'inception'); - if ($start_date != 0 && $end_date != 0 && $date_type != 0) { - - $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); - $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); - - $builder->where('policy_transaction.'.$date_type.'>=', $startDate) - ->where('policy_transaction.'.$date_type.'<=', $endDate); - }else{ - - // $fromDate = date('Y-m-d', strtotime('-30 days')); - // $toDate = date('Y-m-d 23:59:59'); - - // $builder->where('policy_transaction.created_at >=', $fromDate) - // ->where('policy_transaction.created_at <=', $toDate); + // Optimize Date Filtering + if (!empty($start_date) && !empty($end_date) && !empty($date_type)) { + $builder->where("policy_transaction.$date_type >=", date('Y-m-d 00:00:00', strtotime($start_date))) + ->where("policy_transaction.$date_type <=", date('Y-m-d 23:59:59', strtotime($end_date))); } - if ($client_id != 0) { + // Apply Filters Only When Necessary + if (!empty($client_id)) { $builder->where('policy_transaction.client_id', $client_id); } - - if ($insurer_id != 0) { + if (!empty($insurer_id)) { $builder->where('policy_transaction.insurer_id', $insurer_id); } - - if ($policy_type_id != 0) { + if (!empty($policy_type_id)) { $builder->where('client_policy.policy_type_id', $policy_type_id); } - - if ($issuer != 0) { + if (!empty($issuer)) { $builder->where('policy_transaction.issuer', $issuer); } - if ($status != 0) { + if (!empty($status)) { $builder->where('policy_transaction.status', $status); } - if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ - + // Default to Last 30 Days if No Filters Are Applied + if (empty($client_id) && empty($insurer_id) && empty($policy_type_id) && empty($date_type) && empty($issuer)) { $fromDate = date('Y-m-d', strtotime('-30 days')); $toDate = date('Y-m-d 23:59:59'); - + $builder->where('policy_transaction.created_at >=', $fromDate) ->where('policy_transaction.created_at <=', $toDate); - } - + + // Optimize Query Execution $builder->orderBy('policy_transaction.id', 'desc'); - $result = $builder->get()->getResultArray(); - - // dd($this->db->getLastQuery()); - - return $result; + return $builder->get()->getResultArray(); } + public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) { @@ -761,7 +1101,7 @@ class PolicyTransactionModel extends Model pt_co_share_details.exp_amt, pt_co_share_details.variance, - ROUND ( (pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt),2) as original_premium, + ROUND ( (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt),2) as original_premium, ROUND( ( SELECT @@ -779,7 +1119,7 @@ class PolicyTransactionModel extends Model ) AS statement_premium, COALESCE( - (pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 0 + (pt_co_share_details.cop_amt + pt_co_share_details.cotp_amt + pt_co_share_details.cotep_amt), 0 ) - COALESCE( ( diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php index 2b1560e0..2e51f2aa 100644 --- a/app/Models/RFQModel.php +++ b/app/Models/RFQModel.php @@ -77,6 +77,7 @@ class RFQModel extends Model ->where('rfq.lead_id', $lead_id) // ->where('rfq.type', $type) ->where('rfq.is_active', 1) + ->orderBy('rfq.id', 'desc') ->first(); } diff --git a/app/Models/TicketMasterModel.php b/app/Models/TicketMasterModel.php index fbcf696c..f75cf2a6 100644 --- a/app/Models/TicketMasterModel.php +++ b/app/Models/TicketMasterModel.php @@ -64,7 +64,18 @@ class TicketMasterModel extends Model 'utr_details', 'settle_letter', 'is_head_approved', - ]; + + 'return_remark', + 'cancel_remark', + 'awb_no_courier_name', + + 'non_id_reason', + 'head_rejection_reason', + 'pay_initiate_date', + 'emp_personal_mail', + 'client_policy_id' + + ]; // Callbacks @@ -118,14 +129,20 @@ class TicketMasterModel extends Model public function getTemplateDataByTicketID($ticket_id) { $template_data = $this - ->select("ticket_mail_template.*, ticket_master.emp_mail,ticket_master.claim_status_id") + ->select("ticket_mail_template.*, CASE + WHEN employees.email_corporate IS NULL OR employees.email_corporate = '' + THEN ticket_master.emp_mail + ELSE employees.email_corporate + END as emp_mail, ,ticket_master.claim_status_id") ->join('ticket_claim_status', 'ticket_master.claim_status_id = ticket_claim_status.id and ticket_claim_status.is_active = 1') ->join('ticket_mail_template', ' ticket_claim_status.trigger_type = ticket_mail_template.trigger_type and ticket_claim_status.ticket_type = ticket_mail_template.ticket_type and ticket_mail_template.is_active = 1') + ->join('employees','employees.id = ticket_master.emp_id','left') ->where('ticket_master.id', $ticket_id) ->where('ticket_master.is_active', 1) + ->where('ticket_claim_status.is_active', 1) ->first(); return $template_data; @@ -135,6 +152,11 @@ class TicketMasterModel extends Model { $ticket_data = $this->select(" ticket_master.*, + CASE + WHEN employees.email_corporate IS NULL OR employees.email_corporate = '' + THEN ticket_master.emp_mail + ELSE employees.email_corporate + END as emp_mail, user_profiles.first_name as acm, user_profiles.mobile as acm_mobile, @@ -152,6 +174,7 @@ class TicketMasterModel extends Model ->join('tpa', 'ticket_master.tpa_id = tpa.id', 'left') ->join('ticket_notes', 'ticket_master.id = ticket_notes.ticket_id and ticket_notes.is_active = 1 and ticket_notes.is_auto_query = 1','left') ->join('user_profiles', 'ticket_master.acm_id = user_profiles.id', 'left') + ->join('employees','employees.id = ticket_master.emp_id','left') ->where('ticket_master.id', $ticket_id) ->where('ticket_master.is_active', 1) ->first(); @@ -659,5 +682,27 @@ class TicketMasterModel extends Model return $result; } } + + //api + public function get_ticket_data($emp_id, $ticket_type = null, $ticket_id = null) + { + $query = $this->select('ticket_master.*, tms.mail_subject as subject') + ->join('ticket_messages tms', 'ticket_master.id = tms.ticket_id', 'left') + ->where('ticket_master.is_active', 1) + ->where('ticket_master.emp_id', $emp_id); + + if (!empty($ticket_id)) { + $query->where('ticket_master.id', $ticket_id); + } + + if (!empty($ticket_type)) { + $query->where('ticket_master.ticket_type_id', $ticket_type); + } + + $data = $query->findAll(); + // dd($data, db_connect()->getLastQuery()); + return $data; + } + } diff --git a/app/Views/chatbot.php b/app/Views/chatbot.php index 14a5f652..94373196 100644 --- a/app/Views/chatbot.php +++ b/app/Views/chatbot.php @@ -63,7 +63,7 @@ if (window.botmanWidget) { botmanChatWidget.open(); setTimeout(function(){ - botmanChatWidget.sayAsBot('Hi '+ emp_name +',This is ILA your Insurance Assistant, plz choose the following options') + botmanChatWidget.sayAsBot('Hi '+ (typeof emp_name !== "undefined" && emp_name !== null && emp_name !== "" ? emp_name : "Guest User") +',This is ILA your Insurance Assistant, plz choose the following options') botmanChatWidget.whisper('Hi'); },3000); diff --git a/app/Views/client_list.php b/app/Views/client_list.php index ce079c60..592031dc 100755 --- a/app/Views/client_list.php +++ b/app/Views/client_list.php @@ -202,6 +202,7 @@ table.dataTable thead th { customDropdown.querySelectorAll('.dropdown-item').forEach(item => { item.addEventListener('click', function(e) { + e.preventDefault(); const onclickAttr = this.getAttribute('onclick'); if (onclickAttr) { eval(onclickAttr); diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 93fc893d..9dd0956c 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -46,6 +46,38 @@ + +
@@ -154,6 +186,8 @@ ) { ?> Edit + Employee History + @@ -270,6 +304,20 @@
+ + + + diff --git a/app/Views/employee_list.php b/app/Views/employee_list.php index 976e2f69..292d5c21 100755 --- a/app/Views/employee_list.php +++ b/app/Views/employee_list.php @@ -232,7 +232,6 @@ table.dataTable tbody td { document.addEventListener("DOMContentLoaded", init); function init() { - const table = document.getElementById("tickets-table"); let activeDropdown = null; @@ -264,8 +263,21 @@ function init() { const customDropdown = document.createElement('div'); customDropdown.className = 'custom-dropdown-menu'; + + // Clone original dropdown items while moving onclick handlers to data attributes + const originalItems = originalDropdown.querySelectorAll('.dropdown-item'); customDropdown.innerHTML = originalDropdown.innerHTML; + // Transfer onclick handlers to data attributes + customDropdown.querySelectorAll('.dropdown-item').forEach((item, index) => { + const originalItem = originalItems[index]; + const originalOnclick = originalItem.getAttribute('onclick'); + if (originalOnclick) { + item.setAttribute('data-onclick', originalOnclick); + item.removeAttribute('onclick'); // Remove original handler + } + }); + return customDropdown; } @@ -287,11 +299,15 @@ function init() { } function handleItemClick(e, item) { - const onclickAttr = item.getAttribute('onclick'); + e.preventDefault(); + + // Execute the stored onclick handler + const onclickAttr = item.getAttribute('data-onclick'); if (onclickAttr) { eval(onclickAttr); } + // Handle href navigation const href = item.getAttribute('href'); if (href && href !== '#') { window.location.href = href; diff --git a/app/Views/enrollment_dash.php b/app/Views/enrollment_dash.php index 88d9fda6..e9256345 100755 --- a/app/Views/enrollment_dash.php +++ b/app/Views/enrollment_dash.php @@ -1,9 +1,9 @@ -
-
+
@@ -14,7 +14,8 @@
- +
@@ -25,36 +26,46 @@ $currentItem = 0; // Counter for items $isActive = true; // Variable to set the first item as active foreach ($client_branch_emp_list as $clients) { - foreach ($clients['branches'] as $branches) { + // Start a new carousel item if needed if ($currentItem % $itemsPerSlide == 0) { if (!$isActive) echo '
'; // Close previous carousel item - echo '