diff --git a/.cpanel.yml b/.cpanel.yml old mode 100644 new mode 100755 diff --git a/.env.sample b/.env.sample old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/.htaccess b/.htaccess old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/Papirus-Team-Papirus-Apps-Fusion-icon.512.png b/Papirus-Team-Papirus-Apps-Fusion-icon.512.png old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/app/.htaccess b/app/.htaccess old mode 100644 new mode 100755 diff --git a/app/Common.php b/app/Common.php old mode 100644 new mode 100755 diff --git a/app/Config/App.php b/app/Config/App.php old mode 100644 new mode 100755 diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php index 33f1403b..6cdb37c7 100755 --- a/app/Config/Autoload.php +++ b/app/Config/Autoload.php @@ -99,5 +99,5 @@ class Autoload extends AutoloadConfig * @var string[] * @phpstan-var list */ - public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file']; + public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive']; } diff --git a/app/Config/Boot/development.php b/app/Config/Boot/development.php old mode 100644 new mode 100755 diff --git a/app/Config/Boot/production.php b/app/Config/Boot/production.php old mode 100644 new mode 100755 diff --git a/app/Config/Boot/test.php b/app/Config/Boot/test.php old mode 100644 new mode 100755 diff --git a/app/Config/Boot/testing.php b/app/Config/Boot/testing.php old mode 100644 new mode 100755 diff --git a/app/Config/Boot/uat.php b/app/Config/Boot/uat.php old mode 100644 new mode 100755 diff --git a/app/Config/CURLRequest.php b/app/Config/CURLRequest.php old mode 100644 new mode 100755 diff --git a/app/Config/Cache.php b/app/Config/Cache.php old mode 100644 new mode 100755 diff --git a/app/Config/Constants.php b/app/Config/Constants.php old mode 100644 new mode 100755 index 47b92f83..d86cf312 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -92,3 +92,25 @@ define('EVENT_PRIORITY_NORMAL', 100); * @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead. */ define('EVENT_PRIORITY_HIGH', 10); + +/** + * @User Role Constant + */ + +define('ENROLLMENT_TEAM_ID', '1'); +define('CLAIMS_TEAM_ID', '2'); +define('BUSINESS_TEAM_ID', '3'); +define('FINANCE_TEAM_ID', '4'); +define('SALES_TEAM_ID', '5'); + +/** + * @User Teams Constant + */ + +define('ADMIN_ROLE_ID', 1); +define('MANAGER_ROLE_ID', 2); +define('ACCOUNT_MANAGER_ROLE_ID', 3); +define('STAFF_ROLE_ID', 4); +define('HEAD_ROLE_ID', 5); + + diff --git a/app/Config/ContentSecurityPolicy.php b/app/Config/ContentSecurityPolicy.php old mode 100644 new mode 100755 diff --git a/app/Config/Cookie.php b/app/Config/Cookie.php old mode 100644 new mode 100755 diff --git a/app/Config/Database.php b/app/Config/Database.php old mode 100644 new mode 100755 diff --git a/app/Config/Email.php b/app/Config/Email.php old mode 100644 new mode 100755 diff --git a/app/Config/Encryption.php b/app/Config/Encryption.php old mode 100644 new mode 100755 diff --git a/app/Config/Events.php b/app/Config/Events.php old mode 100644 new mode 100755 diff --git a/app/Config/Exceptions.php b/app/Config/Exceptions.php old mode 100644 new mode 100755 diff --git a/app/Config/Feature.php b/app/Config/Feature.php old mode 100644 new mode 100755 diff --git a/app/Config/Filters.php b/app/Config/Filters.php old mode 100644 new mode 100755 diff --git a/app/Config/ForeignCharacters.php b/app/Config/ForeignCharacters.php old mode 100644 new mode 100755 diff --git a/app/Config/Format.php b/app/Config/Format.php old mode 100644 new mode 100755 diff --git a/app/Config/Generators.php b/app/Config/Generators.php old mode 100644 new mode 100755 diff --git a/app/Config/Honeypot.php b/app/Config/Honeypot.php old mode 100644 new mode 100755 diff --git a/app/Config/Images.php b/app/Config/Images.php old mode 100644 new mode 100755 diff --git a/app/Config/Kint.php b/app/Config/Kint.php old mode 100644 new mode 100755 diff --git a/app/Config/Logger.php b/app/Config/Logger.php old mode 100644 new mode 100755 diff --git a/app/Config/Migrations.php b/app/Config/Migrations.php old mode 100644 new mode 100755 diff --git a/app/Config/Mimes.php b/app/Config/Mimes.php old mode 100644 new mode 100755 diff --git a/app/Config/Modules.php b/app/Config/Modules.php old mode 100644 new mode 100755 diff --git a/app/Config/Pager.php b/app/Config/Pager.php old mode 100644 new mode 100755 diff --git a/app/Config/Paths.php b/app/Config/Paths.php old mode 100644 new mode 100755 diff --git a/app/Config/Publisher.php b/app/Config/Publisher.php old mode 100644 new mode 100755 diff --git a/app/Config/Routes.php b/app/Config/Routes.php old mode 100644 new mode 100755 index f4eb5e87..dd81efc5 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -131,6 +131,13 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->post("edit", "ClientController::editClientPolicyPremium"); $routes->post("other_terms", "ClientController::otherPolicyTermsFormSubmit"); }); + + $routes->group("vehicle", ["filter" => "authMVC"], function ($routes) { + $routes->post("create", "ClientController::uploadVehicleFile"); + $routes->post("edit", "ClientController::editUploadVehicleFile"); + $routes->get("list/(:any)", "ClientController::listVehicleFiles/$1"); + $routes->get("delete/(:any)", "ClientController::deleteVehicleFiles/$1"); + }); }); @@ -234,6 +241,12 @@ $routes->group("/master", ["filter" => "authMVC"], function ($routes) { $routes->get("list/(:any)", "MasterController::getCDMasterDataByID/$1"); $routes->get("remove/(:any)", "MasterController::removeCDMaster/$1"); }); + + $routes->group("vehicle", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "MasterController::VehicleMasterList"); + $routes->get("list/(:any)", "MasterController::getVehicleMasterDataByID/$1"); + $routes->get("remove/(:any)", "MasterController::deactiveVehicleData/$1"); + }); }); @@ -278,12 +291,78 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("copy_insurer_templete/(:any)", "MasterController::copyInsurerTemplete/$1"); $routes->get("get_single_excel_template/(:any)", "MasterController::getSingleExcelTemplate/$1"); $routes->get("dublicate_template/(:any)", "MasterController::duplicateTemplate/$1"); + $routes->get("getBranchByClientID/(:any)", "ClientController::getBranchByClientID/$1"); + $routes->get("getPolicyDetailsByPolicyId/(:any)", "ClientController::getPolicyDetailsByPolicyId/$1"); + $routes->get("getClientAndBranchAndPolicy", "ClientController::getClientAndBranchAndPolicy"); + $routes->get("getCDAccNoByClientAndInsurer/(:any)", "ClientController::getCDAccNoByClientAndInsurer/$1"); + $routes->post("createClientWithMinimalData", "ClientController::createClientWithMinimalData"); + $routes->post("createVehicleWithMinimalData", "ClientController::createVehicleWithMinimalData"); + $routes->post("createClientBranchWithMinamalData", "ClientController::createClientBranchWithMinamalData"); + $routes->post("createClientPolicyWithMinimalData", "ClientController::createClientPolicyWithMinimalData"); + $routes->post("createCDAccountNumberUsingAjax", "MasterController::createCDAccountNumberUsingAjax"); + $routes->post("drive_file_upload", "PolicyTransactionController::uploadFile"); + $routes->post("updateInvoiceStatus", "PolicyTransactionController::updateInvoiceStatus"); + $routes->get("remove_co_share_data/(:any)", "PolicyTransactionController::removeCoShareData/$1"); + $routes->get("check_cost_center/(:any)", "ClientController::check_cost_center/$1"); + $routes->get("getPTCOShareCount/(:any)", "PolicyTransactionController::getPTCOShareCount/$1"); + $routes->get("test_mail", "MasterController::testGmailAPI"); + $routes->post("test_mail", "MasterController::testGmailAPI"); + $routes->get("check_policy_no/(:any)", "ClientController::check_policy_no/$1"); + $routes->get("get_client_policy_data_using_policy_no/(:any)", "ClientController::get_client_policy_data_using_policy_no/$1"); + $routes->get("get_client_policy_data_using_policy_no_and_endo_no/(:any)", "ClientController::get_client_policy_data_using_policy_no_and_endo_no/$1"); + $routes->get("checkInvoiceStatus/(:any)", "PolicyTransactionController::checkInvoiceStatus/$1"); + $routes->get("base_policy_for_policy_inception/(:any)", "PolicyTransactionController::getBasePolicy/$1"); }); + +$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) { + + $routes->group("inception", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "PolicyTransactionController::viewInception"); + $routes->post("create", "PolicyTransactionController::createInceptionPolicy"); + $routes->get("list/(:any)", "PolicyTransactionController::getInceptionDataForEdit/$1"); + $routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1"); + }); + + $routes->group("endorsement", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "PolicyTransactionController::viewEndorsement"); + $routes->post("create", "PolicyTransactionController::createEndorsementPolicy"); + $routes->get("list/(:any)", "PolicyTransactionController::getEndorsementDataForEdit/$1"); + $routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1"); + }); + + $routes->group("report", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "PolicyTransactionController::reportBDS"); + $routes->get("report-varience-list", "PolicyTransactionController::reportVarience"); + $routes->get("report-business-list", "PolicyTransactionController::reportBusinessList"); + $routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList"); + }); + + $routes->group("statement", ["filter" => "authMVC"], function ($routes) { + $routes->get("list", "PolicyTransactionController::statementList"); + $routes->post("upload", "PolicyTransactionController::uploadInsurerStatement"); + $routes->get("getPaymentDetails/(:any)", "PolicyTransactionController::getInvoicePaymentDetails/$1"); + $routes->post("saveInvoicePaymentDetails", "PolicyTransactionController::saveInvoicePaymentDetails"); + $routes->get("deletePaymentEntry/(:any)", "PolicyTransactionController::deletePaymentEntry/$1"); + $routes->get("downloadSampleInsurerStatement", "PolicyTransactionController::downloadSampleInsurerStatement"); + $routes->get("getFileErr/(:any)", "PolicyTransactionController::getFileErr/$1"); + }); + +}); + +$routes->get("driveListFiles", "GoogleDriveController::listFiles"); +$routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); +$routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); +$routes->get('downloadGdriveFile', 'GoogleDriveController::downloadGdriveFile', ['filter' => 'authMVC']); + $routes->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); -$routes->cli('cli/enrollment_status', 'JobWorker::enrollment_status'); + $routes->get("processjob", "JobWorker::processJob"); +$routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken'); +$routes->cli('cli/send_mail_cli(/:any)?', 'MasterController::testGmailAPIViaCLI$1'); +$routes->cli('cli/app_check_list', 'MasterController::appCheckList'); +$routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDriveAccessToken'); @@ -304,16 +383,18 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { - - $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { + $routes->post("storeFireBase", "EmployeeRestController::storeFireBase"); $routes->post("saveMpin", "RestAuthenticationController::saveMpin"); $routes->post("updateMpin", "RestAuthenticationController::updateMpin"); - $routes->get("getChatResponse", "ChatBotController::getChatResponse"); + $routes->post("getChatResponse", "ChatBotController::getChatResponse"); $routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile"); + $routes->post("employeeUpload", "EmployeeRestController::employeeUpload"); + $routes->get("relationshipList", "EmployeeRestController::relationshipList"); + $routes->get("getEmployeeAndDependence", "EmployeeRestController::getEmployeeAndDependence"); $routes->post("editEmployeeAndDependence", "EmployeeRestController::editEmployeeAndDependence"); $routes->post("addEmployeeAndDependence", "EmployeeRestController::addEmployeeAndDependence"); diff --git a/app/Config/Routing.php b/app/Config/Routing.php old mode 100644 new mode 100755 diff --git a/app/Config/Security.php b/app/Config/Security.php old mode 100644 new mode 100755 diff --git a/app/Config/Services.php b/app/Config/Services.php old mode 100644 new mode 100755 index e9a21d37..fab85a50 --- a/app/Config/Services.php +++ b/app/Config/Services.php @@ -5,6 +5,8 @@ namespace Config; use CodeIgniter\Config\BaseService; use App\Libraries\Slug; use App\Libraries\MyLogger; +use App\Libraries\GmailAPI; +use App\Libraries\MyGoogleDrive; use App\Libraries\DataServiceSqlite; use App\Controllers\Home; @@ -60,5 +62,23 @@ class Services extends BaseService return new DataServiceSqlite(); } + + public static function gmailapi($getShared = true) + { + if ($getShared) { + return static::getSharedInstance('gmailapi'); + } + + return new GmailAPI(); + } + + public static function myGoogleDrive($getShared = true) + { + if ($getShared) { + return static::getSharedInstance('myGoogleDrive'); + } + + return new MyGoogleDrive(); + } } diff --git a/app/Config/Session.php b/app/Config/Session.php old mode 100644 new mode 100755 diff --git a/app/Config/Toolbar.php b/app/Config/Toolbar.php old mode 100644 new mode 100755 diff --git a/app/Config/UserAgents.php b/app/Config/UserAgents.php old mode 100644 new mode 100755 diff --git a/app/Config/Validation.php b/app/Config/Validation.php old mode 100644 new mode 100755 diff --git a/app/Config/View.php b/app/Config/View.php old mode 100644 new mode 100755 diff --git a/app/Config/google-services.json b/app/Config/google-services.json old mode 100644 new mode 100755 diff --git a/app/Controllers/AdminController.php b/app/Controllers/AdminController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/AppContentManagementController.php b/app/Controllers/AppContentManagementController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/BaseController.php b/app/Controllers/BaseController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/ChatBotController.php b/app/Controllers/ChatBotController.php old mode 100644 new mode 100755 index bb47fe6a..afc79b5e --- a/app/Controllers/ChatBotController.php +++ b/app/Controllers/ChatBotController.php @@ -74,39 +74,61 @@ class ChatBotController extends AdminController public function getChatResponse() { // try { - $request_for = $this->request->getGet('request_for'); - $option = $this->request->getGet('option'); - $is_option = $this->request->getGet('is_option'); + $emp_code = $this->request->getVar('emp_code'); + $client_id = $this->request->getVar('client_id'); + $client_branch_id = $this->request->getVar('client_branch_id'); + $request_for = $this->request->getVar('request_for'); + $option = $this->request->getVar('option'); + $is_option = $this->request->getVar('is_option'); $responseData = $this->ChatBotModel->where('request', $request_for) ->where('is_active', 1 ) ->first(); - + + if ($responseData) { - if(isset($option) && $option != 0){ + if(isset($option) && $option != 0) + { $decodedData = json_decode($responseData['options'],true); - - + if (isset($decodedData[$option]) && $decodedData[$option] !== null) { + $requestFor = $decodedData[$option]; $responseData = $this->ChatBotModel->where('request', $requestFor) ->where('is_active', 1 ) ->first(); + if($responseData['request'] == 'Call' || $responseData['request'] == 'Mail'){ + + $AccountManagerDetails = $this->clientRMModel->select('client_rm.* , user_profiles.*') + ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left') + ->where('client_rm.client_id', $client_id ) + ->where('client_rm.level', 3 ) + ->findAll(); + + if(isset($AccountManagerDetails) && $responseData['request'] == 'Call'){ + $responseData['options'] = $AccountManagerDetails[0]['mobile']; + }else if(isset($AccountManagerDetails) && $responseData['request'] == 'Mail'){ + $responseData['options'] = $AccountManagerDetails[0]['email']; + } + } + }else{ - if( $request_for == 'Create claim'){ + if( $request_for == 'Initiate claim'){ $result = [ 'request_for' => $request_for, 'options' => json_decode($responseData['options'], true), 'text' => "Enter Message", 'is_option' => "0", 'policy_id' => $option, - 'mobile_no' => $this->request->getGet('mobile_no') + 'mobile_no' => $this->request->getVar('mobile_no'), + 'navigation' => $responseData['navigation'], + 'navigation_type' => $responseData['navigation_type'] ]; return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); @@ -123,19 +145,30 @@ class ChatBotController extends AdminController if(isset($is_option) && $is_option == 0){ - $text = $this->request->getGet('text'); - $value = $this->request->getGet('value'); + $text = $this->request->getVar('text'); + $value = $this->request->getVar('value'); + $Data = $this->ChatBotModel->where('options', $text)->where('is_active', 1 )->first(); + if($Data){ if($Data['options'] == 'Please Enter Your Mobile Number To View Your Policies') { + $result = $this->getAllPolicyByMobileNumber($value,'text'); return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); - }else if($Data['options'] == 'Please Enter Your Mobile Number To Raise Ticket'){ + + }else if($Data['options'] == 'Please Enter Your Mobile Number To Raise Claim'){ + $result = $this->getAllPolicyByMobileNumber($value,'options'); return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); - } + + }else if( $Data['options'] == 'Enter Your Claim Number'){ + + $result = $this->getTicket($value,$emp_code,$client_id); + return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); + + } }else{ @@ -151,8 +184,10 @@ class ChatBotController extends AdminController $result = [ 'request_for' => $request_for, 'options' => null, - 'text' => $ticket['message'].', Your Ticket id is '.$ticket['ticket_id'], - 'is_option' => "0" + 'text' => $ticket['message'].', Your Claim id is '.$ticket['ticket_id'], + 'is_option' => "0", + 'navigation' => "0", + 'navigation_type' => null ]; }else{ @@ -160,16 +195,19 @@ class ChatBotController extends AdminController 'request_for' => $request_for, 'options' => null, 'text' => $ticket['message'], - 'is_option' => "0" + 'is_option' => "0", + 'navigation' => "0", + 'navigation_type' => null ]; } return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); + }else{ - $result = $this->sendDefaultMessage(); - return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); + $result = $this->sendDefaultMessage(); + return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); } } @@ -178,11 +216,15 @@ class ChatBotController extends AdminController + + $result = [ 'request_for' => $responseData['request'], 'options' => json_decode($responseData['options'], true), 'text' => $responseData['is_option'] != 1 ? $responseData['options'] : null, - 'is_option' => $responseData['is_option'] + 'is_option' => $responseData['is_option'], + 'navigation' => $responseData['navigation'], + 'navigation_type' => $responseData['navigation_type'] ]; return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200); @@ -190,180 +232,215 @@ class ChatBotController extends AdminController - } else { - - return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); - } + } else { + + return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404); + } // } catch (\Throwable $th) { // return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500); // } } -public function sendDefaultMessage() -{ - $responseData = $this->ChatBotModel->where('id', 1)->where('is_active', 1 )->first(); - return [ - 'request_for' => $responseData['request'], - 'options' => json_decode($responseData['options'], true), - 'text' => $responseData['is_option'] != 1 ? $responseData['options'] : null, - 'is_option' => $responseData['is_option'] - ]; - - -} + public function sendDefaultMessage() + { + $responseData = $this->ChatBotModel->where('id', 1)->where('is_active', 1 )->first(); + return [ + 'request_for' => $responseData['request'], + 'options' => json_decode($responseData['options'], true), + 'text' => $responseData['is_option'] != 1 ? $responseData['options'] : null, + 'is_option' => $responseData['is_option'], + 'navigation' => $responseData['navigation'], + 'navigation_type' => $responseData['navigation_type'] + ]; + + + } -public function getAllPolicyByMobileNumber($mobileNo,$action) -{ - $employee = $this->employeeModel->where('mobile', $mobileNo)->where('is_active', 1 )->first(); - if($employee){ + public function getAllPolicyByMobileNumber($mobileNo,$action) + { + $employee = $this->employeeModel->where('mobile', $mobileNo)->where('is_active', 1 )->first(); + if($employee){ - $employeeData = $this->employeeModel->where('emp_code', $employee['emp_code']) - ->where('client_id',$employee['client_id']) - ->where('client_branch_id',$employee['client_branch_id']) - ->where('is_active', 1 )->findAll(); - $whereArrayForId = []; - foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } + $employeeData = $this->employeeModel->where('emp_code', $employee['emp_code']) + ->where('client_id',$employee['client_id']) + ->where('client_branch_id',$employee['client_branch_id']) + ->where('is_active', 1 )->findAll(); + $whereArrayForId = []; + foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); } - $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policies.name as policy_name , policy_type.policy_type as policy_type') - ->join('policies', 'client_policy.policy_id = policies.id', 'left') - ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') - ->where('client_policy.client_id', $employee['client_id'] ) - ->where('client_policy.client_branch_id', $employee['client_branch_id'] ) - ->where('client_policy.is_active', 1 ) - ->where('client_policy.policy_status', 1) - ->orderby('client_policy.id' , 'ASC') - ->findAll(); - $options = []; - $text = ''; - if(count($ClientPolicyData) > 0 && count($employeeData) > 0) - { - - foreach ($ClientPolicyData as $key => $ClientPolicyValue) { + $ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.long_name as policy_name , policy_type.policy_type as policy_type') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') + ->where('client_policy.client_id', $employee['client_id'] ) + ->where('client_policy.client_branch_id', $employee['client_branch_id'] ) + ->where('client_policy.is_active', 1 ) + ->where('client_policy.policy_status', 1) + ->orderby('client_policy.id' , 'ASC') + ->findAll(); + $options = []; + $text = ''; + if(count($ClientPolicyData) > 0 && count($employeeData) > 0) + { + + foreach ($ClientPolicyData as $key => $ClientPolicyValue) { - $data['policy_name'] = $ClientPolicyValue['policy_name']; - $data['policy_type'] = $ClientPolicyValue['policy_type']; - $data['policy_no'] = $ClientPolicyValue['policy_no']; - + $data['policy_name'] = $ClientPolicyValue['policy_name']; + $data['policy_type'] = $ClientPolicyValue['policy_type']; + $data['policy_no'] = $ClientPolicyValue['policy_no']; + - - $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid') - ->join('employees', 'employee_polices.employee_id = employees.id', 'left') - ->whereIn('employee_polices.employee_id',$whereArrayForId) - ->where('employee_polices.client_policy_id',$ClientPolicyValue['id']) - ->where('employee_polices.is_active', 1 )->findAll(); - if(count($employee_policy) > 0) - { - $policy[$ClientPolicyValue['id']] = $ClientPolicyValue['policy_name']."(".$ClientPolicyValue['policy_type'].")"; - array_push($options, $policy); - $text .= $ClientPolicyValue['policy_name']."(".$ClientPolicyValue['policy_type'].") % "; + + $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid') + ->join('employees', 'employee_polices.employee_id = employees.id', 'left') + ->whereIn('employee_polices.employee_id',$whereArrayForId) + ->where('employee_polices.client_policy_id',$ClientPolicyValue['id']) + ->where('employee_polices.is_active', 1 )->findAll(); + if(count($employee_policy) > 0) + { + $policy[$ClientPolicyValue['id']] = $ClientPolicyValue['policy_name']."(".$ClientPolicyValue['policy_type'].")"; + array_push($options, $policy); + $text .= $ClientPolicyValue['policy_name']." % "; + }else{ + $text .= "There is no any active policies "; + } + + } + if($action == 'options'){ + return [ + 'request_for' => $this->request->getVar('request_for'), + 'options' => $options[count($options) - 1], + 'text' => null, + 'is_option' => "1", + 'mobile_no' => $mobileNo, + ]; }else{ - $text .= "There is no any active policies "; + return [ + 'request_for' => $this->request->getVar('request_for'), + 'options' => null, + 'text' => $text, + 'is_option' => "0", + 'mobile_no' => $mobileNo, + ]; } - } - if($action == 'options'){ - return [ - 'request_for' => $this->request->getGet('request_for'), - 'options' => $options[count($options) - 1], - 'text' => null, - 'is_option' => "1", - 'mobile_no' => $mobileNo, - ]; + + }else{ return [ - 'request_for' => $this->request->getGet('request_for'), + 'request_for' => $this->request->getVar('request_for'), 'options' => null, - 'text' => $text, - 'is_option' => "0", - 'mobile_no' => $mobileNo, + 'text' => "Dear ".$employee['name']." Policy not yet bound for you.", + 'is_option' => "0" ]; + } + - - + }else{ return [ - 'request_for' => $this->request->getGet('request_for'), + 'request_for' => $this->request->getVar('request_for'), 'options' => null, - 'text' => "Dear ".$employee['name'].", % Policy not yet bound for you.", + 'text' => "Invalid Mobile Number", 'is_option' => "0" ]; - } - - }else{ - return [ - 'request_for' => $this->request->getGet('request_for'), - 'options' => null, - 'text' => "Invalid Mobile Number", - 'is_option' => "0" - ]; } + + public function claimTicket() + { -} + $employee = $this->employeeModel->where('mobile', $this->request->getVar('mobile_no'))->where('is_active', 1 )->first(); + if($employee){ -public function claimTicket() -{ - + $url = 'https://venbait.in/nhance/helpdesk/dev/api/tickets/create'; - $employee = $this->employeeModel->where('mobile', $this->request->getGet('mobile_no'))->where('is_active', 1 )->first(); - if($employee){ + + $token = 'uncp8FvG310bEyYdV9MmStlo7KDRZ65fLWTeXCI2JzwPrNHjBqQhUiAgxsaO'; + $headers = [ + 'Token: ' . $token, + ]; - $url = 'https://venbait.in/nhance/helpdesk/dev/api/tickets/create'; + // Form data + $data = [ + 'opener' => 'user', + 'department_id' => 2, + 'subject' => 'Claim Raised by Chat Bot', + 'body' => $this->request->getVar('value'), + 'policy_id' => $this->request->getVar('policy_id'), + 'emp_code' => $employee['emp_code'], + 'mobile_number' => $this->request->getVar('mobile_no'), + 'email' => 'adhavanvalli@gmail.com', + 'fullname' => $employee['name'], + ]; + + // Initialize cURL session + $ch = curl_init(); + + // Set cURL options + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + $response = curl_exec($ch); + return $response; + // Check for errors + // if (curl_errno($ch)) { + // $error = curl_error($ch); + // curl_close($ch); + // return ['status' => 'failed', 'response' => $error]; + // } else { + // // Close cURL session + // curl_close($ch); + // return ['status' => 'success', 'response' => $response]; + // } + }else{ + return ['status' => 'failed', 'response' => 'Employee Not Found']; + } + } + + public function getTicket($value, $emp_code, $client_id) + { + // Construct the URL with query parameters + $url = 'https://venbait.in/nhance/helpdesk/dev/api/tickets/show/' . $value; + $token = 'uncp8FvG310bEyYdV9MmStlo7KDRZ65fLWTeXCI2JzwPrNHjBqQhUiAgxsaO'; $headers = [ 'Token: ' . $token, ]; - - // Form data - $data = [ - 'opener' => 'user', - 'department_id' => 2, - 'subject' => 'Claim Raised by Chat Bot', - 'body' => $this->request->getGet('value'), - 'policy_id' => $this->request->getGet('policy_id'), - 'emp_code' => $employee['emp_code'], - 'mobile_number' => $this->request->getGet('mobile_no'), - 'email' => 'adhavanvalli@gmail.com', - 'fullname' => $employee['name'], - ]; - + // Initialize cURL session $ch = curl_init(); - + // Set cURL options curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - + + // Execute cURL request $response = curl_exec($ch); -return $response; + // Check for errors - // if (curl_errno($ch)) { - // $error = curl_error($ch); - // curl_close($ch); - // return ['status' => 'failed', 'response' => $error]; - // } else { - // // Close cURL session - // curl_close($ch); - // return ['status' => 'success', 'response' => $response]; - // } - - - }else{ - return ['status' => 'failed', 'response' => 'Employee Not Found']; + if (curl_errno($ch)) { + $error = curl_error($ch); + curl_close($ch); + return ['status' => 'failed', 'response' => $error]; + } else { + // Close cURL session + curl_close($ch); + return ['status' => 'success', 'response' => $response]; + } } -} + diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php old mode 100644 new mode 100755 index 5439e64e..586665eb --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -2,6 +2,7 @@ namespace App\Controllers; use App\Helpers\DepositHelper; +use App\Helpers\MailHelper; use App\helpers\JWTToken; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; @@ -33,10 +34,12 @@ use App\Models\EmployeePolicyModel; use App\Models\NotificationModel; use App\Models\CDMasterModel; use App\Models\PolicyTypeModel; +use App\Models\PolicyTransactionModel; +use App\Models\PolicyTransactionStatusModel; +use App\Models\VehicleModel; - - - +use App\Controllers\EmpDataServiceController; +use App\Controllers\GoogleDriveController; class ClientController extends AdminController @@ -68,6 +71,10 @@ class ClientController extends AdminController protected $notificationModel; protected $CDMasterModel; protected $policyTypeModel; + protected $policyTransactionModel; + protected $policyTransactionStatusModel; + protected $vehicleModel; + public function __construct() @@ -99,6 +106,10 @@ class ClientController extends AdminController $this->notificationModel = new NotificationModel(); $this->CDMasterModel = new CDMasterModel(); $this->policyTypeModel = new PolicyTypeModel(); + $this->policyTransactionModel = new PolicyTransactionModel(); + $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); + $this->vehicleModel = new VehicleModel(); + @@ -108,43 +119,9 @@ class ClientController extends AdminController } public function Testing() //this function for only tsesting some logics not use for business logic - { - $results = $this->clientPolicyModel - ->select('id, policy_terms') - ->where('policy_terms IS NOT NULL') - ->where('policy_terms <>', '') - ->whereNotIn('policy_type_id', [1, 6, 7]) - ->orderBy('id', 'desc') - ->get() - ->getResultArray(); - - foreach ($results as $key => $result) { - $client_policy_id = $result['id']; - $policy_terms = json_decode($result['policy_terms'], true); // true to get associative array - - if (isset($policy_terms['family_floaters'])) { - $family_floaters = $policy_terms['family_floaters']; - $parents = $family_floaters['parents'] ?? 0; - $parents_in_law = $family_floaters['parents-in-law'] ?? 0; - - if ($parents == 1 && $parents_in_law == 1) { - $policy_terms['family_floaters']['parents'] = 0; - $policy_terms['family_floaters']['parents-in-law'] = 0; - $policy_terms['family_floaters']['either-parents-pil'] = 2; - - - $results[$key]['policy_terms'] = json_encode($policy_terms); - - // Update the policy_terms in the database - $this->clientPolicyModel - ->where('id', $client_policy_id) - ->set('policy_terms', $results[$key]['policy_terms']) - ->update(); - } - } - } - - dd($results); + { + // $empDataServiceController = new EmpDataServiceController(); + // $empDataServiceController->storeEndorsementNumber(23, '00000000000000000560'); } public function index() @@ -289,6 +266,7 @@ class ClientController extends AdminController $data['policyGridData'] = $this->policyGridModel->findAll(); $data['policy_types'] = $this->policyTypeModel->findAll(); $data['policy_type'] = ['1'=>'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon']; + $data['client_type'] = ['1'=>'Group', '2' => 'Retail']; // echo "
";
         // print_r($data); die;
@@ -343,10 +321,10 @@ class ClientController extends AdminController
 
         $data['subTypeOptions'] = $subTypeOptions;
         $headerData['page_name'] = 'Client Deposit';
-        $data['insurerName']= $this->insurerModel->getInsurerName($insurerId);
         $loggedInUserID = get_session_userid();
         // $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId);
         $clientId = $this->request->getGet('client_id');
+        $data['insurerName']= $this->insurerModel->getInsurerName($insurerId, $clientId);
         $data['depositdata']= $this->clientPolicyModel->getdepositData($clientId,$insurerId); 
         $data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
         $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId);  
@@ -354,7 +332,7 @@ class ClientController extends AdminController
         // dd($data['depositdata']);
         
         // print_r($data['depositdata'] );die;
-        // Load the view for the new list page
+        // Load the view for the new list page;
         echo view('layout/header', $headerData);
         echo view('view_deposit',$data);
         echo view('layout/footer');
@@ -412,6 +390,7 @@ class ClientController extends AdminController
         $editData['policyGridData'] = $this->policyGridModel->findAll();
         $editData['policy_types'] = $this->policyTypeModel->findAll();
         $editData['policy_type'] = ['1'=>'Base Policy', '2' => 'SI Topup', '3' => 'Dependent Addon'];
+        $editData['client_type'] = ['1'=>'Group', '2' => 'Retail'];
 
         // dd($editData['policy_types']);
 
@@ -451,6 +430,7 @@ class ClientController extends AdminController
         $data   = $this->request->getPost();
         $data['created_by'] = get_session_userid();
         $data['client_logo'] = $file_name;
+        $data['client_code'] = generate_client_code();
 
 
         if (!isset($data['is_download_btn'])) {
@@ -502,15 +482,23 @@ class ClientController extends AdminController
         }
     }
     
+
+
     public function createClientKYCInfo()
     {
         $this->myLogger->logme('error','create Client kyc function called');  
         $data = $this->request->getPost();     
+        // print_r($data); die;
         unset($data['file_name']); 
         $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
         $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath);
         if(!empty($File)){
+            
             $data['file_name'] = $File;
+            $uploadFilePath = $uploadFilePath . '/' .$File;
+            $GoogleDriveController = new GoogleDriveController();
+            $GoogleDriveController->uploadFiletoGdrive(client_id: $data['client_id'], doc_type: 'KYC', file_path: $uploadFilePath, file_name: $data['file_name']);
+    
         }
 
         $data['created_by'] = get_session_userid();
@@ -665,11 +653,21 @@ class ClientController extends AdminController
 
         $this->myLogger->logme('error','Client branch CREATE function called');
         $data   = $this->request->getPost();
+        // var_dump($data); die;
         if (!isset($data['sez'])) {
             $data['sez'] = 0;
         } elseif ($data['sez']) {
             $data['sez'] = 1;
         }
+
+        $units = json_decode($data['units'], true) ?? [];
+
+        if (!is_array($units) || empty($units)) {
+            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
+            $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
+            $data['units'] = json_encode([$default_unit]);
+        }
+        
         $data['created_by'] = get_session_userid();
         $insert = $this->clientBranchModel->insert($data); 
         
@@ -723,6 +721,12 @@ class ClientController extends AdminController
         
         $list_of_branch_units = $this->clientBranchModel->find($id);
         $units = json_decode($list_of_branch_units['units']);
+
+        if (!is_array($units) || empty($units)) {
+            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
+            $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
+            $data['units'] = json_encode([$default_unit]);
+        }
         
         if (!empty($units)) {
             foreach ($units as $unit) {
@@ -733,6 +737,7 @@ class ClientController extends AdminController
         
             $total_count = $emp_unit_count + $rr_unit_count + $rr_unit_count2;
         }
+
         $uncommonValues = [];
 
         if ($total_count > 0) {
@@ -758,7 +763,6 @@ class ClientController extends AdminController
             }
         }
         
-
         if (!isset($data['sez'])) {
             $data['sez'] = 0;
         } elseif ($data['sez']) {
@@ -819,7 +823,6 @@ class ClientController extends AdminController
         $policy_type_id   = $this->request->getPost('policy_type_id');
         $client_branch_id = $this->request->getPost('client_branch_id');
         $client_id        = $this->request->getPost('client_id');
-        $policy_type_id   = $this->request->getPost('policy_type_id');
         $base_policy      = $this->request->getPost('base_policy');
 
 
@@ -843,7 +846,6 @@ class ClientController extends AdminController
         $data['client_id']         = $client_id;
         $data['tpa_branch_id']     = $tpaBranchId;
         $data['tpa_id']            = $tpaId;
-        // $data['policy_id']         = $this->request->getPost('policy_id');
         $data['policy_type_id']    = $this->request->getPost('policy_type_id');
 
         $data['no_of_lives']                        = $this->request->getPost('no_of_lives');
@@ -864,47 +866,24 @@ class ClientController extends AdminController
         $data['cd_ac_no']                           = $this->request->getPost('cd_ac_no');
         $data['gst']                                = $this->request->getPost('gst');
         
+
         if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7){
 
-            $data['is_addon'] = 1;
+            $data['is_addon'] = 1; // Base Policy
 
         }else if($policy_type_id == 4 || $policy_type_id == 5){
 
-            $data['is_addon'] = 2;
+            $data['is_addon'] = 2; // SI TOPUP
 
         }else if($policy_type_id == 3){
            
             if($base_policy){
-                $data['is_addon'] = 3;
+                $data['is_addon'] = 3; // Dependent Addon
             }else{
                 $data['is_addon'] = 1;
             }
         }
                     
-        $policy_terms =  $this->clientPolicyModel->where('id', $this->request->getPost('base_policy'))->first();
-
-        // if ($this->request->getPost('is_addon') == 2 || $this->request->getPost('is_addon') == 3) {
-
-        //     if ($this->request->getPost('is_addon') == 3) {
-        //         $policyTerm = $policy_terms['policy_terms'];
-        //         $decoded_policyTerm = json_decode($policyTerm, true);
-        //         $decoded_policyTerm['family_floater'] = 0;
-        //         $decoded_policyTerm['family_floaters']['self'] = 0;
-        //         $decoded_policyTerm['family_floaters']['spouse'] = 0;
-        //         $decoded_policyTerm['family_floaters']['childrens'] = 0;
-        //         $decoded_policyTerm['family_floaters']['parents'] = 0;
-        //         $decoded_policyTerm['family_floaters']['parents-in-law'] = 0;
-        //         $decoded_policyTerm['family_floaters']['either-parents-pil'] = 0;
-
-        //         $data['policy_terms'] =  json_encode($decoded_policyTerm);
-        //     } else {
-
-        //         if ($this->request->getPost('policy_type_id') != 3) {
-
-        //             $data['policy_terms'] =  $policy_terms['policy_terms'];
-        //         }
-        //     }
-        // } 
 
         $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
         $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
@@ -922,8 +901,41 @@ class ClientController extends AdminController
 
         $data['created_by']        = get_session_userid();
 
+        $policy_tranction_data = [
+
+            'issuer' => 2,
+            'client_id' => $this->request->getPost('client_id'),
+            'client_branch_id' => $this->request->getPost('client_branch_id'),
+            'insurer_id' => $insurerId,
+            'insurer_branch_id' => $insurerBranchId,
+            'issue_type' => 1,
+            'policy_no' => $this->request->getPost('policy_no'),
+            'cd_ac_no' => $this->request->getPost('cd_ac_no'),
+            'policy_issue_date' => date('Y-m-d'),
+            'policy_start_date' => change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'),
+            'policy_end_date' => change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'),
+            'action_type' => 'inception',
+            'status' => 'pending',
+            'created_by' => get_session_userid(),
+        ];
+
+
+
         $insert = $this->clientPolicyModel->insert($data);
         if($insert){
+            
+            $policy_tranction_data['client_policy_id'] = $insert;
+            $policy_tranction_data_insert = $this->policyTransactionModel->insert($data);
+            if($policy_tranction_data_insert){
+                $statusData = [
+                    'policy_tran_id' => $policy_tranction_data_insert,
+                    'status' => 'pending',
+                    'created_by' => get_session_userid(),
+                ];
+                $this->policyTransactionStatusModel->insert($statusData);
+            }
+
+
             $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($this->request->getPost('client_id'));
             $clientPoliceData['role'] = get_role_id();
             return $this->respond(['status' => true,'code' => 200,'data' => $clientPoliceData, 'method' => 'CERATE', 'post_data' => $data], 200);
@@ -941,6 +953,8 @@ class ClientController extends AdminController
         $id        = $this->request->getPost('PrimaryKey');
         $client_id = $this->request->getPost('client_id');
         $policy_type_id = $this->request->getPost('policy_type_id');
+        $base_policy      = $this->request->getPost('base_policy');
+
 
         $insurerValue                      = (string) $this->request->getPost('insurer');
         list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
@@ -991,17 +1005,34 @@ class ClientController extends AdminController
             $data['reminder_date'] = null;
         }
 
-        if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){
+        // if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){
 
-            $data['is_addon'] = 1;
+        //     $data['is_addon'] = 1;
 
-        }else if($policy_type_id == 4){
+        // }else if($policy_type_id == 4){
 
-            $data['is_addon'] = 2;
+        //     $data['is_addon'] = 2;
 
-        }else if($policy_type_id == 5){
+        // }else if($policy_type_id == 5){
 
-            $data['is_addon'] = 3;
+        //     $data['is_addon'] = 3;
+        // }
+
+        if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7){
+
+            $data['is_addon'] = 1; // Base Policy
+
+        }else if($policy_type_id == 4 || $policy_type_id == 5){
+
+            $data['is_addon'] = 2; // SI TOPUP
+
+        }else if($policy_type_id == 3){
+           
+            if($base_policy){
+                $data['is_addon'] = 3; // Dependent Addon
+            }else{
+                $data['is_addon'] = 1;
+            }
         }
           
 
@@ -1531,6 +1562,78 @@ class ClientController extends AdminController
 
 
 
+    public function uploadVehicleFile()
+    {
+        $this->myLogger->logme('error','uploadVehicleFile function called');  
+        $data = $this->request->getPost();     
+        $files = $this->request->getFiles();
+        // $data['client_id'] = 12;
+        // $data['vehicle_id'] = 1;
+
+        // upload path
+        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+        
+        $insertedDocs = [];
+    
+        // Check  document names and files
+        if (isset($data['other_docs_name']) && isset($files['file_name'])) {
+            foreach ($data['other_docs_name'] as $key => $docName) {
+                // Get the corresponding file for this document name
+                $file = $files['file_name'][$key];
+    
+                if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
+                    // Upload the file
+                    $uploadedFileName = file_Upload($file, $uploadFilePath);
+    
+                    if ($uploadedFileName) {
+                        // Prepare data for each document upload
+                        $docData = [
+                            'client_id' => $data['client_id'],
+                            'vehicle_id' => $data['vehicle_id'],
+                            'other_docs_name' => $docName,
+                            'file_name' => $uploadedFileName,
+                            'created_by' => get_session_userid(),
+                        ];
+    
+                        // Insert into database
+                        $insert = $this->clientKYCDocsModel->insert($docData);
+    
+                        if ($insert) {
+                            $insertedDocs[] = $docData; // Collect successfully inserted docs
+                        }
+                    }
+                }
+            }
+    
+            if (!empty($insertedDocs)) {
+                // Fetch all documents for the client
+                $vehicleDocs = $this->clientKYCDocsModel
+                            ->where('client_id', $data['client_id'])
+                            ->where('vehicle_id',$data['vehicle_id'])
+                            ->findAll();
+                return $this->respond(['status' => true, 'code' => 200, 'vehicle_docs' => $vehicleDocs, 'inserted_docs' => $insertedDocs], 200);
+            } else {
+                return $this->respond(['status' => false, 'code' => 400, 'message' => 'No documents uploaded or inserted'], 200);
+            }
+        } else {
+            return $this->respond(['status' => false, 'code' => 400, 'message' => 'Invalid data submission'], 200);
+        }
+    }
+    
+
+    public function editUploadVehicleFile()
+    {
+
+    }
+
+    public function listVehicleFiles()
+    {
+
+    }
+
+    public function deleteVehicleFiles(){
+
+    }
 
 
 
@@ -2236,7 +2339,8 @@ class ClientController extends AdminController
 
     }
 
-    public function fetchPolicyDataForPolicyType($client_policy_id){
+    public function fetchPolicyDataForPolicyType($client_policy_id)
+    {
 
         $client_policy_id = $this->request->getGet('client_policy_id');
         $policy_type = $this->request->getGet('policy_type');
@@ -3011,4 +3115,325 @@ class ClientController extends AdminController
         }    
     }
 
+    public function getBranchByClientID($client_id)
+    {
+        $branch_list = $this->clientBranchModel->where('client_id', $client_id)->where('is_active', 1)->findAll();
+        $policy_list = [];
+        foreach ($branch_list as $value) 
+        {
+            $policy_data = $this->clientPolicyModel
+                        ->select('client_policy.*, policy_type.policy_type')
+                        ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+                        ->where('client_policy.client_id', $value['client_id'])
+                        ->where('client_policy.client_branch_id', $value['id'])
+                        ->where('client_policy.is_active', 1)
+                        ->findAll();
+            $policy_list[$value['id']] = $policy_data;
+        }
+       
+        if($branch_list){
+            return $this->respond(['status' => true, 'data' => $branch_list, 'policy_data' => $policy_list], 200);
+        }else{
+            return $this->respond(['status' => false], 200);
+        }
+    }
+
+    public function getClientAndBranchAndPolicy()
+    {
+        $clients = $this->clientModel->where('is_active', 1)->findAll();
+        $vehicles = $this->vehicleModel
+        ->select('vehicle.*, clients.client_type')
+        ->join('clients', 'clients.id=vehicle.owner')
+        ->where('vehicle.is_active', 1)->findAll();
+        $clientIds = array_column($clients, 'id');
+    
+        // Fetch branches in a single query
+        $branches = $this->clientBranchModel
+            ->whereIn('client_id', $clientIds)
+            ->where('is_active', 1)
+            ->findAll();
+        
+        // Fetch policies in a single query
+        $policies = $this->clientPolicyModel
+            ->select("
+                    client_policy.*, 
+                    policy_type.policy_type,
+                    policy_type.ebp,
+                    policy_type.etp,
+                    policy_type.iep,
+                    policy_type.itp,
+                    policy_type.bap,
+                    DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date,
+                    DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date
+                ")
+            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+            ->whereIn('client_policy.client_id', $clientIds)
+            ->where('client_policy.is_active', 1)
+            ->findAll();
+    
+        $branchList = [];
+        $policyList = [];
+        $policyListByClient = [];
+        $unitList = [];
+    
+        foreach ($branches as $branch) {
+            $branchList[$branch['client_id']][] = $branch;
+            $unitList[$branch['id']][] = json_decode($branch['units']);
+        }
+    
+        foreach ($policies as $policy) {
+            $policyList[$policy['client_branch_id']][] = $policy;
+            $policyListByClient[$policy['client_id']][] = $policy;
+            if (isset($policyCount[$policy['client_id']])) {
+                $policyCount[$policy['client_id']]++;
+            } else {
+                $policyCount[$policy['client_id']] = 1;
+            }
+        }
+        
+        foreach ($clients as &$client) {
+            $client['client_policy_count'] = $policyCount[$client['id']] ?? 0;
+        }
+    
+        if (!empty($branchList)) {
+            return $this->respond([
+                'status' => true, 
+                'client_data' => $clients, 
+                'vehicle_data' => $vehicles, 
+                'branch_data' => $branchList, 
+                'policy_data' => $policyList,
+                'policyListByClient' => $policyListByClient,
+                'unit_data' => $unitList,
+            ], 200);
+        } else {
+            return $this->respond(['status' => false], 200);
+        }
+    }
+    
+
+
+    public function getCDAccNoByClientAndInsurer($client, $insurer)
+    {
+        $cdmData = $this->CDMasterModel->where('client_id', $client)->where('insurer_id', $insurer)->findAll();
+
+        if($cdmData){
+            return $this->respond(['status' => true, 'data' => $cdmData], 200);
+        }else{
+            return $this->respond(['status' => false], 200);
+        }
+    }
+
+    public function createClientWithMinimalData()
+    {  
+        $postData = $this->request->getPost();
+        // print_r($postData); die;
+        $client_type = $postData['client_type'];
+        $client_data = [
+            'client_type' => $postData['client_type'],
+            'client_name' => $postData['client_name'],
+            'short_name' => $postData['short_name'],
+            'pan' => $postData['pan'],
+            'client_code' => generate_client_code(),
+        ];
+    
+        // Add additional fields if client type is 2
+        if($client_type == 2) {
+            $client_data = array_merge($client_data, [
+                'dob' => $postData['dob'],
+                'aadhar' => $postData['aadhar'],
+                'phone' => $postData['phone'],
+                'email' => $postData['email'],
+                'entity_type_id' => 7
+            ]);
+        } else {
+            $client_data['entity_type_id'] = $postData['entity_type_id'];
+        }
+    
+        // Insert client data
+        $client_insert = $this->clientModel->insert($client_data);
+    
+        if(!$client_insert) {
+            return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200);
+        }
+    
+        // Additional logic for non-individual clients (client_type != 2)
+        if($client_type != 2) {
+            $unit = $postData['short_name'] . '-' . $postData['branch_code'];
+            $branch_data = [
+                'client_id' => $client_insert,
+                'branch_name' => $postData['branch_name'],
+                'branch_code' => $postData['branch_code'],
+                'gst' => $postData['gst'],
+                'units' => $unit,
+            ];
+            
+            $branch_insert = $this->clientBranchModel->insert($branch_data);
+            if ($branch_insert) {
+                $contact_data = [
+                    'ref_id' => $branch_insert,
+                    'contact_type' => 'client',
+                    'name' => $postData['name'],
+                    'mobile' => $postData['mobile'],
+                ];
+                $this->levelContactModel->insert($contact_data);
+            }
+        }
+    
+        return $this->respond([
+            'status' => true, 
+            'data' => $postData, 
+            'client_id' => $client_insert, 
+            'branch_id' => $branch_insert ?? null, 
+            'message' => 'Client created successfully'
+        ], 200);
+    }
+    
+    public function createVehicleWithMinimalData()
+    {
+        $data = $this->request->getPost();
+        $id = $this->request->getPost('vehicle_primary_key');
+
+        if($id){
+
+            $vehicle_update = $this->vehicleModel->where('id', $id)->set($data)->update();
+
+            if($vehicle_update){
+                return $this->respond(['status' => true, 'message' => 'Vehicle details updated successfully'], 200);
+            }else{
+                return $this->respond(['status' => false, 'message' => 'Failed to update vehicle details'], 200);
+            }
+
+        }else{
+
+            $vehicle_insert = $this->vehicleModel->insert($data);
+
+            if($vehicle_insert){
+                $vehicles = $this->vehicleModel->where('is_active', 1)->findAll();
+                return $this->respond([
+                        'status' => true, 
+                        'vehicle_id' => $vehicle_insert, 
+                        'owner_id' => $data['owner'], 
+                        'owner_branch_id' => $data['branch_id'] ?? null, 
+                        'owner_type' => $data['Owner_type'], 
+                        'vehicles' => $vehicles, 
+                        'message' => 'Vehicle created successfully
+                    '], 200);
+            }else{
+                return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200);
+            }
+        }
+    }
+
+    public function createClientPolicyWithMinimalData()
+    {
+        $data = $this->request->getPost();
+
+        $insurerValue  = (string) $this->request->getPost('insurer');
+        list($insurerBranchId, $insurerId) = explode('-', $insurerValue);
+        
+        $data['insurer_branch_id'] = $insurerBranchId;
+        $data['insurer_id']        = $insurerId;
+        $data['policy_status']        = 1;
+        $data['is_addon']        = 1;
+        $data['gst']        = 18;
+        $data['created_by']        = get_session_userid();
+        $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d');
+        $data['policy_end_date']   = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d');
+
+
+        $insert = $this->clientPolicyModel->insert($data);
+
+        if($insert){
+
+            $policies = $this->clientPolicyModel
+                ->select('client_policy.*, policy_type.policy_type')
+                ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+                ->where('client_policy.client_id', $data['client_id'])
+                ->where('client_policy.client_branch_id', $data['client_branch_id'])
+                ->where('client_policy.is_active', 1)
+                ->findAll();
+
+            return $this->respond(['status' => true, 'data' => $policies, 'client_policy_id' => $insert, 'message' => 'Client policy created successfully'], 200);
+        }else{
+            return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200);
+        }
+    }
+
+    public function getPolicyDetailsByPolicyId($id)
+    {   
+        $policies = $this->clientPolicyModel
+            ->select('client_policy.*, policy_type.policy_type')
+            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+            ->where('client_policy.id', $id)
+            ->where('client_policy.is_active', 1)
+            ->findAll();
+
+        if($policies){
+            return $this->respond(['status' => true, 'data' => $policies, 'message' => 'Client policy created successfully'], 200);
+        }else{
+            return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200);
+        }
+    }
+
+    public function check_cost_center($cost_center)
+    {
+        $uniqueAC = $this->clientModel
+            ->where('cost_center', $cost_center)
+            ->where('is_active', 1)
+            ->findAll();
+
+        if($uniqueAC != null){
+            return $this->respond(['status' => true, 'message' => 'The Cost Center is Already Exist', 'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'code' => 404], 200);
+        }
+    }
+
+    public function check_policy_no($policy_no)
+    {
+        $uniqueAC = $this->clientPolicyModel
+            ->where('policy_no', $policy_no)
+            ->where('is_active', 1)
+            ->findAll();
+
+        if($uniqueAC != null){
+            return $this->respond(['status' => true, 'message' => 'The Policy Number is Already Exist', 'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'code' => 404], 200);
+        }
+    }
+
+    public function get_client_policy_data_using_policy_no($policy_no)
+    {
+        $data = $this->clientPolicyModel
+            ->select('client_policy.*, clients.client_type')
+            ->join('clients', 'client_policy.client_id = clients.id')
+            ->where('client_policy.policy_no', $policy_no)
+            ->where('client_policy.is_active', 1)
+            ->first();
+
+        if($data){
+            return $this->respond(['status' => true, 'data'=> $data,  'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200);
+        }
+    }
+
+    public function get_client_policy_data_using_policy_no_and_endo_no($policy_no, $endorsement_no)
+    {
+        $data = $this->clientPolicyModel
+            ->select('client_policy.*, endorsement.endorsement_type')
+            ->join('endorsement', 'client_policy.id = endorsement.client_policy_id')
+            ->where('client_policy.policy_no', $policy_no)
+            ->where('endorsement.endorsement_no', $endorsement_no)
+            ->where('client_policy.is_active', 1)
+            ->first();
+
+        if($data){
+            return $this->respond(['status' => true, 'data'=> $data,  'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200);
+        }
+    }
+
 }
\ No newline at end of file
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
old mode 100644
new mode 100755
index fe61b51f..4786af5f
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -13,6 +13,7 @@ use CodeIgniter\API\ResponseTrait;
 use App\Models\MessageModel;
 use App\Models\UserMessageModel;
 use App\Models\ClientModel;
+use App\Models\PolicyTransactionModel;
 
 use App\Models\JobModel;
 use App\Models\ClientPolicyModel;
@@ -30,6 +31,7 @@ class DashboardController extends AdminController
     protected $clientPolicyModel;
     protected $notificationModel;
     protected $employeePolicyModel;
+    protected $policyTransactionModel;
 
     protected $myLogger;
 
@@ -42,6 +44,7 @@ class DashboardController extends AdminController
         $this->notificationModel   = new NotificationModel();
         $this->employeePolicyModel = new EmployeePolicyModel();
         $this->clientModel         = new ClientModel();
+        $this->policyTransactionModel         = new PolicyTransactionModel();
 
         $this->myLogger = \Config\Services::mylogger();
 
@@ -65,8 +68,9 @@ class DashboardController extends AdminController
 
         $pendingActionsController = new PendingActionsController;
         $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
-
-
+        $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
+        $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
+       
         $groupedData = [];
 
         foreach ($results as $row) {
@@ -157,6 +161,8 @@ class DashboardController extends AdminController
         $session->set('enrollment_data', json_encode($data));
         // echo "
";
         $data['pendingActionsData'] = $pendingActionsData;
+        $data['businessTeamCount'] = count($businessTeamData) ?? 0;
+        $data['financeTeamCount'] = count($financeTeamData) ?? 0;
         // print_r($data);die;
 
 
diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php
old mode 100644
new mode 100755
index fbf60d4e..4ea1ce46
--- a/app/Controllers/EmpDataServiceController.php
+++ b/app/Controllers/EmpDataServiceController.php
@@ -27,6 +27,7 @@ use App\Models\UserMessageModel;
 use App\Models\CDMasterModel;
 use App\Models\InsurerExcelExportTemplateModel;
 use App\Models\ClientBranchModel;
+use App\Models\EndorsementModel;
 
 use App\Controllers\Jobs;
 use App\Controllers\JobWorker;
@@ -58,6 +59,7 @@ class EmpDataServiceController extends BaseController
     protected $CDMasterModel;
     protected $excelExportTemplateModel;
     protected $clientBranchModel;
+    protected $endorsementModel;
 
 
     public function __construct()
@@ -80,6 +82,7 @@ class EmpDataServiceController extends BaseController
         $this->CDMasterModel    = new CDMasterModel();
         $this->excelExportTemplateModel    = new InsurerExcelExportTemplateModel();
         $this->clientBranchModel  = new ClientBranchModel();
+        $this->endorsementModel  = new EndorsementModel();
 
     }
 
@@ -1808,6 +1811,11 @@ class EmpDataServiceController extends BaseController
         $file_data = $this->getDataByFileId($file_id, 'success');
         $this->setPullNotification($file_data);
 
+        // if(excelFileGDriveUpload($file_id, 'batch_file')){
+        //     $this->myLogger->logme('error', 'Inception Update Google Drive File Upload --    File Uploaded Successfully');
+        // }else{
+        //     $this->myLogger->logme('error', 'Inception Update Google Drive File Upload --    File Uploaded Field');
+        // }
 
         return 'Import Inception Updated ' . $status_val . '- Updated Count : ' . $emp_count;
     }
@@ -2145,6 +2153,7 @@ class EmpDataServiceController extends BaseController
         $status = $file['status'];
         $batch_code = $file['batch_code'];
         $user_id = $file['created_by'];
+        $event_type = $file['event_type'];
 
 
         $status_val = 'success';
@@ -2206,6 +2215,8 @@ class EmpDataServiceController extends BaseController
 
        $this->empEndorsementModel->updateBatch($endorsement_details, 'group_key');
        $this->employeePolicyModel->bulkUpdateForCorrection($emp_details);
+       $this->storeEndorsementNumber($file_id, $endorsement_id[0]);
+
 
         // Update batch file status and amount
         $this->batchFileModel->update($file_id, [
@@ -2801,6 +2812,8 @@ class EmpDataServiceController extends BaseController
         // }
         
         $this->employeePolicyModel->bulkUpdateForEndorsement($endorsement_details);
+        $this->storeEndorsementNumber($file_id, $endorsement_id);
+
 
         // Update batch file status and amount
         $this->batchFileModel->update($file_id, [
@@ -3320,6 +3333,7 @@ class EmpDataServiceController extends BaseController
         $this->employeeModel->updateBatch($employees_table_data, 'id');
         $this->employeePolicyModel->updateBatch($employee_policy_table_data, 'id');
         $this->employeePolicyModel->bulkUpdateForEndorsement($emp_endorsement_table_data);
+        $this->storeEndorsementNumber($file_id, $endorsement_id);
 
         // Update batch file status and amount
         $this->batchFileModel->update($file_id, [
@@ -4367,34 +4381,58 @@ class EmpDataServiceController extends BaseController
          $this->messageModel->insert($msg_data);
     }
 
-    public function updatajson()
-    {
-          
-        // $columns = [
-        //     ["column_index" => 0, "column_name" => "SR NO", "db_column_name" => 'index'],
-        //     ["column_index" => 1, "column_name" => "EmployeeId", "db_column_name" => "emp_code"],
-        //     ["column_index" => 2, "column_name" => "UHID", "db_column_name" => "uhid"],
-        //     ["column_index" => 3, "column_name" => "DOJ", "db_column_name" => "emp_doj"],
-        //     ["column_index" => 4, "column_name" => "Name OF Insured", "db_column_name" => "emp_name"],
-        //     ["column_index" => 5, "column_name" => "Age", "db_column_name" => "emp_age"],
-        //     ["column_index" => 6, "column_name" => "Gender", "db_column_name" => "emp_gender"],
-        //     ["column_index" => 7, "column_name" => "DOC", "db_column_name" => null],
-        //     ["column_index" => 8, "column_name" => "TOTALSI", "db_column_name" => "basic_cover_si"],
-        //     ["column_index" => 9, "column_name" => "DOS", "db_column_name" => "dateofexit"],
-        //     ["column_index" => 10, "column_name" => "Mobile", "db_column_name" => 'emp_mobile'],
-        //     ["column_index" => 11, "column_name" => "EmailID", "db_column_name" => 'emp_email_c'],
-        //     ["column_index" => 12, "column_name" => "REMARKS", "db_column_name" => "remarks"],
-        //     ["column_index" => 13, "column_name" => "FLAG STATUS", "db_column_name" => null],
-        //     ["column_index" => 14, "column_name" => "EXCEPTIONS", "db_column_name" => null],
-        //     ["column_index" => 15, "column_name" => "ABHA", "db_column_name" => null]
-        // ];
-        
-        
-        
-        
-        // $json = json_encode($columns);
-        // $this->excelExportTemplateModel->where('id', 37)->set('jsoncolumns', $json)->update();
+    public function storeEndorsementNumber($file_id, $endorsement_no)
+    {   
+        // Log the function entry with input parameters
+        $this->myLogger->logme('error',  "storeEndorsementNumber --- Starting function with file_id: $file_id and endorsement_no: $endorsement_no");
+    
+        // Log before querying the database
+        $this->myLogger->logme('error', "storeEndorsementNumber --- Fetching file data for file_id: $file_id");
+    
+        $filedata = $this->batchFileModel
+            ->select('
+                batch_files.client_id, 
+                batch_files.client_policy_id, 
+                batch_files.event_type, .
+                batch_files.created_by, 
+                client_policy.insurer_id, 
+                client_policy.tpa_id
+            ')
+            ->join('client_policy', 'batch_files.client_policy_id = client_policy.id')
+            ->where('batch_files.id', $file_id)
+            ->first();
 
+        // dd($filedata);
+    
+        // Log after fetching data
+        if ($filedata) {
+            $this->myLogger->logme('error', 'File data fetched successfully: ' . json_encode($filedata));
+    
+            // Log before inserting data
+            $this->myLogger->logme('error', 'storeEndorsementNumber --- Inserting endorsement data into endorsementModel');
+    
+            $this->endorsementModel->insert([
+                'client_id' => $filedata['client_id'],
+                'client_policy_id' => $filedata['client_policy_id'],
+                'insurer_id' => $filedata['insurer_id'],
+                'tpa_id' => $filedata['tpa_id'],
+                'endorsement_no' => $endorsement_no,
+                'endorsement_type' => $filedata['event_type'],
+                'created_by' => $filedata['created_by'],
+            ]);
+    
+            // Log after data insertion
+            $this->myLogger->logme('error', 'storeEndorsementNumber --- Endorsement data inserted successfully for file_id: ' . $file_id);
+        } else {
+            // Log if no file data is found
+            $this->myLogger->logme('error', "storeEndorsementNumber --- No file data found for file_id: $file_id");
+        }
+    
+        // Log function exit
+        $this->myLogger->logme('error',"storeEndorsementNumber --- Function execution completed for file_id: $file_id");
     }
+    
+
+
 
 }
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
old mode 100644
new mode 100755
index bff8c812..1df4dc16
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -148,6 +148,10 @@ class EmployeeController extends AdminController
     public function employeesUplodWithEvents()
     {
 
+        // $empDataServiceController = new EmpDataServiceController();
+        // !dd($empDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 79]));
+
+
         // $job_details  = new Jobs();
         // $r = Jobs::addJob(['job_name' => 'add','payload' => ['a' => 10, 'b' => 35]]);
         // print_r($r);//die();
@@ -375,7 +379,7 @@ class EmployeeController extends AdminController
         } else if ($actionType == 'deletion') {
             $filePath = ROOTPATH . 'public/sample_excel/sample_deletion.xls';
         } else if ($actionType == 'enrollment') {
-            $filePath = ROOTPATH . 'public/sample_excel/enrollment.xls';
+            $filePath = ROOTPATH . 'public/sample_excel/enrollment.xlsx';
         }else if ($actionType == 'missed_inception') {
             $filePath = ROOTPATH . 'public/sample_excel/sample_inception.xls';
         }
@@ -1194,8 +1198,14 @@ class EmployeeController extends AdminController
         // $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']);
+        if ($file['action'] == 'inception' || $file['action'] == 'dependent_addition' || $file['action'] == 'addition' || $file['action'] == 'enrollment') {
+
+            if($file['action'] == 'enrollment'){
+                $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['draft','enrolled'], policy_status: ['draft','enrolled']);
+            }else{
+                $result = $this->employeeModel->getEmpListByFileId(file_id: $file_id, emp_status: ['active'], policy_status: ['active']);
+            }
+            
             // ~dd($result);
             if (count($result) && $role_id == null) {
                 if(get_role_id() == 1 || get_role_id() == 5){
@@ -1210,6 +1220,7 @@ class EmployeeController extends AdminController
                 $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();
+                // print_r($db->getLastQuery()); die;
                 // $affectedRows = 10;
 
                 //update file status
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
old mode 100644
new mode 100755
index af9c2f07..aba83570
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -27,6 +27,7 @@ use App\Models\NotificationModel;
 use App\Models\UserModel;
 use App\Models\FEContentModel;
 use App\Models\AddImgModel;
+use App\Models\ClientBranchModel;
 
 
 use App\Controllers\Jobs ;
@@ -69,6 +70,8 @@ class EmployeeRestController extends AdminController
     protected $userModel;
     protected $feContentModel;
     protected $addImgModel;
+    protected $clientBranchModel;
+    
     
     public function __construct()
     {
@@ -90,6 +93,7 @@ class EmployeeRestController extends AdminController
         $this->userModel = new UserModel();
         $this->feContentModel = new FEContentModel();
         $this->addImgModel = new AddImgModel();
+        $this->clientBranchModel = new ClientBranchModel();
         
     }
 
@@ -208,7 +212,7 @@ class EmployeeRestController extends AdminController
     
     public function addEmployeeAndDependence()
     {
-        try {
+        // try {
             $data = $this->request->getJSON();
 
             
@@ -216,6 +220,7 @@ class EmployeeRestController extends AdminController
 
                 $Count = 0;
                 foreach ($data as $item) {
+                   
                     if (isset($item->id)) {
                         //update old data
                         $id = $item->id;
@@ -233,6 +238,8 @@ class EmployeeRestController extends AdminController
                         $item->gender = $this->GenderMap($item->relationship , $item->emp_code);
                         $item->dob = $this->convertDateFormatYMD($item->dob);
                         $item->emp_status = 'draft';
+                        
+                        
                         $employee = $this->employeeModel->insert($item);
                    
                         if ($employee) {
@@ -266,7 +273,7 @@ class EmployeeRestController extends AdminController
                     
 
 
-                    $this->updatePremiumAmount($data[0]->client_policy_id , $data[0]->emp_code);
+                    $this->updatePremiumAmount($data[0]->client_policy_id , $data[0]->emp_code , $data[0]->client_branch_id);
 
                     
                     $result = [];
@@ -276,9 +283,9 @@ class EmployeeRestController extends AdminController
                     return $this->respond(['status' => 'failed','code' => 404,'data' => $result], 404);
                 }
             }
-        } catch (\Exception $e) {
-            return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
-        }
+        // } catch (\Exception $e) {
+        //     return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()], 500);
+        // }
         
     }
 
@@ -317,30 +324,36 @@ class EmployeeRestController extends AdminController
             return true;             
     }
 
-    public function updatePremiumAmount($client_policy_id , $emp_code)
+    public function updatePremiumAmount($client_policy_id , $emp_code , $client_branch_id)
     {
-        $response = $this->calculatePremium($client_policy_id , $emp_code);
+        $response = $this->calculatePremium($client_policy_id , $emp_code , null , $client_branch_id);
 
         if(count($response[$emp_code]))
         {
             
             foreach ($response[$emp_code] as $key => $value) 
             {
-               
-                $checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])
+
+                if(isset($value['temp']))
+                {
+                    $checkIfExist = $this->employeePolicyModel->where('employee_id', $value['temp']['emp_id'])
                                                            ->where('client_policy_id', $value['policy_details']['client_policy_id'])
                                                            ->where('is_active', 1 )
                                                            ->findAll();
-                if($checkIfExist) 
-                {  
-                    $this->employeePolicyModel
-                    ->where('client_policy_id',$value['policy_details']['client_policy_id'] )
-                    ->where('employee_id' , $value['temp']['emp_id'] )
-                    ->where('is_active', 1 )
-                    ->set(array('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum']  , 'gst'=> $value['policy_details']['gst'] ))
-                    ->update();        
-                   
+                    if($checkIfExist) 
+                    {  
+                        $this->employeePolicyModel
+                        ->where('client_policy_id',$value['policy_details']['client_policy_id'] )
+                        ->where('employee_id' , $value['temp']['emp_id'] )
+                        ->where('is_active', 1 )
+                        ->set(array('premium'=> $value['policy_details']['premium'] , 'rata_premimum'=> $value['policy_details']['rata_premimum']  , 'gst'=> $value['policy_details']['gst'] ))
+                        ->update();        
+                    
+                    }
+
                 }
+               
+                
             }
         }
     }
@@ -834,7 +847,7 @@ class EmployeeRestController extends AdminController
                     $emp_id =0;
                     
                     $data_after_gpa_or_gmc =[];
-                    if ($policy['policy_type_id'] == 1) {
+                    if ($client_policy['policy_type_id'] == 1) {
                         if (strtolower($dataToInsert[$a]['relationship']) == 'self') {
                             $data_after_gpa_or_gmc = $dataToInsert[$a];
                         }
@@ -1015,6 +1028,7 @@ class EmployeeRestController extends AdminController
                         $self['data']['basic_cover_si'] = $employee_policy->basic_cover_si; 
 
                         $array->mapped_family_floaters = $self;
+                        $array->type = 'GPA';
                       
 
                         
@@ -1142,7 +1156,7 @@ class EmployeeRestController extends AdminController
                         }
 
                         $array->mapped_family_floaters = $data;
-                        $array->type = "Group Medical Coverage";
+                        $array->type = "GMC";
                     
                         $checkGmcParentsPolicyExist = $this->clientPolicyModel->select('client_policy.id as ClientPolicyId , client_policy.client_id as ClientId, client_policy.policy_type_id as policy_type_id, policy_type.long_name as Policy_Name , client_policy.is_addon as is_addon , client_policy.open_for_enrollment as OpenForEnrollment , client_policy.inception_type  as inception_type , client_policy.policy_terms as Policy_Terms')
                                                                                 ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
@@ -1331,7 +1345,7 @@ class EmployeeRestController extends AdminController
         }
 
             $array->mapped_family_floaters = $data;
-            $array->type = "Group Medical Coverage - Parents";
+            $array->type = "GMC - Parents";
 
             return $array;
 
@@ -1398,10 +1412,7 @@ class EmployeeRestController extends AdminController
         }
     }
 
-    public function getGTLIPolicy($empData,$emp_code,$client_id,$client_branch_id)
-    {
-
-    }
+   
 
     public function FloterConvertion($array){
 
@@ -1442,7 +1453,7 @@ class EmployeeRestController extends AdminController
             if ($value > 0) {
                 if($value == 1 && $key ==='either-parents-pil') {
                     $result .= ' + Either 2 Parents or 2 Parents in law';
-                }if($value == 2 && $key ==='either-parents-pil') {
+                }else if($value == 2 && $key ==='either-parents-pil') {
                     $result .= ' + Any 2 of Parents and Parents in law';
                 }else if($value != 0 && $key ==='spouse') {
                     $string = str_replace('-', ' ', $key);
@@ -1781,7 +1792,7 @@ class EmployeeRestController extends AdminController
                 $responce['family_floaters_of_only_si_value'] = $only_si_value;
                 $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value;
                 $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value;
-                $responce['type'] = "Group Medical Coverage - Top Up";
+                
 
                 if($this->request->getGet('policy') == 'GMC-SI-TOPUP'){
                 return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_topup'=>$responce]], 200);
@@ -1830,7 +1841,7 @@ class EmployeeRestController extends AdminController
                 $responce['family_floaters_of_only_si_value'] = $only_si_value;
                 $responce['family_floaters_of_only_si_premium_value'] = $only_si_premium_value;
                 $responce['family_floaters_of_only_si_gst_value'] = $only_si_gst_value;
-                $responce['type'] = "Group Medical Coverage - Parents Top Up";
+                
 
                 if($this->request->getGet('policy') == 'GMC-SI-PARENT-TOPUP'){
                 return $this->respond(['status' => 'success','code' => 200,'data' => ['gmc_si_parent_topup'=>$responce]], 200);
@@ -1929,12 +1940,13 @@ class EmployeeRestController extends AdminController
     //Post method  - which receives client_policy id and empcode of the family.
     //Pull records againest emp code and calculate premium 
     // retun array
-    public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null)//family level
+    public function calculatePremium($clientPolicyId = null , $empCode = null, $default_si = null ,  $client_branch_id = null)//family level
     { 
         helper('excel_util_helper');
         $client_policy_id = $this->request->getVar('client_policy_id') ?? $clientPolicyId;
         $emp_code = $this->request->getVar('emp_code') ?? $empCode;
         $default_si = $this->request->getVar('si') ?? $default_si;// si amt which choosed in add on policy
+        $client_branch_id = $this->request->getVar('client_branch_id') ?? $client_branch_id;
         // dd($client_policy_id);
 
 
@@ -1963,13 +1975,17 @@ class EmployeeRestController extends AdminController
         // dd($this->employeeModel->getLastQuery());
         // print_r($existing_famility_details);die();
         $employee_data_group_by_family = data_group_by_family($existing_famility_details,$data_source = 'db');
-        // print_r(($employee_data_group_by_family));die();
+        // print_r(($employee_data_group_by_family));//die();
+
+
+        $existing_units = $this->clientBranchModel->getExisitingUnits(client_id: $client_id,client_branch_id: $client_branch_id);
+
         foreach ($employee_data_group_by_family as $emp_id => $family) 
         {
             $transformed_famility_details = transform_db_data_to_excel($family);
-            // print_r($transformed_famility_details);die();
-            $data = calculate_premium($transformed_famility_details,$policy_terms,$slab_details,$file,$default_si);
-            // dd($data);
+
+            $data = calculate_premium_new(family_data: $transformed_famility_details,policy_terms:$policy_terms,slab_details:$slab_details,fileArr: $file,existing_units: $existing_units,default_si : $default_si);
+            
             $employee_data_group_by_family[$emp_id] = $data;
             
         }
@@ -2199,14 +2215,16 @@ class EmployeeRestController extends AdminController
 
     function getEmployeeActiveOrInactivePolicy()
     {
-    if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
-        $ClientPolicyData =  $this->clientPolicyModel->select('client_policy.* , policies.name as policy_name , policy_type.policy_type as policy_type')
-                                                    ->join('policies', 'client_policy.policy_id = policies.id', 'left')
+        if($this->request->getGet('type') == 'Active'){ $policy_status = 1; }else{ $policy_status = 0; }
+        $ClientPolicyData =  $this->clientPolicyModel->select('client_policy.* , policy_type.policy_type as policy_type,insurers.name as insurer_name,tpa.name as tpa_name')
+                                                    ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left')
+                                                    ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left')
                                                     ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
                                                     ->where('client_policy.client_id', $this->request->getGet('client_id') )
                                                     ->where('client_policy.client_branch_id', $this->request->getGet('client_branch_id') )
                                                     ->where('client_policy.is_active', 1 )
                                                     ->where('client_policy.policy_status', $policy_status)
+                                                    ->where('client_policy.enrolment_visibility', 1 )
                                                     ->orderby('client_policy.id' , 'ASC')
                                                     ->findAll();
 
@@ -2232,15 +2250,22 @@ class EmployeeRestController extends AdminController
 
                 $terms = json_decode($ClientPolicyValue['policy_terms']);
 
-                if($ClientPolicyValue['policy_type_id'] == 1){ $data['policy_terms'] =  $this->policyTermsFiter($terms,'gpa'); }
-                else{ $data['policy_terms'] =  $this->policyTermsFiter($terms,'gmc'); }
+                if($ClientPolicyValue['policy_type_id'] == 1)
+                { 
+                    $data['policy_terms'] =  $this->policyTermsFiter($terms,'gpa'); 
+                    $data['department_id'] = 3;
+                }else{ 
+                    $data['policy_terms'] =  $this->policyTermsFiter($terms,'gmc'); 
+                    $data['department_id'] = 4;
+                }
             
                 $data['client_id'] = $ClientPolicyValue['client_id'];
                 $data['client_policy_id'] = $ClientPolicyValue['id'];
-                $data['policy_name'] = $ClientPolicyValue['policy_name'];
-                $data['policy_type'] = $ClientPolicyValue['policy_type'];
+                $data['policy_name'] = $ClientPolicyValue['policy_type'];
                 $data['policy_type'] = $ClientPolicyValue['policy_type'];
                 $data['policy_no'] = $ClientPolicyValue['policy_no'];
+                $data['insurer_name'] = $ClientPolicyValue['insurer_name'];
+                $data['tpa_name'] = $ClientPolicyValue['tpa_name'];
                 $data['policy_start_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_start_date']);
                 $data['policy_end_date'] = $this->convertDateFormatDisplay($ClientPolicyValue['policy_end_date']);
                 // $data['policy_terms'] = $terms;
@@ -2251,10 +2276,11 @@ class EmployeeRestController extends AdminController
                 if($ClientPolicyValue['policy_type_id'] == 4){ $data['heading'] = 'Group Medical Coverage - Top Up'; }else
                 if($ClientPolicyValue['policy_type_id'] == 5){ $data['heading'] = 'Group Medical Coverage - Parents (Top Up)'; }
 
-                if($ClientPolicyValue['policy_type_id'] == 1){ $data['floter_text_heading'] = 'Sum Insured'; }
-                else
+                if($ClientPolicyValue['policy_type_id'] == 1 || $ClientPolicyValue['policy_type_id'] == 6 || $ClientPolicyValue['policy_type_id'] == 7)
                 { 
-                if($terms->family_floater == 1){ $data['floter_text_heading'] = 'Floter Sum Insured'; }else{ $data['floter_text_heading'] = 'Sum Insured'; }
+                    $data['floter_text_heading'] = 'Sum Insured'; 
+                }else{ 
+                    if($terms->family_floater == 1){ $data['floter_text_heading'] = 'Floter Sum Insured'; }else{ $data['floter_text_heading'] = 'Sum Insured'; }
                 }
                 
                 $employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid')
@@ -2482,7 +2508,7 @@ class EmployeeRestController extends AdminController
 
     public function sendPushNotification()
     {
-        $deviceToken = 'ffvc39yhRk-J-vGE9luw6l:APA91bFgNv7lzvA3lGuJ_pMDHdZ_rey6SMg11P2DvJk-WWiBs0nXWCF0lo5nEka3dn3DeTCS5yx0WrHs1yKj5faitBQYKeKxLg2VpUkDcmk3FrTDGkZdHcnW1Go0G0K8dYAkajRIjSEJ';
+        $deviceToken = 'cMVKESh8QzqIl8nh_yqbcl:APA91bHKm87Sh1goVJNKZtctV4etgLMQboI0eyDVn3MH1yf9cO-2RtQRlFnKLdataOxosoxm7a4JvATKjfI1_Bids46mGw5m8zesp90mR4odCbD_cJtGmBeMYt4hssSY0YtAht1emK_H';
         $title = 'Nhance';
         $body = 'All your policy enrolled successfully ..!';
     
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
old mode 100644
new mode 100755
index 826c7e29..b045b055
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -1965,6 +1965,7 @@ public function employeesEnrollmentInsert($params)
             $value['family_floater_key'] = null;
             $value['client_id'] = $file['client_id'];
             $value['client_branch_id'] = $file['client_branch_id'];
+            $value['file_id'] = $file_id;
 
             $value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model
             if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'Father') {
@@ -2045,13 +2046,13 @@ public function employeesEnrollmentInsert($params)
                             
                            //store email and mail content via helper to send notification
                            $emp_emails[] = sendMailNotification::sendMailNotification('member_welcome_mail', $params);
-                           Kint::dump($emp_emails);
-                           Kint::dump($key.'-'.count($excel_data));
+                           // Kint::dump($emp_emails);
+                           // Kint::dump($key.'-'.count($excel_data));
                            // if mail count is 20 send bulk mail and reset emp_emails variable
                             if (count($emp_emails) == 20 || $key == count($excel_data) ) {
                                 $job_details  = new Jobs();
                                 $r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $emp_emails]); 
-                                echo 'Mail triggered';
+                                // echo 'Mail triggered';
                                 $emp_emails = [];
                             }
                         
@@ -2059,6 +2060,12 @@ public function employeesEnrollmentInsert($params)
                     }
         } //end of for loop
 
+        $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => ''])->update();
+        $this->myLogger->logme("error",'{file_id} uploaded success',['file_id' => $file_id]);
+
+        $this->setPullNotification($this->getFileMetaDataByFileId($file_id,'success'));
+
+
         return true;
 }
 
diff --git a/app/Controllers/GoogleDriveController.php b/app/Controllers/GoogleDriveController.php
new file mode 100644
index 00000000..5af27b9f
--- /dev/null
+++ b/app/Controllers/GoogleDriveController.php
@@ -0,0 +1,355 @@
+clientModel = new ClientModel();
+        $this->clientPolicyModel = new ClientPolicyModel();
+        $this->googleDrive =  \Config\Services::myGoogleDrive();
+        $this->driveService =  $this->googleDrive->getDriveService();
+        $this->cache = \Config\Services::cache(); // Load the cache service
+    }
+    public function listFiles()
+    {
+        // dd($this->getClientFolderIds(client_id : 18));
+        $file_path = WRITEPATH.'uploads/client_kyc_documents/nhance_bpf.pdf';
+        // dd($file_path);
+        // dd($this->uploadFiletoGdrive(client_id : 18,doc_type:'KYC',file_path:$file_path,file_name:"dummy.pdf"));
+       dd( $this->uploadFiletoGdrive(client_id: 12, doc_type: 'KYC', file_path: $file_path, file_name: "dummy.pdf"));
+
+            $session = \Config\Services::session();
+            $fileName = $request->getVar('filename');
+            $fileType = $request->getVar('filetype');
+            $userAccess = $session->get('userEmail');
+            $parentFolderID = '1M0GH3GbNUOYZLNeHXA5U7C_P2NSx7F7O';
+            $searchQuery = '';//"'your-folder-id' in parents"
+
+
+        try {
+
+            // $driveService = $this->googleDrive->getDriveService();
+            $searchQuery = "name contains 'test' and 'vitvelz@gmail.com' in readers";
+            // Query to list files
+            $response = $this->driveService->files->listFiles([
+                'q' => $searchQuery,
+                'supportsAllDrives' => true,
+                'includeItemsFromAllDrives' => true,
+                'fields' => 'nextPageToken, files(id, name, mimeType, size, createdTime, modifiedTime, owners, shared, permissions, webViewLink, thumbnailLink)',
+                'pageSize' => 20,
+            ]);
+
+            $files = $response->getFiles();
+            if (empty($files)) {
+                echo "No files found.";
+            } else {
+                foreach ($files as $file) {
+                    echo "File Name: " . $file->getName() . " | File ID: " . $file->getId() . "
"; + } + } + } catch (\Exception $e) { + return $this->response->setStatusCode(500)->setBody($e->getMessage()); + } + } + + //by file id + public function downloadFile(string $fileId = '',string $fileName = '',string $mimeType = '',string $fileSize = '') + { + // dd($fileName); + try { + if($fileName == '' && $mimeType == '') + { + // Get file metadata + $file = $this->driveService->files->get($fileId, ['fields' => 'name, mimeType,size']); + $fileName = $file->getName(); + $mimeType = $file->getMimeType(); + $fileSize = $file->getSize(); + } + + // Download the file content from Google Drive + $response = $this->driveService->files->get($fileId, ['alt' => 'media']); + + $fileContent = $response->getBody()->getContents(); + // dd($fileContent); + $temp_file_name = WRITEPATH.'/tmp/'.date('YmdHis'); + $this->cache->save('temp_gdrive_file', $temp_file_name, 300); + file_put_contents( $temp_file_name, $fileContent ); + // Use CodeIgniter helper for downloading the file + return $this->response->download($temp_file_name, null)->setFileName($fileName); + + } catch (\Exception $e) { + return $this->response->setStatusCode(500)->setBody($e->getMessage()); + } + } + + public function generateNewGoogleDriveAccessToken() + { + $this->driveService->generateNewToken(); + } + + public function getClientFolderIds(int $client_id = 0,int $client_policy_id = 0) + { + // Fetch client short name from the database + if($client_id) + { + + //check folder ids in cahce, + $cacheKey = "client_gdrive_folderids_{$client_id}"; + $folderIds = $this->cache->get($cacheKey); + // dd($folderIds); + if($folderIds !== NULL)//if available retrun from cache + { + return $folderIds; + } + + //if not in cache then get it from grdrive + $client = $this->clientModel->find($client_id); + $clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name + } + else if($client_policy_id) + { + + $cacheKey = "client_policy_gdrive_folderids_{$client_policy_id}"; + $folderIds = $this->cache->get($cacheKey); + // dd($folderIds); + if($folderIds !== NULL)//if available retrun from cache + { + return $folderIds; + } + + $client = $this->clientPolicyModel->select('c.short_name,pt.policy_type,client_policy.policy_no') + ->join('clients c','client_policy.client_id = c.id') + ->join('policy_type pt','client_policy.policy_type_id = pt.id') + ->where('client_policy.id',$client_policy_id) + ->get()->getResultarray(); + // dd($client); + $clientShortName = $client[0]['short_name']; + $policyFolderName = $client[0]['policy_type'].'-'.$client[0]['policy_no']; + } + else + { + return []; + } + // dd($policyFolderName); + // Define parent folder ID where client folders are stored + $parentFolderId = getenv('GDRIVE_ROOT_FOLDER_ID');; // Replace with your specific folder ID + + // Check if the client folder exists in GDrive, if not create one + $clientFolderId = $this->checkOrCreateFolder($clientShortName, $parentFolderId); + + // Check or create KYC_DOCS folder inside the client folder + $kycFolderId = $this->checkOrCreateFolder('KYC_DOCS', $clientFolderId); + + // Check or create POLICY_DOCS folder inside the client folder + $policyFolderId = $this->checkOrCreateFolder('POLICY_DOCS', $clientFolderId); + + if($client_policy_id && (isset($policyFolderName))) + { + $clientPolicyFolderId = $this->checkOrCreateFolder($policyFolderName, $policyFolderId); + $clientPolicyUploadFolderId = $this->checkOrCreateFolder('UPLOADS', $clientPolicyFolderId); + } + + + // Return folder IDs in the specified format + $folderIds = [ + 'client_folder_id' => $clientFolderId, // example HCL,TCS + 'kyc_doc_folder_id' => $kycFolderId, // KYC_DOCS inside HCL,TCS + 'policy_doc_folder_id' => $policyFolderId, //POLICY_DOCS inside HCL,TCS + 'client_policy_doc_folder_id' => isset($clientPolicyFolderId) ? $clientPolicyFolderId : null, //GMC-POLICY_NO inside POLICY_DOCS folder + 'client_policy_uoload_doc_folder_id' => isset($clientPolicyUploadFolderId) ? $clientPolicyUploadFolderId : null, //UPLOADS folder in side GMC-POLICY_NO folder + ]; + + // Save the folder IDs in cache for future requests + $this->cache->save($cacheKey, $folderIds, 604800); // Cache for 7 Days (3600 seconds * 24 * 7 ) + return $folderIds; + } + + + // Method to check if a folder exists or create one if it doesn't + public function checkOrCreateFolder($folderName, $parentFolderId) + { + // Step 1: Check if the folder exists + $folderId = $this->getFolderId($folderName, $parentFolderId); + + if ($folderId === null) { + // Step 2: If folder does not exist, create it + $folderId = $this->createFolder($folderName, $parentFolderId); + } + + // Step 3: Return the folder ID + return $folderId; + } + + // Method to get the folder ID by searching in Google Drive + private function getFolderId($folderName, $parentFolderId) + { + $query = "name = '$folderName' and mimeType = 'application/vnd.google-apps.folder' and '$parentFolderId' in parents and trashed = false"; + + $response = $this->driveService->files->listFiles([ + 'q' => $query, + 'spaces' => 'drive', + 'fields' => 'files(id, name)', + 'pageSize' => 1, + ]); + + if (count($response->files) > 0) { + return $response->files[0]->id; // Return folder ID if found + } + + return null; // Return null if folder doesn't exist + } + + // Method to create a folder in Google Drive + private function createFolder($folderName, $parentFolderId) + { + $fileMetadata = new \Google_Service_Drive_DriveFile([ + 'name' => $folderName, + 'mimeType' => 'application/vnd.google-apps.folder', + 'parents' => [$parentFolderId] + ]); + + $folder = $this->driveService->files->create($fileMetadata, [ + 'fields' => 'id', + ]); + + return $folder->id; // Return the newly created folder's ID + } + + // public function uploadFiletoGdrive(int $client_id = 0,int $client_policy_id = 0,string $doc_type,string + // $file_path,string $file_name) + public function uploadFiletoGdrive(int $client_id = 0, int $client_policy_id = 0, string $doc_type = '', string $file_path = '', string $file_name = '') + { + $gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id); + // Kint::dump($gdriveFolderIds);//die(); + $parentFolderId = ''; + if($client_id && $doc_type == 'KYC') + { + $parentFolderId = $gdriveFolderIds['kyc_doc_folder_id']; + } + else if($client_policy_id && $doc_type == 'POLICY') + { + $parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id']; + } + else if($client_policy_id && $doc_type == 'UPLOADS') + { + $parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id']; + } + if($parentFolderId == '') + { + return null; + } + // dd($parentFolderId); + $file = new \Google_Service_Drive_DriveFile([ + 'name' => $file_name, + 'parents' => [$parentFolderId] // Specify the folder ID here + ]); + + $file_blob_data = file_get_contents($file_path); + + $createdFile = $this->driveService->files->create($file, [ + 'data' => $file_blob_data, + 'mimeType' => 'application/octet-stream', + 'uploadType' => 'multipart', + 'fields' => 'id' // Specify fields to return + ]); + + if($createdFile->id) + { + unlink($file_path); + } + + return $createdFile->id; + } + + public function downloadGdriveFile() + { + $client_id = $this->request->getGet('client_id'); + $client_policy_id = $this->request->getGet('client_policy_id'); + $file_type = $this->request->getGet('file_type'); + $file_name = $this->request->getGet('file_name'); + if(!is_numeric($client_policy_id)) + $client_policy_id = 0; + else + $client_id = 0; + + $gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id); + // dd($gdriveFolderIds); + $parentFolderId = ''; + if($file_type == 'kyc') + { + $parentFolderId = $gdriveFolderIds['kyc_doc_folder_id']; + } + else if($file_type == 'policy') + { + $parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id']; + } + else if($file_type == 'uploads') + { + $parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id']; + } + if($parentFolderId == '') + { + return $this->response->setStatusCode(500) + ->setHeader('Content-Type', 'text/html') + ->setBody(''); + } + + return $this->searchGdriveFileByName(parentFolderID: $parentFolderId, fileName: $file_name); + + } + + //search files in gdrive by parent folder id and name of the file + public function searchGdriveFileByName(string $parentFolderID,string $fileName) + { + //check exisitng temp file from cache and delete it + if($this->cache->get('temp_gdrive_file') && is_file($this->cache->get('temp_gdrive_file'))) + { + unlink($this->cache->get('temp_gdrive_file')); + } + + + try { + + $searchQuery = "'$parentFolderID' in parents and (name contains '$fileName')"; + // Query to list files + $response = $this->driveService->files->listFiles([ + 'q' => $searchQuery, + 'supportsAllDrives' => true, + 'includeItemsFromAllDrives' => true, + 'fields' => 'nextPageToken, files(id, name, mimeType, size)', + 'pageSize' => 1, + ]); + + $files = $response->getFiles(); + + if (empty($files)) { + return $this->response->setStatusCode(500) + ->setHeader('Content-Type', 'text/html') + ->setBody(''); + } + else + { + //echo "File Name: " . $files[0]->getName() . " | File ID: " . $file[0]->getId() . "
"; + // echo($files[0]->getId()); + // echo 'working'; + return $this->downloadFile(fileId:$files[0]->getId(),fileName:$files[0]->getName(),mimeType:$files[0]->getMimeType(),fileSize:$files[0]->getSize()); + } + } catch (\Exception $e) { + return $this->response->setStatusCode(500)->setBody($e->getMessage()); + } + } + +} diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php old mode 100644 new mode 100755 diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php old mode 100644 new mode 100755 diff --git a/app/Controllers/Jobs.php b/app/Controllers/Jobs.php old mode 100644 new mode 100755 diff --git a/app/Controllers/Jobs/AddJob.php b/app/Controllers/Jobs/AddJob.php old mode 100644 new mode 100755 diff --git a/app/Controllers/Jobs/SubJob.php b/app/Controllers/Jobs/SubJob.php old mode 100644 new mode 100755 diff --git a/app/Controllers/LoginController.php b/app/Controllers/LoginController.php old mode 100644 new mode 100755 index 42c885d2..10c42716 --- a/app/Controllers/LoginController.php +++ b/app/Controllers/LoginController.php @@ -41,13 +41,20 @@ class LoginController extends BaseController $user = $UserModel->getUserByEmail($value->email); if($user){ if($user->is_active !== '0'){ + + $user_team = $UserModel->getUserTeamsByUserID($user->id); + // dd($user_team); + $session_data = [ 'isLoggedIn' => True , 'userid' => $user->id, 'userData' => $user, 'userProfile' => $value->picture, + 'user_team' => $user_team, ]; + set_session_data($session_data); + log_message('error', 'Set The UserId : `'. $user->id .'` in Session'); log_message('error', 'User Login Sucessfully'); diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php old mode 100644 new mode 100755 index 842dd047..2779a509 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -10,6 +10,7 @@ use CodeIgniter\API\ResponseTrait; use CodeIgniter\Files\File; use App\Helpers\DepositHelper; +use App\Helpers\MailHelper; use App\Models\UserModel; use App\Models\ClientModel; @@ -30,6 +31,8 @@ use App\Models\PolicyTypeModel; use App\Models\CDMasterModel; use App\Models\ClientDepositModel; use App\Models\InsurerExcelExportTemplateModel; +use App\Models\SettingsModel; +use App\Models\VehicleModel; class MasterController extends AdminController { @@ -40,7 +43,7 @@ class MasterController extends AdminController protected $userModel; protected $insurerBranchModel; protected $insurerKYCDocsModel; - protected $insurerPolicyModel; + protected $clientPolicyModel; protected $insurerRMModel; protected $kycDocsModel; protected $kycEntityTypeModel; @@ -54,6 +57,8 @@ class MasterController extends AdminController protected $clientModel; protected $clientDepositModel; protected $insurerTemplateModel; + protected $cli_colors; + protected $vehicleModel; @@ -66,7 +71,7 @@ class MasterController extends AdminController $this->userModel = new UserModel(); // $this->insurerBranchModel = new ClientBranchModel(); $this->insurerKYCDocsModel = new ClientKYCDocsModel(); - $this->insurerPolicyModel = new ClientPolicyModel(); + $this->clientPolicyModel = new ClientPolicyModel(); $this->insurerRMModel = new ClientRMModel(); $this->insurerBranchModel = new InsurerBranchModel(); $this->insurerModel = new InsurerModel(); @@ -82,6 +87,14 @@ class MasterController extends AdminController $this->clientModel = new ClientModel(); $this->clientDepositModel = new ClientDepositModel(); $this->insurerTemplateModel = new InsurerExcelExportTemplateModel(); + $this->vehicleModel = new VehicleModel(); + $this->cli_colors = [ + 'red' => "\033[31m", + 'green' => "\033[32m", + 'yellow' => "\033[33m", + 'blue' => "\033[34m", + 'reset' => "\033[0m" + ]; } @@ -1258,6 +1271,8 @@ class MasterController extends AdminController $insert = $this->CDMasterModel->where('id', $id)->set($data)->update(); + $data = $this->CDMasterModel->where('id', $id)->first(); + $cd_transaction_updated_data = [ 'balance' => $data['opening_bal'], 'amount' => $data['opening_bal'] @@ -1343,6 +1358,103 @@ class MasterController extends AdminController } } + public function createCDAccountNumberUsingAjax() + { + $data = $this->request->getPost(); + $date = (string) $this->request->getPost('opening_date'); + $data['opening_date'] = date('Y-m-d', strtotime($date)); + + + // array with data for CD Traction table + $cd_tranction_data = [ + 'amount' => $data['opening_bal'], + 'sub_type_id' => 7, + 'client_id' => $data['client_id'], + 'client_policy_id' => null, + 'cd_ac_no' => $data['cd_ac_no'], + 'endorsement_no' => null, + 'insurer_id' => (int) $data['insurer_id'], + 'description' => 'opening Amount', + 'transaction_type' => 'Credit', + 'event_name' => null, + 'updated_by' => 1, + ]; + + $loggedInUserID = get_session_userid(); + + $insert = $this->CDMasterModel->insert($data); + + if ($insert) { + + //for CD Tranction Table + $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID); + + $cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll(); + + return $this->respond(['status' => true, 'data' => $cd_data, 'cd_ac_no'=>$data['cd_ac_no'], 'message' => 'CD Account number created successfully'], 200); + }else{ + return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200); + } + } + + + //Vehicle Master data Function + + public function VehicleMasterList() + { + $data['page_name'] = 'Vehicle Master List'; + $data['vehicle_type'] = [ + 'two_wheeler' => 'Two Wheeler', + 'four_wheeler' => 'Four Wheeler', + 'truck' => 'Truck', + 'bus' => 'Bus', + 'van' => 'Van', + 'suv' => 'SUV', + 'motorcycle' => 'Motorcycle', + 'bicycle' => 'Bicycle' + ]; + $data['vehicle_des'] = [ + 'commercial' => 'Commercial', + 'private' => 'Private', + ]; + $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); + $data['clients'] = $this->clientModel->where('is_active', 1)->findAll(); + $data['vehicle_Master_Data'] = $this->vehicleModel->getVehicleMasterList(); + $this->loadLayout('vehicle_master_list', $data); + } + + public function getVehicleMasterDataByID($id = null) + { + $vehicle_data = $this->vehicleModel + ->select('vehicle.*, clients.client_type') + ->join('clients', 'vehicle.owner = clients.id') + ->where('vehicle.id', $id) + ->where('vehicle.is_active', 1) + ->first(); + + if ($vehicle_data) { + return $this->respond(['status' => true, 'code' => 200, 'data' => $vehicle_data], 200); + } else { + return $this->respond(['status' => false, 'code' => 404], 200); + } + } + + public function deactiveVehicleData($id) + { + + $this->myLogger->logme('error','deactiveVehicleData function called'); + + $data['updated_by'] = get_session_userid(); + $data['is_active'] = 0; + + $update = $this->vehicleModel->where('id', $id)->set($data)->update(); + + if($update){ + return $this->respond(['status' => true,'code' => 200], 200); + }else{ + return $this->respond(['status' => false,'code' => 404], 200); + } + } //excel export template @@ -1440,4 +1552,171 @@ class MasterController extends AdminController ]); } } + + + public function generateNewGmailAPIToken() + { + $gmailapi = \Config\Services::gmailapi(); + $gmailapi->generateNewToken(); + + } + + //testing a sample mail from front end + public function testGmailAPI() + { + + if ($this->request->getMethod() == 'post') { + $gmailapi = \Config\Services::gmailapi(); + + $to = $this->request->getPost('to'); + $subject = $this->request->getPost('subject'); + $mail_content = $this->request->getPost('content'); + + /*****CHOOSE ANY ONE AT A TIME, COMMENT ANOTHER ONE******/ + + /*****CALLING DIRECLT USING LIB******/ + // $res = $gmailapi->sendMessage($to, $subject, $mail_content, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc = [], $bcc = []); + + // if($res['status']) + // { + // return $this->respond(['status' => 'success','code' => 200,'data' => $res],200); + // } + // else + // { + // $this->respond(['status' => 'failed','code' => 500,'data' => $res],200); + // } + /*****CALLING DIRECLT USING LIB******/ + + /*****CALLING VIA MAIL HELPER******/ + $res = MailHelper::send_email(['mail' => $to, 'subject' => $subject, 'message' => $mail_content]); + return $this->respond(['status' => 'success','code' => 200,'data' => $res],200); + /*****CALLING VIA MAIL HELPER******/ + + } + + $this->loadLayout('mail_test'); + + } + + + //testing a sample mail from cli + public function testGmailAPIViaCLI(string $email_id = 'velmurugan.s@venbainfotech.com') + { + // print_r($email_id);die(); + $gmailapi = \Config\Services::gmailapi(); + $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => 'This is sample mail sent via CLI mode']); + print_r($res); + + } + + + public function appCheckList() + { + //check temprory folders in writeable and public/uploads folder + $this->checkAndCreateDirectories(); + $this->checkGoogleOAuthCredentialsinDB(); + $this->getCronJobsList(); + $this->checkGdriveRootFolderID(); + + } + + public function checkAndCreateDirectories() + { + echo "#################### CHECKING TEMP DIRECTORIES ############################\n"; + // Array of folder names and their respective paths + $folders = [ + 'e_card_template' => WRITEPATH . 'e_card_template/', + 'uploads' => WRITEPATH . 'uploads/', + 'excel' => WRITEPATH . 'uploads/excel/', + 'statements' => WRITEPATH . 'uploads/statements/', + 'import_excel' => WRITEPATH . 'uploads/import_excel/', + 'logs' => WRITEPATH . 'uploads/logs/', + 'client_kyc_documents' => WRITEPATH . 'uploads/client_kyc_documents/', + 'tmp' => WRITEPATH . 'tmp/', + 'e_card_imgs' => ROOTPATH . 'public/e_card_imgs', + 'uploads' => ROOTPATH . 'public/uploads', + 'add_image_upload' => ROOTPATH . 'public/uploads/add_image_upload/',//adverdisement images for enrollment app + 'logo' => ROOTPATH . 'public/uploads/logo/', + 'template_bg' => ROOTPATH . 'public/uploads/template_bg/' + ]; + + foreach ($folders as $folderName => $folderPath) { + // Check if the folder exists + if (!is_dir($folderPath)) { + // Try to create the folder + if (mkdir($folderPath, 0777, true)) { + // Set permissions to 0777 + chmod($folderPath, 0777); + echo "\nDirectory '$folderPath' created successfully with 0777 permissions.\n"; + } else { + // Handle error in directory creation + echo "Failed to create directory '$folderPath'.\n"; + } + } else { + echo "Directory '$folderPath' already exists.\n"; + } + } + echo "################################################################\n\n"; + } + + public function checkGoogleOAuthCredentialsinDB() + { + $settingsModel = new SettingsModel(); + $token = $settingsModel->where('id', 1)->first(); + + echo "################ CHECKING GMAIL OAUTH FOR EMAIL ###################\n"; + if (is_array($token) && is_null($token['gmail_api_oauth_credentials'])) { + + echo "Email OAuth credentials not found in database.\n"; + echo "Check the following..!\n"; + echo "1. Update Gmail Oauth credentials in 'gmail_api_oauth_credentials' field in 'settings' table in JSON format.\n"; + echo "2. Call this cli route to generate new access token: 'php public/index.php cli/new_gmail_token' from root of the project.\n"; + echo "3. Call this cli route : 'php public/index.php cli/send_mail_cli someone@gmail.com' to send test mail to testGmailAPIViaCLI ( replace someone@gmail.com with real time mail).\n"; + } + else + { + echo "Gmail OAuth for sending email is set in DB\n"; + } + echo "################################################################\n\n"; + } + + + function getCronJobsList() + { + // Execute the shell command to get cron jobs + $output = null; + $resultCode = null; + echo "#################### CHECKING CRONJOBS ############################\n"; + // Use shell_exec to get cron jobs from the current user's crontab + $output = shell_exec('crontab -l 2>&1'); + + // Check if the command was successful + if (strpos($output, 'no crontab') !== false) { + echo "No cron jobs are set for this user.\n"; + } elseif ($output) { + // Return the cron job list + echo nl2br($output); + echo "\n" ;// Convert newlines to
for easier HTML rendering + } else { + echo "Error retrieving cron jobs or no cron jobs set.\n"; + } + echo "################################################################\n\n"; + } + + //check gdrive root folder id in env file + function checkGdriveRootFolderID() + { + echo "#################### CHECKING GDRIVE FOLDER ID IN ENV FILE ############################\n"; + $id = getenv('GDRIVE_ROOT_FOLDER_ID'); + if($id) + { + echo $this->cli_colors['green'] . "ID is :". $id . $this->cli_colors['reset']. "\n"; + } + else + { + echo $this->cli_colors['red'] ."Gdrive Folder id not set in env file. set it under 'GDRIVE_ROOT_FOLDER_ID' in env file.". $this->cli_colors['reset'] ."\n"; + } + echo "################################################################\n\n"; + } + } \ No newline at end of file diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/PendingActionsController.php b/app/Controllers/PendingActionsController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php new file mode 100644 index 00000000..c927ac44 --- /dev/null +++ b/app/Controllers/PolicyTransactionController.php @@ -0,0 +1,2003 @@ +myLogger = \Config\Services::mylogger(); + + $this->clientModel = new ClientModel(); + $this->clientBranchModel = new ClientBranchModel(); + $this->policyTypeModel = new PolicyTypeModel(); + $this->clientDepositModel = new ClientDepositModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->insurerBranchModel = new InsurerBranchModel(); + $this->insurerModel = new InsurerModel(); + $this->policyTransactionModel = new PolicyTransactionModel(); + $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); + $this->kycEntityTypeModel = new KYCEntityTypeModel(); + $this->clientKYCDocsModel = new ClientKYCDocsModel(); + $this->tpaBranchModel = new TPABranchModel(); + $this->tpaModel = new TPAModel(); + $this->PTFileModel = new PTFileModel(); + $this->PTCOShareDetailsModel = new PTCOShareDetailsModel(); + $this->employeeModel = new EmployeeModel(); + $this->userTeamsModel = new UserTeamsModel(); + $this->userModel = new UserModel(); + $this->employeePolicyModel = new EmployeePolicyModel(); + $this->insurerStatements = new InsurerStatements(); + $this->invPaymentDetailsModel = new InvPaymentDetailsModel(); + $this->invoiceStatus = [ + 'pending' => 'Pending', + 'generated' => 'Generated', + 'sent' => 'Sent', + 'payment_received' => 'Payment Received', + ]; + } + + // Policy Transaction Inception + public function viewInception() + { + $data['page_name'] = 'Policy'; + + $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance']; + $data['client_type'] = [1 => 'Group', 2 => 'Individual']; + $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; + $data['policy_status'] = [ + 'under_process' => 'Under Process', + 'client_pending' => 'Client Pending', + 'insurer_pending' => 'Insurer Pending', + 'co_insurer_pending' => 'Co-Insurer Pending', + 'tpa_pending' => 'TPA Pending', + 'validated' => 'Validated', + 'cancelled' => 'Cancelled', + 'instalment_pending' => 'Instalment Pending', + 'completed' => 'Completed', + ]; + $data['invoice_status_array'] = [ + 'yet_to_generate' => 'Pending', + 'generated' => 'Generated', + 'send' => 'Sent', + 'recived' => 'Payment Received', + ]; + $data['vehicle_type'] = [ + 'two_wheeler' => 'Two Wheeler', + 'four_wheeler' => 'Four Wheeler', + 'truck' => 'Truck', + 'bus' => 'Bus', + 'van' => 'Van', + 'suv' => 'SUV', + 'motorcycle' => 'Motorcycle', + 'bicycle' => 'Bicycle' + ]; + $data['vehicle_des'] = [ + 'commercial' => 'Commercial', + 'private' => 'Private', + ]; + $data['date_type'] = [ + 'policy_issue_date' => 'Policy Issue Date', + 'policy_start_date' => 'Policy Start Date', + 'policy_end_date' => 'Policy End Date', + ]; + + //filter datas + $start_date = $this->request->getGet('start_date'); + $end_date = $this->request->getGet('end_date'); + $client_id = $this->request->getGet('client_id'); + $insurer_id = $this->request->getGet('insurer_id'); + $policy_type_id = $this->request->getGet('policy_type_id'); + $date_type = $this->request->getGet('date_type'); + $issuer = $this->request->getGet('issuer'); + $status = $this->request->getGet('status'); + + $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date; + $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date; + + $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id; + $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id; + $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id; + $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type; + $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer; + $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status; + + + $data['inception_data_list'] = $this->policyTransactionModel->getInceptionTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); + + $data['client'] = $this->clientModel->where('is_active', 1)->findAll(); + $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); + $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll(); + $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); + $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll(); + $data['insurer_branch'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); + $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + + $data['salse_team'] = $this->userModel + ->select('user_profiles.*') + ->join('user_teams', 'user_profiles.id = user_teams.user_id') + ->where('user_teams.team_id', 5) + ->where('user_teams.is_active', 1) + ->where('user_profiles.is_active', 1) + ->findAll(); + + $data['ACM'] = $this->userModel + ->where('user_profiles.role', 3) + ->where('user_profiles.is_active', 1) + ->findAll(); + + + $this->loadLayout('policy_transaction_inception_list', $data); + } + + // policy Transaction Create function start + public function createInceptionPolicy() + { + // print_r($this->request->getPost()); die; + $id = $this->request->getPost('id'); + $data = $this->preparePolicyData(); + // print_r($this->request->getPost()); die; + + + if (!$id) { + return $this->insertInceptionPolicy($data); + } else { + return $this->updateInceptionPolicy($id, $data); + } + } + + private function preparePolicyData() + { + $data = $this->request->getPost(); + + // print_r($data); die; + // var_dump($data); die; + + // Format dates + // $data['policy_issue_date'] = change_date_format($this->request->getPost('policy_issue_date'), 'd/m/Y', 'Y-m-d') ?? null; + // $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd/m/Y', 'Y-m-d') ?? null; + // $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd/m/Y', 'Y-m-d') ?? null; + // $data['renewal_date'] = change_date_format($this->request->getPost('renewal_date'), 'd/m/Y', 'Y-m-d') ?? null; + // $data['rollover_date'] = change_date_format($this->request->getPost('rollover_date'), 'd/m/Y', 'Y-m-d') ?? null; + + // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_issue_date'])) + // : null; + + // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_start_date'])) + // : null; + + // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_end_date'])) + // : null; + + // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') + // ? date('d/m/Y', strtotime($data['renewal_date'])) + // : null; + + // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') + // ? date('d/m/Y', strtotime($data['rollover_date'])) + // : null; + + + if(empty($data['policy_issue_date'])){ + $data['policy_issue_date'] = null; + } + + if(empty($data['policy_start_date'])){ + $data['policy_start_date'] = null; + } + + if(empty($data['policy_end_date'])){ + $data['policy_end_date'] = null; + } + + if(empty($data['renewal_date'])){ + $data['renewal_date'] = null; + } + + if(empty($data['rollover_date'])){ + $data['rollover_date'] = null; + } + + + // Separate Insurer and TPA Branch IDs and IDs + if(isset($data['insurer_id']) && !empty($data['insurer_id'])){ + list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']); + if ($data['tpa']) { + list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']); + } + } + + $data['tsi'] = generate_tsi_code($data['issue_type']); + $data['action_type'] = 'inception'; + + if (!isset($data['co_share'])) { + $data['co_share'] = 0; + } elseif ($data['co_share']) { + $data['co_share'] = 1; + } + + if (!isset($data['bro_payable_by'])) { + $data['bro_payable_by'] = 0; + } elseif ($data['bro_payable_by']) { + $data['bro_payable_by'] = 1; + } + + if (!isset($data['same_as_proposer'])) { + $data['same_as_proposer'] = 0; + } elseif ($data['same_as_proposer']) { + $data['same_as_proposer'] = 1; + } + + if($data['ct_type'] == ""){ + $data['ct_type'] = 1; + } + + $month = '01-'.(string)$this->request->getPost('month'); + $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month)); + + // Determine $is_addon value + $data['is_addon'] = in_array($data['policy_type_id'], [1, 2, 6, 7]) ? 1 : + (in_array($data['policy_type_id'], [4, 5]) ? 2 : ($data['policy_type_id'] == 3 && isset($data['base_policy']) ? 3 : 1)); + + // print_r($data); die; + + return $data; + } + + private function insertInceptionPolicy($data) + { + // print_r($data); die; + + $insert = $this->policyTransactionModel->insert($data); + if ($insert) { + $this->insertTransactionStatus($insert, $data['status'], 1); + $emp_data = $this->processInsertIndividualMemberInEmpTable($data); + + if(isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])){ + + $pt_co_share_details = $this->insertOrUpdateCoShareDetails($data, $insert); + + if ($data['ct_type'] == 2) { + + $client_policy_insert_data = $this->prepareClientPolicyInsertData($data); + $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data); + $this->policyTransactionModel->update($insert, ['client_policy_id' => $client_policy_id]); + $emp_policy_insert = $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id); + + if ($data['client_type'] == 1 && $data['status'] == 'completed') { + $this->processCompletedStatus($data, $client_policy_id, $data['insurer_id']); + } + } + + + $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $insert)->where('is_active', 1)->findAll(); + } + + $client_data = $this->clientModel->where('id', $data['client_id'])->first(); + $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll(); + $data['entity_type_id'] = $client_data['entity_type_id']; + + return $this->respondSuccess($insert, "Policy transaction created successfully", $data); + } + return $this->respondError("Failed to create policy transaction"); + } + + private function updateInceptionPolicy($id, $data) + { + if ($this->policyTransactionModel->update($id, $data)) { + + $this->insertTransactionStatus($id, $data['status'], 1); + $emp_data = $this->processInsertIndividualMemberInEmpTable($data); + + if (isset($data['follow_insurer_id']) && !empty($data['follow_insurer_id'][0])) { + + $this->insertOrUpdateCoShareDetails($data, $id); + + if ($data['ct_type'] == 1) { + $this->policyTransactionModel->update($id, ['client_policy_id' => $data['client_policy_id']]); + } + + if (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) { + + if ($data['ct_type'] == 2) { + $client_policy_insert_data = $this->prepareClientPolicyInsertData($data); + $client_policy_id = $this->clientPolicyModel->insert($client_policy_insert_data); + $this->policyTransactionModel->update($id, ['client_policy_id' => $client_policy_id]); + $this->InsertIndividualEmpPolicyTable($emp_data, $client_policy_id); + } + + } else { + if (isset($data['emp_policy_id']) && !empty($data['emp_policy_id'][0])) { + $this->InsertIndividualEmpPolicyTable($emp_data, $data['client_policy_id']); + } + } + + if ($data['status'] == 'completed' && $data['ct_type'] == 2) { + if($data['client_type'] == 1){ + $this->processCompletedStatus($data, $data['client_policy_id'], $data['insurer_id']); + } + } + + $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll(); + } + + $client_data = $this->clientModel->where('id', $data['client_id'])->first(); + $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll(); + $data['entity_type_id'] = $client_data['entity_type_id']; + + return $this->respondSuccess($id, "Policy transaction updated successfully", $data); + } + + return $this->respondError("Failed to update policy transaction"); + } + + private function insertOrUpdateCoShareDetails($data, $pt_id) + { + // Prepare data for insertion and updating + $coShareDetails = []; + + // print_r($data); + // die; + + if(isset($data['follow_insurer_id'])){ + + foreach ($data['follow_insurer_id'] as $index => $insurer) { + + // Separate the insurer and insurer branch + list($insurer_branch_id, $insurer_id) = explode('-', $insurer); + + // Prepare each co-share detail entry + $coShareDetails[] = [ + 'pt_id' => $pt_id, + 'insurer_id' => $insurer_id ?? 0, + 'insurer_branch_id' => $insurer_branch_id ?? 0, + 'co_share_type' => $data['co_share_type'][$index] ?? null, + 'co_share_per' => $data['co_share_per'][$index] ?? 0, + 'bp_amt' => $data['base_premium'][$index] ?? 0, + 'bp_gst_amt' => $data['gst_amount'][$index] ?? 0, + 'bp_igst' => $data['igst'][$index] ?? 0, + 'bp_sgst' => $data['sgst'][$index] ?? 0, + 'bp_cgst' => $data['cgst'][$index] ?? 0, + 'tp_amt' => $data['tp_premium'][$index] ?? 0, + 'tep_amt' => $data['ter_premium'][$index] ?? 0, + 'agreed_amt' => $data['agreed_amount'][$index] ?? 0, + 'agreed_bp_per' => $data['agreed_bp'][$index] ?? 0, + 'agreed_tp_per' => $data['agreed_tp'][$index] ?? 0, + 'agreed_tep_per' => $data['agreed_ter'][$index] ?? 0, + 'standerd_bp_per' => $data['standard_bp'][$index] ?? 0, + 'standerd_tp_per' => $data['standard_tp'][$index] ?? 0, + 'standerd_tep_per' => $data['standard_ter'][$index] ?? 0, + 'actual_bp_amt' => $data['actual_bp_amt'][$index] ?? 0, + 'actual_tp_amt' => $data['actual_tp_amt'][$index] ?? 0, + 'actual_tep_amt' => $data['actual_tep_amt'][$index] ?? 0, + 'actual_bp_per' => $data['actual_bp_per'][$index] ?? 0, + 'actual_tp_per' => $data['actual_tp_per'][$index] ?? 0, + 'actual_tep_per' => $data['actual_tep_per'][$index] ?? 0, + 'actual_bp_brokerage_amt' => $data['actual_bp_brokerage_amt'][$index] ?? 0, + 'actual_tp_brokerage_amt' => $data['actual_tp_brokerage_amt'][$index] ?? 0, + 'actual_tep_brokerage_amt' => $data['actual_tep_brokerage_amt'][$index] ?? 0, + 'exp_amt' => $data['exp_amt'][$index] ?? 0, + 'amount' => $data['total'][$index] ?? 0, + 'stamp_duty' => $data['stamp_duty'][$index] ?? 0, + 'cop_amt' => $data['co_premium'][$index] ?? 0, + 'variance' => $data['variance'][$index] ?? 0, + 'reward' => $data['reward'][$index] ?? null, + 'created_by' => get_session_userid() ?? null, + 'updated_by' => get_session_userid() ?? null, + 'id' => $data['co_share_id'][$index] ?? null, // Assuming this is the ID to identify existing records + ]; + } + + // print_r($pt_id); + // print_r($coShareDetails); + // die; + + // Separate data into insert and update batches + $insertData = array_filter($coShareDetails, function($detail) { + return empty($detail['id']); // Only insert new records + }); + + $updateData = array_filter($coShareDetails, function($detail) { + return !empty($detail['id']); // Only update existing records + }); + + // Insert new records + if (!empty($insertData)) { + $this->PTCOShareDetailsModel->insertBatch($insertData); + } + + // Update existing records + if (!empty($updateData)) { + $this->PTCOShareDetailsModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier + } + + // print_r($this->PTCOShareDetailsModel->getLastQuery()); die; + + // print_r($coShareDetails); + // die; + + return true; + + } + + // print_r($data); + // die; + } + + private function prepareClientPolicyInsertData($data) + { + return [ + 'client_id' => $data['client_id'] ?? null, + 'insurer_id' => $data['insurer_id'] ?? null, + 'insurer_branch_id' => $data['insurer_branch_id'] ?? null, + 'tpa_id' => $data['tpa_id'] ?? null, + 'tpa_branch_id' => $data['tpa_branch_id'] ?? null, + 'policy_type_id' => $data['policy_type_id'] ?? null, + 'policy_start_date' => $data['policy_start_date'] ?? null, + 'policy_end_date' => $data['policy_end_date'] ?? null , + 'policy_status' => 1, + 'is_addon' => $data['is_addon'] ?? null, + 'base_policy' => $data['base_policy'] ?? 0, + 'created_by' => get_session_userid(), + 'policy_no' => $data['policy_no'] ?? null, + 'client_branch_id' => $data['client_branch_id'] ?? 0, + 'cd_ac_no' => $data['cd_ac_no'] ?? null, + 'gst' => 18, + ]; + } + + private function insertTransactionStatus($policyTranId, $status, $statusType) + { + $statusData = [ + 'policy_tran_id' => $policyTranId, + 'status' => $status, + 'status_type' => $statusType, + 'created_by' => get_session_userid(), + ]; + $this->policyTransactionStatusModel->insert($statusData); + } + + private function processCompletedStatus($data, $client_policy_id, $insurer_id) + { + $totalAmount = (int)$data['total'][0] ?? 0; + $description = 'The following amount of Rs. ' . $totalAmount . '/- has been debited for the ' . $data['emp_count'] . ' employees at Inception.'; + + $cdTransactionData = [ + 'amount' => $totalAmount, + 'sub_type_id' => 4, + 'client_id' => $data['client_id'], + 'client_policy_id' => $client_policy_id ?? 0, + 'endorsement_no' => null, + 'cd_ac_no' => $data['cd_ac_no'] ?? null, + 'insurer_id' => $insurer_id, + 'description' => $description, + 'transaction_type' => 'Debit', + 'updated_by' => get_session_userid(), + 'event_name' => 'inception', + 'is_active' => 1, + ]; + + DepositHelper::saveDeposit($cdTransactionData, get_session_userid()); + } + + private function processInsertIndividualMemberInEmpTable($data) + { + // print_r($data); + if(isset($data['family_name']) && !empty($data['family_name'])){ + + $emp_data = []; + $emp_ids = []; + $random_code = generateRandomCode(); // Generate random code once + + foreach ($data['family_name'] as $index => $val) { + + // Determine the gender based on the relationship + $relationship = $data['relationship'][$index] ?? ''; + $gender = 'M'; // Default to Male + + // Set gender based on relationship + if (in_array($relationship, ['Mother', 'Daughter', 'Mother in law', 'Spouse'])) { + $gender = 'F'; + } + + $emp_data[] = [ + 'client_id' => $data['client_id'] ?? 0, + 'client_branch_id' => $data['client_branch_id'] ?? 0, + 'name' => $val, + 'relationship' => $relationship, + 'gender' => $gender, + 'emp_status' => 'active', + 'created_by' => get_session_userid(), + 'emp_code' => $random_code, // Use the same random code for all + 'id' => $data['emp_id'][$index] ?? null + ]; + + $emp_ids[] = $data['emp_id'][$index] ?? 0; + } + + + // print_r($emp_data); die; + + // Separate data into insert and update batches + $insertData = array_filter($emp_data, function($detail) { + return empty($detail['id']); // Only insert new records + }); + + $updateData = array_filter($emp_data, function($detail) { + return !empty($detail['id']); // Only update existing records + }); + + // Insert new records + if (!empty($insertData)) { + $this->employeeModel->insertBatch($insertData); + } + + // Update existing records + if (!empty($updateData)) { + $this->employeeModel->updateBatch($updateData, 'id'); // Assuming 'id' is the unique identifier + } + + return $emp_ids; + + } + } + + private function InsertIndividualEmpPolicyTable($emp_ids, $client_policy_id) + { + if(!empty($emp_ids)){ + + $emp_policy_data = []; + + foreach ($emp_ids as $index => $emp_id) { + + $emp_policy_data[] = [ + 'employee_id' => $emp_id ?? 0, + 'client_policy_id' => $client_policy_id ?? 0, + 'created_by' => get_session_userid(), + 'status' => 'active', + ]; + } + + // print_r($emp_policy_data); die; + + // Insert new records + if (!empty($emp_policy_data)) { + $this->employeePolicyModel->insertBatch($emp_policy_data); + } + + + return true; + + } + } + + private function respondSuccess($id, $message, $data) + { + return $this->respond(['status' => true, 'pt_id' => $id, 'message' => $message, 'data' =>$data], 200); + } + + private function respondError($message) + { + return $this->respond(['status' => false, 'message' => $message], 200); + } + // policy Transaction Create function End + + // Get the Single Inception Tranction data for edit + public function getInceptionDataForEdit($id) + { + $data = $this->policyTransactionModel + ->select(' + policy_transaction.*, + clients.short_name as client_short_name, + clients.client_type, + clients.entity_type_id, + policy_type.policy_type, + client_policy.tpa_id as master_tpa_id, + client_policy.tpa_branch_id as master_tpa_branch_id, + client_policy.policy_type_id as master_policy_type_id, + client_policy.is_addon, + client_policy.base_policy, + ') + ->join('clients', 'clients.id = policy_transaction.client_id') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.id', $id) + ->first(); + + // $data['policy_issue_date'] = (isset($data['policy_issue_date']) && $data['policy_issue_date'] !== null && $data['policy_issue_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_issue_date'])) + // : null; + + // $data['policy_start_date'] = (isset($data['policy_start_date']) && $data['policy_start_date'] !== null && $data['policy_start_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_start_date'])) + // : null; + + // $data['policy_end_date'] = (isset($data['policy_end_date']) && $data['policy_end_date'] !== null && $data['policy_end_date'] !== '') + // ? date('d/m/Y', strtotime($data['policy_end_date'])) + // : null; + + // $data['renewal_date'] = (isset($data['renewal_date']) && $data['renewal_date'] !== null && $data['renewal_date'] !== '') + // ? date('d/m/Y', strtotime($data['renewal_date'])) + // : null; + + // $data['rollover_date'] = (isset($data['rollover_date']) && $data['rollover_date'] !== null && $data['rollover_date'] !== '') + // ? date('d/m/Y', strtotime($data['rollover_date'])) + // : null; + + // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') + // ? date('M/Y', strtotime($data['month'])) + // : null; + + + $data['created_at'] = (isset($data['created_at']) && $data['created_at'] !== null && $data['created_at'] !== '') + ? date('d/m/Y h:i:s A', strtotime($data['created_at'])) + : null; + + $data['updated_at'] = (isset($data['updated_at']) && $data['updated_at'] !== null && $data['updated_at'] !== '') + ? date('d/m/Y h:i:s A', strtotime($data['updated_at'])) + : null; + + + if(!empty($data['policy_issue_date'])){ + $data['policy_issue_date'] = change_date_format($data['policy_issue_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['policy_start_date'])){ + $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['policy_end_date'])){ + $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['renewal_date'])){ + $data['renewal_date'] = change_date_format($data['renewal_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['rollover_date'])){ + $data['rollover_date'] = change_date_format($data['rollover_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['endorse_eff_date'])){ + $data['endorse_eff_date'] = change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y'); + } + + if(!empty($data['month'])){ + $data['month'] = change_date_format($data['month'], 'Y-m-d', 'M/Y'); + } + + + + // print_r($data); die; + + $data['renewal_policy'] = $this->clientPolicyModel + ->select('client_policy.*, policy_type.policy_type') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->where('client_policy.client_id', $data['client_id']) + ->where('client_policy.client_branch_id', $data['client_branch_id']) + ->where('client_policy.is_active', 1) + ->findAll(); + + + $data['base_policy_data'] = $this->clientPolicyModel + ->select('client_policy.*, policy_type.policy_type') + ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') + ->where('client_policy.client_id', $data['client_id']) + ->where('client_policy.client_branch_id', $data['client_branch_id']) + ->whereIn('client_policy.policy_type_id', [2, 3]) + ->where('client_policy.is_active', 1) + ->findAll(); + + $data['pt_files'] = $this->PTFileModel + ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id') + ->where('pt_files.pt_id', $id) + ->where('pt_files.is_active', 1) + ->findAll(); + $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll(); + $data['emp_data'] = $this->employeeModel + ->select('employees.*, employee_polices.id as emp_policy_id') + ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') + ->where('employees.client_id', $data['client_id']) + ->where('employees.is_active', 1)->findAll(); + $data['client_kyc'] = $this->clientKYCDocsModel->where('client_id', $data['client_id'])->findAll(); + $data['vehicle_docs'] = $this->clientKYCDocsModel + ->where('client_id', $data['client_id']) + ->where('vehicle_id', $data['vehicle_id']) + ->findAll(); + + // print_r( $data['pt_co_share_details']); die; + + if($data){ + return $this->respond(['status' => true, 'data' => $data], 200); + }else{ + return $this->respond(['status' => false], 200); + } + + } + + //------------------------------------------------------------------------------------------------ + + // Policy Transaction Endorsement + public function viewEndorsement() + { + // echo '
';
+        // !dd($this->getEndorsementDataForEdit(17));
+
+        $data['page_name'] = 'Endorsement';
+
+        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+        $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+
+        $data['policy_status'] = [
+            'under_process' => 'Under Process',
+            'client_pending' => 'Client Pending',
+            'insurer_pending' => 'Insurer Pending',
+            'co_insurer_pending' => 'Co-Insurer Pending',
+            'tpa_pending' => 'TPA Pending',
+            'validated' => 'Validated',
+            'cancelled' => 'Cancelled',
+            'instalment_pending' => 'Instalment Pending',
+            'completed' => 'Completed',
+        ];
+
+        $data['invoice_status'] = [
+            'yet_to_generate' => 'Pending',
+            'generated' => 'Generated',
+            'send' => 'Sent',
+            'recived' => 'Payment Received',
+        ];
+
+        $data['action_type'] = [
+            'addition' => 'Addition',
+            'deletion' => 'Deletion',
+            'addition_deletion' => 'Addition & Deletion',
+            'si_enhancement' => 'SI Enhancement',
+            'combo_a_d_si' => 'Combo A, D & SI',
+            'correction' => 'Correction',
+            'baby_addition' => 'Baby Addition',
+            'policy_instalment' => 'Policy Instalment',
+            'addition_inception' => 'Addition-Inception',
+            'bds_correction' => 'BDS Correction',
+            'policy_correction' => 'Policy Correction',
+            'policy_cancellation' => 'Policy Cancellation',
+        ];
+
+        $data['date_type'] = [
+            'policy_issue_date' => 'Policy Issue Date',
+            'policy_start_date' => 'Policy Start Date',
+            'policy_end_date' => 'Policy End Date',
+        ];
+
+        //filter datas
+        $start_date = $this->request->getGet('start_date');
+        $end_date = $this->request->getGet('end_date');
+        $client_id = $this->request->getGet('client_id');
+        $insurer_id = $this->request->getGet('insurer_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
+        $date_type = $this->request->getGet('date_type');
+        $issuer = $this->request->getGet('issuer');
+        $status = $this->request->getGet('status');
+        
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
+        
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+        $status = (!isset($issuer) || $status === '' || $status === null) ? 0 : $status;   
+
+
+        $data['endorsement_data_list'] = $this->policyTransactionModel->getEndorsementTranctionListData($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status);
+        $data['client'] = $this->clientModel->where('is_active', 1)->findAll();
+        $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+
+        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+        // $data['tpa']           = $this->tpaModel->where('is_active', 1)->findAll();
+        $data['insurer_branch']      = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
+        $data['tpa']           = $this->tpaBranchModel ->getTpaBranchesWithTpaNames();
+
+
+        $this->loadLayout('policy_transaction_endorsement_list', $data);
+    }
+
+    public function createEndorsementPolicy()
+    {
+        $id = $this->request->getPost('id');
+        $data = $this->preparePolicyTransactionData();
+        
+        if (!$id) {
+            return $this->insertEndorsementTransaction($data);
+        } else {
+            return $this->updateEndorsementTransaction($id, $data);
+        }
+    }
+
+    private function preparePolicyTransactionData()
+    {
+        $data = $this->request->getPost();
+
+        // echo '
';
+        // print_r($data); 
+        // die;
+
+        // $data_received_date = (string)$this->request->getPost('data_received_date');
+        // $closure_date = (string)$this->request->getPost('closure_date');
+        // $endorse_eff_date = (string)$this->request->getPost('endorse_eff_date');
+        // $month = (string)$this->request->getPost('month');
+
+        // $data['data_received_date'] = empty($data['data_received_date']) ? null : date('Y-m-d', strtotime($data_received_date));
+        // $data['closure_date'] = empty($data['closure_date']) ? null : date('Y-m-d', strtotime($closure_date));
+        // $data['endorse_eff_date'] = empty($data['endorse_eff_date']) ? null : date('Y-m-d', strtotime($endorse_eff_date));
+
+        // $month = '01-'.$data['month'];
+        // $data['month'] = empty($data['month']) ? null : date('Y-m-d', strtotime($month)); 
+
+
+
+        if(!empty($data['data_received_date'])){
+            $data['data_received_date'] =  change_date_format($data['data_received_date'], 'd/m/Y', 'Y-m-d');
+        }
+
+        if(!empty($data['closure_date'])){
+            $data['closure_date'] =  change_date_format($data['closure_date'], 'd/m/Y', 'Y-m-d');
+        }
+
+        if(!empty($data['endorse_eff_date'])){
+            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'd/m/Y', 'Y-m-d');
+        }
+
+        if(!empty($data['month'])){
+            $month = '01/'.$data['month'];
+            $data['month'] =  change_date_format($month, 'd/M/Y', 'Y-m-d');
+        }
+
+        // print_r($data); die;   
+
+        // Separate Insurer and TPA Branch IDs and IDs
+        if(isset($data['insurer_id']) && !empty($data['insurer_id'])){
+            list($data['insurer_branch_id'], $data['insurer_id']) = explode('-', $data['insurer_id']);
+            if (isset($data['tpa'])) {
+                list($data['tpa_branch_id'], $data['tpa_id']) = explode('-', $data['tpa']);
+            }
+        }
+
+        $issue_type = $this->policyTransactionModel
+                        ->where('action_type', 'inception')
+                        ->where('client_id', $this->request->getPost('client_id'))
+                        ->where('client_policy_id', $this->request->getPost('client_policy_id'))
+                        ->first();
+
+        $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
+
+        $client_branch_id = $data['client_branch_id'];
+        if($data['client_branch_id'] == ""){
+            $client_branch_id = $issue_type['client_branch_id'];
+        }
+
+        if(!$data['id']){
+
+            $data += [
+                'issuer' => $issue_type['issuer'] ?? null,
+                'client_type' => $data['client_type'] ?? $issue_type['client_type'] ?? null,
+                'policy_type_id' => $issue_type['policy_type_id'] ?? null,
+                'policy_type_id' => $issue_type['policy_type_id'] ?? null,
+                'issue_type' => $issue_type['issue_type'] ?? null,
+                'source_client_policy_id' => $issue_type['source_client_policy_id'] ?? null,
+                'cd_ac_no' => $issue_type['issue_type'] ?? null,
+                'policy_issue_date' => $issue_type['policy_issue_date'] ?? null,
+                'policy_start_date' => $issue_type['policy_start_date'] ?? null,
+                'policy_end_date' => $issue_type['policy_end_date'] ?? null,
+                'revenue_type' =>  $issue_type['revenue_type'] ?? null,
+                'co_share' => $issue_type['co_share'] ?? 0,
+                'bro_payable_by' => $issue_type['bro_payable_by'] ?? 0,
+                'installment' => $issue_type['installment'] ?? null,
+                'installment_data' => $issue_type['installment_data'] ?? null,
+                'location' => $issue_type['location'] ?? null,
+                'links' =>  $issue_type['links'] ??null,
+                'stage' => $issue_type['stage'] ?? null,
+                'etat' => $issue_type['etat'] ?? null,
+                'etat_band' => $issue_type['etat_band'] ?? null,
+                'edate' => $issue_type['edate'] ?? null,
+                'renewal_date' => $issue_type['renewal_date'] ?? null,
+                'rollover_date' => $issue_type['rollover_date'] ?? null,
+                'policy_holder_name' => $issue_type['policy_holder_name'] ?? null,
+                'same_as_proposer' => $issue_type['same_as_proposer'] ?? 1,
+                'ref' => $issue_type['ref'] ?? null,
+                'spl' => $issue_type['spl'] ?? null,
+                'fund_received' => $issue_type['fund_received'] ?? null,
+                'listed_insurers' => $issue_type['listed_insurers'] ?? null,
+                'ppteam' => $issue_type['ppteam'] ?? null,
+                'sales_generated_by' => $issue_type['sales_generated_by'] ?? null,
+                'serviced_by' => $issue_type['serviced_by'] ?? null
+            ];
+
+            $data['client_branch_id'] = $client_branch_id;
+        }
+
+        // print_r($issue_type); 
+        // print_r($data); 
+        // die;
+
+        return $data;
+    }
+
+    private function insertEndorsementTransaction($data)
+    {
+        $insert = $this->policyTransactionModel->insert($data);
+
+        if ($insert) {
+
+            $this->insertTransactionStatus($insert, $data['status'], 1);
+            $this->handleCompletedStatus($data, $insert);
+            $this->insertOrUpdateCoShareDetails($data, $insert);
+
+            return $this->respond(['status' => true, 'message' => 'Endorsement transaction created successfully'], 200);
+        }
+
+        return $this->respond(['status' => false, 'message' => 'Endorsement transaction creation failed'], 400);
+    }
+
+    private function updateEndorsementTransaction($id, $data)
+    {
+        $update = $this->policyTransactionModel->where('id', $id)->set($data)->update();
+
+        if ($update) {
+            $this->insertTransactionStatus($id, $data['status'], 1);
+            $this->handleCompletedStatus($data, $id);
+            $this->insertOrUpdateCoShareDetails($data, $id);
+
+
+            return $this->respond(['status' => true, 'message' => 'Endorsement transaction updated successfully'], 200);
+        }
+
+        return $this->respond(['status' => false, 'message' => 'Endorsement transaction update failed'], 400);
+    }
+
+    private function handleCompletedStatus($data, $policy_tran_id)
+    {
+        if ($data['status'] == 'completed' && $data['ct_type'] == 2) {
+
+            $tolamt = $data['total'][0] ?? 0;
+
+            $description = 'The following amount of Rs. ' . round($tolamt, 2) . '/- has been' . 
+                        ($data['action_type'] == 'deletion' ? ' Credit ' : ' Debit ') . 'from the policy transaction';
+
+            $cd_tranction_data = [
+                'amount' => $tolamt,
+                'sub_type_id' => $data['action_type'] == 'deletion' ? 3 : 4,
+                'client_id' => $data['client_id'],
+                'client_policy_id' => $data['client_policy_id'],
+                'endorsement_no' => null,
+                'cd_ac_no' => $data['cd_ac_no'] ?? null,
+                'insurer_id' => $data['insurer_id'],
+                'description' => $description,
+                'transaction_type' => $data['action_type'] == 'deletion' ? 'Credit' : 'Debit',
+                'updated_by' => get_session_userid(),
+                'event_name' => $data['action_type'],
+                'is_active' => 1,
+            ];
+
+            DepositHelper::saveDeposit($cd_tranction_data, get_session_userid());
+        }
+    }
+
+    public function getEndorsementDataForEdit($id)
+    {
+        $data = $this->policyTransactionModel
+                ->select('
+                        policy_transaction.*, 
+                        clients.short_name as client_short_name, 
+                        clients.client_type, 
+                    ')
+                ->join('clients', 'clients.id = policy_transaction.client_id')
+                ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left')
+                ->where('policy_transaction.id', $id)
+                ->first();
+
+        // $data['policy_start_date'] = empty($data['policy_start_date']) ? '' : date('d/m/Y', strtotime($data['s_date']));
+        // $data['policy_end_date'] = empty($data['policy_end_date']) ? '' : date('d/m/Y', strtotime($data['e_date']));
+        // $data['data_received_date'] = empty($data['data_received_date']) ? '' : date('d/m/Y', strtotime($data['data_received_date']));
+        // $data['closure_date'] = empty($data['closure_date']) ? '' : date('d/m/Y', strtotime($data['closure_date']));
+        // $data['endorse_eff_date'] = empty($data['endorse_eff_date']) ? '' : date('d/m/Y', strtotime($data['endorse_eff_date']));
+
+        // $data['month'] = (isset($data['month']) && $data['month'] !== null && $data['month'] !== '') 
+        //     ? date('M/Y', strtotime($data['month'])) 
+        //     : null;
+
+
+        if(!empty($data['policy_start_date'])){
+            $data['policy_start_date'] =  change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if(!empty($data['policy_end_date'])){
+            $data['policy_end_date'] =  change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if(!empty($data['data_received_date'])){
+            $data['data_received_date'] =  change_date_format($data['data_received_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if(!empty($data['closure_date'])){
+            $data['closure_date'] =  change_date_format($data['closure_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if(!empty($data['endorse_eff_date'])){
+            $data['endorse_eff_date'] =  change_date_format($data['endorse_eff_date'], 'Y-m-d', 'd/m/Y');
+        }
+
+        if(!empty($data['month'])){
+            $data['month'] =  change_date_format($data['month'], 'Y-m-d', 'M/Y');
+        }
+
+        // print_r($data); die;
+
+
+        $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
+
+        // print_r($data['endorse_eff_date']); die;
+
+        if($data){
+            return $this->respond(['status' => true, 'data' => $data], 200);
+        }else{
+            return $this->respond(['status' => false], 200);
+        }
+
+    }
+
+    //------------------------------------------------------------------------------------------------
+
+    //file upload function 
+    public function uploadFile()
+    {   
+        $GoogleDriveController = new GoogleDriveController();
+        $files = $this->request->getFiles();
+        $doc_name = $this->request->getPost('doc_name[]');     
+        $pt_id = $this->request->getPost('pt_id');     
+        $client_policy_id = $this->request->getPost('client_policy_id');     
+        $data = $this->request->getPost();     
+
+        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
+
+        $uploadData = [];
+
+        foreach ($data['doc_name'] as $key => $docName) {
+
+            // Get the corresponding file for this document name
+            $file = $files['file'][$key];
+
+            if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
+
+                // Upload the file
+                $uploadedFileName = file_Upload($file, $uploadFilePath);
+
+                if ($uploadedFileName) {
+                    // Prepare data for each document upload
+                    $docData = [
+                        'pt_id' => $pt_id,
+                        'doc_name' => $docName,
+                        'file_name' => $uploadedFileName,
+                        'created_by' => get_session_userid(),
+                    ];
+
+                    $uploadFilePath = $uploadFilePath . '/' . $uploadedFileName;
+
+                    $GoogleDriveController->uploadFiletoGdrive(client_policy_id: $client_policy_id, doc_type: 'POLICY', file_path: $uploadFilePath, file_name: $uploadedFileName);
+
+                    // Insert into database
+                    $insert = $this->PTFileModel->insert($docData);
+
+                    if ($insert) {
+                        $uploadData[] = $docData; 
+                    }
+                }
+            }
+        }
+
+        // print_r($uploadData); die;
+
+        // $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
+        
+        if (!empty($uploadData)) {
+
+            $data['pt_files'] = $this->PTFileModel
+                ->join('policy_transaction', 'pt_files.pt_id = policy_transaction.id')
+                ->where('pt_files.pt_id', $pt_id)
+                ->where('pt_files.is_active', 1)
+                ->findAll();           
+                 
+            return $this->respond(['status' => true, 'message' => 'File uploaded successfully in G-Drive', 'data' => $data]);
+        } else {
+            return $this->respond(['status' => false, 'message' => 'Failed to upload file in G-Drive']);
+        }
+    }
+
+    // update Invoice Status 
+    public function updateInvoiceStatus()
+    {
+        $ids = $this->request->getPost('ids');
+        $ids = json_decode($ids);
+
+        // var_dump($ids); die;
+
+        $data['invoice_status'] = $this->request->getPost('invoice_status');
+        if($this->request->getPost('invoice_status') == 'generated'){
+            $data['invoice_no'] = $this->request->getPost('invoice_no');
+        }
+
+
+        $update = $this->policyTransactionModel
+            ->whereIn('id', $ids)
+            ->set($data)
+            ->update();
+            
+    
+        if ($update) {
+
+            return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Invoice status updated successfully'], 200);
+        } else {
+            return $this->respond(['status' => true, 'data' => $ids, 'message' => 'Failed to update invoice status'], 200);
+        }
+    }
+
+    public function removeCoShareData($id)
+    {
+        $this->myLogger->logme('error', 'PT Co Share Detailes Remove function called');
+
+        $data = [
+            'updated_by' => get_session_userid(),
+            'is_active' => 0
+        ];
+        
+        $update = $this->PTCOShareDetailsModel->where('id', $id)->set($data)->update();
+
+        if ($update) {
+            return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data removed successfully'], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove data'], 200);
+        }
+    }
+
+    public function getPTCOShareCount($client_id, $client_policy_id)
+    {
+        $totalCount = $this->PTCOShareDetailsModel
+            ->select('pt_co_share_details.*')
+            ->join('policy_transaction', 'policy_transaction.id = pt_co_share_details.pt_id')
+            ->where('policy_transaction.client_id', $client_id)
+            ->where('policy_transaction.client_policy_id', $client_policy_id)
+            ->where('policy_transaction.action_type', 'inception')
+            ->findAll();
+
+        if ($totalCount) {
+            return $this->respond(['status' => true, 'code' => 200, 'data' => $totalCount], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to get data'], 200);
+        }
+
+    }
+
+    public function checkInvoiceStatus($pt_id)
+    {
+        $data = $this->policyTransactionModel
+            ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id')
+            ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id')
+            ->where('policy_transaction.id', $pt_id)
+            ->where('pt_co_share_details.statement_id IS NOT NULL')
+            ->where('insurer_statements.invoice_no IS NOT NULL')
+            ->countAllResults();
+
+        if($data){
+            return $this->respond(['status' => true, 'count'=> $data,  'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+        }
+    }
+
+    public function getBasePolicy($client_id, $client_branch_id)
+    {
+        $data = $this->clientPolicyModel
+        ->select('client_policy.*, policy_type.policy_type')
+        ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
+        ->where('client_policy.client_id', $client_id)
+        ->where('client_policy.client_branch_id', $client_branch_id)
+        ->whereIn('client_policy.policy_type_id', [2, 3])
+        ->where('client_policy.is_active', 1)
+        ->findAll();
+
+        if($data){
+            return $this->respond(['status' => true, 'data'=> $data,  'code' => 200], 200);
+        }else{
+            return $this->respond(['status' => false, 'count'=> 0, 'message' => 'No Data Found', 'code' => 404], 200);
+        }
+    }
+
+    //---------------------------------------------------------------------------------------------------
+
+    //get BDS Reports data
+    public function reportBDS()
+    {   
+
+        $data['page_name'] = 'BDS Report';
+
+        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+        $data['client_type'] = [1 => 'Group', 2 => 'Individual'];
+        $data['issuing_type'] = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over'];
+        $data['policy_status'] = [
+            'pending' => 'Pending',
+            'exported_to_insurer' => 'Exported to Insurer',
+            'imported_from_insurer' => 'Imported from Insurer',
+            'exported_to_tpa' => 'Exported to TPA',
+            'imported_from_tpa' => 'Imported from TPA',
+            'completed' => 'Completed'
+        ];   
+        $data['invoice_status_array'] = [
+            'yet_to_generate' => 'Yet to Generate',
+            'generated' => 'Generated',
+            'send' => 'Send',
+            'recived' => 'Recived',
+        ];
+        $data['date_type'] = [
+            'policy_issue_date' => 'Policy Issue Date',
+            'policy_start_date' => 'Policy Start Date',
+            'policy_end_date' => 'Policy End Date',
+            'data_received_date' => 'Data Received Date',
+            'closure_date' => 'Closure Date',
+        ];
+
+        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+
+        //filter datas
+        $start_date = $this->request->getGet('start_date');
+        $end_date = $this->request->getGet('end_date');
+        $client_id = $this->request->getGet('client_id');
+        $insurer_id = $this->request->getGet('insurer_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
+        $date_type = $this->request->getGet('date_type');
+        $issuer = $this->request->getGet('issuer');
+        
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
+        
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+        
+        
+        //Actual data for the list
+        $data['report_list'] = $this->policyTransactionModel->getBDSReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+        // dd($data);
+        
+        $this->loadLayout('report_bds_filter', $data); 
+    }
+
+    public function reportVarience()
+    {   
+        $data['page_name'] = 'Variance Report';
+
+        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+        $data['date_type'] = [
+            'policy_issue_date' => 'Policy Issue Date',
+            'policy_start_date' => 'Policy Start Date',
+            'policy_end_date' => 'Policy End Date',
+            'data_received_date' => 'Data Received Date',
+            'closure_date' => 'Closure Date',
+        ];
+
+        //filter datas
+        $start_date = $this->request->getGet('start_date');
+        $end_date = $this->request->getGet('end_date');
+        $client_id = $this->request->getGet('client_id');
+        $insurer_id = $this->request->getGet('insurer_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
+        $date_type = $this->request->getGet('date_type');
+        $issuer = $this->request->getGet('issuer');
+        
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
+        
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+
+
+
+        $data['varience_list'] = $this->policyTransactionModel->getVarienceReportLIst($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+        $this->loadLayout('variance_report_list', $data); 
+
+    }
+
+
+    public function reportBusinessList()
+    {   
+        $data['page_name'] = 'Business Report';
+
+        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+        $data['date_type'] = [
+            'policy_issue_date' => 'Policy Issue Date',
+            'policy_start_date' => 'Policy Start Date',
+            'policy_end_date' => 'Policy End Date',
+            'data_received_date' => 'Data Received Date',
+            'closure_date' => 'Closure Date',
+        ];
+
+        //filter datas
+        $start_date = $this->request->getGet('start_date');
+        $end_date = $this->request->getGet('end_date');
+        $client_id = $this->request->getGet('client_id');
+        $insurer_id = $this->request->getGet('insurer_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
+        $date_type = $this->request->getGet('date_type');
+        $issuer = $this->request->getGet('issuer');
+        
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
+        
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+
+
+        $data['business_list'] = $this->policyTransactionModel->getBusinessReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+        $this->loadLayout('business_team_list', $data);     
+    }
+
+
+    public function reportFinanceList()
+    {   
+        $data['page_name'] = 'Finance Report';
+
+        $data['issuer'] = [1 => 'JIBS', 2 => 'Nhance'];
+        $data['insurer'] = $this->insurerModel->where('is_active', 1)->findAll();
+        $data['policy_types'] = $this->policyTypeModel->where('is_active', 1)->findAll();
+        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
+        $data['date_type'] = [
+            'policy_issue_date' => 'Policy Issue Date',
+            'policy_start_date' => 'Policy Start Date',
+            'policy_end_date' => 'Policy End Date',
+            'data_received_date' => 'Data Received Date',
+            'closure_date' => 'Closure Date',
+        ];
+
+        //filter datas
+        $start_date = $this->request->getGet('start_date');
+        $end_date = $this->request->getGet('end_date');
+        $client_id = $this->request->getGet('client_id');
+        $insurer_id = $this->request->getGet('insurer_id');
+        $policy_type_id = $this->request->getGet('policy_type_id');
+        $date_type = $this->request->getGet('date_type');
+        $issuer = $this->request->getGet('issuer');
+        
+        $start_date = (!isset($start_date) || $start_date === '' || $start_date === null) ? 0 : $start_date;
+        $end_date = (!isset($end_date) || $end_date === '' || $end_date === null) ? 0 : $end_date;
+        
+        $client_id = (!isset($client_id) || $client_id === '' || $client_id === null) ? 0 : $client_id;
+        $insurer_id = (!isset($insurer_id) || $insurer_id === '' || $insurer_id === null) ? 0 : $insurer_id;      
+        $policy_type_id = (!isset($policy_type_id) || $policy_type_id === '' || $policy_type_id === null) ? 0 : $policy_type_id;      
+        $date_type = (!isset($date_type) || $date_type === '' || $date_type === null) ? 0 : $date_type;      
+        $issuer = (!isset($issuer) || $issuer === '' || $issuer === null) ? 0 : $issuer;   
+
+
+
+        $data['finance_list'] = $this->policyTransactionModel->getFinanceReportList($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer);
+        $this->loadLayout('finance_team_list', $data); 
+    }
+
+
+    //---------------------------------------------------------------------------------------------------
+
+    //insurer statement list page
+    public function statementList()
+    {
+        // dd($this->validateInsurerStatement(['file_id' => 30]));
+         // $data['insurers'] = $this->insurerModel->where('is_active',1)->findAll();
+        $today = date('Y-m-d');
+        $fromday = $from_date = date('Y-m-d', strtotime('-60 days', strtotime($today)));
+        // echo $fromday;die();
+         $data['invoice_status_array'] = $this->invoiceStatus;
+         $data['insurers'] = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();
+
+         // dd( $data['insurers']);
+         $data['insurer_statement_list'] = $this->insurerStatements
+                                                ->select('insurer_statements.*, 
+                                                          insurers.name AS insurer_name, 
+                                                          insurers.short_name, 
+                                                          user_profiles.first_name, 
+                                                          insurer_branch.branch_code,
+                                                          (SELECT SUM(pt_co_share_details.exp_amt) 
+                                                           FROM pt_co_share_details 
+                                                           WHERE pt_co_share_details.is_active = 1 
+                                                             AND pt_co_share_details.statement_id = insurer_statements.id
+                                                          ) AS exp_inv_amt,
+                                                          (SELECT SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds) 
+                                                           FROM inv_payment_details 
+                                                           WHERE inv_payment_details.is_active = 1 
+                                                             AND inv_payment_details.statement_id = insurer_statements.id
+                                                          ) AS received_inv_amt'
+                                                )
+                                                ->join('insurers', 'insurer_statements.insurer_id = insurers.id')
+                                                ->join('insurer_branch', 'insurer_statements.branch_id = insurer_branch.id')
+                                                ->join('user_profiles', 'insurer_statements.created_by = user_profiles.id')
+                                                ->where('insurer_statements.is_active', 1)
+                                                ->where('date(insurer_statements.created_at) >= ', $from_date)
+                                                ->where('date(insurer_statements.created_at) <= ', $today)
+                                                ->orderBy('insurer_statements.id', 'DESC')
+                                                ->findAll();
+
+            // dd( $this->insurerStatements->getLastQuery());
+        $this->loadLayout('insurer_statement_list',  $data);
+    }
+
+    public function uploadInsurerStatement()
+    {
+
+            //validate uploaded file
+            $filename = '';
+            $validated = $this->validate([
+                'statement' => [
+                    'uploaded[statement]',
+                    'mime_in[statement,application/vnd.ms-excel,application/vnd,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.spreadsheet]',
+                    'max_size[statement,16384]',
+                ],
+            ]);
+            // $this->createStatementFolder();
+            if ($validated) 
+            {
+                    $avatar = $this->request->getFile('statement');
+                    if (!$avatar) {
+                        $this->myLogger->logme("error", 'Statement File not found');
+                        return $this->respond(['dataStatus' => false, 'code' => 400, 'message' => 'File not found'], 400);
+                    }
+
+                    $is_moved = $avatar->move(WRITEPATH . 'uploads/statements/');
+                    if ($is_moved) {
+                        $filename = $avatar->getName();
+                        // Handle successful upload, e.g., log success or further processing
+                        $this->myLogger->logme("error", 'Statement File moved successful');
+                        
+                    } else {
+                        $this->myLogger->logme("error", 'Statement File move failed');
+                        return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => 'File move failed'], 500);
+                    }
+            } else {
+                $this->myLogger->logme("error", 'Statement 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();
+            // dd($loggedInUserID);
+            // $loggedInUserID = 8;
+
+            $insurer = $this->request->getPost('insurer');
+
+            $insurer_id = explode('-', $insurer)[0];
+            $branch_id = explode('-', $insurer)[1];
+            // print_r($insurer_id);
+            // print_r($branch_id);
+            // die();
+            $month = $this->request->getPost('statement_month');
+            $month = $month.'-01';
+            // print_r($month);die;
+            $month = change_date_format($month,'Y-M-d','Y-m-d');
+            // print_r($month);die;
+
+            $file_id = $this->insurerStatements->insert(['insurer_id' => $insurer_id, 'branch_id' => $branch_id, 'file_name' => $filename,'month' => $month, 'created_by' => $loggedInUserID]); //here field policy_id have client_policy_id and not policy id from policy master
+            $this->myLogger->logme("error", '{file_id} statement uploaded success', ['file_id' => $file_id]);
+
+            //validate file
+            $validation_result = $this->validateInsurerStatement(['file_id' => $file_id]);
+            //update file content to DB
+            if($validation_result['status'] )
+            {
+                $this->updateInsurerStatement(['file_id' => $file_id]);
+            }
+           
+            if (!isset($file_id) || !$validation_result['status']) {
+                return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'file not uploaded', 'error_data' => $validation_result['error_data'],'error_code' =>   $validation_result['error_code']], 200);
+            }
+
+            return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => 'file upload success'], 200);
+    }
+
+    public function createStatementFolder()
+    {
+        $folderPath = WRITEPATH . 'uploads/statements/';
+
+        // Check if the folder doesn't exist
+        if (!file_exists($folderPath)) 
+        {
+            // Create the folder
+            if (mkdir($folderPath, 0777, true)) {
+               $this->myLogger->logme('error','statement upload folder created successfully');
+                
+                // Set permissions to a+rwx (read, write, execute for all)
+                chmod($folderPath, 0777);
+                $this->myLogger->logme('error','Permissions set to a+rwx.');
+            } else {
+                // echo "Failed to create folder.";
+                $this->myLogger->logme('error','Failed to create statement upload folder.');
+            }
+        } 
+        else 
+        {
+            $this->myLogger->logme('error','upload folder exists.');
+        }
+    }
+
+    public function validateInsurerStatement($params)
+    {
+        //get file info
+        $file_id = $params['file_id'];
+        $file = $this->insurerStatements->find($file_id);
+        // dd($file);
+        $date = new \DateTime($file['month']);
+        
+        $month = $date->format('m'); 
+        $year = $date->format('Y');
+
+        $error_data = ['error_code' => '','error_data' => []];
+        $status = 'success';
+        $ret_status = true;
+        // dd($month.'-'.$year);
+        $return = [];
+        if(!isset($file))
+        {
+            //file not found in DB
+            return array('status' => false, 'msg' => 'statement file not found in DB');
+        }
+        $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name'];
+        
+        //check physical file
+        if(!file_exists($file_name_with_path))
+        {
+            //file not found  update status and reason 
+            $message = "Physcial file not found";
+            // echo $message;
+            $this->myLogger->logme('error',($message . ' for statement file id ' . $file_id));
+            $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update();
+            return  array('status' => false, 'error_code' => 0); //0 - Physcial file not found
+        }
+
+        //get excel data to php array
+        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path);
+        $sheet = $spreadsheet->getActiveSheet();
+        
+        $highestRowAndColumn = $sheet->getHighestRowAndColumn();
+        // dd($highestRowAndColumn);
+        $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']);
+        unset($excel_data[0]);
+        // Kint::dump($excel_data);
+        //get no of line items and update in DB
+        $line_items = count($excel_data);
+        // get uploaded month transactions data
+        $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']);
+        // var_dump($source_data);die();
+        // Kint::dump($source_data);//die();
+       
+        // check policy no,insurer and etc in DB for this month
+        // if all good return true, otherwise return false with messssage 
+        foreach ($excel_data as $excel_key => $excel_row) 
+        {
+            $is_source_found = 0;
+            $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel
+            $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel
+            $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel
+            $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel
+            $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel
+           
+            foreach ($source_data as $source_key => $source_row) 
+            {
+                if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_row['endorsement_no']  && change_date_format($policy_start_date,'d/m/Y','Y-m-d') == $source_row['policy_start_date'] &&  change_date_format($policy_end_date,'d/m/Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name'])
+                {
+                    $is_source_found = 1;
+                    unset($source_data[$source_key]);
+                    continue 2;
+                }
+            }
+
+            if($is_source_found == 0)
+            {
+                // echo $excel_key.'-'.$excel_row[1] . '- not found
'; + $error_data['error_code'] = 1;//match not found + // $error_data['error_data'] = ($error_data['error_data'] ?? []); + $error_data['error_data'] = array_merge($error_data['error_data'],[$excel_row[0]]);//match not found + } + } + if($error_data['error_code']) + { + $status = 'failed'; + $ret_status = false; + } + //update in DB + $this->insurerStatements->where('id', $file_id)->set(['line_items' => $line_items,'file_status' => $status,'reason' => json_encode($error_data)])->update(); + return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']); + } + + + public function updateInsurerStatement($params) + { + //get file info + $file_id = $params['file_id']; + $file = $this->insurerStatements->find($file_id); + // dd($file); + $date = new \DateTime($file['month']); + + $month = $date->format('m'); + $year = $date->format('Y'); + + $error_data = ['error_code' => '','error_data' => []]; + $status = 'success'; + $ret_status = true; + // dd($month.'-'.$year); + $return = []; + if(!isset($file)) + { + //file not found in DB + return array('status' => false, 'msg' => 'statement file not found in DB'); + } + $file_name_with_path = WRITEPATH."/uploads/statements/".$file['file_name']; + + //check physical file + if(!file_exists($file_name_with_path)) + { + //file not found update status and reason + $message = "Physcial file not found"; + // echo $message; + $this->myLogger->logme('error',($message . ' for statement file id ' . $file_id)); + $this->insurerStatements->where('id', $file_id)->set(['file_status' => 'failed','reason' => json_encode(['error_code' => 0,'error_data' => $message])])->update(); + return array('status' => false, 'error_code' => 0); //0 - Physcial file not found + } + + //get excel data to php array + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); + $sheet = $spreadsheet->getActiveSheet(); + + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + // dd($highestRowAndColumn); + $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + unset($excel_data[0]); + // dd($excel_data); + //get no of line items and update in DB + $line_items = count($excel_data); + // get uploaded month transactions data + $source_data = $this->PTCOShareDetailsModel->getNonReconcileredPolicyTransactions(month:$month,year:$year,insurer_id:$file['insurer_id'],insurer_branch_id:$file['branch_id']); + // Kint::dump($source_data);die; + // Kint::dump($excel_data); + + // check policy no,insurer and etc in DB for this month + // if all good return true, otherwise return false with messssage + $data_to_update = []; + foreach ($excel_data as $excel_key => $excel_row) + { + $is_source_found = 0; + $policy_start_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[4]);//policy_start_date from excel + $policy_end_date = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[5]);//policy_end_date from excel + $policy_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[1]);//policy_end_date from excel + $client_name = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[3]);//clientname from excel + $endorsement_no = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $excel_row[2]);//policy_end_date from excel + + foreach ($source_data as $source_key => $source_row) + { + // Kint::dump(change_date_format($excel_row[3],'d/m/Y','Y-m-d')); + if( ($policy_no == $source_row['policy_no']) && $endorsement_no == $source_row['endorsement_no'] && change_date_format($policy_start_date,'d/m/Y','Y-m-d') == $source_row['policy_start_date'] && change_date_format($policy_end_date,'d/m/Y','Y-m-d') == $source_row['policy_end_date'] && $client_name == $source_row['client_name']) + { + $is_source_found = 1; + + //calculate percentage first + $total_amt = 0; + + $actual_bp_per = trim($excel_row[9]); + $actual_bp_brokerage = trim($excel_row[12]); + $actual_bp_amt = trim($excel_row[6]); + + if(($actual_bp_brokerage && $actual_bp_brokerage != 0 && $actual_bp_brokerage != "")) + { + $total_amt += $actual_bp_brokerage; + //percentage reverse calculation + if($actual_bp_per == 0 || $actual_bp_per == "") + { + $actual_bp_per = round(($actual_bp_brokerage / $actual_bp_amt) * 100,2); + } + + } + else + { + $actual_bp_brokerage = $actual_bp_amt * ($actual_bp_per / 100); + $total_amt += $actual_bp_brokerage; + } + + $actual_tp_per = trim($excel_row[10]); + $actual_tp_brokerage = trim($excel_row[13]); + $actual_tp_amt = trim($excel_row[7]); + + if($actual_tp_brokerage && $actual_tp_brokerage != 0 && $actual_tp_brokerage != "") + { + $total_amt += $actual_tp_brokerage; + //percentage reverse calculation + if($actual_tp_per == 0 || $actual_tp_per == "") + { + $actual_tp_per = ($actual_tp_brokerage / $actual_tp_amt) * 100; + } + } + else + { + $actual_tp_brokerage = $actual_tp_amt * ($actual_tp_per / 100); + $total_amt += $actual_tp_brokerage; + } + + $actual_tep_per = trim($excel_row[11]); + $actual_tep_brokerage = trim($excel_row[14]); + $actual_tep_amt = trim($excel_row[8]); + + if($actual_tep_brokerage && $actual_tep_brokerage != 0 && $actual_tep_brokerage != "") + { + $total_amt += $actual_tep_brokerage; + //percentage reverse calculation + if($actual_tep_per == 0 || $actual_tep_per == "") + { + $actual_tep_per = ($actual_tep_brokerage / $actual_tep_amt) * 100; + } + } + else + { + $actual_tep_brokerage = $actual_tep_amt * ($actual_tep_per / 100); + $total_amt += $actual_tep_brokerage; + } + + //find variance + $variance_amt = $source_row['exp_amt'] - $total_amt; + + $data_to_update[] = ['id' => $source_row['id'],'actual_bp_amt' => $actual_bp_amt,'actual_tp_amt' => $actual_tp_amt,'actual_tep_amt' => $actual_tep_amt,'actual_bp_per' => $actual_bp_per,'actual_tp_per' => $actual_tp_per,'actual_tep_per' => $actual_tep_per,'variance' => $variance_amt,'actual_tep_brokerage_amt' => $actual_tep_brokerage,'actual_tp_brokerage_amt' => $actual_tp_brokerage,'actual_bp_brokerage_amt' => $actual_bp_brokerage,'reward' => trim($excel_row[15]),'statement_id' => $file_id]; + + unset($source_data[$source_key]); + continue 2; + } + } + } + $this->PTCOShareDetailsModel->updateBatch($data_to_update, 'id'); + // dd($data_to_update); + // if($error_data['error_code']) + // { + // $status = 'failed'; + // $ret_status = false; + // } + //update in DB + $this->insurerStatements->where('id', $file_id)->set(['file_status' => $status,'reason' => json_encode($error_data),'invoice_status' =>'pending'])->update(); + return array('status' => $ret_status, 'error_code' => $error_data['error_code'],'error_data' => $error_data['error_data']); + } + + public function getInvoicePaymentDetails() + { + $statement_id = $this->request->getUri()->getSegment(4); + + $inv_details = $this->insurerStatements->find($statement_id); + $inv_payment_details = $this->invPaymentDetailsModel + ->where('statement_id',$statement_id) + ->where('is_active',1) + ->get() + ->getResultArray(); + // ~dd($inv_details); + $data = [ 'invoice_status' => $inv_details['invoice_status'], + 'invoice_no' => $inv_details['invoice_no'], + 'invoice_amount' => $inv_details['invoice_amount'], + 'invoice_date' => isset($inv_details['invoice_date']) ? change_date_format($inv_details['invoice_date'],'Y-m-d','d/m/Y') : null ]; + $data['payments'] = $inv_payment_details; + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $data], 200); + + + } + + public function saveInvoicePaymentDetails() + { + $jsonData = $this->request->getJSON(); + $jsonData = (array)$jsonData; + // echo 'Hi'; + // print_r($jsonData);die(); + + $invoiceStatus = $jsonData['invoice_status']; + $hiddenStatementId = $jsonData['hidden_statement_id']; + $invoiceNo = $jsonData['invoice_no']; + $invoiceDate = change_date_format($jsonData['invoice_date'],'d/m/Y','Y-m-d'); + $invoice_amount = $jsonData['invoice_amount']; + + //Update statement table + $parentData = [ + 'invoice_status' => $invoiceStatus, + 'invoice_no' => $invoiceNo, + 'invoice_date' => $invoiceDate, + 'invoice_amount' => $invoice_amount, + 'updated_by' => get_session_userid() + ]; + + + + $this->insurerStatements->update($hiddenStatementId, $parentData); + + // Process child data + $receivedAmounts = $jsonData['received_amount']; + $utrNos = $jsonData['utr_no']; + $tdsTotal = $jsonData['tds']; + $paymentDates = $jsonData['payment_date']; + $pks = $jsonData['pk']; + + foreach ($receivedAmounts as $index => $receivedAmount) { + $pk = $pks[$index]; // Get the pk for the current record + $utrNo = $utrNos[$index]; + $tds = $tdsTotal[$index]; + $paymentDate = $paymentDates[$index]; + + // Prepare data for insert/update + $childData = [ + 'inv_amt' => $receivedAmount, + 'utr_no' => $utrNo, + 'tds' => $tds, + 'received_date' => change_date_format($paymentDate,'d/m/Y','Y-m-d'), + 'statement_id' => $hiddenStatementId + ]; + if($pk){ + $childData['updated_by'] = get_session_userid(); + $childData['id'] = (int)$pk; + } + else { $childData['created_by'] = get_session_userid(); } + // print_r($childData); + // Insert or update + $this->invPaymentDetailsModel->save($childData); + // print_r($this->invPaymentDetailsModel->errors()); + + } + + return $this->respond(['dataStatus' => true, 'code' => 200], 200); + //return $this->response->setJSON(['dataStatus' => 'true']); + } + + public function deletePaymentEntry() + { + $payment_id = $this->request->getUri()->getSegment(4); + //echo $payment_id; + $this->invPaymentDetailsModel->update($payment_id, ['is_active' => 0]); + return $this->respond(['dataStatus' => true, 'code' => 200], 200); + } + + public function downloadSampleInsurerStatement() + { + + $filePath = ROOTPATH . 'public/sample_excel/insurer_stament_sample.xlsx'; + // 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'); + } + } + + public function getFileErr() + { + $file_id = $this->request->getUri()->getSegment(4); + $file = $this->insurerStatements->find($file_id); + return $this->respond(['dataStatus' => true, 'code' => 200,'data' => $file['reason']], 200); + } + + public function dmsSearch() + { + // echo 'scbsc';die(); + if ($this->request->getMethod() == 'post') + { + // $jsonData = (array)$this->request->getJSON(); + $customer_id = $this->request->getPost('customer_id'); + $policy_id = $this->request->getPost('policy_id'); + $cus_doc_name = $this->request->getPost('cus_doc_name'); + $policy_doc_name = $this->request->getPost('policy_doc_name'); + $pt_files = []; + $kyc_files = []; + // print_r($jsonData);die(); + if($policy_id != "") + { + //get policy docs from policy transation related tables + $pt_files = $this->PTFileModel->getPolicyDriveFilesIndex($policy_id,$policy_doc_name); + // ~dd($this->PTFileModel->getLastQuery()); + // ~dd($pt_files); + } + if($customer_id != "") + { + $kyc_files = $this->clientKYCDocsModel->getClientKYCDriveFilesIndex($customer_id,$cus_doc_name); + // dd($this->clientKYCDocsModel->getLastQuery()); + // !dd($kyc_files); + } + + $data['files'] = array_merge($pt_files,$kyc_files); + // dd($data['files']); + } + + + $data['customers'] = $this->clientModel->select('id,client_name,short_name as display_value')->where('is_active',1)->get()->getResultarray(); + $data['policies'] = $this->clientPolicyModel->select("client_policy.id,client_policy.policy_no,policy_type.policy_type,concat(policy_type.policy_type,' - ',client_policy.policy_no) as display_value") + ->join('policy_type','client_policy.policy_type_id = policy_type.id') + ->where('client_policy.is_active',1)->get()->getResultarray(); + // dd($data); + $this->loadLayout('dms_search', $data); + + + } + + +} \ No newline at end of file diff --git a/app/Controllers/PublicController.php b/app/Controllers/PublicController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/RestAuthenticationController.php b/app/Controllers/RestAuthenticationController.php old mode 100644 new mode 100755 index b313789e..d4256270 --- a/app/Controllers/RestAuthenticationController.php +++ b/app/Controllers/RestAuthenticationController.php @@ -71,7 +71,9 @@ class RestAuthenticationController extends AdminController $mobile_number = $this->request->getJSON()->mobile_number; - $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first(); + $employeeData = $this->employeeModel->where('mobile', $mobile_number) + ->where('relationship', 'self') + ->where('is_active', 1)->first(); if ($employeeData) { @@ -126,7 +128,9 @@ class RestAuthenticationController extends AdminController try { $mobile_number = $this->request->getJSON()->mobile_number; - $HrData = $this->hrModel->where('mobile', $mobile_number)->where('contact_type', 'client')->first(); + $HrData = $this->hrModel->where('mobile', $mobile_number) + ->where('contact_type', 'client') + ->where('is_active', 1)->first(); if ($HrData) { diff --git a/app/Controllers/SwaggerController.php b/app/Controllers/SwaggerController.php old mode 100644 new mode 100755 diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php old mode 100644 new mode 100755 index 53d35bf1..8d68fc1a --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -64,17 +64,28 @@ class UserController extends AdminController if ($insert) { + $teamData['user_id'] = $insert; + foreach ($teams as $value) { + $teamData['team_id'] = $value; + $teamData['created_by'] = get_session_userid(); + $this->userTeamsModel->insert($teamData); + } + if ($userData['role'] == 3) { $db = \Config\Database::connect(); $tableName = 'hdz_staff'; - $admin = 1; + $admin = 0; + $acm = 1; + $acm_id = $insert; $password = '12345678'; //Default password $hashedPassword = password_hash($password, PASSWORD_DEFAULT); foreach ($temp_team as $key => $value) { + $team = $this->teamModel->where('id', $value)->first(); + if ($team['name'] == 'Claims') { $hdz_staff = [ 'emp_code' => $userData['emp_code'], @@ -82,6 +93,8 @@ class UserController extends AdminController 'username' => strtolower($userData['first_name']), 'email' => $userData['email'], 'admin' => $admin, + 'acm' => $acm, + 'acm_id' => $acm_id, 'registration' => time(), 'password' => $hashedPassword, 'active' => 1, @@ -90,13 +103,6 @@ class UserController extends AdminController $db->table($tableName)->insert($hdz_staff); } } - - $teamData['user_id'] = $insert; - foreach ($teams as $value) { - $teamData['team_id'] = $value; - $teamData['created_by'] = get_session_userid(); - $this->userTeamsModel->insert($teamData); - } } } } @@ -117,12 +123,12 @@ class UserController extends AdminController public function edit() { - $teams = $this->request->getPost('team'); if (!$this->request->getPost()) { return redirect()->to(base_url('/user/list')); } else { $id = $this->request->getPost('PrimaryKey'); + $teams = $this->request->getPost('team'); $userData = $this->request->getPost(); unset($userData['csrf_test_name']); unset($userData['PrimaryKey']); @@ -133,6 +139,16 @@ class UserController extends AdminController if ($update) { + if ($teams) { + $this->userTeamsModel->where('user_id', $id)->delete(); + $teamData['user_id'] = $id; + foreach ($teams as $value) { + $teamData['team_id'] = $value; + $teamData['created_by'] = get_session_userid(); + $this->userTeamsModel->insert($teamData); + } + } + if ($userData['role'] == 3) { $db = \Config\Database::connect(); @@ -152,7 +168,6 @@ class UserController extends AdminController 'active' => 1, ]; - $db->table($tableName)->where('emp_code', $userData['emp_code']) ->where('email', $userData['email']) ->set($hdz_staff) @@ -160,16 +175,6 @@ class UserController extends AdminController } } - $this->userTeamsModel->where('user_id', $id)->delete(); - - if ($teams) { - $teamData['user_id'] = $id; - foreach ($teams as $value) { - $teamData['team_id'] = $value; - $teamData['created_by'] = get_session_userid(); - $this->userTeamsModel->insert($teamData); - } - } } } @@ -201,4 +206,4 @@ class UserController extends AdminController $teamData = $this->teamModel->select('id, name')->findAll(); echo json_encode(array("status" => true , 'roleData' => $roleData, 'teamData' => $teamData,)); } -} +} \ No newline at end of file diff --git a/app/Database/Migrations/.gitkeep b/app/Database/Migrations/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Database/Seeds/.gitkeep b/app/Database/Seeds/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Filters/.gitkeep b/app/Filters/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Filters/AuthJWT.php b/app/Filters/AuthJWT.php old mode 100644 new mode 100755 diff --git a/app/Filters/AuthMVC.php b/app/Filters/AuthMVC.php old mode 100644 new mode 100755 diff --git a/app/Filters/CloseDbConnection.php b/app/Filters/CloseDbConnection.php old mode 100644 new mode 100755 diff --git a/app/Filters/HttpRequestLog.php b/app/Filters/HttpRequestLog.php old mode 100644 new mode 100755 diff --git a/app/Filters/RoleCheck.php b/app/Filters/RoleCheck.php old mode 100644 new mode 100755 diff --git a/app/Helpers/.gitkeep b/app/Helpers/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Helpers/DepositHelper.php b/app/Helpers/DepositHelper.php old mode 100644 new mode 100755 index 5d45709e..aa5950f0 --- a/app/Helpers/DepositHelper.php +++ b/app/Helpers/DepositHelper.php @@ -50,13 +50,13 @@ class DepositHelper 'amount' => $data['amount'], 'sub_type' => $data['sub_type_id'], 'client_id' => $data['client_id'], - 'client_policy_id' => $data['client_policy_id'], + 'client_policy_id' => $data['client_policy_id'] ?? 0, 'cd_ac_no' => $data['cd_ac_no'], 'endorsement_no' => $data['endorsement_no'], 'insurer_id' => $data['insurer_id'], 'unit' => $data['unit'] ?? null, - 'description' => $data['description'], - 'event_name' => $data['event_name'], + 'description' => $data['description'] ?? null, + 'event_name' => $data['event_name'] ?? null, 'transaction_type' => $data['transaction_type'], 'is_active' => 1, 'created_by' => $loggedInUserID, @@ -99,17 +99,17 @@ class DepositHelper $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; $getLastBalanceParams = [$cd_ac_no]; - $lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? null; + $lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0; - if(empty($lastBalance) && $lastBalance == null){ + // if(empty($lastBalance) && $lastBalance == null){ - $cd_model = new ClientDepositModel(); + // $cd_model = new ClientDepositModel(); - $getLastBalanceQuery = "SELECT opening_bal FROM cd_master WHERE client_id = ? AND insurer_id = ? AND cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; - $getLastBalanceParams = [$clientId, $insurerId, $cd_ac_no]; + // $getLastBalanceQuery = "SELECT opening_bal FROM cd_master WHERE client_id = ? AND insurer_id = ? AND cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1"; + // $getLastBalanceParams = [$clientId, $insurerId, $cd_ac_no]; - $lastBalance = $cd_model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->opening_bal ?? 0; - } + // $lastBalance = $cd_model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->opening_bal ?? 0; + // } return $lastBalance; } diff --git a/app/Helpers/HttpRequestHelper.php b/app/Helpers/HttpRequestHelper.php old mode 100644 new mode 100755 diff --git a/app/Helpers/JWTToken.php b/app/Helpers/JWTToken.php old mode 100644 new mode 100755 diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php old mode 100644 new mode 100755 index 7b1a9bc7..2eb86cf1 --- a/app/Helpers/MailHelper.php +++ b/app/Helpers/MailHelper.php @@ -14,7 +14,7 @@ use App\Models\JobModel; class MailHelper { - public static function send_email($params) + public static function send_email_smtp($params) { // print_r($params);die; @@ -63,7 +63,7 @@ class MailHelper } } - public static function bulk_mail(array $mails = []) + public static function bulk_mail_smtp(array $mails = []) { // print_r();die; $model = new JobModel(); @@ -82,5 +82,69 @@ class MailHelper } } + //using GmailAPI + public static function send_email($params) + { + + // print_r($params);die; + $myLogger = \Config\Services::mylogger(); + $gmailapi = \Config\Services::gmailapi(); + + $emaill = $params['mail']; + $subject = $params['subject']; + $message = $params['message']; + if (isset($params['bcc'])) { + $bcc = $params['bcc']; + }else{ + $bcc = []; + } + + if (isset($params['cc'])) { + $cc = $params['cc']; + }else{ + $cc = []; + } + try { + + + $res = $gmailapi->sendMessage($emaill, $subject, $message, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc, $bcc); + + if($res['status']) + { + return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200); + } + else + { + $myLogger->logme('error', "mail sent failed - $emaill"); + return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res ],404); + } + + } catch (Exception $e) { + $msg = $e->getMessage(); + $myLogger->logme('error', "mail sent failed - $msg"); + return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500); + } + } + + + public static function bulk_mail(array $mails = []) + { + // print_r();die; + $model = new JobModel(); + $start = microtime(true); + $runtime= 0; + try { + foreach ( $mails as $index=>$mail) { + $runtime = microtime(true) - $start; + $send_mail = self::send_email($mail); + } + + return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200); + + } catch (\Throwable $th) { + return json_encode(['status' => 'failed','code' => 500],500); + } + } + } ?> \ No newline at end of file diff --git a/app/Helpers/drive_helper.php b/app/Helpers/drive_helper.php new file mode 100644 index 00000000..81bd5d22 --- /dev/null +++ b/app/Helpers/drive_helper.php @@ -0,0 +1,150 @@ +get('access_token'); + log_message('error', '////////////// --- G-Drive Access Token {data}', ['data' => $accessToken]); + + // Initialize Google Client + $client = new GoogleClient(); + $client->setApplicationName($appName); + $client->setClientId($clientID); + $client->setClientSecret($clientSecret); + $client->setRedirectUri($redirectUri); + $client->addScope($scopes); + // $client->setApprovalPrompt('force'); + $client->setPrompt('consent'); + $client->setAccessType('offline'); + + + if ($accessToken) { + + $client->setAccessToken($accessToken); + log_message('error', '////////////// --- G-Drive Access Token expired : {data}', ['data' => $client->isAccessTokenExpired()]); + + if ($client->isAccessTokenExpired()) { + + $refreshToken = session()->get('refresh_token'); + log_message('error', '////////////// --- G-Drive Refresh Token : {data}', ['data' => $refreshToken]); + + if ($refreshToken) { + $client->fetchAccessTokenWithRefreshToken($refreshToken); + $token = $client->getAccessToken(); + + if (isset($token['access_token'])) { + session()->set('access_token', $token['access_token']); + // $client->setAccessToken($token); + log_message('error', '////////////// --- G-Drive Access Token refreshed and stored successfully.'); + } else { + log_message('error', '////////////// --- G-Drive Access Token not available after refresh.'); + } + + if (isset($token['refresh_token'])) { + session()->set('refresh_token', $token['refresh_token']); + log_message('error', '////////////// --- G-Drive Refresh Token updated successfully.'); + } else { + log_message('error', '////////////// --- G-Drive Refresh Token not available after refresh.'); + } + + } else { + log_message('error', '////////////// --- G-Drive Refresh Token Not Available'); + redirect()->to(filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL)); + } + } else { + log_message('error', '////////////// --- G-Drive Access Token is still valid.'); + } + + + try { + + $driveService = new Drive($client); + $folderName = 'New Folder'; + + // Check if the folder already exists + $response = $driveService->files->listFiles([ + 'q' => "mimeType='application/vnd.google-apps.folder' and name='{$folderName}' and trashed=false", + 'fields' => 'files(id, name)' + ]); + + $filesList = $response->getFiles(); + $folderId = null; + + if (count($filesList) > 0) { + // Folder already exists + $folderId = $filesList[0]->getId(); + } else { + // Create a new folder + $folder = new Drive\DriveFile(); + $folder->setName($folderName); + $folder->setMimeType('application/vnd.google-apps.folder'); + + $createdFolder = $driveService->files->create($folder, [ + 'fields' => 'id' + ]); + + $folderId = $createdFolder->id; + } + + $uploadedFiles = []; + + foreach ($files as $key => $file) { + + if (!empty($file)) { + + $dname = $doc_name[$key]; + + $driveFile = new Drive\DriveFile(); + $driveFile->setName($file->getClientName()); + $driveFile->setParents([$folderId]); + + $result = $driveService->files->create( + $driveFile, + [ + 'data' => file_get_contents($file->getTempName()), + 'mimeType' => $file->getClientMimeType(), + 'uploadType' => 'multipart' + ] + ); + + $uploadedFiles[] = [ + 'file_name' => $file->getClientName(), + 'drive_id' => $result->id, + 'doc_name' => $dname, + 'pt_id' => $pt_id, + 'created_by' => get_session_userid(), + 'url' => "https://drive.google.com/file/d/{$result->id}/view", + ]; + } + } + + return $uploadedFiles; + + } catch (\Exception $e) { + + $errorDetails = [ + 'status' => 'error', + 'error_message' => 'Error uploading files: ' . $e->getMessage(), + 'error_code' => $e->getCode(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'stack_trace' => $e->getTraceAsString() + ]; + + return $errorDetails; + } + } else { + + $url = $client->createAuthUrl(); + return redirect()->to(filter_var($url, FILTER_SANITIZE_URL)); + } + } +} \ No newline at end of file diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php old mode 100644 new mode 100755 diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php old mode 100644 new mode 100755 index 3f07ed82..90c1c64e --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -234,7 +234,7 @@ if(!function_exists('check_si')) $is_si_found = false; $is_age_slab_found = false; - if($policy_details['policy_type_id'] == 1 && $slab_details[0]['policy_grid_id'] == 1 && $slab_details[0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay + if($policy_details['policy_type_id'] == 1 && $slab_details['slab_rates'][0]['policy_grid_id'] == 1 && $slab_details['slab_rates'][0]['si_or_bp'] == 2) // GPA && grid type 1 for GPA && sub type is basic pay { $is_si_found = true; $is_age_slab_found = true; @@ -924,7 +924,19 @@ if (!function_exists('calculate_premium_new')) $is_self_acting_self_set = true; } - $family_data[$val]['temp'] = ['max_age' => max($applicable_members_from_familiy['max_age']),'max_count' => $applicable_members_from_familiy['max_count'],'grid_name' => $key,'grid_master' => $slab['grid_master'],'acting_self' => $acting_self,'premium_type' => $slab['slab_rates'][0]['premium_type']]; + //$family_data[$val]['temp'] = ['max_age' => max($applicable_members_from_familiy['max_age']),'max_count' => $applicable_members_from_familiy['max_count'],'grid_name' => $key,'grid_master' => $slab['grid_master'],'acting_self' => $acting_self,'premium_type' => $slab['slab_rates'][0]['premium_type']]; + $family_data[$val]['temp'] = array_merge( + $family_data[$val]['temp'] ?? [], // existing 'temp' data or an empty array if it doesn't exist + [ + 'max_age' => max($applicable_members_from_familiy['max_age']), + 'max_count' => $applicable_members_from_familiy['max_count'], + 'grid_name' => $key, + 'grid_master' => $slab['grid_master'], + 'acting_self' => $acting_self, + 'premium_type' => $slab['slab_rates'][0]['premium_type'] + ] + ); + } } else @@ -999,7 +1011,6 @@ if (!function_exists('transform_excel_data_to_db')) { function transform_excel_data_to_db($memArr,$actionArr) { - $current_column_action = null; if($actionArr['action'] == 'inception'){ $current_column_action = 'I'; } else if($actionArr['action'] == 'addition'){ $current_column_action = 'A'; } @@ -1570,7 +1581,7 @@ if(!function_exists('get_emp_records_from_audit_history')) function get_emp_records_from_audit_history($employee_id) { $db = db_connect(); - $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM venbaehn_nhance.auditing_history where pk = $employee_id and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc"; + $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $employee_id and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc"; $res = $db->query($query); // echo $db->getLastQuery(); $res = $res->getResultArray(); @@ -1592,7 +1603,7 @@ if(!function_exists('get_emp_policy_records_from_audit_history')) function get_emp_policy_records_from_audit_history($emp_policy_id) { $db = db_connect(); - $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM venbaehn_nhance.auditing_history where pk = $emp_policy_id and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc"; + $query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $emp_policy_id and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc"; $res = $db->query($query); // echo $db->getLastQuery(); $res = $res->getResultArray(); diff --git a/app/Helpers/fileupload_helper.php b/app/Helpers/fileupload_helper.php old mode 100644 new mode 100755 diff --git a/app/Helpers/header.php b/app/Helpers/header.php old mode 100644 new mode 100755 diff --git a/app/Helpers/oauth_helper.php b/app/Helpers/oauth_helper.php old mode 100644 new mode 100755 index 6741f057..a16ef368 --- a/app/Helpers/oauth_helper.php +++ b/app/Helpers/oauth_helper.php @@ -27,13 +27,21 @@ if (!function_exists('googleOauthLogin')) { $client->setClientSecret($clientSecret); $client->setRedirectUri($redirectUri); $client->addScope($scopesArray); + // $client->setApprovalPrompt('force'); + $client->setPrompt('consent'); + $client->setAccessType('offline'); // Check if an OAuth token is provided if ($oauthToken) { try { // Attempt to fetch the access token with the provided OAuth token $token = $client->fetchAccessTokenWithAuthCode($oauthToken); + session()->set('access_token', $token['access_token']); + if(isset($token['refresh_token'])){ + session()->set('refresh_token', $token['refresh_token']); + } $client->setAccessToken($token); + $oauth = new Oauth2($client); // Get user information using the OAuth2 service diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php old mode 100644 new mode 100755 index 7b8fc5c8..311ccd47 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -105,9 +105,9 @@ class sendMailNotification $wholeData = []; } return $wholeData; - // }else{ - // return "false"; - // } + // }else{ + // return "false"; + // } } else if($action == 'member_ecard_mail'){ $notification = $params['notification']; @@ -160,7 +160,7 @@ class sendMailNotification $client_data =$clientModel->where('id', $client_id)->first(); $notification_data = $notificationModel->where('client_id' ,$client_id)->where('template_name', $action)->first(); - if ($notification_data['enabled'] == 1) { + if (isset($notification_data) && $notification_data['enabled'] == 1) { $mail_content = $notification_data['mail_content']; $subject = $notification_data['subject']; $app_link = $_ENV['App_Url']; @@ -259,7 +259,7 @@ class sendMailNotification $client_data =$clientModel->where('id', $client_id)->first(); $notification_data = $notificationModel->where('client_id' ,$client_id)->where('template_name', $action)->first(); - if ($notification_data['enabled'] == 1) { + if (isset($notification_data) && $notification_data['enabled'] == 1) { $client_rm_data= $clientRMModel->where('client_id', $client_id)->where('is_active',1)->findAll(); $user_list= []; foreach ($client_rm_data as $key => $value) { @@ -376,7 +376,7 @@ class sendMailNotification $notification_data = $notificationModel->where('client_id' ,$client_id)->where('template_name', $action)->first(); $clientRMModel =new ClientRMModel(); - if ($notification_data['enabled'] == 1) { + if (isset($notification_data['enabled']) && $notification_data['enabled'] == 1) { $client_rm_data= $clientRMModel->where('client_id', $client_id)->where('is_active',1)->findAll(); $user_list= []; foreach ($client_rm_data as $key => $value) { diff --git a/app/Helpers/session_helper.php b/app/Helpers/session_helper.php old mode 100644 new mode 100755 index 92f443d2..4a13df4d --- a/app/Helpers/session_helper.php +++ b/app/Helpers/session_helper.php @@ -140,6 +140,15 @@ if (!function_exists('get_session_context')) { } } +if (!function_exists('user_team')) { + function user_team() + { + // $CI =& get_instance(); + $session = \Config\Services::session(); + return $session->get('user_team'); + } +} + diff --git a/app/Helpers/utility_helper.php b/app/Helpers/utility_helper.php old mode 100644 new mode 100755 index da3f5f4c..e0e8ef06 --- a/app/Helpers/utility_helper.php +++ b/app/Helpers/utility_helper.php @@ -1,4 +1,10 @@ format($output_format); @@ -65,8 +73,6 @@ if (!function_exists('file_unlink')) { } } - - if (!function_exists('compressImage')) { function compressImage($file, $destinationPath, $newWidth = 100, $newHeight = 100) { @@ -82,9 +88,7 @@ if (!function_exists('compressImage')) { } } - -if (!function_exists('fancy_date_time_format')) -{ +if (!function_exists('fancy_date_time_format')) { function fancy_date_time_format($datetime,$return_type = 'fancy') { date_default_timezone_set('Asia/Kolkata'); @@ -118,9 +122,7 @@ if (!function_exists('fancy_date_time_format')) } - -if(!function_exists('check_string_date')) -{ +if(!function_exists('check_string_date')){ function check_string_date($str) { if (DateTime::createFromFormat('Y-m-d H:i:s', $str) !== false) { @@ -130,8 +132,6 @@ if(!function_exists('check_string_date')) } } - - if (!function_exists('generate_download_link')) { function generate_download_link($rand_string) { @@ -145,8 +145,6 @@ if (!function_exists('generate_download_link')) { } } - - if (!function_exists('generate_random_alphanumeric')) { function generate_random_alphanumeric($length = 6) { $random_string = ''; @@ -165,8 +163,6 @@ if (!function_exists('generate_random_alphanumeric')) { } } - - if (!function_exists('get_base64_image')) { function get_base64_image($path) @@ -184,7 +180,6 @@ if (!function_exists('get_base64_image')) { } } - if (!function_exists('format_indian_number')) { function format_indian_number($number) { // Round the number to two decimal places @@ -218,7 +213,6 @@ if (!function_exists('format_indian_number')) { } } - if (!function_exists('get_username')) { function get_username($user_id) { // Connect to the database @@ -238,7 +232,6 @@ if (!function_exists('get_username')) { } } - if (!function_exists('get_role_id')) { function get_role_id() { @@ -247,6 +240,143 @@ if (!function_exists('get_role_id')) { } } +if (!function_exists('teams')) { + function teams() { + // Load the UserTeamsModel + $teamModel = new \App\Models\UserTeamsModel(); + // Get the user ID from the session + $user_id = get_session_userid(); + + // Fetch the team IDs associated with the user + $user_teams = $teamModel->select('team_id')->where('user_id', $user_id)->findAll(); + + // Debugging: Log or print the query result to check its structure + // var_dump($user_teams); // You can use this temporarily for testing + // log_message('info', 'User Teams: ' . json_encode($user_teams)); // Optionally log it + + // Check if the result is not empty + if (!empty($user_teams)) { + // Extract only the 'team_id' values + $team_ids = array_column($user_teams, 'team_id'); + return $team_ids; // Return array of team IDs + } else { + return []; // Return empty array if no teams found + } + } +} + + + +if (!function_exists('generate_client_code')) { + function generate_client_code($string = 'GC') { + + $clientModel = new \App\Models\ClientModel(); + + $latestClient = $clientModel->select('id')->orderBy('id', 'DESC')->first(); + $id = $latestClient ? $latestClient['id'] : 0; + + $year = date('y'); + + $newId = $id + 1; + + $client_code = $year . $string . $newId; + + return $client_code; + } +} + +if (!function_exists('generate_tsi_code')) { + function generate_tsi_code($type) { + + $PolicyTransactionModel = new \App\Models\PolicyTransactionModel(); + + $latestClient = $PolicyTransactionModel->select('id')->orderBy('id', 'DESC')->first(); + $id = $latestClient ? $latestClient['id'] : 0; + + $year = date('y'); + $month = date('m'); + $string = 'P'; + + if($type == 2){ + $string2 = 'R'; + }else{ + $string2 = 'F'; + } + + $newId = $id + 1; + + $tsi_code = $string2 . $month . $year . $string . $newId; + + return $tsi_code; + } +} + +if (!function_exists('generateRandomCode')) { + function generateRandomCode($prefix = 'RTL-', $length = 6) { + // Generate a random number with the specified length + $randomNumber = str_pad(mt_rand(0, pow(10, $length)-1), $length, '0', STR_PAD_LEFT); + + // Return the code with the prefix + return $prefix . $randomNumber; + } +} + +if (!function_exists('excelFileGDriveUpload')) { + + function excelFileGDriveUpload($file_id, $table_name) { + $doc_type = "UPLOADS"; + $uploadFilePath = WRITEPATH . 'uploads/' . ($table_name == 'batch_file' ? 'import_excel' : 'excel'); + + $models = [ + 'batch_file' => [ + 'model' => new BatchFileModel(), + 'select' => "client_id, client_policy_id, file_name" + ], + 'files' => [ + 'model' => new FileModel(), + 'select' => "client_id, policy_id as client_policy_id, file_name" + ], + ]; + + if (!array_key_exists($table_name, $models)) { + return; + } + + // Retrieve data + $data = $models[$table_name]['model'] + ->select($models[$table_name]['select']) + ->where('id', $file_id) + ->where('is_active', 1) + ->first(); + + + + if ($data) { + $uploadFilePath .= '/' . $data['file_name']; + // dd($data, $uploadFilePath); + + $GoogleDriveController = new GoogleDriveController(); + $result = $GoogleDriveController->uploadFiletoGdrive( + // client_id : $data['client_id'], + client_policy_id: $data['client_policy_id'], + doc_type : $doc_type, + file_path : $uploadFilePath, + file_name : $data['file_name'] + ); + + // dd($result); + + return true; + + }else{ + + return false; + } + } +} + + + function numberToWords($number) { diff --git a/app/Helpers/uuid_helper.php b/app/Helpers/uuid_helper.php old mode 100644 new mode 100755 diff --git a/app/Language/.gitkeep b/app/Language/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Language/en/Validation.php b/app/Language/en/Validation.php old mode 100644 new mode 100755 diff --git a/app/Libraries/.gitkeep b/app/Libraries/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Libraries/DataServiceSqlite.php b/app/Libraries/DataServiceSqlite.php old mode 100644 new mode 100755 diff --git a/app/Libraries/GmailAPI.php b/app/Libraries/GmailAPI.php new file mode 100755 index 00000000..f08a832e --- /dev/null +++ b/app/Libraries/GmailAPI.php @@ -0,0 +1,180 @@ +myLogger = \Config\Services::mylogger(); + $this->client = new Client(); + $this->client->setApplicationName('Nhance GmailAPI'); + $this->client->setScopes([ + 'https://www.googleapis.com/auth/gmail.addons.current.message.readonly', + 'https://www.googleapis.com/auth/gmail.readonly', + 'https://www.googleapis.com/auth/gmail.labels', + 'https://www.googleapis.com/auth/gmail.send' + ]); + $this->setAuthConfig(); + //die(); + $this->client->setAccessType('offline'); + $this->client->setPrompt('select_account consent'); + + if (php_sapi_name() !== 'cli' || (uri_string() == 'cli/send_mail_cli' || uri_string() == 'cli/processjob') ) + { + $this->setTokenFromDB(); // Call only if not in CLI + } + + $this->service = new Gmail($this->client); + + } + + protected function setAuthConfig() + { + $settingsModel = new SettingsModel(); + $credentials = $settingsModel->where('id', 1)->first(); + + if (!$credentials) { + $this->myLogger->logme('error','OAuth credentials for GmailAPI not found in database.'); + throw new \Exception('OAuth credentials for GmailAPI not found in database.'); + } + // print_r($credentials[$this->authField]);//die(); + // $accessToken = $credentials[$this->authField]; + $this->client->setAuthConfig(json_decode($credentials[$this->authField],true)); + + // if ($this->client->isAccessTokenExpired()) { + // if ($this->client->getRefreshToken()) { + // $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken()); + // $this->storeTokenToDB($this->client->getAccessToken()); + // } else { + // $this->myLogger->logme('error', 'Access token expired and no refresh token available.'); + // throw new \Exception('Access token expired and no refresh token available.'); + // } + // } + } + + protected function setTokenFromDB() + { + $settingsModel = new SettingsModel(); + $token = $settingsModel->where('id', 1)->first(); + // dd(is_array($token) && is_null($token[$this->tokenField])); + + if (is_array($token) && is_null($token[$this->tokenField])) { + $this->myLogger->logme('error','Email Token not found in database.'); + throw new \Exception('Email Token not found in database.'); + } + + $accessToken = json_decode($token[$this->tokenField], true); + $this->client->setAccessToken($accessToken); + + if ($this->client->isAccessTokenExpired()) { + if ($this->client->getRefreshToken()) { + $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken()); + $this->storeTokenToDB($this->client->getAccessToken()); + } else { + $this->myLogger->logme('error', 'Access token expired and no refresh token available.'); + throw new \Exception('Access token expired and no refresh token available.'); + } + } + } + + protected function storeTokenToDB($token) + { + $settingsModel = new SettingsModel(); + $token = json_encode($token); + // $settingsModel->update(['id' => $this->tokenField], ['value' => json_encode($token)]); + $settingsModel->where('id', 1)->set([$this->tokenField => $token])->update(); + } + + public function createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = []) + { + $boundary = uniqid(rand(), true); + + $rawMessageString = "From: $from\r\n"; + $rawMessageString .= "To: $to\r\n"; + $rawMessageString .= "Reply-To: $replyTo\r\n"; + + if (!empty($cc)) { + $rawMessageString .= "Cc: " . implode(',', $cc) . "\r\n"; + } + + if (!empty($bcc)) { + $rawMessageString .= "Bcc: " . implode(',', $bcc) . "\r\n"; + } + + $rawMessageString .= "Subject: $subject\r\n"; + $rawMessageString .= "MIME-Version: 1.0\r\n"; + $rawMessageString .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n"; + $rawMessageString .= "--$boundary\r\n"; + $rawMessageString .= "Content-Type: text/html; charset=UTF-8\r\n"; + $rawMessageString .= "Content-Transfer-Encoding: 7bit\r\n\r\n"; + $rawMessageString .= $htmlContent . "\r\n"; + $rawMessageString .= "--$boundary--"; + + $rawMessage = base64_encode($rawMessageString); + $rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); + + $message = new Message(); + $message->setRaw($rawMessage); + + return $message; + } + + public function sendMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = []) + { + try { + $message = $this->createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc, $bcc); + $res = $this->service->users_messages->send('me', $message); + return array('status' => true, 'data' => $res); + } catch (\Exception $e) { + $err_msg = 'An error occurred while sending the mail: ' . $e->getMessage(); + $this->myLogger->logme('error', $err_msg); + // throw new \Exception('An error occurred while sending the mail: ' . $e->getMessage()); + return array('status' => false, 'data' =>$e->getMessage()); + } + } + + public function generateNewToken() + { + // dd('called'); + if (!is_cli()) { + throw new \RuntimeException('This method can only be accessed via the command line.'); + } + + if (php_sapi_name() != 'cli') { + throw new Exception('This application must be run on the command line.'); + } + + $authUrl = $this->client->createAuthUrl(); + CLI::write('Open the following link in your browser'); + CLI::write("\n"); + CLI::write($authUrl); + // printf ("Open the following link in your browser:\n%s\n", $authUrl); + CLI::write('Enter verification code: '); + // print 'Enter verification code: '; + $authCode = trim(fgets(STDIN)); + + $accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode); + if (array_key_exists('error', $accessToken)) { + $this->myLogger->logme('error', 'Error in getting access token from authCode' . join(', ', $accessToken)); + throw new \Exception(join(', ', $accessToken)); + } + + $this->storeTokenToDB($accessToken); + $this->myLogger->logme('error', 'New token generated and stored in the database.'); + print 'New token generated and stored in the database.'; + } +} diff --git a/app/Libraries/MyGoogleDrive.php b/app/Libraries/MyGoogleDrive.php new file mode 100644 index 00000000..566098eb --- /dev/null +++ b/app/Libraries/MyGoogleDrive.php @@ -0,0 +1,131 @@ +myLogger = \Config\Services::mylogger(); + $this->client = new Google_Client(); + $this->client->setAuthConfig(ROOTPATH . 'nhance-app-google-drive.json'); // App credentials + // putenv('GOOGLE_APPLICATION_CREDENTIALS=' . ROOTPATH . 'nhance-app-google-drive.json'); + $this->client->useApplicationDefaultCredentials(); + + $this->client->addScope(Google_Service_Drive::DRIVE); // Full access to Google Drive + } + + public function getDriveService() + { + return new Google_Service_Drive($this->client); + } + + // this function serve no purpose on anywhere, just for test purpose + public function listFiles(string $searchQuery = '') + { + $service = $this->getDriveService(); + // $searchQuery = "name contains 'test' and 'vitvelz@gmail.com' in readers"; + $searchQuery = "name contains 'test' or name contains 'new'"; + // $searchQuery = "name contains 'test' and mimeType = 'application/vnd.google-apps.folder' or name contains 'new' and mimeType = 'application/vnd.ms-excel'"; + // List the files + $files = $service->files->listFiles([ + 'q' => $searchQuery, + // 'supportsAllDrives' => true, + // 'includeItemsFromAllDrives' => true, + 'fields' => 'nextPageToken, files(id, name, mimeType, size, createdTime, modifiedTime, owners, shared, permissions, webViewLink, thumbnailLink)', + 'pageSize' => 20, + ]); + // print_r($files); + echo "\n**************\n"; + foreach ($files->getFiles() as $file) { + echo 'File ID: ' . $file->getID() . "\n"; + echo 'File Name: ' . $file->getName() . "\n"; + // echo 'MIME Type: ' . $file->getMimeType() . "\n"; + // echo 'Size: ' . $file->getSize() . " bytes\n"; + // echo 'Created Time: ' . $file->getCreatedTime() . "\n"; + // echo 'Modified Time: ' . $file->getModifiedTime() . "\n"; + // echo 'Owner: ' . $file->getOwners()[0]->getEmailAddress() . "\n"; + // echo 'Shared: ' . ($file->getShared() ? 'Yes' : 'No') . "\n"; + // echo 'Permissions: ' . json_encode($file->getPermissions()) . "\n"; + // echo 'Web View Link: ' . $file->getWebViewLink() . "\n"; + // echo 'Thumbnail Link: ' . $file->getThumbnailLink() . "\n"; + echo 'parents: ' .$file->getParents()."\n"; + echo "-----\n"; + } + } + + // this fucntion is not generating any new token, just for testing purpose + public function generateNewToken() + { + // $this->uploadFile();die(); + $this->listFiles();die(); + // dd('called'); + if (!is_cli()) { + throw new \RuntimeException('This method can only be accessed via the command line.'); + } + + if (php_sapi_name() != 'cli') { + throw new Exception('This application must be run on the command line.'); + } + + $authUrl = $this->client->createAuthUrl(); + CLI::write('Open the following link in your browser'); + CLI::write("\n"); + CLI::write($authUrl); + // printf ("Open the following link in your browser:\n%s\n", $authUrl); + CLI::write('Enter verification code: '); + // print 'Enter verification code: '; + $authCode = trim(fgets(STDIN)); + + $accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode); + if (array_key_exists('error', $accessToken)) { + $this->myLogger->logme('error', 'Error in getting access token from authCode' . join(', ', $accessToken)); + throw new \Exception(join(', ', $accessToken)); + } + + $this->storeToken($accessToken); + $this->myLogger->logme('error', 'New token generated and stored in the writepath for google drive.'); + print 'New token generated and stored in the writepath for google drive.'; + } + + /** + * Upload a file to Google Drive + * this function not used in anywhere + */ + public function uploadFile($filePath = '', $fileName= '') + { + $service = $this->getDriveService(); + + // $file = new \Google_Service_Drive_DriveFile(); + // $file->setName('tata.xlsx'); + // $file->setParents('TEST'); + + // Create a new file metadata object + $file = new \Google_Service_Drive_DriveFile([ + 'name' => 'mypdf.pdf', + 'parents' => ['1M0GH3GbNUOYZLNeHXA5U7C_P2NSx7F7O'] // Specify the folder ID here + ]); + + $data = file_get_contents('C:\Users\Venba\Desktop\nhance_bpf.pdf'); + + $createdFile = $service->files->create($file, [ + 'data' => $data, + 'mimeType' => 'application/octet-stream', + 'uploadType' => 'multipart', + 'fields' => 'id' // Specify fields to return + ]); + + echo $createdFile->id; + } + + + +} diff --git a/app/Libraries/MyLogger.php b/app/Libraries/MyLogger.php old mode 100644 new mode 100755 diff --git a/app/Libraries/Slug.php b/app/Libraries/Slug.php old mode 100644 new mode 100755 diff --git a/app/Models/.gitkeep b/app/Models/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Models/AddImgModel.php b/app/Models/AddImgModel.php old mode 100644 new mode 100755 diff --git a/app/Models/AuthHistoryModel.php b/app/Models/AuthHistoryModel.php old mode 100644 new mode 100755 diff --git a/app/Models/BatchFileModel.php b/app/Models/BatchFileModel.php old mode 100644 new mode 100755 diff --git a/app/Models/BatchListModel.php b/app/Models/BatchListModel.php old mode 100644 new mode 100755 diff --git a/app/Models/CDMasterModel.php b/app/Models/CDMasterModel.php old mode 100644 new mode 100755 diff --git a/app/Models/ChatBotModel.php b/app/Models/ChatBotModel.php old mode 100644 new mode 100755 diff --git a/app/Models/ClientBranchModel.php b/app/Models/ClientBranchModel.php old mode 100644 new mode 100755 diff --git a/app/Models/ClientDepositModel.php b/app/Models/ClientDepositModel.php old mode 100644 new mode 100755 diff --git a/app/Models/ClientKYCDocsModel.php b/app/Models/ClientKYCDocsModel.php old mode 100644 new mode 100755 index 6c9f3c8a..913fb375 --- a/app/Models/ClientKYCDocsModel.php +++ b/app/Models/ClientKYCDocsModel.php @@ -17,6 +17,7 @@ class ClientKYCDocsModel extends Model 'is_active', "created_by", "updated_by", + "vehicle_id", ]; public function getKycDocsName($client_id){ @@ -27,4 +28,17 @@ class ClientKYCDocsModel extends Model return $query; } + public function getClientKYCDriveFilesIndex($client_id,$client_doc_name = '') + { + $query = $this->select('client_kyc_documents.client_id,client_kyc_documents.file_name, kyc_docs.file_name as doc_name,"url","client_policy_id","kyc" as file_type') + ->join('kyc_docs', 'kyc_docs.id = client_kyc_documents.kyc_doc_type_id') + ->where(['client_kyc_documents.client_id' => $client_id, 'client_kyc_documents.is_active' => 1]) + ->when($client_doc_name, function($query) use ($client_doc_name){ + return $query->where("kyc_docs.file_name like '%$client_doc_name%'"); + }) + ->get() + ->getResultArray(); + return $query; + } + } diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php old mode 100644 new mode 100755 index 718e67a8..ce5481d3 --- a/app/Models/ClientModel.php +++ b/app/Models/ClientModel.php @@ -13,6 +13,7 @@ class ClientModel extends Model protected $allowedFields = [ "id", "entity_type_id", + "client_type", "client_name", "short_name", "pan", @@ -28,7 +29,14 @@ class ClientModel extends Model "updated_by", "is_active", "common_mails", - "hr_mails" + "hr_mails", + "client_code", + "cost_center", + "dob", + "aadhar", + "reference", + "phone", + "email", ]; diff --git a/app/Models/ClientPolicyModel.php b/app/Models/ClientPolicyModel.php old mode 100644 new mode 100755 index e66bfc88..470bbb0a --- a/app/Models/ClientPolicyModel.php +++ b/app/Models/ClientPolicyModel.php @@ -139,7 +139,7 @@ class ClientPolicyModel extends Model ->select('clients.client_name as client_name') ->join('clients','clients.id=client_policy.client_id') ->join('insurers', 'insurers.id = client_policy.insurer_id') - ->join('cd_master', 'cd_master.insurer_id = client_policy.insurer_id') + ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') ->where('client_policy.client_id', $id) ->groupBy('client_policy.insurer_id') ->groupBy('client_policy.client_id', $id) // Group by insurer_id diff --git a/app/Models/ClientRMModel.php b/app/Models/ClientRMModel.php old mode 100644 new mode 100755 diff --git a/app/Models/EmpEndorsementModel.php b/app/Models/EmpEndorsementModel.php old mode 100644 new mode 100755 diff --git a/app/Models/EmployeeModel.php b/app/Models/EmployeeModel.php old mode 100644 new mode 100755 diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php old mode 100644 new mode 100755 diff --git a/app/Models/EndorsementModel.php b/app/Models/EndorsementModel.php new file mode 100644 index 00000000..22bcec72 --- /dev/null +++ b/app/Models/EndorsementModel.php @@ -0,0 +1,30 @@ +getResult(); } - public function getInsurerName($insurerId) + public function getInsurerName($insurerId, $client_id) { // Fetch the insurer name based on the insurer ID - $query = $this->select('insurers.id,insurers.name, cd_master.cd_ac_no') - ->join('cd_master', 'cd_master.insurer_id = insurers.id') - ->where('insurers.id', $insurerId) - ->get(); + $query = $this->db->table('client_policy') + ->select('insurers.id, insurers.name, cd_master.cd_ac_no') + ->join('insurers', 'insurers.id = client_policy.insurer_id') + ->join('cd_master', 'cd_master.insurer_id = insurers.id AND cd_master.client_id = client_policy.client_id') + ->where('client_policy.insurer_id', $insurerId) + ->where('client_policy.client_id', $client_id) + ->get(); if ($query->resultID->num_rows > 0) { $result = $query->getRow(); diff --git a/app/Models/InsurerStatements.php b/app/Models/InsurerStatements.php new file mode 100644 index 00000000..0e2dc2ec --- /dev/null +++ b/app/Models/InsurerStatements.php @@ -0,0 +1,31 @@ +db->table('pt_co_share_details pt_co') + ->select(' + pt_co.id, + pt_co.pt_id, + pt_co.exp_amt, + pt.id AS policy_transaction_id, + pt.endorsement_no, + c.client_name, + pt.created_at, + pt_co.insurer_id, + pt_co.insurer_branch_id, + pt.policy_no, + pt.policy_issue_date, + pt.policy_start_date, + pt.policy_end_date, + pt.status, + pt_co.bp_amt, + pt_co.tp_amt, + pt_co.tep_amt, + pt_co.exp_amt, + pt_co.statement_id + ') + ->join('policy_transaction pt', 'pt_co.pt_id = pt.id') + ->join('clients c', 'pt.client_id = c.id') + ->where('pt_co.is_active', 1) + ->where('MONTH(pt.month)', $month) + ->where('YEAR(pt.month)', $year) + ->where('pt_co.insurer_id', $insurer_id) + ->where('pt_co.insurer_branch_id', $insurer_branch_id) + ->where('pt_co.statement_id is null') + ->where('pt.status','completed') + // ->where('pt_co.exp_amt', 0.00) + // ->orWhere('pt_co.exp_amt is null') + ->get() + ->getResultArray(); + } + +} diff --git a/app/Models/PTFileModel.php b/app/Models/PTFileModel.php new file mode 100644 index 00000000..702cb30d --- /dev/null +++ b/app/Models/PTFileModel.php @@ -0,0 +1,42 @@ +select('pt_files.doc_name,pt_files.file_name,pt_files.url,pt.client_id,pt.client_policy_id,"policy" as file_type') + ->join('policy_transaction pt', 'pt_files.pt_id = pt.id') + ->where('pt.client_policy_id', $policy_id) + ->where('pt.is_active',1) + ->when($policy_doc_name, function($query) use ($policy_doc_name){ + return $query->where("pt_files.doc_name like '%$policy_doc_name%'"); + }) + ->get() + ->getResultArray(); + return $clients; + } +} diff --git a/app/Models/PolicesModel.php b/app/Models/PolicesModel.php old mode 100644 new mode 100755 diff --git a/app/Models/PolicyGridModel.php b/app/Models/PolicyGridModel.php old mode 100644 new mode 100755 diff --git a/app/Models/PolicyPremium1Model.php b/app/Models/PolicyPremium1Model.php old mode 100644 new mode 100755 diff --git a/app/Models/PolicyPremium2Model.php b/app/Models/PolicyPremium2Model.php old mode 100644 new mode 100755 diff --git a/app/Models/PolicyTransactionModel.php b/app/Models/PolicyTransactionModel.php new file mode 100644 index 00000000..dca5d9b4 --- /dev/null +++ b/app/Models/PolicyTransactionModel.php @@ -0,0 +1,690 @@ +db->table('policy_transaction') + ->select(" + policy_transaction.*, + DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date, + DATE_FORMAT( + IF(policy_transaction.month IS NULL, + policy_transaction.policy_issue_date, + policy_transaction.month), + '%b %Y') AS policy_issue_month, + CASE + WHEN clients.client_type = 1 THEN 'Group' + WHEN clients.client_type = 2 THEN 'Retail' + ELSE '-' + END AS client_type, + CASE + WHEN policy_transaction.revenue_type = 'NA' THEN 'Fresh' + ELSE 'Renewal' + END AS revenue_type, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'Policy' + ELSE 'Endorsement' + END AS action_type, + clients.client_name AS client_name, + clients.short_name AS client_short_name, + client_branch.branch_name AS client_branch_name, + client_branch.address1 AS client_address, + policy_type.policy_type, + policy_type.bap, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + insurer_branch.branch_name AS insurer_branch_name, + insurer_branch.branch_code AS insurer_branch_code, + user_profiles.first_name as user_name, + vehicle.vehicle_no, + tpa.name as tpa_name, + pt_co_share_details.remark as remarks, + pt_co_share_details.reward, + pt_co_share_details.bp_amt, + sales_user.first_name as salse_person_name, + service_user.first_name as service_person_name, + + ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS premium_wo_gst, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2) AS gst_amount, + + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) + ROUND((ROUND((pt_co_share_details.bp_amt + pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) * 18 / 100), 2)), 2) AS total_premium, + + ROUND((pt_co_share_details.tp_amt + pt_co_share_details.tep_amt), 2) AS tp_or_ter, + + DATEDIFF(policy_transaction.policy_end_date, CURDATE()) AS days, + + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per) AS agreed_tp_or_ter_per, + + pt_co_share_details.agreed_bp_per, + + ROUND( + (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, + 2) AS total_irda, + + ROUND( + (ROUND( + (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, + 2) * 18 / 100), + 2) AS gst_on_revenue, + + ROUND( + (ROUND( + (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, + 2) + + ROUND( + (ROUND( + (pt_co_share_details.bp_amt * pt_co_share_details.agreed_bp_per + + (pt_co_share_details.tp_amt + pt_co_share_details.tep_amt) * + (pt_co_share_details.agreed_tp_per + pt_co_share_details.agreed_tep_per)) / 100, + 2) * 18 / 100), + 2)), + 2) AS total_amt_received, + insurer_statements.invoice_date, + insurer_statements.invoice_no, + insurer_statements.invoice_amount, + + ( + SELECT + (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount + FROM + inv_payment_details + WHERE + inv_payment_details.statement_id = insurer_statements.id + AND inv_payment_details.is_active = 1 + + ) AS realization_amount, + + ROUND( + insurer_statements.invoice_amount - + ( + SELECT + (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) + FROM + inv_payment_details + WHERE + inv_payment_details.statement_id = insurer_statements.id + AND inv_payment_details.is_active = 1 + ), + 2) AS outstanding_amount, + + ( + SELECT + GROUP_CONCAT(inv_payment_details.utr_no SEPARATOR ', ') AS utr_numbers + FROM + inv_payment_details + WHERE + inv_payment_details.statement_id = insurer_statements.id + AND inv_payment_details.is_active = 1 + ) AS utr_numbers, + + ( + SELECT + GROUP_CONCAT(inv_payment_details.received_date SEPARATOR ', ') AS payment_dates + FROM + inv_payment_details + WHERE + inv_payment_details.statement_id = insurer_statements.id + AND inv_payment_details.is_active = 1 + ) AS payment_dates + + ") + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id') + ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('user_profiles', 'policy_transaction.created_by = user_profiles.id', 'left') + ->join('vehicle', 'policy_transaction.vehicle_id = vehicle.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->join('insurers', 'policy_transaction.insurer_id = insurers.id', 'left') + ->join('insurer_branch', 'policy_transaction.insurer_branch_id = insurer_branch.id', 'left') + ->join('tpa', 'policy_transaction.tpa_id = tpa.id', 'left') + ->join('tpa_branch', 'policy_transaction.tpa_branch_id = tpa_branch.id', 'left') + ->join('user_profiles AS sales_user', 'policy_transaction.sales_generated_by = sales_user.id', 'left') + ->join('user_profiles AS service_user', 'policy_transaction.serviced_by = service_user.id', 'left') + ->where('policy_transaction.is_active', 1); + + // Check if the start date and end date are provided + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + ->where('policy_transaction.'.$date_type.'<=', $endDate); + }else{ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } + + public function getInceptionTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + { + // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); + $builder = $this->db->table('policy_transaction') + ->select(' + policy_transaction.*, + clients.short_name AS client_short_name, + clients.client_code, + clients.client_type, + clients.client_name, + client_branch.branch_name AS client_branch_name, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + policy_type.policy_type, + pt_co_share_details.agreed_amt AS amount, + pt_co_share_details.bp_amt AS bp, + pt_co_share_details.tp_amt AS tp + ') + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type', 'inception'); + + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + ->where('policy_transaction.'.$date_type.'<=', $endDate); + }else{ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + if ($status != 0) { + $builder->where('policy_transaction.status', $status); + } + + if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } + + public function getEndorsementTranctionListData($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + { + // dd($start_date, $end_date, $client_id, $insurer_id, $policy_type_id, $date_type, $issuer, $status); + $builder = $this->db->table('policy_transaction') + ->select(' + policy_transaction.*, + clients.short_name as client_short_name, + clients.client_code, + client_branch.branch_name as client_branch_name, + insurers.name AS insurer_name, + insurers.short_name AS insurer_short_name, + policy_type.policy_type + ') + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('clients', 'policy_transaction.client_id = clients.id', 'left') + ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id','left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.action_type !=', 'inception'); + + + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.'.$date_type.'>=', $startDate) + ->where('policy_transaction.'.$date_type.'<=', $endDate); + }else{ + + // $fromDate = date('Y-m-d', strtotime('-30 days')); + // $toDate = date('Y-m-d 23:59:59'); + + // $builder->where('policy_transaction.created_at >=', $fromDate) + // ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + if ($status != 0) { + $builder->where('policy_transaction.status', $status); + } + + if($client_id == 0 && $insurer_id == 0 && $policy_type_id == 0 && $date_type == 0 && $issuer == 0){ + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } + + public function getVarienceReportLIst($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + { + $builder = $this->db->table('policy_transaction') + ->select(" + policy_transaction.id, + clients.client_name, + insurers.name AS insurer_name, + policy_type.policy_type, + policy_transaction.policy_no, + policy_transaction.endorsement_no, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'I' + ELSE 'E' + END AS action_type, + pt_co_share_details.exp_amt, + pt_co_share_details.variance, + insurer_statements.invoice_amount, + insurer_statements.invoice_status, + + ROUND((pt_co_share_details.actual_bp_brokerage_amt + pt_co_share_details.actual_tp_brokerage_amt + pt_co_share_details.actual_tep_brokerage_amt), 2) AS realization_amount2, + + ( + SELECT + (SUM(inv_payment_details.inv_amt) + SUM(inv_payment_details.tds)) AS realization_amount + FROM + inv_payment_details + WHERE + inv_payment_details.statement_id = insurer_statements.id + AND inv_payment_details.is_active = 1 + + ) AS realization_amount, + + ") + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('insurer_statements', 'pt_co_share_details.statement_id = insurer_statements.id', 'left') + ->join('inv_payment_details', 'insurer_statements.id = inv_payment_details.statement_id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('pt_co_share_details.actual_bp_brokerage_amt IS NOT NULL AND pt_co_share_details.actual_bp_brokerage_amt != 0') + ->where('pt_co_share_details.variance IS NOT NULL') + ->where('pt_co_share_details.variance !=', 0); + + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } else { + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if ($status != 0) { + $builder->where('policy_transaction.status', $status); + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } + + public function getBusinessReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + { + $builder = $this->db->table('policy_transaction') + ->select([ + 'policy_transaction.id AS policy_trns_id', + 'clients.client_name', + 'insurers.name AS insurer_name', + 'policy_type.policy_type', + 'policy_transaction.policy_no', + 'policy_transaction.endorsement_no', + "CASE + WHEN policy_transaction.action_type = 'inception' THEN 'I' + ELSE 'E' + END AS action_type", + 'policy_transaction.action_type as action_type_full', + 'pt_co_share_details.bp_amt', + 'pt_co_share_details.tp_amt', + 'pt_co_share_details.tep_amt' + ]) + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.status', 'completed') + ->where('pt_co_share_details.bp_amt IS NULL OR pt_co_share_details.bp_amt = 0'); + + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } else { + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if ($status != 0) { + $builder->where('policy_transaction.status', $status); + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } + + public function getFinanceReportList($start_date = 0, $end_date = 0, $client_id = 0, $insurer_id = 0, $policy_type_id = 0, $date_type = 0, $issuer = 0, $status = 0) + { + $builder = $this->db->table('policy_transaction') + ->select(" + policy_transaction.id, + clients.client_name, + insurers.name AS insurer_name, + policy_type.policy_type, + policy_transaction.policy_no, + policy_transaction.endorsement_no, + CASE + WHEN policy_transaction.action_type = 'inception' THEN 'I' + ELSE 'E' + END AS action_type, + policy_transaction.action_type AS action_type_full, + pt_co_share_details.exp_amt, + pt_co_share_details.variance + ") + ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_id', 'left') + ->join('clients', 'clients.id = policy_transaction.client_id', 'left') + ->join('insurers', 'pt_co_share_details.insurer_id = insurers.id', 'left') + ->join('client_policy', 'policy_transaction.client_policy_id = client_policy.id', 'left') + ->join('policy_type', 'policy_transaction.policy_type_id = policy_type.id', 'left') + ->where('policy_transaction.is_active', 1) + ->where('policy_transaction.status', 'completed') + ->where('COALESCE(pt_co_share_details.agreed_bp_per, 0) + COALESCE(pt_co_share_details.agreed_tp_per, 0) + COALESCE(pt_co_share_details.agreed_tep_per, 0) = 0') + ->where('COALESCE(pt_co_share_details.actual_bp_amt, 0) + COALESCE(pt_co_share_details.actual_tp_amt, 0) + COALESCE(pt_co_share_details.actual_tep_amt, 0) = 0') + ->where('COALESCE(pt_co_share_details.actual_bp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tp_brokerage_amt, 0) + COALESCE(pt_co_share_details.actual_tep_brokerage_amt, 0) = 0'); + + + if ($start_date != 0 && $end_date != 0 && $date_type != 0) { + + $startDate = date('Y-m-d 00:00:00', strtotime($start_date)); + $endDate = date('Y-m-d 23:59:59', strtotime($end_date)); + + $builder->where('policy_transaction.' . $date_type . '>=', $startDate) + ->where('policy_transaction.' . $date_type . '<=', $endDate); + } else { + + $fromDate = date('Y-m-d', strtotime('-30 days')); + $toDate = date('Y-m-d 23:59:59'); + + $builder->where('policy_transaction.created_at >=', $fromDate) + ->where('policy_transaction.created_at <=', $toDate); + } + + if ($client_id != 0) { + $builder->where('policy_transaction.client_id', $client_id); + } + + if ($insurer_id != 0) { + $builder->where('policy_transaction.insurer_id', $insurer_id); + } + + if ($policy_type_id != 0) { + $builder->where('client_policy.policy_type_id', $policy_type_id); + } + + if ($issuer != 0) { + $builder->where('policy_transaction.issuer', $issuer); + } + + if ($status != 0) { + $builder->where('policy_transaction.status', $status); + } + + $builder->orderBy('policy_transaction.id', 'desc'); + + return $builder->get()->getResultArray(); + } +} diff --git a/app/Models/PolicyTransactionStatusModel.php b/app/Models/PolicyTransactionStatusModel.php new file mode 100644 index 00000000..712fa8e0 --- /dev/null +++ b/app/Models/PolicyTransactionStatusModel.php @@ -0,0 +1,58 @@ +getResult(); } + public function getUserTeamsByUserID($user_id){ + + $user_teams = $this->db->table('user_profiles') + ->select('user_teams.team_id') + ->join('user_teams', 'user_profiles.id = user_teams.user_id') + ->where('user_profiles.id', $user_id) + ->where('user_teams.is_active', 1) + ->get() + ->getResultArray(); + + if (!empty($user_teams)) { + // Extract only the 'team_id' values + $team_ids = array_column($user_teams, 'team_id'); + return $team_ids; // Return array of team IDs + } else { + return []; // Return empty array if no teams found + } + } + } ?> \ No newline at end of file diff --git a/app/Models/UserTeamsModel.php b/app/Models/UserTeamsModel.php old mode 100644 new mode 100755 diff --git a/app/Models/VehicleModel.php b/app/Models/VehicleModel.php new file mode 100644 index 00000000..dda3af1c --- /dev/null +++ b/app/Models/VehicleModel.php @@ -0,0 +1,86 @@ +db->table('vehicle') + ->select(" + vehicle.*, + CASE + WHEN clients.client_type = 1 THEN 'Group' + WHEN clients.client_type = 2 THEN 'Individual' + ELSE '-' + END AS owner_type, + clients.client_name as owner_name, + client_branch.branch_name as owner_branch + ") + ->join('clients', 'vehicle.owner = clients.id') + ->join('client_branch', 'vehicle.branch_id = client_branch.id', 'left') + ->where('vehicle.is_active', 1) + ->orderBy('vehicle.id', 'desc') + ->get() + ->getResultArray(); + + } + +} diff --git a/app/ThirdParty/.gitkeep b/app/ThirdParty/.gitkeep old mode 100644 new mode 100755 diff --git a/app/Views/AddUser.php b/app/Views/AddUser.php old mode 100644 new mode 100755 diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php old mode 100644 new mode 100755 index 8f2a5aff..b931e838 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -62,10 +62,23 @@ body { Enrolment + + + + + + +
+
diff --git a/app/Views/UserList.php b/app/Views/UserList.php old mode 100644 new mode 100755 diff --git a/app/Views/add_image_list.php b/app/Views/add_image_list.php old mode 100644 new mode 100755 diff --git a/app/Views/add_transaction.php b/app/Views/add_transaction.php old mode 100644 new mode 100755 diff --git a/app/Views/batch_list.php b/app/Views/batch_list.php old mode 100644 new mode 100755 diff --git a/app/Views/bds_dash.php b/app/Views/bds_dash.php new file mode 100644 index 00000000..4418c119 --- /dev/null +++ b/app/Views/bds_dash.php @@ -0,0 +1,195 @@ + + +
+
+ + +
+
+
+
Business Team Pending
+

+

 

+

 

+
+
+
+ + + + + +
+
+
+
Finance Team Pending
+

+

 

+

 

+
+
+
+ + +
+
+ + \ No newline at end of file diff --git a/app/Views/business_team_list.php b/app/Views/business_team_list.php new file mode 100644 index 00000000..33c99426 --- /dev/null +++ b/app/Views/business_team_list.php @@ -0,0 +1,440 @@ + + +
+
+
+
+
+ + + +
+
+
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + +
+ + + + + +
+ + +
+
+
+
+ +
+
+
+ +
+
+
+
+
+

Business Team

+
+ +
+
+ + + + + + + + + + + + + + + + $row){ ?> + + + + + + + + + + + + + +
S.NoClient NameInsurerPolicyPolicy NoEndorsement NoEvent TypeAction
+ +
+ +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/app/Views/cd_master_list.php b/app/Views/cd_master_list.php old mode 100644 new mode 100755 diff --git a/app/Views/client_basic_info.php b/app/Views/client_basic_info.php old mode 100644 new mode 100755 diff --git a/app/Views/client_branch.php b/app/Views/client_branch.php old mode 100644 new mode 100755 index 2867a42c..40e04f54 --- a/app/Views/client_branch.php +++ b/app/Views/client_branch.php @@ -11,6 +11,20 @@ .select2-container .select2-selection--multiple .select2-selection__choice { color: #000000; } + /* .select2-search__field{ + height: 2px !important; + } */ + + .select2-selection__choice { + background-color: #0a8794 !important; + color: white !important; + font-weight: bold; + } + + .select2-selection__choice__remove { + color: white !important; + margin-right: 5px; + } + +
+
+
+
+
+ + + +
+
+
+
+
" id='dms_search_form'> +
+ +
+ + + + + + +
+ +
+ + + + +
+
+ OR +
+
+ + + + + + +
+ +
+ + + + +
+
+ +
+ + +
+
+
+
+
+
+ +
+
+
+ + +
+
+
+
+
+

File search result

+
+ +
+
+ + + + + + + + + + + + $row){ ?> + + + + + + + + + + +
S.NoDoc nameFile nameAction
+ + +
+ +
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/app/Views/drive_file_upload.php b/app/Views/drive_file_upload.php new file mode 100644 index 00000000..158598ec --- /dev/null +++ b/app/Views/drive_file_upload.php @@ -0,0 +1,116 @@ +
+
+
+
+
+
+ + + +
+
+
+
+ + + + +
+ +
+ +
+ +
+ +
+
+
+
+
+ +
+
+
+ +
+
+
+
+

File List

+
+ +
+
+ + + + + + + + + + + +
S.NoDocs NameFile NameAction
+
+
+
+
+
+
+ + + diff --git a/app/Views/ecard_template/default_ecard.php b/app/Views/ecard_template/default_ecard.php old mode 100644 new mode 100755 diff --git a/app/Views/ecard_template/fhpl_tpa.php b/app/Views/ecard_template/fhpl_tpa.php old mode 100644 new mode 100755 diff --git a/app/Views/ecard_template/icici_tpa.php b/app/Views/ecard_template/icici_tpa.php old mode 100644 new mode 100755 diff --git a/app/Views/ecard_template/md_tpa.php b/app/Views/ecard_template/md_tpa.php old mode 100644 new mode 100755 diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php old mode 100644 new mode 100755 diff --git a/app/Views/employee_list.php b/app/Views/employee_list.php old mode 100644 new mode 100755 diff --git a/app/Views/employee_upload.php b/app/Views/employee_upload.php old mode 100644 new mode 100755 index 535418cc..5ad5ea73 --- a/app/Views/employee_upload.php +++ b/app/Views/employee_upload.php @@ -911,10 +911,10 @@ $(document).ready(function() { var select = document.getElementById("upload-action-type"); for (var i = 0; i < select.options.length; i++) { select.options[i].disabled = true; - if (select.options[i].value === "inception") { + if (select.options[i].value === "inception" || select.options[i].value === "enrollment") { select.options[i].disabled = false; } - if (select.options[i].value === "") { + if (select.options[i].value === "" || select.options[i].value === "enrollment") { select.options[i].disabled = false; } } @@ -935,7 +935,7 @@ $(document).ready(function() { console.error('Error fetching data from API:', error); var select = document.getElementById("upload-action-type"); for (var i = 0; i < select.options.length; i++) { - if (select.options[i].value === "inception") { + if (select.options[i].value === "inception" || select.options[i].value === "enrollment" ) { select.options[i].disabled = false; break; } diff --git a/app/Views/endorsement_dash.php b/app/Views/endorsement_dash.php old mode 100644 new mode 100755 diff --git a/app/Views/endorsement_list.php b/app/Views/endorsement_list.php old mode 100644 new mode 100755 diff --git a/app/Views/enrollment_dash.php b/app/Views/enrollment_dash.php old mode 100644 new mode 100755 index 58d8f9cb..17fe0f9d --- a/app/Views/enrollment_dash.php +++ b/app/Views/enrollment_dash.php @@ -1,11 +1,11 @@ - + - + - + diff --git a/app/Views/enrollment_list.php b/app/Views/enrollment_list.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/404.php b/app/Views/errors/404.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/cli/error_404.php b/app/Views/errors/cli/error_404.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/cli/error_exception.php b/app/Views/errors/cli/error_exception.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/cli/production.php b/app/Views/errors/cli/production.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/html/debug.css b/app/Views/errors/html/debug.css old mode 100644 new mode 100755 diff --git a/app/Views/errors/html/debug.js b/app/Views/errors/html/debug.js old mode 100644 new mode 100755 diff --git a/app/Views/errors/html/error_404.php b/app/Views/errors/html/error_404.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/html/error_exception.php b/app/Views/errors/html/error_exception.php old mode 100644 new mode 100755 diff --git a/app/Views/errors/html/production.php b/app/Views/errors/html/production.php old mode 100644 new mode 100755 diff --git a/app/Views/excel_errors.php b/app/Views/excel_errors.php old mode 100644 new mode 100755 diff --git a/app/Views/export_import_error_list.php b/app/Views/export_import_error_list.php old mode 100644 new mode 100755 diff --git a/app/Views/file_list.php b/app/Views/file_list.php old mode 100644 new mode 100755 index c2872c70..2cd80976 --- a/app/Views/file_list.php +++ b/app/Views/file_list.php @@ -247,10 +247,11 @@ $('body').on('click', '.upload_button', function() { $('body').on('click', '.truncate2', function(event) { + event.preventDefault(); // console.log(event); var fileId = JSON.parse(this.getAttribute('data-id')); - // alert('Hi' + fileId); + console.log('Truncate File ID' + fileId); Swal.fire({ title: "Do you want to truncate data from uploaded file?", @@ -260,10 +261,13 @@ $('body').on('click', '.truncate2', function(event) { }).then((result) => { console.log(result); + if (result.isConfirmed) { + $('.loader').fadeIn(); $('.loader-mask').fadeIn(); var apiURL = 'employee/truncate/' + fileId; + // console.log('Truncate API URL : ', apiURL); $.ajax({ url: apiURL, @@ -272,6 +276,9 @@ $('body').on('click', '.truncate2', function(event) { "X-Requested-With": "XMLHttpRequest" }, success: function(response) { + + // console.log('Truncate Response', response) + setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -294,6 +301,10 @@ $('body').on('click', '.truncate2', function(event) { } }, error: function(xhr, status, error) { + + console.error(xhr.responseText); + console.error(status, error); + setTimeout(function() { $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -304,6 +315,7 @@ $('body').on('click', '.truncate2', function(event) { } }); } + }); }) diff --git a/app/Views/finance_team_list.php b/app/Views/finance_team_list.php new file mode 100644 index 00000000..c719a6e7 --- /dev/null +++ b/app/Views/finance_team_list.php @@ -0,0 +1,440 @@ + + +
+
+
+
+
+ + + +
+
+
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + +
+ + + + + +
+ + +
+
+
+
+ +
+
+
+ +
+
+
+
+
+

Finance Team

+
+ +
+
+ + + + + + + + + + + + + + + + $row){ ?> + + + + + + + + + + + + + +
S.NoClient NameInsurerPolicyPolicy NoEndorsement NoEvent TypeAction
+ +
+ +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/app/Views/import_export.php b/app/Views/import_export.php old mode 100644 new mode 100755 diff --git a/app/Views/insurer_basic_info.php b/app/Views/insurer_basic_info.php old mode 100644 new mode 100755 diff --git a/app/Views/insurer_branch.php b/app/Views/insurer_branch.php old mode 100644 new mode 100755 diff --git a/app/Views/insurer_export_templete.php b/app/Views/insurer_export_templete.php old mode 100644 new mode 100755 index 40b757a7..935b669d --- a/app/Views/insurer_export_templete.php +++ b/app/Views/insurer_export_templete.php @@ -48,7 +48,7 @@
- +
@@ -122,7 +122,7 @@