nhance/app/Controllers/EmployeeRestController.php

545 lines
21 KiB
PHP

<?php
namespace App\Controllers;
use App\Helpers\MailHelper;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\PolicesModel;
use App\Models\RelationshipModel;
use App\Models\FileModel;
use App\Models\ClientPolicyModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use CodeIgniter\API\ResponseTrait;
use Illuminate\Http\Request;
class EmployeeRestController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $fileModel;
protected $policesModel;
protected $relationshipModel;
protected $clientPolicyModel;
public function __construct()
{
// helper('utility');
set_session_context('Employee');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->policesModel = new PolicesModel();
$this->relationshipModel = new RelationshipModel();
$this->fileModel= new FileModel();
$this->clientPolicyModel = new ClientPolicyModel();
}
public function getEmployeeProfile()
{
try {
$emp_code = $this->request->getGet('emp_code');
if ($emp_code) {
$relationship = 'self';
$employee = $this->employeeModel->where('emp_code', $emp_code)
->where('relationship', $relationship)
->first();
$result = $employee;
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],404);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function editEmployeeProfile()
{
try {
$data = $this->request->getJSON();
if ($data) {
$id = $data->id;
$employee = $this->employeeModel->update($id, $data);
if ($employee) {
$result = [];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],404);
}
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function getEmployeeAndDependence()
{
try {
$emp_code = $this->request->getGet('emp_code');
if ($emp_code) {
$employee = $this->employeeModel->where('emp_code', $emp_code)
->findAll();
$result = $employee;
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],404);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function editEmployeeAndDependence()
{
try {
$data = $this->request->getJSON();
if ($data) {
$updatedCount = 0;
foreach ($data as $item) {
$id = $item->id;
$employee = $this->employeeModel->update($id, (array)$item);
if ($employee) {
$updatedCount++;
}
}
if ($updatedCount > 0) {
$result = [];
return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404);
}
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th], 500);
}
}
public function addEmployeeAndDependence()
{
try {
$data = $this->request->getJSON();
if ($data) {
$Count = 0;
foreach ($data as $item) {
if (isset($item->id)) {
//update old data
$id = $item->id;
$employee = $this->employeeModel->update($id, (array)$item);
if ($employee) {
$Count++;
}
}else{
//create new data
$employee = $this->employeeModel->insert($item);
if ($employee) {
$Count++;
}
}
}
if ($Count > 0) {
$result = [];
return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200);
} else {
$result = "No Matches";
return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404);
}
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function deleteDependence()
{
try {
$delete = $this->employeeModel->where('id', $this->request->getGet('id'))->delete();
if ($delete) {
return $this->respond(['status' => 'success','code' => 200,'data' =>[] ], 200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => [] ], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function getEmployeeAndDependenceByClientId()
{
try {
$empData = $this->employeeModel->where('client_id', $this->request->getGet('client_id'))
->where('relationship !=', null)
->orderBy('emp_code')->orderBy('id')->findAll();
// $result = [];
// foreach ($empData as $employee) {
// $employeeDependence = $this->employeeModel
// ->where('emp_code', $employee['emp_code'])
// ->where('relationship !=', 'self')
// ->findAll();
// // Use object notation to access properties and set 'dependence'
// $employee['dependence'] = $employeeDependence ?: [];
// $result[] = $employee;
// }
// You probably meant to check $result, not $data
if ($empData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $empData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function getClientPolicy()
{
try {
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.id as client_policy_id , client_policy.client_id as client_id, policies.id as policy_id,policies.policy_type_id as policy_type_id, policies.name as policy_name')
->join('policies', 'client_policy.policy_id = policies.id', 'left')
->where('client_policy.client_id', $this->request->getGet('client_id') )
->findAll();
// You probably meant to check $result, not $data
if ($ClientPolicyData) {
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $ClientPolicyData], 200);
} else {
return $this->respond(['status' => 'failed', 'code' => 404, 'data' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function getEmployeePolicy()
{
try {
$id = $this->request->getGet('id');
$keysToRemove = ["removable_keys"];
$empPolicy = $this->employeeModel->getEmployeePolicy($id);
// dd($empPolicy);
if ($empPolicy) {
$result = [];
foreach ($empPolicy as $array) {
$decodedArray = json_decode($array->Policy_Terms);
$refusingData = (object) array_diff_key((array) $decodedArray, array_flip($keysToRemove));
$array->Policy_Terms = $refusingData;
$getSlabAndGridData = $this->policesModel->getPolicySlabRatesForEmpOnboard($array->ClientPolicyId,$array->ClientId);
$array->SlabRates = $getSlabAndGridData['slab_rates'];
$array->GridMaster = $getSlabAndGridData['grid_master'];
if($getSlabAndGridData['grid_master']['policy_type'] == "GPA"){
$default_si = $array->Policy_Terms->sumInsured2;
$index = -1;
foreach ($array->SlabRates as $key => $value) {
if ($value['si'] == $default_si) {
$index = $key;
break;
}
}
if ($index >= 0) {
$element =$array->SlabRates[$index];
array_splice($array->SlabRates, $index, 1);
array_unshift($array->SlabRates, $element);
}
}else if($getSlabAndGridData['grid_master']['policy_type'] == "GMC"){
// re-arranging order of si
$default_si = $array->Policy_Terms->sum_insured;
$index = -1;
foreach ($array->SlabRates as $key => $value) {
if ($value['si'] == $default_si) {
$index = $key;
break;
}
}
if ($index >= 0) {
$element =$array->SlabRates[$index];
array_splice($array->SlabRates, $index, 1);
array_unshift($array->SlabRates, $element);
}
}
$result[] = $array;
}
return $this->respond(['status' => 'success','code' => 200,'data' => $result], 200);
}else{
return $this->respond(['status' => 'failed','code' => 404,'data' => []], 404);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
// Get the RelationShip list
public function createOrUpdateEmployeePolicySiAmount()
{
try {
$requestData = $this->request->getJSON();
$checkIfExist = $this->employeePolicyModel->where('employee_id', $requestData['employee_id'])
->where('client_policy_id', $requestData['client_policy_id'])
->findAll();
// dd($checkIfExist);
if ($checkIfExist) {
$empPolicy = $this->employeePolicyModel->updateSiAndPremium($requestData['client_policy_id'], $requestData['employee_id'], $requestData['basic_cover_si']);
}else{
$data['employee_id']= $requestData['employee_id'];
$data['client_policy_id']= $requestData['client_policy_id'];
$data['basic_cover_si']= $requestData['basic_cover_si'];
$this->employeePolicyModel->insert($data);
}
return $this->respond(['status' => 'success','code' => 200,'data' => []], 200);
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
public function relationshipList()
{
try {
$relation_ships= $this->relationshipModel->findAll();
if(count($relation_ships) > 0){
return $this->respond(['status' => 'success','code' => 200,'data' => $relation_ships], 200);
}else{
return $this->respond(['status' => 'success','code' => 200,'data' => "No Data..!"], 200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
}
}
// Upload the Sheet Data in DB
public function employeeUpload()
{
$file = $this->request->getFile('file');
$client_id = $this->request->getPost('client_id');
$policy_id = $this->request->getPost('policy_id');
$is_moved = $file->move(WRITEPATH . 'uploads/import_excel');
$filename = $file->getName();
$file_name_with_path = WRITEPATH."/uploads/import_excel/".$filename;
//check the file exist or not
if(!file_exists($file_name_with_path))
{
session()->setFlashdata('error', 'File not found');
return redirect()->to(base_url('employee/upload'));
}
// Load the Excel file
$spreadsheet = IOFactory::load($file_name_with_path);
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Get the highest row and column numbers
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$data = [];
// Iterate through each row
for ($row = 1; $row <= $highestRow; $row++) {
// Initialize the row data array
$rowData = [];
// Iterate through each column in the row
for ($col = 'A'; $col <= $highestColumn; $col++) {
// Get the cell value
$value = $sheet->getCell($col . $row)->getValue();
// Add the cell value to the row data array
$rowData[] = $value;
}
// Add the row data to the main data array
$data[] = $rowData;
}
$extractData['file_name']= $filename;
$extractData['client_id']= $client_id;
$extractData['status']= 'success';
$extractData['policy_id']= $policy_id;
$extractData['action']= 'enrollment';
// $extractData['created_by']=set_session_context('Employee');
$file_data =$this->fileModel->insert($extractData);
$extra = [];
for ($i = 0; $i < count($data); $i++) {
if ($i == 0) {
// Loop through the first row to extract keys
for ($j = 0; $j < count($data[$i]); $j++) {
$extra[$data[$i][$j]] = []; // Initialize keys with empty array
}
} else {
// Loop through subsequent rows
for ($j = 0; $j < count($data[$i]); $j++) {
// Append values to corresponding keys in $extra
if (isset($extra[$data[0][$j]])) {
// Make sure the key exists in the $extra array
$extra[$data[0][$j]][] = $data[$i][$j];
}
}
}
}
// print_r("Extra", $extra);die;
$dataToInsert = [];
$basic_cover_si= [];
foreach ($extra['id'] as $index => $id) {
$record = [
// 'id' => $id,
'emp_code' => isset($extra['emp_code'][$index]) ? $extra['emp_code'][$index] : 0,
'name' => $extra['name'][$index],
// Check if the 'doj' key exists before accessing it
'doj' => isset($extra['doj'][$index]) ? $extra['doj'][$index] : null,
'gender' => $extra['gender'][$index],
'relationship' => $extra['relationship'][$index],
'dob' => $extra['dob'][$index],
'email_personal' => $extra['Email'][$index],
'client_id' => $client_id,
];
$record2 = [
'basic_cover_si' => isset($extra['sum_insure'][$index]) ? $extra['sum_insure'][$index] : 0,
];
$dataToInsert[] = $record;
$basic_cover_si[]= $record2;
}
// print_r("dataToInsert", $dataToInsert);die;
for ($a=0; $a <count($dataToInsert) ; $a++)
{
$employee = $this->employeeModel->checkExistingEmpEntrollment($dataToInsert[$a]);
$emp_id =0;
if ($employee) {
$emp_id =$employee['id'];
$id =$emp_id;
$result = $this->employeeModel->update($id, $dataToInsert[$a]);
if ($result) {
$log_message = 'Update Employee - '.$employee['name'].'('.$employee['emp_code'].') with PK '.$employee['id'];
$this->myLogger->logme('error',('Update - ' . $employee['id'].' - '. $employee['emp_code'] .' - '.$employee['name']));
}
}else{
$result = $this->employeeModel->insert($dataToInsert[$a]);
$emp_id =$result;
if ($result) {
$emp = $this->employeeModel->where('id', $result)->get()->getResult();
$policy_name = $this->employeePolicyModel->where('employee_id', $result)->get()->getResult();;
$log_message = 'Insert Employee- '.$dataToInsert[$a]['name'] .'('.$dataToInsert[$a]['emp_code'] .') with PK ';
$this->myLogger->logme('error',('Insert - ' . $dataToInsert[$a]['emp_code'] .' - '. $dataToInsert[$a]['name']));
}
}
$emp_policy_data =[
'employee_id'=>$emp_id,
'client_policy_id'=>$policy_id,
'status'=> 'draft',
'basic_cover_si'=> $basic_cover_si[$a]
];
$employee_policy = $this->employeePolicyModel->checkExistingEmpPolicy(['employee_id' => $emp_id,'client_policy_id' => $policy_id]);
if ($employee_policy) {
foreach ($employee_policy as $existing_policy) {
$this->employeePolicyModel->update($existing_policy['id'], $emp_policy_data);
}
} else {
$emp_policy = $this->employeePolicyModel->insert($emp_policy_data);
}
//trigger
// print_r($dataToInsert[$a]['email_personal']);die;
$policy = $this->clientPolicyModel->where('id', $policy_id)->first();
$policy_name = $this->policesModel->where('id', $policy['policy_id'])->first();
$mail = $dataToInsert[$a]['email_personal'];
$subject = 'Welcome, Employee Benefit Program Enrolment';
$message = 'Dear ' . $dataToInsert[$a]['name'] . ",<br> We are glad to welcome you to the employee benefit program ," .$policy_name['name'] ."offered by your employer, <br><br><br> Click on the link below to review your personal and family details:<br><a href='https://venbait.in/nhance/app/dev'>Review Details</a>" ;
$return_log = MailHelper::send_email($mail,$subject, $message);
$return_log = json_decode($return_log);
$this->myLogger->logme('info', "Email Status : {mail_status}, Sender Email:{email}", ['mail_status' => $return_log->status, 'email'=> $return_log->data]);
}
}
}