diff --git a/.htaccess b/.htaccess index 34427d9c..cf3c1842 100644 --- a/.htaccess +++ b/.htaccess @@ -36,6 +36,24 @@ Options -Indexes # Ensure Authorization header is passed along RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + + + + + +ExpiresActive On +ExpiresByType image/jpg "access 1 year" +ExpiresByType image/jpeg "access 1 year" +ExpiresByType image/gif "access 1 year" +ExpiresByType image/png "access 1 year" +ExpiresByType text/css "access 1 month" +ExpiresByType text/js "access 1 month" +ExpiresByType application/pdf "access 1 month" +ExpiresByType application/javascript "access 1 month" +ExpiresByType application/x-javascript "access 1 month" +ExpiresByType application/x-shockwave-flash "access 1 month" +ExpiresByType image/x-icon "access 1 year" +ExpiresDefault "access 2 days" diff --git a/app/Config/App.php b/app/Config/App.php index 884c19f1..03514f13 100644 --- a/app/Config/App.php +++ b/app/Config/App.php @@ -42,6 +42,9 @@ class App extends BaseConfig */ public string $indexPage = 'index.php'; + + public $compressOutput = true; + /** * -------------------------------------------------------------------------- * URI PROTOCOL diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 402721b0..3af4c7ec 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -122,6 +122,7 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->group("terms", ["filter" => "authMVC"], function ($routes) { $routes->post("gpa_create", "ClientController::policyGPATerms"); $routes->post("edit", "ClientController::editClientPolicyPremium"); + $routes->post("other_terms", "ClientController::otherPolicyTermsFormSubmit"); }); }); @@ -214,6 +215,14 @@ $routes->group("/master", ["filter" => "authMVC"], function ($routes) { $routes->get("remove/(:any)", "MasterController::removePolicyPolicies/$1"); }); }); + + $routes->group("cash_deposite", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "MasterController::CDMasterList"); + $routes->post("create", "MasterController::createCDMasterData"); + $routes->post("edit", "MasterController::editCDMasterData"); + $routes->get("list/(:any)", "MasterController::getCDMasterDataByID/$1"); + $routes->get("remove/(:any)", "MasterController::removeCDMaster/$1"); + }); }); @@ -242,6 +251,12 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("get-client-branch/(:any)", "ClientController::getClientBranch/$1"); $routes->get("get-client-details/(:any)", "ClientController::getClientAllDetailsByUsingClientID/$1"); $routes->get("delete-additional-rack-rate/(:any)", "ClientController::deleteAdditionalRackRate/$1"); + $routes->get("check_cd_ac_no/(:any)", "MasterController::checkUniqueCDAccountNumber/$1"); + $routes->get("get_cd_ac/(:any)", "ClientController::get_cd_ac/$1"); + $routes->get("check_policy_type/(:any)", "ClientController::checkPolicyType/$1"); + $routes->get("getPolicyTerms/(:any)", "ClientController::getPolicyTerms/$1"); + $routes->get("getPolicyTermsFormJson/(:any)", "ClientController::getPolicyTermsFormJson/$1"); + $routes->get("checkHRNumber/(:any)", "ClientController::checkHRNumber/$1"); }); $routes->cli('cli/processjob', 'JobWorker::processJob'); @@ -265,9 +280,9 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { - +$routes->get("getChatResponse", "ChatBotController::getChatResponse"); $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { - + $routes->get("getChatResponse", "ChatBotController::getChatResponse"); $routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile"); $routes->post("employeeUpload", "EmployeeRestController::employeeUpload"); $routes->get("relationshipList", "EmployeeRestController::relationshipList"); @@ -298,6 +313,9 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); }); + + + $routes->post("sendEmail", "EmployeeRestController::send_email"); diff --git a/app/Controllers/ChatBotController.php b/app/Controllers/ChatBotController.php new file mode 100644 index 00000000..d048ada7 --- /dev/null +++ b/app/Controllers/ChatBotController.php @@ -0,0 +1,118 @@ +myLogger = \Config\Services::mylogger(); + $this->employeeModel = new EmployeeModel(); + $this->employeePolicyModel = new EmployeePolicyModel(); + $this->clientModel = new ClientModel(); + $this->clientRMModel = new ClientRMModel(); + $this->policesModel = new PolicesModel(); + $this->relationshipModel = new RelationshipModel(); + $this->fileModel= new FileModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->policyPremium1Model = new PolicyPremium1Model(); + $this->policyPremium2Model = new PolicyPremium2Model(); + $this->policyTypeModel = new PolicyTypeModel(); + $this->notificationModel = new NotificationModel(); + $this->userModel = new UserModel(); + $this->feContentModel = new FEContentModel(); + $this->addImgModel = new AddImgModel(); + $this->ChatBotModel = new ChatBotModel(); + } + + + public function getChatResponse() + { + // try { + $request_for = $this->request->getGet('request_for'); + $option = $this->request->getGet('option'); + + $requestData = $this->ChatBotModel->where('request', $request_for) + ->where('is_active', 1 ) + ->first(); + + if ($requestData) { + + + + if($option != 0){ + + $decodedData = json_decode($requestData['options'],true); + + $requestFor = $decodedData[$request_for][$option]; + + $requestData = $this->ChatBotModel->where('request', $requestFor) + ->where('is_active', 1 ) + ->first(); + } + + + $result = ['request_for'=>$requestData['request'],'options'=>json_decode($requestData['options'],true)]; + return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); + + + + + } else { + + return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + } + // } catch (\Throwable $th) { + // return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); + // } + } + + + +} + diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 52b3dbca..185ff9ce 100644 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -31,6 +31,10 @@ use App\Models\PolicyPremium2Model; use App\Models\EmployeeModel; use App\Models\EmployeePolicyModel; use App\Models\NotificationModel; +use App\Models\CDMasterModel; +use App\Models\PolicyTypeModel; + + @@ -62,12 +66,15 @@ class ClientController extends AdminController protected $employeeModel; protected $employeePolicyModel; protected $notificationModel; + protected $CDMasterModel; + protected $policyTypeModel; + public function __construct() { set_session_context('Client'); $this->myLogger = \Config\Services::mylogger(); - + $this->clientModel = new ClientModel(); $this->userModel = new UserModel(); $this->clientBranchModel = new ClientBranchModel(); @@ -89,7 +96,11 @@ class ClientController extends AdminController $this->policyPremium2Model = new PolicyPremium2Model(); $this->employeeModel = new EmployeeModel(); $this->employeePolicyModel = new EmployeePolicyModel(); - $this->notificationModel = new NotificationModel(); + $this->notificationModel = new NotificationModel(); + $this->CDMasterModel = new CDMasterModel(); + $this->policyTypeModel = new PolicyTypeModel(); + + @@ -200,13 +211,21 @@ class ClientController extends AdminController public function view_Deposit($insurerId) { // Load your model to fetch data based on $clientId and $insurerId + // $subTypeOptions = [ + // 1 => 'Deposit', + // 2 => 'Adjustment', + // 3 => 'Refund', + // 4 => 'Debit', + // ]; + $subTypeOptions = [ - 1 => 'Deposit', + 1 => 'Replenishment', 2 => 'Adjustment', - 3 => 'Refund', + 3 => 'Refund From Deletion', 4 => 'Debit', - // Add more options as needed + 5 => 'Asset Policy', ]; + $data['subTypeOptions'] = $subTypeOptions; $headerData['page_name'] = 'Client Deposit'; $data['insurerName']= $this->insurerModel->getInsurerName($insurerId); @@ -231,20 +250,33 @@ class ClientController extends AdminController // Retrieve form data from POST request $loggedInUserID = get_session_userid(); + $client_id = $this->request->getPost('client_id'); + $insurer_id = $this->request->getPost('insurer_id'); + + $CD_Account_Number = $this->CDMasterModel + ->where('client_id', $client_id) + ->where('insurer_id', $insurer_id) + ->first(); + // Prepare the array with data $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, + '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, // You need to set the correct value for updated_by + 'updated_by' => 1, ]; + // Call the saveDeposit function from DepositHelper $response = DepositHelper::saveDeposit($data, $loggedInUserID); + // Return a boolean value based on success return $this->response->setJSON(['success' => $response['success']]); } @@ -271,9 +303,9 @@ class ClientController extends AdminController $editData['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $id)->findAll(); $editData['client_branch'] = $this->clientBranchModel->where(['client_id' => $id, 'is_active' => 1])->findAll(); $editData['client_relation'] = $this->clientRMModel->where(['client_id' => $id, 'is_active' => 1])->findAll(); - // dd('Hi'); + $editData['client_branch']['role'] = get_role_id(); $clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($id); - // dd($this->clientPolicyModel->getLastQuery()); + foreach ($clientPoliceData as $key => $value) { $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date)); @@ -281,12 +313,10 @@ class ClientController extends AdminController } $editData['client_policy'] = $clientPoliceData; - - $editData['notification'] =$this->notificationModel->select('template_name,enabled')->where('client_id',$id)->findAll(); $editData['placeHolders'] = ['member_name','nhance_logo','tpa_id','ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name']; - + // dd($editData); echo view('layout/header', $headerData); echo view('client_onboarding', $editData); echo view('layout/footer'); @@ -535,6 +565,7 @@ class ClientController extends AdminController if($insert){ $branchData = $this->clientBranchModel->where('client_id', $this->request->getPost('client_id'))->findAll(); + $branchData['role'] = get_role_id(); return $this->respond(['status' => true,'code' => 200,'data' => $branchData], 200); }else{ return $this->respond(['status' => false,'code' => 404, 'message' => 'no data found'], 200); @@ -588,22 +619,13 @@ class ClientController extends AdminController $policy_type_id = $this->request->getPost('policy_type_id'); $client_branch_id = $this->request->getPost('client_branch_id'); - - $policyCount = $this->clientPolicyModel - ->where('policy_type_id', $policy_type_id) - ->where('client_branch_id', $client_branch_id) - ->countAllResults(); - - if($policyCount > 0 ){ - $clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($this->request->getPost('client_id')); - return $this->respond(['status' => 'policy_exist','code' => 200,'data' => $clientPoliceData, 'method' => 'CERATE'], 200); - } - - $insurerValue = (string) $this->request->getPost('insurer'); - list($insurerBranchId, $insurerId) = explode('-', $insurerValue); $client_id = $this->request->getPost('client_id'); + $insurerValue = (string) $this->request->getPost('insurer'); + list($insurerBranchId, $insurerId) = explode('-', $insurerValue); + + $data['insurer_branch_id'] = $insurerBranchId; $data['insurer_id'] = $insurerId; @@ -638,7 +660,9 @@ class ClientController extends AdminController $data['base_policy'] = $this->request->getPost('base_policy'); $data['policy_status'] = 1; $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; - $data['client_branch_id'] = $this->request->getPost('client_branch_id'); + $data['client_branch_id'] = $this->request->getPost('client_branch_id'); + $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['gst'] = $this->request->getPost('gst'); @@ -733,10 +757,11 @@ class ClientController extends AdminController $data['base_policy'] = $this->request->getPost('base_policy'); $data['policy_status'] = 1; $data['inception_type'] = $this->request->getPost('inception_type') ? 2 : 1; - $data['client_branch_id'] = $this->request->getPost('client_branch_id'); - - + $data['client_branch_id'] = $this->request->getPost('client_branch_id'); + $data['cd_ac_no'] = $this->request->getPost('cd_ac_no'); + $data['gst'] = $this->request->getPost('gst'); + $policy_terms = $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first(); if ( $this->request->getPost('is_addon') == 2 || $this->request->getPost('is_addon') == 3) { @@ -884,6 +909,24 @@ class ClientController extends AdminController $policyPremium = $this->policyPremium1Model->insert($data); } + }else if ($si_or_bp == '2') { + + $premium = str_replace(',', '', $this->request->getPost('gpa_basic_premium[]')); + $sum_insure = str_replace(',', '', $this->request->getPost('gpa_basic_si[]')); + $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay[]')); + + for ($i = 0; $i < count($premium); $i++) { + + $data['si_or_bp'] = $this->request->getPost('si_or_bp'); + $data['basic_multiplier'] = str_replace(',', '', $this->request->getPost('basic_multiplier')); + $data['multiplier'] = $this->request->getPost('premium_multiplier'); + $data['basic_pay'] = $basic_pay[$i]; + $data['si'] = $sum_insure[$i]; + $data['premium'] = $premium[$i]; + + $policyPremium = $this->policyPremium1Model->insert($data); + } + }else { $data['premium'] = str_replace(',', '', $this->request->getPost('gpa_basic_premium')); @@ -1140,9 +1183,10 @@ class ClientController extends AdminController $client_id = $client_policy_data['client_id']; $polices = $this->policesModel->where(['insurer_id' => $insurer_id, 'is_active' => 1])->findAll(); $client_policy_list = $this->clientPolicyModel->getpolicyWithPattern( $client_id ); + $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll(); - return $this->respond(['status' => true,'code' => 200, 'client_policy_list' => $client_policy_list, 'data' => $client_policy_data, "insurer_id" => $client_policy_data['insurer_id'], 'policy' => $polices], 200); + return $this->respond(['status' => true,'code' => 200, 'client_policy_list' => $client_policy_list, 'data' => $client_policy_data, 'cd_data' => $cd_data, "insurer_id" => $client_policy_data['insurer_id'], 'policy' => $polices], 200); }else{ return $this->respond(['status' => false,'code' => 404, 'message' => 'no data found'], 200); } @@ -1177,19 +1221,11 @@ class ClientController extends AdminController $emp_count = $this->employeePolicyModel - ->join('client_policy cp', "cp.id = employee_polices.client_policy_id") - ->where("employee_polices.client_policy_id", $client_policy_id) - ->where("employee_polices.status", 'active') - ->where("employee_polices.is_active", 1) - ->countAllResults(); - - // $emp_count = count($data); - - // if($emp_count == 0){ - // $emp_count = true; - // }else{ - // $emp_count = false; - // } + ->join('client_policy cp', "cp.id = employee_polices.client_policy_id") + ->where("employee_polices.client_policy_id", $client_policy_id) + ->where("employee_polices.status", 'active') + ->where("employee_polices.is_active", 1) + ->countAllResults(); $data = $this->policesModel->getPolicyPremium($record['policy_id']); @@ -1197,9 +1233,11 @@ class ClientController extends AdminController $gmc_pattern = '/gmc/i'; $gpa_pattern = '/gpa/i'; $subject = $data[0]->policy_type; + $policy_type_id = $data[0]->id; + if (preg_match($gmc_pattern, $subject)) { $search_term = 'GMC'; - } else if (preg_match($gpa_pattern, $subject)) { + } else if (preg_match($gpa_pattern, $subject) || $policy_type_id == 6 || $policy_type_id == 7) { $search_term = 'GPA'; } else { $search_term = ""; @@ -1207,7 +1245,7 @@ class ClientController extends AdminController $results = $this->policyGridModel->like('policy_type', $search_term)->findAll(); - if ($search_term === 'GPA') { + if ($search_term === 'GPA' || $policy_type_id == 6 || $policy_type_id == 7) { $premiumData = $this->policyPremium1Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->findAll(); } else if ($search_term === 'GMC') { @@ -1218,9 +1256,6 @@ class ClientController extends AdminController $premiumData = ""; } - - - // echo '
';
         // print_r($premiumData); die;
@@ -1294,7 +1329,7 @@ class ClientController extends AdminController
 
             return $this->respond(['status' => true, 'code' => 200, 'data' => $resultss, 'premiumData' => json_encode($premiumDataa), 'count' => $emp_count, 'policy_name' => $policy_name, 'family_floater' => $family_floater, 'self' => $self, 'client_policy_id' => $client_policy_id], 200);
 
-        } else if ($search_term === 'GPA') {
+        } else if ($search_term === 'GPA' || $policy_type_id == 6 || $policy_type_id == 7) {
 
             return $this->respond(['status' => true, 'code' => 200, 'data' => $results, 'premiumData' => json_encode($premiumData), 'count' => $emp_count, 'policy_name' => $policy_name, 'family_floater' => $family_floater, 'self' => $self, 'client_policy_id' => $client_policy_id], 200);
         } else {
@@ -1315,7 +1350,7 @@ 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['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;
@@ -1399,7 +1434,7 @@ class ClientController extends AdminController
                         }
                     }
 
-                    $data['family_floaters']['elders_count'] =$this->request->getPost("member_count") ? $this->request->getPost("member_count") : 0;
+                    $data['family_floaters']['elders_count'] =$this->request->getPost("elder_member_count") ? $this->request->getPost("elder_member_count") : 0;
 
                     // print_r($data);die;
 
@@ -1427,7 +1462,7 @@ class ClientController extends AdminController
             $data['bioabsorbablestenttoriclensmultifocallens'] =$this->request->getPost("bioabsorbablestenttoriclensmultifocallens");
             $data['roomrentlimit'] =str_replace(',', '',$this->request->getPost("roomrentlimit"));
             $data['proportionatedeductionclause'] =str_replace(',', '',$this->request->getPost("proportionatedeductionclause"));
-            $data['nursingallowance'] =str_replace(',', '',$this->request->getPost("nursingallowance"));
+            // $data['nursingallowance'] =str_replace(',', '',$this->request->getPost("nursingallowance"));
             $data['ailmentcapping'] =str_replace(',', '',$this->request->getPost("ailmentcapping"));
             $data['ambulancecharges'] =str_replace(',', '',$this->request->getPost("ambulancecharges"));
             $data['airambulance'] =str_replace(',', '',$this->request->getPost("airambulance"));
@@ -1435,6 +1470,12 @@ class ClientController extends AdminController
             $data['reasonableandcustomarycharges'] =str_replace(',', '',$this->request->getPost("reasonableandcustomarycharges"));
             $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{
@@ -1455,6 +1496,7 @@ class ClientController extends AdminController
             $data['days_from_dod'] =str_replace(',', '',$this->request->getPost("days_from_dod"));
             $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"));
 
@@ -1509,16 +1551,22 @@ class ClientController extends AdminController
         //     ->where("employees.emp_status",'active')
         //     ->countAllResults();
 
-        $emp_count_by_policy = $this->employeePolicyModel->where('client_policy_id',$client_policy_id)->where('is_active',1)->countAllResults();
+        $emp_count_by_policy = $this->employeePolicyModel
+                        ->where('client_policy_id',$client_policy_id)
+                        ->where("status", 'active')
+                        ->where('is_active',1)
+                        ->countAllResults();
         
-        // if($emp_count == 0){
-        //     $emp_count = true;
-        // }else{
-        //     $emp_count = false;
-        // }
 
         if ($record) {
-            return $this->respond(['Status' => true,'code' => 200,'data' => $record['policy_terms'],  'policy_name' => $policy_name,'policy_addon' => $record['is_addon'], 'emp_count_by_policy'=>$emp_count_by_policy], 200);
+            return $this->respond([
+                'Status' => true,
+                'code' => 200,        
+                'data' => $record['policy_terms'],  
+                'policy_name' => $policy_name,
+                'policy_addon' => $record['is_addon'], 
+                'emp_count_by_policy'=>$emp_count_by_policy],
+            200);
         } else {
             return $this->respond(['Status' => false,'code' => 200,'message' => 'Record not found.',  'policy_name' => $policy_name], 200);
         }
@@ -1584,6 +1632,8 @@ class ClientController extends AdminController
             $data['worldwideCover']        = $this->request->getPost("worldwideCover");
             $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")) ?? [];
+
 
 
             $jsonData = json_encode($data);
@@ -1859,7 +1909,7 @@ class ClientController extends AdminController
             "sum_insured" => "Sum Insured",
             "family_floater" => "Family Floater",
             "family_floaters" => "Family Floaters",
-            "member_count" => "Elders Count:",
+            "elders_count" => "Elders Count:",
             "other_member_min_age" => "Min Age:",
             "other_member_max_age" => "Min Age:",
             "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases",
@@ -1924,8 +1974,6 @@ class ClientController extends AdminController
         ];
           
 
-
-
         foreach ($client_policy as $key => $value) {
 
             $policy_terms = json_decode($value['policy_terms'], true);
@@ -1942,10 +1990,6 @@ class ClientController extends AdminController
 
 
         $data['client_policy'] = $client_policy;
-        
-
-
-
         $data['client_branch'] = $this->clientModel
 
             ->select('
@@ -2025,19 +2069,27 @@ class ClientController extends AdminController
             } else if (array_key_exists($key, $mapping)) {
                 $transformedData[$mapping[$key]] = $value;
             } else if ($key == 'special_condition_label') {
-
-                foreach ($value as $key => $value) {
-                    $transformedData[$value] = $data['special_condition_input'][$key];
+            
+                if (is_array($value)) {
+                    foreach ($value as $key => $value) {
+                        $transformedData[$value] = $data['special_condition_input'][$key];
+                    }
                 }
-            } else if ($key == 'gpa_special_condition_label') {
 
-                foreach ($value as $key => $value) {
-                    $transformedData[$value] = $data['gpa_special_condition_input'][$key];
+            } else if ($key == 'gpa_special_condition_label') {
+                if (is_array($value)) {
+                    foreach ($value as $key => $value) {
+                        $transformedData[$value] = $data['gpa_special_condition_input'][$key];
+                    }
+                }
+            } else if ($key == 'other_special_condition_label') {
+                if (is_array($value)) {
+                    foreach ($value as $key => $value) {
+                        $transformedData[$value] = $data['other_special_condition_label'][$key];
+                    }
                 }
             } else if ($key == 'age_ratio') {
-
                 if (isset($data['sumInsured2'])) {
-
                     $transformedData['Self'] = "(Min: " . $data['age_ratio']['self']['min'] . ", Max: " . $data['age_ratio']['self']['max'] . ")";
                 }
             } else {
@@ -2120,5 +2172,137 @@ class ClientController extends AdminController
     
 
 
+    public function get_cd_ac($client_id, $insurer_id){
+
+        $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();
+
+        if($cd_data){
+            return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200);
+        }else{
+            return $this->respond(['status' => false, 'code' => 404, 'insurer_id' => $insurer_id, 'client_id' => $client_id], 200);
+        }
+
+    }
+
+
+    public function otherPolicyTermsFormSubmit()
+    {
+
+        $client_policy_id = $this->request->getPost("client_policy_id");
+        $policy_terms = $this->request->getPost("policy_terms");
+
+        $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+
+        if ($record) {
+
+            $update = $this->clientPolicyModel->where('id', $client_policy_id)->set('policy_terms',  $policy_terms)->update();
+
+            if ($update) {
+                return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data updated successfully', 'client_policy_id' => $client_policy_id], 200);
+            } else {
+                return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update data', 'formdata' => $this->request->getPost()], 200);
+            }
+        } else {
+
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data. The client policy does not exist', 'formdata' => $this->request->getPost()], 200);
+        }
+    }
+
+
+    public function checkPolicyType($policy_type_id, $client_branch_id, $client_id){
+
+        $policyCount = $this->clientPolicyModel
+        ->where('policy_type_id', $policy_type_id) 
+        ->where('client_branch_id', $client_branch_id)
+        ->where('client_id', $client_id)
+        ->countAllResults(); 
+
+        if($policyCount > 0 ){
+            $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
+            return $this->respond(['status' => true,'code' => 200, 'count' =>  $policyCount, 'data' => $clientPoliceData, 'method' => 'CERATE' ,'client_id' => $client_id, 'client_branch_id' => $client_branch_id, 'policy_type_id' => $policy_type_id], 200);
+        }else{
+            return $this->respond(['status' => false,'code' => 200,'client_id' => $client_id, 'client_branch_id' => $client_branch_id, 'policy_type_id' => $policy_type_id], 200);
+        }
+
+    }
+
+
+    public function getPolicyTerms($client_policy_id)
+    {
+        $policy_terms = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+    
+        if (!$policy_terms) {
+            return $this->respond(['status' => false, 'error' => 'Policy not found'], 404);
+        }
+    
+        if (is_array($policy_terms)) {
+            if (!isset($policy_terms['policy_terms'])) {
+                return $this->respond(['status' => false, 'error' => 'Policy terms not found in array'], 500);
+            }
+            $JSON = json_decode($policy_terms['policy_terms']);
+        } elseif (is_object($policy_terms)) {
+            if (!isset($policy_terms->policy_terms)) {
+                return $this->respond(['status' => false, 'error' => 'Policy terms not found in object'], 500);
+            }
+            $JSON = json_decode($policy_terms->policy_terms);
+        } else {
+            return $this->respond(['status' => false, 'error' => 'Unexpected data type for policy terms'], 500);
+        }
+    
+        if (!$JSON) {
+            return $this->respond(['status' => false, 'error' => 'Invalid JSON format in policy terms'], 500);
+        }
+    
+        $multi_si = [];
+    
+        if (isset($JSON->sum_insured) && !empty($JSON->sum_insured)) {
+            $multi_si[] = $JSON->sum_insured;
+        } elseif (isset($JSON->sumInsured2) && !empty($JSON->sumInsured2)) {
+            $multi_si[] = $JSON->sumInsured2;
+        }
+    
+        if (isset($JSON->multiple_sum_insured) && is_array($JSON->multiple_sum_insured)) {
+            foreach ($JSON->multiple_sum_insured as $msi) {
+                if (!empty($msi)) {
+                    $multi_si[] = $msi;
+                }
+            }
+        }
+    
+        return $this->respond(['status' => true, 'data' => $multi_si], 200);
+    }
+    
+    
+
+    public function getPolicyTermsFormJson($policy_type_id){
+
+        $JSON = $this->policyTypeModel->where('id', $policy_type_id)->first();
+        return $this->respond(['status' => true, 'data' => $JSON], 200);
+    }
+
+    public function createPolicyTermsHtmlAsJSON(){
+
+        
+    }
+
+    public function checkHRNumber($mobileNumber)
+    {
+        try {
+            $mobileNumberCount = $this->levelContactModel
+                            ->join('client_branch', 'client_branch.id = level_contacts.ref_id')
+                            ->join('clients', 'clients.id = client_branch.client_id')
+                            ->where('clients.is_active', 1)
+                            ->where('client_branch.is_active', 1)
+                            ->where('level_contacts.is_active', 1)
+                            ->where('level_contacts.contact_type', 'client')
+                            ->where('level_contacts.mobile', $mobileNumber)
+                            ->countAllResults();
+            return $this->respond(['status' => true, 'data' => $mobileNumberCount, 'message' => "try"], 200);
+        } catch (\Exception $e) {
+            log_message('error', 'Error checking mobile number: ' . $e->getMessage());
+            return $this->respond(['status' => false, 'data' => 0, 'message' => 'An error occurred while checking the mobile number. Please try again later.'], 500);
+        }
+    }
+    
 
 }
\ No newline at end of file
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 1b3fa587..96537b76 100644
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -24,6 +24,7 @@ use App\Models\ClientDepositModel;
 use App\Models\NotificationModel;
 use App\Models\MessageModel;
 use App\Models\UserMessageModel;
+use App\Models\CDMasterModel;
 
 use App\Controllers\Jobs;
 use App\Controllers\JobWorker;
@@ -52,6 +53,8 @@ class EmpDataServiceController extends BaseController
     protected $notificationModel;
     protected $messageModel;
     protected $userMessageModel;
+    protected $CDMasterModel;
+
 
     public function __construct()
     {
@@ -70,6 +73,8 @@ class EmpDataServiceController extends BaseController
         $this->notificationModel    = new NotificationModel();
         $this->messageModel        = new MessageModel();
         $this->userMessageModel          = new UserMessageModel();
+        $this->CDMasterModel    = new CDMasterModel();
+
     }
 
     
@@ -135,9 +140,30 @@ class EmpDataServiceController extends BaseController
 
         // Fetch employee data for export from the database
         $objects = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($export_data);
-        $insurer_id = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first();
-        $cash_balance = $this->clientDepositModel->where('client_id', $export_data['client_id'])->where('insurer_id', $insurer_id['insurer_id'])->orderBy('id', 'DESC')->first();
+        $policy_details = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first();
 
+        // dd($export_data, $policy_details['cd_ac_no']);
+
+        if ($policy_details['cd_ac_no'] == null) {
+            // dd("The policy does not have a CD account number");
+            $this->myLogger->logme('error', 'The policy does not have a CD account number.');
+            return 5;
+        }
+
+        $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first();
+
+        if ($cash_balance == null) {
+
+            $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'])
+                ->first();
+
+            $cash_balance['balance'] = $balance['opening_bal'];
+        }
+
+        // dd($cash_balance);
 
         // Calculate the total amount from the objects
         $totals = array_reduce($objects, function ($carry, $item) {
@@ -147,9 +173,8 @@ class EmpDataServiceController extends BaseController
         $totals = round($totals, 2);
 
         if (!empty($cash_balance)) {
-
+            
             if ((int) $cash_balance['balance']  < (int) $totals) {
-                
                 $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
                 $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
                 return 0;
@@ -188,7 +213,7 @@ class EmpDataServiceController extends BaseController
             'NAME OF EMP/DEP',
             'EMP ID',
             'EMP/DEP TYPE',
-            'RELATION',
+            'RELATIONSHIP CODE',
             'DOB',
             'GENDER',
             'PRE EXISTING AILMENTS',
@@ -352,6 +377,26 @@ class EmpDataServiceController extends BaseController
         $ids = [];
         $objects = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($export_data);
 
+        $policy_details = $this->clientPolicyModel->where('id', $export_data['client_policy_id'])->first();
+
+        if ($policy_details['cd_ac_no'] == null) {
+            $this->myLogger->logme('error', 'The policy does not have a CD account number.');
+            return 1;
+        }
+
+        $cash_balance = $this->clientDepositModel->where('cd_ac_no', $policy_details['cd_ac_no'])->orderBy('id', 'DESC')->first();
+
+        if ($cash_balance == null) {
+
+            $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'])
+                ->first();
+
+            $cash_balance['balance'] = $balance['opening_bal'];
+        }
+
 
         $totals = 0;
         foreach ($objects as $obj) {
@@ -363,6 +408,14 @@ class EmpDataServiceController extends BaseController
         // echo '
';
         // print_r($ids); die;
 
+        if (!empty($cash_balance)) {
+            if ((int) $cash_balance['balance']  < (int) $rounded_totals) {
+                $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
+                $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
+                return 0;
+            }
+        }
+
         $count = count($objects);
         $export_data['count'] = $count;
         $export_data['amount'] = $rounded_totals;
@@ -534,7 +587,7 @@ class EmpDataServiceController extends BaseController
     }
 
 
-
+    //not in use
     public function generateExcelForAdditionAndDependentAddition($export_data)
     {
         $ids = [];
@@ -617,7 +670,7 @@ class EmpDataServiceController extends BaseController
             }
         }
     }
-
+    //end not in use
 
     /**
      * The below functions are Imports data from an Excel file for :
@@ -673,7 +726,7 @@ class EmpDataServiceController extends BaseController
         unset($excel_data[0]);
         array_pop($excel_data);
 
-        $inceptionHeader = ['S.No', 'NAME OF EMP/DEP','EMP ID','EMP/DEP TYPE','RELATION','DOB','GENDER','PRE EXISTING AILMENTS','BASIC COVER SI','DATE OF COVERAGE','AGE','RELATIONSHIP','REMARKS','POLICY END DATE','NO OF DAYS','TPA ID','UHID','PREMIUM','PR0 RATA PREMIUM','GST','TOTAL'];
+        $inceptionHeader = ['S.No', 'NAME OF EMP/DEP','EMP ID','EMP/DEP TYPE','RELATIONSHIP CODE','DOB','GENDER','PRE EXISTING AILMENTS','BASIC COVER SI','DATE OF COVERAGE','AGE','RELATIONSHIP','REMARKS','POLICY END DATE','NO OF DAYS','TPA ID','UHID','PREMIUM','PR0 RATA PREMIUM','GST','TOTAL'];
 
         foreach ($inceptionHeader as $key => $value) {
             if($excel_header[$key] != $value){
@@ -1083,6 +1136,13 @@ class EmpDataServiceController extends BaseController
         $batch_code = $file['batch_code'];
         $user_id = $file['created_by'];
 
+        $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+
+        $CD_Account_Number = $this->CDMasterModel
+                    ->where('client_id', $client_id)
+                    ->where('insurer_id', $insurer_id['insurer_id'])
+                    ->first();
+
 
         $get_policy_type = $this->clientPolicyModel
             ->select('policy_type.policy_type, policies.policy_type_id as policy_type_id')
@@ -1192,6 +1252,8 @@ class EmpDataServiceController extends BaseController
                 'employeeIds' => $emp_policy_ids,
                 'client_id' => $client_id,
                 'client_policy_id' => $client_policy_id,
+                'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+                'endorsement_no' => null,
                 'client_branch_id' => $client_branch_id,
                 'count' => $emp_count,
                 'event' => $file['event_type'],
@@ -2095,6 +2157,13 @@ class EmpDataServiceController extends BaseController
         $batch_code = $file['batch_code'];
         $user_id = $file['created_by'];
 
+        $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+
+        $CD_Account_Number = $this->CDMasterModel
+                    ->where('client_id', $client_id)
+                    ->where('insurer_id', $insurer_id['insurer_id'])
+                    ->first();
+
 
         $status_val = 'success';
         if ($status == 'in-progress-partially') {
@@ -2113,7 +2182,7 @@ class EmpDataServiceController extends BaseController
         $emp_policy_ids = [];
         $employeeIds = [];
         $emp_details = [];
-        $endorsement_id = [];
+        $endorsement_id = '';
         $endorsement_details = [];
         $totals = 0;
 
@@ -2121,7 +2190,7 @@ class EmpDataServiceController extends BaseController
 
             $emp_name = $value[1];
             $emp_code = $value[2];
-            $endorsement_id[] = $value[19];
+            $endorsement_id = $value[19];
             $totals += $value[18];
 
 
@@ -2229,6 +2298,8 @@ class EmpDataServiceController extends BaseController
             'client_id' => $client_id,
             'client_policy_id' => $client_policy_id,
             'client_branch_id' => $client_branch_id,
+            'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+            'endorsement_no' => $endorsement_id ?? null,
             'count' => $emp_count,
             'event' => $file['event_type'],
             'policy_name' => $policy_name['policy_name'],
@@ -2633,6 +2704,13 @@ class EmpDataServiceController extends BaseController
         $batch_code = $file['batch_code'];
         $user_id = $file['created_by'];
 
+        $insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
+
+        $CD_Account_Number = $this->CDMasterModel
+                    ->where('client_id', $client_id)
+                    ->where('insurer_id', $insurer_id['insurer_id'])
+                    ->first();
+
 
         $status_val = 'success';
         if ($status == 'in-progress-partially') {
@@ -2653,6 +2731,7 @@ class EmpDataServiceController extends BaseController
         $emp_endorsement_table_data = [];
         $employee_policy_table_data = [];
         $employee_policy_table_primaryKey = [];
+        $endorsement_id = '';
 
         $totals = 0;
 
@@ -2662,6 +2741,7 @@ class EmpDataServiceController extends BaseController
             $emp_name = $value[2]; //employee name
             $emp_code = $value[1]; //employee code
             $totals = $totals + $value[13];
+            $endorsement_id = $value[15];
 
 
             $fetch_data = [
@@ -2733,6 +2813,8 @@ class EmpDataServiceController extends BaseController
             'client_id' => $client_id,
             'client_policy_id' => $client_policy_id,
             'client_branch_id' => $client_branch_id,
+            'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+            'endorsement_no' => $endorsement_id ?? null,
             'count' => $emp_count,
             'event' => $file['event_type'],
             'policy_name' => $policy_name['policy_name'],
@@ -2748,7 +2830,7 @@ class EmpDataServiceController extends BaseController
 
     //Endorsement Addition and Dependent Addition
 
-
+    //not in use
     public function AdditionAndDependentAddition($params)
     {
 
@@ -3139,6 +3221,7 @@ class EmpDataServiceController extends BaseController
 
     }
 
+    //end not in use
 
     /**
      * The below functions are Calculates and records cash deposits for employee policies at inception.
@@ -3176,6 +3259,9 @@ class EmpDataServiceController extends BaseController
                 'amount' => $amount->total_sum ?? 0,
                 'sub_type_id' => 4,
                 'client_id' => $arrayData['client_id'],
+                'client_policy_id' => $arrayData['client_policy_id'],
+                'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+                'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
                 'insurer_id' => $insurer_id['insurer_id'],
                 'description' => $description,
                 'transaction_type' => 'Debit',
@@ -3214,6 +3300,9 @@ class EmpDataServiceController extends BaseController
                 'amount' => $amount->total_sum,
                 'sub_type_id' => 4,
                 'client_id' => $arrayData['client_id'],
+                'client_policy_id' => $arrayData['client_policy_id'],
+                'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+                'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
                 'insurer_id' => $insurer_id['insurer_id'],
                 'description' => $description,
                 'transaction_type' => 'Debit',
@@ -3254,6 +3343,9 @@ class EmpDataServiceController extends BaseController
                 'amount' => $amount->total_sum,
                 'sub_type_id' => 3,
                 'client_id' => $arrayData['client_id'],
+                'client_policy_id' => $arrayData['client_policy_id'],
+                'endorsement_no' => $arrayData['endorsement_no'] ?? null,
+                'cd_ac_no' => $arrayData['cd_ac_no'] ?? null,
                 'insurer_id' => $insurer_id['insurer_id'],
                 'description' => $description,
                 'transaction_type' => 'Credit',
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 61c66278..ec8467e6 100644
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -79,13 +79,16 @@ class EmployeeController extends AdminController
             $data['employees'] = $this->employeePolicyModel->getEmployeePolicy(
                 client_id: $filterData['client_id'], 
                 policy_id: $filterData['policy_id'], 
-                status: $filterData['status'], 
-                branch_id: $filterData['branch_id']
+                branch_id: $filterData['branch_id'],
+                emp_code : $filterData['emp_code'],
+                emp_name : $filterData['emp_name'],
+                status   : $filterData['status'], 
             );
 
             $data['getData'] = $filterData;
         }
 
+        // dd($this->request->getGet());
         $this->myLogger->logme('error', 'list called');
         $this->loadLayout('employee_list', $data);
     }
@@ -265,22 +268,33 @@ class EmployeeController extends AdminController
                                 '(SELECT SUM(ep.rata_premimum) + SUM(ep.gst)
                                   FROM employees e
                                   JOIN employee_polices ep ON e.id = ep.employee_id
-                                  WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as total'
+                                  WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as total',
+                                 'policy_type.policy_type' ,
+                                 'cp.policy_no' ,
                             ])
                             ->join('user_profiles up', 'files.created_by = up.id')
                             ->join('client_policy cp', 'files.policy_id = cp.id', 'left')
                             ->join('client_branch cb', 'files.client_branch_id = cb.id', 'left')
                             ->join('policies pm', 'cp.policy_id = pm.id', 'left')
+                            ->join('policy_type', 'policy_type.id = pm.policy_type_id')
                             ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
                             ->where('files.created_by', get_session_userid())
                             ->orderBy('files.created_at', 'desc')
                             ->findAll();
         // dd($data['fileList']);
 
-        $data['batch_list'] = $this->batchFileModel->select('batch_files.*, policies.name as policy_name, clients.short_name as client_short_name, client_branch.branch_name')
+        $data['batch_list'] = $this->batchFileModel->select(
+                        'batch_files.*, 
+                         policies.name as policy_name, 
+                         clients.short_name as client_short_name, 
+                         client_branch.branch_name,
+                         client_policy.policy_no,
+                         policy_type.policy_type
+                    ')
             ->join('client_policy', 'client_policy.id = batch_files.client_policy_id')
             ->join('client_branch', 'client_branch.id = batch_files.client_branch_id')
             ->join('policies', 'policies.id = client_policy.policy_id')
+            ->join('policy_type', 'policy_type.id = policies.policy_type_id')
             ->join('clients', 'clients.id = client_policy.client_id')
             ->orderBy('batch_files.id', 'desc')
             ->findAll();
@@ -408,10 +422,15 @@ class EmployeeController extends AdminController
 
                 $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data);
 
-                if ($return == 0) {
+                if ($return === 0) {
 
                     session()->setFlashdata('error', "Insufficient deposit amount.");
                     return redirect()->to(base_url('employee/upload'));
+
+                }else if($return === 5){
+
+                    session()->setFlashdata('error', "The policy does not have a CD account number.");
+                    return redirect()->to(base_url('employee/upload'));
                 }
 
                 if (!$return) {
@@ -439,10 +458,14 @@ class EmployeeController extends AdminController
 
                 $return = $empDataServiceController->generateExcelForSIEnhancement($batch_data);
 
-                if ($return == 0) {
+                if ($return === 0) {
 
                     session()->setFlashdata('error', "Insufficient deposit amount.");
                     return redirect()->to(base_url('employee/upload'));
+                }else if($return === 5){
+
+                    session()->setFlashdata('error', "The policy does not have a CD account number.");
+                    return redirect()->to(base_url('employee/upload'));
                 }
 
                 if (!$return) {
@@ -772,13 +795,9 @@ class EmployeeController extends AdminController
             ->findAll();
 
         $emp_count = count($data);
-
-        if ($data) {
-            return $this->respond(['dataStatus' => true, 'code' => 200, 'emp_count' => $emp_count], 200);
-        } else {
-
-            return $this->respond(['dataStatus' => false, 'code' => 404], 404);
-        }
+        $events = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
+        return $this->respond(['dataStatus' => true, 'code' => 200,  'emp_count' => $emp_count, 'events' => $events, 'client_policy_id' => $id], 200);
+       
     }
 
 
@@ -1060,33 +1079,34 @@ class EmployeeController extends AdminController
     public function viewECard()
     {
 
-        $this->loadLayout('ecard_template/default_ecard');
+        // $this->loadLayout('ecard_template/default_ecard');
         
-        // Load the session library if it's not autoloaded
-        // $session = \Config\Services::session();
-        
-        // Access session data
-        $sessionData = session()->get();
-        
-        // Check if session data exists and if expiration time is set
-        if (!empty($sessionData) && isset($sessionData['isLoggedIn']) && isset($sessionData['session_expiration'])) {
-            // Get the session expiration timestamp
-            $expirationTimestamp = $sessionData['session_expiration'];
-        
-            // Get the current timestamp
-            $currentTimestamp = time();
-        
-            // Check if the current time is greater than the expiration time
-            if ($currentTimestamp > $expirationTimestamp) {
-                // Session has expired
-                echo "Session has expired";
-            } else {
-                // Session is active
-                echo "Session is active";
-            }
-        } else {
-            // Session data is not set or session is not started
-            echo "Session is not started or data is not set";
+        $empDataServiceController = new EmpDataServiceController();
+        $file_name = generate_filename("TCS", 'inception', 'export', 'insurer', 'policy', 'branch');
+
+        $batch_data = [
+            'client_id' => 12,
+            'client_policy_id' => 12,
+            'client_branch_id' => 1,
+            'insurer_or_tpa' => 'insurer',
+            'event_type' => 'inception',
+            'actions' => 'export',
+            'file_name' => $file_name,
+        ];
+
+        $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data);
+
+        if ($return == 0) {
+
+           dd('error', "Insufficient deposit amount.");
+
+        }else if($return == 1){
+
+            dd('error', "The policy does not have a CD account number.");
+        }
+
+        if (!$return) {
+            dd('error', "No data was found");
         }
         
     }
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index ef41e1b2..54b8ed25 100644
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -27,6 +27,7 @@ use App\Models\NotificationModel;
 use App\Models\UserModel;
 use App\Models\FEContentModel;
 use App\Models\AddImgModel;
+use App\Models\FileModel;
 
 
 use App\Controllers\Jobs ;
@@ -40,6 +41,8 @@ use PhpOffice\PhpSpreadsheet\IOFactory;
 use CodeIgniter\API\ResponseTrait;
 use Illuminate\Http\Request;
 
+use App\Controllers\EmployeeServiceController;
+
 
 class EmployeeRestController extends AdminController
 {
@@ -83,6 +86,7 @@ class EmployeeRestController extends AdminController
         $this->userModel = new UserModel();
         $this->feContentModel = new FEContentModel();
         $this->addImgModel = new AddImgModel();
+        
     }
 
     
@@ -487,7 +491,7 @@ class EmployeeRestController extends AdminController
     {
         try {
             $empData =   $this->employeePolicyModel->getEmployeePolicy( client_id:$this->request->getGet('client_id'),policy_id: $this->request->getGet('client_policy_id'),status:0,branch_id:$this->request->getGet('client_branch_id'));
-           
+         
             if ($empData) {
                 return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
             } else {
@@ -648,9 +652,24 @@ class EmployeeRestController extends AdminController
                 $sum_insured_amount_for_check_employee_1 = isset($policy_permium_1['si']) ? $policy_permium_1['si'] : null;
                 $sum_insured_amount_for_check_employee_2 = isset($policy_permium_2['si']) ? $policy_permium_2['si'] : null;
 
-                $is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
+                $is_moved = $file->move(WRITEPATH . 'uploads/excel');
                 $filename = $file->getName();
-                $file_name_with_path = WRITEPATH."/uploads/import_excel/".$filename;
+                $file_name_with_path = WRITEPATH."/uploads/excel/".$filename;
+
+                //make an entry in DB 
+                 $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master
+                $this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]);
+
+                 $empServiceController = new EmployeeServiceController();
+                 $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]);
+                 // dd($result);
+                 if(isset($result['error_summary']) && count($result['error_summary']))
+                 {
+                    $result = $empServiceController->getExcelErrorData($file_id);
+                    return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "file upload failed with errors",'data' => $result], 200);
+                 }
+                 
+                 
 
                 //check the file exist or not
                 if(!file_exists($file_name_with_path))
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index ed6bf76e..c351d0b1 100644
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -35,14 +35,576 @@ class EmployeeServiceController extends AdminController
     protected $policiesModel;
     protected $empEndorsementModel;
     protected $messageModel;
-    protected $general_relationships = ['self' => ['name' => 'Self', 'gender' => 'M','age_min' => 18,'age_max' => null], 'spouse' => ['name' => 'Spouse', 'gender' => 'F','age_min' => 18,'age_max' => null], 'son' => ['name' => 'Son', 'gender' => 'M','age_min' => null,'age_max' => 25], 'daughter' => ['name' => 'Daughter', 'gender' => 'F','age_min' => null,'age_max' => 25], 'father' => ['name' => 'Father', 'gender' => 'M','age_min' => 18,'age_max' => null], 'mother' => ['name' => 'Mother', 'gender' => 'F','age_min' => 18,'age_max' => null], 'father-in-law' => ['name' => 'Father in Law', 'gender' => 'M','age_min' => 18,'age_max' => null], 'mother-in-law' => ['name' => 'Mother in Law', 'gender' => 'F','age_min' => 18,'age_max' => null]];
-    protected $inception_excel_columns = ['sno'=>['col_idx'=>0,'col_cell_name'=>'A','col_name'=>'S.No','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'emp_id'=>['col_idx'=>1,'col_cell_name'=>'B','col_name'=>'EMP ID','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'name_of_emp_dep'=>['col_idx'=>2,'col_cell_name'=>'C','col_name'=>'NAME OF EMP/DEP','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'dob'=>['col_idx'=>3,'col_cell_name'=>'D','col_name'=>'DOB','is_mandatory'=>['I','A','DA'],'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null,'custom'=>'check_dob_diff','params'=>['row','relationship','default_age_ratio']],'gender'=>['col_idx'=>4,'col_cell_name'=>'E','col_name'=>'Gender','is_mandatory'=>['I','A','DA'],'data_type'=>'str','format'=>null,'allowed_values'=>['M','F']],'relationship'=>['col_idx'=>5,'col_cell_name'=>'F','col_name'=>'RELATIONSHIP','is_mandatory'=>['I','A','DA'],'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom'=>'check_relationship','params'=>['row','relationship','policy_terms']],'basic_cover_si'=>['col_idx'=>6,'col_cell_name'=>'G','col_name'=>'BASIC COVER SI','is_mandatory'=>['I','A','DA'],'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom' => 'check_si','params' => ['row','policy_terms','slab_details']],'doc'=>['col_idx'=>7,'col_cell_name'=>'H','col_name'=>'Date of Coverage','is_mandatory'=>['A','DA'],'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null,'params'=>['row']],'doj'=>['col_idx'=>8,'col_cell_name'=>'I','col_name'=>'DOJ','is_mandatory'=>false,'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null,'custom'=>'check_doj','params'=>['row']],'basic_pay'=>['col_idx'=>9,'col_cell_name'=>'J','col_name'=>'Basic Pay','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom'=>'check_basic_pay','params'=>['row','policy_terms','slab_details']],'band_grade'=>['col_idx'=>10,'col_cell_name'=>'K','col_name'=>'Band/Grade','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom'=>'check_employee_band','params'=>['row','policy_terms','slab_details']],'designation'=>['col_idx'=>11,'col_cell_name'=>'L','col_name'=>'Designation','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null],'phone'=>['col_idx'=>12,'col_cell_name'=>'M','col_name'=>'Phone','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom' => 'check_dup_mobileno','params' => ['row','existing_mobilenos']],'email'=>['col_idx'=>13,'col_cell_name'=>'N','col_name'=>'Email','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null],'pre_existing_ailments'=>['col_idx'=>14,'col_cell_name'=>'O','col_name'=>'PRE EXISTING AILMENTS','is_mandatory'=>['I','A','DA'],'data_type'=>'str','format'=>null,'allowed_values'=>['0','1']],'change_event'=>['col_idx'=>15,'col_cell_name'=>'P','col_name'=>'Change event','is_mandatory'=>['A','DA','D'],'data_type'=>'str','format'=>null,'allowed_values'=>null],'date_of_exit'=>['col_idx'=>16,'col_cell_name'=>'Q','col_name'=>'Date of exit','is_mandatory'=>['D'],'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null],'reason_for_exit'=>['col_idx'=>17,'col_cell_name'=>'R','col_name'=>'Reason for exit','is_mandatory'=>['D'],'data_type'=>'str','format'=>null,'allowed_values'=>null]];
+    
+    protected $general_relationships = [
+                'self' => [
+                    'name' => 'Self',
+                    'gender' => 'M',
+                    'age_min' => 18,
+                    'age_max' => null
+                ],
+                'spouse' => [
+                    'name' => 'Spouse',
+                    'gender' => 'F',
+                    'age_min' => 18,
+                    'age_max' => null
+                ],
+                'son' => [
+                    'name' => 'Son',
+                    'gender' => 'M',
+                    'age_min' => null,
+                    'age_max' => 25
+                ],
+                'daughter' => [
+                    'name' => 'Daughter',
+                    'gender' => 'F',
+                    'age_min' => null,
+                    'age_max' => 25
+                ],
+                'father' => [
+                    'name' => 'Father',
+                    'gender' => 'M',
+                    'age_min' => 18,
+                    'age_max' => null
+                ],
+                'mother' => [
+                    'name' => 'Mother',
+                    'gender' => 'F',
+                    'age_min' => 18,
+                    'age_max' => null
+                ],
+                'father-in-law' => [
+                    'name' => 'Father in Law',
+                    'gender' => 'M',
+                    'age_min' => 18,
+                    'age_max' => null
+                ],
+                'mother-in-law' => [
+                    'name' => 'Mother in Law',
+                    'gender' => 'F',
+                    'age_min' => 18,
+                    'age_max' => null
+                ]
+            ];
+    
+    protected $inception_excel_columns = [
+                'sno' => [
+                    'col_idx' => 0,
+                    'col_cell_name' => 'A',
+                    'col_name' => 'S.No',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'emp_id' => [
+                    'col_idx' => 1,
+                    'col_cell_name' => 'B',
+                    'col_name' => 'EMP ID',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'name_of_emp_dep' => [
+                    'col_idx' => 2,
+                    'col_cell_name' => 'C',
+                    'col_name' => 'NAME OF EMP/DEP',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'dob' => [
+                    'col_idx' => 3,
+                    'col_cell_name' => 'D',
+                    'col_name' => 'DOB',
+                    'is_mandatory' => ['I', 'A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null,
+                    'custom' => 'check_dob_diff',
+                    'params' => ['row', 'relationship', 'default_age_ratio']
+                ],
+                'gender' => [
+                    'col_idx' => 4,
+                    'col_cell_name' => 'E',
+                    'col_name' => 'Gender',
+                    'is_mandatory' => ['I', 'A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => ['M', 'F']
+                ],
+                'relationship' => [
+                    'col_idx' => 5,
+                    'col_cell_name' => 'F',
+                    'col_name' => 'RELATIONSHIP',
+                    'is_mandatory' => ['I', 'A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => 'check_relationship',
+                    'params' => ['row', 'relationship', 'policy_terms']
+                ],
+                'basic_cover_si' => [
+                    'col_idx' => 6,
+                    'col_cell_name' => 'G',
+                    'col_name' => 'BASIC COVER SI',
+                    'is_mandatory' => null,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => 'check_si',
+                    'params' => ['row', 'policy_terms', 'slab_details']
+                ],
+                'doc' => [
+                    'col_idx' => 7,
+                    'col_cell_name' => 'H',
+                    'col_name' => 'Date of Coverage',
+                    'is_mandatory' => ['A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null,
+                    'custom' => 'check_doc',
+                    'params' => ['row', 'policy_details']
+                ],
+                'doj' => [
+                    'col_idx' => 8,
+                    'col_cell_name' => 'I',
+                    'col_name' => 'DOJ',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null,
+                    'custom' => 'check_doj',
+                    'params' => ['row']
+                ],
+                'basic_pay' => [
+                    'col_idx' => 9,
+                    'col_cell_name' => 'J',
+                    'col_name' => 'Basic Pay',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => 'check_basic_pay',
+                    'params' => ['row', 'policy_terms', 'slab_details']
+                ],
+                'band_grade' => [
+                    'col_idx' => 10,
+                    'col_cell_name' => 'K',
+                    'col_name' => 'Band/Grade',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => 'check_employee_band',
+                    'params' => ['row', 'policy_terms', 'slab_details']
+                ],
+                'designation' => [
+                    'col_idx' => 11,
+                    'col_cell_name' => 'L',
+                    'col_name' => 'Designation',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'phone' => [
+                    'col_idx' => 12,
+                    'col_cell_name' => 'M',
+                    'col_name' => 'Phone',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => 'check_dup_mobileno',
+                    'params' => ['row', 'existing_mobilenos']
+                ],
+                'email' => [
+                    'col_idx' => 13,
+                    'col_cell_name' => 'N',
+                    'col_name' => 'Email',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'pre_existing_ailments' => [
+                    'col_idx' => 14,
+                    'col_cell_name' => 'O',
+                    'col_name' => 'PRE EXISTING AILMENTS',
+                    'is_mandatory' => ['I', 'A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => ['0', '1']
+                ],
+                'change_event' => [
+                    'col_idx' => 15,
+                    'col_cell_name' => 'P',
+                    'col_name' => 'Change event',
+                    'is_mandatory' => ['A', 'DA', 'D'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'date_of_exit' => [
+                    'col_idx' => 16,
+                    'col_cell_name' => 'Q',
+                    'col_name' => 'Date of exit',
+                    'is_mandatory' => ['D'],
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null
+                ],
+                'reason_for_exit' => [
+                    'col_idx' => 17,
+                    'col_cell_name' => 'R',
+                    'col_name' => 'Reason for exit',
+                    'is_mandatory' => ['D'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ]
+            ];
 
-    protected $deletion_excel_columns = ['sno'=>['col_idx'=>0,'col_cell_name'=>'A','col_name'=>'S.No','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'emp_id'=>['col_idx'=>1,'col_cell_name'=>'B','col_name'=>'EMP ID','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'name_of_emp_dep'=>['col_idx'=>2,'col_cell_name'=>'C','col_name'=>'NAME OF EMP/DEP','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'change_event'=>['col_idx'=>3,'col_cell_name'=>'D','col_name'=>'Change event','is_mandatory'=>['D'],'data_type'=>'str','format'=>null,'allowed_values'=>null],'date_of_exit'=>['col_idx'=>4,'col_cell_name'=>'E','col_name'=>'Date of exit','is_mandatory'=>['D'],'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null],'reason_for_exit'=>['col_idx'=>5,'col_cell_name'=>'F','col_name'=>'Reason for exit','is_mandatory'=>['D'],'data_type'=>'str','format'=>null,'allowed_values'=>null]];
+    protected $deletion_excel_columns = [
+                'sno' => [
+                    'col_idx' => 0,
+                    'col_cell_name' => 'A',
+                    'col_name' => 'S.No',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'emp_id' => [
+                    'col_idx' => 1,
+                    'col_cell_name' => 'B',
+                    'col_name' => 'EMP ID',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'name_of_emp_dep' => [
+                    'col_idx' => 2,
+                    'col_cell_name' => 'C',
+                    'col_name' => 'NAME OF EMP/DEP',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'change_event' => [
+                    'col_idx' => 3,
+                    'col_cell_name' => 'D',
+                    'col_name' => 'Change event',
+                    'is_mandatory' => ['D'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'date_of_exit' => [
+                    'col_idx' => 4,
+                    'col_cell_name' => 'E',
+                    'col_name' => 'Date of exit',
+                    'is_mandatory' => ['D'],
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null
+                ],
+                'reason_for_exit' => [
+                    'col_idx' => 5,
+                    'col_cell_name' => 'F',
+                    'col_name' => 'Reason for exit',
+                    'is_mandatory' => ['D'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ]
+            ];
 
-    protected $correction_excel_columns = ['sno'=>['col_idx'=>0,'col_cell_name'=>'A','col_name'=>'S.No','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'emp_id'=>['col_idx'=>1,'col_cell_name'=>'B','col_name'=>'EMP ID','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'name_of_emp_dep'=>['col_idx'=>2,'col_cell_name'=>'C','col_name'=>'NAME OF EMP/DEP','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'field'=>['col_idx'=>3,'col_cell_name'=>'D','col_name'=>'Field','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>['name','dob','relationship']],'value'=>['col_idx'=>4,'col_cell_name'=>'E','col_name'=>'Value','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'date_of_correction'=>['col_idx'=>5,'col_cell_name'=>'F','col_name'=>'Date of Correction','is_mandatory'=>true,'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null],'change_event'=>['col_idx'=>6,'col_cell_name'=>'G','col_name'=>'Change event','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'remarks'=>['col_idx'=>7,'col_cell_name'=>'H','col_name'=>'Remarks','is_mandatory'=>false,'data_type'=>'str','format'=>null,'allowed_values'=>null]];
+    protected $correction_excel_columns = [
+                    'sno' => [
+                        'col_idx' => 0,
+                        'col_cell_name' => 'A',
+                        'col_name' => 'S.No',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'emp_id' => [
+                        'col_idx' => 1,
+                        'col_cell_name' => 'B',
+                        'col_name' => 'EMP ID',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'name_of_emp_dep' => [
+                        'col_idx' => 2,
+                        'col_cell_name' => 'C',
+                        'col_name' => 'NAME OF EMP/DEP',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'field' => [
+                        'col_idx' => 3,
+                        'col_cell_name' => 'D',
+                        'col_name' => 'Field',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => ['name', 'dob', 'relationship']
+                    ],
+                    'value' => [
+                        'col_idx' => 4,
+                        'col_cell_name' => 'E',
+                        'col_name' => 'Value',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'date_of_correction' => [
+                        'col_idx' => 5,
+                        'col_cell_name' => 'F',
+                        'col_name' => 'Date of Correction',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => 'd-M-Y',
+                        'allowed_values' => null
+                    ],
+                    'change_event' => [
+                        'col_idx' => 6,
+                        'col_cell_name' => 'G',
+                        'col_name' => 'Change event',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'remarks' => [
+                        'col_idx' => 7,
+                        'col_cell_name' => 'H',
+                        'col_name' => 'Remarks',
+                        'is_mandatory' => false,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ]
+                ];
 
-    protected $si_enhance_excel_columns = ['sno'=>['col_idx'=>0,'col_cell_name'=>'A','col_name'=>'S.No','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'emp_id'=>['col_idx'=>1,'col_cell_name'=>'B','col_name'=>'EMP ID','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'name_of_emp_dep'=>['col_idx'=>2,'col_cell_name'=>'C','col_name'=>'NAME OF EMP/DEP','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null],'augmented_si'=>['col_idx'=>3,'col_cell_name'=>'D','col_name'=>'Augmented SI','is_mandatory'=>true,'data_type'=>'str','format'=>null,'allowed_values'=>null,'custom' => 'check_si','params' => ['row','policy_terms','slab_details']],'date_of_enhancement'=>['col_idx'=>4,'col_cell_name'=>'E','col_name'=>'Date of SI Enhancement','is_mandatory'=>true,'data_type'=>'str','format'=>'d-M-Y','allowed_values'=>null]];
+    protected $si_enhance_excel_columns = [
+                    'sno' => [
+                        'col_idx' => 0,
+                        'col_cell_name' => 'A',
+                        'col_name' => 'S.No',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'emp_id' => [
+                        'col_idx' => 1,
+                        'col_cell_name' => 'B',
+                        'col_name' => 'EMP ID',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'name_of_emp_dep' => [
+                        'col_idx' => 2,
+                        'col_cell_name' => 'C',
+                        'col_name' => 'NAME OF EMP/DEP',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null
+                    ],
+                    'augmented_si' => [
+                        'col_idx' => 3,
+                        'col_cell_name' => 'D',
+                        'col_name' => 'Augmented SI',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => null,
+                        'allowed_values' => null,
+                        'custom' => 'check_si',
+                        'params' => ['row', 'policy_terms', 'slab_details']
+                    ],
+                    'date_of_enhancement' => [
+                        'col_idx' => 4,
+                        'col_cell_name' => 'E',
+                        'col_name' => 'Date of SI Enhancement',
+                        'is_mandatory' => true,
+                        'data_type' => 'str',
+                        'format' => 'd-M-Y',
+                        'allowed_values' => null
+                    ]
+                ];
+
+    protected $enrollment_excel_columns = [
+                'sno' => [
+                    'col_idx' => 0,
+                    'col_cell_name' => 'A',
+                    'col_name' => 'Sno',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'emp_id' => [
+                    'col_idx' => 1,
+                    'col_cell_name' => 'B',
+                    'col_name' => 'Emp code',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'name_of_emp_dep' => [
+                    'col_idx' => 2,
+                    'col_cell_name' => 'C',
+                    'col_name' => 'Name',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'doj' => [
+                    'col_idx' => 3,
+                    'col_cell_name' => 'D',
+                    'col_name' => 'DOJ',
+                    'is_mandatory' => true,
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null,
+                    'custom' => null
+                ],
+                'gender' => [
+                    'col_idx' => 4,
+                    'col_cell_name' => 'E',
+                    'col_name' => 'Gender',
+                    'is_mandatory' => ['I', 'A', 'DA','E'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => ['M', 'F']
+                ],
+                'relationship' => [
+                    'col_idx' => 5,
+                    'col_cell_name' => 'F',
+                    'col_name' => 'Relation',
+                    'is_mandatory' => ['I', 'A', 'DA','E'],
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => null
+                ],
+                'dob' => [
+                    'col_idx' => 6,
+                    'col_cell_name' => 'G',
+                    'col_name' => 'DOB',
+                    'is_mandatory' => ['I', 'A', 'DA'],
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null,
+                    'custom' => null,
+                ],
+                'email' => [
+                    'col_idx' => 7,
+                    'col_cell_name' => 'H',
+                    'col_name' => 'Mail',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null
+                ],
+                'phone' => [
+                    'col_idx' => 8,
+                    'col_cell_name' => 'I',
+                    'col_name' => 'Mobile',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => null
+                ],
+                'basic_cover_si' => [
+                    'col_idx' => 9,
+                    'col_cell_name' => 'J',
+                    'col_name' => 'SI',
+                    'is_mandatory' => null,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => null
+                ],
+                'band_grade' => [
+                    'col_idx' => 10,
+                    'col_cell_name' => 'K',
+                    'col_name' => 'Grade',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => null
+                ],
+                'basic_pay' => [
+                    'col_idx' => 11,
+                    'col_cell_name' => 'L',
+                    'col_name' => 'Basic Pay',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => null,
+                    'allowed_values' => null,
+                    'custom' => null
+                ]
+            ];
+
+    protected $incetion_to_enrollment_mapping = [
+                0 => 0,    // inception: sno (S.No) -> enrollment: sno (Sno)
+                1 => 1,    // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code)
+                2 => 2,    // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP)
+                3 => 6,    // inception: dob (DOB) -> enrollment: dob (DOB)
+                4 => 4,    // inception: gender (Gender) -> enrollment: gender (Gender)
+                5 => 5,    // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
+                6 => 9,    // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
+                7 => null, // inception: doc (Date of Coverage) -> No match in enrollment
+                8 => 3,    // inception: doj (DOJ) -> enrollment: doj (DOJ)
+                9 => 11,   // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
+                10 => 10,  // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
+                11 => null, // inception: designation (Designation) -> No match in enrollment
+                12 => 8,   // inception: phone (Phone) -> enrollment: phone (Mobile)
+                13 => 7,   // inception: email (Email) -> enrollment: email (Email)
+                14 => null, // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment
+                15 => null, // inception: change_event (Change event) -> No match in enrollment
+                16 => null, // inception: date_of_exit (Date of exit) -> No match in enrollment
+                17 => null  // inception: reason_for_exit (Reason for exit) -> No match in enrollment
+            ];
+
+    protected $enrollment_to_inception_mapping = [
+                0 => 0,    // enrollment: sno (Sno) -> inception: sno (S.No)
+                1 => 1,    // enrollment: emp_code (Emp_Code) -> inception: emp_id (EMP ID)
+                2 => 2,    // enrollment: name (NAME OF EMP/DEP) -> inception: name_of_emp_dep (NAME OF EMP/DEP)
+                3 => 8,    // enrollment: doj (DOJ) -> inception: doj (DOJ)
+                4 => 4,    // enrollment: gender (Gender) -> inception: gender (Gender)
+                5 => 5,    // enrollment: relationship (Relation) -> inception: relationship (RELATIONSHIP)
+                6 => 3,    // enrollment: dob (DOB) -> inception: dob (DOB)
+                7 => 13,   // enrollment: email (Email) -> inception: email (Email)
+                8 => 12,   // enrollment: phone (Mobile) -> inception: phone (Phone)
+                9 => 6,    // enrollment: basic_cover_si (SI) -> inception: basic_cover_si (BASIC COVER SI)
+                10 => 10,  // enrollment: band_grade (Grade) -> inception: band_grade (Band/Grade)
+                11 => 9    // enrollment: basic_pay (Basic Pay) -> inception: basic_pay (Basic Pay)
+            ];
+
+    
 
     public function __construct()
     {
@@ -100,6 +662,7 @@ class EmployeeServiceController extends AdminController
         if($file['action'] == 'deletion'){ $columns_to_check = $this->deletion_excel_columns; }
         if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; }
         if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; }
+        if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; }
 
 
         $result = ['error_type' => 1,'error_summary' => [], 'error_data' => [] ];
@@ -162,7 +725,6 @@ class EmployeeServiceController extends AdminController
         // dd($existing_mobilenos);
         foreach ($excel_data as $row_key => $row) 
         {
-         
             //define row wise action/event in temporary variable
             $current_column_action = null;
             if($file['action'] == 'inception'){ $current_column_action = 'I'; }
@@ -171,25 +733,44 @@ class EmployeeServiceController extends AdminController
             else if($file['action'] == 'deletion'){ $current_column_action = 'D'; }
             else if($file['action'] == 'correction'){ $current_column_action = 'C'; }
             else if($file['action'] == 'si_enhancement'){ $current_column_action = 'SI'; }
+            else if($file['action'] == 'enrollment'){ $current_column_action = 'I'; }
          //1. avoid empty rows
             if(check_row_is_empty_or_null($row))
             {
               break;
             }
-
+            // Kint::dump($keys);
+            if ($file['action'] == 'enrollment') 
+            {
+                $row = transform_enrollment_row_to_inception_row($row);
+                $columns_to_check = $this->inception_excel_columns;
+                $keys = array_keys($columns_to_check);
+                $enrollment_columns_to_check = $this->enrollment_excel_columns;
+                $enrollment_keys = array_keys($enrollment_columns_to_check);
+            }
+       
             //iterate each row for columns validations
             foreach ($row as $col_key => $col) 
             {
-
-
                 $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory'];
                 $format = $columns_to_check[$keys[$col_key]]['format'];
                 $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values'];
                 $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null;
                 $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null;
+                
                 $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name'];
                 $column_index = $columns_to_check[$keys[$col_key]]['col_idx'];
                 $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name'];
+                if($file['action'] == 'enrollment')
+                {
+                    if(isset($enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]) && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != null && $enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]] != "")
+                    {
+                         $column_dispaly_name = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_name'];
+                         $column_index = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_idx'];
+                         $column_cell = $enrollment_columns_to_check[$enrollment_keys[$this->incetion_to_enrollment_mapping[$col_key]]]['col_cell_name'];
+                    }
+                }
+            
                 $row['current_action'] = $current_column_action;
 
                 //mandatory check
@@ -278,20 +859,27 @@ class EmployeeServiceController extends AdminController
 
                     //set failure msg to pull notifications
                     $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'failure'));
+
                 }
                 else //trigger next data validation via job queue server
                 {
-                    //proceed next data level validation in JOB queue
+                     if($file['action'] == 'enrollment') // if current action is enrollment call next validation and return result
+                     {
+                        $res = $this->excelFileDataValidation(['file_id' => $file['id']]);
+                        return $res;
+                     }
+
+                     //proceed next data level validation in JOB queue
                      $job_details  = new Jobs();
                      $r = Jobs::addJob(['job_name' => 'excelFileDataValidation','payload' => ['file_id' => $file_id]]);
                      // $jobWorker = new JobWorker();
-                     // JobWorker::processJob($r);
+                     // JobWorker::processJob($r);s
+                     
                 }       
         return $result;
 
     }
 
-
     public function excelFileDataValidation($params)
     {
         helper('excel_util_helper');
@@ -325,6 +913,7 @@ class EmployeeServiceController extends AdminController
         if($file['action'] == 'deletion'){ $columns_to_check = $this->deletion_excel_columns; }
         if($file['action'] == 'correction'){ $columns_to_check = $this->correction_excel_columns; }
         if($file['action'] == 'si_enhancement'){ $columns_to_check = $this->si_enhance_excel_columns; }
+        if($file['action'] == 'enrollment'){ $columns_to_check = $this->enrollment_excel_columns; }
 
         // get policy and rack details
         $policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
@@ -347,19 +936,23 @@ class EmployeeServiceController extends AdminController
 
         //remove header
         unset($excel_data[0]);
+        // dd($columns_to_check);
         $relationship = $this->general_relationships;
 
 
-        if(in_array($file['action'],['inception','addition','dependent_addition']))// the below funcitons are only for I,DA,A
+        if(in_array($file['action'],['inception','addition','dependent_addition','deletion','correction','si_enhancement','enrollment']))// the below funcitons are only for I,DA,A
         {
-                $employee_data_group_by_family = data_group_by_family($excel_data);
-
+                $employee_data_group_by_family = data_group_by_family($excel_data,'excel','enrollment');
+                // dd($employee_data_group_by_family);
                      $is_self_available_in_policy_terms = false;
                     if($policy_details['policy_type_id'] == 3) // GMC parents
                     {
                         $temp = $policy_terms['family_floaters'];
                         $temp = is_array($temp) ? $temp : (is_object($temp) ? (array)$temp : []);
-                        $is_self_available_in_policy_terms = isset($temp['self']) ? true : false;
+
+                        $is_self_available_in_policy_terms = isset($temp['self']) &&  $temp['self'] == 1 ? true : false;
+                        // Kint::dump($temp['self']);
+                        // dd($is_self_available_in_policy_terms);
                     }
                     // dd($employee_data_group_by_family);
                         foreach ($employee_data_group_by_family as $emp_id => $family) 
@@ -378,9 +971,9 @@ class EmployeeServiceController extends AdminController
                                  $family = data_group_by_family($family)[ $emp_id ];// reason to call this again is bring self to first index of the array
                             }
                             // kint::dump($family);//die();
+                            
                             //check name dup within a family
-
-                            if($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition')
+                            if($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition' || $file['action'] == 'enrollment')
                             {
                                 $res = name_dup_check_within_family($family,$file['action']);//in both file data & DB data
                                 // dd($res);
@@ -395,11 +988,9 @@ class EmployeeServiceController extends AdminController
                             }
 
                             //check self availbale in uploaded file
-                            if(($file['action'] == 'inception' || $file['action'] == 'addition') && ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) // 3 is GMC parents dep addon)
+                            if(($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'enrollment') || ($policy_details['policy_type_id'] == 3 && $is_self_available_in_policy_terms)) // 3 is GMC parents dep addon)
                             {
-                                // dd('file check');
                                 $res = check_self_available_in_family($family,$file['action']);
-                                // dd($res);
                                 if(!$res['is_self_found'])
                                 {
                                         array_push($result['error_summary'],14); // Self not found
@@ -415,12 +1006,12 @@ class EmployeeServiceController extends AdminController
                                 if(!count($self_details))
                                 {
                                         array_push($result['error_summary'],14); // Self not found
-                                        $result['error_data'][ $family[0][0] ]['sno']['error'][] = "Self not found in System";
+                                        $result['error_data'][ $family[0][0] ]['sno']['error'][] = "Self not found in Database";
                                 }
                             }
                            
 
-                           if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception')
+                           if($file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'inception' || $file['action'] == 'enrollment')
                             {
                                 $res = check_dependent_conflict($family,$policy_terms,$file['action']);
                                 // dd($res);
@@ -491,7 +1082,7 @@ class EmployeeServiceController extends AdminController
                              
                              $r = Jobs::addJob(['job_name' => 'employeesCorrectionProcess','payload' => ['file_id' => $file_id]]);
                         }
-                        else //inception OR addition OR dependent addition
+                        else if ($file['action'] == 'inception' || $file['action'] == 'addition' || $file['action'] == 'dependent_addition')//inception OR addition OR dependent addition
                         {
                             //proceed next data level validation in JOB queue
                              $job_details  = new Jobs();                             
@@ -499,6 +1090,8 @@ class EmployeeServiceController extends AdminController
                              // $jobWorker = new JobWorker();
                              // JobWorker::processJob($r);
                         }
+
+
                 return $result;
         
     }
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index 8afffb88..5d6ec3b9 100644
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -25,6 +25,7 @@ use App\Models\TPABranchModel;
 use App\Models\TPAModel;
 use App\Models\StateModel;
 use App\Models\PolicyTypeModel;
+use App\Models\CDMasterModel;
 
 class MasterController extends AdminController
 {   
@@ -45,6 +46,9 @@ class MasterController extends AdminController
     protected $tpaModel;
     protected $stateModel;
     protected $policyTypeModel;
+    protected $CDMasterModel;
+    protected $clientModel;
+
 
     
     public function __construct()
@@ -68,6 +72,9 @@ class MasterController extends AdminController
         $this->tpaModel           = new TPAModel();
         $this->stateModel         = new StateModel();
         $this->policyTypeModel    = new PolicyTypeModel();
+        $this->CDMasterModel    = new CDMasterModel();
+        $this->clientModel        = new ClientModel();
+
     }
 
     public function insurerList()
@@ -1111,4 +1118,111 @@ class MasterController extends AdminController
         }
     }
 
+
+
+    public function CDMasterList()
+    {
+
+        $data['CD_Master_Data'] = $this->CDMasterModel->getCDMasterList();
+        $data['insurers'] = $this->insurerModel->findAll();
+        $data['clients'] = $this->clientModel->findAll();
+        $this->loadLayout('cd_master_list', $data);
+    }
+
+
+    public function createCDMasterData()
+    {
+
+        $data = $this->request->getPost();
+        $date = (string) $this->request->getPost('opening_date');
+        $data['opening_date'] = date('Y-m-d', strtotime($date));
+
+
+        if ($data) {
+
+            $insert = $this->CDMasterModel->insert($data);
+
+            if ($insert) {
+
+                session()->setFlashdata('success', "Cash Deposite Master Added Successfully");
+                return redirect()->to(base_url('/master/cash_deposite/list'));
+            } else {
+
+                session()->setFlashdata('error', "Cash Deposite Master Added Failed");
+                return redirect()->to(base_url('/master/cash_deposite/list'));
+            }
+        } else {
+
+            session()->setFlashdata('error', "Cash Deposite Master Added Failed. Data Not Found");
+            return redirect()->to(base_url('/master/cash_deposite/list'));
+        }
+    }
+
+
+    public function editCDMasterData($id = null)
+    {
+
+        $id = $this->request->getPost('PrimaryKey');
+        $date = (string) $this->request->getPost('opening_date');
+        $data = $this->request->getPost();
+        $data['opening_date'] = date('Y-m-d', strtotime($date));
+
+        if ($data) {
+
+            $insert = $this->CDMasterModel->where('id', $id)->set($data)->update();
+
+            if ($insert) {
+
+                session()->setFlashdata('success', "Cash Deposite Master Updated Successfully");
+                return redirect()->to(base_url('/master/cash_deposite/list'));
+            } else {
+
+                session()->setFlashdata('error', "Cash Deposite Master Update Failed");
+                return redirect()->to(base_url('/master/cash_deposite/list'));
+            }
+        } else {
+
+            session()->setFlashdata('error', "Cash Deposite Master Update Failed. Data Not Found");
+            return redirect()->to(base_url('/master/cash_deposite/list'));
+        }
+    }
+
+    public function getCDMasterDataByID($id = null)
+    {
+
+        $cd_data = $this->CDMasterModel->where('id', $id)->first();
+        $cd_data['opening_date'] = date('d-m-Y', strtotime($cd_data['opening_date']));
+
+        if ($cd_data) {
+            return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404], 200);
+        }
+    }
+
+    public function checkUniqueCDAccountNumber($AccountNumber)
+    {
+        $uniqueAC = $this->CDMasterModel->where('cd_ac_no', $AccountNumber)->findAll();
+
+        if($uniqueAC != null){
+            return $this->respond(['status' => true, 'message' => 'The CD Account Number is Already Exist', 'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'code' => 404], 200);
+        }
+    }
+
+
+    public function removeCDMaster($id){
+
+        $this->myLogger->logme('error','CDMaster Remove function called');
+        $data['updated_by'] = get_session_userid();
+        $data['is_active'] = 0;
+        $update             = $this->CDMasterModel->where('id', $id)->set($data)->update();
+        if($update){
+            return $this->respond(['status' => true,'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false,'code' => 404], 200);
+        }
+    }
+
 }
\ No newline at end of file
diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php
index a25aff9e..f6d14a7c 100644
--- a/app/Helpers/DepositHelper.php
+++ b/app/Helpers/DepositHelper.php
@@ -4,6 +4,7 @@
 namespace App\Helpers;
 
 use App\Models\ClientDepositModel;
+use App\Models\CDMasterModel;
 
 class DepositHelper
 {
@@ -32,7 +33,7 @@ class DepositHelper
     public static function saveDeposit(array $data, int $loggedInUserID): array
     {
         // Retrieve the last known balance
-        $lastBalance = self::calculateLastBalance($data['client_id'], $data['insurer_id']);
+        $lastBalance = self::calculateLastBalance($data['client_id'], $data['insurer_id'], $data['cd_ac_no']);
 
         // Calculate the new balance based on the transaction type
         $newBalance = self::calculateBalance(
@@ -49,6 +50,9 @@ class DepositHelper
             'amount' => $data['amount'],
             'sub_type' => $data['sub_type_id'],
             'client_id' => $data['client_id'],
+            'client_policy_id' => $data['client_policy_id'],
+            'cd_ac_no' => $data['cd_ac_no'],
+            'endorsement_no' => $data['endorsement_no'],
             'insurer_id' => $data['insurer_id'],
             'description' => $data['description'],
             'transaction_type' => $data['transaction_type'],
@@ -83,14 +87,27 @@ class DepositHelper
      *
      * @return float The last known balance.
      */
-    public static function calculateLastBalance(int $clientId, int $insurerId): float
+    public static function calculateLastBalance(int $clientId, int $insurerId, $cd_ac_no): float
     {
         $model = new ClientDepositModel();
 
-        $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE client_id = ? AND insurer_id = ? ORDER BY created_at DESC LIMIT 1";
-        $getLastBalanceParams = [$clientId, $insurerId];
+        // $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE client_id = ? AND insurer_id = ? ORDER BY created_at DESC LIMIT 1";
+        // $getLastBalanceParams = [$clientId, $insurerId];
 
-        $lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0;
+        $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? ORDER BY created_at DESC LIMIT 1";
+        $getLastBalanceParams = [$cd_ac_no];
+
+        $lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? null;
+
+        if(empty($lastBalance) && $lastBalance == null){
+
+            $cd_model = new ClientDepositModel();
+
+            $getLastBalanceQuery = "SELECT opening_bal FROM cd_master WHERE client_id = ? AND insurer_id = ? AND cd_ac_no = ? ORDER BY created_at DESC LIMIT 1";
+            $getLastBalanceParams = [$clientId, $insurerId, $cd_ac_no];
+    
+            $lastBalance = $cd_model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->opening_bal ?? 0;
+        }
 
         return $lastBalance;
     }
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index ca88b7f1..11f9a5ee 100644
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -65,10 +65,19 @@ if (!function_exists('check_excel_date_format')) {
        if($dateString == ""){  return array('status' => true); }
         $date = DateTime::createFromFormat('d-M-Y', $dateString);
         
-        if ($date !== false && !is_array($date::getLastErrors())) {
+        if ($date && $date->format('d-M-Y') == $dateString) {
              return array('status' => true);
         } else {
-             return array('status' => false,'error' => "wrong date format: Expected 'd-M-Y' and received $dateString");
+
+             $res = convert_string_to_date($dateString);
+             if(!$res)
+             {
+                return array('status' => false,'error' => "wrong date format: Expected 'd-M-Y' and received $dateString");
+             }
+             else
+             {
+                 return array('status' => true);
+             }
         }
     }
 }
@@ -143,6 +152,36 @@ if(!function_exists('check_doj'))
     }
 }
 
+if(!function_exists('check_doc'))
+{
+
+    function check_doc($row,$policy_details)
+    {
+        if($row['current_action'] != null &&  $row[7] != null && $row[7] != '' && in_array(strtoupper($row['current_action']), ['A','DA']))// check rule only of action column data available
+        {
+            // dd($policy_details);
+            $dateString = convert_string_to_date($row[7]);
+            if($dateString)
+            {
+                $date = new DateTime($dateString);
+                $startDate = new DateTime($policy_details[0]->policy_start_date);
+                $endDate = new DateTime($policy_details[0]->policy_end_date);
+
+                if ($date >= $startDate && $date <= $endDate) {
+                   return array('status' => true);
+                } else {
+                   return array('status' => false,'error' => 'the given date of coverage is not between policy start/end date');
+                }
+            }
+            else
+            {
+                return array('status' => false,'error' => 'date format error');
+            }
+        }
+        else {  return array('status' => true); } // in else condition no need to check rule, just return true
+    }
+}
+
 
 if(!function_exists('check_employee_band'))
 {
@@ -151,6 +190,7 @@ if(!function_exists('check_employee_band'))
         if($row['current_action'] != null &&  in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available
         {
             $is_emp_band_needed = $slab_details['grid_master']['emp_band'];
+            // $is_emp_band_needed = true;
             if($slab_details['grid_master']['ui_type'] == 1) //gpa rack rate 1
             {
                 if($slab_details['slab_rates'][0]['si_or_bp'] == 3)
@@ -206,36 +246,40 @@ if(!function_exists('check_si'))
                     }
 
                     // check age slab 
-                    if(in_array(strtoupper($row['current_action']), ['I','A','DA']))
+                    if(in_array(strtoupper($row['current_action']), ['I','A','DA']) && strtolower($row['5']) == 'self')
                     {
-                        if($row[3] != null && DateTime::createFromFormat('d-M-Y', $row[3]) !== false)// dob
+                        if($row[3] != '' && $row[3] != null)// dob
                         {
-                            $dob = change_date_format($row[3],'d-M-Y','Y-m-d');
-                            // echo $row[3].' - '.$dob;echo '
'; - $currentDateTime = new DateTime();//die(); - $passedDateTime = new DateTime($dob); - $interval = $currentDateTime->diff($passedDateTime); - if(!$is_age_slab_found) - { - if(isset($slab_value['age_from']) && isset($slab_value['age_to'])) + $dob = convert_string_to_date($row[3]); + if($dob !== false) { - if($slab_value['age_from'] !== null && $slab_value['age_to'] !== null && $slab_value['age_from'] <= $interval->y && $slab_value['age_to'] >= $interval->y && $slab_value['si'] == $received_si) + // echo $row[3].' - '.$dob;echo '
'; + $currentDateTime = new DateTime();//die(); + $passedDateTime = new DateTime($dob); + $interval = $currentDateTime->diff($passedDateTime); + if(!$is_age_slab_found) { - $is_age_slab_found = true;// send true if age slab found + if(isset($slab_value['age_from']) && isset($slab_value['age_to'])) + { + if($slab_value['age_from'] !== null && $slab_value['age_to'] !== null && $slab_value['age_from'] <= $interval->y && $slab_value['age_to'] >= $interval->y && $slab_value['si'] == $received_si) + { + $is_age_slab_found = true;// send true if age slab found + } + } + else + { + $is_age_slab_found = true;// send true if age conditin is not applicable + } + } } - else - { - $is_age_slab_found = true;// send true if age conditin is not applicable - } - - } } } else { $is_age_slab_found = true;// send true if age conditin is not applicable + $is_si_found = true; }//end of check age slab }// end of for loop @@ -252,6 +296,12 @@ if(!function_exists('check_si')) $return_array['error'] = !empty($return_array['error']) ? ($return_array['error'].', '.'Sum insured not configured for this age slab') : 'Sum insured not configured for this age slab'; } + if(empty($received_si)) + { + $return_array['status'] = false; + $return_array['error'] = "Sum insured value mandantory"; + } + return $return_array; } } @@ -263,6 +313,7 @@ if(!function_exists('check_basic_pay')) if($row['current_action'] != null && in_array(strtoupper($row['current_action']), ['I','A','DA']))// check rule only of action column data available { $is_basic_pay_needed = $slab_details['grid_master']['basicpay']; + // $is_basic_pay_needed = true; $slug = \Config\Services::slug(); $relationship = $slug->slugify($row[5]); // echo $relationship;echo $row[7]; @@ -281,12 +332,13 @@ if (!function_exists('check_dob_diff')) { if($row[3] != null && $row[5] != null) { - if (DateTime::createFromFormat('d-M-Y', $row[3]) === false) + $dateString = convert_string_to_date($row[3]); + if ($dateString === false) { return array('status' => false,'error' => 'Not a valid Date'); } // return array('status' => true); - $dob = change_date_format($row[3],'d-M-Y','Y-m-d'); + $dob = $dateString; // echo $row[3].' - '.$dob;echo '
'; $currentDateTime = new DateTime();//die(); // print_r($currentDateTime); @@ -325,7 +377,7 @@ if (!function_exists('check_dob_diff')) if (!function_exists('data_group_by_family')) { - function data_group_by_family($emp_data,$data_source = 'excel') + function data_group_by_family($emp_data,$data_source = 'excel',$action = '') { $result = []; // Kint::dump($emp_data); @@ -335,6 +387,11 @@ if (!function_exists('data_group_by_family')) { if(!check_row_is_empty_or_null($row)) { + if($action == 'enrollment') //if action is enrollment transform current row into inception row, becoz we treat enrollment as inception + { + $row = transform_enrollment_row_to_inception_row($row); + } + if(strtolower($row[5]) == 'self' && isset($result[$row[1]])) { array_unshift($result[$row[1]],$row); @@ -417,6 +474,7 @@ if (!function_exists('name_and_empid_check_in_db')) $result = ['del' => [],'i' => []]; $client_id = $actionArr['client_id']; $policy_id = $actionArr['policy_id']; + $client_branch_id = $actionArr['client_branch_id']; $current_action = $actionArr['action']; foreach ($family_data as $rkey => $row) @@ -428,6 +486,7 @@ if (!function_exists('name_and_empid_check_in_db')) ->join('employee_polices ep',"cp.id = ep.client_policy_id AND employees.id = ep.employee_id") ->where("cp.id",$policy_id) ->where("employees.client_id",$client_id) + ->where("employees.client_branch_id",$client_branch_id) ->where("employees.is_active",1) ->where("employees.emp_status",'active') ->where("ep.is_active",1) @@ -443,7 +502,7 @@ if (!function_exists('name_and_empid_check_in_db')) { array_push($result['del'],$row[0]); } - if(($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition') && count($res)) + if(($current_action == 'inception' || $current_action == 'dependent_addition' || $current_action == 'addition' || $current_action == 'enrollment') && count($res)) { array_push($result['i'],$row[0]); } @@ -572,10 +631,8 @@ if (!function_exists('check_dependent_conflict')) $result['error_data'][] = ['code' => 12,'col_name' => 'sno','msg' => 'Rule conflict: As per policy, count of dependents has exceeded configured count','row_id' => (isset($self_emp_row_id) ? $self_emp_row_id : $family_data[0][0])];//dependent count mismatch } } - - // var_dump($allowed_adults == 0); - // dd($allowed_adults == 0 && (($allowed_parents_count < $received_parents_count) || ($allowed_parent_in_laws_count < $received_parent_in_laws_count))); - if($allowed_adults == 0 && (($allowed_parents_count < $received_parents_count) || ($allowed_parent_in_laws_count < $received_parent_in_laws_count) )) + //check for any cross parents but not more than two + if($allowed_adults == 0 && $allowed_parents_count == 1 && $allowed_parent_in_laws_count == 1 && (2 < ($received_parents_count + $received_parent_in_laws_count))) { // dd($allowed_adults); $result['status'] = false; @@ -813,7 +870,7 @@ if (!function_exists('transform_excel_data_to_db')) // $policy['date_of_exit'] = isset($memArr[16]) ? change_date_format($memArr[16],'d-M-Y','Y-m-d') : NULL; // $policy['reason_for_exit'] = $memArr[17]; $policy['client_policy_id'] = $actionArr['policy_id']; - $policy['date_coverage'] = isset($memArr[7]) ? change_date_format($memArr[7],'d-M-Y','Y-m-d') : NULL;; + $policy['date_coverage'] = isset($memArr[7]) ? convert_string_to_date($memArr[7],'Y-m-d') : NULL; $policy['policy_end_date'] = null; $policy['days'] = null; $policy['premium'] = null; @@ -823,11 +880,11 @@ if (!function_exists('transform_excel_data_to_db')) $result['emp_code'] = $memArr[1]; $result['name'] = $memArr[2]; - $result['dob'] = isset($memArr[3]) ? change_date_format($memArr[3],'d-M-Y','Y-m-d') : NULL; + $result['dob'] = isset($memArr[3]) ? convert_string_to_date($memArr[3],'Y-m-d') : NULL; $result['gender'] = $memArr[4]; $result['relationship'] = $memArr[5]; $result['relationship_code'] = $memArr[5]; - $result['doj'] = isset($memArr[8]) ? change_date_format($memArr[8],'d-M-Y','Y-m-d') : NULL; + $result['doj'] = isset($memArr[8]) ? convert_string_to_date($memArr[8],'Y-m-d') : NULL; $result['basic_pay'] = $memArr[9]; $result['band'] = $memArr[10]; $result['designation'] = $memArr[11]; @@ -897,7 +954,7 @@ if (!function_exists('premium_calculation_manager')) $slug = \Config\Services::slug(); $grid_type = $emp_data['temp']['grid_id']; $temp_slab_rates = $emp_data['temp']['grid_type'] == 'primary' ? $slab_details['slab_rates'] : $slab_details['additional_slab_info']['slab_rates']; - + //if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage if($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') { @@ -956,7 +1013,7 @@ if (!function_exists('premium_calculation_manager')) $employee_received_si = $default_si == null ? $emp_data['policy_details']['basic_cover_si'] : $default_si; foreach ($temp_slab_rates as $skey => $slab_value) { - if($slab_value['si'] == $employee_received_si) + if($slab_value['si'] == $employee_received_si && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -979,7 +1036,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) + if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { // dd($slab_value); $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; @@ -1000,7 +1057,7 @@ if (!function_exists('premium_calculation_manager')) foreach ($temp_slab_rates as $skey => $slab_value) { $age = calculate_days_bw_dates(from_date: $emp_data['dob'])->y; - if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age)) + if($slab_value['si'] == $employee_received_si && ($slab_value['age_from'] <= $age && $slab_value['age_to'] >= $age) && (($slab_value['premium_type'] == 1 && ( strtolower($emp_data['relationship']) == 'self' || $emp_data['temp']['additional_rack_rate_acting_self']) ) || ($slab_value['premium_type'] == 2 || $slab_value['premium_type'] == null) )) { $emp_data['policy_details']['basic_cover_si'] = $slab_value['si']; $emp_data['policy_details']['date_coverage'] = (isset($emp_data['policy_details']['date_coverage']) ? $emp_data['policy_details']['date_coverage'] : $policy_terms['policy_start_date']); @@ -1505,4 +1562,57 @@ if(!function_exists('generate_family_relationship_array')) return $family_relationships; } +} + +if(!function_exists('convert_string_to_date')) +{ + function convert_string_to_date($dateString,$defaultFormat = 'd-M-Y') + { + $formats = [ + 'd-M-Y', // 03-APr-2024 + 'd M Y', // 03 Apr 2024 + 'd/M/Y', // 03/Apr/2024 + 'j M Y', // 3 Apr 2024 + 'j/M/Y', // 3/Apr/2024 + 'j-M-Y', // 3-Apr-2024 + 'Y-m-d' // 2024-04-04 + ]; + + foreach ($formats as $format) { + $date = DateTime::createFromFormat($format, $dateString); + if ($date && $date->format($format) == $dateString) { + return $date->format($defaultFormat); + } + } + + return false; + } +} + + +if(!function_exists('transform_enrollment_row_to_inception_row')) +{ + function transform_enrollment_row_to_inception_row($row) + { + $res = []; + $res[0] = $row[0]; // inception: sno (S.No) -> enrollment: sno (Sno) + $res[1] = $row[1]; // inception: emp_id (EMP ID) -> enrollment: emp_code (Emp_Code) + $res[2] = $row[2]; // inception: name_of_emp_dep (NAME OF EMP/DEP) -> enrollment: name (NAME OF EMP/DEP) + $res[3] = $row[6]; // inception: dob (DOB) -> enrollment: dob (DOB) + $res[4] = $row[4]; // inception: gender (Gender) -> enrollment: gender (Gender) + $res[5] = $row[5]; // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation) + $res[6] = $row[9]; // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI) + $res[7] = null; // inception: doc (Date of Coverage) -> No match in enrollment + $res[8] = $row[3]; // inception: doj (DOJ) -> enrollment: doj (DOJ) + $res[9] = $row[11]; // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay) + $res[10] = $row[10]; // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade) + $res[11] = null; // inception: designation (Designation) -> No match in enrollment + $res[12] = $row[8]; // inception: phone (Phone) -> enrollment: phone (Mobile) + $res[13] = $row[7]; // inception: email (Email) -> enrollment: email (Email) + $res[14] = 1; // inception: pre_existing_ailments (PRE EXISTING AILMENTS) -> No match in enrollment + $res[15] = null; // inception: change_event (Change event) -> No match in enrollment + $res[16] = null; // inception: date_of_exit (Date of exit) -> No match in enrollment + $res[17] = null; // inception: reason_for_exit (Reason for exit) -> No match in enrollment + return $res; + } } \ No newline at end of file diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php index 2dbcb1ce..87945e48 100644 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -239,3 +239,12 @@ if (!function_exists('get_username')) { } +if (!function_exists('get_role_id')) { + function get_role_id() { + + $role_id = get_session_userdata()->role; + return $role_id; + } +} + + diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php new file mode 100644 index 00000000..0e5c39a1 --- /dev/null +++ b/app/Models/CDMasterModel.php @@ -0,0 +1,86 @@ +db->table('cd_master') + ->select('cd_master.*, clients.client_name, clients.short_name, insurers.name AS insurer_name, user_profiles.first_name AS user_name, IFNULL(cd_ac_counts.cd_ac_no_count, 0) AS cd_ac_no_count') + ->join('clients', 'clients.id = cd_master.client_id') + ->join('insurers', 'insurers.id = cd_master.insurer_id') + ->join('user_profiles', 'user_profiles.id = cd_master.created_by') + ->join( + '(SELECT cd_master.cd_ac_no, COUNT(client_policy.cd_ac_no) AS cd_ac_no_count + FROM cd_master + JOIN client_policy ON client_policy.cd_ac_no = cd_master.cd_ac_no + GROUP BY cd_master.cd_ac_no) AS cd_ac_counts', + 'cd_ac_counts.cd_ac_no = cd_master.cd_ac_no', + 'left' + ) + ->where('cd_master.is_active', 1) + ->get(); + + $result = $query->getResultArray(); + return $result; + } + +} diff --git a/app/Models/ChatBotModel.php b/app/Models/ChatBotModel.php new file mode 100644 index 00000000..caae27a5 --- /dev/null +++ b/app/Models/ChatBotModel.php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/app/Models/ClientDepositModel.php b/app/Models/ClientDepositModel.php index 0f2573b5..9f520dd2 100644 --- a/app/Models/ClientDepositModel.php +++ b/app/Models/ClientDepositModel.php @@ -22,6 +22,9 @@ class ClientDepositModel extends Model "updated_at", "description", "balance", + "client_policy_id", + "cd_ac_no", + "endorsement_no", ]; diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php index fd1e8510..d1d35a2f 100644 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -36,9 +36,25 @@ class ClientModel extends Model //get client and its associated policies in same array public function clientsWithPolicies() { + + $role_id = get_role_id(); + $user_id = get_session_userid(); + + $columns = ['clients.id ', 'client_name','short_name']; + $clients = $this->select($columns) + ->where('is_active',1) + ->findAll(); + + // if($role_id == 2 || $role_id == 3){ + + // $clients = $this->select($columns) + // ->join('client_rm', 'client_rm.client_id = clients.id') + // ->where('client_rm.user_id', $user_id) + // ->where('clients.is_active',1) + // ->findAll(); + // } - $columns = ['id', 'client_name','short_name']; - $clients = $this->select($columns)->where('is_active',1)->findAll(); + foreach ($clients as &$client) { $clientPolicyModel = new ClientPolicyModel(); @@ -51,6 +67,7 @@ class ClientModel extends Model 'client_branch.client_id', 'client_policy.id as client_policy_id', 'client_policy.policy_terms', + 'client_policy.policy_no', 'p.name', 'pt.policy_type', ]) diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php index b9cd0ae1..8d2af103 100644 --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -42,7 +42,9 @@ class ClientPolicyModel extends Model "date_of_exit", "reason_for_exit", "policy_no", - "client_branch_id" + "client_branch_id", + "cd_ac_no", + "gst", ]; public function getClientPolicyById($id){ @@ -76,12 +78,14 @@ class ClientPolicyModel extends Model ->select('insurer_branch.branch_name as insurer_branch_name, insurer_branch.branch_code as insurer_branch_code') ->select('tpa_branch.branch_name as tpa_branch_name, tpa_branch.branch_code as tpa_branch_code') ->select('policy_type.policy_type as policy_type_name') + ->select('client_branch.branch_name as branch_name') ->join('insurers', 'insurers.id = client_policy.insurer_id') ->join('insurer_branch', 'client_policy.insurer_branch_id = insurer_branch.id') ->join('tpa', 'tpa.id = client_policy.tpa_id', 'left') ->join('tpa_branch', 'client_policy.tpa_branch_id = tpa_branch.id', 'left') ->join('policies', 'policies.id = client_policy.policy_id') ->join('policy_type', 'policy_type.id = policies.policy_type_id') + ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') ->where('client_policy.client_id', $client_id) ->where('client_policy.policy_status', 1) ->where('client_policy.is_active', 1) @@ -182,18 +186,21 @@ class ClientPolicyModel extends Model ->select('cash_deposit.*') ->select('insurers.name as insurer_name, insurers.short_name as insurer_short') ->select('clients.client_name as clientname, clients.short_name as clientshort') + ->select('policies.name as policy_name') ->select('user_profiles.first_name as username') - ->join('user_profiles','user_profiles.id=cash_deposit.created_by') - ->join('insurers', 'insurers.id = cash_deposit.insurer_id') - ->join('clients', 'clients.id = cash_deposit.client_id') - + ->join('user_profiles', 'user_profiles.id = cash_deposit.created_by', 'left') + ->join('insurers', 'insurers.id = cash_deposit.insurer_id', 'left') + ->join('clients', 'clients.id = cash_deposit.client_id', 'left') + ->join('client_policy', 'client_policy.id = cash_deposit.client_policy_id', 'left') + ->join('policies', 'policies.id = client_policy.policy_id', 'left') ->where('cash_deposit.client_id', $clientId) - ->where('cash_deposit.insurer_id', $insurerId) // Add this line to filter by insurer_id + ->where('cash_deposit.insurer_id', $insurerId) ->orderBy('cash_deposit.id', 'DESC') ->get() ->getResult(); } + public function getDepositSummary($clientId, $insurerId) { // Fetch the sum of credit and debit transactions and calculate the balance diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 4f9652d9..160eb71e 100644 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -76,31 +76,71 @@ class EmployeePolicyModel extends Model } // ----------------------------------------------------------------------------------------------------- - public function getEmployeePolicy($client_id,$policy_id,$status, $branch_id) + public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=0, $branch_id=0, $emp_code="", $emp_name="") { - $result = $this->select(['employee_polices.*','pm.name as policy_name','im.short_name as insurer_short_name','ib.branch_name as insurer_branch_name','ib.branch_code as insurer_branch_code','tpam.name as tpa_name','tpam.short_name as tpa_short_name','tpab.branch_code as tpa_branch_code','cm.client_name','cm.short_name as client_short_name','emp.relationship','emp.relationship_code','emp.change_event','emp.emp_code','emp.name','emp.email_corporate','emp.dob','emp.gender','emp.emp_status','emp.is_active as emp_is_active','emp.mobile as mobile']) - ->join('employees emp', 'employee_polices.employee_id = emp.id') - ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy - ->join('policies pm', 'cp.policy_id = pm.id') //pm - policy master - ->join('insurers im', 'cp.insurer_id = im.id') //im - insurar master - ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurar branch - ->join('tpa tpam', 'cp.tpa_id = tpam.id') //tpam - tpa master - ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id') //tpab - tpa brach - ->join('clients cm', 'cp.client_id = cm.id') //cm - client master - ->where('emp.client_id',$client_id) - ->where('emp.client_branch_id',$branch_id) - ->where('employee_polices.is_active',1) - ->where('emp.is_active',1) - ->where('employee_polices.client_policy_id',$policy_id) - ->orderBy('emp.emp_code','ASC')->orderBy('employee_polices.employee_id','ASC'); - - - if($status != 0 && !empty($status)){ + + $result = $this->select([ + 'employee_polices.*', + 'pm.name as policy_name', + 'im.short_name as insurer_short_name', + 'ib.branch_name as insurer_branch_name', + 'ib.branch_code as insurer_branch_code', + 'tpam.name as tpa_name', + 'tpam.short_name as tpa_short_name', + 'tpab.branch_code as tpa_branch_code', + 'cm.client_name', + 'cm.short_name as client_short_name', + 'emp.relationship', + 'emp.relationship_code', + 'emp.change_event', + 'emp.emp_code', + 'emp.name', + 'emp.email_corporate', + 'emp.dob', + 'emp.gender', + 'emp.emp_status', + 'emp.is_active as emp_is_active', + 'emp.mobile as mobile', + 'policy_type.policy_type', + 'cp.policy_no', + ]) + ->join('employees emp', 'employee_polices.employee_id = emp.id') + ->join('client_policy cp', 'employee_polices.client_policy_id = cp.id') //cp - client policy + ->join('policies pm', 'cp.policy_id = pm.id') //pm - policy master + ->join('policy_type', 'policy_type.id = pm.policy_type_id') + ->join('insurers im', 'cp.insurer_id = im.id') //im - insurer master + ->join('insurer_branch ib', 'cp.insurer_branch_id = ib.id') //ib - insurer branch + ->join('tpa tpam', 'cp.tpa_id = tpam.id', 'left') //tpam - tpa master + ->join('tpa_branch tpab', 'cp.tpa_branch_id = tpab.id', 'left') //tpab - tpa branch + ->join('clients cm', 'cp.client_id = cm.id') //cm - client master + ->orderBy('emp.emp_code', 'ASC') + ->orderBy('employee_polices.employee_id', 'ASC'); + + // Conditionally add where clauses + if ($client_id !=0 && !empty($client_id)) { + $result->where('emp.client_id', $client_id); + } + if ($branch_id !=0 && !empty($branch_id)) { + $result->where('emp.client_branch_id', $branch_id); + } + if ($policy_id !=0 && !empty($policy_id)) { + $result->where('employee_polices.client_policy_id', $policy_id); + } + if ($status !=0 && !empty($status)) { $result->where('employee_polices.status', $status); } + if (!empty($emp_code)) { + $result->where('emp.emp_code', $emp_code); + } + if (!empty($emp_name)) { + $result->like('emp.name', $emp_name); + } - $result = $result->findAll(); - return ($result); + // Always check these conditions + $result->where('employee_polices.is_active', 1) + ->where('emp.is_active', 1); + + return $result->findAll(); } @@ -665,7 +705,9 @@ class EmployeePolicyModel extends Model e.endorsement_id, ep.client_policy_id, policies.name as policy_name, - insurers.short_name as insurer_short_name + insurers.short_name as insurer_short_name, + client_policy.policy_no, + policy_type.policy_type '); $query1->distinct(); $query1->join('employee_polices ep', 'ep.id = e.pk'); @@ -673,6 +715,7 @@ class EmployeePolicyModel extends Model $query1->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query1->join('client_branch', 'client_branch.id = employees.client_branch_id'); $query1->join('policies', 'policies.id = client_policy.policy_id'); + $query1->join('policy_type', 'policy_type.id = policies.policy_type_id'); $query1->join('insurers', 'insurers.id = policies.insurer_id'); $query1->whereIn('e.actions', ['c']); $query1->where('ep.client_policy_id', $policy_id); @@ -699,18 +742,21 @@ class EmployeePolicyModel extends Model e.remarks, ep.client_policy_id, policies.name as policy_name, - insurers.short_name as insurer_short_name + insurers.short_name as insurer_short_name, + client_policy.policy_no, + policy_type.policy_type '); $query2->join('employee_polices ep', 'ep.id = e.pk'); $query2->join('employees', 'employees.id = ep.employee_id'); $query2->join('client_policy', 'client_policy.id = ep.client_policy_id'); $query2->join('client_branch', 'client_branch.id = employees.client_branch_id'); $query2->join('policies', 'policies.id = client_policy.policy_id'); + $query2->join('policy_type', 'policy_type.id = policies.policy_type_id'); $query2->join('insurers', 'insurers.id = policies.insurer_id'); $query2->whereIn('e.actions', ['si', 'd']); $query2->where('ep.client_policy_id', $policy_id); $query2->where('employees.client_id', $client_id); - $query1->where('employees.client_branch_id', $branch_id); + $query2->where('employees.client_branch_id', $branch_id); if($status != 0 && !empty($status)){ $query2->where('e.status', $status); diff --git a/app/Views/UserList.php b/app/Views/UserList.php index c1794990..e53e341d 100644 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -269,20 +269,19 @@ $(document).ready(function () { $('body').on('click', '.btnDelete', function () { Swal.fire({ - title: "Are you sure?", - text: "You won't be able to revert this!", - icon: "warning", - showCancelButton: true, - confirmButtonColor: "#3085d6", - cancelButtonColor: "#d33", - confirmButtonText: "Yes, delete it!" + title: "Are you sure?", + text: "You need to remove this user", + icon: "info", + showCancelButton: true, + confirmButtonColor: "#3085d6", + confirmButtonText: "Yes", }).then((result) => { if (result.isConfirmed) { var student_id = $(this).attr('data-id'); $.get(''+student_id, function (data) { console.log(data); - // $('#tickets-table tbody #'+ student_id).remove(); + toastr.success('User removed successfully', 'success'); window.location.reload() }) } diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php index 0b28f477..a909008c 100644 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -6,6 +6,13 @@ .reload:hover { cursor: pointer; } + +.truncate { + max-width: 80px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +}
@@ -22,13 +29,13 @@ SNO - Batch
Code + Batch Code File Name Client - Client
Branch + Client Branch Client Policy - Event
Type - Insurer/
TPA + Event Type + Insurer/ TPA Action Count (₹)Amount @@ -46,13 +53,12 @@ - - + + - + - - diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php new file mode 100644 index 00000000..21e599ce --- /dev/null +++ b/app/Views/cd_master_list.php @@ -0,0 +1,339 @@ + + +
+
+
+
+
+
+

CD Master List

+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Client NameInsurer NameOpening DateCD Account NoDeposite AmountDate/UserAction
( ) by + + +
+
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/app/Views/client_branch.php b/app/Views/client_branch.php index 93ea7137..81b308e4 100644 --- a/app/Views/client_branch.php +++ b/app/Views/client_branch.php @@ -1,11 +1,12 @@
- +
- +
-
- +
+ @@ -23,52 +24,51 @@
- +
- +
-
- - - + + + +
- +
- - + +
- +
- - + +
- - + +
@@ -79,26 +79,37 @@
- +
- +
- +
- +
- - + +
@@ -119,168 +130,196 @@ \ No newline at end of file diff --git a/app/Views/client_info.php b/app/Views/client_info.php index f029a2b0..94bc56ee 100644 --- a/app/Views/client_info.php +++ b/app/Views/client_info.php @@ -16,7 +16,8 @@
@@ -253,7 +254,7 @@ - @@ -270,50 +271,71 @@ $(document).ready(function() { $(document).on('click', '.policy_terms', function() { var terms = $(this).data('id'); console.log(terms); + console.log(terms.length); + console.log(JSON.stringify(terms)); + + // terms = JSON.parse(terms); $('#modal_body').empty(); function createListItems(obj) { + + if (obj.length == 0) { + const message = document.createElement('div'); + message.textContent = 'Policy Terms Not Available'; + message.style.display = 'flex'; + message.style.justifyContent = 'center'; + message.style.alignItems = 'center'; + message.style.height = '100%'; // Adjust as necessary to fit the context + message.style.textAlign = 'center'; + return message; + } + const fragment = document.createDocumentFragment(); for (const key in obj) { - if (obj.hasOwnProperty(key) && obj[key] !== null && obj[key] !== '' && key != - 'family_floater' && key != 'gpa_special_condition_input' && key != - 'gpa_special_condition_label' && key != 'special_condition_label' && key != - 'special_condition_input' && key != 'age_ratio') { - + if ( + obj.hasOwnProperty(key) && + obj[key] !== null && + obj[key] !== '' && + key !== 'family_floater' && + key !== 'gpa_special_condition_input' && + key !== 'gpa_special_condition_label' && + key !== 'special_condition_label' && + key !== 'special_condition_input' && + key !== 'age_ratio' && + key !== 'multiple_sum_insured' && + key !== 'other_special_condition_label' && + key !== 'other_special_condition_input' + ) { const listItem = document.createElement('li'); + let formattedKey = key.replace(/_/g, ' '); - var formattedKey = ''; - formattedKey = key.replace(/_/g, ' '); - obj[key] = obj[key].replace(/<\/?[^>]+>/gi, ''); + console.log('type', typeof obj[key]) + // Strip HTML tags from values + if (typeof obj[key] === 'string') { + console.log('before', obj[key]) + obj[key] = obj[key].replace(/<\/?[^>]+>/gi, ''); + console.log('after', obj[key]) + } + + // Convert 0 and 1 to 'No' and 'Yes' if (obj[key] == 0) { obj[key] = 'No'; } - if (obj[key] == 1) { obj[key] = 'Yes'; } - console.log(formattedKey) - - if (key == 'burnExpenses' && obj[key] == 'Yes') { - - listItem.innerHTML = - `${formattedKey.charAt(0).toUpperCase() + formattedKey.slice(1)}: ${obj['burnExpensesData']}`; - - } else if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) { - + // Handle nested objects + if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) { listItem.innerHTML = `${formattedKey.charAt(0).toUpperCase() + formattedKey.slice(1)}:`; const nestedList = document.createElement('ul'); - nestedList.appendChild(createListItems(obj[key])); - listItem.appendChild(nestedList); - } else { listItem.innerHTML = `${formattedKey.charAt(0).toUpperCase() + formattedKey.slice(1)}: ${Array.isArray(obj[key]) ? JSON.stringify(obj[key]) : obj[key]}`; @@ -325,7 +347,8 @@ $(document).on('click', '.policy_terms', function() { return fragment; } - $('#modal_body').append(createListItems(terms)); -}); + $('#modal_body').append(createListItems(terms)); + +}); \ No newline at end of file diff --git a/app/Views/client_list.php b/app/Views/client_list.php index 4548631a..2d84afdf 100644 --- a/app/Views/client_list.php +++ b/app/Views/client_list.php @@ -59,7 +59,9 @@ table.dataTable thead th { @@ -111,38 +113,47 @@ table.dataTable thead th { function removeClient(element) { - var id = element.getAttribute('data-id'); - var form_action = '' + id; - $.ajax({ - url: form_action, - type: "GET", - dataType: 'json', - processData: false, - contentType: false, - success: function(res) { - // console.log(res.status == true); - if(res){ - if (res.status == true) { - toastr.success('Remove Done!', 'success'); - location.reload(); + Swal.fire({ + title: "Are you sure?", + text: "You need to remove this client.", + icon: "info", + showCancelButton: true, + confirmButtonColor: "#3085d6", + confirmButtonText: "Yes", + }).then((result) => { - } else { - toastr.warning('Remove Not Done!', 'warning'); - } + if (result.isConfirmed) { + var id = element.getAttribute('data-id'); + var form_action = '' + id; + $.ajax({ + url: form_action, + type: "GET", + dataType: 'json', + processData: false, + contentType: false, + success: function(res) { + // console.log(res.status == true); + if(res){ + if (res.status == true) { + toastr.success('Client removed successfully.', 'success'); + location.reload(); + } else { + toastr.warning('Failed to remove client.', 'warning'); + } + } + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); + console.error(status, error); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + console.log('Something Wrong!', 'warning'); + } + }); } - }, - error: function (xhr, status, error) { - console.error(xhr.responseText); - console.error(status, error); - setTimeout(function() { - $('.loader').fadeOut(); - $('.loader-mask').delay(350).fadeOut('slow'); - toastr.warning('Something Wrong!', 'warning'); - }, 1000); - } - }); - + + }); } diff --git a/app/Views/client_policy.php b/app/Views/client_policy.php index 34a1cd9e..8690c71b 100644 --- a/app/Views/client_policy.php +++ b/app/Views/client_policy.php @@ -7,14 +7,15 @@
-
- +
+ + - + @@ -39,6 +40,7 @@ +
@@ -121,13 +123,28 @@
@@ -148,6 +165,7 @@ + \ No newline at end of file diff --git a/app/Views/client_rm.php b/app/Views/client_rm.php index a47280ee..73ad031c 100644 --- a/app/Views/client_rm.php +++ b/app/Views/client_rm.php @@ -16,7 +16,7 @@
- +
- +
- + diff --git a/app/Views/employee_list.php b/app/Views/employee_list.php index 479260a6..c15e7f14 100644 --- a/app/Views/employee_list.php +++ b/app/Views/employee_list.php @@ -59,6 +59,16 @@ table.dataTable tbody td { +
+
+ +
+ +
+
+ +
+
@@ -243,7 +253,7 @@ function appendPolicies(data) { $.each(data, function(index, item) { var option = $('
-
Insurer PolicyClient Branch TPA DateEnrollment
Status
Enrollment Status Status Action
( - ) - -
+
@@ -110,7 +110,7 @@ - + @@ -326,7 +326,7 @@ $.each(data, function(index, item) { var option = $(' - + - + diff --git a/app/Views/insurer_branch.php b/app/Views/insurer_branch.php index dd2e5a6f..0398cc44 100644 --- a/app/Views/insurer_branch.php +++ b/app/Views/insurer_branch.php @@ -473,38 +473,48 @@ function removeInsurerBranch(element) { - var id = element.getAttribute('data-id'); - var form_action = '' + id; - $.ajax({ - url: form_action, - type: "GET", - dataType: 'json', - processData: false, - contentType: false, - success: function(res) { - // console.log(res.status == true); - if(res){ - if (res.status == true) { - toastr.success('Remove Done!', 'success'); - location.reload(); + Swal.fire({ + title: "Are you sure?", + text: "You need to remove this insurer branch.", + icon: "info", + showCancelButton: true, + confirmButtonColor: "#3085d6", + confirmButtonText: "Yes", + }).then((result) => { + + if (result.isConfirmed) { + var id = element.getAttribute('data-id'); + var form_action = '' + id; + $.ajax({ + url: form_action, + type: "GET", + dataType: 'json', + processData: false, + contentType: false, + success: function(res) { + // console.log(res.status == true); + if(res){ + if (res.status == true) { + toastr.success('Insurer branch removed successfully', 'success'); + location.reload(); + } else { + toastr.warning('Failed to remove insurer branch', 'warning'); + } + } + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); + console.error(status, error); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + toastr.warning('Failed to remove insurer branch', 'warning'); + } + }); - } else { - toastr.warning('Remove Not Done!', 'warning'); - } - } - }, - error: function (xhr, status, error) { - console.error(xhr.responseText); - console.error(status, error); - setTimeout(function() { - $('.loader').fadeOut(); - $('.loader-mask').delay(350).fadeOut('slow'); - toastr.warning('Something Wrong!', 'warning'); - }, 1000); } - }); - - } + }); + + } \ No newline at end of file diff --git a/app/Views/insurer_list.php b/app/Views/insurer_list.php index 0487ca37..4d048546 100644 --- a/app/Views/insurer_list.php +++ b/app/Views/insurer_list.php @@ -134,38 +134,47 @@ class csvExport { function removeInsurer(element) { - var id = element.getAttribute('data-id'); - var form_action = '' + id; - $.ajax({ - url: form_action, - type: "GET", - dataType: 'json', - processData: false, - contentType: false, - success: function(res) { - // console.log(res.status == true); - if(res){ - if (res.status == true) { - toastr.success('Remove Done!', 'success'); - location.reload(); + Swal.fire({ + title: "Are you sure?", + text: "You need to remove this insurer.", + icon: "info", + showCancelButton: true, + confirmButtonColor: "#3085d6", + confirmButtonText: "Yes", + }).then((result) => { - } else { - toastr.warning('Remove Not Done!', 'warning'); - } + if (result.isConfirmed) { + var id = element.getAttribute('data-id'); + var form_action = '' + id; + $.ajax({ + url: form_action, + type: "GET", + dataType: 'json', + processData: false, + contentType: false, + success: function(res) { + // console.log(res.status == true); + if(res){ + if (res.status == true) { + toastr.success('Insurer removed successfully', 'success'); + location.reload(); + } else { + toastr.warning('Failed to remove insurer', 'warning'); + } + } + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); + console.error(status, error); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + toastr.warning('Failed to remove insurer', 'warning'); + } + }); } - }, - error: function (xhr, status, error) { - console.error(xhr.responseText); - console.error(status, error); - setTimeout(function() { - $('.loader').fadeOut(); - $('.loader-mask').delay(350).fadeOut('slow'); - toastr.warning('Something Wrong!', 'warning'); - }, 1000); - } + }); - } diff --git a/app/Views/insurer_or_tpa_data.php b/app/Views/insurer_or_tpa_data.php index c068ec39..15b70b51 100644 --- a/app/Views/insurer_or_tpa_data.php +++ b/app/Views/insurer_or_tpa_data.php @@ -415,7 +415,7 @@ $.each(data, function(index, item) { var option = $(' - - + + - - + + @@ -155,8 +160,8 @@ - - + +
SNO
( ) - -
+ + - - ' . $file['first_name'] . '' ?>
Self:
Min Age:
Max Age:
Min Age:
Max Age:
Spouse:
Min Age:
Max Age:
Min Age:
Max Age:
Children:
Min Age:
Max Age:
Min Age:
Max Age:
@@ -184,21 +189,19 @@ - - - + + + -
Elders Count:
Min Age:
Max Age:
Elders Count:
Min Age:
Max Age:
-

- +
+
+ +
+
+ +
+
+
@@ -315,6 +327,15 @@
+
+
+ +
+
+ +
+
+
@@ -323,6 +344,29 @@ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
@@ -445,7 +507,7 @@