nhance/app/Controllers/ClientController.php

9662 lines
417 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Controllers;
use App\Helpers\DepositHelper;
use App\Helpers\MailHelper;
use App\Helpers\ClientTokenHelper;
use App\helpers\JWTToken;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use App\Models\ClientModel;
use App\Models\ClientBranchModel;
use App\Models\ClientKYCDocsModel;
use App\Models\ClientDepositModel;
use App\Models\ClientPolicyModel;
use App\Models\ClientRMModel;
use App\Models\InsurerBranchModel;
use App\Models\InsurerModel;
use App\Models\KYCDocsModel;
use App\Models\KYCEntityTypeModel;
use App\Models\LevelContactModel;
use App\Models\PolicesModel;
use App\Models\TPABranchModel;
use App\Models\TPAModel;
use App\Models\StateModel;
use App\Models\PolicyGridModel;
use App\Models\PolicyPremium1Model;
use App\Models\PolicyPremium2Model;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\NotificationModel;
use App\Models\CDMasterModel;
use App\Models\PolicyTypeModel;
use App\Models\PolicyTransactionModel;
use App\Models\PolicyTransactionStatusModel;
use App\Models\VehicleModel;
use App\Models\LeadsModel;
use App\Models\ClientApiModel;
use App\Models\HRAccessControlModel;
use App\Controllers\EmpDataServiceController;
use App\Controllers\GoogleDriveController;
use App\Controllers\PolicyTransactionController;
use App\Helpers\sendMailNotification;
use App\Models\PTCOShareDetailsModel;
use App\Models\RFQModel;
use App\Models\TicketMasterModel;
use SebastianBergmann\Type\NullType;
use Kint\Kint;
class ClientController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $clientModel;
protected $userModel;
protected $clientBranchModel;
protected $clientKYCDocsModel;
protected $clientPolicyModel;
protected $clientRMModel;
protected $insurerBranchModel;
protected $insurerModel;
protected $kycDocsModel;
protected $kycEntityTypeModel;
protected $levelContactModel;
protected $policesModel;
protected $tpaBranchModel;
protected $tpaModel;
protected $stateModel;
protected $policyGridModel;
protected $policyPremium1Model;
protected $policyPremium2Model;
protected $clientDepositModel;
protected $employeeModel;
protected $employeePolicyModel;
protected $notificationModel;
protected $CDMasterModel;
protected $policyTypeModel;
protected $policyTransactionModel;
protected $policyTransactionStatusModel;
protected $vehicleModel;
protected $leadsModel;
protected $clientApi;
protected $PTCOShareDetailsModel;
protected $HRAccessControlModel;
public function __construct()
{
set_session_context('Client');
$this->myLogger = \Config\Services::mylogger();
$this->clientModel = new ClientModel();
$this->userModel = new UserModel();
$this->clientBranchModel = new ClientBranchModel();
$this->clientKYCDocsModel = new ClientKYCDocsModel();
$this->clientDepositModel = new ClientDepositModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->clientRMModel = new ClientRMModel();
$this->insurerBranchModel = new InsurerBranchModel();
$this->insurerModel = new InsurerModel();
$this->kycDocsModel = new KYCDocsModel();
$this->kycEntityTypeModel = new KYCEntityTypeModel();
$this->levelContactModel = new LevelContactModel();
$this->policesModel = new PolicesModel();
$this->tpaBranchModel = new TPABranchModel();
$this->tpaModel = new TPAModel();
$this->stateModel = new StateModel();
$this->policyGridModel = new PolicyGridModel();
$this->policyPremium1Model = new PolicyPremium1Model();
$this->policyPremium2Model = new PolicyPremium2Model();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->notificationModel = new NotificationModel();
$this->CDMasterModel = new CDMasterModel();
$this->policyTypeModel = new PolicyTypeModel();
$this->policyTransactionModel = new PolicyTransactionModel();
$this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
$this->vehicleModel = new VehicleModel();
$this->leadsModel = new LeadsModel();
$this->clientApi = new ClientApiModel();
$this->PTCOShareDetailsModel = new PTCOShareDetailsModel();
$this->HRAccessControlModel = new HRAccessControlModel();
}
//--------------------------------------------------------------------------------------------------------
public function validateDuplicateByClientBranch()
{
$value = $this->request->getPost('value');
$clientId = $this->request->getPost('client_id');
$branchId = $this->request->getPost('branch_id');
$field = $this->request->getPost('field');
$isDuplicate = $this->clientModel->isDuplicateByClientBranch($value, $field, $clientId, $branchId);
return $this->response->setJSON(['isDuplicate' => $isDuplicate]);
}
private const ALLOWED_DUPLICATE_CHECK_TABLES = [
'clients', 'client_branch', 'level_contacts', 'insurers', 'insurer_branch',
'tpa', 'tpa_branch', 'policies', 'client_policy', 'user_profiles',
];
public function checkDuplicateTableFieldValue()
{
$table = $this->request->getPost('table');
$field = $this->request->getPost('field');
$value = $this->request->getPost('value');
if (!in_array($table, self::ALLOWED_DUPLICATE_CHECK_TABLES, true)) {
return $this->response->setJSON(['isDuplicate' => false, 'error' => 'Invalid table']);
}
$db = db_connect();
$tableFields = $db->getFieldNames($table);
$builder = $db->table($table);
if (is_array($value)) {
$filteredValue = array_intersect_key($value, array_flip($tableFields));
if (empty($filteredValue)) {
return $this->response->setJSON(['isDuplicate' => false, 'error' => 'Invalid fields']);
}
$isDuplicate = $builder->where($filteredValue)->where('is_active', 1)->countAllResults() > 0;
} else {
if (!in_array($field, $tableFields, true)) {
return $this->response->setJSON(['isDuplicate' => false, 'error' => 'Invalid field']);
}
$isDuplicate = $builder->where($field, $value)->where('is_active', 1)->countAllResults() > 0;
}
return $this->response->setJSON(['isDuplicate' => $isDuplicate]);
}
public function testMailAttachments($email = 'venkateshraman786@gmail.com')
{
$message = '<style>body{font-family:Arial,sans-serif;color:#333;line-height:1.6;margin:0;padding:0}.email-container{width:100%;max-width:600px;margin:0 auto;padding:20px;border:1px solid #e0e0e0;background-color:#f9f9f9}.header{background-color:#4a90e2;color:#fff;padding:15px;text-align:center}.header h1{margin:0;font-size:24px}.content{padding:20px;background-color:#fff}.content h2{color:#4a90e2;font-size:20px;margin-top:0}.content p{margin:10px 0}.details-table{width:100%;border-collapse:collapse;margin-top:20px}.details-table td,.details-table th{border:1px solid #ddd;padding:10px;text-align:left}.details-table th{background-color:#f2f2f2}.footer{margin-top:20px;font-size:12px;color:#777;text-align:center}.attachment-note{margin-top:20px;padding:10px;background-color:#f7f7f7;border-left:4px solid #4a90e2;font-style:italic}</style><div class=email-container><div class=header><h1>Request for Quotation (RFQ)</h1></div><div class=content><h2>Dear {{RECIPIENT_NAME}},</h2><p>We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.<h2>RFQ Details</h2><table data-custom-table-css="table" class=details-table><tr><th>Client name<td>{{CLIENT_NAME}}<tr><th>Coverage Type<td>{{POLICY_LONG_NAME}}<tr><th>Policy Start Date<td>{{POLICY_START_DATE}}<tr><th>Policy Duration<td>{{DURATION}}</table><div class=attachment-note>Please note: Additional terms and details are included in the attachment for your reference.</div><p>Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.<p>Best regards,<p><strong>Nhance India Pvt Ltd</strong><br></div><div class=footer><p>© Nhance India Pvt Ltd. All rights reserved.</div></div>';
// $attachments = [
// ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"],
// ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"],
// ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"]
// ];
$attachments = [];
$res = MailHelper::send_email(['mail' => $email, 'subject' => 'Mail Via Attachment Testing URL', 'message' => $message, 'attachments' => $attachments]);
print_rr($res);
echo '------------------------------------------------------------------------------------------';
// print_rr($attachments);
}
//Function for Testing Member Review and Summery Confirmation Mail
public function testingForReviewMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0) //this function for only tsesting some logics not use for business logic
{
// dd($client_id, $emp_code, $policy_id, $mail_active);
if (empty($policy_id)) {
$client_policy_ids = $this->employeeModel
->select('employee_polices.client_policy_id')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.client_id', $client_id)
->where('employees.emp_code', $emp_code)
->where('employee_polices.is_active', 1)
->where('employees.is_active', 1)
->findAll();
$client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id');
$client_policy_id = array_unique($client_policy_ids2);
} else {
$client_policy_id = json_decode($policy_id, true);
}
// echo '<pre>';
// dd($client_policy_id);
// print_r($unique_policy_ids); die;
// sort($client_policy_id);
$wholeData = '';
$mail_send_return = '';
$mail_send_return1 = '';
$mail_send_return2 = '';
if (!is_null($client_policy_id) && is_array($client_policy_id)) {
$empData = $this->employeeModel->where('emp_code', $emp_code)->where('client_id', $client_id)->where('is_active', 1)->findAll();
// dd($empData);
$filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self');
// dd($filteredEmpData);
$array_list = [];
foreach ($client_policy_id as $key => $value) {
$find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']);
if (count($find) > 0) {
$array_list[] = $find;
}
}
// dd($array_list);
$notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_review_and_summary_mail')->first();
if (isset($notification) && $notification['enabled'] == 1) {
$params['array_list'] = $array_list;
$params['client_policy_id'] = $client_policy_id;
$params['emp_code'] = $emp_code;
$params['client_id'] = $client_id;
$params['notification'] = $notification;
$params['common'] = [
'client_id' => $filteredEmpData[0]['client_id'],
'client_branch_id' => $filteredEmpData[0]['client_branch_id'],
'client_policy_id' => null,
'employee_policy_id' => null,
'employee_id' => $filteredEmpData[0]['id'],
'mail_type' => 'member_review_and_summary_mail',
];
// dd($params);
$wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
// print_r($wholeData); die;
if ($mail_active == 1) {
$mail_send_return = MailHelper::send_email($wholeData[0]);
$this->myLogger->logme("error", $mail_send_return);
}
// if (isset($wholeData)) {
// $params['common']['mail_type'] = 'account_maneger_summary_mail';
// $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params);
// // print_r($account_manager_wholeData); die;
// if($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData))
// {
// if($mail_active > 0){
// foreach ($account_manager_wholeData as $key => $value) {
// // $mail_send_return1 = MailHelper::send_email($value);
// $this->myLogger->logme("info", $mail_send_return1);
// }
// }
// }else{
// $this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client');
// }
// $params['common']['mail_type'] = 'client_hr_summary_mail';
// $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params);
// // print_r($client_hr_wholeData); die;
// if($client_hr_wholeData != null && $client_hr_wholeData != '' &&count($client_hr_wholeData))
// {
// if($mail_active > 0){
// foreach ($client_hr_wholeData as $key => $value) {
// // $mail_send_return2 = MailHelper::send_email($value);
// $this->myLogger->logme("info", $mail_send_return2);
// }
// }
// }else{
// $this->myLogger->logme("error", 'Client HR Mail Configuration not Enable for this client');
// }
// }
} else {
$this->myLogger->logme("error", 'Member Review Mail Configuration not Enable for this client');
}
}
print_r($wholeData);
echo '<pre>';
echo '<h3>member_review_and_summary_mail</h3> <br><br>';
print_r($mail_send_return);
echo '<h3>account_maneger_summary_mail</h3> <br><br>';
print_r($mail_send_return1);
echo '<h3>client_hr_summary_mail</h3> <br><br>';
print_r($mail_send_return2);
// return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200);
}
//Function for Send Member Review and Summery Confirmation Mail
public function sendMemberReviewConfirmationMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0)
{
// dd($client_id, $emp_code, $policy_id, $mail_active);
if (empty($policy_id)) {
$client_policy_ids = $this->employeeModel
->select('employee_polices.client_policy_id')
->join('employee_polices', 'employees.id = employee_polices.employee_id')
->where('employees.client_id', $client_id)
->where('employees.emp_code', $emp_code)
->where('employee_polices.is_active', 1)
->where('employees.is_active', 1)
->findAll();
$client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id');
$client_policy_id = array_unique($client_policy_ids2);
} else {
$client_policy_id = json_decode($policy_id, true);
}
// dd($client_policy_id);
if (!is_null($client_policy_id) && is_array($client_policy_id)) {
$empData = $this->employeeModel
->where('emp_code', $emp_code)
->where('client_id', $client_id)
->where('is_active', 1)
->findAll();
$filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self');
if (empty($filteredEmpData)) {
return $this->respond([
'status' => 'error',
'code' => 404,
'message' => 'No active employee data found for the given criteria.',
], 404);
}
$array_list = [];
foreach ($client_policy_id as $value) {
$find = $this->employeeModel->getEmpFamilybyEmpCode(
client_policy_id: $value,
emp_code: $emp_code,
client_id: $client_id,
emp_status: ['draft', 'enrolled'],
policy_status: ['draft', 'enrolled']
);
if (count($find) > 0) {
$array_list[] = $find;
}
}
$notification = $this->notificationModel
->where('client_id', $client_id)
->where('template_name', 'member_review_and_summary_mail')
->first();
if ($notification && $notification['enabled'] == 1) {
$params = [
'array_list' => $array_list,
'client_policy_id' => $client_policy_id,
'emp_code' => $emp_code,
'client_id' => $client_id,
'notification' => $notification,
'common' => [
'client_id' => $filteredEmpData[0]['client_id'],
'client_branch_id' => $filteredEmpData[0]['client_branch_id'],
'client_policy_id' => null,
'employee_policy_id' => null,
'employee_id' => $filteredEmpData[0]['id'],
'mail_type' => 'member_review_and_summary_mail',
],
];
$wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
if ($mail_active == 0) {
// $mail_send_result = [];
$mail_send_result = MailHelper::send_email($wholeData[0]);
if ($mail_send_result['status'] === 'success') {
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Email sent successfully.',
'response' => $mail_send_result,
], 200);
} else {
return $this->respond([
'status' => 'error',
'code' => 500,
'message' => 'Failed to send email.',
'details' => $mail_send_result,
], 500);
}
}
return $this->respond([
'status' => 'success',
'code' => 200,
'message' => 'Notification prepared but email not sent as mail_active is 0.',
'data' => $wholeData,
], 200);
}
return $this->respond([
'status' => 'error',
'code' => 400,
'message' => 'Member Review Mail configuration is not enabled for this client.',
], 400);
}
return $this->respond([
'status' => 'error',
'code' => 404,
'message' => 'No active client policy IDs found.',
], 404);
}
//--------------------------------------------------------------------------------------------------------
public function index()
{
$this->myLogger->logme('error', 'Client list function called');
// echo "<script>console.log( 'client list function called );</script>";
$headerData['tab_name'] = 'Clients';
$headerData['page_name'] = 'Clients'; // Both Browser Tab name And Page name are same.
// $data['clientList'] = $this->clientModel->getCreatedByUserName(1); // passing client_type
$data['client_rm'] = $this->clientRMModel->getAllClientRM();
$data['lead_data'] = $this->leadsModel->getLeadForInsertClientList();
$rawList = $this->clientModel->getCreatedByUserName(1);
$clientRM = $data['client_rm'];
$rmMap = [];
foreach ($clientRM as $rm) {
$rmMap[$rm->client_id][] = $rm->account_manager;
}
$data['clientList'] = (!empty($rawList) && is_array($rawList)) ? array_map(function($item) use ($rmMap) {
$managers = isset($rmMap[$item->id]) ? implode(", ", $rmMap[$item->id]) : "N/A";
return (object) [
'id' => $item->id,
'client_name' => $item->client_name,
'short_name' => $item->short_name,
'account_managers' => $managers
];
}, $rawList) : [];
// dd($data);
// dd($data['clientList']);
echo view('layout/header', $headerData);
echo view('client_list', $data);
echo view('layout/footer');
// $this->loadLayout('client_onboarding', $data);
}
public function typeList($id = null)
{
try {
$rawList = $this->clientModel->getCreatedByUserName($id); // passing client_type
$clientRM = $this->clientRMModel->getAllClientRM();;
$rmMap = [];
foreach ($clientRM as $rm) {
$rmMap[$rm->client_id][] = $rm->account_manager;
}
$data['clientList'] = (!empty($rawList) && is_array($rawList)) ? array_map(function($item) use ($rmMap) {
$managers = isset($rmMap[$item->id]) ? implode(", ", $rmMap[$item->id]) : "N/A";
return (object) [
'id' => $item->id,
'client_name' => $item->client_name,
'short_name' => $item->short_name,
'account_managers' => $managers
];
}, $rawList) : [];
if (empty($data)) {
return $this->response
->setJSON(['status' => 'error', 'message' => 'No Records found'])
->setStatusCode(404);
}
return $this->response
->setJSON(['status' => 'success', 'data' => $data])
->setStatusCode(200);
} catch (\Throwable $e) {
return $this->response
->setJSON(['status' => 'error', 'message' => $e->getMessage()])
->setStatusCode(500);
}
}
public function updateEmpAndPolicyStatus()
{
$return = $this->clientPolicyModel->updateStatus();
print_rr($return);
$this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]);
$this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]);
}
public function updatePolicyTermsForCorrections()
{
$results = $this->clientPolicyModel
->select('id, policy_terms')
->where('policy_terms IS NOT NULL')
->where('policy_terms <>', '')
->whereNotIn('policy_type_id', [1, 6, 7])
->orderBy('id', 'desc')
->get()
->getResultArray();
$client_policy_ids = [];
foreach ($results as $key => $result) {
$client_policy_id = $result['id'];
$policy_terms = json_decode($result['policy_terms'], true); // true to get associative array
if (isset($policy_terms['family_floaters'])) {
$family_floaters = $policy_terms['family_floaters'];
$parents = $family_floaters['parents'] ?? 0;
$parents_in_law = $family_floaters['parents-in-law'] ?? 0;
if ($parents == 1 && $parents_in_law == 1) {
$client_policy_ids[] = $client_policy_id;
$policy_terms['family_floaters']['parents'] = 0;
$policy_terms['family_floaters']['parents-in-law'] = 0;
$policy_terms['family_floaters']['either-parents-pil'] = 2;
$results[$key]['policy_terms'] = json_encode($policy_terms);
// Update the policy_terms in the database
$this->clientPolicyModel
->where('id', $client_policy_id)
->set('policy_terms', $results[$key]['policy_terms'])
->update();
}
}
}
if (count($client_policy_ids) > 0) {
echo 'There are ' . count($client_policy_ids) . ' records to be updated.';
echo '<br>';
dd($client_policy_ids);
} else {
echo 'There is no records to be update.';
}
// dd($results);
}
public function removeClient($id = null)
{
$this->myLogger->logme('error', 'Client Remove function called');
$client_policy_data = $this->clientPolicyModel
->where('policy_status', 1)
->where('Is_active', 1)
->where('client_id', $id)
->countAllResults();
if ($client_policy_data == 0) {
$data['updated_by'] = get_session_userid();
$data['is_active'] = 0;
$update = $this->clientModel->update($id, $data);
return $this->respond(['status' => true, 'code' => 200], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Client has active policy'], 200);
}
}
public function removeClientBranch($id = null)
{
$this->myLogger->logme('error', 'Client Branch Remove function called');
$data = [
'updated_by' => get_session_userid(),
'is_active' => 0
];
$config_count = $this->clientPolicyModel->where('client_branch_id', $id)->countAllResults();
if ($config_count > 0) {
$update = $this->clientBranchModel->where('id', $id)->set($data)->update();
if ($update) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Client branch removed successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove client branch'], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The client branch configuration with policy cannot be deleted.'], 200);
}
}
public function clientOnboarding()
{
$this->myLogger->logme('error', 'Client Onboarding function called');
$headerData['tab_name'] = 'Client Onboarding';
$headerData['page_name'] = 'Clients';
$data['entity'] = $this->kycEntityTypeModel->findAll();
$data['kyc_docs'] = $this->kycDocsModel->findAll();
$data['police'] = $this->policesModel->findAll();
$data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$data['state'] = $this->stateModel->getAllStates();
$data['RM'] = $this->userModel->where('is_active', 1)->findAll();
$data['policyGridData'] = $this->policyGridModel->findAll();
$data['policy_types'] = $this->policyTypeModel->findAll();
$data['policy_type'] = ['1' => 'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon'];
$data['client_type'] = ['1' => 'Group', '2' => 'Retail'];
$data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
$data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
// echo "<pre>";
// print_r($data); die;
$data['placeHolders'] = ['hr_name', 'member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
// dd($data['placeHolders']);
// auto fetch client list and branch list from pre
$data['auto_fetch_client_list'] = $this->getClientListFromPre();
echo view('layout/header', $headerData);
echo view('client_onboarding', $data);
echo view('layout/footer');
}
// In your controller
public function deposit($ClientId = null, $requestFrom = null, $policyId = null)
{
$headerData['tab_name'] = 'Client Deposit';
$headerData['page_name'] = 'Clients';
if (is_string($ClientId) && preg_match('/^[a-f0-9]{32}$/i', $ClientId))
{
$data['clientName'] = $this->clientModel->where('md5(id)', $ClientId)->find();
}else {
$data['clientName'] = $this->clientModel->where('id', $ClientId)->find();
}
$data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($ClientId, $policyId);
$data['depositsummary'] = $this->clientPolicyModel->getDepositlistsummary($ClientId);
// Fetch associated insurer names and balances
$balances = $this->clientPolicyModel->getBalances($ClientId);
$data['balances'] = $balances;
// dd($data);
if ($requestFrom == 'rest') {
return $data;
}
echo view('layout/header', $headerData);
echo view('client_deposit_list', $data);
echo view('layout/footer');
}
public function view_Deposit($insurerId, $requestFrom = null, $param = null)
{
// Load your model to fetch data based on $clientId and $insurerId
// $subTypeOptions = [
// 1 => 'Deposit',
// 2 => 'Adjustment',
// 3 => 'Refund',
// 4 => 'Debit',
// ];
$subTypeOptions = [
1 => 'Replenishment By Client',
2 => 'Adjustment',
3 => 'Refund From Deletion',
4 => 'Debit',
5 => 'Non EB',
6 => 'Refund By Insurer',
7 => 'Opening Amount',
8 => 'Truncated',
];
$data['subTypeOptions'] = $subTypeOptions;
$headerData['tab_name'] = 'Client Deposit';
$headerData['page_name'] = 'Clients';
$loggedInUserID = get_session_userid();
// $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId);
if ($requestFrom == 'rest') {
$clientId = $param['client_id'];
$cd_ac_pk = $param['cd_ac_pk'];
} else {
$clientId = $this->request->getGet('client_id');
$cd_ac_pk = $this->request->getGet('cd_ac_pk');
}
$data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId);
$data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId, $cd_ac_pk, $subTypeOptions);
$data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
$data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId, $cd_ac_pk);
$data['cd_ac_pk'] = $cd_ac_pk;
if ($requestFrom == 'rest') {
return $data;
}
// print_rr($data);die();
// Load the view for the new list page;
echo view('layout/header', $headerData);
echo view('view_deposit', $data);
echo view('layout/footer');
}
public function saveDeposit()
{
$rules = [
'amount' => [
'rules' => 'required|numeric|greater_than_equal_to[0]',
'errors' => [
'required' => 'Amount is required',
'numeric' => 'Amount must be a valid number',
'greater_than_equal_to' => 'Amount cannot be negative',
]
],
'client_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Client ID is required',
'is_natural_no_zero' => 'Client ID must be a positive integer',
]
],
'insurer_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Insurer ID is required',
'is_natural_no_zero' => 'Insurer ID must be a positive integer',
]
],
'cd_ac_pk' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Account PK is required',
'is_natural_no_zero' => 'Account PK must be a positive integer',
]
],
'cd_ac_no' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-_]+$/]',
'errors' => [
'required' => 'CD Account number is required.',
'regex_match' => 'CD Account number can only contain letters, numbers, hyphens(-), underscores(_), and slashes(/).',
]
],
'sub_type_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Sub type ID is required',
'is_natural_no_zero' => 'Sub type ID must be a positive integer',
]
],
'description' => [
'rules' => 'required|string|min_length[3]|max_length[255]',
'errors' => [
'required' => 'Description is required',
'string' => 'Description must be text',
'min_length' => 'Description must be at least 3 characters',
'max_length' => 'Description must not exceed 255 characters',
]
],
'transaction_type' => [
'rules' => 'required|in_list[Credit,Debit]',
'errors' => [
'required' => 'Transaction type is required',
'in_list' => 'Transaction type must be either credit or debit',
]
],
];
if (! $this->validate($rules)) {
return $this->response
->setStatusCode(400)
->setJSON([
'status' => 'error',
'message' => 'Input validation failed',
'errors' => $this->validator->getErrors()
]);
}
//sanitize the post params
$post_data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($post_data);
// Retrieve form data from POST request
$loggedInUserID = get_session_userid();
// print_rr($sanitized_post_data);die();
$client_id = $sanitized_post_data['client_id'] ?? null;
$insurer_id = $sanitized_post_data['insurer_id'] ?? null;
$record_date = $sanitized_post_data['record_date'] ?? null;
$cd_ac_pk = $sanitized_post_data['cd_ac_pk'] ?? null;
$cd_ac_no = $sanitized_post_data['cd_ac_no'] ?? null;
// $CD_Account_Number = $this->CDMasterModel
// ->where('client_id', $client_id)
// ->where('insurer_id', $insurer_id)
// ->where('is_active', 1)
// ->first();
if (!empty($record_date)) {
// Prepare the array with data
$date = \DateTime::createFromFormat('d/m/Y', $record_date);
$record_date = $date->format('Y-m-d');
} else {
$record_date = null;
}
$data = [
'amount' => $sanitized_post_data['amount'] ?? null,
'sub_type_id' => $sanitized_post_data['sub_type_id'] ?? null,
'client_id' => $sanitized_post_data['client_id'] ?? null,
'client_policy_id' => null,
'cd_ac_no' => $cd_ac_no ?? null,
'cd_ac_pk' => $cd_ac_pk ?? null,
'endorsement_no' => null,
'insurer_id' => $sanitized_post_data['insurer_id'] ?? null,
'description' => $sanitized_post_data['description'] ?? null,
'transaction_type' => $sanitized_post_data['transaction_type'] ?: 'Credit',
'updated_by' => 1,
'record_date' => $record_date
];
// log_message('error','data for insert'.json_encode($data));die();
// print_rr($data);die();
// Call the saveDeposit function from DepositHelper
$response = DepositHelper::saveDeposit($data, $loggedInUserID);
// Return a boolean value based on success
return $this->response->setJSON(['success' => $response['success']]);
}
public function editClientOnboarding($id = null)
{
$this->myLogger->logme('error', 'Edit Client Onboarding function called');
$headerData['tab_name'] = 'Edit Client Onboarding';
$headerData['page_name'] = 'Clients';
$editData['RM'] = $this->userModel->where('is_active', 1)->findAll();
$editData['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
$editData['tpa_list'] = $this->tpaModel->where('is_active', 1)->findAll();
$editData['state'] = $this->stateModel->getAllStates();
$editData['police'] = $this->policesModel->findAll();
$editData['entity'] = $this->kycEntityTypeModel->findAll();
$editData['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
$editData['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
$editData['insurer_branch'] = $this->insurerBranchModel->where('is_active', 1)->findAll();
$editData['clients'] = $this->clientModel->where('is_active', 1)->findAll();
$editData['kyc_docs'] = $this->kycDocsModel->findAll();
$editData['policyGridData'] = $this->policyGridModel->findAll();
$editData['policy_types'] = $this->policyTypeModel->findAll();
$editData['policy_type'] = ['1' => 'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon'];
$editData['client_type'] = ['1' => 'Group', '2' => 'Retail'];
// dd($editData['policy_types']);
$editData['client'] = $this->clientModel->where(['id' => $id])->first();
$editData['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $id)->findAll();
$editData['client_kyc_primary_table'] = $this->generateKycPrimaryTable($id);
$editData['client_kyc_other_table'] = $this->generateKycOthersTable($id);
$editData['client_branch'] = $this->clientBranchModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
$editData['client_relation'] = $this->clientRMModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
$editData['client_branch']['role'] = get_role_id();
$editData['lead_data'] = $this->leadsModel->getLeadForInsertClientList(2, $id);
$clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($id);
foreach ($clientPoliceData as $key => $value) {
$clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
$clientPoliceData[$key]->open_date = date('d-M-Y', strtotime($value->open_date));
$clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
$clientPoliceData[$key]->close_date = date('d-M-Y', strtotime($value->close_date));
}
$editData['client_policy'] = $clientPoliceData;
//Notes : $editData['client_policy'] this on called in client_policy page
$rawList = $editData['client_policy'];
$editData['client_policy'] = (!empty($rawList) && is_array($rawList))
? array_values(array_map(function ($item) {
return (object) [
'id' => $item->id,
'policy_no' => $item->policy_no,
'policy_type_name' => $item->policy_type_name,
'policy_start_date' => $item->policy_start_date,
'policy_end_date' => $item->policy_end_date,
'insurer_short' => $item->insurer_short,
'insurer_branch_name' => $item->insurer_branch_name,
'branch_name' => $item->branch_name ?? ' - ',
'tpa_short' => $item->tpa_short,
'policy_type_name' => $item->policy_type_name,
'policy_type_id' => $item->policy_type_id,
'lead_cd_amount' => $item->lead_cd_amount,
'tpa_branch_code' => $item->tpa_branch_code,
'branch_name' => $item->branch_name ?? ' - ',
'policy_type_id' => $item->policy_type_id,
'allocg' => $item->allocg,
'lead_misc' => $item->lead_misc,
];
}, $rawList)) : [];
$editData['client_policy']['role'] = get_role_id();
$editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll();
$editData['placeHolders'] = ['hr_name', 'member_name', 'member_mobile', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];
$editData['api_data'] = $this->clientApi->where("client_id", $id)->where("is_active", 1)->first();
// dd($editData);
$edit['pre_branch_id'] = $this->clientBranchModel->select('pre_branch_id')->where('client_id',$id)->get()->getResultArray()[0]['pre_branch_id']??"";
$editData['auto_fetch_client_list'] = $this->getClientListFromPre();
echo view('layout/header', $headerData);
echo view('client_onboarding', $editData);
echo view('layout/footer');
}
public function createClientGeneralInfo()
{
$this->myLogger->logme('error', 'Client general info function called');
$rules = [
'entity_type_id' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Entity Type is required',
'numeric' => 'Invalid Entity Type selected'
]
],
'client_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]|min_length[2]|max_length[45]',
'errors' => [
'required' => 'Client Name is required',
'regex_match' => 'Client Name can only contain letters, numbers, spaces, hyphens and underscores.',
'min_length' => 'Client Name must be at least 2 characters.',
'max_length' => 'Client Name must not exceed 45 characters.',
]
],
'short_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_\- ]+$/]|min_length[2]|max_length[15]',
'errors' => [
'required' => 'Client Short Name is required',
'regex_match' => 'Client Short Name can only contain letters, numbers, hyphens and underscores.',
'min_length' => 'Client Short Name must be at least 2 characters.',
'max_length' => 'Client Short Name must not exceed 15 characters.',
]
],
'pan' => [
'rules' => 'permit_empty|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]$/]',
'errors' => [
'regex_match' => 'Invalid PAN format. Example: ABCDE1234F'
]
],
'hr_file_processed_by' => [
'rules' => 'required',
'errors' => [
'required' => 'HR File Processed By is required.',
]
],
// 'client_logo' => [
// 'rules' => [
// 'uploaded[client_logo]', // Add this to check if a file was actually sent
// 'is_image[client_logo]',
// 'max_size[client_logo,200]',
// 'ext_in[client_logo,jpg,jpeg,png]',
// 'max_dims[client_logo,100,100]',
// ],
// 'errors' => [
// 'uploaded' => 'Please upload a client logo',
// 'is_image' => 'The uploaded file must be an image',
// 'max_size' => 'File size should not exceed 200 KB',
// 'ext_in' => 'Allowed file types: jpg, jpeg, png',
// 'max_dims' => 'Image dimensions must be 100 x 100 pixels',
// ]
// ],
'client_logo' => [
'label' => 'Client Logo',
'rules' => 'permit_empty|is_image[client_logo]|max_size[client_logo,200]|ext_in[client_logo,jpg,jpeg,png]|max_dims[client_logo,100,100]',
'errors' => [
'is_image' => 'Please upload a valid image file.',
'max_size' => 'The logo is too heavy (Max 200KB).',
'ext_in' => 'Only JPG, JPEG, and PNG files are allowed.',
'max_dims' => 'The logo must be no larger than 100x100 pixels.',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$sanitized_post_data['created_by'] = get_session_userid();
$sanitized_post_data['client_logo'] = $file_name;
$sanitized_post_data['client_code'] = generate_client_code();
if (!isset($sanitized_post_data['is_download_btn'])) {
$sanitized_post_data['is_download_btn'] = 0;
} elseif ($sanitized_post_data['is_download_btn']) {
$sanitized_post_data['is_download_btn'] = 1;
}
if (empty($sanitized_post_data['parent_client_id'])) {
$sanitized_post_data['parent_client_id'] = null;
}
$insertID = $this->clientModel->insert($sanitized_post_data);
if ($insertID) {
$client_info = $this->clientModel->where(['id' => $insertID, 'is_active' => 1])->first();
// Template Creation
if (!$this->createDefaultMailTemplate($insertID, $client_info)) {
$this->myLogger->logme('error', 'Default Mail Template Creation Failed for Client ID: ' . $insertID);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $client_info], 200);
}
return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to create client'], 500);
}
public function editClientGeneralInfo()
{
$rules = [
'entity_type_id' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Entity Type is required',
'numeric' => 'Invalid Entity Type selected'
]
],
'client_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]',
'errors' => [
'required' => 'Client Name is required',
'regex_match' => 'Client Name can only contain letters, numbers, spaces, hyphens and underscores.',
'min_length' => 'Client Name must be at least 2 characters.',
'max_length' => 'Client Name must not exceed 45 characters.',
]
],
'short_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_\- ]+$/]|min_length[2]|max_length[15]',
'errors' => [
'required' => 'Client Short Name is required',
'regex_match' => 'Client Short Name can only contain letters, numbers, hyphens and underscores.',
'min_length' => 'Client Short Name must be at least 2 characters.',
'max_length' => 'Client Short Name must not exceed 15 characters.',
]
],
'pan' => [
'rules' => 'permit_empty|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]$/]',
'errors' => [
'regex_match' => 'Invalid PAN format. Example: ABCDE1234F'
]
],
'hr_file_processed_by' => [
'rules' => 'required',
'errors' => [
'required' => 'HR File Processed By is required.',
]
],
'client_logo' => [
'rules' => 'permit_empty|is_image[client_logo]|max_size[client_logo,200]|ext_in[client_logo,jpg,jpeg,png]|max_dims[client_logo,100,100]',
'errors' => [
'is_image' => 'The uploaded file must be an image',
'max_size' => 'File size should not exceed 200 KB',
'ext_in' => 'Allowed file types: jpg, jpeg, png',
'max_dims' => 'Image dimensions must be 100 x 100 pixels',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$this->myLogger->logme('error', 'edit client general info function called');
$uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$id = $this->request->getPost('PrimaryKey');
$data = $this->request->getPost();
$data['updated_by'] = get_session_userid();
if (!empty($file_name)) {
$data['client_logo'] = $file_name;
}
if (!isset($data['is_download_btn'])) {
$data['is_download_btn'] = 0;
} elseif ($data['is_download_btn']) {
$data['is_download_btn'] = 1;
}
if (empty($data['parent_client_id'])) {
$data['parent_client_id'] = null;
}
// print_r($data);die;
$update = $this->clientModel->update($id, $data);
if ($update) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function createClientKYCInf()
{
$this->myLogger->logme('error', 'create Client kyc function called');
$data = $this->request->getPost();
$form_type = $this->request->getPost('form_type') ?? null;
// print_r($data); die;
unset($data['file_name']);
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$File = file_Upload($this->request->getFile('file_name'), $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($File)) {
$data['file_name'] = $File;
// $uploadFilePath = $uploadFilePath . '/' . $File;
// $GoogleDriveController = new GoogleDriveController();
// $GoogleDriveController->uploadFiletoGdrive(client_id: $data['client_id'], doc_type: 'KYC', file_path: $uploadFilePath, file_name: $data['file_name']);
}
$data['created_by'] = get_session_userid();
$insert = $this->clientKYCDocsModel->insert($data);
if ($insert) {
// $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll();
if ($form_type == "others") {
$kycDocs = $this->generateKycOthersTable($this->request->getPost('client_id'));
} else {
$kycDocs = $this->generateKycPrimaryTable($this->request->getPost('client_id'));
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
/** Create Client KYC Documents V1 */
public function createClientKYCInfo()
{
$this->myLogger->logme('error', 'Create Client KYC function called');
$rules = [
'other_docs_name' => [
'label' => 'Documents Name',
'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9_\- ]+$/]',
'errors' => [
'regex_match' => 'Document Name can only contain letters, numbers, hyphens, and underscores'
]
],
'file_name' => [
'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]',
'errors' => [
'uploaded' => 'KYC document file is required',
'max_size' => 'File size should not exceed 5MB',
'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$sanitized_data = sanitizeInputArrayAdvanced($data);
$form_type = $sanitized_data['form_type'] ?? null;
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
unset($data['file_name']);
$file = $this->request->getFile('file_name');
$fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName;
}
$sanitized_data['created_by'] = get_session_userid();
$insertID = $this->clientKYCDocsModel->insert($sanitized_data);
if ($insertID) {
if ($form_type === 'others') {
$kycDocs = $this->generateKycOthersTable($sanitized_data['client_id']);
} else {
$kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $file
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200);
}
}
/** Edit Client KYC Documents V1 */
public function editClientKYCInfo()
{
$this->myLogger->logme('error', 'Edit Client KYC function called');
$rules = [
'file_name' => [
'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]',
'errors' => [
'uploaded' => 'KYC document file is required',
'max_size' => 'File size should not exceed 5MB',
'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$sanitized_data = sanitizeInputArrayAdvanced($data);
$form_type = $sanitized_data['form_type'] ?? null;
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
unset($sanitized_data['file_name']);
$file = $this->request->getFile('file_name');
$fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName;
}
$id = $sanitized_data['PrimaryKey'];
$sanitized_data['client_id'] = $id;
$sanitized_data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id');
$sanitized_data['updated_by'] = get_session_userid();
$insertID = $this->clientKYCDocsModel->insert($sanitized_data);
if ($insertID) {
if ($form_type === 'others') {
$kycDocs = $this->generateKycOthersTable($sanitized_data['client_id']);
} else {
$kycDocs = $this->generateKycPrimaryTable($sanitized_data['client_id']);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $file], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to upload KYC document'], 200);
}
}
public function deleteClientKycDocs($id = null)
{
$delete = $this->clientKYCDocsModel->where('kyc_doc_type_id', $id)->delete();
if ($delete) {
return $this->respond(['status' => true, 'code' => 200, 'id' => $id], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function deleteClientKycOtherDocs($id = null)
{
$delete = $this->clientKYCDocsModel->where('id', $id)->delete();
if ($delete) {
return $this->respond(['status' => true, 'code' => 200, 'id' => $id], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
/** Client KYC Documents V2 */
public function createClientKYCInfo_2()
{
$this->myLogger->logme('error', 'Create Client KYC V2 function called');
$rules = [
'file_name' => [
'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]',
'errors' => [
'uploaded' => 'KYC document file is required',
'max_size' => 'File size should not exceed 5MB',
'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$uploadedFile = $this->request->getFile('file_name');
if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
$this->myLogger->logme('info', 'File is valid and ready to move.');
} else {
$this->myLogger->logme('error', 'File failed validation or was not uploaded.');
}
unset($data['file_name']);
$sanitized_data = sanitizeInputArrayAdvanced($data);
$form_type = $sanitized_data['form_type'] ?? null;
$file = $this->request->getFile('file_name');
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName;
}
$sanitized_data['created_by'] = get_session_userid();
$this->myLogger->logme('info', 'Result of file_Upload: ' . $fileName);
unset($data['file_name']);
$insertID = $this->clientKYCDocsModel->insert($sanitized_data);
if ($insertID) {
$html = $this->generateKycSingleTable($sanitized_data['client_id']);
$dropdown = $this->fetch_dropdown($sanitized_data['client_id']);
return $this->respond(['status' => true, 'code' => 200, 'file_name' => $fileName, 'html' => $html,'dropdown'=>$dropdown], 200);
} else {
$this->myLogger->logme('error', 'Database insert failed.');
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to add document'], 200);
}
}
/** Edit Client KYC Documents V2 */
public function editClientKYCInfo_2()
{
$this->myLogger->logme('error', 'Edit Client KYC V2 function called');
$rules = [
'file_name' => [
'rules' => 'uploaded[file_name]|max_size[file_name,5120]|ext_in[file_name,pdf,jpg,jpeg,png]',
'errors' => [
'uploaded' => 'KYC document file is required',
'max_size' => 'File size should not exceed 5MB',
'ext_in' => 'Allowed file types: pdf, jpg, jpeg, png',
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
unset($data['file_name']);
$sanitized_data = sanitizeInputArrayAdvanced($data);
$form_type = $sanitized_data['form_type'] ?? null;
$kyc_id = $sanitized_data['id'] ?? null;
$client_id = $sanitized_data['client_id'] ?? null;
$old_file_name = $sanitized_data['old_file_name'] ?? null;
if (empty($kyc_id)) {
return $this->respond(['status' => false, 'message' => 'Missing KYC ID'], 400);
}
$updateData = [];
$uploadedFile = $this->request->getFile('file_name');
$new_file_name = null;
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
$new_file_name = file_Upload($uploadedFile, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!$new_file_name) {
return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200);
}
$updateData['file_name'] = $new_file_name;
// Delete the old file from the storage if it exists
// if (!empty($old_file_name)) {
// $old_file_path = $uploadFilePath . '/' . $old_file_name;
// if (file_exists($old_file_path)) {
// unlink($old_file_path);
// // Optionally delete from G-Drive here if applicable
// }
// }
}
if (empty($updateData)) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'No changes detected. Document remains the same.'], 200);
}
$updateData['updated_by'] = get_session_userid();
$update = $this->clientKYCDocsModel->update($kyc_id, $updateData);
if ($update) {
return $this->respond([
'status' => true,
'message' => 'Document updated successfully',
'html' => $this->generateKycSingleTable($client_id),
'dropdown' => $this->fetch_dropdown($client_id)
], 200);
}
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Database update failed or record not found.'], 200);
}
/** Delete Client KYC Documents V2 */
public function deleteClientKycDocs_2()
{
$this->myLogger->logme('error', 'Delete Client KYC V2 function called');
$data = $this->request->getPost();
$sanitized_data = sanitizeInputArrayAdvanced($data);
$kyc_id = $sanitized_data['id'] ?? null;
$client_id = $sanitized_data['client_id'] ?? null;
$is_active = $sanitized_data['is_active'] ?? null;
if (empty($kyc_id)) {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Missing document ID.'], 200);
}
$updateData = [
'is_active' => (int) $is_active,
'updated_by' => get_session_userid()
];
$delete = $this->clientKYCDocsModel->update($kyc_id, $updateData);
if ($delete) {
return $this->respond([
'status' => true,
'code' => 200,
'id' => $kyc_id,
'message' => 'Document successfully deactivated.',
'html' => $this->generateKycSingleTable($client_id),
'dropdown' => $this->fetch_dropdown($client_id)
], 200);
}
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update record (ID not found or DB error).'], 200);
}
public function fetch_dropdown($client_id)
{
$db = db_connect();
// Already uploaded docs
$uploadedData = $db->table('client_kyc_documents')
->select('kyc_doc_type_id')
->where('client_id', $client_id)
->where('is_active', 1)
->get()
->getResultArray();
$excludedIds = array_column($uploadedData, 'kyc_doc_type_id');
// Available docs
$builder = $db->table('kyc_docs kd');
$builder->select('kd.id, kd.file_name');
$builder->join('clients c', 'kd.kyc_type_id = c.entity_type_id');
$builder->where('c.id', $client_id);
$builder->where('kd.is_active', 1);
if (!empty($excludedIds)) {
$builder->whereNotIn('kd.id', $excludedIds);
}
$result = $builder->get()->getResultArray(); // ✅ ARRAY
// Build dropdown
$dropdown = '<option value="">Select Document</option>';
$dropdown .= '<option value="other">Additional Document</option>';
foreach ($result as $row) {
$dropdown .= '<option value="' . esc($row['id']) . '">'
. esc($row['file_name']) .
'</option>';
}
return $dropdown;
}
public function createClientRelation()
{
$this->myLogger->logme('error', 'Client relation function called');
$rules = [
// --- Hidden Fields ---
'PrimaryKey' => [
'rules' => 'permit_empty|numeric',
],
'client_id' => [
'rules' => 'required|numeric',
'errors' => ['required' => 'Client ID is missing.']
],
// --- Account Manager (Array Category) ---
// Note the .* which validates every item inside the multiple select array
'account_manager' => [
'rules' => 'required',
'errors' => [
'required' => 'Please select at least one Account Manager (L1).',
]
],
// --- Manager (L2) ---
'manager' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Please select a Manager (L2).',
'numeric' => 'Invalid Manager selection.'
]
],
// --- Head ---
'head' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Please select a Head.',
'numeric' => 'Invalid Head selection.'
]
],
];
// if (!$this->validate($rules)) {
// return $this->response->setStatusCode(400)->setJSON([
// 'status' => false,
// 'message' => 'Input validation failed',
// 'code' => 400,
// 'errors' => $this->validator->getErrors()
// ]);
// }
$data['client_id'] = $this->request->getPost('client_id');
$data['created_by'] = get_session_userid();
$inserted = false;
if ($this->request->getPost('head')) {
$data['level'] = "1";
$data['user_id'] = $this->request->getPost('head');
$inserted = $this->clientRMModel->insert($data);
}
if ($this->request->getPost('manager')) {
$data['level'] = "2";
$data['user_id'] = $this->request->getPost('manager');
$inserted = $this->clientRMModel->insert($data);
}
if ($this->request->getPost('account_manager')) {
$data['level'] = "3";
foreach ($this->request->getPost('account_manager') as $value) {
$data['user_id'] = $value;
$inserted = $this->clientRMModel->insert($data);
}
}
if ($inserted) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $this->request->getPost()], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function editClientRelation()
{
$this->myLogger->logme('error', 'Client relation function called');
$rules = [
// --- Hidden Fields ---
'PrimaryKey' => [
'rules' => 'permit_empty|numeric',
],
'client_id' => [
'rules' => 'required|numeric',
'errors' => ['required' => 'Client ID is missing.']
],
// --- Account Manager (Array Category) ---
// Note the .* which validates every item inside the multiple select array
'account_manager' => [
'rules' => 'required',
'errors' => [
'required' => 'Please select at least one Account Manager (L1).',
]
],
// --- Manager (L2) ---
'manager' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Please select a Manager (L2).',
'numeric' => 'Invalid Manager selection.'
]
],
// --- Head ---
'head' => [
'rules' => 'required|numeric',
'errors' => [
'required' => 'Please select a Head.',
'numeric' => 'Invalid Head selection.'
]
],
];
// if (!$this->validate($rules)) {
// return $this->response->setStatusCode(400)->setJSON([
// 'status' => false,
// 'message' => 'Input validation failed',
// 'code' => 400,
// 'errors' => $this->validator->getErrors()
// ]);
// }
$id = $this->request->getPost('PrimaryKey');
$data['client_id'] = $this->request->getPost('client_id');
$data['updated_by'] = get_session_userid();
$inserted = false;
// print_r($this->request->getPost()); die;
if ($this->request->getPost('head')) {
$data['user_id'] = $this->request->getPost('head');
$this->clientRMModel->where('client_id', $id)->where('level', 1)->delete();
$data['level'] = "1";
$data['user_id'] = $this->request->getPost('head');
$inserted = $this->clientRMModel->insert($data);
}
if ($this->request->getPost('manager')) {
$data['user_id'] = $this->request->getPost('manager');
$this->clientRMModel->where('client_id', $id)->where('level', 2)->delete();
$data['level'] = "2";
$data['user_id'] = $this->request->getPost('manager');
$inserted = $this->clientRMModel->insert($data);
}
// if ($this->request->getPost('head')) {
// $data['user_id'] = $this->request->getPost('head');
// $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('head'), 1);
// if ($checkHead) {
// $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 1)->set($data)->update();
// } else {
// $data['level'] = "1";
// $data['user_id'] = $this->request->getPost('head');
// $inserted = $this->clientRMModel->insert($data);
// }
// }
// if ($this->request->getPost('manager')) {
// $data['user_id'] = $this->request->getPost('manager');
// $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('manager'), 2);
// if ($checkHead) {
// $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 2)->set($data)->update();
// } else {
// $data['level'] = "2";
// $data['user_id'] = $this->request->getPost('manager');
// $inserted = $this->clientRMModel->insert($data);
// }
// }
if ($this->request->getPost('account_manager')) {
$this->clientRMModel->where('client_id', $id)->where('level', 3)->delete();
$data['level'] = "3";
foreach ($this->request->getPost('account_manager') as $value) {
$data['user_id'] = $value;
$inserted = $this->clientRMModel->insert($data);
}
}
$lastQuery = $this->clientRMModel->getLastQuery();
if ($inserted) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $this->request->getPost(), "place" => 'edit'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, "place" => 'edit', 'message' => 'no data found'], 200);
}
}
public function createClientBranchNew()
{
$this->myLogger->logme('error', 'Client branch CREATE function called');
$rules = [
'branch_name' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]|min_length[3]',
'errors' => [
'required' => 'Branch Name is required',
'regex_match' => 'Branch Name can only contain letters, numbers, spaces, hyphens and underscores.',
]
],
'branch_code' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]',
'errors' => [
'required' => 'Branch Code is required',
'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores.',
]
],
'address1' => [
'rules' => 'required',
'errors' => ['required' => 'Address Line 1 is required']
],
'address2' => [
'rules' => 'permit_empty|string',
],
'state' => [
'label' => 'State',
'rules' => 'required',
'errors' => ['required' => 'State is required.']
// 'rules' => 'required|regex_match[/^[a-zA-Z\s\-]+$/]',
// 'errors' => [
// 'required' => 'State is required.',
// 'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
// ]
],
'district' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'required' => 'District is required.',
'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
]
],
'city' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
]
],
'pincode' => [
'rules' => 'required|numeric|exact_length[6]',
'errors' => [
'required' => 'Pincode is required.',
'numeric' => 'Pincode must be digits only.',
'exact_length' => 'Pincode must be exactly 6 digits.'
]
],
'gst' => [
'rules' => 'required|regex_match[/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$/]',
'errors' => [
'required' => 'GST number is required',
'regex_match' => 'Invalid GST Number format.'
]
],
'name.*' => [
'rules' => 'required|alpha_space',
'errors' => [
'required' => 'Contact name is required',
'alpha_space' => 'Contact name may contain only letters and spaces'
]
],
'designation.*' => [
'rules' => 'required|regex_match[/^[A-Za-z0-9\-_\/ ]+$/]',
'errors' => [
'required' => 'Designation is required',
'regex_match' => 'Designation may only contain letters, numbers, /, -, _ and spaces'
]
],
'email.*' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
]
],
'mobile.*' => [
'rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required',
'numeric' => 'Mobile number must contain digits only',
'exact_length' => 'Mobile number must be exactly 10 digits'
]
],
'units.*' => [
'rules' => 'permit_empty|numeric' // For the multiple select
],
'sez' => [
'rules' => 'permit_empty' // For the checkbox
]
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
if (!isset($sanitized_post_data['sez'])) {
$sanitized_post_data['sez'] = 0;
} elseif ($sanitized_post_data['sez']) {
$sanitized_post_data['sez'] = 1;
}
$units = json_decode($sanitized_post_data['units'], true) ?? [];
if (!is_array($units) || empty($units)) {
$client_data = $this->clientModel->where('id', $sanitized_post_data['client_id'])->first();
$default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($sanitized_post_data['branch_code'] ?? ''), '-');
$sanitized_post_data['units'] = json_encode([$default_unit]);
}
$sanitized_post_data['created_by'] = get_session_userid();
// before updating check if pre_branch_id is already existing in the current db
if(isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('pre_branch_id',$sanitized_post_data['pre_branch_id'])
//->where('id !=',$post_branch_id)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->insert($sanitized_post_data);
$post_branch_id = $insert;
if ($insert) {
$level_contact_data_raw = $this->request->getPost('level_contect_data');
$level_contact_data = [];
if (!empty($level_contact_data_raw)) {
$level_contact_data_decoded = json_decode($level_contact_data_raw, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($level_contact_data_decoded)) {
$level_contact_data = sanitizeInputArrayAdvanced($level_contact_data_decoded);
}
}
if (!empty($level_contact_data)) {
$this->saveLevelContacts($level_contact_data, $insert);
}
}
if($post_branch_id && isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id']))
{
// need to update the client_branch in the pre
$result = $this->updatePreClientBranch($sanitized_post_data['pre_branch_id'],$post_branch_id , "create");
log_message('error','Pre client_branch update result for pre_branch_id '.$sanitized_post_data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
}
if ($insert) {
$branchData = $this->clientBranchModel->where('client_id', $sanitized_post_data['client_id'])->findAll();
$branchData['role'] = get_role_id();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $branchData,
'message' => 'Client branch created successfully',
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Failed to create client branch ',
], 200);
}
}
public function editClientBranchNew()
{
$this->myLogger->logme('error', 'Client branch EDIT function called');
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = $sanitized_post_data['branch_id_primarykey'] ?? null;
$client_id = $sanitized_post_data['client_id'] ?? null;
$pre_branch_id = $sanitized_post_data['pre_branch_id'] ?? '';
$data['pre_branch_id'] = $pre_branch_id;
$raw_units = $this->request->getPost('units');
$emp_unit_count = 0;
$rr_unit_count = 0;
$rr_unit_count2 = 0;
$total_count = 0;
$list_of_branch_units = $this->clientBranchModel->find((int)$id);
$units = !empty($list_of_branch_units['units']) ? json_decode($list_of_branch_units['units'], true) : [];
if (!is_array($units) || empty($units)) {
$client_data = $this->clientModel->where('id', $sanitized_post_data['client_id'])->first();
$default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($sanitized_post_data['branch_code'] ?? ''), '-');
$sanitized_post_data['units'] = json_encode([$default_unit]);
$units = [$default_unit]; // Update local variable for counting
}
if (!empty($units)) {
foreach ($units as $unit) {
$emp_unit_count += $this->employeeModel->where('unit', $unit)->countAllResults();
$rr_unit_count += $this->policyPremium2Model->where('unit', $unit)->countAllResults();
$rr_unit_count2 += $this->policyPremium1Model->where('unit', $unit)->countAllResults();
}
$total_count = $emp_unit_count + $rr_unit_count + $rr_unit_count2;
}
$uncommonValues = [];
if ($total_count > 0) {
$post_units_raw = $sanitized_post_data['units'] ?? '[]';
$branch_units = json_decode($list_of_branch_units['units'] ?? '[]', true);
// Ensure we handle both string-json and array types
$incoming_units = is_array($post_units_raw) ? $post_units_raw : json_decode($post_units_raw, true);
if (is_array($branch_units) && is_array($incoming_units)) {
$uncommonValues = array_diff($branch_units, $incoming_units);
}
if (count($uncommonValues) > 0) {
$branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();
return $this->respond([
'status' => false,
'code' => 404,
'message' => "Deleted unit(s) in use. couldn't complete this operation.",
'uncommonValues' => $uncommonValues,
'data' => $branchData,
], 200);
}
}
if (!isset($sanitized_post_data['sez'])) {
$sanitized_post_data['sez'] = 0;
} elseif ($sanitized_post_data['sez']) {
$sanitized_post_data['sez'] = 1;
}
$sanitized_post_data['updated_by'] = get_session_userid();
$post_branch_id = $id;
// before updating check if pre_branch_id is already existing in the current db
if(isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('pre_branch_id',$sanitized_post_data['pre_branch_id'])
->where('id !=',$post_branch_id)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->update($id, $sanitized_post_data);
if($post_branch_id && isset($sanitized_post_data['pre_branch_id']) && !empty($sanitized_post_data['pre_branch_id']))
{
// need to update the client_branch in the pre
$result = $this->updatePreClientBranch($sanitized_post_data['pre_branch_id'],$post_branch_id , "update");
log_message('error','Pre client_branch update result for pre_branch_id '.$sanitized_post_data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
}
$this->myLogger->logme('error', 'Client branch EDITED by {data}', ['data' => get_session_userid()]);
if ($insert) {
$level_contact_data_raw = $this->request->getPost('level_contect_data');
$level_contact_data = [];
if (!empty($level_contact_data_raw)) {
$level_contact_data_decoded = json_decode($level_contact_data_raw ?? '{}', true);
$level_contact_data = sanitizeInputArrayAdvanced($level_contact_data_decoded);
}
if (!empty($level_contact_data)) {
$this->saveLevelContacts($level_contact_data, $insert);
}
}
if ($insert) {
$branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $branchData,
'emp_unit_count' => $emp_unit_count,
'rr_unit_count' => $rr_unit_count,
'list_of_branch_units' => $list_of_branch_units,
'total_count' => $total_count,
'uncommonValues' => $uncommonValues,
'message' => 'Client branch updated successfully',
'response_data' => $sanitized_post_data
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update client branch'], 200);
}
}
public function saveLevelContactsNew($level_contact_data, $branch_id)
{
if (!empty($level_contact_data) && is_array($level_contact_data)) {
foreach ($level_contact_data as $value) {
if (!empty($value['id'])) {
$id = $value['id'];
unset($value['id']);
$this->levelContactModel->update($id, $value);
} else {
unset($value['id']);
$value['contact_type'] = "client";
$value['ref_id'] = $branch_id ?? null;
$this->levelContactModel->insert($value);
}
}
}
}
public function removeLevelContactsNew()
{
$id = $this->request->getGet('id');
try {
if (empty($id)) {
return $this->respond([
'status' => false,
'message' => 'Invalid ID provided. ID is empty',
'data' => $id
], 400);
}
$updated = $this->levelContactModel->update($id, ['is_active' => 0]);
if ($updated === false) {
return $this->respond([
'status' => false,
'message' => 'Failed to remove contact'
], 500);
}
return $this->respond([
'status' => true,
'message' => 'Contact removed successfully'
]);
} catch (\Exception $e) {
return $this->respond([
'status' => false,
'message' => 'An error occurred: ' . $e->getMessage()
], 500);
}
}
public function createClientBranch()
{
$this->myLogger->logme('error', 'Client branch CREATE function called');
$rules = [
'branch_name' => [
'rules' => 'required|min_length[3]|regex_match[/^[a-zA-Z0-9\s\-_]+$/]',
'errors' => [
'required' => 'Branch Name is required',
'min_length' => 'Branch Name must be at least 3 characters long',
'regex_match' => 'Branch Name can only contain letters, numbers, spaces, hyphens and underscores.'
]
],
'branch_code' => [
// Note: Codes usually don't have spaces, but I've included the others
'rules' => 'required|min_length[2]|regex_match[/^[a-zA-Z0-9\-_]+$/]',
'errors' => [
'required' => 'Branch Code is required',
'min_length' => 'Branch Code must be at least 2 characters long',
'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores.'
]
],
'address1' => [
'rules' => 'required',
'errors' => [
'required' => 'Address Line 1 is required',
]
],
'state' => [
'label' => 'State',
// 'rules' => 'required|regex_match[/^[a-zA-Z\s\-]+$/]',
'rules' => 'required',
'errors' => [
'required' => 'State is required.',
// 'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
]
],
'district' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'required' => 'District is required.',
'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
]
],
'city' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
]
],
'pincode' => [
'rules' => 'required|numeric|exact_length[6]',
'errors' => [
'required' => 'Pincode is required.',
'numeric' => 'Pincode must be digits only.',
'exact_length' => 'Pincode must be exactly 6 digits.'
]
],
'gst' => [
'rules' => 'required|regex_match[/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$/]',
'errors' => [
'required' => 'GST number is required',
'regex_match' => 'Invalid GST Number. Example: 12ABCDE1234F5Z6'
]
],
'name.*' => [
'rules' => 'required|min_length[3]|regex_match[/^[a-zA-Z0-9\s\-_]+$/]',
'errors' => [
'required' => 'Contact name is required',
'min_length' => 'Contact name must be at least 3 characters long',
'regex_match' => 'Contact name can only contain letters, numbers, spaces, hyphens and underscores.'
]
],
'designation.*' => [
'rules' => 'required|regex_match[/^[A-Za-z0-9\-_\/ ]+$/]',
'errors' => [
'required' => 'Designation is required',
'regex_match' => 'Designation may only contain letters, numbers, /, -, _ and spaces'
]
],
'email.*' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
]
],
'mobile.*' => [
'rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required',
'numeric' => 'Mobile number must contain digits only',
'exact_length' => 'Mobile number must be exactly 10 digits'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($data);
if (!isset($data['sez'])) {
$data['sez'] = 0;
} elseif ($data['sez']) {
$data['sez'] = 1;
}
$units = json_decode($data['units'], true) ?? [];
if (!is_array($units) || empty($units)) {
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
$default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
$data['units'] = json_encode([$default_unit]);
}
$data['created_by'] = get_session_userid();
// before updating check if pre_branch_id is already existing in the current db
if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('pre_branch_id',$data['pre_branch_id'])
//->where('id !=',$post_branch_id)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->insert($data);
$post_branch_id = $insert;
if ($insert) {
$level_contact_data = $this->request->getPost('level_contect_data');
$level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null;
$this->saveLevelContacts($level_contact_data, $insert);
}
if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
{
// need to update the client_branch in the pre
$result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "create");
log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
}
if ($insert) {
$branchData = $this->clientBranchModel->where('client_id', $this->request->getPost('client_id'))->findAll();
$branchData['role'] = get_role_id();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $branchData,
'message' => 'Client branch created successfully',
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'Failed to create client branch ',
], 200);
}
}
public function editClientBranch()
{
$this->myLogger->logme('error', 'Client branch EDIT function called');
$id = $this->request->getPost('branch_id_primarykey');
$client_id = $this->request->getPost('client_id');
$pre_branch_id = $this->request->getPost('pre_branch_id') ?? '';
$rules = [
'branch_name' => [
'rules' => 'required|min_length[3]|regex_match[/^[a-zA-Z0-9\s\-_]+$/]',
'errors' => [
'required' => 'Branch Name is required',
'min_length' => 'Branch Name must be at least 3 characters long',
'regex_match' => 'Branch Name can only contain letters, numbers, spaces, hyphens and underscores.'
]
],
'branch_code' => [
// Note: Codes usually don't have spaces, but I've included the others
'rules' => 'required|min_length[2]|regex_match[/^[a-zA-Z0-9\-_]+$/]',
'errors' => [
'required' => 'Branch Code is required',
'min_length' => 'Branch Code must be at least 2 characters long',
'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores.'
]
],
'address1' => [
'rules' => 'required',
'errors' => [
'required' => 'Address Line 1 is required',
]
],
'state' => [
'label' => 'State',
'rules' => 'required',
'errors' => ['required' => 'State is required.']
],
'district' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'required' => 'District is required.',
'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
]
],
'city' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
'errors' => [
'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
]
],
'pincode' => [
'rules' => 'required|numeric|exact_length[6]',
'errors' => [
'required' => 'Pincode is required.',
'numeric' => 'Pincode must be digits only.',
'exact_length' => 'Pincode must be exactly 6 digits.'
]
],
'gst' => [
'rules' => 'required|regex_match[/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$/]',
'errors' => [
'required' => 'GST number is required',
'regex_match' => 'Invalid GST Number. Example: 12ABCDE1234F5Z6'
]
],
'name.*' => [
'rules' => 'required|min_length[3]|regex_match[/^[a-zA-Z0-9\s\-_]+$/]',
'errors' => [
'required' => 'Contact name is required',
'min_length' => 'Contact name must be at least 3 characters long',
'regex_match' => 'Contact name can only contain letters, numbers, spaces, hyphens and underscores.'
]
],
'designation.*' => [
'rules' => 'required|regex_match[/^[A-Za-z0-9\-_\/ ]+$/]',
'errors' => [
'required' => 'Designation is required',
'regex_match' => 'Designation may only contain letters, numbers, /, -, _ and spaces'
]
],
'email.*' => [
'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
'errors' => [
'required' => 'Email address is required.',
'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
]
],
'mobile.*' => [
'rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required',
'numeric' => 'Mobile number must contain digits only',
'exact_length' => 'Mobile number must be exactly 10 digits'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($data);
$data['pre_branch_id'] = $pre_branch_id;
$units = $this->request->getPost('units');
$emp_unit_count = 0;
$rr_unit_count = 0;
$rr_unit_count2 = 0;
$total_count = 0;
$list_of_branch_units = $this->clientBranchModel->find((int)$id);
$units = json_decode($list_of_branch_units['units']);
if (!is_array($units) || empty($units)) {
$client_data = $this->clientModel->where('id', $data['client_id'])->first();
$default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
$data['units'] = json_encode([$default_unit]);
}
if (!empty($units)) {
foreach ($units as $unit) {
$emp_unit_count += $this->employeeModel->where('unit', $unit)->countAllResults();
$rr_unit_count += $this->policyPremium2Model->where('unit', $unit)->countAllResults();
$rr_unit_count2 += $this->policyPremium1Model->where('unit', $unit)->countAllResults();
}
$total_count = $emp_unit_count + $rr_unit_count + $rr_unit_count2;
}
$uncommonValues = [];
if ($total_count > 0) {
$units = (string) $this->request->getPost('units'); // Assuming 'units' is an array
$list_of_branch_units = $this->clientBranchModel->find((int)$id);
$branch_units = json_decode($list_of_branch_units['units'], true);
$units = json_decode($units);
$uncommonValues = array_diff($branch_units, $units);
if (count($uncommonValues) > 0) {
$branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();
return $this->respond([
'status' => false,
'code' => 404,
'message' => "Deleted unit(s) in use. couldn't complete this operation.",
'uncommonValues' => $uncommonValues,
'data' => $branchData,
], 200);
}
}
if (!isset($data['sez'])) {
$data['sez'] = 0;
} elseif ($data['sez']) {
$data['sez'] = 1;
}
$data['updated_by'] = get_session_userid();
$post_branch_id = $id;
// before updating check if pre_branch_id is already existing in the current db
if(isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
{
$existing_pre_branch = $this->clientBranchModel
->where('pre_branch_id',$data['pre_branch_id'])
->where('id !=',$post_branch_id)
->first();
if($existing_pre_branch)
{
return $this->respond([
'status' => false,
'code' => 409,
'message' => 'The branch is already mapped with another branch. Please check.',
], 409);
}
}
$insert = $this->clientBranchModel->update($id, $data);
if($post_branch_id && isset($data['pre_branch_id']) && !empty($data['pre_branch_id']))
{
// need to update the client_branch in the pre
$result = $this->updatePreClientBranch($data['pre_branch_id'],$post_branch_id , "update");
log_message('error','Pre client_branch update result for pre_branch_id '.$data['pre_branch_id'].' and post_branch_id '.$post_branch_id.' is '.json_encode($result));
}
$this->myLogger->logme('error', 'Client branch EDITED by {data}', ['data' => get_session_userid()]);
if ($insert) {
$level_contact_data = $this->request->getPost('level_contect_data');
$level_contact_data = !empty($level_contact_data) ? json_decode($level_contact_data, true) : null;
$this->saveLevelContacts($level_contact_data, $id);
}
if ($insert) {
$branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $branchData,
'emp_unit_count' => $emp_unit_count,
'rr_unit_count' => $rr_unit_count,
'list_of_branch_units' => $list_of_branch_units,
'total_count' => $total_count,
'uncommonValues' => $uncommonValues,
'message' => 'Client branch updated successfully',
'response_data' => $this->request->getPost()
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update client branch'], 200);
}
}
public function saveLevelContacts($level_contact_data, $branch_id)
{
if (!empty($level_contact_data) && is_array($level_contact_data)) {
foreach ($level_contact_data as $value) {
if (!empty($value['id'])) {
$id = $value['id'];
unset($value['id']);
$this->levelContactModel->update($id, $value);
} else {
unset($value['id']);
$value['contact_type'] = "client";
$value['ref_id'] = $branch_id ?? null;
$this->levelContactModel->insert($value);
}
}
}
}
public function removeLevelContacts()
{
$id = $this->request->getGet('id');
try {
if (empty($id)) {
return $this->respond([
'status' => false,
'message' => 'Invalid ID provided. ID is empty',
'data' => $id
], 400);
}
$updated = $this->levelContactModel->update($id, ['is_active' => 0]);
if ($updated === false) {
return $this->respond([
'status' => false,
'message' => 'Failed to remove contact'
], 500);
}
return $this->respond([
'status' => true,
'message' => 'Contact removed successfully'
]);
} catch (\Exception $e) {
return $this->respond([
'status' => false,
'message' => 'An error occurred: ' . $e->getMessage()
], 500);
}
}
/** here ci4 rules not implemented, because UI screen Fields are hide/show implemented thats why */
public function createClientPolicy()
{
// print_r($this->request->getPost()); die;
$this->myLogger->logme('error', 'Client policy CREATE function called');
$request_post_data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($request_post_data);
$rules = [
'client_branch_id' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a Client Branch.']
],
'policy_type_id' => [
'rules' => ['required', 'is_natural_no_zero'],
'errors' => [
'required' => 'Policy Type is required.',
'is_natural_no_zero' => 'Please select a valid Policy Type.'
]
],
'insurer' => [
'rules' => 'required',
'errors' => ['required' => 'Please select an Insurer.']
],
'tpa' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
],
'policy_no' => [
'rules' => ['required', 'regex_match[/^[a-zA-Z0-9\s_\-\/\\\]+$/]'],
'errors' => [
'required' => 'Policy No is required.',
'regex_match' => 'Invalid characters in Policy No.'
]
],
'gst' => [
'rules' => [
'required',
'numeric',
'greater_than_equal_to[0]',
'less_than_equal_to[100]'
],
'errors' => [
'required' => 'GST percentage is required.',
'numeric' => 'GST must be a valid number.',
'greater_than_equal_to' => 'GST cannot be negative.',
'less_than_equal_to' => 'GST percentage cannot exceed 100%.'
]
],
'policy_start_date' => [
'rules' => 'required',
'errors' => ['required' => 'Start date is required.']
],
'policy_end_date' => [
'rules' => 'required',
'errors' => ['required' => 'End date is required.']
],
'wellness_plan_id' => [
'rules' => 'permit_empty|alpha_numeric',
'errors' => ['alpha_numeric' => 'Wellness Plan ID can only contain letters and numbers.']
],
'wellness_vendor_id' => [
'rules' => 'permit_empty'
],
'disclaimer' => [
'rules' => ['permit_empty', 'string', 'min_length[5]'],
'errors' => ['min_length' => 'Disclaimer should be at least 5 characters long if provided.']
],
'enrolment_visibility' => ['rules' => 'permit_empty'],
'is_lgbtq' => ['rules' => 'permit_empty']
];
// 2. Run the initial validation
$isValid = $this->validate($rules);
// 3. Perform manual date comparison
$start = $this->request->getPost('policy_start_date');
$end = $this->request->getPost('policy_end_date');
$startDate = change_date_format($start ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$endDate = change_date_format($end ?? null, 'd-m-Y', 'Y-m-d') ?? null;
if ($startDate && $endDate && ($endDate < $startDate)) {
// Manually push the error into the validator
$this->validator->setError('policy_end_date', 'Policy start and end date are mismatched (End date cannot be before Start date).');
$isValid = false;
}
// 4. Check final status
if (!$isValid) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$policy_type_id = $sanitized_post_data['policy_type_id'] ?? null;
$client_branch_id = $sanitized_post_data['client_branch_id'] ?? null;
$client_id = $sanitized_post_data['client_id'] ?? null;
$base_policy = $sanitized_post_data['base_policy'] ?? null;
$insurerValue = (string) $sanitized_post_data['insurer'] ?? null;
list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
$sanitized_post_data['insurer_branch_id'] = $insurerBranchId;
$sanitized_post_data['insurer_id'] = $insurerId;
$tpaValue = (string) $sanitized_post_data['tpa'] ?? null;
if ($tpaValue === null || $tpaValue === '') {
$tpaBranchId = null;
$tpaId = null;
} else {
list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
}
$sanitized_post_data['client_id'] = $client_id;
$sanitized_post_data['tpa_branch_id'] = $tpaBranchId;
$sanitized_post_data['tpa_id'] = $tpaId;
$sanitized_post_data['policy_type_id'] = $sanitized_post_data['policy_type_id'] ?? null;
$sanitized_post_data['earned_premium_date'] = change_date_format($sanitized_post_data['earned_premium_date'] ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$sanitized_post_data['claims_incurred_date'] = change_date_format($sanitized_post_data['claims_incurred_date'] ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$sanitized_post_data['base_policy'] = ($sanitized_post_data['base_policy'] === '' || $sanitized_post_data['base_policy'] == 0) ? null : $sanitized_post_data['base_policy'];
$sanitized_post_data['policy_status'] = 1;
$sanitized_post_data['inception_type'] = (isset($sanitized_post_data['inception_type']) && $sanitized_post_data['inception_type'] !== "")
? $sanitized_post_data['inception_type']
: 1;
$sanitized_post_data['is_member_modify_allowed'] = $sanitized_post_data['is_member_modify_allowed'] ?? null ? 1 : 0;
$sanitized_post_data['enrolment_visibility'] = $sanitized_post_data['enrolment_visibility'] ?? null ? 1 : 0;
$sanitized_post_data['is_lgbtq'] = $sanitized_post_data['is_lgbtq'] ?? null ? 1 : 0;
$sanitized_post_data['wellness_vendor_id'] = !empty($sanitized_post_data['wellness_vendor_id']) ? $sanitized_post_data['wellness_vendor_id'] : null;
$sanitized_post_data['cd_ac_pk'] = $sanitized_post_data['cd_ac_no'] ?? null;
if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {
$sanitized_post_data['is_addon'] = 1; // Base Policy
} else if ($policy_type_id == 4 || $policy_type_id == 5) {
$sanitized_post_data['is_addon'] = 2; // SI TOPUP
} else if ($policy_type_id == 3) {
if ($base_policy) {
$sanitized_post_data['is_addon'] = 3; // Dependent Addon
} else {
$sanitized_post_data['is_addon'] = 1;
}
}
$sanitized_post_data['policy_start_date'] = change_date_format($sanitized_post_data['policy_start_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['policy_end_date'] = change_date_format($sanitized_post_data['policy_end_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['policy_no'] = $sanitized_post_data['policy_no'] ?? null;
if (isset($sanitized_post_data['inception_type']) && $sanitized_post_data['inception_type'] == 2) {
$sanitized_post_data['open_date'] = change_date_format($sanitized_post_data['open_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['close_date'] = change_date_format($sanitized_post_data['close_date'] ?? null, 'd-m-Y', 'Y-m-d');
// $data['reminder_date'] = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d');
$sanitized_post_data['reminder_date'] = $sanitized_post_data['reminder_date'] ?? null;
} else {
$sanitized_post_data['open_date'] = null;
$sanitized_post_data['closedate'] = null;
$sanitized_post_data['reminder_date'] = null;
}
$sanitized_post_data['created_by'] = get_session_userid();
$insert = $this->clientPolicyModel->insert($sanitized_post_data);
if ($insert) {
// this function to create a policy transaction entry at the time of client policy create
$this->createPolicyTransactionInceptionEntry($insert, $sanitized_post_data);
$clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($sanitized_post_data['client_id']);
$clientPoliceData['role'] = get_role_id();
return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'client_id' => $client_id, 'method' => 'CERATE', 'post_data' => $insert], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
/** here ci4 rules not implemented, because UI screen Fields are hide/show implemented thats why */
public function editClientPolicy()
{
$rules = [
'client_branch_id' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a Client Branch.']
],
'policy_type_id' => [
'rules' => ['required', 'is_natural_no_zero'],
'errors' => [
'required' => 'Policy Type is required.',
'is_natural_no_zero' => 'Please select a valid Policy Type.'
]
],
'insurer' => [
'rules' => 'required',
'errors' => ['required' => 'Please select an Insurer.']
],
'tpa' => [
'rules' => 'required',
'errors' => ['required' => 'Please select a TPA.']
],
'policy_no' => [
'rules' => ['required', 'regex_match[/^[a-zA-Z0-9\s_\-\/\\\]+$/]'],
'errors' => [
'required' => 'Policy No is required.',
'regex_match' => 'Invalid characters in Policy No.'
]
],
'gst' => [
'rules' => [
'required',
'numeric',
'greater_than_equal_to[0]',
'less_than_equal_to[100]'
],
'errors' => [
'required' => 'GST percentage is required.',
'numeric' => 'GST must be a valid number.',
'greater_than_equal_to' => 'GST cannot be negative.',
'less_than_equal_to' => 'GST percentage cannot exceed 100%.'
]
],
'policy_start_date' => [
'rules' => 'required',
'errors' => ['required' => 'Start date is required.']
],
'policy_end_date' => [
'rules' => 'required',
'errors' => ['required' => 'End date is required.']
],
'wellness_plan_id' => [
'rules' => 'permit_empty|alpha_numeric',
'errors' => ['alpha_numeric' => 'Wellness Plan ID can only contain letters and numbers.']
],
'wellness_vendor_id' => [
'rules' => 'permit_empty'
],
'disclaimer' => [
'rules' => ['permit_empty', 'string', 'min_length[5]'],
'errors' => ['min_length' => 'Disclaimer should be at least 5 characters long if provided.']
],
'enrolment_visibility' => ['rules' => 'permit_empty'],
'is_lgbtq' => ['rules' => 'permit_empty']
];
// 2. Run the initial validation
$isValid = $this->validate($rules);
// 3. Perform manual date comparison
$start = $this->request->getPost('policy_start_date');
$end = $this->request->getPost('policy_end_date');
$startDate = change_date_format($start ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$endDate = change_date_format($end ?? null, 'd-m-Y', 'Y-m-d') ?? null;
if ($startDate && $endDate && ($endDate < $startDate)) {
// Manually push the error into the validator
$this->validator->setError('policy_end_date', 'Policy start and end date are mismatched (End date cannot be before Start date).');
$isValid = false;
}
// 4. Check final status
if (!$isValid) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$this->myLogger->logme('error', 'Client policy function called');
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = $sanitized_post_data['PrimaryKey'] ?? null;
$client_id = $sanitized_post_data['client_id'] ?? null;
$policy_type_id = $sanitized_post_data['policy_type_id'] ?? null;
$base_policy = $sanitized_post_data['base_policy'] ?? null;
$insurerValue = (string) $sanitized_post_data['insurer'];
list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
$sanitized_post_data['insurer_branch_id'] = $insurerBranchId ?? null;
$sanitized_post_data['insurer_id'] = $insurerId ?? null;
$tpaValue = (string) $sanitized_post_data['tpa'] ?? null;
if (!empty($tpaValue) || $tpaValue !== '') {
list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
} else {
$tpaBranchId = null;
$tpaId = null;
}
$sanitized_post_data['tpa_branch_id'] = $tpaBranchId ?? null;
$sanitized_post_data['client_id'] = $client_id ?? null;
$sanitized_post_data['tpa_id'] = $tpaId ?? null;
$sanitized_post_data['policy_type_id'] = $sanitized_post_data['policy_type_id'] ?? null;
$sanitized_post_data['policy_no'] = $sanitized_post_data['policy_no'] ?? null;
// $sanitized_post_data['insured'] = $sanitized_post_data['insured'];
$sanitized_post_data['no_of_lives'] = $sanitized_post_data['no_of_lives'] ?? null;
$sanitized_post_data['policy_status'] = $sanitized_post_data['policy_status'] ?? null;
$sanitized_post_data['no_of_employees'] = $sanitized_post_data['no_of_employees'] ?? null;
$sanitized_post_data['earned_premium_date'] = change_date_format($sanitized_post_data['earned_premium_date'] ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$sanitized_post_data['claims_incurred_date'] = change_date_format($sanitized_post_data['claims_incurred_date'] ?? null, 'd-m-Y', 'Y-m-d') ?? null;
$sanitized_post_data['incurred_claims_ratio'] = $sanitized_post_data['incurred_claims_ratio'] ?? null;
$sanitized_post_data['no_lives_at_inception'] = $sanitized_post_data['no_lives_at_inception'] ?? null;
$sanitized_post_data['premium_paid_at_inception'] = $sanitized_post_data['premium_paid_at_inception'] ?? null;
$sanitized_post_data['claims_experience_for_last_3_years'] = $sanitized_post_data['claims_experience_for_last_3_years'] ?? null;
$sanitized_post_data['earned_premium_amount'] = $sanitized_post_data['earned_premium_amount'] ?? null;
$sanitized_post_data['claims_incurred_amount'] = $sanitized_post_data['claims_incurred_amount'] ?? null;
$sanitized_post_data['base_policy'] = ($sanitized_post_data['base_policy'] === '' || $sanitized_post_data['base_policy'] == 0) ? null : $sanitized_post_data['base_policy'];
$sanitized_post_data['policy_status'] = 1;
$sanitized_post_data['inception_type'] = $sanitized_post_data['inception_type'] ?? null ? 2 : 1;
$sanitized_post_data['enrolment_visibility'] = $sanitized_post_data['enrolment_visibility'] ?? null ? 1 : 0;
$sanitized_post_data['client_branch_id'] = $sanitized_post_data['client_branch_id'] ?? null;
$sanitized_post_data['cd_ac_pk'] = $sanitized_post_data['cd_ac_no'] ?? null;
$sanitized_post_data['gst'] = $sanitized_post_data['gst'] ?? null;
$sanitized_post_data['disclaimer'] = $sanitized_post_data['disclaimer'] ?? null;
$sanitized_post_data['policy_start_date'] = change_date_format($sanitized_post_data['policy_start_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['policy_end_date'] = change_date_format($sanitized_post_data['policy_end_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['is_member_modify_allowed'] = $sanitized_post_data['is_member_modify_allowed'] ?? null ? 1 : 0;
$sanitized_post_data['is_lgbtq'] = $sanitized_post_data['is_lgbtq'] ?? null ? 1 : 0;
$sanitized_post_data['wellness_plan_id'] = $sanitized_post_data['wellness_plan_id'] ?? null;
$sanitized_post_data['wellness_vendor_id'] = $sanitized_post_data['wellness_vendor_id'] ?? null;
$sanitized_post_data['wellness_vendor_id'] = !empty($sanitized_post_data['wellness_vendor_id']) ? $sanitized_post_data['wellness_vendor_id'] : null;
if ($sanitized_post_data['inception_type'] == 2) {
$sanitized_post_data['open_date'] = change_date_format($sanitized_post_data['open_date'] ?? null, 'd-m-Y', 'Y-m-d');
$sanitized_post_data['close_date'] = change_date_format($sanitized_post_data['close_date'] ?? null, 'd-m-Y', 'Y-m-d');
// $sanitized_post_data['reminder_date'] = change_date_format($sanitized_post_data['reminder_date'), 'd-m-Y', 'Y-m-d');
$sanitized_post_data['reminder_date'] = $sanitized_post_data['reminder_date'] ?? null;
} else {
$sanitized_post_data['open_date'] = null;
$sanitized_post_data['close_date'] = null;
$sanitized_post_data['reminder_date'] = null;
}
if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {
$sanitized_post_data['is_addon'] = 1; // Base Policy
} else if ($policy_type_id == 4 || $policy_type_id == 5) {
$sanitized_post_data['is_addon'] = 2; // SI TOPUP
} else if ($policy_type_id == 3) {
if ($base_policy) {
$sanitized_post_data['is_addon'] = 3; // Dependent Addon
} else {
$sanitized_post_data['is_addon'] = 1;
}
}
$policy_terms = $this->clientPolicyModel->where('id', $sanitized_post_data['base_policy'])->first();
$old_client_policy_data = $this->clientPolicyModel->where('is_active', 1)->where('id', $id)->first();
$sanitized_post_data['updated_by'] = get_session_userid();
$update = $this->clientPolicyModel->update($id, $sanitized_post_data);
if ($update) {
$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();
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, 'client_id' => $client_id, 'method' => 'EDIT'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function removePolicy($id = null)
{
$this->myLogger->logme('error', 'Client Policy Remove function called');
$data = [
'updated_by' => get_session_userid(),
'is_active' => 0
];
$emp_details = $this->employeePolicyModel
->join('employees', 'employees.id = employee_polices.employee_id')
->where('client_policy_id', $id)
->where('employee_polices.status', 'active')
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'active')
->where('employees.is_active', 1)
->countAllResults();
if ($emp_details == 0) {
$update = $this->clientPolicyModel->where('id', $id)->set($data)->update();
if ($update) {
// $policy_transaction_update = $this->deactivatePolicyTransactionsPolicy($id);
return $this->respond(['status' => true, 'code' => 200], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy'], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The policy has active employees'], 200);
}
}
public function getNonEbRackRateFiles()
{
$clientPolicyId = $this->request->getGet('client_policy_id');
$policy = $this->clientPolicyModel->where('id', $clientPolicyId)->first();
if (!$policy) {
return $this->respond(['status' => false, 'message' => 'Policy not found'], 200);
}
$files = [];
$jsonField = is_array($policy) ? ($policy['non_eb_rack_rate_files'] ?? null) : ($policy->non_eb_rack_rate_files ?? null);
if (!empty($jsonField)) {
$files = json_decode($jsonField, true) ?? [];
}
return $this->respond(['status' => true, 'files' => $files], 200);
}
public function uploadNonEbRackRateFile()
{
$clientPolicyId = $this->request->getPost('client_policy_id');
$policy = $this->clientPolicyModel->where('id', $clientPolicyId)->first();
if (!$policy) {
return $this->respond(['status' => false, 'message' => 'Policy not found'], 200);
}
$uploadFilePath = WRITEPATH . 'uploads/non_eb_rack_rate';
$fileName = file_Upload($this->request->getFile('file'), $uploadFilePath, UPLOAD_EXT_NON_EB_RACK_RATE);
if (empty($fileName)) {
return $this->respond(['status' => false, 'message' => 'Invalid file. Only PDF and Excel files are allowed.'], 200);
}
$originalName = $this->request->getFile('file')->getClientName();
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$jsonField = is_array($policy) ? ($policy['non_eb_rack_rate_files'] ?? null) : ($policy->non_eb_rack_rate_files ?? null);
$files = !empty($jsonField) ? (json_decode($jsonField, true) ?? []) : [];
$fileEntry = [
'name' => $fileName,
'original_name' => $originalName,
'type' => $ext,
'uploaded_at' => date('Y-m-d H:i:s'),
];
$files[] = $fileEntry;
$this->clientPolicyModel->where('id', $clientPolicyId)->set(['non_eb_rack_rate_files' => json_encode($files)])->update();
return $this->respond(['status' => true, 'file' => $fileEntry], 200);
}
public function removeNonEbRackRateFile()
{
$clientPolicyId = $this->request->getPost('client_policy_id');
$filename = $this->request->getPost('filename');
$policy = $this->clientPolicyModel->where('id', $clientPolicyId)->first();
if (!$policy) {
return $this->respond(['status' => false, 'message' => 'Policy not found'], 200);
}
$jsonField = is_array($policy) ? ($policy['non_eb_rack_rate_files'] ?? null) : ($policy->non_eb_rack_rate_files ?? null);
$files = !empty($jsonField) ? (json_decode($jsonField, true) ?? []) : [];
$files = array_values(array_filter($files, function ($file) use ($filename) {
return $file['name'] !== $filename;
}));
$this->clientPolicyModel->where('id', $clientPolicyId)->set(['non_eb_rack_rate_files' => json_encode($files)])->update();
// Delete physical file
$filePath = WRITEPATH . 'uploads/non_eb_rack_rate/' . $filename;
if (file_exists($filePath)) {
unlink($filePath);
}
return $this->respond(['status' => true], 200);
}
public function deactivatePolicyTransactionsPolicy($clientPolicyId)
{
// Deactivate policy_transaction records
$this->policyTransactionModel
->where('client_policy_id', $clientPolicyId)
->set(['is_active' => 0])
->update();
// Get related policy_transaction IDs
$transactionIds = $this->policyTransactionModel
->select('id')
->where('client_policy_id', $clientPolicyId)
->findAll();
$ids = array_column($transactionIds, 'id');
// Deactivate related pt_co_share records
if (!empty($ids)) {
$this->PTCOShareDetailsModel
->whereIn('pt_id', $ids)
->set(['is_active' => 0])
->update();
}
}
public function createPolicyTransactionInceptionEntry($client_policy_id, $data)
{
$data['action_type'] = 'inception';
$data['client_policy_id'] = $client_policy_id;
$data['entry_from'] = 3;
$data['issuer_branch'] = 1;
$data['issuer'] = 2;
$data['status'] = 'completed';
$data['renewal_date'] = $data['policy_end_date'];
$data['bro_payable_by'] = 1;
$insert = $this->policyTransactionModel->insert($data);
if($insert){
$pcsd_data['pt_id'] = $insert;
$pcsd_data['insurer_id'] = $data['insurer_id'] ?? null;
$pcsd_data['insurer_branch_id'] = $data['insurer_branch_id'] ?? null;
$this->PTCOShareDetailsModel->insert($pcsd_data);
}
return $insert;
}
// Save Rack Rate function
public function createClientPolicyPremium()
{
try {
// 1. Fetch and Sanitize all input at once
$rawPost = $this->request->getPost();
$data = sanitizeInputArrayAdvanced($rawPost);
// Extract base variables from the sanitized array
$client_id = $data['client_id'] ?? null;
$client_policy_id = $data['client_policy_id'] ?? null;
$premium_type = $data['premium_type'] ?? null;
$policy_grid_id = $data['policy_grid_id'] ?? null;
$rack_rate_name = $data['rack_rate_name'] ?? null;
$si_or_bp = $data['si_or_bp'] ?? null;
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
if (!$record) {
return $this->respond(['status' => false, 'message' => 'Policy record not found'], 404);
}
if (empty($client_id)) {
$client_id = $record['client_id'];
}
$branch_units_raw = $this->getBranchUnitsByBranchId($record['client_branch_id']);
$branch_units = json_decode($branch_units_raw, true);
$default_unit = !empty($branch_units) ? $branch_units[0] : null;
// Relationship Logic
$relation_data = [
'self' => $data['self'] ?? 'NA',
'spouse' => $data['spouse'] ?? 'NA',
'childrens' => $data['childrens'] ?? 'NA',
'parents' => $data['parents'] ?? 'NA',
'parents-in-law' => $data['parents-in-law'] ?? 'NA',
];
if (in_array($policy_grid_id, ['1', '2'])) {
$relation_data = ['self' => 1, 'spouse' => 'NA', 'childrens' => 'NA', 'parents' => 'NA', 'parents-in-law' => 'NA'];
}
$jsonDataForRelation = json_encode($relation_data);
$submit_check_json = json_encode([$rack_rate_name => $relation_data]);
// Deactivate old records
if (in_array($policy_grid_id, ['1', '2'])) {
$this->policyPremium1Model->where(['client_id' => $client_id, 'client_policy_id' => $client_policy_id])->set(['is_active' => 0])->update();
} else {
$this->policyPremium2Model->where(['client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'rack_rate_name' => $rack_rate_name])->set(['is_active' => 0])->update();
}
// Helper closures for cleaning and unit selection
$cleanNum = fn($val) => str_replace(',', '', (string)($val ?? '0'));
$getUnit = fn($unitArr, $index) => (empty($unitArr[$index]) || $unitArr[$index] === 'undefined') ? $default_unit : $unitArr[$index];
$insert = false;
$baseInsertData = [
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'policy_grid_id' => $policy_grid_id,
'premium_type' => $premium_type,
'rack_rate_name' => $rack_rate_name,
'additional_relationship' => $jsonDataForRelation
];
// --- Logic Switch based on Grid ID ---
if ($policy_grid_id == '1') {
if ($si_or_bp == '1') {
$premiums = $data['gpa_sum_premium'] ?? [];
foreach ($premiums as $i => $p) {
$this->policyPremium1Model->insert(array_merge($baseInsertData, [
'si' => $cleanNum($data['gpa_sum_si'][$i] ?? 0),
'premium' => $cleanNum($p),
'multiplier' => $data['gpa_sum_multiplier'] ?? null,
'si_or_bp' => $si_or_bp,
'unit' => $getUnit($data['gpa_unit_1'] ?? [], $i)
]));
$insert = true;
}
} else if ($si_or_bp == '3') {
$premiums = $data['gpa_sum_premium2'] ?? [];
foreach ($premiums as $i => $p) {
$this->policyPremium1Model->insert(array_merge($baseInsertData, [
'si' => $cleanNum($data['gpa_sum_si2'][$i] ?? 0),
'premium' => $cleanNum($p),
'grade' => $data['gpa_band'][$i] ?? null,
'multiplier' => $data['gpa_sum_multiplier2'] ?? null,
'si_or_bp' => $si_or_bp,
'unit' => $getUnit($data['gpa_unit_3'] ?? [], $i)
]));
$insert = true;
}
} else if ($si_or_bp == '2') {
$premiums = $data['gpa_basic_premium'] ?? [];
foreach ($premiums as $i => $p) {
$this->policyPremium1Model->insert(array_merge($baseInsertData, [
'si_or_bp' => $si_or_bp,
'basic_multiplier' => $cleanNum($data['basic_multiplier'] ?? 0),
'multiplier' => $cleanNum($data['premium_multiplier'] ?? 0),
'basic_pay' => $cleanNum($data['basic_pay'][$i] ?? 0),
'si' => $cleanNum($data['gpa_basic_si'][$i] ?? 0),
'premium' => $cleanNum($p),
'unit' => $getUnit($data['gpa_unit'] ?? [], $i)
]));
$insert = true;
}
}
} else if (in_array($policy_grid_id, ['2', '9'])) {
$premiums = $data['gpa_premium29'] ?? [];
$model = ($policy_grid_id == '2') ? $this->policyPremium1Model : $this->policyPremium2Model;
foreach ($premiums as $i => $p) {
$model->insert(array_merge($baseInsertData, [
'premium' => $cleanNum($p),
'si' => $cleanNum($data['gpa_si29'][$i] ?? 0),
'unit' => $getUnit($data['gpa_unit29'] ?? [], $i)
]));
$insert = true;
}
} else {
// Handles grids 3, 4, 5, 6, 7, 8, 10, 11, 12, 13
$pfx = $policy_grid_id . "_";
$premiums = $data[$pfx . 'premium'] ?? [];
$is_si_array = is_array($data[$pfx . 'si'] ?? null);
foreach ($premiums as $i => $p) {
$this->policyPremium2Model->insert(array_merge($baseInsertData, [
'premium' => $cleanNum($p),
'si' => $cleanNum($is_si_array ? ($data[$pfx . 'si'][$i] ?? 0) : ($data[$pfx . 'si'] ?? 0)),
'unit' => $getUnit($data[$pfx . 'unit'] ?? [], $i),
'age_from' => $data[$pfx . 'age_from'][$i] ?? null,
'age_to' => $data[$pfx . 'age_to'][$i] ?? null,
'grade' => $data[$pfx . 'grade'][$i] ?? null,
'relationship' => $data[$pfx . 'relationship'][$i] ?? null,
'max_si' => $cleanNum($data[$pfx . 'max_si'][$i] ?? 0)
]));
$insert = true;
}
}
if ($insert) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'rack_rate_json' => $submit_check_json], 200);
}
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
} catch (\Exception $e) {
return $this->respond(['status' => false, 'message' => $e->getMessage() . ' line ' . $e->getLine()], 500);
}
}
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($params = null)
{
$this->myLogger->logme('error', 'uploadVehicleFile function called');
$client_id = null;
$vehicle_id = null;
$files = null;
$docs_name = null;
if(empty($params) && $this->request){
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$files = $this->request->getFiles();
$client_id = $sanitized_post_data['client_id'] ?? null;
$vehicle_id = $sanitized_post_data['vehicle_id'] ?? null;
$docs_name = $sanitized_post_data['other_docs_name'] ?? null;
}else {
$client_id = $params['client_id'] ?? null;
$vehicle_id = $params['vehicle_id'] ?? null;
$docs_name = $params['other_docs_name'] ?? null;
$files = $params['file_data'] ?? null;
}
// upload path
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$insertedDocs = [];
// Check document names and files
if (!empty($docs_name) && !empty($files) && !empty($client_id) && !empty($vehicle_id)) {
foreach ($docs_name as $key => $docName) {
// Get the corresponding file for this document name
$file = $files['file_name'][$key];
if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
// Upload the file
$uploadedFileName = file_Upload_for_lead($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if ($uploadedFileName) {
// Prepare data for each document upload
$docData = [
'client_id' => $client_id,
'vehicle_id' => $vehicle_id,
'other_docs_name' => $docName,
'file_name' => $uploadedFileName,
'created_by' => get_session_userid(),
];
// Insert into database
$insert = $this->clientKYCDocsModel->insert($docData);
if ($insert) {
$insertedDocs[] = $docData; // Collect successfully inserted docs
}
}
}
}
if(!empty($params) && !$this->request){
return true;
}
if (!empty($insertedDocs)) {
// Fetch all documents for the client
$vehicleDocs = $this->clientKYCDocsModel
->where('client_id', $sanitized_post_data['client_id'])
->where('vehicle_id', $sanitized_post_data['vehicle_id'])
->findAll();
return $this->respond(['status' => true, 'code' => 200, 'vehicle_docs' => $vehicleDocs, 'inserted_docs' => $insertedDocs, 'message' => 'File uploaded successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No documents uploaded or inserted'], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Invalid data submission'], 200);
}
}
public function getKycDocsById($id = null)
{
$this->myLogger->logme('error', 'getKycDocsById function called');
if ($id) {
$kyc_docs_data = $this->kycDocsModel->where(['kyc_type_id' => $id, 'is_active' => 1])->findAll();
$this->myLogger->logme('error', 'getKycDocs status TRUE');
return $this->respond(['status' => true, 'code' => 200, 'data' => $kyc_docs_data], 200);
} else {
$this->myLogger->logme('error', 'getKycDocs status FALSE');
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function generateKycPrimaryTable($client_id)
{
$db = db_connect();
$builder = $db->table('kyc_docs kd');
$builder->select('kd.*, ck.file_name AS upload_doc_name');
$builder->join('clients c', 'kd.kyc_type_id = c.entity_type_id');
$builder->join(
'client_kyc_documents ck',
'kd.id = ck.kyc_doc_type_id AND ck.client_id = c.id AND ck.is_active = 1',
'left'
);
$builder->where('c.id', $client_id);
$builder->groupBy(['kd.id', 'ck.file_name']);
$query = $builder->get();
$result['data'] = $query->getResultArray();
$result['client_id'] = $client_id;
$table = view('client_kyc_primary_table', $result);
return $table;
// print_r($table); die;
}
public function generateKycOthersTable($client_id)
{
$result['data'] = $this->clientKYCDocsModel
->where('is_active', 1)
->where('client_id', $client_id)
->groupStart()
->where('kyc_doc_type_id', null)
->orWhere('kyc_doc_type_id', 0)
->groupEnd()
->findAll();
$result['client_id'] = $client_id;
$table = view('client_kyc_other_table', $result);
return $table;
// print_r($table); die;
}
public function generateKycSingleTable($client_id)
{
// $result['ckdlist'] = db_connect()->table('client_kyc_documents ckd')
// ->select("ckd.id,ckd.client_id,ckd.kyc_doc_type_id,ckd.file_name,kd.file_name AS kd_docs_name,ckd.other_docs_name,ckd.vehicle_id,ckd.is_active,
// CASE
// WHEN ckd.kyc_doc_type_id IS NULL
// OR ckd.kyc_doc_type_id = 0
// OR ckd.kyc_doc_type_id = ''
// THEN ckd.other_docs_name
// ELSE kd.file_name
// END AS ui_docs_name")
// ->join('kyc_docs kd','ckd.kyc_doc_type_id = kd.id','left')
// ->where('ckd.client_id',$client_id)
// ->where('ckd.is_active',1)
// ->groupBy('ckd.id')
// ->get()
// ->getResultArray();
$builder = db_connect()->table('client_kyc_documents AS ckd');
// Select the standard fields
$builder->select('
ckd.id,
ckd.client_id,
ckd.kyc_doc_type_id,
ckd.file_name,
ckd.other_docs_name,
ckd.vehicle_id,
ckd.is_active
');
// Add the CASE statement for ui_docs_name
// Using false as the second parameter tells CI4 not to escape the string
$builder->select("
CASE
WHEN ckd.kyc_doc_type_id IS NULL OR ckd.kyc_doc_type_id = 0 OR ckd.kyc_doc_type_id = ''
THEN ckd.other_docs_name
ELSE kd.file_name
END AS ui_docs_name
", false);
// Join with kyc_docs
$builder->join('kyc_docs AS kd', 'ckd.kyc_doc_type_id = kd.id', 'left');
// Where clauses
$builder->where('ckd.client_id', $client_id);
$builder->where('ckd.is_active', 1);
// Group By
$builder->groupBy('ckd.id');
$result['ckdlist'] = $builder->get()->getResultArray();
$result['client_id'] = $client_id;
$table = view('client_kyc_single_table', $result);
return $table;
// print_r($table); die;
}
public function getPolicesByInsurerId($id = null)
{
$this->myLogger->logme('error', 'getPolicesByInsurerId function called');
if ($id) {
$police_data = $this->policesModel
->select('policies.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
->where(['insurer_id' => $id, 'policies.is_active' => 1])->findAll();
return $this->respond(['status' => true, 'code' => 200, 'data' => $police_data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function getSingleBranchDataById($id = null)
{
$this->myLogger->logme('error', 'getSingleBranchDataById function called');
if ($id) {
$branch_data = $this->clientBranchModel->where(['id' => $id, 'is_active' => 1])->first();
$branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->findAll();
return $this->respond(['status' => true, 'code' => 200, 'data' => $branch_data, 'contact' => $branch_contact_data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function getClientPolicyById($id = null)
{
$this->myLogger->logme('error', 'getClientPolicyById function called');
if ($id) {
$client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first();
$insurer_id = $client_policy_data['insurer_id'];
$client_id = $client_policy_data['client_id'];
$insurer_branch_id = $client_policy_data['insurer_branch_id'];
if (!empty($client_policy_data['policy_start_date'])) {
$client_policy_data['source_policy_start_date'] = change_date_format($client_policy_data['policy_start_date'], 'Y-m-d', 'd/m/Y');
} else {
$client_policy_data['source_policy_start_date'] = null;
}
if (!empty($client_policy_data['policy_end_date'])) {
$client_policy_data['source_policy_end_date'] = change_date_format($client_policy_data['policy_end_date'], 'Y-m-d', 'd/m/Y');
} else {
$client_policy_data['source_policy_end_date'] = null;
}
$polices = $this->policesModel
->select('policies.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])
->findAll();
$client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
// $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->where('is_active', 1)->findAll();
$cd_data = $this->get_cd_ac($client_id, $insurer_id, $insurer_branch_id, "internal");
// $client_policy_data['policy_end_date'] = date('d/m/Y', strtotime($client_policy_data['policy_end_date']));
$fromDate = new \DateTime($client_policy_data['policy_end_date']);
$fromDate->modify('+1 year');
$newDate = $fromDate->format('d/m/Y');
// print_rr($client_policy_data['policy_end_date']);die();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $client_policy_data,
'cd_data' => $cd_data,
"insurer_id" => $client_policy_data['insurer_id'],
'policy' => $polices,
'client_policy_list' => $client_policy_list,
'end_date' => $newDate,
'new_start_date' => date('d/m/Y', strtotime($client_policy_data['policy_end_date'] . ' +1 day')),
], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function getpolicyGridData()
{
$client_policy_id = $this->request->getGet('client_policy_id');
$terms_si_amount_array = $this->getPolicyTerms($client_policy_id);
$record = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.id', $client_policy_id)
->first();
$family_floater = '';
if (isset(json_decode($record['policy_terms'])->family_floater)) {
$family_floater = json_decode($record['policy_terms'])->family_floater;
}
$policy_terms_data = json_decode($record['policy_terms']);
$self = "";
if ($policy_terms_data !== null && isset($policy_terms_data->family_floaters)) {
$self = $policy_terms_data->family_floaters;
}
$branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']);
$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();
$gmc_pattern = '/gmc/i';
$gpa_pattern = '/gpa/i';
$subject = $record['policy_type'];
$policy_type_id = $record['policy_type_id'];
if (preg_match($gmc_pattern, $subject)) {
$search_term = 'GMC';
} else if (preg_match($gpa_pattern, $subject) || $policy_type_id == 6 || $policy_type_id == 7) {
$search_term = 'GPA';
} else if($policy_type_id == 72){
$search_term = 'GMC';
}else {
$search_term = "";
}
$results = $this->policyGridModel->like('policy_type', $search_term)->findAll();
$jsonArray = [];
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' || $policy_type_id == 72) {
$premiumData = $this->policyPremium2Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->findAll();
$rackRateJson = $this->policyPremium2Model
->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->groupBy('rack_rate_name')
->orderBy('id')
->findAll();
foreach ($rackRateJson as $value) {
$jsonArray[$value['rack_rate_name']] = json_decode($value['additional_relationship']);
}
} else {
$premiumData = "";
}
// echo '<pre>';
// print_r($premiumData); die;
// echo $record['client_id'];
// echo "-----";
// echo $client_policy_id;
// print_r($premiumData);die;
// echo '<pre>';
// echo $family_floater;
if ($search_term === 'GMC' || $policy_type_id == 72 ) {
// $resultss = [];
$resultss = $results;
// try {
// foreach ($results as $index => $record) {
// // if ($self->self == 1 && $self->spouse == 0 && $self->childrens == 0 && $self->parents == 0 && $self->{'parents-in-law'} == 0 && $self->{'either-parents-pil'} == 0 && $family_floater == 0) {
// if ($family_floater == 1) {
// if ($index == '7' || $index == '8' || $index == '9' || $index == '10') {
// $resultss[$index] = $record;
// }
// } else {
// if ($index == '0' || $index == '1' || $index == '2' || $index == '3' || $index == '4' || $index == '5' || $index == '6') {
// $resultss[$index] = $record;
// }
// }
// }
// } catch (\Exception $e) {
// $resultss = $results; // Reset $resultss to an empty array if an exception occurs
// }
$premiumDataa = '';
if ($family_floater == 0) {
// print_r($premiumData);die;
if (count($premiumData) == 0) {
$premiumDataa = $premiumData;
} else if ($premiumData[0]['policy_grid_id'] == '3' || $premiumData[0]['policy_grid_id'] == '4' || $premiumData[0]['policy_grid_id'] == '5' || $premiumData[0]['policy_grid_id'] == '6' || $premiumData[0]['policy_grid_id'] == '7' || $premiumData[0]['policy_grid_id'] == '8' || $premiumData[0]['policy_grid_id'] == '9') {
$premiumDataa = $premiumData;
}
} else if ($family_floater == 1) {
if (count($premiumData) == 0) {
$premiumDataa = $premiumData;
} else if ($premiumData[0]['policy_grid_id'] == '10' || $premiumData[0]['policy_grid_id'] == '11') {
$premiumDataa = $premiumData;
}
} else {
$premiumDataa = $premiumData;
}
if ($premiumDataa == "") {
$premiumDataa = $premiumData;
}
// $premium1 = [];
// $premium2 = [];
// foreach ($premiumDataa as $key => $item) {
// if ($item['rack_rate_type'] == 0) {
// $premium1[] = $item;
// } elseif ($item['rack_rate_type'] == 1) {
// $premium2[] = $item;
// }
// }
// print_r($premium1);
// print_r($premium2); die;
return $this->respond([
'status' => true,
'code' => 200,
'data' => $resultss,
'premiumData' => json_encode($premiumDataa),
'count' => $emp_count,
'family_floater' => $family_floater,
'self' => $self,
'client_policy_id' => $client_policy_id,
'terms_si_amount_array' => $terms_si_amount_array,
'branch_units' => $branch_units,
'jsonArray' => $jsonArray,
], 200);
} 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,
'family_floater' => $family_floater,
'self' => $self,
'client_policy_id' => $client_policy_id,
'terms_si_amount_array' => $terms_si_amount_array,
'branch_units' => $branch_units,
'jsonArray' => $jsonArray,
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 200,
'data' => $results,
'premiumData' => json_encode($premiumData),
'count' => $emp_count,
'family_floater' => $family_floater,
'self' => $self,
'client_policy_id' => $client_policy_id,
'terms_si_amount_array' => $terms_si_amount_array,
'branch_units' => $branch_units,
'jsonArray' => $jsonArray,
], 200);
}
}
public function policyGMCTerms()
{
try {
// echo "<pre>";
// print_r($this->request->getPost());die;
$this->myLogger->logme('error', "post data : " . json_encode($this->request->getPost() ?? []));
$this->myLogger->logme('error', 'Terms CREATE function called');
/*** Client Policy Table Primary Key(ID) ***/
$client_policy_id = $this->request->getPost("client_policy_id");
$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['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;
$data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age") ? $this->request->getPost("self_max_age") : 0;
$data['age_ratio']['spouse']['min'] = $this->request->getPost("spouse_min_age") ? $this->request->getPost("spouse_min_age") : 0;
$data['age_ratio']['spouse']['max'] = $this->request->getPost("spouse_max_age") ? $this->request->getPost("spouse_max_age") : 0;
$data['age_ratio']['child']['min'] = $this->request->getPost("child_min_age") ? $this->request->getPost("child_min_age") : 0;
$data['age_ratio']['child']['max'] = $this->request->getPost("child_max_age") ? $this->request->getPost("child_max_age") : 0;
$data['age_ratio']['elders']['min'] = $this->request->getPost("other_member_min_age") ? $this->request->getPost("other_member_min_age") : 0;
$data['age_ratio']['elders']['max'] = $this->request->getPost("other_member_max_age") ? $this->request->getPost("other_member_max_age") : 0;
$data['is_payable_employee']['self'] = $this->request->getPost("is_payable_employee_for_self") ? 1 : 0;
$data['is_payable_employee']['spouse'] = $this->request->getPost("is_payable_employee_for_spouse") ? 1 : 0;
$data['is_payable_employee']['childern'] = $this->request->getPost("is_payable_employee_for_child") ? 1 : 0;
$data['is_payable_employee']['elders'] = $this->request->getPost("is_payable_employee_for_elders") ? 1 : 0;
$temp_family_floaters = $data['family_floaters'];
$data['family_floaters'] = [];
if (in_array("self", $temp_family_floaters) == 1) {
$data['family_floaters']['self'] = 1;
} else {
$data['family_floaters']['self'] = 0;
}
if (in_array("spouse", $temp_family_floaters) == 1) {
$data['family_floaters']['spouse'] = 1;
} else {
$data['family_floaters']['spouse'] = 0;
}
if (count($temp_family_floaters)) {
$children_value = 0;
$value = 0;
if (count($temp_family_floaters) == 2) {
$children_value = 0;
$value = 1;
} else if (count($temp_family_floaters) == 3) {
$children_value = 1;
$value = 2;
} else {
$children_value = 2;
$value = 3;
}
$data['family_floaters']['childrens'] = (int)$temp_family_floaters[$children_value];
if ($temp_family_floaters[$value] == '1P') {
$data['family_floaters']['parents'] = 1;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2P') {
$data['family_floaters']['parents'] = 2;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '1PIL') {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 1;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2PIL') {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 2;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2EPORPIL') {
//Parents or PIL (Any two of Father, Mother, MIl, FIL)
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 2;
} else if ($temp_family_floaters[$value] == 'EPORPIL') {
//Either Parents or PIL (Parents or Parents In Law)
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 1;
} else if ($temp_family_floaters[$value] == '4EPORPIL') {
$data['family_floaters']['parents'] = 2;
$data['family_floaters']['parents-in-law'] = 2;
$data['family_floaters']['either-parents-pil'] = 0;
} else {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
}
}
$data['family_floaters']['elders_count'] = $this->request->getPost("elder_member_count") ? $this->request->getPost("elder_member_count") : 0;
// print_r($data);die;
// $data['waiverofpreexistingdiseases'] = $this->request->getPost("waiverofpreexistingdiseases");
// $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
// $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
// $data['waiver_of_90_days_waiting_period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
// $data['waiver_of_other_waiting_periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
// $data['maternity_benefit'] = $this->request->getPost("maternity_benefit");
// $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
// $data['maternitycoverage'] = str_replace(',', '', $this->request->getPost("maternitycoverage"));
// $data['twindelivery'] = str_replace(',', '', $this->request->getPost("twindelivery"));
// $data['well_baby_well_mother_expenses'] = str_replace(',', '', $this->request->getPost("well_baby_well_mother_expenses"));
// $data['preandpostnatal'] = str_replace(',', '', $this->request->getPost("preandpostnatal"));
// $data['infertility_treatment_coverage'] = str_replace(',', '', $this->request->getPost("infertility_treatment_coverage"));
// $data['babyday1cover'] = str_replace(',', '', $this->request->getPost("babyday1cover"));
// $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
// $data['mid_term_addition_of_new_born_newly_wedded_spouse'] = str_replace(',', '', $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse"));
// $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
// $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
// $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
// $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
// $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
// $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
// $data['icu_limit'] = str_replace(',', '', $this->request->getPost("icu_limit"));
// $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
// $data['ailmentcapping'] = $this->request->getPost("ailmentcapping");
// $data['ailment_capping_details'] = str_replace(',', '', $this->request->getPost("ailment_capping_details"));
// $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
// $data['non_admissible_contingency_corporate_buffer'] = str_replace(',', '', $this->request->getPost("non_admissible_contingency_corporate_buffer"));
// $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
// $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
// $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
// $data['daycaretreatment'] = str_replace(',', '', $this->request->getPost("daycaretreatment"));
// $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
// $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
// $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
// $data['opd_treatment'] = str_replace(',', '', $this->request->getPost("opd_treatment"));
// $data['days_of_discharge'] = str_replace(',', '', $this->request->getPost("days_of_discharge"));
// $data['days_from_dod'] = str_replace(',', '', $this->request->getPost("days_from_dod"));
// $data['terrorism'] = str_replace(',', '', $this->request->getPost("terrorism"));
// $data['widower_cover'] = str_replace(',', '', $this->request->getPost("widower_cover"));
// $data['breavement_cover'] = str_replace(',', '', $this->request->getPost("breavement_cover"));
// $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
// $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
// $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
// $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
$fields = [
'waiverofpreexistingdiseases' => false,
'waiverof1,2,3&4thyearexclusions' => false,
'waiverof30dayswaitingperiod' => false,
'waiver_of_90_days_waiting_period' => false,
'waiver_of_other_waiting_periods' => false,
'maternity_benefit' => false,
'9monthwaitingperiodwaived' => true,
'maternitycoverage' => true,
'twindelivery' => true,
'well_baby_well_mother_expenses' => true,
'preandpostnatal' => true,
'infertility_treatment_coverage' => true,
'babyday1cover' => true,
'coverfromthedateofjoining' => true,
'mid_term_addition_of_new_born_newly_wedded_spouse' => true,
'prehospitalizationcover' => true,
'posthospitalizationcover' => false,
'congenitaldiseasesinternal' => true,
'congenitaldiseasesexternal' => true,
'copayzonewisecopay' => false,
'roomrentlimit' => true,
'icu_limit' => true,
'proportionatedeductionclause' => true,
'ailmentcapping' => false,
'ailment_capping_details' => true,
'corporatebuffer' => true,
'non_admissible_contingency_corporate_buffer' => true,
'ambulancecharges' => true,
'airambulance' => true,
'reasonableandcustomarycharges' => true,
'daycaretreatment' => true,
'lasiksurgery' => true,
'ayudhtreatmentcover' => true,
'moderntreatmentsasperirdai' => true,
'opd_treatment' => true,
'days_of_discharge' => true,
'days_from_dod' => true,
'terrorism' => true,
'widower_cover' => true,
'breavement_cover' => true,
'suminsuredenhancement' => true,
'special_condition_label' => true,
'special_condition_input' => true,
'multiple_sum_insured' => true,
];
foreach ($fields as $field => $needsCleanup) {
$value = $this->request->getPost($field);
if ($value !== null && $value !== '') {
$data[$field] = $needsCleanup ? str_replace(',', '', $value) : $value;
} else {
$data[$field] = $value;
}
}
$data['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();
$this->myLogger->logme('error', "contructed post data : " . json_encode($data ?? []));
// print_r($data);die;
$jsonData = json_encode($data);
$dataa = array(
'policy_terms' => $jsonData,
);
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
// print_r($data);die;
if ($record) {
$update = $this->clientPolicyModel->update($client_policy_id, $dataa);
if ($update) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data updated successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update data'], 200);
}
} else {
$insert = $this->clientPolicyModel->insert($dataa);
if ($insert) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data stored successfully'], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data'], 200);
}
}
} catch (\Exception $e) {
echo "Failed to insert data: " . $e->getMessage();
// Log the error
log_message('error', 'Failed to insert data: ' . $e->getMessage());
}
}
public function enrollmentGMCDisplayValueTransform()
{
$data = [];
// Mapping of POST keys to display labels
$fields = [
'waiverofpreexistingdiseases' => 'Waiver of Pre-existing Diseases',
'waiverof1,2,3&4thyearexclusions' => 'Waiver of 1, 2, 3 & 4th year Exclusions',
'waiverof30dayswaitingperiod' => 'Waiver of 30 days waiting period',
'suminsuredenhancement' => 'Sum Insured Enhancement',
'waiver_of_90_days_waiting_period' => 'Waiver of 90 Days Waiting Period',
'waiver_of_other_waiting_periods' => 'Waiver of Other Waiting Periods',
'maternity_benefit' => 'Maternity Benefit',
'9monthwaitingperiodwaived' => '9-month waiting Period - waived',
'maternitycoverage' => 'Maternity Coverage',
'twindelivery' => 'Twin Delivery',
'well_baby_well_mother_expenses' => 'Well baby / Well Mother Expenses',
'preandpostnatal' => 'Pre and Post natal',
'infertility_treatment_coverage' => 'Infertility Treatment Coverage',
'babyday1cover' => 'Baby Day 1 Cover',
'coverfromthedateofjoining' => 'Cover from the date of Joining',
'mid_term_addition_of_new_born_newly_wedded_spouse' => 'Mid Term Addition of New Born / Newly Wedded Spouse',
'prehospitalizationcover' => 'Pre Hospitalization Cover',
'posthospitalizationcover' => 'Post Hospitalization Cover',
'congenitaldiseasesinternal' => 'Congenital Diseases - Internal',
'congenitaldiseasesexternal' => 'Congenital Diseases - External',
'copayzonewisecopay' => 'Co-Pay/Zone wise Co Pay',
'roomrentlimit' => 'Room Rent Limit',
'icu_limit' => 'ICU Limit',
'proportionatedeductionclause' => 'Proportionate Deduction Clause',
'ailmentcapping' => 'Ailment capping',
'ailment_capping_details' => 'Ailment capping Details',
'corporatebuffer' => 'Corporate Buffer',
'non_admissible_contingency_corporate_buffer' => 'Non-Admissible / Contingency Corporate Buffer',
'ambulancecharges' => 'Ambulance Charges',
'airambulance' => 'Air Ambulance',
'reasonableandcustomarycharges' => 'Reasonable and Customary Charges',
'daycaretreatment' => 'Day Care Treatment',
'lasiksurgery' => 'Lasik Surgery',
'ayudhtreatmentcover' => 'AYUSH treatment cover',
'moderntreatmentsasperirdai' => 'Modern treatments as per IRDAI',
'opd_treatment' => 'OPD Treatment',
'days_of_discharge' => 'Claim Intimation Clause',
'days_from_dod' => 'Claim Submission',
'terrorism' => 'Terrorism',
'widower_cover' => 'Widower Cover',
'breavement_cover' => 'Breavement Cover'
];
foreach ($fields as $postKey => $label) {
$displayKey = $postKey . '_display';
$value = $this->request->getPost($postKey);
if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
$data[$label] = $value;
}
}
// Handle special conditions
if ($this->request->getPost("special_condition_display_value")) {
$specialConditionKeyValue = json_decode($this->request->getPost("special_condition_display_value"), true);
if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
$mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
// Only add non-empty values
foreach ($mergedArray as $k => $v) {
if ($v !== null && $v !== '') {
$data[$k] = $v;
}
}
}
}
return $data;
}
public function getterms()
{
$client_policy_id = $this->request->getVar('client_policy_id');
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
// $emp_count = $this->employeeModel ->join('client_policy cp',"employees.client_id = cp.client_id")
// ->join('employee_polices ep',"cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
// ->where("employees.client_id", $record['client_id'])
// ->where("employees.emp_status",'active')
// ->countAllResults();
$emp_count_by_policy = $this->employeePolicyModel
->where('client_policy_id', $client_policy_id)
->where("status", 'active')
->where('is_active', 1)
->countAllResults();
if ($record) {
return $this->respond(
[
'Status' => true,
'code' => 200,
'policy_type_id' => $record['policy_type_id'],
'data' => $record['policy_terms'],
'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.'], 200);
}
}
public function policyGPATerms()
{
try {
$this->myLogger->logme('error', 'Policy GPA Terms CREATE function called');
// print_r($this->request->getPost()); die;
/*** Client Policy Table Primary Key(ID) ***/
$client_policy_id = $this->request->getPost("client_policy_id");
$data['sumInsured2'] = str_replace(',', '', $this->request->getPost("sumInsured2"));
$data['totalSumInsured'] = str_replace(',', '', $this->request->getPost("totalSumInsured"));
$data['age_ratio']['self']['min'] = $this->request->getPost("self_min_age");
$data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age");
$data['is_payable_employee']['self'] = 0;
// $data['accidentalDeathBenefit'] = str_replace(',', '', $this->request->getPost("accidentalDeathBenefit"));
// $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement"));
// $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement");
// $data['temporaryTotalDisablementBenefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
// $data['medical_expenses_medical_extension'] = str_replace(',', '', $this->request->getPost("medical_expenses_medical_extension"));
// $data['opd_treatment_cover'] = str_replace(',', '', $this->request->getPost("opd_treatment_cover"));
// $data['ambulanceCharges'] = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
// $data['repatriation_of_mortal_remains'] = str_replace(',', '', $this->request->getPost("repatriation_of_mortal_remains"));
// $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
// $data['terrorism'] = $this->request->getPost("terrorism");
// $data['worldwideCover'] = $this->request->getPost("worldwideCover");
// $data['family_transportation_benefits'] = $this->request->getPost("family_transportation_benefits");
// $data['fractures_dislocation_burns'] = $this->request->getPost("fractures_dislocation_burns");
// $data['coma'] = $this->request->getPost("coma");
// $data['carriageOfDeadBody'] = $this->request->getPost("carriageOfDeadBody");
// $data['compassionateVisitExpenses'] = $this->request->getPost("compassionateVisitExpenses");
// $data['travel_expenses_for_medical_treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
// $data['daily_cash_allowance'] = $this->request->getPost("daily_cash_allowance");
// $data['artifical_limb_and_prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
// $data['animalSnakeInsectBite'] = $this->request->getPost("animalSnakeInsectBite");
// $data['air_ambulance'] = $this->request->getPost("air_ambulance");
// $data['gpa_special_condition_label'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_label")) ?? [];
// $data['gpa_special_condition_input'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_input")) ?? [];
// $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];
$fieldsWithCommaRemoval = [
'accidentalDeathBenefit',
'permanentTotalDisablement',
'medical_expenses_medical_extension',
'opd_treatment_cover',
'ambulanceCharges',
'repatriation_of_mortal_remains',
'childrenEducationWelfareFund',
'gpa_special_condition_label',
'gpa_special_condition_input',
'multiple_sum_insured',
];
$fieldsWithoutCommaRemoval = [
'permanentPartialDisablement',
'temporaryTotalDisablementBenefit',
'terrorism',
'worldwideCover',
'family_transportation_benefits',
'fractures_dislocation_burns',
'coma',
'carriageOfDeadBody',
'compassionateVisitExpenses',
'travel_expenses_for_medical_treatment',
'daily_cash_allowance',
'artifical_limb_and_prosthesis',
'animalSnakeInsectBite',
'air_ambulance'
];
// Remove commas and assign if present
foreach ($fieldsWithCommaRemoval as $field) {
$value = $this->request->getPost($field);
if ($value !== null) {
$data[$field] = str_replace(',', '', $value);
} else {
$data[$field] = $value;
}
}
// Direct assign if present
foreach ($fieldsWithoutCommaRemoval as $field) {
$value = $this->request->getPost($field);
if ($value !== null) {
$data[$field] = $value;
} else {
$data[$field] = $value;
}
}
$data['enrollment_display_key'] = $this->enrollmentGPADisplayValueTransform();
// print_r($data); die;
$jsonData = json_encode($data);
$dataa = array(
'policy_terms' => $jsonData,
);
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
if ($record) {
$update = $this->clientPolicyModel->update($client_policy_id, $dataa);
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'], 200);
}
} else {
$insert = $this->clientPolicyModel->insert($dataa);
if ($insert) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data stored successfully', 'client_policy_id' => $client_policy_id], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data'], 200);
}
}
} catch (\Exception $e) {
echo "Failed to insert data: " . $e->getMessage();
log_message('error', 'Failed to insert data: ' . $e->getMessage());
}
}
public function enrollmentGPADisplayValueTransform()
{
$data = [];
// Map POST keys to display labels
$fields = [
'accidentalDeathBenefit' => 'Accidental Death Benefit',
'permanentTotalDisablement' => 'Permanent Total Disablement',
'permanentPartialDisablement' => 'Permanent Partial Disablement',
'temporaryTotalDisablementBenefit' => 'Temporary Total Disablement Benefit',
'medical_expenses_medical_extension' => 'Medical Expenses / Medical Extension (IPD)',
'opd_treatment_cover' => 'OPD Treatment Cover',
'ambulanceCharges' => 'Ambulance Charges',
'repatriation_of_mortal_remains' => 'Repatriation of Mortal Remains',
'childrenEducationWelfareFund' => 'Children Education Welfare Fund',
'terrorism' => 'Terrorism',
'worldwideCover' => 'Worldwide Cover',
'family_transportation_benefits' => 'Family Transportation Benefits',
'fractures_dislocation_burns' => 'Fractures / Dislocation / Burns',
'coma' => 'Coma',
'carriageOfDeadBody' => 'Carriage of Dead Body',
'compassionateVisitExpenses' => 'Compassionate Visit Expenses',
'travel_expenses_for_medical_treatment' => 'Travel expenses for Medical Treatment',
'daily_cash_allowance' => 'Daily cash Allowance',
'artifical_limb_and_prosthesis' => 'Artifical Limb and Prosthesis',
'animalSnakeInsectBite' => 'Animal/Snake/Insect Bite',
'air_ambulance' => 'Air Ambulance'
];
foreach ($fields as $postKey => $label) {
$displayKey = $postKey . '_display';
$value = $this->request->getPost($postKey);
if ($this->request->getPost($displayKey) && $value !== null && $value !== '') {
$data[$label] = $value;
}
}
// Handle GPA special conditions
if ($this->request->getPost("gpa_special_condition_display_value")) {
$specialConditionKeyValue = json_decode($this->request->getPost("gpa_special_condition_display_value"), true);
if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
$mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
foreach ($mergedArray as $k => $v) {
if ($v !== null && $v !== '') {
$data[$k] = $v;
}
}
}
}
return $data;
}
public function getPolicyGPATerms()
{
$client_id = $this->request->getVar('client_id');
$policy_id = $this->request->getVar('policy_id');
$record = $this->clientPolicyModel->where(['client_id' => $client_id, 'policy_id' => $policy_id])->first();
if ($record) {
echo $record['policy_terms'];
} else {
echo "Record not found.";
}
}
public function updateClientPolicyStatus()
{
$client_policy_id = $this->request->getGet('client_policy_id');
$message = 'Policy updated Successfully';
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
if ($record['open_for_enrollment'] == 0) {
$open_for_enrollment_update_value = 1;
$message = 'Enrolment Opened Successfully';
} else if ($record['open_for_enrollment'] == 1) {
$open_for_enrollment_update_value = 0;
$message = 'Enrolment Closed Successfully';
}
$data = $this->policesModel->getPolicyPremium($client_policy_id);
$pattern = '/gmc/i';
$subject = $data[0]->policy_type;
if (preg_match($pattern, $subject)) {
$search_term = 'GMC';
} else {
$search_term = 'GPA';
}
if ($search_term === 'GPA') {
$racRate = $this->policyPremium1Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->countAllResults();
} else if ($search_term === 'GMC') {
$racRate = $this->policyPremium2Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->countAllResults();
}
$termsData = $this->clientPolicyModel->where(['id' => $client_policy_id, 'is_active' => 1])->first();
if (empty($termsData['policy_terms'])) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Please define policy terms '], 200);
}
$termsData = json_decode($termsData['policy_terms']);
if (isset($termsData->sum_insured) && $termsData->sum_insured == "" && $termsData->sum_insured == null) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty', 'data' => $record], 200);
}
if (isset($termsData->sumInsured2) && $termsData->sumInsured2 == "" && $termsData->sumInsured2 == null) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty'], 200);
}
// Check if 'family_floater' key exists and has a value
if (isset($termsData->family_floater) && $termsData->family_floater === null) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Family Floater field is empty', 'termsData' => $termsData, 'family_floater' => $termsData->family_floater], 200);
}
// Check if 'family_floaters' key exists and has a value
if (isset($termsData->family_floaters) && is_array($termsData->family_floaters) && count($termsData->family_floaters) <= 0) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Family Members field is empty'], 200);
$familyFloatersCount = count($termsData->family_floaters);
}
if ($racRate == 0) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Please define policy premium'], 200);
}
// $policy_status = $this->clientPolicyModel->where('id', $client_policy_id )->set('policy_status', 1)->update();
$json_data = '';
$open_for_enrollment = $this->clientPolicyModel->where('id', (int)$client_policy_id)->set('open_for_enrollment', $open_for_enrollment_update_value)->update();
if ($open_for_enrollment) {
$open_for_enrollment_1 = $this->clientPolicyModel->where('id', (int)$client_policy_id)->find();
$open_for_enrollment_value = $open_for_enrollment_1[0]['open_for_enrollment'];
$client_policy_id_value = $client_policy_id;
$json_data = json_encode(['open_for_enrollment' => $open_for_enrollment_value, 'client_policy_id' => $client_policy_id_value]);
}
return $this->respond(['status' => true, 'code' => 200, 'message' => $message, 'data' => $termsData, 'racRate' => $racRate, 'open_for_enrollment' => $json_data, 'client_policy_data' => $record], 200);
}
public function getClientPolicyList($client_id = null)
{
$record = $this->clientPolicyModel->getpolicyWithPattern($client_id);
if ($record) {
return $this->respond(['Status' => true, 'code' => 200, 'data' => $record], 200);
} else {
return $this->respond(['Status' => false, 'code' => 200, 'message' => 'Record not found.'], 200);
}
}
public function fetchPolicyDataForPolicyType($client_policy_id)
{
$client_policy_id = $this->request->getGet('client_policy_id');
$policy_type = $this->request->getGet('policy_type');
$client_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$insurer_id = $client_id['insurer_id'];
if ($policy_type == 2) {
$polices = $this->policesModel
->select('policies.*')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
->where('policy_type.policy_type', 'GMC - Top-up')
->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])->findAll();
} else if ($policy_type == 3) {
$polices = $this->policesModel
->select('policies.*')
->join('policy_type', 'policy_type.id = policies.policy_type_id')
->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)'])
->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])->findAll();
}
$data = $this->clientPolicyModel->getClientPolicyByPolicyType($client_id['client_id'], $policy_type);
return $this->respond(['Status' => true, 'code' => 200, 'data' => $data, 'client_policy_id' => $client_policy_id, 'policy' => $polices], 200);
}
public function downloadKYCDocument($file_name)
{
$file = WRITEPATH . 'uploads/client_kyc_documents/' . $file_name; // Example file path
if (file_exists($file)) {
return $this->response->download($file, null)->setFileName($file_name);
} else {
return "File not found.";
}
}
//for this function policy binding dropdown list use ( client policy )
public function getClientBranch($client_id)
{
$branchs = $this->clientBranchModel
->select('*')
->where('client_id', $client_id)
->where('is_active', 1)
->findAll();
return $this->respond(['status' => true, 'code' => 200, 'data' => $branchs], 200);
}
public function getClientAllDetailsByUsingClientID($client_id)
{
$db = \Config\Database::connect();
$builder = $db->table('clients');
$builder->select('
policy_type.policy_type,
insurers.name as insurer_name,
insurers.short_name as insurer_short_name,
tpa.name as tpa_name,
tpa.short_name as tpa_short_name,
client_policy.policy_terms,
DATE_FORMAT(client_policy.policy_start_date, "%d-%b-%Y") as policy_start_date,
DATE_FORMAT(client_policy.policy_end_date, "%d-%b-%Y") as policy_end_date,
CASE
WHEN client_policy.base_policy IS NULL THEN "Not Appear"
WHEN client_policy.base_policy = 0 THEN "Not Appear"
ELSE (SELECT policy_type.policy_type
FROM client_policy AS base_client_policy
JOIN policy_type ON policy_type.id = base_client_policy.policy_type_id
WHERE base_client_policy.id = client_policy.base_policy)
END as base_policy_name,
CASE
WHEN client_policy.is_addon = 1 THEN "Base Policy"
WHEN client_policy.is_addon = 2 THEN "SI Topup"
WHEN client_policy.is_addon = 3 THEN "Dependent Addon"
ELSE "n/a"
END as is_addon,
CASE
WHEN client_policy.policy_status = 1 THEN "Active"
WHEN client_policy.policy_status = 0 THEN "Expired"
ELSE "n/a"
END as policy_status,
CASE
WHEN client_policy.inception_type = 1 THEN "File Upload"
WHEN client_policy.inception_type = 2 THEN "Enrolment"
ELSE "n/a"
END as inception_type,
CASE
WHEN client_policy.open_for_enrollment = 1 THEN "Open"
WHEN client_policy.open_for_enrollment = 0 THEN "Closed"
ELSE "n/a"
END as open_for_enrollment,
client_branch.branch_name
', false);
$builder->join('client_policy', 'client_policy.client_id = clients.id');
$builder->join('client_branch', 'client_policy.client_branch_id = client_branch.id');
$builder->join('policy_type', 'policy_type.id = client_policy.policy_type_id');
$builder->join('insurers', 'insurers.id = client_policy.insurer_id');
$builder->join('tpa', 'tpa.id = client_policy.tpa_id');
$builder->where('clients.is_active', 1);
$builder->where('client_policy.is_active', 1);
$builder->where('policy_type.is_active', 1);
$builder->where('client_policy.policy_status', 1);
$builder->where('clients.id', $client_id);
$query = $builder->get();
$client_policy = $query->getResultArray();
$gmc_keys = [
"sum_insured" => "Sum Insured",
"family_floater" => "Family Floater",
"family_floaters" => "Family Floaters",
"elders_count" => "Elders Count:",
"other_member_min_age" => "Min Age:",
"other_member_max_age" => "Min Age:",
"waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases",
"9monthwaitingperiodwaived" => "9-month waiting Period waived",
"coverfromthedateofjoining" => "Cover from the date of Joining",
"waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions",
"waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period",
"prehospitalizationcover" => "Pre Hospitalization Cover",
"congenitaldiseasesinternal" => "Congenital Diseases - Internal",
"copayzonewisecopay" => "Co-Pay/Zone wise Co Pay",
"bioabsorbablestenttoriclensmultifocallens" => "Bio absorbable stent / Toric lens/ Multi Focal lens",
"roomrentlimit" => "Room Rent Limit",
"proportionatedeductionclause" => "Proportionate Deduction Clause",
"nursingallowance" => "Nursing Allowance",
"ailmentcapping" => "Ailment capping",
"ambulancecharges" => "Ambulance Charges",
"airambulance" => "Air Ambulance",
"familytransportationbenefit" => "Family Transportation Benefit",
"reasonableandcustomarycharges" => "Reasonable and Customary Charges",
"daycaretreatment" => "Day Care Treatment",
"ayudhtreatmentcover" => "AYUSH treatment cover",
"armdcovered" => "ARMD Covered",
"suminsuredenhancement" => "Sum Insured enhancement",
"automaticsuminsuredreinstatement" => "Automatic Sum Insured reinstatement",
"additionalsicknessbenefit" => "Additional Sickness Benefit",
"lasiksurgery" => "Lasik Surgery",
"midterminclusion" => "Mid Term inclusion",
"capd" => "CAPD",
"organdonorexpenses" => "Organ donor expenses",
"moderntreatmentsasperirdai" => "Modern treatments as per IRDAI",
"Wellness" => "Wellness",
"days_of_discharge" => "Claim Intimation Clause",
"days_from_dod" => "Claim Submission",
"cataract" => "Cataract"
];
$gpa_keys = [
"sumInsured2" => "Sum Insured",
"totalSumInsured" => "Total Sum Assured",
"self" => "Self",
"self_min_age" => "Min Age",
"self_max_age" => "Max Age",
"accidentalDeathBenefit" => "Accidental Death Benefit",
"permanentTotalDisablement" => "Permanent Total Disablement",
"permanentPartialDisablement" => "Permanent Partial Disablement",
"temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit",
"accidentalHospitalizationExpenses" => "Accidental Hospitalization Expenses",
"childrenEducationWelfareFund" => "Children Education Welfare Fund",
"compassionateVisitExpenses" => "Compassionate Visit Expenses",
"compassionateVisitExpensesData" => "Compassionate Visit Expenses Data",
"brokenBoneExpenses" => "Broken Bone Expenses",
"brokenBoneExpensesData" => "Broken Bone Expenses Data",
"ambulanceCharges" => "Ambulance charges",
"ambulanceChargesData" => "Ambulance charges Data",
"burnExpenses" => "Burn Expenses",
"burnExpensesData" => "Burn Expenses Data",
"carriageOfDeadBody" => "Carriage of Dead Body",
"carriageOfDeadBodyData" => "Carriage of Dead Body Data",
"animalSnakeInsectBite" => "Animal/Snake/Insect bite",
"terrorism" => "Terrorism",
"worldwideCover" => "Worldwide Cover"
];
foreach ($client_policy as $key => $value) {
$policy_terms = json_decode($value['policy_terms'], true);
$mapping = $gmc_keys;
if ($value['policy_type'] == 'GPA') {
$mapping = $gpa_keys;
}
$client_policy[$key]['policy_terms'] = $this->transformArray($policy_terms, $mapping);
}
$data['client_policy'] = $client_policy;
$data['client_branch'] = $this->clientModel
->select('
client_branch.branch_name,
client_branch.branch_code,
client_branch.city,
level_contacts.name as hr_name,
level_contacts.designation,
level_contacts.mobile,
level_contacts.email
')
->join('client_branch', 'client_branch.client_id = clients.id')
->join('level_contacts', 'level_contacts.ref_id = client_branch.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('clients.id', $client_id)
->get()->getResultArray();
$data['client'] = $this->clientModel->where('clients.id', $client_id)->first();
$client_rm = $this->clientRMModel
->select('client_rm.*, user_profiles.first_name as user_name')
->join('user_profiles', 'user_profiles.id = client_rm.user_id')
->where('client_id', $client_id)->get()->getResultArray();
$account_managers = [];
$managers = [];
$heads = [];
foreach ($client_rm as $key => $value) {
if ($value['level'] == 3) {
$account_managers[] = $value['user_name'];
} elseif ($value['level'] == 2) {
$managers[] = $value['user_name'];
} elseif ($value['level'] == 1) {
$heads[] = $value['user_name'];
}
}
$data['account_managers'] = $account_managers;
$data['managers'] = $managers;
$data['heads'] = $heads;
// dd($data);
// $this->loadLayout('client_info', $data);
$html = view('client_info', $data);
return $this->respond(['status' => true, 'code' => 200, 'data' => $html], 200);
}
public function transformArray($data, $mapping)
{
// dd($data);
$transformedData = [];
if (!is_array($data)) {
return json_encode($transformedData, JSON_PRETTY_PRINT);
}
foreach ($data as $key => $value) {
if ($key == 'family_floaters') {
$transformedData[$key] = $this->transformFamilyFloaters($value, $data);
} else if (array_key_exists($key, $mapping)) {
$transformedData[$mapping[$key]] = $value;
} else if ($key == 'special_condition_label') {
if (is_array($value)) {
foreach ($value as $key => $value) {
$transformedData[$value] = $data['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 {
$transformedData[$key] = $value;
}
}
return json_encode($transformedData, JSON_PRETTY_PRINT);
}
public function transformFamilyFloaters($familyFloaters, $json)
{
$result = [];
$min = $json['age_ratio']['self'];
$max = $json['age_ratio']['self'];
$spouse_min = $json['age_ratio']['spouse'];
$spouse_max = $json['age_ratio']['spouse'];
$child_min = $json['age_ratio']['child'];
$child_max = $json['age_ratio']['child'];
$elders_min = $json['age_ratio']['elders'];
$elders_max = $json['age_ratio']['elders'];
foreach ($familyFloaters as $key => $value) {
if ($value !== 0) {
switch ($key) {
case 'self':
$result[] = "Self (Min: {$min['min']}, Max: {$max['max']})";
break;
case 'spouse':
$result[] = "Spouse (Min: {$spouse_min['min']}, Max: {$spouse_max['max']})";
break;
case 'childrens':
$result[] = "Children(s) - $value (Min: {$child_min['min']}, Max: {$child_max['max']})";
break;
case 'parents':
$result[] = "Parent(s) - $value (Min: {$elders_min['min']}, Max: {$elders_max['max']})";
break;
case 'parents-in-law':
$result[] = "Parents-in-Law - $value (Min: {$elders_min['min']}, Max: {$elders_max['max']})";
break;
case 'either-parents-pil':
$result[] = "Either Parents Nor Parents-in-Law - $value (elders_min: {$elders_min['min']}, Max: {$elders_max['max']})";
break;
}
}
}
return implode(", ", $result);
}
public function deleteAdditionalRackRate($client_id, $client_policy_id, $rack_rate_type)
{
try {
$result = $this->policyPremium2Model
->where('client_id', $client_id)
->where('client_policy_id', $client_policy_id)
->where('rack_rate_type', $rack_rate_type)
->set('is_active', 0)
->update();
if (!$result) {
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Failed to update the record.'], 200);
}
} catch (\Exception $e) {
log_message('error', $e->getMessage());
return $this->respond(['status' => false, 'code' => 200, 'message' => 'Failed to update the record.'], 200);
}
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Additionaly Rack Rate Data Remove Successfully'], 200);
}
public function get_cd_ac($client_id, $insurer_id, $insurer_branch_id, $return_type = null)
{
// Get client data
$client_data = $this->clientModel
->where('is_active', 1)
->where('id', $client_id)
->first();
$cd_data = [];
// If client has a parent, fetch parent client CD data
if (!empty($client_data['parent_client_id'])) {
$parent_cd_data = $this->CDMasterModel
->where('client_id', $client_data['parent_client_id'])
->where('insurer_id', $insurer_id)
->where('insurer_branch_id', $insurer_branch_id)
->where('is_active', 1)
->findAll();
$cd_data = array_merge($cd_data, $parent_cd_data);
}
// Fetch current client CD data
$client_cd_data = $this->CDMasterModel
->where('client_id', $client_id)
->where('insurer_id', $insurer_id)
->where('insurer_branch_id', $insurer_branch_id)
->where('is_active', 1)
->findAll();
$cd_data = array_merge($cd_data, $client_cd_data);
if ($return_type == "internal") {
if (!empty($cd_data)) {
return $cd_data;
} else {
return [];
}
}
if (!empty($cd_data)) {
return $this->respond([
'status' => true,
'code' => 200,
'data' => $cd_data
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 404,
'client_id' => $client_id,
'insurer_id' => $insurer_id,
'insurer_branch_id' => $insurer_branch_id
], 200);
}
}
public function otherPolicyTermsFormSubmit()
{
$client_policy_id = $this->request->getPost("client_policy_id");
$policy_terms = $this->request->getPost("policy_terms");
$policy_terms = json_decode($policy_terms, true);
$record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
// print_r($policy_terms); die;
if (empty($policy_terms)) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Policy terms data could not be empty', 'formdata' => $this->request->getPost()], 200);
}
if ($record) {
$data = [];
if ($record['policy_type_id'] == 72) {
$data['sum_insured'] = $policy_terms['sum_insured'] ?? 0;
$data['multiple_sum_insured'] = $policy_terms['multiple_sum_insured'] ?? [];
$data['family_floater'] = $policy_terms['family_floater'] ?? 0;
$data['family_floaters'] = $policy_terms["family_floaters"] ?? [];
$data['age_ratio']['self']['min'] = $policy_terms["self_min_age"] ?? 0;
$data['age_ratio']['self']['max'] = $policy_terms["self_max_age"] ?? 0;
$data['age_ratio']['spouse']['min'] = $policy_terms["spouse_min_age"] ?? 0;
$data['age_ratio']['spouse']['max'] = $policy_terms["spouse_max_age"] ?? 0;
$data['age_ratio']['child']['min'] = $policy_terms["child_min_age"] ?? 0;
$data['age_ratio']['child']['max'] = $policy_terms["child_max_age"] ?? 0;
$data['age_ratio']['elders']['min'] = $policy_terms["other_member_min_age"] ?? 0;
$data['age_ratio']['elders']['max'] = $policy_terms["other_member_max_age"] ?? 0;
$temp_family_floaters = $data['family_floaters'];
$data['family_floaters'] = [];
if (in_array("self", $temp_family_floaters) == 1) {
$data['family_floaters']['self'] = 1;
} else {
$data['family_floaters']['self'] = 0;
}
if (in_array("spouse", $temp_family_floaters) == 1) {
$data['family_floaters']['spouse'] = 1;
} else {
$data['family_floaters']['spouse'] = 0;
}
if (count($temp_family_floaters)) {
$children_value = 0;
$value = 0;
if (count($temp_family_floaters) == 2) {
$children_value = 0;
$value = 1;
} else if (count($temp_family_floaters) == 3) {
$children_value = 1;
$value = 2;
} else {
$children_value = 2;
$value = 3;
}
$data['family_floaters']['childrens'] = (int)$temp_family_floaters[$children_value];
if ($temp_family_floaters[$value] == '1P') {
$data['family_floaters']['parents'] = 1;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2P') {
$data['family_floaters']['parents'] = 2;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '1PIL') {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 1;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2PIL') {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 2;
$data['family_floaters']['either-parents-pil'] = 0;
} else if ($temp_family_floaters[$value] == '2EPORPIL') {
//Parents or PIL (Any two of Father, Mother, MIl, FIL)
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 2;
} else if ($temp_family_floaters[$value] == 'EPORPIL') {
//Either Parents or PIL (Parents or Parents In Law)
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 1;
} else if ($temp_family_floaters[$value] == '4EPORPIL') {
$data['family_floaters']['parents'] = 2;
$data['family_floaters']['parents-in-law'] = 2;
$data['family_floaters']['either-parents-pil'] = 0;
} else {
$data['family_floaters']['parents'] = 0;
$data['family_floaters']['parents-in-law'] = 0;
$data['family_floaters']['either-parents-pil'] = 0;
}
}
$data['family_floaters']['elders_count'] = $this->request->getPost("elder_member_count") ? $this->request->getPost("elder_member_count") : 0;
$data['special_condition_label'] = $policy_terms['special_condition_label'] ?? [];
$data['special_condition_input'] = $policy_terms["special_condition_input"] ?? [];
$data['enrollment_display_key'] = $this->otherPolicyTermsDisplayKeyConstruct($policy_terms);
} else {
foreach ($policy_terms as $key => $value) {
if (str_ends_with($key, '_display')) {
$original_key = substr($key, 0, -8);
$newKey = implode(' ', array_map('ucfirst', explode('_', $original_key)));
$data['enrollment_display_key'][$newKey] = $policy_terms[$original_key] ?? " ";
} else {
$data[$key] = $value;
}
}
}
if (!empty($data)) {
if ($record['policy_type_id'] == 72) {
$policy_terms['is_payable_employee']['self'] = 0;
$policy_terms['is_payable_employee']['spouse'] = 0;
$policy_terms['is_payable_employee']['childern'] = 0;
$policy_terms['is_payable_employee']['elders'] = 0;
} else {
$policy_terms['is_payable_employee']['self'] = 0;
}
$policy_terms = json_encode($data);
$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 policy therms.', '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 otherPolicyTermsDisplayKeyConstruct($data)
{
$labels = $data['special_condition_label'] ?? [];
$values = $data['special_condition_input'] ?? [];
$special_conditions = [];
foreach ($labels as $i => $label) {
$value = $values[$i] ?? '';
// skip if label or value is empty
if (trim($label) === '' || trim($value) === '') {
continue;
}
$special_conditions[$label] = $value;
}
return $special_conditions;
}
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);
return [];
}
if (is_array($policy_terms)) {
if (!isset($policy_terms['policy_terms'])) {
// return $this->respond(['status' => false, 'error' => 'Policy terms not found in array'], 500);
return [];
}
$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);
return [];
}
$JSON = json_decode($policy_terms->policy_terms);
} else {
// return $this->respond(['status' => false, 'error' => 'Unexpected data type for policy terms'], 500);
return [];
}
if (!$JSON) {
// return $this->respond(['status' => false, 'error' => 'Invalid JSON format in policy terms'], 500);
return [];
}
$multi_si = [];
if (isset($JSON->sum_insured) && $JSON->sum_insured != "" && $JSON->sum_insured != null) {
$multi_si[] = $JSON->sum_insured;
} elseif (isset($JSON->sumInsured2) && $JSON->sumInsured2 != "" && $JSON->sumInsured2 != null) {
$multi_si[] = $JSON->sumInsured2;
}
if (isset($JSON->multiple_sum_insured) && is_array($JSON->multiple_sum_insured)) {
foreach ($JSON->multiple_sum_insured as $msi) {
if ($msi != "" && $msi != null) {
$multi_si[] = $msi;
}
}
}
// return $this->respond(['status' => true, 'data' => $multi_si], 200);
return $multi_si;
}
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()
{
echo 'hi';
}
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);
}
}
public function checkAdditionPremiumJSON($client_id, $client_policy_id)
{
$get_additional_rack_rate_relationship_json = $this->policyPremium2Model
->where('client_id', $client_id)
->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->where('additional_relationship IS NOT NULL', null, false)
->countAllResults();
return $this->respond(['status' => true, 'data' => $get_additional_rack_rate_relationship_json, 'message' => "try"], 200);
}
public function getPolicyTypeForBasePolicy($client_id)
{
$result = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
return $this->respond(['status' => true, 'data' => $result], 200);
}
public function getClientDetails($client_id)
{
$result = $this->clientModel->where('id', $client_id)->first();
return $this->respond(['status' => true, 'data' => $result], 200);
}
public function getBranchUnitsByBranchId($branch_id)
{
$units = $this->clientBranchModel->select('units')->where('id', $branch_id)->first();
if ($units) {
return $units['units'];
} else {
return [];
}
}
public function updateRackRateJson()
{
// $client_policy_id = 12;
$results = $this->policyPremium2Model
->select('*')
// ->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->groupBy('client_policy_id')
->get()
->getResultArray();
$results2 = $this->policyPremium1Model
->select('*')
// ->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->groupBy('client_policy_id')
->get()
->getResultArray();
// dd($results, $results2);
$client_policy_ids = [];
$json = [];
$json1 = [];
foreach ($results as $key => $result) {
$client_policy_id = $result['client_policy_id'];
$client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$policy_terms = [];
if (isset($client_policy_data['policy_terms'])) {
$policy_terms = json_decode($client_policy_data['policy_terms'], true);
}
if (isset($policy_terms['family_floaters'])) {
$family_floaters = $policy_terms['family_floaters'];
if (isset($family_floaters['self']) && isset($family_floaters['spouse']) && isset($family_floaters['childrens']) && isset($family_floaters['parents']) && isset($family_floaters['parents-in-law']) && isset($family_floaters['either-parents-pil']) && isset($family_floaters['elders_count'])) {
$json1[] = $family_floaters;
$self = 1;
$spouse = 'any';
$childrens = 'any';
$parents = 'any';
$parents_in_law = 'any';
if ($family_floaters['self'] == 0) {
$self = 'NA';
}
if ($family_floaters['spouse'] == 0) {
$spouse = 'NA';
}
if ($family_floaters['childrens'] == 0) {
$childrens = 'NA';
}
if ($family_floaters['parents'] == 0) {
$parents = 'NA';
}
if ($family_floaters['parents-in-law'] == 0) {
$parents_in_law = 'NA';
}
$transformed_family_floaters = [
"self" => $self,
"spouse" => $spouse,
"childrens" => $childrens,
"parents" => $parents,
"parents-in-law" => $parents_in_law,
];
$formatedJSON = json_encode($transformed_family_floaters);
$json[] = $formatedJSON;
$forUpdateData = [
"additional_relationship" => $formatedJSON,
"rack_rate_name" => 'Primary',
];
$this->policyPremium2Model
->where('client_policy_id', $client_policy_id)
->set($forUpdateData)
->update();
}
$client_policy_ids[] = $client_policy_id;
}
}
foreach ($results2 as $key => $result) {
$client_policy_id = $result['client_policy_id'];
$client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
// dd($client_policy_data);
if (isset($client_policy_data) && $client_policy_data['policy_terms']) {
$self = 1;
$spouse = 'NA';
$childrens = 'NA';
$parents = 'NA';
$parents_in_law = 'NA';
$transformed_family_floaters = [
"self" => $self,
"spouse" => $spouse,
"childrens" => $childrens,
"parents" => $parents,
"parents-in-law" => $parents_in_law,
];
$formatedJSON = json_encode($transformed_family_floaters);
$json[] = $formatedJSON;
$forUpdateData = [
"additional_relationship" => $formatedJSON,
"rack_rate_name" => 'Primary',
];
$this->policyPremium1Model
->where('client_policy_id', $client_policy_id)
->set($forUpdateData)
->update();
}
}
$client_policy_ids[] = $client_policy_id;
if (count($client_policy_ids) > 0) {
echo 'There are ' . count($client_policy_ids) . ' records to be updated.';
echo '<br>';
dd($client_policy_ids);
} else {
echo 'There is no records to be update.';
}
}
public function removeRackRate($rack_rate_name = null, $client_policy_id = null)
{
$this->myLogger->logme('error', 'Rack Rate Remove function called');
$data = [
'updated_by' => get_session_userid(),
'is_active' => 0
];
$rackRateData = $this->policyPremium2Model
->where('rack_rate_name', $rack_rate_name)
->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->countAllResults();
if ($rackRateData > 0) {
$update = $this->policyPremium2Model
->where('rack_rate_name', $rack_rate_name)
->where('client_policy_id', $client_policy_id)
->set($data)->update();
if ($update) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Rack Rate removed successfully', 'rr_count' => $rackRateData], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove Rack Rate', 'rr_count' => $rackRateData], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Rack Rate not available', 'rr_count' => $rackRateData], 200);
}
}
public function renameRackRateTab($rack_rate_name = null, $new_rack_rate_name = null, $client_policy_id = null)
{
$this->myLogger->logme('error', 'Rack Rate renameRackRateTab function called');
$data = [
'updated_by' => get_session_userid(),
'rack_rate_name' => $new_rack_rate_name
];
$rackRateData = $this->policyPremium2Model
->where('rack_rate_name', $rack_rate_name)
->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->countAllResults();
if ($rackRateData > 0) {
$update = $this->policyPremium2Model
->where('rack_rate_name', $rack_rate_name)
->where('client_policy_id', $client_policy_id)
->where('is_active', 1)
->set($data)
->update();
$affectedRows = $this->policyPremium2Model->affectedRows();
if ($update) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Rack Rate renamed successfully', 'rr_count' => $affectedRows], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to rename Rack Rate', 'rr_count' => $affectedRows], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Rack Rate not available', 'rr_count' => $rackRateData, 'rack_rate_name' => $rack_rate_name, 'client_policy_id' => $client_policy_id, 'new_rack_rate_name' => $new_rack_rate_name,], 200);
}
}
public function getBranchByClientID($client_id)
{
$branch_list = $this->clientBranchModel->where('client_id', $client_id)->where('is_active', 1)->findAll();
$policy_list = [];
foreach ($branch_list as $value) {
$policy_data = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.client_id', $value['client_id'])
->where('client_policy.client_branch_id', $value['id'])
->where('client_policy.is_active', 1)
->findAll();
$policy_list[$value['id']] = $policy_data;
}
if ($branch_list) {
return $this->respond(['status' => true, 'data' => $branch_list, 'policy_data' => $policy_list], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
//Function for get all client, branch and policy data
public function getClientAndBranchAndPolicy()
{
// ---------for client-----------------------------------------------------------------------------
$role_id = get_role_id();
$user_id = get_session_userid();
if ($role_id == 2 || $role_id == 3) {
$clients = $this->clientModel
->select("clients.*, DATE_FORMAT(clients.dob, '%d-%m-%Y') as dob")
->join('client_rm', 'client_rm.client_id = clients.id')
->where('client_rm.user_id', $user_id)
->where('clients.is_active', 1)
->findAll();
} else {
$clients = $this->clientModel
->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
->where('is_active', 1)
->findAll();
}
$clientIds = array_column($clients, 'id');
// Fetch branches in a single query
$branches = $this->clientBranchModel
->whereIn('client_id', $clientIds)
->where('is_active', 1)
->findAll();
// -----------for vehicle ---------------------------------------------------------------------------
$vehicles = $this->vehicleModel
->select('vehicle.*, clients.client_type')
->join('clients', 'clients.id=vehicle.owner')
->where('vehicle.is_active', 1)->findAll();
// -----------for Insurer ---------------------------------------------------------------------------
//fetch all insurer data
$insurers = $this->insurerModel->where('is_active', 1)->findAll();
//map the insurer primary key to column
$insurersIds = array_column($insurers, 'id');
// Fetch insurer branches in a single query
$insurerBranches = $this->insurerBranchModel
->whereIn('insurer_id', $insurersIds)
->where('is_active', 1)
->findAll();
// -----------for Policy ---------------------------------------------------------------------------
// Fetch policies in a single query
$policies = $this->clientPolicyModel
->select("
client_policy.*,
policy_type.policy_type,
policy_type.ebp,
policy_type.etp,
policy_type.iep,
policy_type.itp,
policy_type.bap,
policy_type.allocg,
DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
")
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->whereIn('client_policy.client_id', $clientIds)
->where('client_policy.is_active', 1)
->findAll();
// --------------------------------------------------------------------------------------
$branchList = [];
$policyList = [];
$policyListByClient = [];
$unitList = [];
$insurerBranchList = [];
//for client branch mapping to the client
foreach ($branches as $branch) {
$branchList[$branch['client_id']][] = $branch;
$unitList[$branch['id']][] = json_decode($branch['units']);
}
//for insurer branch mapping to the insurer
foreach ($insurerBranches as $branch) {
$insurerBranchList[$branch['insurer_id']][] = $branch;
}
//for client policy mapping to the branch and client
foreach ($policies as $policy) {
$policyList[$policy['client_branch_id']][] = $policy;
$policyListByClient[$policy['client_id']][] = $policy;
if (isset($policyCount[$policy['client_id']])) {
$policyCount[$policy['client_id']]++;
} else {
$policyCount[$policy['client_id']] = 1;
}
}
//get policy count
foreach ($clients as &$client) {
$client['client_policy_count'] = $policyCount[$client['id']] ?? 0;
}
if (!empty($branchList)) {
return $this->respond([
'status' => true,
'client_data' => $clients,
'vehicle_data' => $vehicles,
'branch_data' => $branchList,
'policy_data' => $policyList,
'policyListByClient' => $policyListByClient,
'insurer_data' => $insurers,
'insurer_branch_data' => $insurerBranchList,
'unit_data' => $unitList,
], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
public function getCDAccNoByClientAndInsurer($client_id, $insurer_id, $insurer_branch_id)
{
// Get client data
$client_data = $this->clientModel
->where('is_active', 1)
->where('id', $client_id)
->first();
$cd_data = [];
// If client has a parent, fetch parent client CD data
if (!empty($client_data['parent_client_id'])) {
$parent_cd_data = $this->CDMasterModel
->where('client_id', $client_data['parent_client_id'])
->where('insurer_id', $insurer_id)
->where('insurer_branch_id', $insurer_branch_id)
->where('is_active', 1)
->findAll();
$cd_data = array_merge($cd_data, $parent_cd_data);
}
// Fetch current client CD data
$client_cd_data = $this->CDMasterModel
->where('client_id', $client_id)
->where('insurer_id', $insurer_id)
->where('insurer_branch_id', $insurer_branch_id)
->where('is_active', 1)
->findAll();
$cd_data = array_merge($cd_data, $client_cd_data);
if (!empty($cd_data)) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'client_id' => $client_id, 'insurer_id' => $insurer_id, 'insurer_branch_id' => $insurer_branch_id], 200);
}
}
// public function getCDAccNoByClientAndInsurer($client, $insurer, $insurer_branch_id)
// {
// $cdmData = $this->CDMasterModel
// ->where('client_id', $client)
// ->where('insurer_id', $insurer)
// ->where('insurer_branch_id', $insurer_branch_id)
// ->where('is_active', 1)
// ->findAll();
// if ($cdmData) {
// return $this->respond(['status' => true, 'data' => $cdmData], 200);
// } else {
// return $this->respond(['status' => false], 200);
// }
// }
// ------------- CLIENT AND VEHICLE ------------------------------------------------------------------------------------------------
public function createClientWithMinimalData2()
{
$postData = $this->request->getPost();
// print_r($postData); die;
$client_type = $postData['client_type'];
$client_data = [
'client_type' => $postData['client_type'],
'client_name' => $postData['client_name'],
'short_name' => $postData['short_name'] ?? $postData['client_name'],
'pan' => $postData['pan'],
'client_code' => generate_client_code(),
];
// Add additional fields if client type is 2
if ($client_type == 2) {
$client_data = array_merge($client_data, [
'dob' => change_date_format($postData['dob'], 'd/m/Y', 'Y-m-d'),
'aadhar' => $postData['aadhar'],
'phone' => $postData['phone'],
'entity_type_id' => 7
]);
} else {
$client_data['entity_type_id'] = $postData['entity_type_id'];
}
// print_rr($client_data);die();
// Insert client data
$client_insert = $this->clientModel->insert($client_data);
if (!$client_insert) {
return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200);
}
// Additional logic for non-individual clients (client_type != 2)
if ($client_type != 2) {
$unit[] = $postData['short_name'] . '-' . $postData['branch_code'];
$branch_data = [
'client_id' => $client_insert,
'branch_name' => $postData['branch_name'],
'branch_code' => $postData['branch_code'],
'gst' => $postData['gst'],
'units' => json_encode($unit) ?? null,
];
$branch_insert = $this->clientBranchModel->insert($branch_data);
if ($branch_insert) {
$contact_data = [
'ref_id' => $branch_insert,
'contact_type' => 'client',
'name' => $postData['name'],
'mobile' => $postData['mobile'],
'email' => $postData['email'],
];
$this->levelContactModel->insert($contact_data);
}
}
return $this->respond([
'status' => true,
'data' => $postData,
'client_id' => $client_insert,
'branch_id' => $branch_insert ?? null,
'message' => 'Client created successfully'
], 200);
}
public function createClientWithMinimalData()
{
$postData = $this->request->getPost();
// print_r($postData); die;
$client_type = $postData['client_type'] ?? null;
$from_modal = $postData['from_modal'] ?? null;
$rules = [
'client_name' => [
'label' => 'Client Name',
'rules' => 'required|regex_match[/^[a-zA-Z0-9 ,\/_\-]+$/]',
'errors' => [
'required' => 'Client Name is required.',
'regex_match' => 'Client Name only allows letters, numbers, spaces, and , / _ -'
]
],
'short_name' => [
'label' => 'Client Short Name',
'rules' => 'required|regex_match[/^[a-zA-Z0-9,\/_\-]+$/]|is_unique[clients.short_name]',
'errors' => [
'required' => 'Short Name is required.',
'regex_match' => 'Short Name only allows letters, numbers, and , / _ -',
'is_unique' => 'This Short Name is already in use.'
]
],
'pan' => [
'label' => 'PAN',
'rules' => 'permit_empty|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/]',
'errors' => [
'regex_match' => 'Invalid PAN format (Example: ABCDE1234F).'
]
],
'entity_type_id' => [
'label' => 'Entity Type',
'rules' => 'required',
'errors' => [
'required' => 'Please select an Entity Type.'
]
],
'branch_name' => [
'label' => 'Branch Name',
'rules' => 'required|regex_match[/^[a-zA-Z0-9 ,\/_\-]+$/]',
'errors' => [
'required' => 'Branch Name is required.',
'regex_match' => 'Branch Name only allows letters, numbers, spaces, and , / _ -'
]
],
'branch_code' => [
'label' => 'Branch Code',
'rules' => 'required|regex_match[/^[a-zA-Z0-9,\/_\-]+$/]',
'errors' => [
'required' => 'Branch Code is required.',
'regex_match' => 'Branch Code only allows letters, numbers, and , / _ -'
]
],
'name' => [
'label' => 'Contact Person Name',
'rules' => 'required|regex_match[/^[a-zA-Z0-9 ,\/_\-]+$/]',
'errors' => [
'required' => 'Name is required.',
'regex_match' => 'Name only allows letters, numbers, spaces, and , / _ -'
]
],
'mobile' => [
'label' => 'Mobile',
'rules' => 'required|numeric|exact_length[10]',
'errors' => [
'required' => 'Mobile number is required.',
'numeric' => 'Mobile must contain only digits.',
'exact_length' => 'Mobile number must be exactly 10 digits.'
]
],
'email' => [
'label' => 'Email',
'rules' => 'required|valid_email',
'errors' => [
'required' => 'Email is required.',
'valid_email' => 'Please provide a valid email address.'
]
],
'gst' => [
'label' => 'GST',
'rules' => 'required|regex_match[/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}$/]',
'errors' => [
'required' => 'GST Number is required.',
'regex_match' => 'Invalid GST format (Example: 12ABCDE1234F5Z6).'
]
]
];
if (isset($from_modal) && !$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$client_insert = null;
if ($client_type == 2) {
$client_data = [
'client_type' => $postData['client_type'],
'client_name' => $postData['client_name'],
'short_name' => $postData['short_name'] ?? $postData['client_name'],
'email' => $postData['email'] ?? null,
'phone' => $postData['mobile'] ?? null,
'client_code' => generate_client_code()
];
$client_insert = $this->clientModel->insert($client_data);
} else if ($client_type == 1) {
$client_data = [
'client_type' => $postData['client_type'],
'client_name' => $postData['client_name'],
'short_name' => $postData['short_name'] ?? $postData['client_name'],
'email' => $postData['email'] ?? null,
'phone' => $postData['mobile'] ?? null,
'client_code' => generate_client_code(),
'entity_type_id' => 2
];
$client_insert = $this->clientModel->insert($client_data);
}
if (!$client_insert) {
return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200);
}
// Additional logic for non-individual clients (client_type != 2)
$branch_insert = null;
if ($client_type != 2) {
$unit[] = $postData['short_name'] . '-' . ($postData['branch_code'] ?? 001);
$branch_data = [
'client_id' => $client_insert,
'branch_name' => $postData['branch_name'],
'branch_code' => $postData['branch_code'] ?? 001,
'gst' => $postData['gst'],
'units' => json_encode($unit) ?? null,
];
$branch_insert = $this->clientBranchModel->insert($branch_data);
if ($branch_insert) {
$contact_data = [
'ref_id' => $branch_insert,
'contact_type' => 'client',
'name' => $postData['name'],
'email' => $postData['email'],
'mobile' => $postData['mobile'] ?? null,
];
$this->levelContactModel->insert($contact_data);
}
}
$clients = $this->clientModel
->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
->where('is_active', 1)
->findAll();
// Fetch branches in a single query
$branches = $this->clientBranchModel
->where('client_id', $client_insert)
->where('is_active', 1)
->findAll();
return $this->respond([
'status' => true,
'data' => $postData,
'client_id' => $client_insert,
'branch_id' => $branch_insert ?? null,
'clients' => $clients,
'branches' => $branches,
'message' => 'Client created successfully'
], 200);
}
public function createVehicleWithMinimalData()
{
$rules = [
'Owner_type' => [
'rules' => 'required|in_list[1,2]',
'errors' => [
'required' => 'Owner type is required',
'in_list' => 'Invalid owner type selected'
]
],
'vehicle_no' => [
'rules' => 'required|regex_match[/^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{4}$/]',
'errors' => [
'required' => 'Vehicle number is required',
'regex_match' => 'Invalid Vehicle Number. Example: TN22AB1234'
]
],
'rc' => [
'rules' => 'required|trim',
'errors' => [
'required' => 'RC Book number is required'
]
],
'type' => [
'rules' => 'required',
'errors' => [
'required' => 'Vehicle type is required'
]
],
'description' => [
'rules' => 'required',
'errors' => [
'required' => 'Vehicle description is required'
]
],
'owner' => [
'rules' => 'required',
'errors' => [
'required' => 'Owner is required'
]
],
];
if (!$this->validate($rules)) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Input validation failed',
'code' => 400,
'errors' => $this->validator->getErrors()
]);
}
$data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = $sanitized_post_data['vehicle_primary_key'] ?? null;
if ($id) {
$vehicle_update = $this->vehicleModel->where('id', $id)->set($sanitized_post_data)->update();
if ($vehicle_update) {
return $this->respond(['status' => true, 'message' => 'Vehicle details updated successfully'], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to update vehicle details'], 200);
}
} else {
$vehicle_insert = $this->vehicleModel->insert($sanitized_post_data);
if ($vehicle_insert) {
// $vehicles = $this->vehicleModel->where('is_active', 1)->findAll();
$vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type')
->join('clients', 'clients.id=vehicle.owner')
->where('vehicle.is_active', 1)
->findAll();
return $this->respond([
'status' => true,
'vehicle_id' => $vehicle_insert,
'owner_id' => $sanitized_post_data['owner'] ?? null,
'owner_branch_id' => $sanitized_post_data['branch_id'] ?? null,
'owner_type' => $sanitized_post_data['Owner_type']?? null,
'vehicles' => $vehicles,
'message' => 'Vehicle created successfully
'
], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
}
}
}
public function createVehicleWithMinimalDataForBDS()
{
$data = $this->request->getPost();
// print_r($data); die;
if (isset($data['client_name']) && !empty($data['client_name'])) {
$client_type = $data['client_type'] ?? null;
$client_insert = null;
if ($client_type == 2) {
$client_data = [
'client_type' => $data['client_type'],
'client_name' => $data['client_name'],
'short_name' => $postData['short_name'] ?? $data['client_name'],
'email' => $data['email'] ?? null,
'phone' => $data['mobile'] ?? null,
'client_code' => generate_client_code()
];
$client_insert = $this->clientModel->insert($client_data);
} else if ($client_type == 1) {
$client_data = [
'client_type' => $data['client_type'],
'client_name' => $data['client_name'],
'short_name' => $data['short_name'] ?? $data['client_name'],
'email' => $data['email'] ?? null,
'phone' => $data['mobile'] ?? null,
'client_code' => generate_client_code(),
'entity_type_id' => 2
];
$client_insert = $this->clientModel->insert($client_data);
}
// Additional logic for non-individual clients (client_type != 2)
$branch_insert = null;
if ($client_type != 2) {
$unit[] = $data['short_name'] . '-' . 001;
$branch_data = [
'client_id' => $client_insert,
'branch_name' => $data['branch_name'],
'branch_code' => 001,
'gst' => $data['gst'],
'units' => json_encode($unit) ?? null,
];
$branch_insert = $this->clientBranchModel->insert($branch_data);
if ($branch_insert) {
$contact_data = [
'ref_id' => $branch_insert,
'contact_type' => 'client',
'name' => $data['name'],
'email' => $data['email'],
];
$this->levelContactModel->insert($contact_data);
}
}
$vehicle_data = [
'vehicle_no' => $data['vehicle_no'],
'type' => $data['type'],
'rc' => $data['rc'],
'rto_id' => $data['rto_id'],
'branch_id' => $branch_insert,
'owner' => $client_insert,
];
$vehicle_insert = $this->vehicleModel->insert($vehicle_data);
if ($vehicle_insert) {
// $vehicles = $this->vehicleModel->where('is_active', 1)->findAll();
$vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type')
->join('clients', 'clients.id = vehicle.owner')
->where('vehicle.is_active', 1)
->findAll();
$clients = $this->clientModel
->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
->where('is_active', 1)
->findAll();
// Fetch branches in a single query
$branches = $this->clientBranchModel
->where('client_id', $client_insert)
->where('is_active', 1)
->findAll();
return $this->respond([
'status' => true,
'vehicle_id' => $vehicle_insert,
'client_id' => $client_insert,
'branch_id' => $branch_insert,
'data' => $data,
'clients' => $clients,
'branches' => $branches,
'vehicles' => $vehicles,
'message' => 'Vehicle created successfully'
], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
}
} else if (isset($data['owner']) && !empty($data['owner'])) {
$vehicle_data = [
'vehicle_no' => $data['vehicle_no'],
'type' => $data['type'],
'rc' => $data['rc'],
'rto_id' => $data['rto_id'],
'branch_id' => $data['branch_id'] ?? null,
'owner' => $data['owner'],
];
$vehicle_insert = $this->vehicleModel->insert($vehicle_data);
$vehicles = $this->vehicleModel->select('vehicle.*, clients.client_type')
->join('clients', 'clients.id = vehicle.owner')
->where('vehicle.is_active', 1)
->findAll();
$clients = $this->clientModel
->select("*, DATE_FORMAT(dob, '%d-%m-%Y') as dob")
->where('is_active', 1)
->findAll();
// Fetch branches in a single query
$branches = $this->clientBranchModel
->where('client_id', $data['owner'])
->where('is_active', 1)
->findAll();
if ($vehicle_insert) {
return $this->respond([
'status' => true,
'vehicle_id' => $vehicle_insert,
'client_id' => $data['owner'],
'branch_id' => $data['branch_id'],
'data' => $data,
'clients' => $clients,
'branches' => $branches,
'vehicles' => $vehicles,
'message' => 'Vehicle created successfully'
], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
}
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
}
}
public function createClientPolicyWithMinimalData()
{
$data = $this->request->getPost();
$insurerValue = (string) $this->request->getPost('insurer');
list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
$data['insurer_branch_id'] = $insurerBranchId;
$data['insurer_id'] = $insurerId;
$data['policy_status'] = 1;
$data['is_addon'] = 1;
$data['gst'] = 18;
$data['created_by'] = get_session_userid();
$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');
$insert = $this->clientPolicyModel->insert($data);
if ($insert) {
$policies = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.client_id', $data['client_id'])
->where('client_policy.client_branch_id', $data['client_branch_id'])
->where('client_policy.is_active', 1)
->findAll();
return $this->respond(['status' => true, 'data' => $policies, 'client_policy_id' => $insert, 'message' => 'Client policy created successfully'], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200);
}
}
// ------------- CLIENT AND VEHICLE ------------------------------------------------------------------------------------------------
public function getPolicyDetailsByPolicyId($id)
{
$policies = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.id', $id)
->where('client_policy.is_active', 1)
->findAll();
if ($policies) {
return $this->respond(['status' => true, 'data' => $policies, 'message' => 'Client policy created successfully'], 200);
} else {
return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200);
}
}
public function check_cost_center($cost_center)
{
$uniqueAC = $this->clientModel
->where('cost_center', $cost_center)
->where('is_active', 1)
->findAll();
if ($uniqueAC != null) {
return $this->respond(['status' => true, 'message' => 'The Cost Center is Already Exist', 'code' => 200], 200);
} else {
return $this->respond(['status' => false, 'code' => 404], 200);
}
}
public function check_policy_no($policy_no)
{
$uniqueAC = $this->clientPolicyModel
->where('policy_no', $policy_no)
->where('is_active', 1)
->findAll();
if ($uniqueAC != null) {
return $this->respond(['status' => true, 'message' => 'The Policy Number is Already Exist', 'code' => 200], 200);
} else {
return $this->respond(['status' => false, 'code' => 404], 200);
}
}
// public function get_client_policy_data_using_policy_no()
// {
// $received_data = $this->request->getGet();
// $policy_no = $this->request->getGet('policy_no');
// $client_id = $this->request->getGet('client_id');
// $client_branch_id = $this->request->getGet('client_branch_id');
// $policy_type_id = $this->request->getGet('policy_type_id');
// $client_type = $this->request->getGet('client_type');
// $data = $this->clientPolicyModel
// ->select("
// client_policy.*,
// policy_type.policy_type,
// clients.client_type,
// clients.client_name,
// DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
// DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
// ")
// ->join('clients', 'client_policy.client_id = clients.id')
// ->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
// ->where('client_policy.policy_no', $policy_no)
// ->where('client_policy.is_active', 1)
// ->where('client_policy.policy_status', 1)
// ->first();
// if ($data) {
// if ($client_type == 1) {
// if ($data['client_id'] == $client_id && $data['client_branch_id'] == $client_branch_id) {
// if ($data['policy_type_id'] == $policy_type_id) {
// return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200);
// } else {
// $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first();
// $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.';
// return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200);
// }
// } else {
// $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check';
// return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200);
// }
// } else {
// if ($data['client_id'] == $client_id) {
// if ($data['policy_type_id'] == $policy_type_id) {
// return $this->respond(['status' => true, 'data' => $data, 'code' => 200, 'received_data' => $received_data], 200);
// } else {
// $policy_type = $this->policyTypeModel->where('id', $policy_type_id)->first();
// $message = 'This policy number is mapped to the selected client with policy type: ' . (!empty($data['policy_type']) ? $data['policy_type'] : 'N/A') . '. You selected: ' . (!empty($policy_type['policy_type']) ? $policy_type['policy_type'] : 'N/A') . '. Please check.';
// return $this->respond(['status' => true, 'data' => $data, 'code' => 409, "message" => $message, 'received_data' => $received_data], 200);
// }
// } else {
// $message = 'This policy number is already linked to another client' . (!empty($data['client_name']) ? '. Client name : ' . $data['client_name'] : '') . '. Please check';
// return $this->respond(['status' => true, 'code' => 409, "message" => $message, 'received_data' => $received_data, 'db_data' => $data], 200);
// }
// }
// } else {
// return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404, 'received_data' => $received_data], 200);
// }
// }
public function get_client_policy_data_using_policy_no()
{
$received_data = $this->request->getGet();
$policy_no = trim($this->request->getGet('policy_no'));
$client_id = $this->request->getGet('client_id') ?? null;
$client_branch_id = $this->request->getGet('client_branch_id') ?? null;
$policy_type_id = $this->request->getGet('policy_type_id') ?? null;
$client_type = $this->request->getGet('client_type') ?? null;
// Check in Policy Transaction (BDS)
$bds_data = $this->policyTransactionModel
->where('is_active', 1)
->where('action_type', 'inception')
->where('TRIM(policy_no)', $policy_no)
->where('policy_no IS NOT NULL AND policy_no <> ""')
->orderBy('id', 'desc')
->first() ?? [];
// Check in Enrollment (client_policy)
$client_policy_data = $this->clientPolicyModel
->where('is_active', 1)
->where('policy_status', 1)
->where('TRIM(policy_no)', $policy_no)
->first();
// Decide message + count
if (count($bds_data) > 0) {
return $this->respond([
'status' => true,
'message' => "This policy number is already linked to another policy in the BDS",
'code' => 409,
'data' => $bds_data['id'],
'received_data' => $received_data,
'pt_id' => $bds_data['id'],
'client_policy_id' => $client_policy_data['id'] ?? null
], 200);
} elseif (!empty($client_policy_data)) {
return $this->respond([
'status' => true,
'message' => "This policy number is already linked to another policy in the Enrollment",
'code' => 409,
'data' => 1,
'received_data' => $received_data,
'client_policy_id' => $client_policy_data['id']
], 200);
} else {
return $this->respond([
'status' => false,
'message' => 'Policy number not found in BDS or Enrollment, so proceed to add a new policy.',
'code' => 404,
'is_dublicate' => false,
'received_data' => $received_data,
'client_policy_id' => null
], 200);
}
}
public function get_client_policy_data_using_policy_no_and_endo_no()
{
$policy_no = $this->request->getGet('policy_no');
$endorsement_no = $this->request->getGet('endorsement_no');
$data = $this->clientPolicyModel
->select('client_policy.*, endorsement.endorsement_type')
->join('endorsement', 'client_policy.id = endorsement.client_policy_id')
->where('client_policy.policy_no', $policy_no)
->where('endorsement.endorsement_no', $endorsement_no)
->where('client_policy.is_active', 1)
->first();
if ($data) {
return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200);
} else {
return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200);
}
}
public function get_client_branch_data($id = null)
{
if ($id) {
$branch_data = $this->clientBranchModel
->select('client_branch.*, clients.pan')
->join('clients', 'client_branch.client_id = clients.id')
->where(['client_branch.id' => $id, 'client_branch.is_active' => 1])
->first();
$branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->findAll();
// print_rr($branch_contact_data);die();
return $this->respond(['status' => true, 'code' => 200, 'data' => $branch_data, 'contact' => $branch_contact_data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
public function getClientData()
{
$client_id = $this->request->getGet('client_id') ?? null;
$result = $this->clientModel->getClientData($client_id);
dd($result);
}
// ---------------------------------------------------------------------------------------------------------
public function updatePolicyTermsKey()
{
$client_id = $this->request->getGet('client_id');
$policy_type_id = $this->request->getGet('policy_type_id');
$query = $this->clientPolicyModel
->where("policy_terms IS NOT NULL AND policy_terms <> ''")
->where('is_active', 1);
if (!empty($client_id)) {
$query->where('client_id', $client_id);
}
if (!empty($policy_type_id)) {
$query->where('policy_type_id', $policy_type_id);
}
$data = $query->findAll();
for ($i = 0; $i < count($data); $i++) {
// dd($data[$i]);
if (isset($data[$i]['policy_terms']) && !empty($data[$i]['policy_terms'])) {
$policyTerms = json_decode($data[$i]['policy_terms'], true);
} else {
continue;
}
// dd($policyTerms);
$is_addon = $data[$i]['is_addon'];
$payable_arr = [];
if (in_array($data[$i]['policy_type_id'], [2, 3]) && $is_addon == 1) {
$payable_arr = ["self" => 0, "spouse" => 0, "childern" => 0, "elders" => 0,];
} else if ($data[$i]['policy_type_id'] == 3 && $is_addon == 3) {
$payable_arr = ["self" => 1, "spouse" => 1, "childern" => 1, "elders" => 1,];
} else if (in_array($data[$i]['policy_type_id'], [4, 5])) {
$payable_arr = ["self" => 1, "spouse" => 1, "childern" => 1, "elders" => 1,];
}
// Initialize an empty array for the ordered policy terms
$orderedPolicyTerms = [];
if (in_array($data[$i]['policy_type_id'], [2, 3, 4, 5])) {
// Set default value of copayzonewisecopay to "empty"
// $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty';
// add is_payable_employee for the GMC Policy
if (isset($policyTerms['age_ratio'])) {
if (!isset($policyTerms['is_payable_employee'])) {
$aliment_index = array_search('age_ratio', array_keys($policyTerms));
$orderedPolicyTerms[] = [
"key" => "is_payable_employee",
"value" => $payable_arr,
"position" => $aliment_index + 1,
];
}
}
// // Add copayzonewisecopay and copayzonewisecopaydata if they exist_
// if (isset($policyTerms['copayzonewisecopay'])) {
// if(!isset($policyTerms['co_pay_details'])){
// $co_pay_details_value = "";
// if (strtolower($ans) == "nil" || $ans == 0) {
// $policyTerms['copayzonewisecopay'] = 0;
// $co_pay_details_value = "";
// } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) {
// $policyTerms['copayzonewisecopay'] = 1;
// $co_pay_details_value = $ans;
// }
// $co_pay_index = array_search('copayzonewisecopay', array_keys($policyTerms));
// $orderedPolicyTerms[] = [
// "key" => "co_pay_details",
// "value" => $co_pay_details_value,
// "position" => $co_pay_index + 2,
// ];
// unset($policyTerms['optionalparentalcopay']);
// }
// }
// Add ailmentcapping and ailmentcappingdata if they exist
if (isset($policyTerms['ailmentcapping'])) {
if (!isset($policyTerms['ailment_capping_details'])) {
$aliment_index = array_search('ailmentcapping', array_keys($policyTerms));
$orderedPolicyTerms[] = [
"key" => "ailment_capping_details",
"value" => "",
"position" => $aliment_index + 2,
];
}
}
} else {
// add is_payable_employee for the GMC Policy
if (isset($policyTerms['age_ratio'])) {
if (!isset($policyTerms['is_payable_employee'])) {
$aliment_index = array_search('age_ratio', array_keys($policyTerms));
$orderedPolicyTerms[] = [
"key" => "is_payable_employee",
"value" => [
"self" => 0,
],
"position" => $aliment_index + 1,
];
}
} else {
if (!isset($policyTerms['is_payable_employee'])) {
$orderedPolicyTerms[] = [
"key" => "is_payable_employee",
"value" => [
"self" => 0,
],
"position" => 2,
];
}
}
}
foreach ($orderedPolicyTerms as $term) {
$position = $term['position'];
$key = $term['key'];
$value = $term['value']; // Insert the key-value pair at the specified index
$policyTerms = array_merge(
array_slice($policyTerms, 0, $position, true),
[$key => $value],
array_slice($policyTerms, $position, null, true)
);
}
foreach ($policyTerms as $key => $term) {
if ($term == "0") {
$policyTerms[$key] = "No"; // Use = for assignment
} elseif ($term == "1") {
$policyTerms[$key] = "Yes"; // Use = for assignment
}
}
if (in_array($data[$i]['policy_type_id'], [2, 3, 4, 5])) {
if (!isset($policyTerms['waiver_of_90_days_waiting_period'])) {
$policyTerms['waiver_of_90_days_waiting_period'] = "";
}
if (!isset($policyTerms['waiver_of_other_waiting_periods'])) {
$policyTerms['waiver_of_other_waiting_periods'] = "";
}
if (!isset($policyTerms['maternity_benefit'])) {
$policyTerms['maternity_benefit'] = "";
}
if (!isset($policyTerms['well_baby_well_mother_expenses'])) {
$policyTerms['well_baby_well_mother_expenses'] = "";
}
if (!isset($policyTerms['icu_limit'])) {
$policyTerms['icu_limit'] = "";
}
if (!isset($policyTerms['infertility_treatment_coverage'])) {
$policyTerms['infertility_treatment_coverage'] = "";
}
if (!isset($policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'])) {
$policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'] = "";
}
if (!isset($policyTerms['non_admissible_contingency_corporate_buffer'])) {
$policyTerms['non_admissible_contingency_corporate_buffer'] = "";
}
if (!isset($policyTerms['terrorism'])) {
$policyTerms['terrorism'] = "";
}
if (!isset($policyTerms['widower_cover'])) {
$policyTerms['widower_cover'] = "";
}
if (!isset($policyTerms['breavement_cover'])) {
$policyTerms['breavement_cover'] = "";
}
if (!isset($policyTerms['enrollment_display_key'])) {
$policyTerms['enrollment_display_key'] = $this->existingGMCDisplayValueTransform($policyTerms);
}
} else if ($data[$i]['policy_type_id'] == 1) {
if (!isset($policyTerms['medical_expenses_medical_extension'])) {
$policyTerms['medical_expenses_medical_extension'] = "";
}
if (!isset($policyTerms['opd_treatment_cover'])) {
$policyTerms['opd_treatment_cover'] = "";
}
if (!isset($policyTerms['repatriation_of_mortal_remains'])) {
$policyTerms['repatriation_of_mortal_remains'] = "";
}
if (!isset($policyTerms['family_transportation_benefits'])) {
$policyTerms['family_transportation_benefits'] = "";
}
if (!isset($policyTerms['fractures_dislocation_burns'])) {
$policyTerms['fractures_dislocation_burns'] = "";
}
if (!isset($policyTerms['coma'])) {
$policyTerms['coma'] = "";
}
if (!isset($policyTerms['travel_expenses_for_medical_treatment'])) {
$policyTerms['travel_expenses_for_medical_treatment'] = "";
}
if (!isset($policyTerms['daily_cash_allowance'])) {
$policyTerms['daily_cash_allowance'] = "";
}
if (!isset($policyTerms['artifical_limb_and_prosthesis'])) {
$policyTerms['artifical_limb_and_prosthesis'] = "";
}
if (!isset($policyTerms['air_ambulance'])) {
$policyTerms['air_ambulance'] = "";
}
if (!isset($policyTerms['enrollment_display_key'])) {
$policyTerms['enrollment_display_key'] = $this->existingGPADisplayValueTransform($policyTerms);
}
}
// dd($policyTerms);
// Re-encode the ordered policy terms
$updatedPolicyTerms = json_encode($policyTerms);
// dd($updatedPolicyTerms);
// dd($orderedPolicyTerms, $updatedPolicyTerms);
$this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]);
}
}
public function existingGMCDisplayValueTransform($data)
{
$transformedData = [];
if (isset($data["waiverofpreexistingdiseases"])) {
$transformedData['Waiver of Pre-existing Diseases'] = $data["waiverofpreexistingdiseases"];
}
if (isset($data["waiverof1,2,3&4thyearexclusions"])) {
$transformedData['Waiver of 1, 2, 3 & 4th year Exclusions'] = $data["waiverof1,2,3&4thyearexclusions"];
}
if (isset($data["waiverof30dayswaitingperiod"])) {
$transformedData['Waiver of 30 days waiting period'] = $data["waiverof30dayswaitingperiod"];
}
if (isset($data["waiver_of_90_days_waiting_period"])) {
$transformedData['Waiver of 90 Days Waiting Period'] = $data["waiver_of_90_days_waiting_period"];
}
if (isset($data["waiver_of_other_waiting_periods"])) {
$transformedData['Waiver of Other Waiting Periods'] = $data["waiver_of_other_waiting_periods"];
}
if (isset($data["maternity_benefit"])) {
$transformedData['Maternity Benefit'] = $data["maternity_benefit"];
}
if (isset($data["9monthwaitingperiodwaived"])) {
$transformedData['9-month waiting Period - waived'] = $data["9monthwaitingperiodwaived"];
}
if (isset($data["maternitycoverage"])) {
$transformedData['Maternity Coverage'] = $data["maternitycoverage"];
}
if (isset($data["twindelivery"])) {
$transformedData['Twin Delivery'] = $data["twindelivery"];
}
if (isset($data["well_baby_well_mother_expenses"])) {
$transformedData['Well baby / Well Mother Expenses'] = $data["well_baby_well_mother_expenses"];
}
if (isset($data["preandpostnatal"])) {
$transformedData['Pre and Post natal'] = $data["preandpostnatal"];
}
if (isset($data["infertility_treatment_coverage"])) {
$transformedData['Infertility Treatment Coverage'] = $data["infertility_treatment_coverage"];
}
if (isset($data["babyday1cover"])) {
$transformedData['Baby Day 1 Cover'] = $data["babyday1cover"];
}
if (isset($data["coverfromthedateofjoining"])) {
$transformedData['Cover from the date of Joining'] = $data["coverfromthedateofjoining"];
}
if (isset($data["mid_term_addition_of_new_born_newly_wedded_spouse"])) {
$transformedData['Mid Term Addition of New Born / Newly Wedded Spouse'] = $data["mid_term_addition_of_new_born_newly_wedded_spouse"];
}
if (isset($data["prehospitalizationcover"])) {
$transformedData['Pre Hospitalization Cover'] = $data["prehospitalizationcover"];
}
if (isset($data["posthospitalizationcover"])) {
$transformedData['Post Hospitalization Cover'] = $data["posthospitalizationcover"];
}
if (isset($data["congenitaldiseasesinternal"])) {
$transformedData['Congenital Diseases - Internal'] = $data["congenitaldiseasesinternal"];
}
if (isset($data["congenitaldiseasesexternal"])) {
$transformedData['Congenital Diseases - External'] = $data["congenitaldiseasesexternal"];
}
if (isset($data["copayzonewisecopay"])) {
$transformedData['Co-Pay/Zone wise Co Pay'] = $data["copayzonewisecopay"];
}
if (isset($data["roomrentlimit"])) {
$transformedData['Room Rent Limit'] = $data["roomrentlimit"];
}
if (isset($data["icu_limit"])) {
$transformedData['ICU Limit'] = $data["icu_limit"];
}
if (isset($data["proportionatedeductionclause"])) {
$transformedData['Proportionate Deduction Clause'] = $data["proportionatedeductionclause"];
}
if (isset($data["ailmentcapping"])) {
$transformedData['Ailment capping'] = $data["ailmentcapping"];
}
if (isset($data["ailment_capping_details"])) {
$transformedData['Ailment capping Details'] = $data["ailment_capping_details"];
}
if (isset($data["corporatebuffer"])) {
$transformedData['Corporate Buffer'] = $data["corporatebuffer"];
}
if (isset($data["non_admissible_contingency_corporate_buffer"])) {
$transformedData['Non-Admissible / Contingency Corporate Buffer'] = $data["non_admissible_contingency_corporate_buffer"];
}
if (isset($data["ambulancecharges"])) {
$transformedData['Ambulance Charges'] = $data["ambulancecharges"];
}
if (isset($data["airambulance"])) {
$transformedData['Air Ambulance'] = $data["airambulance"];
}
if (isset($data["reasonableandcustomarycharges"])) {
$transformedData['Reasonable and Customary Charges'] = $data["reasonableandcustomarycharges"];
}
if (isset($data["daycaretreatment"])) {
$transformedData['Day Care Treatment'] = $data["daycaretreatment"];
}
if (isset($data["lasiksurgery"])) {
$transformedData['Lasik Surgery'] = $data["lasiksurgery"];
}
if (isset($data["ayushtreatmentcover"])) {
$transformedData['AYUSH treatment cover'] = $data["ayushtreatmentcover"];
}
if (isset($data["moderntreatmentsasperirdai"])) {
$transformedData['Modern treatments as per IRDAI'] = $data["moderntreatmentsasperirdai"];
}
if (isset($data["opd_treatment"])) {
$transformedData['OPD Treatment'] = $data["opd_treatment"];
}
if (isset($data["days_of_discharge"])) {
$transformedData['Claim Intimation Clause'] = $data["days_of_discharge"];
}
if (isset($data["days_from_dod"])) {
$transformedData['Claim Submission'] = $data["days_from_dod"];
}
if (isset($data["terrorism"])) {
$transformedData['Terrorism'] = $data["terrorism"];
}
if (isset($data["widower_cover"])) {
$transformedData['Widower Cover'] = $data["widower_cover"];
}
if (isset($data["breavement_cover"])) {
$transformedData['Breavement Cover'] = $data["breavement_cover"];
}
return !empty($transformedData) ? $transformedData : [];
}
public function existingGPADisplayValueTransform($data)
{
$transformedData = [];
if (isset($data["accidentalDeathBenefit"])) {
$transformedData['Accidental Death Benefit'] = $data["accidentalDeathBenefit"];
}
if (isset($data["permanentTotalDisablement"])) {
$transformedData['Permanent Total Disablement'] = $data["permanentTotalDisablement"];
}
if (isset($data["permanentPartialDisablement"])) {
$transformedData['Permanent Partial Disablement'] = $data["permanentPartialDisablement"];
}
if (isset($data["temporaryTotalDisablementBenefit"])) {
$transformedData['Temporary Total Disablement Benefit'] = $data["temporaryTotalDisablementBenefit"];
}
if (isset($data["medical_expenses_medical_extension"])) {
$transformedData['Medical Expenses / Medical Extension (IPD)'] = $data["medical_expenses_medical_extension"];
}
if (isset($data["opd_treatment_cover"])) {
$transformedData['OPD Treatment Cover'] = $data["opd_treatment_cover"];
}
if (isset($data["ambulanceCharges"])) {
$transformedData['Ambulance Charges'] = $data["ambulanceCharges"];
}
if (isset($data["repatriation_of_mortal_remains"])) {
$transformedData['Repatriation of Mortal Remains'] = $data["repatriation_of_mortal_remains"];
}
if (isset($data["childrenEducationWelfareFund"])) {
$transformedData['Children Education Welfare Fund'] = $data["childrenEducationWelfareFund"];
}
if (isset($data["terrorism"])) {
$transformedData['Terrorism'] = $data["terrorism"];
}
if (isset($data["worldwideCover"])) {
$transformedData['Worldwide Cover'] = $data["worldwideCover"];
}
if (isset($data["family_transportation_benefits"])) {
$transformedData['Family Transportation Benefits'] = $data["family_transportation_benefits"];
}
if (isset($data["fractures_dislocation_burns"])) {
$transformedData['Fractures / Dislocation / Burns'] = $data["fractures_dislocation_burns"];
}
if (isset($data["coma"])) {
$transformedData['Coma'] = $data["coma"];
}
if (isset($data["carriageofDeadBody"])) {
$transformedData['Carriage of Dead Body'] = $data["carriageofDeadBody"];
}
if (isset($data["compassionateVisitExpenses"])) {
$transformedData['Compassionate Visit Expenses'] = $data["compassionateVisitExpenses"];
}
if (isset($data["travel_expenses_for_medical_treatment"])) {
$transformedData['Travel expenses for Medical Treatment'] = $data["travel_expenses_for_medical_treatment"];
}
if (isset($data["daily_cash_allowance"])) {
$transformedData['Daily cash Allowance'] = $data["daily_cash_allowance"];
}
if (isset($data["artifical_limb_and_prosthesis"])) {
$transformedData['Artifical Limb and Prosthesis'] = $data["artifical_limb_and_prosthesis"];
}
if (isset($data["animalSnakeInsectBite"])) {
$transformedData['Animal/Snake/Insect Bite'] = $data["animalSnakeInsectBite"];
}
if (isset($data["air_ambulance"])) {
$transformedData['Air Ambulance'] = $data["air_ambulance"];
}
return !empty($transformedData) ? $transformedData : [];
}
public function updateRemainderDate()
{
// Connect to the database and fetch the data
$data = db_connect()->table('client_policy')
->where("reminder_date IS NOT NULL AND reminder_date <> ''")
->where('is_active', 1)
->get()
->getResultArray();
$days = [];
foreach ($data as $value) {
$reminderDate = strtotime($value['reminder_date']);
if ($reminderDate) {
$date_of_date = date('d', $reminderDate);
$days[] = $date_of_date;
$days[] = $value['reminder_date'];
db_connect()->table('client_policy')->where('id', $value['id'])->set('reminder_date', $date_of_date)->update();
}
}
dd($days);
}
public function sendextraparam()
{
// $zipService = new \App\Libraries\ZipService();
// $source = WRITEPATH . 'uploads/hr_files';
// $destination = WRITEPATH . 'tmp/archive_' . date('Ymd') . '.zip';
// $result = $zipService->createLocalZip($source, $destination);
// if ($result['status']) {
// echo "File is ready at: " . $result['path'];
// } else {
// echo "Error creating zip: " . $result['message'];
// }
// die;
// $cd = $this->view_Deposit(2, 'rest', ['client_id' => 58, 'cd_ac_pk' => 94]);
// dd($cd);
// $return = db_connect()->table('jobs')->where('id', 1677)->get()->getRowArray();
// $return = $this->updatePolicyTransactionDataWhileClinetPolicyUpdate(json_decode($data['payload'], true));
// dd($return);
// $ticket_id = 515;
// $apiServiceController = new ApiServiceController();
// $apiServiceController->pushClaims($ticket_id); die;
// echo change_date_format('13/10/1998 00:00:00','d/m/Y H:i:s');die();
// $medi_assist = new MediAssistApiController();
// $res = $medi_assist->MediAssistGetBenefDetails(['policy_no' => '97000034240400000030', 'file_id' => 389, 'return_type' => 'job', 'client_policy_id' => 6192 ]);
// dd($res);
// // 1. Dummy JSON data create panrom (Temp file)
// $tempJsonFile = tempnam(sys_get_temp_dir(), 'test_vidal_');
// $dummyData = [
// [
// 'empNo' => 'EMP001',
// 'name' => 'John Doe',
// 'dob' => '01/01/1990',
// 'relationship' => 'Self',
// 'gender' => 'Male',
// 'enrollmentId' => 'TPA123',
// 'age' => 34
// ]
// ];
// file_put_contents($tempJsonFile, json_encode($dummyData));
// $inputArray = [
// 'file_id' => 10,
// 'json_file_path' => $tempJsonFile
// ];
// $vidalController = new VidalApiController();
// $res = $vidalController->saveVidalAPIData($inputArray);
// dd($res);
$employeeController = new EmployeeController();
// $response = $employeeController->getEmployeeEcardFromTmpFolderAndZipToS3(json_decode('{"batch_no":2,"last_emp_policy_id":"13218","folder_name":"bulk_ecards_IOCL-77448855996699885555_2026-02-05_09-32-22","processed_in_this_batch_data_count":7,"pdf_count":0,"hr_id":"1"}', true));
// $response = $employeeController->bulkEcardDownloadAsZipFromS3(json_decode('{"client_policy_id":"6066","hr_id":"1"}', true));
// dd($response);
// $employeeController->truncateFileData('633');
// $res = $this->getHrAccessData(4075); dd($res);
// ---------- TICKET SERVICE CONTROLLER --------------------------------------------------------------------------------
$ticketServiceController = new TicketServiceController();
// $response = $ticketServiceController->claimDumpExcelFileFormatValidation(["file_id" => 34]);
// $response = $ticketServiceController->claimDumpExcelFileDataValidation(["file_id" => 34]);
// $response = $ticketServiceController->getClaimExcelErrorData(["file_id" => 41]);
// $response = $ticketServiceController->claimDumpOnBoardProcess(["file_id" => 17]);
// $response = $ticketServiceController->extractExcelData("claims_dump_form_client.xlsx");
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 51]); //abhi
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 50]); //fhpl
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 53]); //icici
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 54]); //mediassist
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 52]); //reliance
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 48]); //vidal`
// $response = $ticketServiceController->tpaClaimDumpImporter(["file_id" => 57]); //mediassist
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 51]); //abhi
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 50]); //fhpl
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 53]); //icici
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 54]); //mediassist
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 52]); //reliance
// $response = $ticketServiceController->tpaClaimDumpToTicketMasterImporters(["file_id" => 48]); //vidal
// $response = $ticketServiceController->getTpaClaimDumpErrorData(["file_id" => 48]);
// dd($response);
// ---------- TICKET CONTROLLER --------------------------------------------------------------------------------
$TicketController = new TicketController();
// $response = $TicketController->getMoreInfo($requestFrom = 'rest', $ticket_id = 70);
// $response = $TicketController->sendAutoMailTrigger($ticket_id = 602);
// dd($response);
// ---------- EMP SERVICE CONTROLLER --------------------------------------------------------------------------------
$empServiceController = new EmployeeServiceController();
// $res = $empServiceController->excelFileFormatValidation(['file_id' => '1264']);
// $res = $empServiceController->excelFileDataValidation(['file_id' => '1264']);
// $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 1264]);
// $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 1262]);
// $res = $empServiceController->employeesOnboardPreprocess(['file_id' => 1169]);
// $res = $empServiceController->employeesOnboardProcess(['file_id' => 835]);
// $res = $empServiceController->employeesEnrollmentInsert(['file_id' => 836]);
// $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '1131']);
// $res = $empServiceController->employeeDisembark(['file_id' => '1681']);
// $res = $empServiceController->employeesCorrectionProcess(['file_id' => '2033']);
// $res = $empServiceController->compareMemberDataAndInceptionData(['file_id' => '1126']);
// dd($res);
// ---------- EMP MULTI EVENT SERVICE CONTROLLER --------------------------------------------------------------------------------
$EmployeeMultiEventServiceController = new EmployeeMultiEventServiceController();
// $res = $EmployeeMultiEventServiceController->constructMultiEventData(['file_id' => '1069']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileFormateValidation(['file_id' => '2373']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileDataValidation(['file_id' => '2373']);
// $res = $EmployeeMultiEventServiceController->excelMultieventFileOnBoard(['file_id' => '1069']);
// $res = $EmployeeMultiEventServiceController->getExcelErrorData(1069, $res);
// $res['file_id'] = 1069;
// echo view('excel_errors', $res);
// dd($res);
// ---------- POLICY TRANSACTION CONTROLLER --------------------------------------------------------------------------------
$policyTransactionController = new PolicyTransactionController();
// $res = $policyTransactionController->validateInsurerStatement(['file_id' => '281']);
// $res = $policyTransactionController->updateInsurerStatement(['file_id' => '62']);
// $res = $policyTransactionController->bdsDumpExcelFileFormatValidation(['file_id' => '73']);
// $res = $policyTransactionController->insertBulkBdsData(['file_id' => '78']);
// dd($res);
// ----------EMP DATA SERVICE CONTROLLER--------------------------------------------------------------------------------
// $batch_data = [
// 'client_id' => 51,
// 'client_branch_id' => 40,
// 'client_policy_id' => 63,
// 'insurer_or_tpa' => "insurer",
// 'event_type' => "correction",
// 'actions' => "export",
// 'file_name' => "deletion_enhancement_test_file.xlsx",
// ];
$batch_data = [
'client_id' => 12,
'client_policy_id' => 8063,
'client_branch_id' => 1,
'insurer_or_tpa' => "insurer",
// 'insurer_or_tpa' => "tpa",
'event_type' => "inception",
'file_name' => "si_enhancement_test_file.xlsx",
'actions' => "export",
];
// $batch_data['insurer_or_tpa'] = 'insurer';
// $batch_data['insurer_or_tpa'] = 'tpa';
// $dashBoardController = new DashboardController();
// $client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id=159, $client_branch_id=126);
// $dashBoardController->sendRemainderMail($client_policy_data);
// $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard(12);
// $ids = array_column($emp_data, 'id');
// $client_policy_id = 5062;
// $ids = [408518,408519,408520,408521,408522,408523,408524,408525,408526,408527,408528,408529,408530,408531,408532,408533,408534,408535,408536,408537,408538,408539,408540,408541,408542,408543,408544,408545,408546,408547,408548,408549,408550,408551,408552,408553,408554,408555,408556,408557,408558,408559,408560,408561,408562,408563,408564,408565,408566,408567,408568,408569,408570,408571,408572,408573,408574,408575,408576,408577,408578,408579,408580,408581,408582,408583,408584,408585,408586,408587,408588,408589,408590,408591,408592,408593,408594,408595,408596,408597,408598,408599,408600,408601,408602,408603,408604,408605,408606,408607,408608,408609,408610,408611,408612,408613,408614,408615,408616,408617,408618,408619,408620,408621,408622,408623,408624,408625,408626,408627,408628,408629,408630,408631,408632,408633,408634,408635,408636,408637,408638,408639,408640,408641,408642,408643];
$EmpDataServiceController = new EmpDataServiceController();
// $res = $EmpDataServiceController->generateExcelForDeletion($batch_data); dd($return); die;
// $res = $EmpDataServiceController->generateExcelForSIEnhancement($batch_data); die;
// $res = $EmpDataServiceController->generateExcelForCorrection($batch_data);
// $res = $EmpDataServiceController->importInceptionFileValidation(['file_id' => 1932]); die;
// $res = $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live
// $res = $EmpDataServiceController->importSIEnhancementUpdateEndorsementID(['file_id' => 387]); //for live
// $res = $EmpDataServiceController->importSIEnhancementValidation(['file_id' => 387]); //for live
// $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 214]); //for live
// $res = $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 310]); dd($res);//for live
// $res = $EmpDataServiceController->getInceptionBasePremium(["13332","13333","13334","13335","13336"]); dd($res);//for live
// $res = $EmpDataServiceController->getDeletionBasePremium(["13248","13250","13249","13247"], json_decode('{"employeeIds":["13248","13250","13249","13247"],"client_id":"3927","client_policy_id":"6183","client_branch_id":"1874","cd_ac_no":"CD9751909505","endorsement_no":"END1238","count":4,"event_name":"deletion","policy_name":"GMC","user_id":"48"}', true)); dd($res);//for live
// $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction(json_decode('{"client_policy_id":"6187","endorsement_no":"000000001","emp_count":5,"action_type":"addition","no_of_insured":3,"no_of_dependent":0, "base_premium" : "1000", "gst" : "180", "policy_issue_date" : "2025-12-31"}', true)); dd($res);//for live
// $res = $EmpDataServiceController->sendMailForDownloadingECard(['ids' => $ids, 'client_policy_id' => $client_policy_id]);
// $res = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data, 1); dd($result);
// $res = $this->employeePolicyModel->getSIEnhancementEmployeesDataForExportExcel($batch_data, 1);
// return $this->downloadInsurerExcelExport($batch_data);
// dd($res); die;
// $params = [
// 'client_policy_id' => 6090,
// 'action_type' => "inception",
// ];
// $res = $EmpDataServiceController->makeEntryForBDSPolicyTransaction($params);
// dd($res);
// $array = [
// "employeeIds" => ["12800", "12798", "12797", "12799"],
// "client_id" => "159",
// "client_policy_id" => "336",
// "client_branch_id" => "126",
// "cd_ac_no" => "Apple_123",
// "endorsement_no" => "ENDORSEMENT_ID",
// "count" => 4,
// "event_name" => "deletion",
// "policy_name" => "GMC",
// "user_id" => "1"
// ];
// $EmpDataServiceController->cashDepositCalculationForDeletion($array);
// $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data);
// $totals = 0;
// foreach ($result as $item) {
// $totals = $totals + $item->total;
// }
// clear_cd_balance_session();
// $data = [
// 'cd_balance' => session()->get('cd_balance'),
// 'hr_data' => session()->get('hr_data'),
// 'cd_balance_info' => session()->get('cd_balance_info'),
// get_cd_balance()
// ];
// dd($data);
// $result = $this->employeePolicyModel->getCorrectionEmployeesDataForExportExcel($batch_data);
// dd(db_connect()->getLastQuery());
// ------------- LEADS CONTROLLER ----------------------------------------------------------
$LeadsController = new LeadsController();
$RFQModel = new RFQModel();
// $data = $RFQModel->where('is_active', 1)->where('lead_id', 323)->orderBy('id', 'desc')->first();
// $data = db_connect()->table('leads')->where('is_active', 1)->where('id', 326)->orderBy('id', 'desc')->get()->getResultArray();
// dd($data);
// $policy_type = 2;
// $proposel_name = "Proposal 2";
// $insurer_name = "ICICI-P-ICICI002-V1";
// $jsonArray = json_decode($data['json'], true);
// dd($jsonArray);
// $res = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name);
// $res = $LeadsController->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => 169]);
// $res = $LeadsController->reorderProposalsByInsurerTotal($jsonArray);
// $res = $LeadsController->calculateMembersDemography(['lead_id' => 287], "internal");
// $res = $LeadsController->generateDemographyDataTable(['lead_id' => 287]);
// echo $res;
// dd($res);
// -----------BDS REPORT CONTROLLER---------------------------------------------------------------------------------
// $BDSReportController = new BDSReportController();
// $data['data'] = $BDSReportController->getBAPInsurerData();
// return $this->loadLayout('irda_bap_insurer_report_list', $data);
// $data['data'] = $BDSReportController->getBAPClientData();
// return $this->loadLayout('irda_bap_client_report_list', $data);
// $data['data'] = $BDSReportController->getClientData(1);
// return $this->loadLayout('irda_client_report_list', $data);
// $BDSReportController->getBAPClientData();
//--------------------------------------------------------------------------------------------------------
// $email_id = 'venkateshraman786@gmail.com';
// $common = ['mail_type'=>'test_mail_cli'];
// $bcc = "vitvelz@gmail.com";
// $data = db_connect()
// ->table('jobs')
// ->where('id', 2264)
// ->get()
// ->getResultArray();
// $data = json_decode($data[0]['payload'], true);
// // dd($data);
// // Send email and get response
// $result = MailHelper::send_email($data[0]);
// echo json_encode($result);
// log_message('error',json_encode($result));
//--------------------------------------------------------------------------------------------------------
// $ticketModel = new TicketMasterModel();
// $reportData['data'] = $ticketModel->getTATReport(1);
// print_rr($reportData);
// $this->loadLayout('tat_report_band_wise_list', $reportData);
// $data = $ticketModel->getTATReport(1);
// $empmodel = new EmployeeModel();
// $data = $empmodel->getEmployeePolicy(348);
// dd($data);
$LeadsController = new LeadsController();
$RFQModel = new RFQModel();
// $path = $LeadsController->constructNonEbExcelToSaveTemp(106, 2, "Proposal 2-ICICIPRU-ICICI001");
// $filepath = $path['filePath'];
// if (file_exists($filepath)) {
// // Set headers to force download
// header('Content-Description: File Transfer');
// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
// header('Content-Length: ' . filesize($filepath));
// header('Pragma: public');
// // Output the file content
// readfile($filepath);
// // Delete the file after download
// unlink($filepath);
// exit;
// } else {
// echo "File does not exist.";
// }
// $data = $this->leadsModel->where('leads.id', 125)->where('leads.is_active', 1)->first();
// $RFQdata = $RFQModel->getRFQTableDataWithLeadIDAndType(145, 2);
// $returnData = $LeadsController->getPlacementJson($data);
// Kint::dump($returnData);
// $policy_terms = $LeadsController->convertNonEbQCRJsonToPolicyTerms(json_decode($returnData, true));
// Kint::dump($policy_terms);
// // $this->clientPolicyModel->where('id', 6050)->set('placement_json', $returnData)->update();
// $this->clientPolicyModel->where('id', 6050)->set('policy_terms', $policy_terms)->update();
// dd($returnData);
// Kint::dump($RFQdata['json']);
// $inputJson = json_decode($RFQdata['json'], true);
// Kint::dump($inputJson);
// // print_rr($inputJson['table_data']);
// $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson);
// // If you want to convert back to JSON string
// $finalJson = json_encode($sortedJson, JSON_PRETTY_PRINT);
// // $RFQModel->insert(['lead_id' => 145, 'json' => $finalJson, 'type' => 1]);
// dd($finalJson);
// $baseWhere = [
// 'client_id' => 159,
// 'client_policy_id' => 336,
// 'insurer_id' => 1,
// 'cd_ac_pk' => 56,
// 'event_name' => "addition",
// ];
// $return_value = check_cd_entry_exist($baseWhere);
// dd($return_value);
// $param = 9715454901;
// $type = 'emp_code';
// $client_policy_id = 64;
// $client_id = 3927;
// $result = $this->getTheEmpDataForClaimSearchByMobile($param, $type, $client_policy_id, $client_id);
// $result = $this->employeePolicyModel->getEmployeePolicy();
// $result = $this->getHrAccessData($client_id);
// $html = view('hr_access_controll', $result);
// dd($html);
// $employeeRestController = new EmployeeRestController();
// $result = $employeeRestController->getPreEmployeePolicyCount($param, $client_id);
// dd($result);
}
// -------------------------------------------------------------------------------------------------------
public function createOtherTabContent()
{
$this->myLogger->logme('error', 'Client Others function called');
$data = $this->request->getPost();
$data['created_by'] = get_session_userid();
$client_id = $data['client_id'];
unset($data['client_id']);
$insert = $this->clientModel->where('id', $client_id)->set($data)->update();
if ($insert) {
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Client others data updated', 'data' => $data], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data to update'], 200);
}
}
// -------------------------------------------------------------------------------------------------------
public function enrollmentAddonSIAmountDropdown($client_policy_id)
{
if (!empty($client_policy_id)) {
$client_policy_details = $this->clientPolicyModel->where('id', $client_policy_id)->where('policy_status', 1)->where('is_active', 1)->first();
if (!empty($client_policy_details) && $client_policy_details['policy_type_id'] == 3 && $client_policy_details['is_addon'] == 3) {
$base_policy_id = $client_policy_details['base_policy'] ?? 0;
if (!empty($base_policy_id)) {
}
}
}
}
public function getCDAmount()
{
$cd_ac_pk = $this->request->getGet('cd_ac_pk');
$cd_amount = $this->clientDepositModel
->where('is_active', 1)
->where('cd_ac_pk', $cd_ac_pk)
->orderBy('id', 'desc')
->first();
if ($cd_amount) {
return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_amount], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
}
}
// -----------Function for Claim Module--------------------------------------------------------------------------------------------
public function getTheEmpDataForClaim($param, $type = null)
{
// Construct the base query
$data = $this->clientPolicyModel
->select("
clients.id AS client_id,
clients.client_name,
insurers.id AS insurer_id,
insurers.name AS insurer_name,
tpa.id AS tpa_id,
tpa.name AS tpa_name,
employees.id AS emp_id,
employees.name AS emp_name,
employees.emp_code,
employees.mobile AS emp_mobile,
employees.email_corporate AS emp_email,
employees.relationship AS emp_relationship,
employee_polices.uhid AS policy_no,
employee_polices.client_policy_id
")
->join('clients', 'client_policy.client_id = clients.id', 'left')
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('employees', 'clients.id = employees.client_id', 'left')
->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left')
->where('client_policy.is_active', 1)
->where('insurers.is_active', 1)
->where('tpa.is_active', 1)
->where('employees.is_active', 1)
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
->whereIn('employees.emp_status', ['active', 'expired'])
->whereIn('employee_polices.status', ['active', 'expired'])
->where('employees.is_active', 1)
->where('client_policy.id', $param)
->groupBy('employees.emp_code')
->get()
->getResultArray();
// print_r(db_connect()->getLastQuery()); die;
$dataForClientAndInsurer = $this->clientPolicyModel
->select("
clients.id AS client_id,
clients.client_name,
insurers.id AS insurer_id,
insurers.name AS insurer_name,
tpa.id AS tpa_id,
tpa.name AS tpa_name,
")
->join('clients', 'client_policy.client_id = clients.id', 'left')
->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->where('client_policy.id', $param)
->first();
$memberData = [];
// Respond based on the query result
if (!empty($data) || !empty($dataForClientAndInsurer)) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Data found',
'data' => $data,
'param' => $param,
'type' => $type,
'dataForClientAndInsurer' => $dataForClientAndInsurer,
'memberData' => $memberData
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'No Employee found',
'param' => $param,
'type' => $type,
'dataForClientAndInsurer' => $dataForClientAndInsurer,
'memberData' => $memberData
], 404);
}
}
// public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null, $ticket_type_id = null)
public function getTheEmpDataForClaimSearchByMobile()
{
$request = $this->request;
// Get parameters from GET request
$param = $request->getGet('param');
$type = $request->getGet('type') ?? 'mobile';
$client_policy_id = $request->getGet('client_policy_id');
$client_id = $request->getGet('client_id');
$ticket_type_id = $request->getGet('ticket_type_id');
// Validate required parameter
if (empty($param)) {
return $this->response->setJSON([
'status' => false,
'message' => 'Parameter is required'
])->setStatusCode(400);
}
$field_name = 'employees.' . $type;
$policy_type_id = [];
if ($ticket_type_id == 1) {
$policy_type_id = [2, 3, 4, 5];
} else if ($ticket_type_id == 2) {
$policy_type_id = [1];
} else if ($ticket_type_id == 3) {
$policy_type_id = [6];
} else if ($ticket_type_id == 4) {
$policy_type_id = [7];
}
// Construct the base query
$query = $this->clientPolicyModel
->select("
clients.id AS client_id,
clients.client_name,
insurers.id AS insurer_id,
insurers.name AS insurer_name,
tpa.id AS tpa_id,
tpa.name AS tpa_name,
employees.id AS emp_id,
employees.name AS emp_name,
employees.emp_code,
employees.mobile AS emp_mobile,
employees.email_corporate AS emp_email,
employees.relationship AS emp_relationship,
employee_polices.uhid AS policy_no,
employee_polices.tpa_id AS tpa_no,
employee_polices.client_policy_id AS policy_id
")
->join('clients', 'client_policy.client_id = clients.id')
->join('insurers', 'client_policy.insurer_id = insurers.id')
->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
->join('employees', 'clients.id = employees.client_id')
->join('employee_polices', 'employees.id = employee_polices.employee_id AND client_policy.id = employee_polices.client_policy_id')
->where('client_policy.is_active', 1)
->where('insurers.is_active', 1)
->where('tpa.is_active', 1)
->where('employees.is_active', 1)
->whereIn('employees.emp_status', ['active', 'expired'])
->where('employees.relationship', "Self")
->where('employee_polices.is_active', 1)
->whereIn('employee_polices.status', ['active', 'expired'])
->where($field_name, $param);
if (!empty($client_id)) {
$query->where('employees.client_id', $client_id);
}
if (!empty($client_policy_id)) {
$query->where('employee_polices.client_policy_id', $client_policy_id);
}
if ($policy_type_id != null) {
$query->whereIn('client_policy.policy_type_id', $policy_type_id);
}
$query->groupBy('employees.id')
->orderBy('employees.id', 'DESC');
$data = $query->get()->getRowArray();
// print_r(db_connect()->getLastQuery()); die;
$memberData = [];
$dataForClientAndInsurer = [];
// $acms = db_connect()->table('user_profiles')
// ->select('user_profiles.id, user_profiles.first_name')
// ->where('user_profiles.is_active', 1)
// ->where('user_profiles.role', 3)
// ->get()
// ->getResultArray();
if (!empty($data) && count($data) > 0) {
$memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $client_policy_id, $client_id);
$acms_datas = $this->employeeModel->getAcmUsingClientID($data['client_id']);
// if(!empty($acms_datas)){
// $acms = $acms_datas;
// }
} else {
$acms_datas = "";
}
// Respond based on the query result
if (!empty($data)) {
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'Data found',
'data' => $data,
'param' => $param,
'client_policy_id' => $client_policy_id,
'type' => $type,
'dataForClientAndInsurer' => $dataForClientAndInsurer,
'memberData' => $memberData,
'acms' => $acms_datas,
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 404,
'message' => 'No Employee found',
'param' => $param,
'client_policy_id' => $client_policy_id,
'type' => $type,
'dataForClientAndInsurer' => $dataForClientAndInsurer,
'memberData' => $memberData,
'acms' => $acms_datas
], 200);
}
}
// -----------------------------------------------------------------------------------------------------
public function updateRenewalData()
{
$db = db_connect();
$renewalData = $db->table('old_renewal_data_copy')
->where('client_id IS NOT NULL')
->where('is_inserted != 1')
->get()
->getResultArray();
// dd($renewalData);
$successData = [];
foreach ($renewalData as $key => $value) {
// Get branch_id properly
$branch = $this->clientBranchModel->where('client_id', $value['client_id'] ?? 0)->first();
// kint::dump($branch);
$value['branch_id'] = $branch['id'] ?? null;
// Fix vehicle_id key (previously "vehicel_id")
$value['vehicle_id'] = null;
if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) {
$value['vehicle_id'] = $this->prepareVehicleData($value);
}
// Process client policy, policy transaction, and co-share details
$value['client_policy_id'] = $this->prepareClientPolicy($value);
$value['pt_id'] = $this->preparePolicyData($value);
$value['pt_co_id'] = $this->preparePtCoShareDetails($value);
// Update is_inserted field in DB
$db->table('old_renewal_data_copy')
->where('id', $value['id'])
->set(['is_inserted' => 1])
->update();
$successData[] = ['id' => $value['id'], 'client' => $value['insured']];
}
kint::dump($successData);
}
public function updateRenewalInsurerData()
{
$db = db_connect();
$renewalData = $db->table('old_renewal_data_copy')
->where('insurer_id IS NULL')
->get()
->getResultArray();
// dd($renewalData);
$successData = [];
foreach ($renewalData as $key => $value) {
$insurer_data = $this->insurerModel->where('name', $value['insurer_name'])->where('is_active', 1)->first();
if (!empty($insurer_data)) {
$insurer_branch_data = $this->insurerBranchModel->where('branch_name', $value['insurer_branch'])->first();
if (!empty($insurer_branch_data)) {
$branch = $this->insurerBranchModel->where('insurer_id', $insurer_data['id'] ?? 0)->first();
$value['insurer_id'] = $insurer_data['id'] ?? null;
$value['insurer_branch_id'] = $branch['id'] ?? null;
} else {
$value['insurer_id'] = $insurer_data['id'] ?? null;
$value['insurer_branch_id'] = $this->prepareInsurerBranch($value);
}
} else {
$value['insurer_id'] = $this->prepareinsurer($value);
$value['insurer_branch_id'] = $this->prepareInsurerBranch($value);
}
// Update is_inserted field in DB
$db->table('old_renewal_data_copy')
->where('id', $value['id'])
->set([
'insurer_id' => $value['insurer_id'],
'insurer_branch_id' => $value['insurer_branch_id'],
])
->update();
$successData[] = ['id' => $value['id'], 'insurer' => $value['insurer_name'], 'insurer_id' => $value['insurer_id'], 'insurer_branch_id' => $value['insurer_branch_id'],];
}
kint::dump($successData);
}
public function updateRenewalDataNotExistingClient()
{
$limit = $this->request->getGet('limit') ?? 10;
$group = $this->request->getGet('group') ?? 2;
$db = db_connect();
$renewalData = $db->table('old_renewal_data_copy')
->where('client_id IS NULL')
->where('is_inserted = 0')
->where('client_type_id', $group)
// ->limit($limit)
->get()
->getResultArray();
// dd($renewalData);
$successData = [];
foreach ($renewalData as $key => $value) {
$client_data = $this->clientModel->where('client_name', $value['insured'])->where('is_active', 1)->first();
if (!empty($client_data)) {
$branch = $this->clientBranchModel->where('client_id', $client_data['id'] ?? 0)->first();
$value['branch_id'] = $branch['id'] ?? null;
$value['client_id'] = $client_data['id'] ?? null;
} else {
$value['client_id'] = $this->prepareClient($value);
if ($value['client_type_id'] == 1) {
$value['branch_id'] = $this->prepareClientBranch($value);
}
}
// Fix vehicle_id key (previously "vehicel_id")
if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) {
$value['vehicle_id'] = $this->prepareVehicleData($value);
} else {
$value['vehicle_id'] = 0;
}
// Process client policy, policy transaction, and co-share details
$value['client_policy_id'] = $this->prepareClientPolicy($value);
$value['pt_id'] = $this->preparePolicyData($value);
$value['pt_co_id'] = $this->preparePtCoShareDetails($value);
// Update is_inserted field in DB
$db->table('old_renewal_data_copy')
->where('id', $value['id'])
->set(['is_inserted' => 1])
->update();
$successData[] = ['id' => $value['id'], 'client' => $value['insured'], 'vehicle_id' => $value['vehicle_id']];
}
kint::dump($successData);
}
private function preparePolicyData($renewalData)
{
$data = [
'issuer' => $renewalData['issuer_type_id'] ?? null,
'client_id' => $renewalData['client_id'] ?? null,
'client_branch_id' => $renewalData['branch_id'] ?? 0,
'vehicle_id' => $renewalData['vehicle_id'] ?? null,
'insurer_id' => $renewalData['insurer_id'] ?? null,
'insurer_branch_id' => $renewalData['insurer_branch_id'],
'tpa_id' => null,
'tpa_branch_id' => null,
'policy_type_id' => $renewalData['policy_type_id'] ?? null,
'client_policy_id' => $renewalData['client_policy_id'] ?? null,
'issue_type' => 1,
'source_client_policy_id' => null,
'policy_no' => $renewalData['policy_no'] ?? null,
'cd_ac_no' => null,
'policy_issue_date' => $renewalData['date_date_of_issue'],
'policy_start_date' => $renewalData['date_policy_start_date'],
'policy_end_date' => $renewalData['date_policy_end_date'],
'action_type' => 'inception',
'endorsement_no' => null,
'data_received_date' => null,
'closure_date' => null,
'emp_count' => null,
'dependent_count' => null,
'revenue_type' => $renewalData['revenue_type'] ?? null,
'co_share' => 0,
'pre_payable_by' => 1,
'bro_payable_by' => 1,
'tsi' => '500000',
'status' => 'completed',
'ct_status' => 0,
'is_active' => 1,
'co_broking_status' => null,
'installment' => 0,
'installment_data' => null,
'location' => null,
'links' => null,
'stage' => null,
'etat' => null,
'etat_band' => null,
'edate' => null,
'renewal_date' => null,
'rollover_date' => null,
'policy_holder_name' => $renewalData['insured'],
'same_as_proposer' => 1, // 1 - Yes, 0 - No
'ref' => $renewalData['ref'],
'spl' => null,
'fund_received' => null,
'listed_insurers' => null,
'ppteam' => null,
'endorse_eff_date' => null,
'month' => '2025-02-01',
'sales_generated_by' => null,
'serviced_by' => null,
'ct_type' => 1,
'ct_tran_id' => null,
'remarks' => null,
'cd_ac_pk' => $renewalData['cd_ac_pk'] ?? null,
'install_due_date' => null,
'policy_with_corr' => 0
];
// kint::dump($data);
// dd($data);
$policyTransactionModel = new PolicyTransactionModel();
$id = $policyTransactionModel->insert($data);
return $id;
}
private function prepareVehicleData($renewalData)
{
$VehicleModel = new VehicleModel();
if ($renewalData['client_type_id'] == 1) {
$veh_no = explode(" ", $renewalData['insured'])[0] . "_veh_no";
} else {
$veh_no = $renewalData['insured'] . "_veh_no";
}
$vehicleData = $VehicleModel->where('owner', $renewalData['client_id'])
->where('is_active', 1)
->findAll();
if (!empty($vehicleData)) {
$increment = count($vehicleData);
$veh_no = $increment . "_" . $veh_no;
}
$vehicleData = [
'vehicle_no' => $veh_no,
'type' => null,
'description' => null,
'owner' => $renewalData['client_id'], // client_id
'branch_id' => $renewalData['client_type_id'] == 1 ? $renewalData['branch_id'] : 0, // client_branch_id
'old_owner' => null,
'rc' => null,
];
// dd($vehicleData);
$id = $VehicleModel->insert($vehicleData);
return $id;
}
private function preparePtCoShareDetails($renewalData)
{
$pt_co_share_details = [
'pt_id' => $renewalData['pt_id'],
'insurer_id' => $renewalData['insurer_id'],
'insurer_branch_id' => $renewalData['insurer_branch_id'],
'co_share_type' => 0,
'co_share_per' => 0.00,
'bp_amt' => 0.00,
'bp_gst_amt' => 0.00,
'bp_igst' => 0,
'bp_sgst' => 0,
'bp_cgst' => 0,
'tp_amt' => 0.00,
'tp_gst_amt' => 0.00,
'tp_igst' => 0.00,
'tp_sgst' => 0.00,
'tp_cgst' => 0.00,
'tep_amt' => 0.00,
'tep_gst_amt' => 0.00,
'tep_igst' => 0.00,
'tep_sgst' => 0.00,
'tep_cgst' => 0.00,
'agreed_amt' => 0.00,
'agreed_bp_per' => 0.00,
'agreed_tp_per' => 0.00,
'agreed_tep_per' => 0.00,
'standerd_bp_per' => 0.00,
'standerd_tp_per' => 0.00,
'standerd_tep_per' => 0.00,
'actual_bp_amt' => 0.00,
'actual_tp_amt' => 0.00,
'actual_tep_amt' => 0.00,
'actual_bp_per' => 0.00,
'actual_tp_per' => 0.00,
'actual_tep_per' => 0.00,
'actual_bp_brokerage_amt' => 0.00,
'actual_tp_brokerage_amt' => 0.00,
'actual_tep_brokerage_amt' => 0.00,
'reward' => 0.00,
'exp_amt' => 0.00,
'variance' => 0.00,
'remark' => null,
'cd_ac_no' => null,
'amount' => 0.00,
'stamp_duty' => 0.00,
'gst_type' => 0,
'cop_amt' => 0.00,
'statement_id' => 0,
'follower_policy_no' => $renewalData['policy_no'],
'non_comm_per_amt' => 0.00
];
$PTCOShareDetailsModel = new PTCOShareDetailsModel();
$id = $PTCOShareDetailsModel->insert($pt_co_share_details);
return $id;
}
private function prepareClientPolicy($renewalData)
{
$client_policy = [
'client_id' => $renewalData['client_id'],
'client_branch_id' => $renewalData['branch_id'] ?? 0,
'policy_type_id' => $renewalData['policy_type_id'],
'insurer_id' => $renewalData['insurer_id'],
'insurer_branch_id' => $renewalData['insurer_branch_id'],
'tpa_id' => null,
'tpa_branch_id' => null,
'policy_start_date' => $renewalData['date_policy_start_date'],
'policy_end_date' => $renewalData['date_policy_end_date'],
'policy_no' => $renewalData['policy_no'],
'cd_ac_no' => null,
'policy_status' => 1,
'policy_terms' => null,
'is_addon' => 1,
'base_policy' => null,
'inception_type' => 1,
'open_for_enrollment' => 0,
'gst' => 18.00,
'enrolment_visibility' => 1,
'open_date' => null,
'close_date' => null,
'reminder_date' => null,
'disclaimer' => null,
'is_member_modify_allowed' => 0,
'cd_ac_pk' => $renewalData['cd_ac_pk'],
'is_lgbtq' => 0
];
$ClientPolicyModel = new ClientPolicyModel();
$id = $ClientPolicyModel->insert($client_policy);
return $id;
}
private function prepareClientBranch($renewalData)
{
$branch_code = "BRANCH001";
$short_name = explode(" ", $renewalData['insured'])[0];
$unit = $short_name . " - " . $branch_code;
$clientBranchData = [
'client_id' => $renewalData['client_id'],
'branch_name' => "Branch 1",
'branch_code' => $branch_code,
'city' => null,
'district' => null,
'state' => null,
'pincode' => null,
'address1' => null,
'address2' => null,
'gst' => null,
'sez' => 0,
'is_active' => 1,
'units' => $unit
];
$ClientBranchModel = new ClientBranchModel();
$id = $ClientBranchModel->insert($clientBranchData);
return $id;
}
private function prepareClient($renewalData)
{
if ($renewalData['client_type_id'] == 1) {
$short_name = explode(" ", $renewalData['insured'])[0];
} else {
$short_name = $renewalData['insured'];
}
$clientData = [
'client_type' => $renewalData['client_type_id'],
'entity_type_id' => null,
'client_name' => $renewalData['insured'],
'short_name' => $short_name,
'cost_center' => null,
'client_code' => null, // Auto-generated
'pan' => null,
'gst' => null,
'address1' => null,
'address2' => null,
'city' => null,
'state' => null,
'pincode' => null,
'is_download_btn' => 0, // Assuming a default value if not specified
'client_logo' => null,
'created_by' => null,
'created_at' => null, // Will be set automatically by MySQL
'updated_by' => null,
'updated_at' => null, // Will be set automatically by MySQL
'is_active' => 1, // Default value is 1
'common_mails' => null,
'hr_mails' => null,
'mail_domain' => null,
'reply_to' => null,
'dob' => null,
'aadhar' => null,
'reference' => null,
'phone' => null,
'email' => null,
'addon_subheading' => null
];
$ClientModel = new ClientModel();
$id = $ClientModel->insert($clientData);
return $id;
}
private function prepareInsurerBranch($renewalData)
{
$insurerBranchData = [
'insurer_id' => $renewalData['insurer_id'],
'branch_name' => $renewalData['insurer_branch'],
'branch_code' => $renewalData['insurer_branch'],
'address1' => null,
'address2' => null,
'city' => null,
'district' => null,
'state' => null,
'pincode' => null,
];
$InsurerBranchModel = new InsurerBranchModel();
$id = $InsurerBranchModel->insert($insurerBranchData);
return $id;
}
private function prepareinsurer($renewalData)
{
$short_name1 = explode(" ", $renewalData['insurer_name'])[0];
$short_name2 = explode(" ", $renewalData['insurer_name'])[1];
$short_name = $short_name1 . ' ' . $short_name2;
$insurerData = [
'type' => "pvt",
'category' => "general",
'addition_add_day' => 0,
'deletion_add_day' => 0,
'name' => $renewalData['insurer_name'],
'short_name' => $short_name,
'insurer_logo' => null,
'is_multi_event' => 0, // Default is 0
];
$InsurerModel = new InsurerModel();
$id = $InsurerModel->insert($insurerData);
return $id;
}
private function reorderProposalsByInsurerTotal(array $data): array
{
Kint::dump($data);
if (!isset($data['premium_data']['data'])) return $data;
$original = $data['premium_data']['data'];
$proposals = [];
$others = [];
$emptyKeyData = [];
foreach ($original as $key => $value) {
// Match only keys that look like 'Proposal X'
if (preg_match('/^Proposal\s+\d+$/', $key)) {
// Get the insurer entry (not 'Quote Asked')
foreach ($value as $subKey => $subVal) {
if ($subKey !== 'Quote Asked' && isset($subVal['Total'])) {
$proposals[$key] = $value;
break;
} else {
$proposals[$key] = $value;
}
}
} else {
if ($key === '' && isset($value['']) && is_array($value[''])) {
// Capture empty key to push it later
$emptyKeyData[$key] = $value;
} else {
$others[$key] = $value;
}
}
}
// dd($proposals, $others, $emptyKeyData);
// Sort proposals by their insurer's total
uasort($proposals, function ($a, $b) {
$totalA = 0;
$totalB = 0;
foreach ($a as $key => $val) {
if ($key !== 'Quote Asked' && isset($val['Total'])) {
$totalA = floatval($val['Total']);
break;
}
}
foreach ($b as $key => $val) {
if ($key !== 'Quote Asked' && isset($val['Total'])) {
$totalB = floatval($val['Total']);
break;
}
}
return $totalA <=> $totalB;
});
// Merge back the sorted proposals into the full structure
$data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData);
$data = $this->reorderProposalDataByPremiumOrder($data);
return $data;
}
private function reorderProposalDataByPremiumOrder(array $data): array
{
if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) {
return $data;
}
$premiumProposals = array_keys($data['premium_data']['data']);
$filteredProposals = [];
// Collect proposal keys that match the pattern "Proposal X"
foreach ($premiumProposals as $key) {
if (preg_match('/^Proposal\s+\d+$/', $key) && isset($data['proposal_data']['over_all_column_data'][$key])) {
$filteredProposals[$key] = $data['proposal_data']['over_all_column_data'][$key];
}
}
// dd($premiumProposals, $filteredProposals);
$data['proposal_data']['over_all_column_data'] = $filteredProposals;
$data = $this->reorderProposalInHeaderAndData($data);
return $data;
}
private function reorderProposalInHeaderAndData(array $data): array
{
// Kint::dump($data);
$tableData = $data['table_data'];
$sortedProposalOrder = $data['proposal_data']['over_all_column_data'];
$headers = $tableData['headers'] ?? [];
$dataRows = $tableData['data'] ?? [];
// Step 1: Separate static and proposal headers
$staticHeaders = [];
$proposalHeaders = [];
$actionHeader = [];
foreach ($headers as $header) {
if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) {
$proposalHeaders[$header['parentHeader']] = $header;
} else {
if ($header['parentHeader'] == "Action") {
$actionHeader[] = $header;
} else {
$staticHeaders[] = $header;
}
}
}
// dd($staticHeaders, $proposalHeaders, $sortedProposalOrder);
// Step 2: Reorder headers
$reorderedHeaders = [];
foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
if (isset($proposalHeaders[$proposalKey])) {
$reorderedHeaders[] = $proposalHeaders[$proposalKey];
}
}
// print_rr($reorderedHeaders); die;
foreach ($reorderedHeaders as $key => &$value) {
$value['parentHeader'] = 'Proposal ' . ($key + 1);
}
unset($value);
$reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader);
// Step 3: Reorder each row's `data` by matching parentth
foreach ($dataRows as $dataRowIndex => &$row) {
$staticData = [];
$proposalData = [];
$actionData = [];
foreach ($row['data'] as $entry) {
if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) {
$proposalData[$entry['parentth']][] = $entry;
} else {
if ($entry['parentth'] == "Action") {
$actionData[] = $entry;
} else {
$staticData[] = $entry;
}
}
}
$reorderedProposalData = [];
foreach ($sortedProposalOrder as $proposalKey => $proposalValue) {
if (isset($proposalData[$proposalKey])) {
foreach ($proposalData[$proposalKey] as $entry) {
$reorderedProposalData[] = $entry;
}
}
}
$dubParTh = "";
$increament = 0;
foreach ($reorderedProposalData as $key => &$value) {
if ($dubParTh == $value['parentth']) {
$value['parentth'] = 'Proposal ' . ($increament);
} else {
$dubParTh = $value['parentth'];
$increament = $increament + 1;
$value['parentth'] = 'Proposal ' . ($increament);
}
}
unset($value);
$row['data'] = array_merge($staticData, $reorderedProposalData, $actionData);
}
$data['table_data']['headers'] = $reorderedHeaders;
$data['table_data']['data'] = $dataRows;
// dd('-----', $data);
$renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']);
$updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']);
$data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data'];
$data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data'];
return $data;
}
private function renumberProposalKeys(array $input): array
{
$result = [];
$counter = 1;
foreach ($input as $key => $value) {
if (strpos($key, 'Proposal') === 0) {
$newKey = 'Proposal ' . $counter++;
$result[$newKey] = $value;
} else {
$result[$key] = $value;
}
}
return $result;
}
public function saveApiData()
{
$receivedData = $this->request->getPost();
if (!empty($receivedData['id'])) {
$status = $this->clientApi->save($receivedData);
} else {
$status = $this->clientApi->insert($receivedData);
}
if ($status) {
return $this->respond(['status' => "Sucesss", 'message' => "Submitted Successfully"], 200);
} else {
return $this->respond(['status' => "Failed", 'message' => "Submission Faild"], 500);
}
}
public function sendToken()
{
$client_id = $this->request->getGet('client_id');
$token = ClientTokenHelper::generateKey($client_id);
if ($token) {
return $this->respond(['status' => 'success', 'token' => $token, 'message' => "Token Generated Successfully"], 200);
} else {
return $this->respond(['status' => "Failed", "message" => "Token Generation Failed, Try Again After some time"], 500);
}
}
// ---------------- HR ACCESS CONTROL -----------------------------------------------------------------------------------
public function viewHrAccessData()
{
$client_id = $this->request->getGet('client_id');
$data = $this->getHrAccessData($client_id);
// $data = [];
$html = view('hr_access_controll', $data);
return $this->respond([
'status' => true,
'code' => 200,
'data' => $html
], 200);
}
public function getHrAccessData($client_id)
{
$hrAccessData = [];
$post_client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first();
$hrAccessData['post_hr_data'] = $this->clientBranchModel
->select('lc.id as post_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail ,
client_branch.id as post_branch_id , client_branch.branch_name as post_branch_name')
->join('level_contacts lc', 'client_branch.id = lc.ref_id')
->where('client_branch.is_active', 1)
->where('lc.is_active', 1)
->where('lc.contact_type', 'client')
->where('client_branch.client_id', $client_id)
->findAll();
$hrAccessData['post_policy_data'] = $this->clientPolicyModel
->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status , client_policy.client_branch_id as branch_id')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
->where('client_policy.is_active', 1)
->where('client_policy.client_id', $client_id)
// ->orderBy('client_policy_id', 'desc')
->orderBy('client_policy.policy_status', 'desc')
->findAll();
$hrAccessData['post_cd_data'] = $this->CDMasterModel
->select('cd_master.id as cd_master_pk, cd_master.cd_ac_no as cd_account_no, insurers.name as insurer_name, insurers.short_name as insurer_short_name')
->join('insurers', 'cd_master.insurer_id = insurers.id')
->where('cd_master.is_active', 1)
->where('cd_master.client_id', $client_id)
->findAll();
$hrAccessData['hr_access_table_data'] = $this->HRAccessControlModel
->where('is_active', 1)
->where('post_client_id', $client_id)
->findAll();
try {
log_message('error', 'Attempting to connect to preDB...');
$db2 = \Config\Database::connect('preDB');
log_message('error', 'Connection to preDB successful.');
} catch (\Throwable $e) {
log_message('error', 'DB connection to preDB failed: ' . $e->getMessage());
$hrAccessData['pre_hr_data'] = [];
$hrAccessData['pre_policy_data'] = [];
$combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id , $pre_client_data['id']??'');
return $combinedHrAccessData;
}
$post_branch = $this->clientBranchModel->select('pre_branch_id')->where('client_id',$client_id)->get()->getResultArray()[0]??[];
$pre_client_data = $db2->table('client_branch cb')
->join('clients c', "c.id = cb.client_id")
->where('c.is_active',1)
->where('cb.is_active', 1)
->where('cb.id', $post_branch['pre_branch_id']??'')
->get()->getRowArray();
if (empty($pre_client_data)) {
$hrAccessData['pre_hr_data'] = [];
$hrAccessData['pre_policy_data'] = [];
$combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id , $pre_client_data['id']??'');
return $combinedHrAccessData;
}
$hrAccessData['pre_hr_data'] = $db2->table('client_branch')
->select('lc.id as pre_hr_id, lc.name as hr_name, lc.mobile as hr_mobile, lc.email as hr_mail
, client_branch.id as pre_branch_id , client_branch.branch_name as pre_branch_name ' )
->join('level_contacts lc', 'client_branch.id = lc.ref_id')
->where('client_branch.is_active', 1)
->where('lc.is_active', 1)
->where('lc.contact_type', 'client')
->where('client_branch.client_id', $pre_client_data['id'])
->get()
->getResultArray();
$hrAccessData['pre_policy_data'] = $db2->table('client_policy')
->select('client_policy.id as client_policy_id, client_policy.policy_no as policy_no, policy_type.policy_type, client_policy.policy_status , client_policy.client_branch_id as branch_id')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
->where('client_policy.is_active', 1)
->where('client_policy.client_id', $pre_client_data['id'])
// ->orderBy('client_policy_id', 'desc')
->orderBy('client_policy.policy_status', 'desc')
->get()
->getResultArray();
// dd($hrAccessData);
$combinedHrAccessData = $this->constructHrAccessData($hrAccessData, $client_id ,$pre_client_data['id']);
return $combinedHrAccessData;
}
public function constructHrAccessData($data, $client_id , $pre_client_id)
{
try{
$preHrs = $data['pre_hr_data'];
$postHrs = $data['post_hr_data'];
$hrAccessTableData = $data['hr_access_table_data'];
$merged = [];
// Merge based on mobile and email
foreach ($postHrs as $post) {
$found = false;
foreach ($preHrs as $index => $pre) {
if ( trim($post['hr_mobile']) == trim($pre['hr_mobile']) && trim($post['hr_mail']) == trim($pre['hr_mail']) ) {
$merged[] = [
'pre_hr_id' => $pre['pre_hr_id'],
'post_hr_id' => $post['post_hr_id'],
'hr_name' => $post['hr_name'],
'hr_mobile' => $post['hr_mobile'],
'hr_mail' => $post['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null,
'post_branch_name' => $post['post_branch_name'] ?? null
];
unset($preHrs[$index]); // remove matched pre_hr
$found = true;
break;
}
}
if (!$found) {
$merged[] = [
'pre_hr_id' => null,
'post_hr_id' => $post['post_hr_id'],
'hr_name' => $post['hr_name'],
'hr_mobile' => $post['hr_mobile'],
'hr_mail' => $post['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null ,
'post_branch_name' => $post['post_branch_name'] ?? null
];
}
}
// Remaining preHrs (not matched)
foreach ($preHrs as $pre) {
foreach ($merged as $value) {
if ( trim($pre['hr_mobile']) == trim($value['hr_mobile']) && trim($pre['hr_mail']) == trim($value['hr_mail']) ) {
continue 2; // Skip adding this pre_hr as it's already matched
}
}
$merged[] = [
'pre_hr_id' => $pre['pre_hr_id'],
'post_hr_id' => null,
'hr_name' => $pre['hr_name'],
'hr_mobile' => $pre['hr_mobile'],
'hr_mail' => $pre['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null ,
'post_branch_name' => $post['post_branch_name'] ?? null
];
}
$result = [];
if (empty($hrAccessTableData)) {
// No access data — fill result with hr data and other fields as null
foreach ($merged as $hr) {
$result[] = [
'hr_access_table_pk' => null,
'post_client_id' => $client_id ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => [],
'allowed_post_modules' => [],
'allowed_pre_policies' => [],
'allowed_active_policies' => [],
'allowed_cd' => [],
'hr_name' => $hr['hr_name'] ?? null,
'hr_mobile' => $hr['hr_mobile'] ?? null,
'hr_mail' => $hr['hr_mail'] ?? null,
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null
];
}
} else {
// First create a map of HR data by post_hr_id for quick lookup
$hrMap = [];
foreach ($merged as $hr) {
if(!empty($hr['post_hr_id'])){
$hrMap['post_hr_id_' . $hr['post_hr_id']] = $hr;
}else{
$hrMap['pre_hr_id_' . $hr['pre_hr_id']] = $hr;
}
}
// Process access data first
foreach ($hrAccessTableData as $access) {
$post_hr_id = $access['post_hr_id'];
$pre_hr_id = $access['pre_hr_id'];
if (empty($post_hr_id) && !empty($pre_hr_id)) {
$type_of_access_data = "PRE";
} elseif (!empty($post_hr_id) && empty($pre_hr_id)) {
$type_of_access_data = "POST";
} elseif (!empty($post_hr_id) && !empty($pre_hr_id)) {
$type_of_access_data = "POST&PRE";
} else {
$type_of_access_data = "UNKNOWN";
}
// Check if this HR exists in our merged data
if (isset($hrMap['post_hr_id_' . $post_hr_id])) {
$hr = $hrMap['post_hr_id_' . $post_hr_id];
$temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'] . $post_hr_id;
// Parse allowed modules
$allowed_modules = json_decode($access['allowed_modules'], true) ?? null;
$allowed_pre_modules = $allowed_modules['pre'] ?? [];
$allowed_post_modules = $allowed_modules['post'] ?? [];
$result[$temp_arr_key] = [
'hr_access_table_pk' => $access['id'] ?? null,
'post_client_id' => $access['post_client_id'] ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => $allowed_pre_modules,
'allowed_post_modules' => $allowed_post_modules,
'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [],
'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [],
'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [],
'hr_name' => $hr['hr_name'],
'hr_mobile' => $hr['hr_mobile'],
'hr_mail' => $hr['hr_mail'],
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null,
'type_of_access_data' => $type_of_access_data ?? null
];
// Remove from map so we know it's been processed
unset($hrMap['post_hr_id_' . $post_hr_id]);
}else if (isset($hrMap['pre_hr_id_' . $pre_hr_id])){
$hr = $hrMap['pre_hr_id_' . $pre_hr_id];
$temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'] . $post_hr_id;
// Parse allowed modules
$allowed_modules = json_decode($access['allowed_modules'], true) ?? null;
$allowed_pre_modules = $allowed_modules['pre'] ?? [];
$allowed_post_modules = $allowed_modules['post'] ?? [];
$result[$temp_arr_key] = [
'hr_access_table_pk' => $access['id'] ?? null,
'post_client_id' => $access['post_client_id'] ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => $allowed_pre_modules,
'allowed_post_modules' => $allowed_post_modules,
'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [],
'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [],
'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [],
'hr_name' => $hr['hr_name'],
'hr_mobile' => $hr['hr_mobile'],
'hr_mail' => $hr['hr_mail'],
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null,
'type_of_access_data' => $type_of_access_data ?? null
];
// Remove from map so we know it's been processed
unset($hrMap['pre_hr_id_' . $pre_hr_id]);
}
}
// Now process any remaining HRs that didn't have access records
foreach ($hrMap as $hr) {
$temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
$post_hr_id = $hr['post_hr_id'];
$pre_hr_id = $hr['pre_hr_id'];
if (empty($post_hr_id) && !empty($pre_hr_id)) {
$type_of_access_data = "PRE";
} elseif (!empty($post_hr_id) && empty($pre_hr_id)) {
$type_of_access_data = "POST";
} elseif (!empty($post_hr_id) && !empty($pre_hr_id)) {
$type_of_access_data = "POST&PRE";
} else {
$type_of_access_data = "UNKNOWN";
}
$result[$temp_arr_key] = [
'hr_access_table_pk' => null,
'post_client_id' => $client_id ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => [],
'allowed_post_modules' => [],
'allowed_pre_policies' => [],
'allowed_active_policies' => [],
'allowed_cd' => [],
'hr_name' => $hr['hr_name'] ?? null,
'hr_mobile' => $hr['hr_mobile'] ?? null,
'hr_mail' => $hr['hr_mail'] ?? null,
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null,
'type_of_access_data' => $type_of_access_data ?? null
];
}
}
// dd($result);
$resultData['hr_access_data'] = array_values($result);
$resultData['pre_policy_data'] = $data['pre_policy_data'];
$resultData['post_policy_data'] = $data['post_policy_data'];
$resultData['post_cd_data'] = $data['post_cd_data'];
return $resultData;
} catch (\Throwable $th) {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateInsurerStatement: Exception: " . $th->getMessage() . " --- Line: " . $th->getLine() . " --- Trace: " . $th->getTraceAsString());
return [];
$errorData = [
'message' => $th->getMessage(),
'file' => $th->getFile(),
'line' => $th->getLine(),
'code' => $th->getCode(),
'trace' => $th->getTraceAsString(),
'trace_array' => $th->getTrace(), // full array version (optional)
'function' => $th->getTrace()[0]['function'] ?? null,
'class' => $th->getTrace()[0]['class'] ?? null,
];
return ['status' => 'failed', 'code' => 500, 'message' => $th->getMessage(), 'error_data' => $errorData];
}
}
public function constructHrAccessData_OLD($data, $client_id , $pre_client_id)
{
// print_rr($data);die;
$preHrs = $data['pre_hr_data'];
$postHrs = $data['post_hr_data'];
$hrAccessTableData = $data['hr_access_table_data'];
$merged = [];
// Merge based on mobile and email
foreach ($postHrs as $post) {
$found = false;
foreach ($preHrs as $index => $pre) {
if ( trim($post['hr_mobile']) == trim($pre['hr_mobile']) && trim($post['hr_mail']) == trim($pre['hr_mail']) ) {
$merged[] = [
'pre_hr_id' => $pre['pre_hr_id'],
'post_hr_id' => $post['post_hr_id'],
'hr_name' => $post['hr_name'],
'hr_mobile' => $post['hr_mobile'],
'hr_mail' => $post['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null,
'post_branch_name' => $post['post_branch_name'] ?? null
];
unset($preHrs[$index]); // remove matched pre_hr
$found = true;
break;
}
}
if (!$found) {
$merged[] = [
'pre_hr_id' => null,
'post_hr_id' => $post['post_hr_id'],
'hr_name' => $post['hr_name'],
'hr_mobile' => $post['hr_mobile'],
'hr_mail' => $post['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null ,
'post_branch_name' => $post['post_branch_name'] ?? null
];
}
}
// Remaining preHrs (not matched)
foreach ($preHrs as $pre) {
foreach ($merged as $value) {
if ( trim($pre['hr_mobile']) == trim($value['hr_mobile']) && trim($pre['hr_mail']) == trim($value['hr_mail']) ) {
continue 2; // Skip adding this pre_hr as it's already matched
}
}
$merged[] = [
'pre_hr_id' => $pre['pre_hr_id'],
'post_hr_id' => null,
'hr_name' => $pre['hr_name'],
'hr_mobile' => $pre['hr_mobile'],
'hr_mail' => $pre['hr_mail'],
'pre_branch_id' => $pre['pre_branch_id'] ?? null,
'post_branch_id' => $post['post_branch_id'] ?? null ,
'post_branch_name' => $post['post_branch_name'] ?? null
];
}
// dd($merged);
$result = [];
if (empty($hrAccessTableData)) {
// No access data — fill result with hr data and other fields as null
foreach ($merged as $hr) {
$result[] = [
'hr_access_table_pk' => null,
'post_client_id' => $client_id ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => [],
'allowed_post_modules' => [],
'allowed_pre_policies' => [],
'allowed_active_policies' => [],
'allowed_cd' => [],
'hr_name' => $hr['hr_name'] ?? null,
'hr_mobile' => $hr['hr_mobile'] ?? null,
'hr_mail' => $hr['hr_mail'] ?? null,
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null
];
}
} else {
// First create a map of HR data by post_hr_id for quick lookup
$hrMap = [];
foreach ($merged as $hr) {
$hrMap[$hr['post_hr_id']] = $hr;
}
// Process access data first
foreach ($hrAccessTableData as $access) {
$post_hr_id = $access['post_hr_id'];
// Check if this HR exists in our merged data
if (isset($hrMap[$post_hr_id])) {
$hr = $hrMap[$post_hr_id];
$temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
// Parse allowed modules
$allowed_modules = json_decode($access['allowed_modules'], true) ?? null;
$allowed_pre_modules = $allowed_modules['pre'] ?? [];
$allowed_post_modules = $allowed_modules['post'] ?? [];
$result[$temp_arr_key] = [
'hr_access_table_pk' => $access['id'] ?? null,
'post_client_id' => $access['post_client_id'] ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => $allowed_pre_modules,
'allowed_post_modules' => $allowed_post_modules,
'allowed_pre_policies' => json_decode($access['allowed_pre_policies'], true) ?? [],
'allowed_active_policies' => json_decode($access['allowed_active_policies'], true) ?? [],
'allowed_cd' => json_decode($access['allowed_cd'], true) ?? [],
'hr_name' => $hr['hr_name'],
'hr_mobile' => $hr['hr_mobile'],
'hr_mail' => $hr['hr_mail'],
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null
];
// Remove from map so we know it's been processed
unset($hrMap[$post_hr_id]);
}
}
// Now process any remaining HRs that didn't have access records
foreach ($hrMap as $hr) {
$temp_arr_key = $hr['hr_mobile'] . $hr['hr_mail'];
$result[$temp_arr_key] = [
'hr_access_table_pk' => null,
'post_client_id' => $client_id ?? null,
'pre_hr_id' => $hr['pre_hr_id'] ?? null,
'post_hr_id' => $hr['post_hr_id'] ?? null,
'allowed_pre_modules' => [],
'allowed_post_modules' => [],
'allowed_pre_policies' => [],
'allowed_active_policies' => [],
'allowed_cd' => [],
'hr_name' => $hr['hr_name'] ?? null,
'hr_mobile' => $hr['hr_mobile'] ?? null,
'hr_mail' => $hr['hr_mail'] ?? null,
'pre_branch_id' => $hr['pre_branch_id'] ?? null,
'post_branch_id' => $hr['post_branch_id'] ?? null ,
'post_branch_name' => $hr['post_branch_name'] ?? null ,
'pre_client_id' => $pre_client_id ?? null
];
}
}
$resultData['hr_access_data'] = array_values($result);
$resultData['pre_policy_data'] = $data['pre_policy_data'];
$resultData['post_policy_data'] = $data['post_policy_data'];
$resultData['post_cd_data'] = $data['post_cd_data'];
return $resultData;
}
public function saveHrAccessData()
{
try {
// Step 1: Fetch and decode the JSON data
$client_id = $this->request->getPost('client_id');
$jsonData = $this->request->getPost('json');
$data = json_decode($jsonData, true);
if (!$data || !is_array($data)) {
log_message('error', 'Invalid or empty JSON in saveHrAccessData: ' . $jsonData);
return $this->respond(['status' => false,'code' => 400,'message' => 'Invalid JSON data provided.',], 400);
}
$success = [];
$errors = [];
$skippedCount = 0;
// Step 2: Loop and insert/update
foreach ($data as $index => $value) {
try {
// Decode allowed_modules and validate
$allowed_modules = json_decode($value['allowed_modules'], true);
if (empty($allowed_modules)) {
$skippedCount++;
continue; // Skip this record
}
// Format allowed_modules: { pre: [1], post: [2,3,4] }
$pre = in_array(1, $allowed_modules) ? [1] : [];
$post = array_values(array_filter($allowed_modules, fn($v) => $v !== 1));
$value['allowed_modules'] = json_encode(['pre' => $pre, 'post' => $post]);
$post_client_id = $value['post_client_id'];
$post_branch_id = $value['post_branch_id'];
$post_hr_id = $value['post_hr_id'];
// $preBranchId = $this->getPreBranchIdByPostBranchId($post_branch_id);
// if (!empty($preBranchId)) {
// $value['pre_branch_id'] = $preBranchId;
// $value['pre_client_id'] = $this->getPreClientIdByPreBranchId($preBranchId);
// $value["pre_hr_id"] = $this->getPreHrIdByPreBranchId($preBranchId);
// }
// INSERT or UPDATE
if (empty($value['pk']) || (int)$value['pk'] === 0) {
unset($value['pk']); // Prevent insert error
$insertedId = $this->HRAccessControlModel->insert($value);
if ($insertedId === false) {
throw new \Exception('Insert failed: ' . json_encode($this->HRAccessControlModel->errors()));
}
$success[] = "Inserted row at index {$index} with ID {$insertedId}.";
} else {
$update = $this->HRAccessControlModel->update($value['pk'], $value);
if ($update === false) {
throw new \Exception('Update failed for ID ' . $value['pk'] . ': ' . json_encode($this->HRAccessControlModel->errors()));
}
$success[] = "Updated row with ID {$value['pk']}.";
}
} catch (\Exception $e) {
log_message('error', 'HRAccess Save Error at index ' . $index . ': ' . $e->getMessage());
$errors[] = "Error at index {$index}: " . $e->getMessage();
}
}
// Step 3: If all rows were skipped (no allowed_modules)
if (count($data) === $skippedCount) {
return $this->respond([
'status' => false,
'code' => 422,
'message' => 'Please select at least one module for any user.',
], 422);
}
// Step 4: Final response
if (empty($errors)) {
$data = $this->getHrAccessData($client_id);
$html = view('hr_access_controll', $data);
return $this->respond([
'status' => true,
'code' => 200,
'message' => 'All records processed successfully.',
'details' => $success,
'data' => $html,
], 200);
} else {
return $this->respond([
'status' => false,
'code' => 207,
'message' => 'Some records failed to save.',
'success' => $success,
'errors' => $errors
], 207);
}
} catch (\Exception $e) {
log_message('critical', 'Fatal error in saveHrAccessData: ' . $e->getMessage());
return $this->respond([
'status' => false,
'code' => 500,
'message' => 'Unexpected server error.',
'error' => $e->getMessage()
], 500);
}
}
private function getPreClientIdByPreBranchId($pre_branch_id){
$db2 = \Config\Database::connect('preDB');
$pre_client_id = $db2->table('client_branch')->where('id',$pre_branch_id)->where('is_Active',1)->get()->getResultArray()[0]['client_id']??"";
return $pre_client_id;
}
private function getPreHrIdByPreBranchId($pre_branch_id){
$db2 = \Config\Database::connect('preDB');
$pre_hr_id = $db2->table('client_branch cb')
->select('lc.id')
->join('level_contacts lc','lc.ref_id = cb.id')
->where('lc.contact_type', 'client')
->where('cb.id',$pre_branch_id)->where('cb.is_Active',1)
->where('lc.is_Active',1)->get()->getResultArray()[0]['id']??"";
return $pre_hr_id;
}
private function getPreBranchIdByPostBranchId($post_branch_id){
$db = \Config\Database::connect();
$pre_branch_id = $db->table('client_branch')->where('id',$post_branch_id)->where('is_Active',1)->get()->getResultArray()[0]['pre_branch_id']??"";
return $pre_branch_id;
}
// ------------------- DEMO CLIENT FUNCTION --------------------------------------------------------------------------------
public function wipeDemoClient()
{
$this->myLogger->logme('error', "========================================");
$this->myLogger->logme('error', "WIPE DEMO CLIENT FUNCTION STARTED");
$this->myLogger->logme('error', "========================================");
$this->myLogger->logme('error', "Request Payload: " . json_encode($this->request->getPost() ?? []));
$client_id = $this->request->getPost('client_id');
if (empty($client_id)) {
$this->myLogger->logme('error', "ERROR: Client ID is required");
return $this->respond(['status' => false, 'message' => 'Client id required'], 404);
}
$this->myLogger->logme('error', "Client ID to wipe: " . $client_id);
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 1. CLIENT MODEL DELETION
// ========================================
$this->myLogger->logme('error', "1. PROCESSING CLIENT MODEL");
$client_data = $this->clientModel->where('id', $client_id)->where('is_active', 1)->first();
$this->myLogger->logme('error', " Found Client Data: " . json_encode($client_data ?? []));
if (!empty($client_data)) {
$is_deleted = $this->clientModel->where('id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete client record");
}
} else {
$this->myLogger->logme('error', " ✗ Client not found or inactive");
return $this->respond(['status' => false, 'message' => 'Client not found'], 404);
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 2. CLIENT RM MODEL DELETION
// ========================================
$this->myLogger->logme('error', "2. PROCESSING CLIENT RM MODEL");
$client_rm_data = $this->clientRMModel->where('client_id', $client_id)->first();
$this->myLogger->logme('error', " Found Client RM Data: " . json_encode($client_rm_data ?? []));
if (!empty($client_rm_data)) {
$is_deleted = $this->clientRMModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client RM data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Client RM record");
}
} else {
$this->myLogger->logme('error', " No Client RM data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 3. CLIENT KYC DOCS MODEL DELETION
// ========================================
$this->myLogger->logme('error', "3. PROCESSING CLIENT KYC DOCS MODEL");
$client_kyc_data = $this->clientKYCDocsModel->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Client KYC Records: " . count($client_kyc_data ?? []));
$this->myLogger->logme('error', " Client KYC Data: " . json_encode($client_kyc_data ?? []));
if (!empty($client_kyc_data)) {
$is_deleted = $this->clientKYCDocsModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client KYC Docs data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Client KYC Docs records");
}
} else {
$this->myLogger->logme('error', " No Client KYC Docs data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 4. CLIENT BRANCH MODEL DELETION
// ========================================
$this->myLogger->logme('error', "4. PROCESSING CLIENT BRANCH MODEL");
$client_branch_data = $this->clientBranchModel->where('client_id', $client_id)->findAll();
$branch_ids = array_column($client_branch_data, 'id') ?? [];
$this->myLogger->logme('error', " Found Client Branch Records: " . count($client_branch_data ?? []));
$this->myLogger->logme('error', " Branch IDs: " . json_encode($branch_ids));
$this->myLogger->logme('error', " Client Branch Data: " . json_encode($client_branch_data ?? []));
if (!empty($client_branch_data)) {
$is_deleted = $this->clientBranchModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client Branch data removed successfully");
// Delete related Level Contact data
if (!empty($branch_ids)) {
$this->myLogger->logme('error', " 4a. PROCESSING RELATED LEVEL CONTACT DATA");
$level_contact_data = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->findAll();
$this->myLogger->logme('error', " Found Level Contact Records: " . count($level_contact_data ?? []));
$this->myLogger->logme('error', " Level Contact Data: " . json_encode($level_contact_data ?? []));
$is_deleted = $this->levelContactModel->where('contact_type', 'client')->whereIn('ref_id', $branch_ids)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Level Contact data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Level Contact records");
}
} else {
$this->myLogger->logme('error', " No Branch IDs available for Level Contact deletion");
}
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Client Branch records");
}
} else {
$this->myLogger->logme('error', " No Client Branch data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 5. CLIENT POLICY MODEL DELETION
// ========================================
$this->myLogger->logme('error', "5. PROCESSING CLIENT POLICY MODEL");
$client_policy_data = $this->clientPolicyModel->where('client_id', $client_id)->findAll();
$policy_ids = array_column($client_policy_data, 'id') ?? [];
$this->myLogger->logme('error', " Found Client Policy Records: " . count($client_policy_data ?? []));
$this->myLogger->logme('error', " Policy IDs: " . json_encode($policy_ids));
$this->myLogger->logme('error', " Client Policy Data: " . json_encode($client_policy_data ?? []));
if (!empty($client_policy_data)) {
$is_deleted = $this->clientPolicyModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client Policy data removed successfully");
// Delete related Employee Policy data
if (!empty($policy_ids)) {
$this->myLogger->logme('error', " 5a. PROCESSING RELATED EMPLOYEE POLICY DATA");
$employee_policy_data = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->findAll();
$this->myLogger->logme('error', " Found Employee Policy Records: " . count($employee_policy_data ?? []));
$is_deleted = $this->employeePolicyModel->whereIn('client_policy_id', $policy_ids)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Employee Policy data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Employee Policy records");
}
} else {
$this->myLogger->logme('error', " No Policy IDs available for Employee Policy deletion");
}
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Client Policy records");
}
} else {
$this->myLogger->logme('error', " No Client Policy data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 6. EMPLOYEE MODEL DELETION
// ========================================
$this->myLogger->logme('error', "6. PROCESSING EMPLOYEE MODEL");
$employee_data = $this->employeeModel->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Employee Records: " . count($employee_data ?? []));
if (!empty($employee_data)) {
$is_deleted = $this->employeeModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Employee data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Employee records");
}
} else {
$this->myLogger->logme('error', " No Employee data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 7. CLIENT DEPOSIT MODEL DELETION
// ========================================
$this->myLogger->logme('error', "7. PROCESSING CLIENT DEPOSIT MODEL");
$client_deposit_data = $this->clientDepositModel->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Client Deposit Records: " . count($client_deposit_data ?? []));
$this->myLogger->logme('error', " Client Deposit Data: " . json_encode($client_deposit_data ?? []));
if (!empty($client_deposit_data)) {
$is_deleted = $this->clientDepositModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Client Deposit data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Client Deposit records");
}
} else {
$this->myLogger->logme('error', " No Client Deposit data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 8. POLICY PREMIUM 1 MODEL DELETION
// ========================================
$this->myLogger->logme('error', "8. PROCESSING POLICY PREMIUM 1 MODEL");
$policy_premium1_data = $this->policyPremium1Model->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Policy Premium 1 Records: " . count($policy_premium1_data ?? []));
if (!empty($policy_premium1_data)) {
$is_deleted = $this->policyPremium1Model->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Policy Premium 1 data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Policy Premium 1 records");
}
} else {
$this->myLogger->logme('error', " No Policy Premium 1 data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 9. POLICY PREMIUM 2 MODEL DELETION
// ========================================
$this->myLogger->logme('error', "9. PROCESSING POLICY PREMIUM 2 MODEL");
$policy_premium2_data = $this->policyPremium2Model->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Policy Premium 2 Records: " . count($policy_premium2_data ?? []));
if (!empty($policy_premium2_data)) {
$is_deleted = $this->policyPremium2Model->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Policy Premium 2 data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Policy Premium 2 records");
}
} else {
$this->myLogger->logme('error', " No Policy Premium 2 data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 10. NOTIFICATION MODEL DELETION
// ========================================
$this->myLogger->logme('error', "10. PROCESSING NOTIFICATION MODEL");
$notification_data = $this->notificationModel->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found Notification Records: " . count($notification_data ?? []));
$this->myLogger->logme('error', " Notification Data: " . json_encode($notification_data ?? []));
if (!empty($notification_data)) {
$is_deleted = $this->notificationModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Notification data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Notification records");
}
} else {
$this->myLogger->logme('error', " No Notification data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 11. CD MASTER MODEL DELETION
// ========================================
$this->myLogger->logme('error', "11. PROCESSING CD MASTER MODEL");
$cd_master_data = $this->CDMasterModel->where('client_id', $client_id)->findAll();
$this->myLogger->logme('error', " Found CD Master Records: " . count($cd_master_data ?? []));
$this->myLogger->logme('error', " CD Master Data: " . json_encode($cd_master_data ?? []));
if (!empty($cd_master_data)) {
$is_deleted = $this->CDMasterModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ CD Master data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete CD Master records");
}
} else {
$this->myLogger->logme('error', " No CD Master data found");
}
$this->myLogger->logme('error', "----------------------------------------");
// ========================================
// 12. POLICY TRANSACTION MODEL DELETION
// ========================================
$this->myLogger->logme('error', "12. PROCESSING POLICY TRANSACTION MODEL");
$policy_transaction_data = $this->policyTransactionModel->where('client_id', $client_id)->findAll();
$pt_ids = array_column($policy_transaction_data, 'id') ?? [];
$this->myLogger->logme('error', " Found Policy Transaction Records: " . count($policy_transaction_data ?? []));
$this->myLogger->logme('error', " Policy Transaction IDs: " . json_encode($pt_ids));
$this->myLogger->logme('error', " Policy Transaction Data: " . json_encode($policy_transaction_data ?? []));
if (!empty($policy_transaction_data)) {
$is_deleted = $this->policyTransactionModel->where('client_id', $client_id)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ Policy Transaction data removed successfully");
// Delete related PT CO Share data
if (!empty($pt_ids)) {
$this->myLogger->logme('error', " 12a. PROCESSING RELATED PT CO SHARE DATA");
$pt_co_share_data = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->findAll();
$this->myLogger->logme('error', " Found PT CO Share Records: " . count($pt_co_share_data ?? []));
$this->myLogger->logme('error', " PT CO Share Data: " . json_encode($pt_co_share_data ?? []));
$is_deleted = $this->PTCOShareDetailsModel->whereIn('pt_id', $pt_ids)->delete();
if ($is_deleted) {
$this->myLogger->logme('error', " ✓ PT CO Share data removed successfully");
} else {
$this->myLogger->logme('error', " ✗ Failed to delete PT CO Share records");
}
} else {
$this->myLogger->logme('error', " No Policy Transaction IDs available for PT CO Share deletion");
}
} else {
$this->myLogger->logme('error', " ✗ Failed to delete Policy Transaction records");
}
} else {
$this->myLogger->logme('error', " No Policy Transaction data found");
}
$this->myLogger->logme('error', "========================================");
$this->myLogger->logme('error', "WIPE DEMO CLIENT FUNCTION COMPLETED");
$this->myLogger->logme('error', "Client ID: " . $client_id . " - Successfully processed");
$this->myLogger->logme('error', "========================================");
return $this->respond(['status' => true, 'message' => 'Demo client data wiped successfully'], 200);
}
private function getClientlistFromPre()
{
$db2 = \Config\Database::connect('preDB');
$auto_fetch_client_list = $db2->table('clients')
->select('id,client_name')
->where('is_active', 1)
->get()->getResultArray() ?? [];
return $auto_fetch_client_list;
}
public function auto_fetch_branch()
{
$data = $this->request->getPost();
$db2 = \Config\Database::connect('preDB');
$auto_fetch_branch_list = $db2->table('client_branch')
->select('id,branch_name')
->where('client_id', $data['client_id'])
->where('is_active', 1)
->get()->getResultArray() ?? [];
return
empty($auto_fetch_branch_list)
? $this->response->setJSON([
'status' => false,
'message' => 'branch list is empty',
'data' => []
])->setStatusCode(400)
: $this->response->setJSON([
'status' => true,
'message' => 'branch list is found',
'data' => $auto_fetch_branch_list
])->setStatusCode(200);
}
public function auto_fetch_branch_details()
{
$data = $this->request->getPost();
$db2 = \Config\Database::connect('preDB');
$auto_fetch_branch_details = $db2->table('client_branch')
->where('client_id', $data['client_id'])
->where('id', $data['branch_id'])
->where('is_active', 1)
->get()->getResultArray() ?? [];
return empty($auto_fetch_branch_details)
? $this->response->setJSON([
'status' => false,
'message' => 'branch details is empty',
'data' => []
])->setStatusCode(400)
: $this->response->setJSON([
'status' => true,
'message' => 'branch details found',
'data' => $auto_fetch_branch_details
])->setStatusCode(200);
}
private function updatePreClientBranch($pre_branch_id, $post_branch_id, $operation)
{
$preDB = \Config\Database::connect('preDB');
if ($operation != 'create') {
$builder = $preDB->table('client_branch');
$builder->where('post_branch_id', $post_branch_id);
$builder->update(['post_branch_id' => null]);
}
$builder = $preDB->table('client_branch');
$builder->where('id', $pre_branch_id);
$builder->update(['post_branch_id' => $post_branch_id]);
return true;
}
public function createDefaultMailTemplate($client_id, $client_data)
{
$member_welcome_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_welcome_mail')->get()->getResultArray()[0] ?? [];
$member_remainder_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_reminder_mail')->get()->getResultArray()[0] ?? [];
$member_review_and_summary_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_review_and_summary_mail')->get()->getResultArray()[0] ?? [];
$member_ecard_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_ecard_mail')->get()->getResultArray()[0] ?? [];
$member_common_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'member_common_mail')->get()->getResultArray()[0] ?? [];
$hr_cd_insufficient_balance_mail_template = $this->notificationModel->where('client_id', NULL)->where('template_name', 'hr_cd_insufficient_balance_mail')->get()->getResultArray()[0] ?? [];
$default_member_welcome_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_welcome_mail',
'subject' => $member_welcome_mail_template['subject'] ?? '',
'mail_content' => $member_welcome_mail_template['mail_content'] ?? '',
'mail_content_json' => $member_welcome_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$default_member_remainder_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_reminder_mail',
'subject' => $member_remainder_mail_template['subject'] ?? '',
'mail_content' => $member_remainder_mail_template['mail_content'] ?? '',
'mail_content_json' => $member_remainder_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$default_member_review_and_summary_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_review_and_summary_mail',
'subject' => $member_review_and_summary_mail_template['subject'] ?? '',
'mail_content' => $member_review_and_summary_mail_template['mail_content'] ?? '',
'mail_content_json' => $member_review_and_summary_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$default_member_ecard_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_ecard_mail',
'subject' => $member_ecard_mail_template['subject'] ?? '',
'mail_content' => $member_ecard_mail_template['mail_content'] ?? '',
'mail_content_json' => $member_ecard_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$default_member_common_mail_template = [
'client_id' => $client_id,
'template_name' => 'member_common_mail',
'subject' => $member_common_mail_template['subject'] ?? '',
'mail_content' => $member_common_mail_template['mail_content'] ?? '',
'mail_content_json' => $member_common_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$hr_cd_insufficient_balance_mail_template = [
'client_id' => $client_id,
'template_name' => 'hr_cd_insufficient_balance_mail',
'subject' => $hr_cd_insufficient_balance_mail_template['subject'] ?? '',
'mail_content' => $hr_cd_insufficient_balance_mail_template['mail_content'] ?? '',
'mail_content_json' => $hr_cd_insufficient_balance_mail_template['mail_content_json'] ?? '',
'created_by' => get_session_userid(),
'created_at' => date('Y-m-d H:i:s'),
'updated_by' => null,
'updated_at' => date('Y-m-d H:i:s'),
'mail_content_copy' => null
];
$this->myLogger->logme('error', 'Default Mail Template Data ' . json_encode([
$default_member_welcome_mail_template,
$default_member_remainder_mail_template,
$default_member_review_and_summary_mail_template
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$default_templates_inserted = $this->notificationModel->insertBatch([
$default_member_welcome_mail_template,
$default_member_remainder_mail_template,
$default_member_review_and_summary_mail_template,
$default_member_ecard_mail_template,
$default_member_common_mail_template,
$hr_cd_insufficient_balance_mail_template,
]);
return $default_templates_inserted ? true : false;
}
public function downloadClientKycDocs_2($file_name = null)
{
if (!$file_name) {
return "No file specified.";
}
// Use absolute path to your upload folder
$file = WRITEPATH . 'uploads/client_kyc_documents/' . $file_name;
if (file_exists($file)) {
// download() takes the path as first param and null (or data) as second
return $this->response->download($file, null);
} else {
return "File not found at: " . $file;
}
}
}