myLogger = \Config\Services::mylogger(); $this->employeeModel = new EmployeeModel(); $this->employeePolicyModel = new EmployeePolicyModel(); $this->clientModel = new ClientModel(); $this->fileModel = new FileModel(); $this->batchListModel = new BatchListModel(); $this->batchFileModel = new BatchFileModel(); $this->empEndorsementModel = new EmpEndorsementModel(); $this->clientPolicyModel = new ClientPolicyModel(); $this->TPAModel = new TPAModel(); $this->policiesModel = new PolicesModel(); } public function list() { // $model = new UserModel(); $data = []; $data['status'] = ['draft' => 'Draft', 'active' => 'Active', 'inactive' => 'In-Active', 'expired' => 'Expired']; if (count($this->request->getGet())) { $filterData = $this->request->getGet(); $data['employees'] = $this->employeePolicyModel->getEmployeePolicy( client_id: $filterData['client_id'], policy_id: $filterData['policy_id'], branch_id: $filterData['branch_id'], emp_code : $filterData['emp_code'], emp_name : $filterData['emp_name'], status : $filterData['status'], ); $data['getData'] = $filterData; } // dd($this->request->getGet()); $this->myLogger->logme('error', 'list called'); $this->loadLayout('employee_list', $data); } public function getClientWithPolicies() { //echo $this->request->isAJAX();die(); $result = $this->clientModel->clientsWithPolicies(); // dd($result); // print_r($result);die(); if (!count($result)) { return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200); } else { return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $result], 200); } } public function getUploadedFileError() { $file_id = $this->request->uri->getSegment(3); // dd($segments[2]); // die(); // $file_id = $this->request->getGet(); // echo $file_id;die(); $file = $this->fileModel->find($file_id); // print_r($result);die(); if (!isset($file)) { return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200); } else { return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200); } } //handles employee & dependent bulk upload with events like inception,addition,deletion, correction and SI enhancements public function employeesUplodWithEvents() { // $job_details = new Jobs(); // $r = Jobs::addJob(['job_name' => 'add','payload' => ['a' => 10, 'b' => 35]]); // print_r($r);//die(); // // $jobWorker = new JobWorker(); // JobWorker::processJob($r); // die(); // echo $this->request->getMethod();die(); // print_r($this->request->getFiles('emplist'));print_r($this->request->getPost('emplist')); // print_r($this->request->getPost('clients')); // print_r($this->request->getPost('policies')); // print_r($this->request->getPost('upload-action-type')); // die(); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->excelFileFormatValidation(['file_id' => '42']); // dd($res); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->excelFileDataValidation(['file_id' => '38']); // dd($res); // $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: '2'); // dd($existing_famility_details); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeesSIEnhanceProcess(['file_id' => '38']); // dd($res); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeesCorrectionProcess(['file_id' => '37']); // // dd($res); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => '3']); // dd($res); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeeDisembark(['file_id' => '36']); // dd($res); // if(isset($res['error_summary']) && count($res['error_summary'])) // { // $res['error_summary'] = (array_count_values($res['error_summary'])); // $failure_reason = ((json_encode($res))); // // dd($failure_reason); // $this->fileModel->where('id', '12')->set(['status' => 'failed','reason' => $failure_reason])->update(); // dd($failure_reason); // } if ($this->request->getMethod() == 'post') { //validate uploaded file $filename = ''; $validated = $this->validate([ 'emplist' => [ 'uploaded[emplist]', 'mime_in[emplist,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]', 'max_size[emplist,16384]', ], ]); if ($validated) { $avatar = $this->request->getFile('emplist'); if (!$avatar) { $this->myLogger->logme("error", 'File not found'); return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400); } $is_moved = $avatar->move(WRITEPATH . 'uploads/excel/'); if ($is_moved) { $filename = $avatar->getName(); // Handle successful upload, e.g., log success or further processing $this->myLogger->logme("error", 'File move successful'); } else { $this->myLogger->logme("error", 'File move failed'); return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500); } } else { $this->myLogger->logme("error", 'Upload failed Invalid file'); return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'Invalid file'], 404); } //process post variable entry in file table $loggedInUserID = get_session_userid(); // $loggedInUserID = 8; $client_id = $this->request->getPost('client_id'); $policy_id = $this->request->getPost('policy_id'); $branch_id = $this->request->getPost('branch_id'); $action = $this->request->getPost('upload-action-type'); $status = 'inprogress'; $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $loggedInUserID, 'status' => $status, 'action' => $action, 'client_branch_id' => $branch_id]); //here field policy_id have client_policy_id and not policy id from policy master $this->myLogger->logme("error", '{file_id} uploaded success', ['file_id' => $file_id]); //start validation process $empServiceController = new EmployeeServiceController(); $result = $empServiceController->excelFileFormatValidation(['file_id' => $file_id]); //endof validation process if (isset($result['error_summary']) && count($result['error_summary'])) { return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file rejected with errors'], 200); } return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200); } $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; $data['actions'] = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addtion' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; $data['import_or_export'] = ['import' => 'Import', 'export' => 'Export']; $data['insurer_or_tpa'] = ['insurer' => 'Insurer', 'tpa' => 'TPA']; // $data['fileList'] = $this->fileModel // ->select(['files.*', 'up.emp_code', 'up.first_name', 'pm.name as policy_name', 'c.short_name', 'cp.id as client_policy_id']) // ->join('user_profiles up', 'files.created_by = up.id') // ->join('client_policy cp', 'files.policy_id = cp.id', 'left') // ->join('policies pm', 'cp.policy_id = pm.id', 'left') // ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left') // ->where('files.created_by', get_session_userid())->orderBy('files.created_at', 'desc')->findAll(); // dd($this->fileModel->getLastQuery()); $data['fileList'] = $this->fileModel ->select([ 'files.*', 'up.emp_code', 'up.first_name', 'pm.name as policy_name', 'c.short_name', 'cb.branch_name', 'cp.id as client_policy_id', '(SELECT COUNT(*) FROM employees e JOIN employee_polices ep ON e.id = ep.employee_id WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as employee_count', '(SELECT SUM(ep.rata_premimum) + SUM(ep.gst) FROM employees e JOIN employee_polices ep ON e.id = ep.employee_id WHERE e.file_id = files.id AND ep.client_policy_id = files.policy_id) as total', 'policy_type.policy_type' , 'cp.policy_no' , ]) ->join('user_profiles up', 'files.created_by = up.id') ->join('client_policy cp', 'files.policy_id = cp.id', 'left') ->join('client_branch cb', 'files.client_branch_id = cb.id', 'left') ->join('policies pm', 'cp.policy_id = pm.id', 'left') ->join('policy_type', 'policy_type.id = pm.policy_type_id') ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left') ->where('files.created_by', get_session_userid()) ->orderBy('files.created_at', 'desc') ->findAll(); // dd($data['fileList']); $data['batch_list'] = $this->batchFileModel->select( 'batch_files.*, policies.name as policy_name, clients.short_name as client_short_name, client_branch.branch_name, client_policy.policy_no, policy_type.policy_type ') ->join('client_policy', 'client_policy.id = batch_files.client_policy_id') ->join('client_branch', 'client_branch.id = batch_files.client_branch_id') ->join('policies', 'policies.id = client_policy.policy_id') ->join('policy_type', 'policy_type.id = policies.policy_type_id') ->join('clients', 'clients.id = client_policy.client_id') ->orderBy('batch_files.id', 'desc') ->findAll(); // dd($data['fileList']);die(); if ($this->request->getMethod() == "get") { $this->loadLayout('import_export', $data); } } public function getExcelFileErrors() { $file_id = $this->request->uri->getSegment(3); $empServiceController = new EmployeeServiceController(); // Render views and capture output $result = $empServiceController->getExcelErrorData($file_id); if ($result != 0) { $result['file_id'] = $file_id; echo view('excel_errors', $result); } else if ($result == 0) { $data['message'] = 'File Not Found Physically'; return view('errors/404', $data); } else { echo view('errors/html/production'); } } /** * The below function Downloads a sample Excel file based on the provided action type. * * @param string|null $actionType The type of action : * * - inception * - correction * - si_enhancement for selecting the appropriate sample Excel file. * * @return redirect back with an error message if the file is not found, otherwise sends the file to the user for download. */ public function downloadSampleExcelFile($actionType = null) { // $actionType = $this->request->getGet(); $filePath = ''; // Path to your file if ($actionType == 'inception') { $filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls'; } else if ($actionType == 'correction') { $filePath = ROOTPATH . 'public/sample_excel/sample_correction .xls'; } else if ($actionType == 'si_enhancement') { $filePath = ROOTPATH . 'public/sample_excel/sample_si_enhancement.xls'; } else if ($actionType == 'dependent_addtion') { $filePath = ROOTPATH . 'public/sample_excel/sample_dependent_addition.xls'; } else if ($actionType == 'addition') { $filePath = ROOTPATH . 'public/sample_excel/sample_addition.xls'; } else if ($actionType == 'deletion') { $filePath = ROOTPATH . 'public/sample_excel/sample_deletion.xls'; } // Check if the file exists if (file_exists($filePath)) { // Set the appropriate MIME type $mimeType = mime_content_type($filePath); // Send the file to the client for download return $this->response->download($filePath, null, $mimeType); } else { // File not found, show an error message or redirect echo view('errors/html/production'); } } /** * The below function are Handles import and export operations based on the provided parameters. * * This function logs the call, retrieves necessary data, generates a filename, * and then either exports data to an Excel file or imports data from an Excel file * depending on the provided action type and event type. * * @return void Redirects the user to the appropriate page with flash messages indicating success or failure. */ public function importExport() { $this->myLogger->logme('error', 'Import Export -- Function called'); $empDataServiceController = new EmpDataServiceController(); $client_id = $this->request->getPost('client_id'); $client_policy_id = $this->request->getPost('client_policy_id'); $client_branch_id = $this->request->getPost('client_branch_id'); $insurer_or_tpa = $this->request->getPost('insurer_or_tpa'); $event_type = $this->request->getPost('event_type'); $actions = $this->request->getPost('action_type'); $client_data = $this->clientModel->where('id', $client_id)->first(); $policy_name_and_branch_name = $this->clientPolicyModel->select('policies.name, client_branch.branch_code') ->join('client_branch', 'client_branch.id = client_policy.client_branch_id') ->join('policies', 'policies.id = client_policy.policy_id') ->where('client_policy.id', $client_policy_id) ->first(); $file_name = generate_filename($client_data['short_name'], $event_type, $actions, $insurer_or_tpa, $policy_name_and_branch_name['name'], $policy_name_and_branch_name['branch_code']); $batch_data = [ 'client_id' => $client_id, 'client_policy_id' => $client_policy_id, 'client_branch_id' => $client_branch_id, 'insurer_or_tpa' => $insurer_or_tpa, 'event_type' => $event_type, 'actions' => $actions, 'file_name' => $file_name, ]; if ($actions == 'export') { if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition') { $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data); if ($return === 0) { session()->setFlashdata('error', "Insufficient deposit amount."); return redirect()->to(base_url('employee/upload')); }else if($return === 5){ session()->setFlashdata('error', "The policy does not have a CD account number."); return redirect()->to(base_url('employee/upload')); } if (!$return) { if ($insurer_or_tpa == 'tpa') { session()->setFlashdata('error', "No data was found for this action. The TPA ID has already been updated."); return redirect()->to(base_url('employee/upload')); } else if ($insurer_or_tpa == 'insurer') { session()->setFlashdata('error', "No data was found for this action. The UHID has already been updated."); return redirect()->to(base_url('employee/upload')); } } else { $this->myLogger->logme('error', 'Successfully exported Excel file in {data}.', ['data' => $event_type]); } } else if ($event_type == 'correction') { $return = $empDataServiceController->generateExcelForCorrection($batch_data); if (!$return) { session()->setFlashdata('error', 'No data found about this action'); return redirect()->to(base_url('employee/upload')); } else { $this->myLogger->logme('error', 'Successfully exported Excel file in Correction.'); } } else if ($event_type == 'si_enhancement') { $return = $empDataServiceController->generateExcelForSIEnhancement($batch_data); if ($return === 0) { session()->setFlashdata('error', "Insufficient deposit amount."); return redirect()->to(base_url('employee/upload')); }else if($return === 5){ session()->setFlashdata('error', "The policy does not have a CD account number."); return redirect()->to(base_url('employee/upload')); } if (!$return) { session()->setFlashdata('error', 'No data found about this action'); return redirect()->to(base_url('employee/upload')); } else { $this->myLogger->logme('error', 'Successfully exported Excel file in SI_Enhancement.'); } } else if ($event_type == 'deletion') { $return = $empDataServiceController->generateExcelForDeletion($batch_data); if (!$return) { session()->setFlashdata('error', 'No data found about this action'); return redirect()->to(base_url('employee/upload')); } else { $this->myLogger->logme('error', 'Successfully exported Excel file in Deletion.'); } } } else if ($actions == 'import') { $batch_data['file'] = $this->request->getFile('import_file_data'); $file = $this->request->getFile('import_file_data'); $is_moved = $file->move(WRITEPATH . 'uploads/import_excel'); $filename = $file->getName(); $this->myLogger->logme('error', 'Inception Import file name : {data}', ['data' => $filename]); $random_number_count = 4; $batch_data['batch_code'] = generate_random_string($random_number_count); $batch_data['created_by'] = get_session_userid(); $batch_data['status'] = 'pending'; $batch_data['file_name'] = $filename; if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition') { $file_id = $this->batchFileModel->insert($batch_data); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'importInceptionFileValidation', 'payload' => ['file_id' => $file_id]]); $return = 1; // $return = $empDataServiceController->importInceptionFileValidation(['file_id' => $file_id]); if ($return == 1) { session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.'); return redirect()->to(base_url('employee/upload')); } else { session()->setFlashdata($return['status'], $return['message']); return redirect()->to(base_url('employee/upload')); } } else if ($event_type == 'correction') { $file_id = $this->batchFileModel->insert($batch_data); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'importCorrectionValidation', 'payload' => ['file_id' => $file_id]]); $return = 1; // $return = $empDataServiceController->importCorrectionValidation(['file_id' => $file_id]); if ($return == 1) { session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.'); return redirect()->to(base_url('employee/upload')); } else { session()->setFlashdata('error', $return); return redirect()->to(base_url('employee/upload')); } } else if ($event_type == 'si_enhancement') { $file_id = $this->batchFileModel->insert($batch_data); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'importSIEnhancementValidation', 'payload' => ['file_id' => $file_id]]); $return = 1; // $return = $empDataServiceController->importSIEnhancementValidation(['file_id' => $file_id]); if ($return == 1) { session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.'); return redirect()->to(base_url('employee/upload')); } else { session()->setFlashdata('error', $return); return redirect()->to(base_url('employee/upload')); } } else if ($event_type == 'deletion') { $file_id = $this->batchFileModel->insert($batch_data); $job_details = new Jobs(); $r = Jobs::addJob(['job_name' => 'importDeletionValidation', 'payload' => ['file_id' => $file_id]]); $return = 1; // $return = $empDataServiceController->importDeletionValidation(['file_id' => $file_id]); if ($return == 1) { session()->setFlashdata('success', 'File Uploaded Successfully File is being validated.'); return redirect()->to(base_url('employee/upload')); } else { session()->setFlashdata('error', $return); return redirect()->to(base_url('employee/upload')); } } } } // ------------------------------------------------------------------------------------------- /** * Below function displays the endorsement list page. * * This method retrieves filter data from the request and fetches the endorsement list * based on the provided filters such as client ID, policy ID, and status. */ public function endorsementList() { $data = []; $data['status'] = ['pending' => 'Pending', 'inprogress' => 'In-Progress', 'complete' => 'Complete']; if (count($this->request->getGet())) { $filterData = $this->request->getGet(); $data['employees'] = $this->employeePolicyModel->getEmployeeEndorsementList( client_id: $filterData['client_id'], policy_id: $filterData['policy_id'], status: $filterData['status'], branch_id: $filterData['branch_id'] ); $data['getData'] = $filterData; // echo "
";
            // print_r($data); die;
        }

        $this->myLogger->logme('error', 'list called');
        $this->loadLayout('endorsement_list', $data);
    }


    /**
     * Beleo function retrieves employee endorsement (emp_endorsement table) data.
     *
     * This method fetches endorsement data based on the provided ID.
     * It determines the type of endorsement action (SI enhancement, deletion, or other),
     * formats the data accordingly, and returns it as a response.
     *
     * @param int|null $id The ID of the endorsement entry to retrieve.
     * @return \CodeIgniter\HTTP\Response Returns a JSON response containing the endorsement entry data.
     */
    public function getEmpEndoresmentEntry($id = null)
    {
        // Create instance of EmpDataServiceController
        $empDataServiceController = new EmpDataServiceController();

        // Check if $id is provided
        if ($id) {
            // Retrieve group key and actions based on $id
            $group_key_actions = $this->empEndorsementModel->select('group_key, actions')->where('id', $id)->first();
            $groupedData = $this->empEndorsementModel->where('group_key', $group_key_actions['group_key'])->findAll();

            // If group key and actions are found
            if ($group_key_actions) {
                // Retrieve endorsement data based on actions
                switch ($group_key_actions['actions']) {
                    case 'si':
                        $data = $this->empEndorsementModel->getDataForEnodrsementListinSIEnhancement($group_key_actions['group_key']);
                        $formatedData = $empDataServiceController->convertRowTColumnForSIEnhancement($data);
                        break;
                    case 'd':
                        $data = $this->empEndorsementModel->getDataForEnodrsementListinDeletion($group_key_actions['group_key']);
                        $formatedData = $empDataServiceController->convertRowTColumnForDeletion($data);
                        break;
                    default:
                        $formatedData = $groupedData;
                        $formatedData[0]['field_name'] = remove_underscore_capitalize_first_letter($formatedData[0]['field_name']);
                        $formatedData[0]['old_value'] = formatDateOrReturn($formatedData[0]['old_value']);
                        $formatedData[0]['new_value'] = formatDateOrReturn($formatedData[0]['new_value']);
                        break;
                }

                // Return response with data
                return $this->respond([
                    'dataStatus' => true,
                    'code' => 200,
                    'data' => $formatedData,
                    'data2' => $groupedData
                ], 200);
            } else {
                // Return response if group key and actions are not found
                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
            }
        } else {
            // Return response if $id is not provided
            return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }


    // @param int $client_policy_id
    // this funciton initiate Inception/adition/DA of employees data only form enrollment app when passing
    // client_policy_id pull draft and enrolled status employees and proceed to calculatin and make entry in DB
    public function initiateManualEmployeesOnboardProcess($client_policy_id)
    {
        $client_data = $this->clientPolicyModel->select('clients.client_name as client_name, policies.name as policy_name,client_branch_id')
            ->join('clients', 'clients.id = client_policy.client_id')
            ->join('policies', 'policies.id = client_policy.policy_id')
            ->where('client_policy.id', $client_policy_id)
            ->first();

        $empServiceController = new EmployeeServiceController();
        $res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => $client_policy_id,'client_branch_id' => $client_data['client_branch_id']]);
        // dd($res);

        $count = count($res);
        $message =  $count . ' Employees are Initiate Onboard Process againts Client ' . $client_data['client_name'] . ' and the Policy is ' . $client_data['policy_name'];
        session()->setFlashdata('success1',  $message);
        return redirect()->to(base_url('/employee/upload'));
    }


    public function downloadFileList($file_id = null)
    {
        // $actionType = $this->request->getGet();
        $file_data = $this->fileModel->where('id', $file_id)->first();
        $fileName = $file_data['file_name'];

        $error_data = json_decode($file_data['reason']);

        $filePath = WRITEPATH . '/uploads/excel/' . $fileName;

        try {

            // Check if the file exists
            if (file_exists($filePath)) {
                // Set the appropriate MIME type
                $mimeType = mime_content_type($filePath);

                // Send the file to the client for download
                return $this->response->download($filePath, null, $mimeType);
            } else {

                $data['message'] = 'The Physical File Not Found';
                echo view('errors/404', $data);
            }
        } catch (\Exception $e) {
            // Handle any exceptions
            $errorMessage = $e->getMessage();
            $this->myLogger->logme('error', $errorMessage);
            // You can return an error response here
            echo $errorMessage;
        }
    }


    public function featchEmpList()
    {
        $client_id = $this->request->getGet('client_id');
        $policy_id = $this->request->getGet('policy_id');

        $emp_data['employees'] = $this->employeePolicyModel->getEmployeePolicyForFileList($client_id, $policy_id);
        $html = view('employee_data_list', $emp_data);

        return $this->respond(['dataStatus' => true, 'code' => 200, 'data' =>  $html], 200);
    }


    public function viewUploadedEmployeeList()
    {

        $empDataServiceController = new EmpDataServiceController();

        $file_id = $this->request->getGet('file_id');
        // $emp_data['employees'] = $this->employeePolicyModel->getViewEmpSuccessList($file_id);
        // $html = view('view_file_upload_emp_list', $emp_data);
        $file_name = $this->fileModel
            ->select(['files.*', 'up.emp_code', 'up.first_name', 'pm.name as policy_name', 'c.short_name', 'cp.id as client_policy_id'])
            ->join('user_profiles up', 'files.created_by = up.id')
            ->join('client_policy cp', 'files.policy_id = cp.id', 'left')
            ->join('policies pm', 'cp.policy_id = pm.id', 'left')
            ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
            ->where('files.id', $file_id)->first();

            // dd($file_name);

        try {

            $filePath = WRITEPATH . '/uploads/excel/' . $file_name['file_name'];

            if (file_exists($filePath)) {
                
                $excel_data = $empDataServiceController->readExcelFileToArray($filePath);
                $emp_data['thead'] = $excel_data[0];
                unset($excel_data[0]);
                $emp_data['tbody'] = $excel_data;
                $emp_data['count'] = count($excel_data);

                // dd($emp_data);

                $html = view('view_file_upload_emp_list', $emp_data);
            } else {

                $html = '
No Data Found
'; } return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $html, 'file_data' => $file_name, 'excel_data' => $excel_data], 200); } catch (\Exception $e) { // Handle exception $errorMessage = 'Error occurred: ' . $e->getMessage(); $this->myLogger->logme('error', $errorMessage); $html = '
No Data Found
'; return $this->respond(['dataStatus' => false, 'code' => 500, 'data' => $html, 'file_data' => $file_name], 500); } } public function getEmpCount($id = null) { $data = $this->employeePolicyModel->select('employee_polices.id') ->where('employee_polices.is_active', 1) ->where('employee_polices.client_policy_id', $id) ->findAll(); $emp_count = count($data); $events = ['inception' => 'Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement']; return $this->respond(['dataStatus' => true, 'code' => 200, 'emp_count' => $emp_count, 'events' => $events, 'client_policy_id' => $id], 200); } public function downloadFullExcelErrorFile($file_id, $rowIndex = 1, $colIndex = 1) { // Get file data from the database $file_data = $this->fileModel->find($file_id); $error = json_decode($file_data['reason']); // echo '
';
        //    print_r($error); die;
        //    dd($error);

        // Check if the file exists
        if (!$file_data) {
            $error_message = "File not found";
            $this->myLogger->logme('error', $error_message . ' for file id ' . $file_id);
            return $error_message;
        }

        $fileName = $file_data['file_name'];
        $filePath = WRITEPATH . '/uploads/excel/' . $fileName;

        // Check if the file exists
        if (!file_exists($filePath)) {
            $error_message = "File not found";
            $this->myLogger->logme('error', $error_message . ' for file id ' . $file_id);
            $data['message'] = 'Physical File Not Found';
            return view('errors/404', $data);
        }

        // Load the Excel file
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();

        //  echo '
';

        foreach ($error->error_data as $index => $error_data) {

            $rowIndex = $index + 1;

            if ($error->error_type == 1) {

                foreach ($error_data as $key => $value) {

                    $colIndex = $value->col_idx + 1;

                    $originalValue = $sheet->getCell([$colIndex, $rowIndex])->getValue();

                    $newValue =  implode(', ', $value->error);
                    $val = $originalValue . ' ( ' . $newValue . ' )';
                    $sheet->setCellValue([$colIndex, $rowIndex],  $val);

                    $style = [
                        'fill' => [
                            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                            'startColor' => ['rgb' => 'ffad99'] // Red color
                        ]
                    ];

                    $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
                }
            } else if ($error->error_type == 2) {


                foreach ($error_data as $key => $value) {


                    $originalValue = $sheet->getCell([1, $rowIndex])->getValue();

                    $newValue =  implode(', ', $value->error);
                    $val = $originalValue . ' ( ' . $newValue . ' )';
                    $sheet->setCellValue([$colIndex, $rowIndex],  $val);

                    $style = [
                        'fill' => [
                            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                            'startColor' => ['rgb' => 'ffad99'] // Red color
                        ]
                    ];
                    $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style);
                }
            }
        }



        // Create a new filename for the modified Excel file
        $newFileName = 'error_with_highlight_' . $fileName;

        // Save the modified Excel file to a new location
        $newFilePath = WRITEPATH . '/uploads/excel/' . $newFileName;
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($newFilePath);

        // Set headers to force download
        $response = service('response');
        $response->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $response->setHeader('Content-Disposition', 'attachment;filename="' . $newFileName . '"');
        $response->setHeader('Cache-Control', 'max-age=0');
        $response->setHeader('Content-Length', filesize($newFilePath));
        $response->setBody(file_get_contents($newFilePath));

        // Delete the temporary file
        unlink($newFilePath);

        // Return the response
        return $response;
    }


    public function generateIDCardForEmployee($rand_string, $people = 0)
    {    
        // dd($rand_string, $people);

        try {

            $get_emp_code_and_client_policy_id = $this->employeePolicyModel
                ->select('employee_polices.client_policy_id, employees.emp_code, tpa.short_name,employees.client_id')
                ->join('client_policy', 'client_policy.id = employee_polices.client_policy_id')
                ->join('employees', 'employees.id = employee_polices.employee_id')
                ->join('tpa', 'tpa.id = client_policy.tpa_id')
                ->where('employees.emp_status', 'active')
                ->where('employees.is_active', '1')
                ->where("employee_polices.tpa_id IS NOT NULL AND employee_polices.tpa_id <> ''")
                ->where('employee_polices.status', 'active')
                ->where('employee_polices.is_active', '1')
                ->where('employee_polices.rand_string', $rand_string)->first();

            // dd($get_emp_code_and_client_policy_id);


            if ($get_emp_code_and_client_policy_id == null || $get_emp_code_and_client_policy_id == "") {

                $data['message'] = 'Record Not Found';
                return view('errors/404', $data);
            }

            $client_policy_id = $get_emp_code_and_client_policy_id['client_policy_id'];
            $emp_code = $get_emp_code_and_client_policy_id['emp_code'];


            $data = $this->employeePolicyModel->getECardDataUsingMd5($client_policy_id, $emp_code,$client_id);
            
            if($people == 0){
               $data = $this->employeePolicyModel->getECardSingleData($rand_string, $emp_code,$client_id);
            }

            // dd($data);

            $template_data_path =  WRITEPATH . 'e_card_template/';
            $tpa_short_name = strtolower(str_replace(' ', '_', $get_emp_code_and_client_policy_id['short_name'])) . '.html';
            $final_path =  $template_data_path . $tpa_short_name;

            // dd($template_data_path, $tpa_short_name, $final_path);

            if (!file_exists($final_path)) {

                $data['message'] = 'Record Not Found';
                return view('errors/404', $data);
            } 

            $tmplt_data = file_get_contents($final_path);

            // dd($tmplt_data);

            $html = ""; // Initialize the HTML variable
            foreach ($data as $key => $value) {
                
                // Get the HTML content from the template
                // $htmlContent = view('ecard_template/md_tpa');
                $htmlContent = $tmplt_data;
                
                // Define the placeholders and their corresponding values
                $placeholders = [
                    '{TPA_ID}' => $value['tpa_id'],
                    '{NAME}' => $value['name'],
                    '{UHID}' => $value['uhid'],
                    '{GENDER}' => $value['gender'],
                    '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
                    '{SELF_NAME}' => $value['self'] ?? $value['name'],
                    '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
                    '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
                    '{POLICY_NO}' => date('d-M-Y', strtotime($value['policy_start_date'])),
                    '{INSURER_NAME}' => strtoupper($value['insurer_name']),
                    '{INSURER_LOGO}' => base_url() . 'public/uploads/logo/' . $value['insurer_logo'],
                    '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['front_card'],
                    '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $value['back_card'],
                    '{EMP_ID}' =>$value['emp_code'],
                    '{CORPORATE_NAME}' =>$value['client_name'],
                    '{AGE}' =>$value['emp_age'],
                    '{TPA_NAME}' =>$value['tpa_name'],
                    '{INSURER_BRANCH}' =>$value['insurer_branch_city'],
                    '{RELATION}' =>$value['relationship'],
                    '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $value['tpa_logo'],
                    '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
                    '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
                    '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
                    '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
                    '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png',
                    '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
                    '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',
        
                ];
                
                // Replace placeholders with values in HTML content
                foreach ($placeholders as $placeholder => $replaceValue) {
                    $htmlContent = str_replace($placeholder, $replaceValue, $htmlContent);
                }
            
                $html .= $htmlContent;
            }
            
            echo '' . $html . '
                  ';
            
            

            // $file_name = $get_emp_code_and_client_policy_id['short_names'] ?? 'md_tpa';
            // $file_name = strtolower(str_replace(' ', '_', $file_name));



            // $file_path = ROOTPATH . 'app/Views/ecard_template/' . $file_name . '.php';

            // if (is_file($file_path)) {
            //     $view_file = 'ecard_template/' . $file_name;

            // } else {
            //     $view_file = 'ecard_template/default_ecard';

            // }


            // $dpi = 132;
            // $html =  view('ecard_template/md_tpa');
            // // echo $html; die;

            // $options = new Options();
            // $options->set('isRemoteEnabled', true);
            // $options->set('isPhpEnabled', true);
            // $options->setDpi($dpi);
            // $dompdf = new Dompdf($options);

            // $dompdf->loadHtml($html);
            // $dompdf->setPaper('A4', 'portrait');
            // $dompdf->render();


            // $filename = 'ECard.pdf'; // Default filename

            // foreach ($data['data'] as $key => $value) {

            //     if ($value['relationship'] == "Self") {

            //         $filename = $value['tpa_id'] . '.pdf'; // Update filename if relationship is "Self"
            //     } elseif (!empty($value['tpa_id']) && $filename == 'ECard.pdf') {

            //         $filename = $value['tpa_id'] . '.pdf';
            //     }
            // }

            // $dompdf->stream($filename, array("Attachment" => false));

        } catch (\Exception $e) {

            $data['message'] = 'Record Not Founds';
            return view('errors/404', $data);
        }
    }


    public function viewECard()
    {

        // $this->loadLayout('ecard_template/default_ecard');
        
        $empDataServiceController = new EmpDataServiceController();
        $file_name = generate_filename("TCS", 'inception', 'export', 'insurer', 'policy', 'branch');

        $batch_data = [
            'client_id' => 12,
            'client_policy_id' => 12,
            'client_branch_id' => 1,
            'insurer_or_tpa' => 'insurer',
            'event_type' => 'inception',
            'actions' => 'export',
            'file_name' => $file_name,
        ];

        $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data);

        if ($return == 0) {

           dd('error', "Insufficient deposit amount.");

        }else if($return == 1){

            dd('error', "The policy does not have a CD account number.");
        }

        if (!$return) {
            dd('error', "No data was found");
        }
        
    }


    public function truncateFileData() //truncateFileDataIn DB (de activate rows)
    {
        $file_id = $this->request->uri->getSegment(3);
        // $file_id = 112;
        $file = $this->fileModel->find($file_id);
        // $file['action'] = 'si_enhancement';
        // $result = [];
        // !dd($file);
        if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition') {
            $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']);
            // ~dd($result);
            if (count($result)) {
                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
            } else {

                //update emp and emp plocies
                $db = db_connect();
                $query = "UPDATE employees JOIN employee_polices ON employees.id = employee_polices.employee_id and employees.file_id = $file_id SET employees.emp_status = 'truncated', employee_polices.status = 'truncated', employees.is_active = 0,employee_polices.is_active = 0 WHERE employees.file_id = $file_id";
                $db->query($query);
                $affectedRows = $db->affectedRows();
                // $affectedRows = 10;

                //update file status
                $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update();

                return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => round($affectedRows / 2)], 200);
            }
        } else if ($file['action'] == 'si_enhancement' || $file['action'] == 'correction' || $file['action'] == 'deletion') {
            $res = $this->empEndorsementModel->select(['count(id) as count'])
                ->where('emp_endorsement.file_id', $file_id)
                ->groupStart()
                ->where('emp_endorsement.endorsement_id is not null')
                ->orwhereIn('emp_endorsement.status', ['complete'])
                ->groupEnd()
                ->get()
                ->getResult();
            // print_r($this->empEndorsementModel->getLastQuery());
            // echo $res[0]->count;die();
            if ($res[0]->count == 0) {
                //update truncated status to db
                $this->empEndorsementModel->where('file_id', $file_id)
                    ->set(['status' => 'truncated'])
                    ->update();
                //update file status
                $this->fileModel->where('id', $file_id)->set(['status' => 'truncated'])->update();
                return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'success'], 200);
            } else {
                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'File data already processed'], 200);
            }
        }
    }




    public function previewTemplate($id = null)
    {

        
        $value = [
            'tpa_id' => 'TPA12345',
            'name' => 'John Doe',
            'uhid' => 'UHID67890',
            'gender' => 'Male',
            'dob' => '1985-05-15',
            'self' => 'John Doe',
            'policy_end_date' => '2024-12-31',
            'policy_start_date' => '2023-01-01',
            'policy_no' => 'POL1234567890',
            'insurer_name' => 'Example Insurance Company',
            'emp_code' => 'EMP001122',
            'client_name' => 'Corporate Client Inc.',
            'emp_age' => 39,
            'tpa_name' => 'Example TPA',
            'insurer_branch_city' => 'New York',
            'relationship' => 'Self'
        ];
        

        $tpa_id = $this->TPAModel->where('id', $id)->first();

        $template_data_path =  WRITEPATH . 'e_card_template/';
        $tpa_short_name = strtolower(str_replace(' ', '_', $tpa_id['short_name'])) . '.html';
        $final_path =  $template_data_path . $tpa_short_name;

        if (!file_exists($final_path)) {

            $data['message'] = 'Record Not Found';
            return view('errors/404', $data);
        }

        $tmplt_data = file_get_contents($final_path);

        $placeholders = [
            '{TPA_ID}' => $value['tpa_id'],
            '{NAME}' => $value['name'],
            '{UHID}' => $value['uhid'],
            '{GENDER}' => $value['gender'],
            '{DOB}' => date('d-M-Y', strtotime($value['dob'])),
            '{SELF_NAME}' => $value['self'] ?? $value['name'],
            '{POLICY_DATE}' => date('d-M-Y', strtotime($value['policy_end_date'])),
            '{POLICY_START_DATE}' => date('d-M-Y', strtotime($value['policy_start_date'])),
            '{POLICY_NO}' => $value['policy_no'], 
            '{INSURER_NAME}' => strtoupper($value['insurer_name']),
            '{EMP_ID}' => $value['emp_code'],
            '{CORPORATE_NAME}' => $value['client_name'],
            '{AGE}' => $value['emp_age'],
            '{TPA_NAME}' => $value['tpa_name'],
            '{INSURER_BRANCH}' => $value['insurer_branch_city'],
            '{RELATION}' => $value['relationship'],
            '{FRONT_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['front_card'],
            '{BACK_CARD}' => base_url() . 'public/uploads/template_bg/' . $tpa_id['back_card'],
            '{TPA_LOGO}' => base_url() . 'public/uploads/logo/' . $tpa_id['tpa_logo'],
            '{INSURER_LOGO}' => base_url() . 'public/assets/images/sample_logo_3.png',
            '{MEDI_USER}' => base_url() . 'public/e_card_imgs/medi_uesr.jpg',
            '{MEDI_INSURER}' => base_url() . 'public/e_card_imgs/Magma.png',
            '{MEDI_BARCODE}' => base_url() . 'public/e_card_imgs/borcode.jpeg',
            '{QR_ANDROID}' => base_url() . 'public/e_card_imgs/android.png',
            '{QR_IOS}' => base_url() . 'public/e_card_imgs/ios.png', 
            '{QR_ANDROID_2}' => base_url() . 'public/e_card_imgs/play_store.png',
            '{QR_IOS_2}' => base_url() . 'public/e_card_imgs/appstore.png',

        ];

        // Get the values to replace the placeholders
        $replaceValues = array_values($placeholders);

        // Get the placeholders to search for
        $searchPlaceholders = array_keys($placeholders);

        // Replace placeholders with values in HTML content
        $htmlContent = str_replace($searchPlaceholders, $replaceValues, $tmplt_data);


        echo $htmlContent;
    }


    public function errorListExportImport($file_id)
    {

        $empDataServiceController = new EmpDataServiceController();

        $file = $this->batchFileModel->where('id', $file_id)->first();
        $client_id = $file['client_id'];
        $client_policy_id = $file['client_policy_id'];
        $insurer_or_tpa = $file['insurer_or_tpa'];
        $event_type = $file['event_type'];

        $error_data = json_decode($file['error_data']);

        $file_name_with_path = WRITEPATH . "/uploads/import_excel/" . $file['file_name'];

        if (!file_exists($file_name_with_path)) {
            $error_message = "File not found";
            $this->myLogger->logme('error', ($error_message . ' for file id ' . $file_id));
            $data['message'] = 'Physical File Not Found';
            return view('errors/404', $data);
        }

        $excel_data = $empDataServiceController->readExcelFileToArray($file_name_with_path);
        $excelErrorData['excel_header'] = $excel_data[0];
        unset($excel_data[0]);

        if($event_type == 'inception' || $event_type == 'deletion'){
            array_pop($excel_data);
        }

        $finalArray = [];
        foreach ($error_data as $key => $values) {

            foreach ($values as $key2 => $value) {

                $row = $value->row;
                $column = $value->column;

                if(property_exists($value, 'db_data')){

                    $error = 'Expected value: ' . ($value->db_data == null ||  $value->db_data == "" ? 'NULL' : $value->db_data);

                }else{

                    if($event_type == 'inception'){

                        if ($insurer_or_tpa == 'tpa') {

                            $error = 'Expected value : TPA ID';
    
                        } else if ($insurer_or_tpa == 'insurer') {
            
                            $error = 'Expected value : UHID';
                        }

                    }else{
                        $error = 'Expected value : ENDORSEMENT ID';
                    }


                }
                $data = ['value' => $excel_data[$row][$column], 'error' => $error,];
                $excel_data[$row][$column] = $data;
            }

            array_push($finalArray, $excel_data[$key]);
        }


        foreach ($finalArray as $fkey => $value) {
            foreach ($value as $vkey => $arrayData) {
                if (!is_array($arrayData)) {
                    $data = ['value' => $arrayData];
                    $finalArray[$fkey][$vkey] =  $data;
                }
            }
        }

        $excelErrorData['excel_data'] = $finalArray;
        $excelErrorData['file_id'] = $file_id;

        // dd($finalArray);

        echo view('export_import_error_list', $excelErrorData);
    }

    public function hasPolicyConfigCompleted()
    {
        $client_policy_id = $this->request->uri->getSegment(3);
        $policy_details = $this->clientPolicyModel->find($client_policy_id);
        $policy_terms = isset($policy_details['policy_terms']) ? true : false;

        $si_enhancement_true_or_false = 1;
        if($policy_terms){
            $policyTermsData = json_decode($policy_details['policy_terms']);

            if (isset($policyTermsData->suminsuredenhancement) && $policyTermsData->suminsuredenhancement !== null) {
                $si_enhancement_true_or_false = $policyTermsData->suminsuredenhancement;
            }        
        }
        

        $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$policy_details['client_id']);

        $message = null;

        if (!isset($policy_terms)) {
            $message  .= 'Policy terms';
        }

        if($slab_details['slab_rates'] == null && $slab_details['grid_master'] == null)
        {
            $message  = isset($message) ? ($message . ' and rack rates ') : ($message . ' Rack rates');
        }
        $message  = isset($message) ? ($message . ' not defined for choosed policy') : null;

        return $this->respond(['dataStatus' => true, 'code' => 200, 'message' => $message, 'si_enhancement' => $si_enhancement_true_or_false], 200);
        
    }

}