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/Routes.php b/app/Config/Routes.php index 846d547e..9dce6e34 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -278,10 +278,47 @@ $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->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->cli('cli/processjob', 'JobWorker::processJob'); $routes->cli('cli/processjobs', 'JobWorker::processJobs'); $routes->cli('cli/enrollment_status', 'JobWorker::enrollment_status'); diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 5439e64e..25c8170e 100755 --- 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,9 @@ 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; class ClientController extends AdminController @@ -68,6 +68,10 @@ class ClientController extends AdminController protected $notificationModel; protected $CDMasterModel; protected $policyTypeModel; + protected $policyTransactionModel; + protected $policyTransactionStatusModel; + protected $vehicleModel; + public function __construct() @@ -99,6 +103,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 +116,13 @@ 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; - + { + $params['mail'] = 'venkateshraman786@gmail.com'; + $params['subject'] = 'testing'; + $params['message'] = 'testing'; - $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); + $result = MailHelper::send_email($params); + dd($result); } public function index() @@ -289,6 +267,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;
@@ -412,6 +391,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 +431,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'])) {
@@ -819,7 +800,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 +823,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');
@@ -881,30 +860,6 @@ class ClientController extends AdminController
             }
         }
                     
-        $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 +877,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);
@@ -2236,7 +2224,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 +3000,261 @@ 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
+                ')
+            ->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'],
+            ]);
+        } 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, 
+            'client_id' => $client_insert, 
+            'branch_id' => $branch_insert ?? null, 
+            'message' => 'Client created successfully'
+        ], 200);
+    }
+    
+    public function createVehicleWithMinimalData()
+    {
+        $data = $this->request->getPost();
+
+        $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'], 
+                    '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);
+        }
+    }
+
+
+
 }
\ No newline at end of file
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index ed30157c..2e7ee6a4 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -41,7 +41,7 @@ class MasterController extends AdminController
     protected $userModel;
     protected $insurerBranchModel;
     protected $insurerKYCDocsModel;
-    protected $insurerPolicyModel;
+    protected $clientPolicyModel;
     protected $insurerRMModel;
     protected $kycDocsModel;
     protected $kycEntityTypeModel;
@@ -67,7 +67,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();
@@ -1344,6 +1344,44 @@ 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, 'message' => 'CD Account number created successfully'], 200);
+        }else{
+            return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200);
+        }
+    }
 
 
     //excel export template 
diff --git a/app/Controllers/PolicyTransactionController.php b/app/Controllers/PolicyTransactionController.php
new file mode 100644
index 00000000..7c9c46e7
--- /dev/null
+++ b/app/Controllers/PolicyTransactionController.php
@@ -0,0 +1,970 @@
+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();
+    }
+
+    // Policy Transaction Inception
+    public function viewInception()
+    {   
+        $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['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['inception_data_list'] = $this->policyTransactionModel
+            ->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,
+                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', 'policy_transaction.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')
+            ->orderBy('policy_transaction.id', 'desc')
+            ->findAll();
+
+        $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;
+
+        // Format dates
+        $data['policy_issue_date'] = date('Y-m-d', strtotime($data['policy_issue_date'])) ?? null;
+        $data['policy_start_date'] = date('Y-m-d', strtotime($data['policy_start_date'])) ?? null;
+        $data['policy_end_date'] = date('Y-m-d', strtotime($data['policy_end_date'])) ?? null;
+        $data['renewal_date'] = date('Y-m-d', strtotime($data['renewal_date'])) ?? null;
+        $data['rollover_date'] = date('Y-m-d', strtotime($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;
+        }
+    
+        // 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 && $data['base_policy'] ? 3 : 1));
+    
+        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);
+
+                $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['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();
+            }
+    
+            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 (empty($data['client_policy_id']) || $data['client_policy_id'] == 0) {
+    
+                    $client_policy_insert_data = $this->prepareClientPolicyInsertData($data);
+                    // print_r($client_policy_insert_data); die;
+                    $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') {
+                    $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();
+            }
+    
+            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;
+
+        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' => isset($data['co_share_type'][$index]) ? 2 : 1,
+                '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_ter_premium'][$index] ?? 0,
+                'tep_amt' => $data['tp_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_ter'][$index] ?? 0,
+                'agreed_tep_per' => $data['agreed_tp_ter'][$index] ?? 0,
+                'standerd_bp_per' => $data['standard_bp'][$index] ?? 0,
+                'standerd_tp_per' => $data['standard_tp'][$index] ?? 0,
+                'standerd_tep_per' => $data['standard_tep'][$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,
+                '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,
+                'remark' => $data['remark'][$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($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;
+
+        return true;
+    }
+    
+    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, 
+                        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'] = !empty($data['policy_issue_date']) ? date('d-m-Y', strtotime($data['policy_issue_date'])) : null;
+        $data['policy_start_date'] = !empty($data['policy_start_date']) ? date('d-m-Y', strtotime($data['policy_start_date'])) : null;
+        $data['policy_end_date'] = !empty($data['policy_end_date']) ? date('d-m-Y', strtotime($data['policy_end_date'])) : null;
+        $data['renewal_date'] = !empty($data['renewal_date']) ? date('d-m-Y', strtotime($data['renewal_date'])) : null;
+        $data['rollover_date'] = !empty($data['rollover_date']) ? date('d-m-Y', strtotime($data['rollover_date'])) : null;
+        $data['created_at'] = !empty($data['created_at']) ? date('d-m-Y h:i:s A', strtotime($data['created_at'])) : null;
+        $data['updated_at'] = !empty($data['updated_at']) ? date('d-m-Y h:i:s A', strtotime($data['updated_at'])) : null;
+                
+        // 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'])
+            ->where('client_policy.policy_type_id', 2)
+            ->where('client_policy.is_active', 1)
+            ->findAll();
+
+        $data['pt_files'] = $this->PTFileModel->where('pt_id', $id)->where('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();
+
+        // 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()
+    {   
+        $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['endorsement_data_list'] = $this->policyTransactionModel
+            ->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,
+                        policy_type.policy_type 
+                    ')
+            ->join('clients', 'policy_transaction.client_id = clients.id', 'left')
+            ->join('client_branch', 'policy_transaction.client_branch_id = client_branch.id', 'left')
+            ->join('insurers', 'policy_transaction.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')
+            ->orderBy('policy_transaction.id', 'desc')
+            ->findAll(); 
+
+        $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();
+        // print_r($data);
+
+        $data_received_date = (string)$this->request->getPost('data_received_date');
+        $closure_date = (string)$this->request->getPost('closure_date');
+        $data['data_received_date'] = date('Y-m-d', strtotime($data_received_date));
+        $data['closure_date'] = date('Y-m-d', strtotime($closure_date));
+
+        // 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']);
+            }
+        }
+
+        $issue_type = $this->policyTransactionModel
+                        ->where('action_type', 'inception')
+                        ->where('client_id', $this->request->getPost('client_id'))
+                        ->where('client_branch_id', $this->request->getPost('client_branch_id'))
+                        ->first();
+        $data['tsi'] = generate_tsi_code($issue_type['issue_type'] ?? 1);
+
+        // 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') {
+
+            $tolamt = $data['total'][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, 
+                        client_policy.policy_start_date as s_date,
+                        client_policy.policy_end_date as e_date,
+                    ')
+                ->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'] = date('d-m-Y', strtotime($data['s_date']));
+        $data['policy_end_date'] = date('d-m-Y', strtotime($data['e_date']));
+        $data['data_received_date'] = date('d-m-Y', strtotime($data['data_received_date']));
+        $data['closure_date'] = date('d-m-Y', strtotime($data['closure_date']));
+
+        $data['pt_co_share_details'] = $this->PTCOShareDetailsModel->where('pt_id', $id)->where('is_active', 1)->findAll();
+
+
+        if($data){
+            return $this->respond(['status' => true, 'data' => $data], 200);
+        }else{
+            return $this->respond(['status' => false], 200);
+        }
+
+    }
+
+    //------------------------------------------------------------------------------------------------
+
+    //file upload function 
+    public function uploadFile()
+    {
+        $files = $this->request->getFiles();
+        $doc_name = $this->request->getPost('doc_name[]');     
+        $pt_id = $this->request->getPost('pt_id');     
+        
+        $uploadData = uploadFilesToGoogleDrive($files['file'], $doc_name, $pt_id);
+        $insert = false;
+        if(!isset($uploadData['status'])){
+            $this->PTFileModel->insertBatch($uploadData);
+            $insert = true;
+        }
+
+        if ($insert) {
+            $data['pt_files'] = $this->PTFileModel->where('pt_id', $pt_id)->where('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)
+            ->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);
+        }
+
+    }
+
+    //---------------------------------------------------------------------------------------------------
+
+    //get BDS Reports data
+    public function reportBDS()
+    {   
+
+        $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); 
+    }
+    
+    
+}
\ No newline at end of file
diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php
index 53d35bf1..8d68fc1a 100755
--- 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/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/oauth_helper.php b/app/Helpers/oauth_helper.php
index 6741f057..a16ef368 100755
--- 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/utility_helper.php b/app/Helpers/utility_helper.php
index da3f5f4c..6c7c6c1a 100755
--- a/app/Helpers/utility_helper.php
+++ b/app/Helpers/utility_helper.php
@@ -1,4 +1,6 @@
 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;
+    }
+}
+
+
 
 function numberToWords($number)
 {
diff --git a/app/Models/ClientModel.php b/app/Models/ClientModel.php
index 718e67a8..ce5481d3 100755
--- 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/PTCOShareDetailsModel.php b/app/Models/PTCOShareDetailsModel.php
new file mode 100644
index 00000000..070e7e1f
--- /dev/null
+++ b/app/Models/PTCOShareDetailsModel.php
@@ -0,0 +1,64 @@
+db->table('policy_transaction')
+            ->select("
+                policy_transaction.*,
+                DATE_FORMAT(policy_transaction.policy_issue_date, '%d %b %Y') AS policy_issue_date,
+                DATE_FORMAT(policy_transaction.policy_issue_date, '%b') 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.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)), 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)), 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)), 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)), 2) * 18 / 100), 2)), 
+                2) AS total_amt_received
+            ")
+            ->join('pt_co_share_details', 'policy_transaction.id = pt_co_share_details.pt_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', 'client_policy.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);
+        }
+
+        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);
+        }
+    
+        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 @@
+
+    
+
+
+
+
+ + + +
+
+
+
+ + + +
+ +
+ +
+ +
+ +
+
+
+
+
+ +
+
+
+ +
+
+
+
+

File List

+
+ +
+
+ + + + + + + + + + + +
S.NoDocs NameFile NameDrive File Location
+
+
+
+
+
+ + + + diff --git a/app/Views/insurer_export_templete.php b/app/Views/insurer_export_templete.php index 40b757a7..935b669d 100755 --- a/app/Views/insurer_export_templete.php +++ b/app/Views/insurer_export_templete.php @@ -48,7 +48,7 @@
- +
@@ -122,7 +122,7 @@