nhance/app/Controllers/TestingController.php
2026-06-02 14:26:20 +05:30

1805 lines
64 KiB
PHP
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\Controllers\BaseController;
use App\Models\EmployeePolicyModel;
use App\Models\ClientPolicyModel;
use App\Models\TpaApiDataModel;
use App\Models\BatchFileModel;
use App\Models\InsurerBranchModel;
use App\Models\RFQModel;
use App\Models\EmployeeModel;
use App\Libraries\JobStatusService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use Dompdf\Dompdf;
use Dompdf\Options;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Firebase\JWT\JWT;
class TestingController extends BaseController
{
use ResponseTrait;
protected $myLogger;
protected $ClientPolicyModel;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->ClientPolicyModel = new ClientPolicyModel();
}
public function saveForm()
{
// Get JSON input
$data = $this->request->getPost();
// For testing: just return the received data
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => $data
]);
}
/**
* Get latest job status by job name.
* Supports:
* - GET -> ?job_name=...
* - POST -> job_name in form/json payload
*/
public function jobStatus()
{
$jobName = trim((string) ($this->request->getGet('job_name') ?? ''));
if ($jobName === '') {
$jobName = trim((string) ($this->request->getPost('job_name') ?? ''));
}
if ($jobName === '') {
$jsonPayload = $this->request->getJSON(true);
if (is_array($jsonPayload)) {
$jobName = trim((string) ($jsonPayload['job_name'] ?? ''));
}
}
$service = new JobStatusService();
$result = $service->getJobStatusByName($jobName);
$httpCode = 200;
if (($result['success'] ?? false) !== true) {
if ($jobName === '') {
$httpCode = 422;
} elseif (($result['message'] ?? '') === 'No job record found for given name.') {
$httpCode = 404;
} else {
$httpCode = 500;
}
}
return $this->response->setStatusCode($httpCode)->setJSON($result);
}
/**
* QA-only: invokes EmployeeController::updateTpaIdForNotInNhance.
* Routed under /util with authMVC — must be logged into the admin app.
*
* GET or POST: batch_file_id (required), file_id (optional, omit or 0 to skip file_id filter).
*/
public function qaUpdateTpaIdForNotInNhance()
{
$batchFileId = $this->request->getGet('batch_file_id');
if ($batchFileId === null || $batchFileId === '') {
$batchFileId = $this->request->getPost('batch_file_id');
}
$fileId = $this->request->getGet('file_id');
if ($fileId === null || $fileId === '') {
$fileId = $this->request->getPost('file_id');
}
if ($batchFileId === null || $batchFileId === '') {
return $this->response->setStatusCode(422)->setJSON([
'success' => false,
'message' => 'batch_file_id is required (query string or POST).',
]);
}
$params = [
'batch_file_id' => (int) $batchFileId,
'file_id' => ($fileId !== null && $fileId !== '') ? (int) $fileId : 0,
];
$employeeController = new EmployeeController();
$employeeController->initController($this->request, $this->response, service('logger'));
$result = $employeeController->updateTpaIdForNotInNhance($params);
return $this->response->setJSON(array_merge($result, ['params' => $params]));
}
/**
* QA-only: invokes EmployeeController::updateEmployeeDataFromTpa (Need to Review → DB updates, no Excel).
* Routed under /util with authMVC.
*
* GET or POST: batch_file_id (required).
*/
public function qaUpdateEmployeeDataFromTpa()
{
$batchFileId = $this->request->getGet('batch_file_id');
if ($batchFileId === null || $batchFileId === '') {
$batchFileId = $this->request->getPost('batch_file_id');
}
if ($batchFileId === null || $batchFileId === '') {
return $this->response->setStatusCode(422)->setJSON([
'success' => false,
'message' => 'batch_file_id is required (query string or POST).',
]);
}
$employeeController = new EmployeeController();
$employeeController->initController($this->request, $this->response, service('logger'));
$result = $employeeController->updateEmployeeDataFromTpa([
'batch_file_id' => (int) $batchFileId,
]);
return $this->response->setJSON($result);
}
public function testcli()
{
echo "hi";
$this->myLogger->logme('error', "test log");
echo "hi 2";
log_message('error', 'test message for log_message_function');
echo "hi 3";
}
public function generatePDF()
{
// Sample data - replace with your actual data source
$data = [
'NAME' => 'John Doe',
'GENDER' => 'Male',
'DOB' => '01/01/1990',
'RELATION' => 'Self',
'POLICY_NO' => 'POL123456789',
'TPA_ID' => 'TPA987654321',
'POLICY_START_DATE' => '01/01/2024',
'POLICY_DATE' => '31/12/2024',
'INSURER_NAME' => 'ABC Insurance Co.',
'TPA_NAME' => 'XYZ TPA Ltd.',
'FRONT_CARD' => base_url('assets/images/front-card.jpg'), // Your card images
'BACK_CARD' => base_url('assets/images/back-card.jpg'),
'LEVELS' => 'Level 1: 1800-XXX-XXXX<br>Level 2: support@company.com'
];
// Load the HTML template
$html = $this->loadTemplate($data);
// Configure DomPDF options
$options = new Options();
$options->set('isRemoteEnabled', true); // Enable loading of remote images
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', true);
$options->set('debugPng', false);
$options->set('debugKeepTemp', false);
$options->set('debugCss', false);
$options->set('debugLayout', false);
$options->set('debugLayoutLines', false);
$options->set('debugLayoutBlocks', false);
$options->set('debugLayoutInline', false);
$options->set('debugLayoutPaddingBox', false);
// Initialize DomPDF
$dompdf = new Dompdf($options);
// Load HTML content
$dompdf->loadHtml($html);
// Set paper size and orientation
$dompdf->setPaper('A4', 'landscape'); // or 'portrait'
// Render PDF
$dompdf->render();
// Output PDF to browser
$filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
$dompdf->stream($filename, ['Attachment' => true]); // Set to false for inline view
}
public function viewPDF()
{
// Same as generatePDF but with inline view
$data = [
'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari',
'GENDER' => 'Male',
'DOB' => '01/01/1990',
'RELATION' => 'Self',
'POLICY_NO' => '97000034230400000109_EX_Parental',
'TPA_ID' => 'TPA987654321',
'POLICY_START_DATE' => '01/01/2024',
'POLICY_DATE' => '31/12/2024',
'INSURER_NAME' => 'ZURICH KOTAK GTNERAL INSURANCE COIIPANY lNDlA LIMITED',
'TPA_NAME' => 'HealthIndia Insurance TPA Services Pvt. Ltd.',
'FRONT_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
'LEVELS' => 'Level 1: 1800-XXX-XXXX<br>Level 2: support@company.com'
];
$data2 = [
'NAME' => 'John Doe',
'GENDER' => 'Male',
'DOB' => '01/01/1990',
'RELATION' => 'Self',
'POLICY_NO' => 'POL123456789',
'TPA_ID' => 'TPA987654321',
'POLICY_START_DATE' => '01/01/2024',
'POLICY_DATE' => '31/12/2024',
'INSURER_NAME' => 'ABC Insurance Co.',
'TPA_NAME' => 'XYZ TPA Ltd.',
'FRONT_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
'BACK_CARD' => base_url() . ('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
'LEVELS' => 'Level 1: 1800-XXX-XXXX<br>Level 2: support@company.com'
];
$employeeController = new EmployeeController();
// $html = $employeeController->generateIDCardForEmployeeUsingDom('LfpH3R');
$html = $this->loadTemplate($data2);
// print_r($html); die;
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
// $dompdf->loadHtml($html);
$dompdf->loadHtml('<style>@page { margin: 0; }</style>' . $html);
$dompdf->setPaper('A4', 'portrait');
// $dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
// $dompdf->stream($filename, ['Attachment' => true]); // Inline view
$dompdf->stream($filename, ['Attachment' => false]); // Force download
}
private function loadTemplate($data)
{
// Load your HTML template
$template = file_get_contents(WRITEPATH . 'e_card_template/common.html');
// Replace placeholders with actual data
foreach ($data as $key => $value) {
$template = str_replace('{' . $key . '}', $value, $template);
}
return $template;
}
// not using and not working
public function viewPdfUsingMpdf()
{
$data = [
'NAME' => 'Korukonda Naga Venkata Ramalinga Satya Swarna Kumari',
'GENDER' => 'Male',
'DOB' => '01/01/1990',
'RELATION' => 'Self',
'POLICY_NO' => '97000034230400000109_EX_Parental',
'TPA_ID' => 'TPA987654321',
'POLICY_START_DATE' => '01/01/2024',
'POLICY_DATE' => '31/12/2024',
'INSURER_NAME' => 'ZURICH KOTAK GTNERAL INSURANCE COIIPANY lNDlA LIMITED',
'TPA_NAME' => 'HealthIndia Insurance TPA Services Pvt. Ltd.',
'FRONT_CARD' => base_url('public/uploads/template_bg/Nhance_Ecard_working_1_front_3.png'),
'BACK_CARD' => base_url('public/uploads/template_bg/Nhance_Ecard_working_1_Back_3.png'),
'LEVELS' => 'Level 1: 1800-XXX-XXXX<br>Level 2: support@company.com'
];
$html = $this->loadTemplate($data);
// Load mPDF
$mpdf = "";
// $mpdf = new \Mpdf\Mpdf([
// 'mode' => 'utf-8',
// 'format' => 'A4',
// 'margin_left' => 0,
// 'margin_right' => 0,
// 'margin_top' => 0,
// 'margin_bottom' => 0,
// 'tempDir' => __DIR__ . '/writable/mpdf'
// ]);
// Optional: Stretch background or images fully
// $html = '
// <style>
// body { margin:0; padding:0; }
// @page { margin:0; }
// </style>' . $html;
// $mpdf->WriteHTML($html);
// // Output inline (no download prompt)
// $filename = 'ecard_' . date('Y-m-d_H-i-s') . '.pdf';
// $mpdf->Output($filename, 'D');
/*
'I' = inline view in browser (no download prompt).
'D' = force download.
'F' = save to file.
'S' = return as string.
*/
}
public function getEmployeePolicyTypes($client_id, $emp_code, $emp_id)
{
$employeePolicy = new EmployeePolicyModel();
$data = $employeePolicy
->select('client_policy.policy_type_id')
->join('employees', 'employee_polices.employee_id = employees.id')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id')
->where('employees.is_active', 1)
->where('employees.emp_status', ['active', 'expired'])
->where('employee_polices.is_active', 1)
->where('employee_polices.status', ['active', 'expired'])
->where('employees.client_id', $client_id)
->where('employees.emp_code', $emp_code)
->groupBy('employee_polices.client_policy_id')
->findAll();
}
public function ptedfitdata($id)
{
$policy_transaction = new PolicyTransactionController();
$data = $policy_transaction->getInceptionDataForEdit($id);
// dd($data);
$insurerBranchModel = new InsurerBranchModel();
$insurer_branch = $insurerBranchModel->getInsurerBranchesWithInsurerNames();
$dataArray = $data['pt_co_share_details']; // Example
$cd_ac_pk = 'CD12345';
$role_id = 1;
$team_id = ['6'];
$insurer_branch = $insurer_branch;
return view('pt_calc_table', [
'dataArray' => $dataArray,
'cd_ac_pk' => $cd_ac_pk,
'role_id' => $role_id,
'team_id' => $team_id,
'insurer_branch' => $insurer_branch
]);
}
function generateInsurerTable($dataArray, $cd_ac_pk, $role_id, $team_id, $insurer_branch)
{
$html = '<table id="insurerTable" class="table table-bordered"><tbody>';
foreach ($dataArray as $index => $data) {
$disable_td = ($data['record_count'] > 0) ? 'readonly-select' : '';
$insurer = $data['insurer_branch_id'] . '-' . $data['insurer_id'];
$html .= '<tr id="table_tr_' . ($index + 1) . '">';
// Insurer selection
$html .= '<td><select class="form-control follow_insurer ' . $disable_td . '" name="follow_insurer_id[]">';
$html .= '<option value="">Select Insurer</option>';
foreach ($insurer_branch as $value) {
$selected = ($insurer == ($value['id'] . '-' . $value['insurer_id'])) ? 'selected' : '';
$html .= '<option value="' . $value['id'] . '-' . $value['insurer_id'] . '" ' . $selected . '>'
. $value['insurer_name'] . '-' . $value['branch_code'] . '</option>';
}
$html .= '</select></td>';
// Leader toggle
$checked = ($data['co_share_type'] == 1) ? 'checked' : '';
$html .= '<td><input type="checkbox" class="' . $disable_td . '" name="co_share_type[]" ' . $checked . '></td>';
// CD Account
$html .= '<td><select class="form-control follow_insurer_cd ' . $disable_td . '" name="cd_ac_no_for_child[]">';
$html .= '<option value="">Select CD No</option>';
$html .= '<option value="add_cd">+ Add CD No</option>';
if ($cd_ac_pk) {
$html .= '<option value="' . $cd_ac_pk . '" selected>' . $cd_ac_pk . '</option>';
}
$html .= '</select></td>';
// CD Amount
$html .= '<td><input type="text" readonly value="' . htmlspecialchars($data['cd_amount'] ?? '') . '"></td>';
// Example of follower policy no
$html .= '<td><input type="text" class="' . $disable_td . '" value="' . htmlspecialchars($data['follower_policy_no']) . '"></td>';
// Add other fields (bp_amt, tp_amt, gst, etc.)
$html .= '<td><input type="text" class="' . $disable_td . '" value="' . htmlspecialchars($data['bp_amt']) . '"></td>';
$html .= '<td><input type="text" class="' . $disable_td . '" value="' . htmlspecialchars($data['tp_amt']) . '"></td>';
$html .= '<td><input type="text" class="' . $disable_td . '" value="' . htmlspecialchars($data['tep_amt']) . '"></td>';
$html .= '<td><input type="hidden" name="co_share_id[]" value="' . htmlspecialchars($data['id']) . '"></td>';
$html .= '</tr>';
}
$html .= '</tbody></table>';
return $html;
}
public function viewRFQNonEb()
{
$insurerBranchModel = new InsurerBranchModel();
$data['page_name'] = "RFQ NON EB";
$data['insurer'] = $insurerBranchModel->getInsurerBranchesWithInsurerNames();
// dd($data);
return $this->loadLayout('view_rfq_non_eb_new', $data);
}
public function saverfq()
{
$json = $this->request->getPost('json');
$json = json_encode($json);
print_r($json);
// $data['lead_id'] = 10000;
// $data['json'] = $json;
// $rfq = new RFQModel();
// $rfq->insert($data);
}
public function exportExcel()
{
$rfq = new RFQModel();
$policy_data = $rfq->where('lead_id', 10000)->first();
// print_rr($policy_data['json']); die;
$policy_data = json_decode($policy_data['json'], true);
$policy_data = array_slice($policy_data, 0, -2);
print_rr($policy_data);
die;
dd($policy_data);
}
public function mapping_client_id_and_branch_id()
{
$post_clients_list = $this->getNonDuplicatePostClients();
$pre_clients_list = $this->getNonDuplicatePreClients();
$log_post_clients_list = $post_clients_list;
$log_pre_clients_list = $pre_clients_list;
log_message('error', 'Post Clients to be processed: ' . count($log_post_clients_list));
log_message('error', 'Pre Clients to be processed: ' . count($log_pre_clients_list));
$matched_Count = 0;
$expected_match_count = min(count($post_clients_list), count($pre_clients_list));
if (
!empty($pre_clients_list) &&
!empty($post_clients_list)
) {
$postDB = \Config\Database::connect();
$preDB = \Config\Database::connect('preDB');
foreach ($post_clients_list as $index => $post_client) {
foreach ($pre_clients_list as $index => $pre_client) {
if (trim($post_client['short_name']) == trim($pre_client['short_name'])) {
unset($log_post_clients_list[$index]);
unset($log_pre_clients_list[$index]);
$matched_Count++;
$postDB->table('clients')->where('id', $post_client['id'])->update(['pre_client_id' => $pre_client['id']]);
$preDB->table('clients')->where('id', $pre_client['id'])->update(['post_client_id' => $post_client['id']]);
// upto here we updated client_id in both dbs.
$post_branches = $postDB->table('client_branch')
->where('client_id', $post_client['id'])
->get()
->getResultArray() ?? [];
$pre_branches = $preDB->table('client_branch')
->where('client_id', $pre_client['id'])
->get()
->getResultArray() ?? [];
if (!empty($post_branches) && !empty($pre_branches)) {
foreach ($post_branches as $post_branch) {
$pre_branch = $preDB->table('client_branch')
->where('client_id', $pre_client['id'])
->where('branch_code', $post_branch['branch_code'])
->get()
->getRowArray() ?? [];
if (!empty($pre_branch)) {
$postDB->table('client_branch')->where('id', $post_branch['id'])->update(['pre_branch_id' => $pre_branch['id']]);
}
}
foreach ($pre_branches as $pre_branch) {
$post_branch = $postDB->table('client_branch')
->where('client_id', $post_client['id'])
->where('branch_code', $pre_branch['branch_code'])
->get()
->getRowArray() ?? [];
if (!empty($post_branch)) {
$preDB->table('client_branch')->where('id', $pre_branch['id'])->update(['post_branch_id' => $post_branch['id']]);
}
}
}
}
}
}
log_message('error', 'Expected Match Count : ' . $expected_match_count);
log_message('error', 'Total Matched Count: ' . $matched_Count);
log_message('error', 'Total UnMatched Count: ' . $expected_match_count - $matched_Count);
log_message('error', 'unmatched_reocrds');
$log_post_clients_list = array_values($log_post_clients_list);
$log_pre_clients_list = array_values($log_pre_clients_list);
if ((count($log_pre_clients_list) < count($log_post_clients_list))) {
log_message('error', "unmatched records count from pre- " . count($log_pre_clients_list));
log_message('error', print_r($log_pre_clients_list, true));
} else {
log_message('error', "unmatched records count from post - " . count($log_post_clients_list));
log_message('error', print_r($log_post_clients_list, true));
}
}
return $this->response->setJSON(['status' => 'success', 'message' => 'Client and Branch mapping completed.'])->setStatusCode(200);
}
private function getNonDuplicatePostClients()
{
$postDB = \Config\Database::connect();
$sql = "SELECT *
FROM clients AS post_clients
WHERE post_clients.client_type = 1
AND post_clients.is_active = 1
AND (post_clients.short_name NOT IN
(
SELECT ir_post_clients.short_name
FROM clients as ir_post_clients
WHERE ir_post_clients.client_type = 1
AND ir_post_clients.short_name IS NOT NULL
AND TRIM(ir_post_clients.short_name) <> ''
AND ir_post_clients.is_active = 1
GROUP BY ir_post_clients.short_name
HAVING COUNT(*) > 1)
)
ORDER BY post_clients.short_name";
$binds = [];
$query = $postDB->query($sql, $binds);
$results = $query->getResultArray() ?? [];
return $results;
}
private function getNonDuplicatePreClients()
{
$preDB = \Config\Database::connect('preDB');
$sql = "SELECT *
FROM clients AS pre_clients
WHERE pre_clients.client_type = 1
AND pre_clients.is_active = 1
AND (pre_clients.short_name NOT IN
(
SELECT ir_pre_clients.short_name
FROM clients as ir_pre_clients
WHERE ir_pre_clients.client_type = 1
AND ir_pre_clients.short_name IS NOT NULL
AND TRIM(ir_pre_clients.short_name) <> ''
AND ir_pre_clients.is_active = 1
GROUP BY ir_pre_clients.short_name
HAVING COUNT(*) > 1)
)
ORDER BY pre_clients.short_name";
$binds = [];
$query = $preDB->query($sql, $binds);
$results = $query->getResultArray() ?? [];
return $results;
}
public function membervalidation($lead_id = 329)
{
$lead_controll = new LeadsController();
// $lead_controll->getMemberDataExcelFileErrors();
$res = $lead_controll->memberDataListExcelFileFormatValidation(['lead_id' => $lead_id]);
dd($res);
}
private $firstNames = [
'Rajesh',
'Priya',
'Amit',
'Sneha',
'Vikram',
'Anjali',
'Rahul',
'Deepika',
'Sanjay',
'Kavita',
'Arun',
'Pooja',
'Manoj',
'Nisha',
'Suresh',
'Meera',
'Karthik',
'Divya',
'Ravi',
'Lakshmi',
'Anand',
'Swathi',
'Vijay',
'Rekha',
'Ashok',
'Sangeetha',
'Prakash',
'Uma',
'Ramesh',
'Vani',
'Kumar',
'Radha',
'Dinesh',
'Shanti',
'Ganesh',
'Parvati',
'Mohan',
'Sita',
'Arjun',
'Geetha'
];
private $lastNames = [
'Kumar',
'Sharma',
'Singh',
'Patel',
'Reddy',
'Nair',
'Iyer',
'Krishnan',
'Rao',
'Gupta',
'Verma',
'Agarwal',
'Joshi',
'Mehta',
'Desai',
'Pillai',
'Menon',
'Bhat',
'Naidu',
'Varma',
'Malhotra',
'Kapoor',
'Chopra',
'Saxena',
'Pandey',
'Mishra',
'Tiwari',
'Dubey',
'Sinha',
'Jain',
'Shah',
'Thakur'
];
private $relationships = ['Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother'];
private $genders = ['M', 'F'];
private $domains = ['gmail.com', 'yahoo.com', 'outlook.com', 'company.com', 'example.com'];
public function generateExcel()
{
// Increase execution time and memory for large files
ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Define headers
$headers = [
'Sl no',
'Emp Code',
'Name',
'Relationship',
'Gender',
'DOB',
'Age',
'Email',
'Mobile',
'SI',
'SI Enhancement',
'Proposed Sum Insured 1',
'Proposed Sum Insured 2',
'Proposed Sum Insured 3',
'Proposed Sum Insured 4'
];
// Set headers in row 1
$col = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($col . '1', $header);
$col++;
}
// Style the header row
$headerStyle = [
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4472C4']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]]
];
$sheet->getStyle('A1:O1')->applyFromArray($headerStyle);
// Generate 70,000 sample records
$totalRecords = 1000;
$batchSize = 1000;
for ($i = 1; $i <= $totalRecords; $i++) {
$row = $i + 1; // Start from row 2 (row 1 is header)
$record = $this->generateSampleRecord($i);
$sheet->setCellValue('A' . $row, $record['sl_no']);
$sheet->setCellValue('B' . $row, $record['emp_code']);
$sheet->setCellValue('C' . $row, $record['name']);
$sheet->setCellValue('D' . $row, $record['relationship']);
$sheet->setCellValue('E' . $row, $record['gender']);
$sheet->setCellValue('F' . $row, $record['dob']);
$sheet->setCellValue('G' . $row, $record['age']);
$sheet->setCellValue('H' . $row, $record['email']);
$sheet->setCellValue('I' . $row, $record['mobile']);
$sheet->setCellValue('J' . $row, $record['si']);
$sheet->setCellValue('K' . $row, $record['si_enhancement']);
$sheet->setCellValue('L' . $row, $record['proposed_si_1']);
$sheet->setCellValue('M' . $row, $record['proposed_si_2']);
$sheet->setCellValue('N' . $row, $record['proposed_si_3']);
$sheet->setCellValue('O' . $row, $record['proposed_si_4']);
// Clear memory every batch
if ($i % $batchSize == 0) {
$sheet->garbageCollect();
}
}
// Auto-size columns
foreach (range('A', 'O') as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// Generate filename
$filename = 'employee_data_70k_' . date('Y-m-d_His') . '.xlsx';
// Set headers for download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// Write file to output
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
// Clean up
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
}
private function generateSampleRecord($index)
{
$firstName = $this->firstNames[array_rand($this->firstNames)];
$lastName = $this->lastNames[array_rand($this->lastNames)];
$name = $firstName . ' ' . $lastName;
$relationship = $this->relationships[array_rand($this->relationships)];
$gender = $this->genders[array_rand($this->genders)];
// Generate random age between 18 and 65
$age = rand(18, 65);
// Calculate DOB based on age
$year = date('Y') - $age;
$month = str_pad(rand(1, 12), 2, '0', STR_PAD_LEFT);
$day = str_pad(rand(1, 28), 2, '0', STR_PAD_LEFT);
$dob = "{$day}-{$month}-{$year}";
// Generate employee code
$empCode = 'EMP' . str_pad($index, 6, '0', STR_PAD_LEFT);
// Generate email
$email = strtolower($firstName . '.' . $lastName . $index) . '@' . $this->domains[array_rand($this->domains)];
// Generate mobile number (Indian format)
$mobile = '+91' . rand(7000000000, 9999999999);
// Generate insurance amounts
$siOptions = [100000, 200000, 300000, 500000, 1000000];
$si = $siOptions[array_rand($siOptions)];
$si_enhancement = rand(0, 1) ? rand(50000, 200000) : 0;
$proposed_si_1 = $si + rand(100000, 500000);
$proposed_si_2 = $proposed_si_1 + rand(100000, 500000);
$proposed_si_3 = $proposed_si_2 + rand(100000, 500000);
$proposed_si_4 = $proposed_si_3 + rand(100000, 500000);
return [
'sl_no' => $index,
'emp_code' => $empCode,
'name' => $name,
'relationship' => $relationship,
'gender' => $gender,
'dob' => $dob,
'age' => $age,
'email' => $email,
'mobile' => $mobile,
'si' => $si,
'si_enhancement' => $si_enhancement,
'proposed_si_1' => $proposed_si_1,
'proposed_si_2' => $proposed_si_2,
'proposed_si_3' => $proposed_si_3,
'proposed_si_4' => $proposed_si_4
];
}
public function logo_renaming()
{
$directory = ROOTPATH . 'public/uploads/logo/';
if (!is_dir($directory)) {
die("Directory not found: $directory");
}
$files = scandir($directory);
$client_logo_files = $this->get_client_logo_files();
$rename_files = "";
$failed_rename_files = "";
foreach ($files as $file) {
// Skip system entries
if ($file === '.' || $file === '..') {
continue;
}
$oldPath = $directory . $file;
if (is_file($oldPath) && in_array(trim($file), $client_logo_files)) {
// Remove all spaces from filename
$newFileName = preg_replace('/\s+|\x{00A0}|\x{200B}|\x{200C}|\x{200D}|\x{FEFF}/u', '', $file);
$newPath = $directory . $newFileName;
// Only rename if the name changed
if ($oldPath !== $newPath) {
if (rename($oldPath, $newPath)) {
$rename_files .= "\n Renamed: $file$newFileName \n";
} else {
$failed_rename_files .= "\n Failed file: $file \n";
}
}
}
}
$dbUpdated = $this->update_client_logo_files();
log_message('error', 'Renamed Files: ' . $rename_files);
log_message('error', 'Failed Renames: ' . $failed_rename_files);
log_message('error', 'Database Update Status: ' . ($dbUpdated ? 'Success' : 'No changes made'));
return $this->response->setJSON([
'status' => 'success',
'message' => 'Logo renaming completed. kindly check backend logs for details',
'data' => [
'renamed_files' => $rename_files,
'failed_renames' => $failed_rename_files
]
])->setStatusCode(200);
}
public function get_client_logo_files()
{
$db = \Config\Database::connect();
$sql = "SELECT client_logo FROM clients WHERE client_logo IS NOT NULL AND TRIM(client_logo) <> '' ";
$query = $db->query($sql);
$results = $query->getResultArray() ?? [];
$files = array_map(function ($item) {
return trim($item['client_logo']);
}, $results);
return $files;
}
public function update_client_logo_files()
{
$db = \Config\Database::connect();
$sql = "UPDATE clients
SET client_logo = REPLACE(REPLACE(REPLACE(client_logo, CHAR(160), ''), ' ', ''), '\t', '')
WHERE client_logo IS NOT NULL
AND TRIM(client_logo) <> ''
";
$query = $db->query($sql);
return $db->affectedRows() > 0;
}
public function createDefaultMailTempalteInCrossDB()
{
$postDB = \Config\Database::connect(); // target DB
$preDB = \Config\Database::connect('preDB'); // source DB
// Templates to copy
$templateNames = [
'member_welcome_mail',
'member_reminder_mail',
'member_review_and_summary_mail'
];
foreach ($templateNames as $template) {
$exists = $postDB->table('notifications')
->where('client_id', NULL)
->where('template_name', $template)
->countAllResults();
if ($exists > 0) {
continue; // Skip if already inserted
}
// Fetch template from preDB
$templateData = $preDB->table('notifications')
->where('client_id', NULL)
->where('template_name', $template)
->get()
->getRowArray();
if (!empty($templateData)) {
// Remove ID to avoid duplicate primary key issues
unset($templateData['id']);
// Set created_by and timestamps if needed
$templateData['client_id'] = NULL;
$templateData['created_by'] = 1;
$templateData['cretaed_at'] = date('Y-m-d H:i:s');
$templateData['updated_by'] = NULL;
$templateData['updated_at'] = NULL;
// Insert into postDB
$postDB->table('notifications')->insert($templateData);
}
}
return $this->response->setJSON(['message'=>"Created Default Mail Tempalte In Cross DB "])->setStatusCode(200);
}
public function createDefaultMailTempalteInSameDB()
{
$postDB = \Config\Database::connect();
// Templates to copy
$templateNames = [
'member_welcome_mail',
'member_reminder_mail',
'member_review_and_summary_mail',
'member_common_mail',
'member_ecard_mail'
];
foreach ($templateNames as $template) {
$exists = $postDB->table('notifications')
->where('client_id', NULL)
->where('template_name', $template)
->countAllResults();
if ($exists > 0 ) {
continue; // Skip if already inserted
}
// Fetch template from preDB
$templateData = $postDB->table('notifications')
// this is where we want to replace 0 with the client id we want to replace
->where('client_id', 0)
// template_name from which you want to create a common template from templateNames array.
->where('template_name', $template)
->get()
->getRowArray();
if (!empty($templateData)) {
// Remove ID to avoid duplicate primary key issues
unset($templateData['id']);
// Set created_by and timestamps if needed
$templateData['client_id'] = NULL;
$templateData['created_by'] = 1;
$templateData['cretaed_at'] = date('Y-m-d H:i:s');
$templateData['updated_by'] = NULL;
$templateData['updated_at'] = NULL;
// Insert into postDB
$postDB->table('notifications')->insert($templateData);
}
}
return $this->response->setJSON(['message'=>"Created Default Mail Tempalte In Same DB "])->setStatusCode(200);
}
public function metaDashboardDemo()
{
// 🔐 Move this to .env in real projects
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$database_id = (int)$this->request->getGet('database_id') ?? 2;
$policy_id = $this->request->getGet('client_policy') ?? null;
$tpa_url = 'https://nsights.nhanceindia.in/public/dashboard/4babf324-6c1e-4c5a-adbb-1c80a0f545b1';
$policy_id = $policy_id ? $policy_id : 4687;
$payload = [
'resource' => [
// 'dashboard' => 1
'dashboard' => $database_id
],
'exp' => time() + (10 * 60), // 10 minutes
];
if(!empty($policy_id)){
$payload['params'] = (object)['client_policy' => $policy_id]; // MUST be object for Metabase
}else{
$payload['params'] = (object)[]; // MUST be object for Metabase
}
// dd($payload);
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// // You can either return token only
// return $this->response->setJSON([
// 'token' => $token,
// 'iframe_url' => "https://your-metabase-domain/embed/dashboard/{$token}#bordered=true&titled=true"
// ]);
if($this->request->getGet('api') == 1)
{
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in']
]);
}
return view('meta_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
public function apacheSuperSetDemo()
{
// echo 'Dta';die;
// 🔐 Move this to .env in real projects
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$database_id = (int)$this->request->getGet('database_id') ?? 2;
$policy_id = $this->request->getGet('client_policy') ?? null;
$tpa_url = 'https://nsights.nhanceindia.in/public/dashboard/4babf324-6c1e-4c5a-adbb-1c80a0f545b1';
$policy_id = $policy_id ? $policy_id : 4687;
$payload = [
'resource' => [
// 'dashboard' => 1
'dashboard' => 2
],
'exp' => time() + (10 * 60), // 10 minutes
];
if(!empty($policy_id)){
$payload['params'] = (object)['client_policy' => $policy_id]; // MUST be object for Metabase
}else{
$payload['params'] = (object)[]; // MUST be object for Metabase
}
// dd($payload);
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// // You can either return token only
// return $this->response->setJSON([
// 'token' => $token,
// 'iframe_url' => "https://your-metabase-domain/embed/dashboard/{$token}#bordered=true&titled=true"
// ]);
if($this->request->getGet('api') == 1)
{
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in']
]);
}
return view('apache_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
public function testingquerys()
{
$calendar = new \App\Libraries\GoogleCalendarService();
// Check if user is authenticated without passing tokens manually
if (!$calendar->isReady()) {
return $this->respond(['status' => 'failed', 'code' => '404' , 'message' => 'Google Access Token Expired'], 200);
}
$data = [
'summary' => 'Client Follow up',
'meeting_date' => '2026-02-22 10:00:00',
'description' => 'Visit Client place',
'emails' => ['surendarsuri30@gmail.com', 'vitvelz@gmail.com', 'venbalap2026@gmail.com', 'gowthamceline46@gmail.com']
];
try {
$response = $calendar->createEvent($data);
return $this->respond(['status' => 'success', 'code' => '200' , 'message' => 'Follow-up Saved', 'response' => $response], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed', 'code' => '500' , 'message' => 'Error: ' . $e->getMessage()], 200);
}
}
public function metaTpaDashboardDemo()
{
$METABASE_SECRET_KEY = getenv('METABASE_SECRET_KEY');
$policy_id = $this->request->getGet('client_policy') ?? 4687;
$client_policy_data = $this->ClientPolicyModel
->select('tpa.dashboard_id')
->join('tpa', 'client_policy.tpa_id = tpa.id')
->where('client_policy.id', $policy_id)
->first();
$database_id = isset($client_policy_data['dashboard_id']) ? (int) $client_policy_data['dashboard_id'] : null;
if (empty($database_id)) {
if ($this->request->getGet('api') == 1) {
return $this->respond([
'status' => 'failed',
'message' => 'There is no dashboard for this TPA.',
'data' => []
]);
}
return view('errors/404', [
'message' => 'There is no dashboard for this TPA.'
]);
}
$payload = [
'resource' => [
'dashboard' => $database_id
],
'exp' => time() + (10 * 60), // 10 minutes
'params' => (object) ['client_policy' => $policy_id ], // MUST be object for Metabase
];
$token = JWT::encode($payload, $METABASE_SECRET_KEY, 'HS256');
// dd($token);
if ($this->request->getGet('api') == 1) {
return $this->respond([
'status' => 'success',
'message' => 'Form data received successfully!',
'data' => [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in'
]
]);
}
return view('meta_dashboard_demo_one', [
'metabaseToken' => $token,
'metabaseUrl' => 'https://nsights.nhanceindia.in',
]);
}
/**
* Insert sample data into tpa_api_data for testing variance report (Not in NHANCE, Not in TPA, Need to Review).
* Uses client_policy (policy_status=1, is_active=1), employee_policies (active), and employees.
*
* @param int|null $client_policy_id Optional. If not provided, first eligible policy is used.
* @return \CodeIgniter\HTTP\ResponseInterface
*/
public function insertSampleTpaApiData($client_policy_id = null)
{
$db = \Config\Database::connect();
$clientPolicyModel = new ClientPolicyModel();
$employeePolicyModel = new EmployeePolicyModel();
$employeeModel = new EmployeeModel();
$tpaApiDataModel = new TpaApiDataModel();
$batchFileModel = new BatchFileModel();
// 1. Get policies: policy_status = 1, is_active = 1
$policyBuilder = $clientPolicyModel
->where('policy_status', 1)
->where('is_active', 1);
if ($client_policy_id !== null && $client_policy_id !== '') {
$policyBuilder->where('id', (int) $client_policy_id);
}
$policies = $policyBuilder->orderBy('id', 'ASC')->findAll();
if (empty($policies)) {
return $this->respond([
'status' => false,
'message' => 'No active client policy found (policy_status=1, is_active=1).',
'data' => [],
], 400);
}
$policy = $policies[0];
$client_policy_id = (int) $policy['id'];
$client_id = (int) $policy['client_id'];
$client_branch_id = !empty($policy['client_branch_id']) ? (int) $policy['client_branch_id'] : 0;
// 2. Get related employees from employee_policies (active) + employees
$empPolicies = $db->table('employee_polices ep')
->select('ep.id AS emp_policy_id, ep.employee_id, ep.tpa_id, e.emp_code, e.name, e.dob, e.gender, e.relationship')
->join('employees e', 'e.id = ep.employee_id')
->where('ep.client_policy_id', $client_policy_id)
->where('ep.is_active', 1)
->whereIn('ep.status', ['active', 'expired'])
->where('e.is_active', 1)
->get()
->getResultArray();
if (empty($empPolicies)) {
return $this->respond([
'status' => false,
'message' => 'No active employee policies found for this client policy.',
'data' => ['client_policy_id' => $client_policy_id],
], 400);
}
// 3. Create a test batch file so we have a file_id for tpa_api_data
$createdBy = function_exists('get_session_userid') ? get_session_userid() : 1;
$batchCode = 'TPA_SAMPLE_' . date('YmdHis') . '_' . bin2hex(random_bytes(4));
$batchFileId = $batchFileModel->insert([
'client_id' => $client_id,
'client_policy_id' => $client_policy_id,
'client_branch_id' => $client_branch_id,
'batch_code' => $batchCode,
'file_name' => 'sample_tpa_data_test_' . date('Y-m-d_His') . '.xlsx',
'insurer_or_tpa' => 'tpa',
'event_type' => 'api',
'actions' => 'fetch',
'status' => 'partially success',
'count' => 0,
'created_by' => $createdBy,
'is_active' => 1,
]);
if (!$batchFileId) {
return $this->respond([
'status' => false,
'message' => 'Failed to create test batch file.',
'data' => [],
], 500);
}
$file_id = (int) $batchFileId;
$tpaApiDataModel->skipValidation(true);
$inserted = ['not_in_nhance' => 0, 'need_to_review' => 0];
$toInsert = [];
// 4. Not in NHANCE: insert TPA records with emp_codes that do NOT exist in NHANCE for this policy
$fakeEmpCodes = ['TPA_SAMPLE_NOTINNHANCE_1', 'TPA_SAMPLE_NOTINNHANCE_2'];
foreach ($fakeEmpCodes as $i => $empCode) {
$toInsert[] = [
'file_id' => $file_id,
'emp_code' => $empCode,
'name' => 'Sample TPA Only ' . ($i + 1),
'dob' => '1990-01-' . str_pad((string)(15 + $i), 2, '0', STR_PAD_LEFT),
'relation' => 'Self',
'gender' => ($i % 2 === 0) ? 'M' : 'F',
'self' => 'Sample TPA Only ' . ($i + 1),
'tpa_id' => 'TPA' . (1000 + $i),
'age' => 32 + $i,
'is_active' => 1,
'desc' => 'Sample data Not in NHANCE',
'created_by'=> $createdBy,
];
$inserted['not_in_nhance']++;
}
// 5. Need to Review: same employee as in NHANCE but with different name/dob/gender
$needReview = array_slice($empPolicies, 0, min(2, count($empPolicies)));
foreach ($needReview as $emp) {
$dob = $emp['dob'];
if (is_string($dob) && preg_match('/^(\d{4})-(\d{2})-(\d{2})/', $dob, $m)) {
$altDob = $m[1] . '-' . $m[2] . '-' . str_pad((string)((int)$m[3] + 1), 2, '0', STR_PAD_LEFT);
} else {
$altDob = '1995-06-15';
}
$toInsert[] = [
'file_id' => $file_id,
'emp_code' => $emp['emp_code'],
'name' => '[TPA Altered] ' . ($emp['name'] ?? 'Unknown'),
'dob' => $altDob,
'relation' => $emp['relationship'] ?? 'Self',
'gender' => (strtoupper($emp['gender'] ?? 'M') === 'M') ? 'F' : 'M',
'self' => $emp['name'] ?? 'Unknown',
'tpa_id' => $emp['tpa_id'] ?? ('T' . $emp['employee_id']),
'age' => 30,
'is_active' => 1,
'desc' => 'Sample data Need to Review (mismatch)',
'created_by'=> $createdBy,
];
$inserted['need_to_review']++;
}
foreach ($toInsert as $row) {
$tpaApiDataModel->insert($row);
}
// Not in TPA: we do NOT insert those into tpa_api_data; NHANCE already has employees. So any employee
// we did not add to tpa_api_data will appear as "Not in TPA". We added only "Need to Review" and
// "Not in NHANCE" rows; the rest of NHANCE employees remain without TPA rows => they show as Not in TPA.
return $this->respond([
'status' => true,
'message' => 'Sample TPA API data inserted successfully.',
'data' => [
'file_id' => $file_id,
'client_policy_id' => $client_policy_id,
'client_id' => $client_id,
'batch_code' => $batchCode,
'inserted' => $inserted,
'not_in_tpa_note' => 'Employees in NHANCE that were not added to TPA data will appear as "Not in TPA" when you run the variance report for this file.',
],
], 200);
}
/**
* List employee count per client policy.
* No input parameters. Checks all client_policy records and counts linked employee_policies per policy.
*
* @return \CodeIgniter\HTTP\ResponseInterface
*/
public function listEmployeeCountByClientPolicy()
{
$db = \Config\Database::connect();
$rows = $db->table('client_policy cp')
->select('cp.id AS client_policy_id, COUNT(ep.id) AS employee_policy_count', false)
->join('employee_polices ep', 'ep.client_policy_id = cp.id', 'left')
->groupBy('cp.id')
->orderBy('cp.id', 'ASC')
->get()
->getResultArray();
$list = array_map(function ($row) {
return [
'client_policy_id' => (int) $row['client_policy_id'],
'employee_policy_count' => (int) $row['employee_policy_count'],
];
}, $rows);
return $this->respond([
'status' => true,
'message' => 'Employee count per client policy.',
'data' => $list,
], 200);
}
/**
* Test Wellness SSO token generation for Medi Assist (MediBuddy).
*
* This uses the token-based authentication details shared by Medi Assist:
* - Cipher: AES-256-CBC
* - Padding: PKCS7 (OpenSSL default)
* - Login URL: https://login.mediassist.in/SSOLogon.aspx?PartnerCorpId={0}&EncryptedSSO={1}
*
* Environment variables (recommended):
* - MEDIASSIST_WELLNESS_KEY
* - MEDIASSIST_WELLNESS_IV
* - MEDIASSIST_WELLNESS_PARTNER_CORP_ID
* - MEDIASSIST_WELLNESS_LOGIN_URL
*
* If env values are not present, sensible dummy defaults are used so that
* the function can still be exercised.
*/
public function testMediAssistWellnessOld()
{
// Configuration prefer environment variables, fall back to demo values
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$loginUrlTemplate = env('MEDIASSIST_WELLNESS_LOGIN_URL' );
$partnerCorpId = '15963';
$cipher_algorithm = 'AES-256-CBC';
// Plain SSO JSON payload, as per Medi Assist sample
$payload = [
'Id' => '15022',
'expiryTime' => time() + (10 * 60), // 10 minutes
'CPartnerId' => $partnerCorpId,
];
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// Derive a 32byte key (AES256) and 16byte IV from the provided strings
// $key = substr(hash('sha256', $keyString, true), 0, 32);
// $iv = substr(hash('md5', $ivString, true), 0, 16);
// Encrypt with AES256CBC + PKCS7 padding (OpenSSL default)
$cipherTextRaw = openssl_encrypt( $plainJson, $cipher_algorithm, $keyString, OPENSSL_RAW_DATA, $ivString);
if ($cipherTextRaw === false) {
return $this->respond([
'status' => false,
'message' => 'Encryption failed while generating Medi Assist wellness token.',
], 500);
}
// Base64 encode and URLencode for use as EncryptedSSO
$encryptedSSO = urlencode(base64_encode($cipherTextRaw));
// $encryptedSSO = rtrim(strtr(base64_encode($cipherTextRaw), '+/', '-_'), '=');
// Build the final login URL
$loginUrl = str_replace(['{0}', '{1}'], [$partnerCorpId, $encryptedSSO], $loginUrlTemplate);
return $this->respond([
'status' => true,
'message' => 'Medi Assist wellness test URL generated successfully.',
'data' => [
'loginUrl' => $loginUrl,
'encryptedSSO' => $encryptedSSO,
'plainPayload' => $payload,
],
], 200);
}
public function chartbrewDashboardDemo()
{
// 1. Configuration - Use a Chartbrew-specific Secret Key from .env
$chartbrew_base_url = "https://analytics.nhanceindia.in/report/my-first-dashboard-oHbWNWH0";
$chartbrew_secret = getenv('METABASE_SECRET_KEY'); // Ensure this is set in your .env
// 2. Get dynamic parameters (matching your screenshot's naming convention)
$policy_id = $this->request->getGet('client_policy_id') ?? 4687;
// 3. Define the Payload
// Note: 'sub' (Subject) should usually be the user ID or a unique identifier
// depending on Chartbrew's specific JWT requirements.
$payload = [
"sub" => [
"type" => "Project",
"id" => 4, // Integer type usually preferred
"sharePolicyId" => 4
],
"iat" => time(),
"exp" => time() + (10 * 60), // 10 minute expiration
];
// 4. Encode the JWT
// Make sure you have 'use Firebase\JWT\JWT;' at the top of your controller
$token = JWT::encode($payload, $chartbrew_secret, 'HS256');
// 5. Construct the URL
// We use http_build_query to ensure special characters are handled correctly
$params = [
'token' => $token,
'theme' => 'light',
'client_policy_id' => $policy_id
];
$url = $chartbrew_base_url . '?' . http_build_query($params);
// 6. Optional API response
if ($this->request->getGet('api') == 1) {
return $this->response->setJSON([
'status' => 'success',
'data' => [
'chartbrewUrl' => $url,
'policy_id' => $policy_id
]
]);
}
// 7. Return the View
return view('chartbrew_dashboard_view', [
'iframe_url' => $url,
'policy_id' => $policy_id
]);
}
public function testMediAssistWellness2()
{
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$loginUrlTemplate = env('MEDIASSIST_WELLNESS_LOGIN_URL');
$partnerCorpId = '15963';
$cipher_algorithm = 'AES-256-CBC';
// Payload (MATCH EXACT CASE from doc)
$payload = [
'Id' => '15022',
'expiryTime' => (string)(time() + 600), // string format safer
'CPartnerId' => $partnerCorpId,
];
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// ✅ IMPORTANT: Ensure correct key + IV length (ASCII based)
$key = substr(str_pad($keyString, 32, '0'), 0, 32); // 32 bytes
$iv = substr(str_pad($ivString, 16, '0'), 0, 16); // 16 bytes
// Encrypt
$cipherTextRaw = openssl_encrypt(
$plainJson,
$cipher_algorithm,
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($cipherTextRaw === false) {
return $this->respond([
'status' => false,
'message' => 'Encryption failed.',
], 500);
}
// ✅ Use ONLY Base64 (NO urlencode unless explicitly required)
$encryptedSSO = base64_encode($cipherTextRaw);
// Build URL
$loginUrl = str_replace(
['{0}', '{1}'],
[$partnerCorpId, $encryptedSSO],
$loginUrlTemplate
);
return $this->respond([
'status' => true,
'data' => [
'loginUrl' => $loginUrl,
'encryptedSSO' => $encryptedSSO,
'plainPayload' => $payload,
'decryptMediAssistWellness' => $this->decryptMediAssistWellness($encryptedSSO),
],
], 200);
}
public function testMediAssistWellness()
{
try {
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$loginUrlTemplate = env('MEDIASSIST_WELLNESS_LOGIN_URL');
$partnerCorpId = '15963';
$cipher_algorithm = 'AES-256-CBC';
// Payload
$payload = [
'Id' => '15022',
'expiryTime' => (string)(time() + 600),
'CPartnerId' => $partnerCorpId,
];
$plainJson = json_encode($payload, JSON_UNESCAPED_SLASHES);
// ✅ EXACT same as C#
$key = substr(str_pad($keyString, 32, '0'), 0, 32);
$iv = substr(str_pad($ivString, 16, '0'), 0, 16);
// Encrypt
$cipherTextRaw = openssl_encrypt($plainJson,$cipher_algorithm,$key,OPENSSL_RAW_DATA,$iv);
if ($cipherTextRaw === false) {
throw new \Exception('Encryption failed.');
}
// ✅ Step 1: Base64 encode
$base64Cipher = base64_encode($cipherTextRaw);
// ✅ Step 2: PREFIX IV (CRITICAL — matches C#)
$encryptedSSO = $iv . $base64Cipher;
// ⚠️ URL encode (VERY IMPORTANT for this format)
$finalSSO = urlencode($encryptedSSO);
// Build URL
$loginUrl = str_replace(
['{0}', '{1}'],
[$partnerCorpId, $finalSSO],
$loginUrlTemplate
);
return $this->respond([
'status' => true,
'data' => [
'loginUrl' => $loginUrl,
'encryptedSSO' => $encryptedSSO,
'base64Only' => $base64Cipher,
'ivUsed' => $iv,
'plainPayload' => $payload,
],
], 200);
} catch (\Throwable $e) {
log_message('error', 'MediAssist SSO Error: ' . $e->getMessage());
return $this->respond([
'status' => false,
'message' => $e->getMessage(),
], 500);
}
}
public function decryptMediAssistWellness($encryptedSSO)
{
// Config
$keyString = env('MEDIASSIST_WELLNESS_KEY');
$ivString = env('MEDIASSIST_WELLNESS_IV');
$cipher_algorithm = 'AES-256-CBC';
// Ensure same key + IV format used in encryption
$key = substr(str_pad($keyString, 32, '0'), 0, 32); // 32 bytes
$iv = substr(str_pad($ivString, 16, '0'), 0, 16); // 16 bytes
// Decode Base64
$cipherTextRaw = base64_decode($encryptedSSO, true);
if ($cipherTextRaw === false) {
return [
'status' => false,
'message' => 'Invalid Base64 string.',
];
}
// Decrypt
$decrypted = openssl_decrypt(
$cipherTextRaw,
$cipher_algorithm,
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($decrypted === false) {
return [
'status' => false,
'message' => 'Decryption failed.',
];
}
// Convert JSON to array
$data = json_decode($decrypted, true);
return [
'status' => true,
'data' => [
'decryptedRaw' => $decrypted,
'decoded' => $data
],
];
}
public function getVidalEnrollmentInfo()
{
helper('api');
$url = 'https://devapigw.vidalhealthtpa.com/partner-integration/enrollment/info';
$subscriptionKey = getenv('VIDAL_API_SUBSCRIPTION_KEY');
if (empty($subscriptionKey)) {
return $this->response->setStatusCode(500)->setJSON([
'error' => 'Missing VIDAL_API_SUBSCRIPTION_KEY in env',
]);
}
$policyNo = '000/VZXSY';
$startIndex = 1;
$endIndex = 5;
$body = [
'policyNo' => $policyNo,
'startIndex' => $startIndex,
'endIndex' => $endIndex,
];
$headers = [
'Content-Type: application/json',
'ocp-apim-subscription-key: ' . $subscriptionKey,
];
$method = "POST";
$rawResponse = call_third_party_api($url, $method, $headers, $body);
return $this->response->setStatusCode(200)->setJSON([
'request' => [
'url' => $url,
'method' => $method,
'headers' => $headers,
'body' => $body,
],
'raw_response' => $rawResponse,
]);
}
}