diff --git a/app/Config/Routes.php b/app/Config/Routes.php index f11f6451..73fe07a4 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -332,7 +332,7 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("send_manual_ecard/(:any)", "DashboardController::sendManualEcard/$1"); $routes->get("get_client_policy_list_for_remainder/(:any)", "EmployeeController::get_client_policy_list_for_remainder/$1"); $routes->get("get_client_branch_data/(:any)", "ClientController::get_client_branch_data/$1"); - $routes->get("getLevelContects", "LeadsControllerg::getLevelContects"); + $routes->get("getLevelContects", "LeadsController::getLevelContects"); $routes->get("get_emp_master_data_for_update/(:any)", "EmployeeController::get_emp_master_data_for_update/$1"); $routes->get("send_mail_for_individual_employee_ecard/(:any)", "EmployeeController::send_mail_for_individual_employee_ecard/$1"); $routes->post("update_emp_data", "EmployeeController::update_emp_data"); @@ -524,6 +524,8 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy"); $routes->get("getFEContent", "EmployeeRestController::getFEContent"); $routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage"); + $routes->get("getWellnessURL", "EmployeeRestController::getWellnessURL"); + // $routes->post('postDataForTicket',"EmployeeRestController::postDataForTicket"); }); $routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy"); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 50546278..9e5f0aa2 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -87,6 +87,7 @@ class ClientController extends AdminController protected $vehicleModel; protected $leadsModel; protected $clientApi; + protected $PTCOShareDetailsModel; public function __construct() @@ -123,6 +124,7 @@ class ClientController extends AdminController $this->vehicleModel = new VehicleModel(); $this->leadsModel = new LeadsModel(); $this->clientApi = new ClientApiModel(); + $this->PTCOShareDetailsModel = new PTCOShareDetailsModel(); } //-------------------------------------------------------------------------------------------------------- @@ -270,7 +272,7 @@ class ClientController extends AdminController if($mail_active == 1){ $mail_send_return = MailHelper::send_email($wholeData[0]); - $this->myLogger->logme("info", $mail_send_return); + $this->myLogger->logme("error", $mail_send_return); } // if (isset($wholeData)) { @@ -685,6 +687,7 @@ class ClientController extends AdminController $CD_Account_Number = $this->CDMasterModel ->where('client_id', $client_id) ->where('insurer_id', $insurer_id) + ->where('is_active', 1) ->first(); // Prepare the array with data $date = \DateTime::createFromFormat('d/m/Y', $record_date); @@ -1255,15 +1258,12 @@ class ClientController extends AdminController public function editClientPolicy() { - - // print_r('test'); die; $this->myLogger->logme('error', 'Client policy function called'); - - $id = $this->request->getPost('PrimaryKey'); - $client_id = $this->request->getPost('client_id'); + $id = $this->request->getPost('PrimaryKey'); + $client_id = $this->request->getPost('client_id'); $policy_type_id = $this->request->getPost('policy_type_id'); - $base_policy = $this->request->getPost('base_policy'); + $base_policy = $this->request->getPost('base_policy'); $insurerValue = (string) $this->request->getPost('insurer'); @@ -1279,9 +1279,7 @@ class ClientController extends AdminController $data['client_id'] = $client_id; $data['tpa_id'] = $tpaId; $data['policy_type_id'] = $this->request->getPost('policy_type_id'); - $data['policy_no'] = $this->request->getPost('policy_no'); - // $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); - // $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); + $data['policy_no'] = $this->request->getPost('policy_no'); $data['insured'] = $this->request->getPost('insured'); $data['no_of_lives'] = $this->request->getPost('no_of_lives'); @@ -1318,19 +1316,6 @@ class ClientController extends AdminController $data['reminder_date'] = null; } - // if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){ - - // $data['is_addon'] = 1; - - // }else if($policy_type_id == 4){ - - // $data['is_addon'] = 2; - - // }else if($policy_type_id == 5){ - - // $data['is_addon'] = 3; - // } - if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) { $data['is_addon'] = 1; // Base Policy @@ -1348,47 +1333,26 @@ class ClientController extends AdminController } } - - $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) { - // if ($this->request->getPost('is_addon') == 3) { - // $policyTerm = $policy_terms['policy_terms']; - // $decoded_policyTerm = json_decode($policyTerm, true); - // $decoded_policyTerm['family_floater'] =0; - // $decoded_policyTerm['family_floaters']['self'] =0; - // $decoded_policyTerm['family_floaters']['spouse'] =0; - // $decoded_policyTerm['family_floaters']['childrens'] =0; - // $decoded_policyTerm['family_floaters']['parents'] =0; - // $decoded_policyTerm['family_floaters']['parents-in-law'] =0; - // $decoded_policyTerm['family_floaters']['either-parents-pil'] =0; - - // $data['policy_terms'] = json_encode($decoded_policyTerm); - // } else { - // $data['policy_terms'] = $policy_terms['policy_terms']; - // } - - - // } - - // dd($data); + $old_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first(); $data['updated_by'] = get_session_userid(); - // print_r(json_encode($data));die; $insert = $this->clientPolicyModel->update($id, $data); - $lastQuery = $this->clientPolicyModel->getLastQuery(); - - // echo '
';
-        // print_r($data); die;
 
         if ($insert) {
+
+            $new_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first();
+            $policy_transaction_data = $this->policyTransactionModel->where('is_active', 1)->where('client_policy_id', $id)->countAllResults();
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
             $clientPoliceData['role'] = get_role_id();
-            // foreach ($clientPoliceData as $key => $value) {
 
-            //     $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
-            //     $clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
-            // }
+            if($policy_transaction_data > 0){
+                $r = Jobs::addJob(['job_name' => 'updatePolicyTransactionDataWhileClinetPolicyUpdate', 'payload' => [
+                    'old_client_policy_data' => $old_client_policy_data ?? null,
+                    'new_client_policy_data' => $new_client_policy_data ?? null,
+                ]]);
+            }
+
             return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'EDIT'], 200);
         } else {
             return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
@@ -1857,6 +1821,146 @@ class ClientController extends AdminController
         }
     }
 
+    public function updatePolicyTransactionDataWhileClinetPolicyUpdate($params)
+    {
+        try {
+            // Basic validation
+            if (empty($params) || !isset($params['old_client_policy_data']) || empty($params['old_client_policy_data'])) {
+                $this->myLogger->logme("error", "Old client policy data is missing or empty: " . json_encode(['params' => $params]));
+                return ['status' => "Failed", 'message' => "Old client policy data is missing or empty", 'data' => $params];
+            }
+
+            if (!isset($params['new_client_policy_data']) || empty($params['new_client_policy_data'])) {
+                $this->myLogger->logme("error", "New client policy data is missing or empty: " . json_encode(['params' => $params]));
+                return ['status' => "Failed", 'message' => "New client policy data is missing or empty", 'data' => $params];
+            }
+
+            $old = $params['old_client_policy_data'];
+            $new = $params['new_client_policy_data'];
+
+            $data = [];
+
+            // Check differences and prepare update data
+            $fields_to_check = [
+                'client_branch_id', 'policy_type', 'insurer_id', 'insurer_branch_id',
+                'cd_ac_pk', 'policy_end_date', 'policy_start_date', 'tpa_id', 'tpa_branch_id'
+            ];
+
+            foreach ($fields_to_check as $field) {
+                if (isset($new[$field]) && isset($old[$field]) && $new[$field] != $old[$field]) {
+                    $data[$field] = $new[$field];
+                }
+            }
+
+            if (empty($data)) {
+                $this->myLogger->logme("error", "No changes detected in client policy update.");
+                return ['status' => "Failed", 'message' => "No changes detected in policy data."];
+            }
+
+            // Fetch related policy transactions
+            $policy_transactions = $this->policyTransactionModel
+                ->where('is_active', 1)
+                ->where('client_policy_id', $new['id'])
+                ->findAll();
+
+            $updated_pt_ids = [];
+
+            if (!empty($policy_transactions)) {
+
+                // Update each policy transaction and track affected IDs
+                foreach ($policy_transactions as $pt) {
+                    $result = $this->policyTransactionModel
+                        ->where('id', $pt['id'])
+                        ->set($data)
+                        ->update();
+
+                    if ($this->policyTransactionModel->affectedRows() > 0) {
+                        $updated_pt_ids[] = $pt['id'];
+                    }
+                }
+
+                if (empty($updated_pt_ids)) {
+                    $this->myLogger->logme("error", "No policy_transaction records were updated.");
+                    return ['status' => "Failed", 'message' => "No records updated."];
+                }
+
+                // If insurer-related fields are updated, update co-share table as well
+                if (isset($data['insurer_id']) && !empty($data['insurer_id'])) {
+                    $co_share_result = $this->updatePTCoShareTableEntry($policy_transactions, $old, $data);
+                    $this->myLogger->logme("error", "PT co-share update result: " . json_encode($co_share_result));
+                }
+
+                $this->myLogger->logme("error", "Policy transaction(s) updated successfully. Updated IDs: " . json_encode($updated_pt_ids));
+                
+                return [
+                    'status' => "Success",
+                    'message' => "Policy transaction(s) updated.",
+                    'updated_ids' => $updated_pt_ids
+                ];
+
+            } else {
+                $this->myLogger->logme("error", "No active policy_transaction records found for update.");
+                return ['status' => "Failed", 'message' => "No active policy_transaction records found."];
+            }
+
+        } catch (\Throwable $e) {
+            $this->myLogger->logme("error", "Exception during policy_transaction update: " . $e->getMessage());
+            return [
+                'status' => "Failed",
+                'message' => "An error occurred during update.",
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+
+    private function updatePTCoShareTableEntry($policy_transaction_data, $old_client_policy_data, $data)
+    {
+        $updated_ids = [];
+        $errors = [];
+
+        foreach ($policy_transaction_data as $value) {
+            $pt_id = $value['id'];
+
+            try {
+                // Find matching rows
+                $rows = $this->PTCOShareDetailsModel
+                    ->where('pt_id', $pt_id)
+                    ->where('insurer_id', $old_client_policy_data['insurer_id'])
+                    ->where('insurer_branch_id', $old_client_policy_data['insurer_branch_id'])
+                    ->where('is_active', 1)
+                    ->findAll();
+
+                foreach ($rows as $row) {
+                    // Update each row individually
+                    $result = $this->PTCOShareDetailsModel
+                        ->where('id', $row['id'])
+                        ->set([
+                            'insurer_id' => $data['insurer_id'],
+                            'insurer_branch_id' => $data['insurer_branch_id'],
+                        ])
+                        ->update();
+
+                    // Check if the update was successful
+                    if ($this->PTCOShareDetailsModel->affectedRows() > 0) {
+                        $updated_ids[] = $row['id'];
+                    } else {
+                        $errors[] = "No change or failed update for ID {$row['id']}";
+                    }
+                }
+
+            } catch (\Exception $e) {
+                $errors[] = "Error updating pt_id {$pt_id}: " . $e->getMessage();
+            }
+        }
+
+        return [
+            'updated_ids' => $updated_ids,
+            'errors' => $errors,
+        ];
+    }
+
+
 
 
     public function uploadVehicleFile()
@@ -1989,7 +2093,7 @@ class ClientController extends AdminController
                 ->findAll();
 
             $client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
-            $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();
+            $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->where('is_active', 1)->findAll();
             // $client_policy_data['policy_end_date'] = date('d/m/Y', strtotime($client_policy_data['policy_end_date']));
             $fromDate = new \DateTime($client_policy_data['policy_end_date']);
             $fromDate->modify('+1 year');
@@ -3900,6 +4004,7 @@ class ClientController extends AdminController
         $cdmData = $this->CDMasterModel
                         ->where('client_id', $client)
                         ->where('insurer_id', $insurer)
+                        ->where('is_active', 1)
                         ->findAll();
 
         if ($cdmData) {
@@ -4684,6 +4789,11 @@ class ClientController extends AdminController
 
     public function sendextraparam()
     {   
+        //     $data = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
+        //     // dd($data);
+        //    $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true));
+        //    dd($return);
+        //     die;
 
         // $employeeController = new EmployeeController();
         // $employeeController->truncateFileData('633');
@@ -4699,7 +4809,7 @@ class ClientController extends AdminController
         $empServiceController = new EmployeeServiceController();
         // $res = $empServiceController->excelFileFormatValidation(['file_id' => '865']);
         // $res = $empServiceController->excelFileDataValidation(['file_id' => '865']);
-        // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '829']);
+        // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '978']);
         // $res = $empServiceController->employeeDisembark(['file_id' => '858']);
 
         $policyTransactionController = new PolicyTransactionController();
@@ -4733,6 +4843,7 @@ class ClientController extends AdminController
         // $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live
         // $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 1199]); //for live
         // $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 1205]); //for live
+        // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live
 
         // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
         // print_rr($result); die;
@@ -4757,12 +4868,12 @@ class ClientController extends AdminController
         // $EmpDataServiceController->importDeletionUpdateEndorsementID(['file_id' => 171]);
         // $EmpDataServiceController->importCorrectionUpdateEndorsementID(['file_id' => 188]);
 
-        $params = [
-            'client_policy_id' => 6090,
-            'action_type' => "inception",
-        ];
-        $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction($params);
-        dd($res);
+        // $params = [
+        //     'client_policy_id' => 6090,
+        //     'action_type' => "inception",
+        // ];
+        // $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction($params);
+        // dd($res);
         
         // $array = [
         //         "employeeIds" => ["12800", "12798", "12797", "12799"],
@@ -4798,7 +4909,7 @@ class ClientController extends AdminController
         // $returndata = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name);
         // dd($returndata);
 
-         $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
+        //  $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
 
         // -----------BDS REPORT CONTROLLER---------------------------------------------------------------------------------
         
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
index 5709b0ae..cb93e213 100755
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -447,7 +447,7 @@ class EmpDataServiceController extends BaseController
             ];
 
             //for addition and dependent addition adding a ENDORSEMENT NO column
-            if(in_array($export_data['event_type'], ['addition', 'dependent_addition'])){
+            if(in_array($export_data['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
                 $excel_header_columns[] = [
                     'column_index' => 18, 
                     'column_name' => 'ENDORSEMENT NO', 
@@ -1404,7 +1404,7 @@ class EmpDataServiceController extends BaseController
             'TOTAL AMOUNT',
         ];
 
-        if(in_array($file['event_type'], ['addition', 'dependent_addition'])){
+        if(in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
             $inceptionHeader[] = 'ENDORSEMENT NO';
         }
 
@@ -1566,6 +1566,17 @@ class EmpDataServiceController extends BaseController
                 }
             }
 
+            if (in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])) {
+                if ($excel_data[$key][18] === null) {
+                    $missing_id[$key][] = [
+                        'row' => $key,
+                        'column' => 18,
+                        'db_data' => "Endorsement ID is Must",
+                        'excel_data' => $excel_data[$key][18]
+                    ];
+                }
+            }
+
 
             if ($emp_value['emp_name'] != $excel_data[$key][1]) {
                 $errors[$key][] = [
@@ -1900,6 +1911,27 @@ class EmpDataServiceController extends BaseController
                     $emp_details[] = array('id' => $result['id'], 'tpa_id' => $value[13], 'uhid' => $value[14]);
                 }
 
+                if(in_array($file['event_type'], ['missed_inception']) && isset($value[18])){
+                    $endorsement_id = $value[18];
+
+                    $result_for_employees_policy = $this->employeePolicyModel
+                        ->select('employee_polices.*')
+                        ->join('employees', 'employees.id = employee_polices.employee_id')
+                        ->join('emp_endorsement', 'emp_endorsement.employee_id = employees.id') // assuming this is the correct join
+                        ->where('employees.emp_code', $emp_code)
+                        ->where('employees.name', $name)
+                        ->where('employees.client_id', $client_id)
+                        ->where('employees.client_branch_id', $client_branch_id)
+                        ->where('employee_polices.client_policy_id', $client_policy_id)
+                        ->where('employee_polices.is_active', 1)
+                        ->where('employee_polices.status', 'active')
+                        ->where('employees.is_active', 1)
+                        ->where('employees.emp_status', 'active')
+                        ->first();
+
+                    $enrollment_file_id = $result_for_employees_policy['file_id'] ?? null;
+                }
+
                 //for addition and dependent_addition endorsement , endorsement_id update functionality 
                 if(in_array($file['event_type'], ['addition', 'dependent_addition']) && isset($value[18])){
 
@@ -1929,7 +1961,9 @@ class EmpDataServiceController extends BaseController
                     ->first();
 
                     if (!empty($result_for_endorsement) && count($result_for_endorsement)) {
-                        $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key
+                        if(empty($enrollment_file_id)){
+                            $enrollment_file_id = $result_for_endorsement['file_id']; //files table primary key
+                        }
                         $emp_endorsement_table_data[] = array('id' => $result_for_endorsement['id'], 'group_key' => $result_for_endorsement['group_key'], 'endorsement_id' => $value[18], 'status' => 'complete');
                     }
                 }
@@ -1945,7 +1979,6 @@ class EmpDataServiceController extends BaseController
 
         if(in_array($file['event_type'], ['addition', 'dependent_addition']) && !empty($emp_endorsement_table_data)){
             $this->employeePolicyModel->updateEmpEndorsementAddition($emp_endorsement_table_data);
-            $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
         }
 
         // Update batch file status and amount
@@ -1962,6 +1995,11 @@ class EmpDataServiceController extends BaseController
         //update CD transaction entry if only insurer
         if ($file['insurer_or_tpa'] == 'insurer') {
 
+            if(in_array($file['event_type'], ['addition', 'dependent_addition', 'missed_inception'])){
+                $this->storeEndorsementNumber($file_id, $endorsement_id, $enrollment_file_id);
+            }
+
+
             $this->myLogger->logme('error', 'Inception Update TPA and UHID --    set  cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE');
 
             $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
@@ -2388,7 +2426,9 @@ class EmpDataServiceController extends BaseController
 
             if (isset($result['id']) && $result['id'] !== null) {
                 // return $result;
-                $enrollment_file_id = $result['file_id'];
+                if(empty($enrollment_file_id)){
+                    $enrollment_file_id = $result['file_id'];
+                }
 
                 if($result['field_name'] == 'dob'){
                     $value[8] = change_date_format($value[8]);
@@ -2967,7 +3007,10 @@ class EmpDataServiceController extends BaseController
 
             if (isset($result['id']) && $result['id'] !== null) {
 
-                $enrollment_file_id = $result['file_id'];
+                if(empty($enrollment_file_id)){
+                    $enrollment_file_id = $result['file_id'];
+                }
+                
                 $emp_policy_ids[] = array('id' => $result['emp_policy_id'], 'is_active' => 0);
                 $employeeIds[] = $result['emp_policy_id'];
                 $endorsement_details[] = array('id' => $result['id'], 'group_key' => $result['group_key'], 'endorsement_id' => $value[19], 'status' => 'complete');
@@ -3472,7 +3515,9 @@ class EmpDataServiceController extends BaseController
 
                 if (isset($result['emp_endorsement_primarykey']) && $result['emp_endorsement_primarykey'] !== null) {
 
-                    $enrollment_file_id = $result['file_id']; //files table primary key
+                    if(empty($enrollment_file_id)){
+                        $enrollment_file_id = $result['file_id']; //files table primary key
+                    }
                     $employee_policy_table_primaryKey[] = $result['emp_policy_primarykey']; //for cash deposite
                     $employee_policy_table_data[] = array('id' => $result['emp_policy_primarykey'], 'date_of_exit' => change_date_format($result['date_of_exit']), 'reason_for_exit' => $result['reason_for_exit'], 'claim_status' => $result['claim_status'], 'status' => $result['status']);
                     // $employees_table_data[] = array('id' => $result['employees_id'], 'emp_status' => $result['status']);
@@ -4735,6 +4780,14 @@ class EmpDataServiceController extends BaseController
                 return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
             }
 
+            //Function call for if the old policy transaction entries exisit than active the Policy transaction entries
+            $existing_policy_transaction_entry = $this->retrivePolicyTransactionEntries($params);
+
+            if($existing_policy_transaction_entry != false){
+                return $existing_policy_transaction_entry;
+            }
+
+            //get the policy data
             $policy_data = $this->clientPolicyModel
                 ->where('id', $params['client_policy_id'])
                 ->where('is_active', 1)
@@ -4745,6 +4798,7 @@ class EmpDataServiceController extends BaseController
                 return ['status' => "Failed", 'message' => "No policy data found for the given client policy ID", 'data' => ['params' => $params]];
             }
 
+            //get the leads data
             $lead_data = $this->leadsModel
                 ->where('is_policy_created', $params['client_policy_id'])
                 ->where('is_active', 1)
@@ -4752,13 +4806,15 @@ class EmpDataServiceController extends BaseController
 
             if (empty($lead_data)) {
                 $this->myLogger->logme("error", "No lead data found: " . json_encode(['client_policy_id' => $params['client_policy_id']]));
-                return ['status' => "Failed", 'message' => "No lead data found for the given client policy ID", 'data' => ['params' => $params]];
+                // return ['status' => "Failed", 'message' => "No lead data found for the given client policy ID", 'data' => ['params' => $params]];
             }
 
             $this->myLogger->logme("error", "Constructing policy transaction data: " . json_encode(['policy_data' => $policy_data, 'lead_data' => $lead_data]));
 
+            //Function to construct the policy transaction data to insert
             $policyTransactionData = $this->constructBDSData($policy_data, $lead_data, $params);
 
+            //insert the policy transaction data to othe table
             $insert_id = $this->policyTransactionModel->insert($policyTransactionData);
 
             if (!$insert_id) {
@@ -4774,20 +4830,23 @@ class EmpDataServiceController extends BaseController
 
             // $this->myLogger->logme("error", "PT Co share data inserted successfully: " . json_encode(['pt_co_share_id' => $pt_co_share_id]));
 
-            $lead_installment_data = $this->leadInstallmentPaymentDetailesModel
-                ->select('lead_id, installment_amount, payment_date, utr_no')
-                ->where('lead_id', $lead_data['id'])
-                ->where('is_active', 1)
-                ->findAll();
+            // get the lead installment data
 
-            if (!empty($lead_installment_data) && (isset($params['action_type']) && $params['action_type'] == "inception")) {
-                $this->myLogger->logme("error", "Found lead installment data: " . json_encode($lead_installment_data));
+            if(!empty($lead_data)){
+                $lead_installment_data = $this->leadInstallmentPaymentDetailesModel
+                    ->select('lead_id, installment_amount, payment_date, utr_no')
+                    ->where('lead_id', $lead_data['id'])
+                    ->where('is_active', 1)
+                    ->findAll();
 
-                $installment_ids = $this->constructInstallmentData($lead_installment_data, $insert_id);
+                if (!empty($lead_installment_data) && (isset($params['action_type']) && $params['action_type'] == "inception")) {
 
-                $this->myLogger->logme("error", "Installment data inserted: " . json_encode(['installment_ids' => $installment_ids]));
-            }else{
-                $this->myLogger->logme("error", "Failed to insert Installment data : " . json_encode($params));
+                    $this->myLogger->logme("error", "Found lead installment data: " . json_encode($lead_installment_data));
+                    $installment_ids = $this->constructInstallmentData($lead_installment_data, $insert_id);
+                    $this->myLogger->logme("error", "BDS Installment data inserted ids: " . json_encode(['installment_ids' => $installment_ids]));
+                }else{
+                    $this->myLogger->logme("error", "Failed to insert Installment data : " . json_encode($params));
+                }
             }
 
             return ['status' => "Success", 'message' => "Policy transaction entry created successfully", 'data' => ['params' => $params, 'insert_id' => $insert_id]];
@@ -4804,6 +4863,11 @@ class EmpDataServiceController extends BaseController
     private function constructBDSData($policy_data, $lead_data, $params)
     {   
 
+        $action_type_string = $params['action_type'];
+         if(in_array($params['action_type'], ['dependent_addition', 'missed_inception'])){
+            $action_type_string = "addition";
+         }
+
         $policyTransactionData = [
 
             'issuer' => 2,
@@ -4834,12 +4898,13 @@ class EmpDataServiceController extends BaseController
             'is_cd_reduce_from_bds' => 0,
             'client_type_id' => 0,
 
-            'status' => "completed",
-            'action_type' => $params['action_type'] ?? null,
+            'status' => "co_insurer_pending",
+            'action_type' => $action_type_string ?? null,
             'endorsement_no' => $params['endorsement_no'] ?? null,
-            'issue_type' => $lead_data['lead_type'] ?? null,
+
+            'issue_type' => $lead_data['lead_type'] ?? 1,
             'source_client_policy_id' => $lead_data['source_policy_id'] ?? null,
-            'tsi' => generate_tsi_code($lead_data['lead_type']) ?? null,
+            'tsi' => generate_tsi_code($lead_data['lead_type'] ?? 1) ?? null,
             'installment' => $lead_data['no_of_installment'] ?? null,
         ];
 
@@ -4877,12 +4942,138 @@ class EmpDataServiceController extends BaseController
         }
     }
 
-    
-
-    public function retriveBDSPolicyTransactionEntry()
+    private function retrivePolicyTransactionEntries($params)
     {
+        $policy_transaction_data = $this->policyTransactionModel
+                ->where('is_active', 0)
+                ->where('client_policy_id', $params['client_policy_id']);
+
+        if ($params['action_type'] != "inception") {
+            $policy_transaction_data = $policy_transaction_data->where('endorsement_no', $params['endorsement_no']);
+        }
+
+        $policy_transaction_data = $policy_transaction_data
+                ->where('action_type', $params['action_type'])
+                ->first();
+
+        if(empty($policy_transaction_data)){
+            $this->myLogger->logme("error", "retrive Policy Transaction Entries data not found : " . json_encode(['params' => $params]));
+            return false;
+        }
+        
+        $pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 0)->where('pt_id', $policy_transaction_data['id'])->findAll();
+
+         if(empty($pt_co_share_data)){
+            $this->myLogger->logme("error", "PT Co Share Table data not found");
+         }
+
+         $activated_pt_co_share_ids = [];
+         foreach ($pt_co_share_data as $key => $value) {
+            $this->PTCOShareDetailsModel->where('id', $value['id'])->set(['is_active' => 1])->update();
+            $activated_pt_co_share_ids[] = $value['id'];
+         }
+
+         $this->myLogger->logme("error", "Activated pt_co_share_ids : ". json_encode($activated_pt_co_share_ids));
+
+
+        $update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 1])->update();
+
+        if($update_return){
+            $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+            return ['status' => "Success", 'message' => "Policy transaction entry Retrived successfully", 'data' => ['params' => $params, 'updated_id' => $policy_transaction_data['id']]];
+        }else{
+            $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+            return ['status' => "Success", 'message' => "Failed to retrive the policy transaction entry", 'data' => ['params' => $params, 'updated_id' => $policy_transaction_data['id']]];
+        }
+
+    }
+    
+    public function removeBDSPolicyTransactionEntryFromTruncate($params)
+    {
+        if (empty($params) || !isset($params['client_policy_id']) || empty($params['client_policy_id'])) {
+            $this->myLogger->logme("error", "Invalid parameters provided: " . json_encode(['params' => $params]));
+            return ['status' => "Failed", 'message' => "Client Policy ID is missing or empty", 'data' => ['params' => $params]];
+        }
+
+        if (!isset($params['file_id']) || empty($params['file_id'])) {
+            $this->myLogger->logme("error", "File ID is missing or empty : " . json_encode(['params' => $params]));
+            return ['status' => "Failed", 'message' => "File ID is missing or empty : ", 'data' => ['params' => $params]];
+        }
+
+        if (!isset($params['action_type']) || empty($params['action_type'])) {
+            $this->myLogger->logme("error", "Invalid action type: " . json_encode(['params' => $params]));
+            return ['status' => "Failed", 'message' => "Action type is missing or empty", 'data' => ['params' => $params]];
+        }
+
+        
+        if($params['action_type'] != "inception"){
+            
+            $endorsement_data = $this->endorsementModel
+                                    ->where('is_active', 1)
+                                    ->where('client_policy_id', $params['client_policy_id'])
+                                    ->where('endorsement_type', $params['action_type'])
+                                    ->where('file_id', $params['file_id'])
+                                    ->first();
+
+            if(empty($endorsement_data)){
+                $this->myLogger->logme("error", "Endorsement data not found");
+                return ['status' => "Failed", 'message' => "Endorsement data not found", 'data' => ['params' => $params]];
+            }
+        }
+        
+        $action_type_string = $params['action_type'];
+         if(in_array($params['action_type'], ['dependent_addition', 'missed_inception'])){
+            $action_type_string = "addition";
+         }
+
+
+        $policy_transaction_data = $this->policyTransactionModel
+            ->where('is_active', 1)
+            ->where('client_policy_id', $params['client_policy_id']);
+
+        if ($params['action_type'] != "inception") {
+            $policy_transaction_data = $policy_transaction_data->where('endorsement_no', $endorsement_data['endorsement_no']);
+        }
+
+        $policy_transaction_data = $policy_transaction_data
+            ->where('action_type', $action_type_string)
+            ->first();
+
+
+        if(empty($policy_transaction_data)){
+            $this->myLogger->logme("error", "Policy transaction data not found");
+            return ['status' => "Failed", 'message' => "Policy transaction data not found", 'data' => ['params' => $params]];
+        }
+
+
+        $pt_co_share_data = $this->PTCOShareDetailsModel->where('is_active', 1)->where('pt_id', $policy_transaction_data['id'])->findAll();
+
+         if(empty($pt_co_share_data)){
+            $this->myLogger->logme("error", "PT Co Share Table data not found");
+         }
+
+         $de_activated_pt_co_share_ids = [];
+         foreach ($pt_co_share_data as $key => $value) {
+            $this->PTCOShareDetailsModel->where('id', $value['id'])->set(['is_active' => 0])->update();
+            $de_activated_pt_co_share_ids[] = $value['id'];
+         }
+
+         $this->myLogger->logme("error", "De-activated pt_co_share_ids : ". json_encode($de_activated_pt_co_share_ids));
+
+         $update_return = $this->policyTransactionModel->where('id', $policy_transaction_data['id'])->set(['is_active' => 0])->update();
+
+         if($update_return){
+            $this->myLogger->logme("error", "Policy transaction data de-active successfully");
+            return ['status' => "Success", 'message' => "Policy transaction data Truncated successfully", 'data' => ['params' => $params]];
+         }else{
+            $this->myLogger->logme("error", "Failed to de-active policy transaction data");
+            return ['status' => "Success", 'message' => "Failed to truncated the policy transaction data", 'data' => ['params' => $params]];
+         }
 
     }
 
 
+
+
+
 }
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 0bcc03c5..e5281998 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -1384,6 +1384,13 @@ class EmployeeController extends AdminController
                             $this->myLogger->logme('error', 'cash_deposite table updated -- cd transaction');
                         }
 
+                        //this job for deactive policy transaction and pt co share table entry for BDS Sync
+                         $r = Jobs::addJob(['job_name' => 'removeBDSPolicyTransactionEntryFromTruncate', 'payload' => [
+                            'client_policy_id' => $client_policy_id ?? null,
+                            'file_id' => $file_id ?? null,
+                            'action_type' => $file['action'] ?? null,
+                        ]]);
+
                     }else{
 
                         $this->myLogger->logme('error', '---- There is no data to truncate ----');
@@ -1534,6 +1541,13 @@ class EmployeeController extends AdminController
 
                 }
 
+                //this job for deactive policy transaction and pt co share table entry for BDS Sync
+                $r = Jobs::addJob(['job_name' => 'removeBDSPolicyTransactionEntryFromTruncate', 'payload' => [
+                    'client_policy_id' => $client_policy_id ?? null,
+                    'file_id' => $file_id ?? null,
+                    'action_type' => $file['action'] ?? null,
+                ]]);
+
                 $this->myLogger->logme('error', 'SUCCESSFULLY TRUNCATED');
 
                 return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200);
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 3feb5558..711366a3 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -1100,7 +1100,7 @@ class EmployeeRestController extends AdminController
             $keysToRemove  = ["removable_keys"];
             // Retrieve employee policy data by passing the employee primary key
             $empPolicy = $this->employeeModel->getEmployeePolicy($id);
-// dd($empPolicy);
+            // dd($empPolicy);
             // Retrieve employee and dependents data by passing the employee code
             $employeeData = $this->employeeModel->where('emp_code',$emp_code)
                                                 ->where('client_id',$client_id)
@@ -3323,4 +3323,22 @@ class EmployeeRestController extends AdminController
         return $this->response->setJSON(['ticket_data' => $ticket_data])->setStatusCode(200);
     }
 
+    public function getWellnessUrl()
+    {
+        $url = "https://aam.mohfw.gov.in/home/login";
+
+        if (!empty($url)) {
+            return $this->respond([
+                'status' => 'success',
+                'data' =>  $url
+            ], 200);
+        } else {
+            return $this->respond([
+                'status' => 'failed',
+                'message' => 'No link found'
+            ], 200);
+        }
+    }
+
+
 }
\ No newline at end of file
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index 5d65c4a4..5584d67c 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -153,7 +153,7 @@ class EmployeeServiceController extends AdminController
                     'is_mandatory' => ['I', 'A', 'DA'],
                     'data_type' => 'str',
                     'format' => null,
-                    'allowed_values' => null,
+                    'allowed_values' => ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father in Law', 'Mother in Law'],
                     'custom' => 'check_relationship',
                     'params' => ['row', 'relationship', 'policy_terms']
                 ],
@@ -1587,9 +1587,17 @@ class EmployeeServiceController extends AdminController
                     {
                         $pre_rack_rate_name = $slab_value['rack_rate_name'];
                         $rack_rate_json = json_decode($slab_value['additional_relationship'], true);
-                        $relationship_array_key = strtolower($employee['relationship']);
+                        $relationship_array_key = strtolower(trim($employee['relationship']));
 
-                        if(array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[ strtolower($employee['relationship']) ] != 0 && $rack_rate_json[ strtolower($employee['relationship']) ] != 'NA')
+                        if (in_array($relationship_array_key, ['son', 'daughter'])) {
+                            $relationship_array_key = 'childrens';
+                        } elseif (in_array($relationship_array_key, ['father', 'mother'])) {
+                            $relationship_array_key = 'parents';
+                        } elseif (in_array($relationship_array_key, ['father in law', 'mother in law', 'father-in-law', 'mother-in-law'])) {
+                            $relationship_array_key = 'parents-in-law';
+                        }
+
+                        if(array_key_exists($relationship_array_key, $rack_rate_json) && $rack_rate_json[$relationship_array_key] != 0 && $rack_rate_json[$relationship_array_key] != 'NA')
                         {   
                             $applicable_rack_rate_name = $slab_value['rack_rate_name'];
                             $applicable_rack_rate_master = $slab_value['grid_master'];
@@ -1623,6 +1631,7 @@ class EmployeeServiceController extends AdminController
 
 
         }
+
         $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
         $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
         //set success msg to pull notifications
diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php
index c471a9e6..4cbf5350 100755
--- a/app/Controllers/JobWorker.php
+++ b/app/Controllers/JobWorker.php
@@ -124,8 +124,12 @@ class JobWorker extends AdminController
     'handler' => 'App\Controllers\EmpDataServiceController',
     ],
     'makeEntryForBDSPolicyTransaction' => [
-    'type' => 'CC', // Handler Category
-    'handler' => 'App\Controllers\EmpDataServiceController',
+        'type' => 'CC', // Handler Category
+        'handler' => 'App\Controllers\EmpDataServiceController',
+    ],
+    'removeBDSPolicyTransactionEntryFromTruncate' => [
+        'type' => 'CC', // Handler Category
+        'handler' => 'App\Controllers\EmpDataServiceController',
     ],
     'employeesEnrollmentInsert' => [
         'type' => 'CC', // Handler Category
@@ -134,7 +138,11 @@ class JobWorker extends AdminController
     'calculateMembersDemography' => [
         'type' => 'CC', // Handler Category
         'handler' => 'App\Controllers\LeadsController',
-    ]
+    ],
+    'updatePolicyTransactionDataWhileClinetPolicyUpdate' => [
+        'type' => 'CC', // Handler Category
+        'handler' => 'App\Controllers\ClientController',
+    ],
 ];
 
     
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index bb0e45f6..38e76d58 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -724,6 +724,9 @@ class LeadsController extends BaseController
 
         $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']);
         $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']);
+        
+        $data['placement_mail_content'] = $this->transformMailContent($lead_data, $mail_content, 'Placement');
+        $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement');
 
         $data['multi_file_data'] = $this->leadFilesModel->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
         $installment_data['installments'] = $this->leadInstallmentPaymentDetails->where('lead_id', $id)->where('is_active', 1)->findAll() ?? null;
@@ -1199,13 +1202,14 @@ class LeadsController extends BaseController
     public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null)
     {
         $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type);
+        $is_placement = false;
 
         // dd($rfq_data, $lead_id, $type, $propsal_and_insurer);
         // print_r($propsal_and_insurer); die;
 
         if ($rfq_data['lead_type'] == 1) {
 
-            if ($rfq_data['policy_type_id'] == 2) {
+            if (in_array($rfq_data['policy_type_id'], [2,3,4,5])) {
                 $lead_data = [
                     'Insured' => $rfq_data['client_name'],
                     'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "",
@@ -1215,9 +1219,9 @@ class LeadsController extends BaseController
                     'Total Lives' => $rfq_data['incept_no_of_lives'],
 
                     'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d/m/Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d/m/Y', strtotime($rfq_data['policy_end_date'])) : "To be decided",
-                    'Policy Run Days' => $rfq_data['policy_run_days'],
+                    // 'Policy Run Days' => $rfq_data['policy_run_days'],
                 ];
-            } else if ($rfq_data['policy_type_id'] == 1) {
+            } else if (in_array( $rfq_data['policy_type_id'], [1, 6, 7])) {
                 $lead_data = [
                     'Insured' => $rfq_data['client_name'],
                     'No of Employees at Inception' => $rfq_data['incept_emp_count'],
@@ -1228,7 +1232,7 @@ class LeadsController extends BaseController
             }
 
         } else {
-            if ($rfq_data['policy_type_id'] == 2) {
+            if (in_array($rfq_data['policy_type_id'], [2,3,4,5])) {
                 $lead_data = [
 
                     'Insured' => $rfq_data['client_name'],
@@ -1256,7 +1260,7 @@ class LeadsController extends BaseController
                     'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'],
                     'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'],
                 ];
-            } else if ($rfq_data['policy_type_id'] == 1) {
+            } else if (in_array( $rfq_data['policy_type_id'], [1, 6, 7])) {
                 $lead_data = [
                     'Insured' => $rfq_data['client_name'],
                     'No of Employees at Renewal' => $rfq_data['renewal_emp_count'],
@@ -1279,6 +1283,7 @@ class LeadsController extends BaseController
             if ($propsal_and_insurer !== null) {
                 list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2);
                 $data = $this->transformProposelData($data, $proposal_key, $insurer_key);
+                $is_placement = true;
             }
         } else if ($type == 1) {
             $sheetName = 'RFQ';
@@ -1382,7 +1387,11 @@ class LeadsController extends BaseController
             ],
         ]);
         $subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers']));
-        $subheader_count = $subheader_count - 2;
+       
+        if($is_placement == false){
+            $subheader_count = $subheader_count - 2;
+        }
+
         $headerCount = count($data['table_data']['headers']);
         $lastColumn = Coordinate::stringFromColumnIndex($subheader_count);
         // dd( $headerCount, $lastColumn);
@@ -1428,7 +1437,11 @@ class LeadsController extends BaseController
             $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header
 
             // Set parent header value
-            $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+            if($is_placement == true && !in_array($header['parentHeader'] , ['Particulars', 'S.No.'])){
+                $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms");
+            }else{
+                $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']);
+            }
             $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([
                 'font' => ['bold' => true],
                 'alignment' => [
@@ -1448,7 +1461,7 @@ class LeadsController extends BaseController
             // Add subheaders
             foreach ($header['subHeaders'] as $subHeader) {
 
-                if($type == 2){
+                if($type == 2 && $is_placement == false){
                     $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
                 }
 
@@ -1458,13 +1471,16 @@ class LeadsController extends BaseController
                     $sheet->getColumnDimension('A')->setWidth(10);
                 }
 
-                $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
-                    'font' => ['bold' => true],
-                    'alignment' => [
-                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
-                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
-                    ],
-                ]);
+                if($is_placement == false){
+                    $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
+                        'font' => ['bold' => true],
+                        'alignment' => [
+                            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
+                            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
+                        ],
+                    ]);
+                }
+
                 $columnLetter++; // Move to the next column for subheaders
             }
         }
@@ -1485,7 +1501,12 @@ class LeadsController extends BaseController
         $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height
         $sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height
 
-        $rowNumber = $subHeaderRow + 2;
+        if($is_placement == true){
+            $rowNumber = $subHeaderRow;
+        }else{
+            $rowNumber = $subHeaderRow + 2;
+        }
+        // dd($rowNumber);
         $column_data = $data['table_data']['data'];
         $serial_no = 1;
         $maxColumnWidths = [];
@@ -1521,7 +1542,7 @@ class LeadsController extends BaseController
             ],
         ]);
 
-
+        //premium data 
         if ($type == 2) {
 
             $rowNumber += 2;
@@ -1558,9 +1579,14 @@ class LeadsController extends BaseController
                 $rowNumber++;
             }
 
-            $prevColumn3 = $this->getPreviousColumn($columnLetter, 2);
+            if($is_placement == true){
+                $prevColumn3 = $this->getPreviousColumn($columnLetter);
+            }else{
+                $prevColumn3 = $this->getPreviousColumn($columnLetter, 2);
+            }
             $premiumRange = "B" . ($rowNumber - 4) . ":" . "{$prevColumn3}" . ($rowNumber - 1);
             // dd($premiumRange);
+
             $sheet->getStyle($premiumRange)->applyFromArray([
                 'borders' => [
                     'allBorders' => [
@@ -1575,7 +1601,11 @@ class LeadsController extends BaseController
         //set imgage and align the row and column
         // Kint::dump($columnLetter);
         if($type == 2){
-            $columnLetter_img = $this->getPreviousColumn($columnLetter, 2);
+            if($is_placement == true){
+                $columnLetter_img = $this->getPreviousColumn($columnLetter);
+            }else{
+                $columnLetter_img = $this->getPreviousColumn($columnLetter, 2);
+            }
         }else{
             $columnLetter_img = $this->getPreviousColumn($columnLetter);
         }
@@ -1667,7 +1697,7 @@ class LeadsController extends BaseController
 
 
         // Set filename
-        $string = ($type == 2) ? 'QCR' : 'RFQ';
+        $string = ($type == 2) ? ( $is_placement == true ? 'Placement' : 'QCR') : 'RFQ';
         $current_year = date('Y');
         $next_year = $current_year + 1;
         $policy_year = "$current_year-$next_year";
@@ -2163,6 +2193,13 @@ class LeadsController extends BaseController
         $mail_subject = $params['subject'];
         $attachment_file_ids = $params['selected_attachment_files'];
 
+        $from_mail = getenv('email.fromEmail');
+        if(in_array($recipient_type ,['placement', 'insurer', 'internal'])){
+            $from_mail = "im@nhanceindia.in";
+        }else if(in_array($recipient_type, ['client'])){
+            $from_mail = "bs@nhanceindia.in";
+        }
+
         $result_data = [];
         // dd($recipient_mail);
         if ($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0)) {
@@ -2348,7 +2385,7 @@ class LeadsController extends BaseController
                 $string = implode(", ", $cc_mails);
                 $bcc_string = implode(", ", $bcc_mails);
 
-                $res = MailHelper::send_email(['mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
+                $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string]);
                 // !dd($res);
                 $result_data[] = ['mail' => $recipient['email'], 'status' => $res];
             }
@@ -2367,8 +2404,8 @@ class LeadsController extends BaseController
             $data = [
                 'proposel_data' => json_encode($lead_update_data),
                 'status' => 'won',
-                'placement_date' => date('Y-m-d', strtotime($params['placement_date']) ?? "") ?? null,
-                'payment_date' => date('Y-m-d', strtotime($params['payment_date'] ?? "")) ?? null,
+                'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null,
+                'payment_date'   => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null,
                 'utr_no' => $params['utr_no'] ?? null,
                 'is_cd' => $params['is_cd'] ?? null ,
                 'premium_amount' => $params['premium_amount'] ?? null,
@@ -2483,7 +2520,7 @@ class LeadsController extends BaseController
                         $headerData[] = [
                             'parentHeader' => $header['parentHeader'],
                             'subHeaders' => [
-                                'Quote Asked', // Default value
+                                // 'Quote Asked', // Default value
                                 $subHeader     // Matched insurer key
                             ]
                         ];
@@ -2519,15 +2556,16 @@ class LeadsController extends BaseController
                     ];
                 }
 
-                // Include Proposal with Quote Asked by default
-                if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
-                    $result['data'][] = [
-                        "parentth" => $item['parentth'],
-                        "subth" => $item['subth'],
-                        "value" => $item['value'],
-                        "input_value" => $item['input_value']
-                    ];
-                }
+                // Include Proposal with Quote Asked by default 
+                /* For proposel do not remove it */
+                // if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") {
+                //     $result['data'][] = [
+                //         "parentth" => $item['parentth'],
+                //         "subth" => $item['subth'],
+                //         "value" => $item['value'],
+                //         "input_value" => $item['input_value']
+                //     ];
+                // }
 
                 // Example of including matching specific proposals and insurers
                 if ($item['parentth'] === $proposel && $item['subth'] === $insurer) {
@@ -2548,7 +2586,7 @@ class LeadsController extends BaseController
 
         foreach ($data['premium_data']['data'] as $key => $value) {
             if ($key === $proposel) {
-                $premiumData[$key]['Quote Asked'] = $value['Quote Asked'];
+                // $premiumData[$key]['Quote Asked'] = $value['Quote Asked'];
                 $premiumData[$key][$insurer] = $value[$insurer];
             }
         }
@@ -4113,32 +4151,63 @@ class LeadsController extends BaseController
 
     public function handleMultiFileAttachments($json_string, $lead_id)
     {
+        log_message('error', 'handleMultiFileAttachments called with lead_id: ' . $lead_id);
+
         $attachments = [];
 
         if (!empty($json_string)) {
+            log_message('error', 'json_string is not empty');
+
             $fileIds = json_decode($json_string, true);
+            log_message('error', 'Decoded fileIds: ' . print_r($fileIds, true));
+
             $lead_file_path = WRITEPATH . 'uploads/lead_files/';
+            log_message('error', 'Lead file path: ' . $lead_file_path);
 
             foreach ($fileIds as $id) {
-                $lead_file = $this->leadFilesModel->where('lead_id', $lead_id)->where('id', $id)->where('is_active', 1)->first();
+                log_message('error', 'Processing file ID: ' . $id);
+
+                $lead_file = $this->leadFilesModel
+                    ->where('lead_id', $lead_id)
+                    ->where('id', $id)
+                    ->where('is_active', 1)
+                    ->first();
 
                 if ($lead_file) {
+                    log_message('error', 'Found lead file: ' . print_r($lead_file, true));
 
                     $fullPath = $lead_file_path . $lead_file['file_name'];
+                    log_message('error', 'Full file path: ' . $fullPath);
 
-                    if (file_exists($fullPath) && !empty($fileName)) {
-                        $attachments[] = [
-                            'fileName' => $lead_file['file_name'],
-                            'filePath' => $fullPath
-                        ];
+                    if (file_exists($fullPath)) {
+                        log_message('error', 'File exists at path: ' . $fullPath);
+
+                        if (!empty($lead_file['file_name'])) {
+                            log_message('error', 'File name is not empty: ' . $lead_file['file_name']);
+
+                            $attachments[] = [
+                                'fileName' => $lead_file['file_name'],
+                                'filePath' => $fullPath
+                            ];
+                        } else {
+                            log_message('warning', 'File name is empty for ID: ' . $id);
+                        }
+                    } else {
+                        log_message('warning', 'File does not exist at path: ' . $fullPath);
                     }
+                } else {
+                    log_message('warning', 'No active lead file found for ID: ' . $id . ' and lead_id: ' . $lead_id);
                 }
             }
+        } else {
+            log_message('error', 'json_string is empty');
         }
 
+        log_message('error', 'Attachments prepared: ' . print_r($attachments, true));
         return $attachments;
     }
 
+
     public function handleMemberDataGPATotalSumInsurerFromExcel($params)
     {
         $lead_id = $params['lead_id'];
diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php
index 15c2fad6..9474bac2 100644
--- a/app/Controllers/TicketController.php
+++ b/app/Controllers/TicketController.php
@@ -1576,14 +1576,21 @@ class TicketController extends BaseController
         $statusMapping = json_decode($incoming_form_values['extra_fields_array_for_validate']);
     
         foreach ($statusMapping as $status => $requiredFields) {
+
             // Ensure requiredFields is an array
             if (!is_array($requiredFields)) {
                 $requiredFields = [$requiredFields];
+
             }
     
             // Check if all required fields exist and are not empty in the incoming form values
             $allFieldsMatched = true;
             foreach ($requiredFields as $field) {
+
+                if(in_array($field, ['approved_description'])){
+                    continue;
+                }
+
                 if (!isset($incoming_form_values[$field]) || empty($incoming_form_values[$field])) {
                     $allFieldsMatched = false;
                     break;
diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php
index 67ffc9b1..99c08108 100755
--- a/app/Helpers/excel_util_helper.php
+++ b/app/Helpers/excel_util_helper.php
@@ -1769,7 +1769,7 @@ if(!function_exists('check_dup_mobileno'))
     {
         foreach($existing_mobilenos as $k => $value)
         {
-            if ($row['12'] == $value['mobile']) {
+            if (strtolower($row['5']) == 'self' && $row['12'] == $value['mobile']) {
                  return array('status' => false,'error' => "Duplicate Mobile No");
                 // break;
             }
@@ -1784,7 +1784,7 @@ if(!function_exists('check_dup_email'))
     {
         foreach($existing_mobilenos as $k => $value)
         {
-            if ($row['13'] == $value['email_corporate']) {
+            if (strtolower($row['5']) == 'self' && $row['13'] == $value['email_corporate']) {
                  return array('status' => false,'error' => "Duplicate Email");
                 // break;
             }
diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php
index d456c311..e1f97747 100755
--- a/app/Models/ClientPolicyModel.php
+++ b/app/Models/ClientPolicyModel.php
@@ -180,6 +180,7 @@ class ClientPolicyModel extends Model
             ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id')
             ->where('client_policy.client_id', $id)
             ->where('cd_master.id = client_policy.cd_ac_pk')
+            ->where('cd_master.is_active', 1)
             ->groupBy('client_policy.insurer_id')
             ->groupBy('client_policy.client_id', $id)  // Group by insurer_id
             ->get()
diff --git a/app/Models/EndorsementModel.php b/app/Models/EndorsementModel.php
index 22bcec72..60b675cb 100644
--- a/app/Models/EndorsementModel.php
+++ b/app/Models/EndorsementModel.php
@@ -24,6 +24,7 @@ class EndorsementModel extends Model
         'created_at',
         'updated_by',
         'updated_at',
+        'file_id',
         'is_active'
     ];
     
diff --git a/app/Views/leads_form_handler.php b/app/Views/leads_form_handler.php
index 7d9a6006..09a630e8 100644
--- a/app/Views/leads_form_handler.php
+++ b/app/Views/leads_form_handler.php
@@ -848,18 +848,25 @@ if (isset($selected_lead_type)) {
         }
 
         function waitForDropdownValue(selector, value, callback, retries = 20) {
+
             const trySet = () => {
+
+                $('.loader').fadeIn();
+                $('.loader-mask').fadeIn();
+
                 const $el = $(selector);
                 if ($el.find(`option[value="${value}"]`).length > 0) {
                     $el.val(value).trigger('change');
                     callback();
                 } else if (retries > 0) {
-                    setTimeout(() => trySet(selector, value, callback, retries - 1), 300);
+                    setTimeout(trySet, 300); // retry without re-passing arguments
+                    retries--;
                 } else {
                     console.warn(`Value ${value} not found for ${selector}`);
                     callback(); // Proceed anyway to avoid hanging
                 }
             };
+
             trySet();
         }
 
@@ -867,41 +874,42 @@ if (isset($selected_lead_type)) {
 
             let lead_type = data.lead_type || null;
             waitForDropdownValue('#client_id', data.client_id || '', () => {
+                
                 if (lead_type == 3) {
-                    
-                    $('#client_id').prepend($('