<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\RoleMasterModel;
use App\Models\VehicleTypeMasterModel;
use App\Models\InsurancePlanTypeMasterModel;
use App\Models\ClaimTypeModel;
use App\Models\EndorsementTypeModel;
use App\Models\InsurersModel;
use App\Models\StaffModel;
use App\Models\PartnerBrokerModel;
use App\Models\PaymentModeModel;
use App\Models\PartnerPosModel;
use App\Models\PolicyModel;


class MasterController extends ResourceController
{
    protected $format    = 'json';
    protected $myLogger;
    protected $RoleMasterModel;
    protected $VehicleTypeMasterModel;
    protected $InsurancePlanTypeMasterModel;
    protected $ClaimTypeModel;
    protected $EndorsementTypeModel;
    protected $InsurersModel;
    protected $StaffModel;
    protected $PartnerBrokerModel;
    protected $PaymentModeModel;
    protected $PartnerPosModel;
    protected $PolicyModel;
   

    public function __construct()
    {
        $this->myLogger = \Config\Services::mylogger();
        $this->RoleMasterModel = new RoleMasterModel();
        $this->VehicleTypeMasterModel = new VehicleTypeMasterModel();
        $this->InsurancePlanTypeMasterModel = new InsurancePlanTypeMasterModel();
        $this->ClaimTypeModel = new ClaimTypeModel();
        $this->EndorsementTypeModel = new EndorsementTypeModel();
        $this->InsurersModel = new InsurersModel();
        $this->StaffModel = new StaffModel();
        $this->PartnerBrokerModel = new PartnerBrokerModel();
        $this->PaymentModeModel = new PaymentModeModel();
        $this->PartnerPosModel = new PartnerPosModel();
         $this->PolicyModel = new PolicyModel();
       
    }

    public function app_test()
    {

        return $this->respond(['status' => 200,'message' => 'success','data' => []]);
    }


    public function getRoleMaster()
    {
        $data = $this->RoleMasterModel->whereIn('id',[1,2,3,4])->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }



    public function getInsurancePlanTypeMaster()
    {
        $data = $this->InsurancePlanTypeMasterModel->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getClaimMaster()
    {
        $data = $this->ClaimTypeModel->select('id,claim_type')->where('is_active',1)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getEndorsementMaster()
    {
        $data = $this->EndorsementTypeModel->select('id,endorsement_type')->where('is_active',1)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function getInsurersMaster()
    {
        $data = $this->InsurersModel->select('id,name,short_name')->where('is_active',1)->where('category','general')->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function saveInsurer()
    {
        $input = $this->request->getPost();

        if (empty($input['name'])) {
            return $this->respond(['status' => 404, 'message' => 'Insurer name is required', 'data' => []]);
        }

        if (empty($input['short_name'])) {
            return $this->respond(['status' => 404, 'message' => 'Insurer short name is required', 'data' => []]);
        }

        $id = !empty($input['id']) ? (int) $input['id'] : null;

        // Duplicate name check (case-insensitive)
        $nameQuery = $this->InsurersModel
            ->where('LOWER(name)', strtolower($input['name']))
            ->where('category', 'general');

        if ($id) {
            $nameQuery->where('id !=', $id);
        }

        if ($nameQuery->first()) {
            return $this->respond(['status' => 404, 'message' => 'Insurer name already exists', 'data' => []]);
        }

        // Duplicate short name check (case-insensitive)
        $shortNameQuery = $this->InsurersModel
            ->where('LOWER(short_name)', strtolower($input['short_name']))
            ->where('category', 'general');

        if ($id) {
            $shortNameQuery->where('id !=', $id);
        }

        if ($shortNameQuery->first()) {
            return $this->respond(['status' => 404, 'message' => 'Insurer short name already exists', 'data' => []]);
        }

        if ($id) {
            if (!$this->InsurersModel->find($id)) {
                return $this->respond(['status' => 404, 'message' => 'Record not found', 'data' => []]);
            }

            $data = [
                'name'       => $input['name'],
                'short_name' => $input['short_name'],
                'updated_by' => $input['updated_by'] ?? null,
            ];

            $this->InsurersModel->update($id, $data);

            $record = $this->InsurersModel->select('id,name,short_name')->find($id);

            return $this->respond(['status' => 200, 'message' => 'Insurer updated successfully', 'data' => $record]);
        }

        $data = [
            'name'       => $input['name'],
            'short_name' => $input['short_name'],
            'category'   => 'general',
            'is_active'  => 1,
            'created_by' => $input['created_by'] ?? null,
        ];

        $insertId = $this->InsurersModel->insert($data);
        $record = $this->InsurersModel->select('id,name,short_name')->find($insertId);

        return $this->respond(['status' => 200, 'message' => 'Insurer created successfully', 'data' => $record]);
    }

    public function getStaffMaster()
    {
        $data = $this->StaffModel->select('id,name')->where('is_active',1)->where('role_id',2)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    //Vehicle type CRUD---------------------------------------------------------------------
    public function getVehicleTypeMaster()
    {
        $valueFor = $this->request->getGet('value_for');

        if(isset($valueFor) && $valueFor == 'dropdown')
        {
            $isActive = [1];
        }else{
            $isActive = [0,1];
        }

        $data = $this->VehicleTypeMasterModel->whereIn('is_active',$isActive)->findAll();

        if (!$data) {
            return $this->failNotFound('No data found');
        }

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createVehicleType()
    {
        $input = $this->request->getJSON(true);

        if (empty($input['vehicle_type'])) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Value is required']);
        }

        // Duplicate check (case-insensitive)
        $exists = $this->VehicleTypeMasterModel
            ->where('LOWER(vehicle_type)', strtolower($input['vehicle_type']))
            // ->where('is_active', 1)
            ->first();

        if ($exists) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Vehicle Type already exists'
            ]);
        }

        $data = [
            'vehicle_type'  => $input['vehicle_type'],
            'is_active'     => 1,
            'created_by'    => $input['created_by'] ?? null,
        ];

        $this->VehicleTypeMasterModel->insert($data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Vehicle Type created successfully'
        ]);
    }

    public function updateVehicleType($id)
    {
        $input = $this->request->getJSON(true);

        if (!$this->VehicleTypeMasterModel->find((int)$id)) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        // Duplicate name check (excluding current record)
        $checkDuplicate = $this->VehicleTypeMasterModel
            ->where('LOWER(vehicle_type)', strtolower($input['vehicle_type']))
            ->where('id !=', $id)
            // ->where('is_active', 1)
            ->first();

        if ($checkDuplicate) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Vehicle Type already exists'
            ]);
        }

        $data = [
            'vehicle_type'  => $input['vehicle_type'] ,
            'updated_by'    => $input['updated_by'] ?? null,
        ];

        $this->VehicleTypeMasterModel->update($id, $data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Vehicle Type updated successfully'
        ]);
    }

    public function updateVehicleTypeStatus($id)
    {
        $input = $this->request->getJSON(true);

        if (!isset($input['is_active'])) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'is_active field is required'
            ]);
        }

        $record = $this->VehicleTypeMasterModel->find((int)$id);
        if (!$record) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        $status = ($input['is_active'] == 1) ? 0 : 1;

        $this->VehicleTypeMasterModel->update((int)$id, [
            'is_active'  => $status, 
            'updated_by' => $input['updated_by'] ?? null,
        ]);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Status updated successfully'
        ]);
    }


    //Broker CRUD---------------------------------------------------------------------------
    public function getAllBrokers()
    {
   
        $data = $this->PartnerBrokerModel->where('is_active', 1)->findAll();

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createBroker()
    {
        $input = $this->request->getJSON(true);

        if (empty($input['name'])) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Value is required']);
        }

        // Duplicate check (case-insensitive)
        $exists = $this->PartnerBrokerModel
            ->where('LOWER(name)', strtolower($input['name']))
            // ->where('is_active', 1)
            ->first();

        if ($exists) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Broker name already exists'
            ]);
        }

        $data = [
            'name'      => $input['name'],
            'short_name'      => $input['short_name'],
            'is_active'  => 1,
            'created_by' => $input['created_by'] ?? null,
        ];

        $this->PartnerBrokerModel->insert($data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Broker name created successfully'
        ]);
    }

    public function updateBroker($id)
    {
        $input = $this->request->getJSON(true);

        if (!$this->PartnerBrokerModel->find((int)$id)) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        // Duplicate name check (excluding current record)
        $checkDuplicate = $this->PartnerBrokerModel
            ->where('LOWER(name)', strtolower($input['name']))
            ->where('id !=', $id)
            // ->where('is_active', 1)
            ->first();

        if ($checkDuplicate) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Broker name already exists'
            ]);
        }

        $data = [
            'name'      => $input['name'] ,
            'short_name'=> $input['short_name'],
            'updated_by' => $input['updated_by'] ?? null,
        ];

        $this->PartnerBrokerModel->update($id, $data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Broker name updated successfully'
        ]);
    }

    public function updateBrokerStatus($id)
    {
        $input = $this->request->getJSON(true);

        if (!isset($input['is_active'])) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'is_active field is required'
            ]);
        }

        $record = $this->PartnerBrokerModel->find((int)$id);
        if (!$record) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        $status = ($input['is_active'] == 1) ? 0 : 1;

        $this->PartnerBrokerModel->update($id, [
            'is_active'  => $status, 
            'updated_by' => $input['updated_by'] ?? null,
        ]);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Status updated successfully'
        ]);
    }
    //---------------------------------------------------------------------------------------


    //Payment Mode CRUD----------------------------------------------------------------------
    public function getAllPaymentModelist()
    {
        $data = $this->PaymentModeModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll();

        return $this->response->setJSON(['status' => 200,'message' => 'success','data'   => $data]);
    }

    public function createPaymentMode()
    {
        $input = $this->request->getJSON(true);

        if (empty($input['value'])) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Value is required']);
        }

        // Duplicate check (case-insensitive)
        $exists = $this->PaymentModeModel
            ->where('LOWER(value)', strtolower($input['value']))
            // ->where('is_active', 1)
            ->first();

        if ($exists) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Payment Mode already exists'
            ]);
        }

        $data = [
            'value'      => $input['value'],
            'is_active'  => 1,
            'created_by' => $input['created_by'] ?? null,
        ];

        $this->PaymentModeModel->insert($data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Payment mode created successfully'
        ]);
    }

    public function updatePaymentMode($id)
    {
        $input = $this->request->getJSON(true);

        if (!$this->PaymentModeModel->find((int)$id)) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        // Duplicate name check (excluding current record)
        $checkDuplicate = $this->PaymentModeModel
            ->where('LOWER(value)', strtolower($input['value']))
            ->where('id !=', $id)
            // ->where('is_active', 1)
            ->first();

        if ($checkDuplicate) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'Payment Mode already exists'
            ]);
        }

        $data = [
            'value'      => $input['value'] ?? null,
            'updated_by' => $input['updated_by'] ?? null,
        ];

        $this->PaymentModeModel->update($id, $data);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Payment mode updated successfully'
        ]);
    }

    public function updatePaymentModeStatus($id)
    {
        $input = $this->request->getJSON(true);

        if (!isset($input['is_active'])) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'is_active field is required'
            ]);
        }

        $record = $this->PaymentModeModel->find((int)$id);
        if (!$record) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        $status = ($input['is_active'] == 1) ? 0 : 1;

        $this->PaymentModeModel->update($id, [
            'is_active'  => $status,
            'updated_by' => $input['updated_by'] ?? null,
        ]);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Status updated successfully'
        ]);
    }
    //---------------------------------------------------------------------------------------


    //POS CRUD---------------------------------------------------------------------------
    public function getAllPOS()
    {

        $is_active = $this->request->getGet('is_active');
        $manager_id = $this->request->getGet('manager_id');

        $data = $this->PartnerPosModel->where('is_active', $is_active)->where('manager_id', $manager_id)->findAll();

        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    //---------------------------------------------------------------------------------------

    //Endorsement CRUD Copied As Per Broker CRUD line No 136 ---------------------------------
    
    public function getAllEndorsement()
    {
        $data = $this->EndorsementTypeModel->where('is_active', 1)->findAll();
        return $this->respond(['status' => 200,'message' => 'success','data' => $data]);
    }

    public function createEndorsement()
    {
        $input = $this->request->getJSON(true);

        if (empty($input['endorsement_type'])) {
            return $this->respond([
                'status'  => 404, 
                'message' => 'Endorsement type is required'
            ]);
        }

        // Duplicate check (Case-insensitive) on endorsement_type
        $exists = $this->EndorsementTypeModel
            ->where('LOWER(endorsement_type)', strtolower($input['endorsement_type']))
            // ->where('is_active', 1)
            ->first();

        if ($exists) {
            return $this->respond([
                'status'  => 404,
                'message' => 'Endorsement type already exists'
            ]);
        }

        $data = [
            'endorsement_type' => $input['endorsement_type'],
            'is_active'        => 1,
        ];

        $this->EndorsementTypeModel->insert($data);

        return $this->respond([
            'status'  => 200,
            'message' => 'Endorsement type created successfully'
        ]);
    }

    public function updateEndorsement($id)
    {
        $input = $this->request->getJSON(true);

        if (!$this->EndorsementTypeModel->find((int)$id)) {
            return $this->respond([
                'status'  => 404, 
                'message' => 'Record not found'
            ]);
        }

        // Duplicate check excluding current ID
        $checkDuplicate = $this->EndorsementTypeModel
            ->where('LOWER(endorsement_type)', strtolower($input['endorsement_type']))
            ->where('id !=', $id)
            // ->where('is_active', 1)
            ->first();

        if ($checkDuplicate) {
            return $this->respond([
                'status'  => 404,
                'message' => 'Endorsement type already exists'
            ]);
        }

        $data = [
            'endorsement_type' => $input['endorsement_type'],
        ];

        $this->EndorsementTypeModel->update($id, $data);

        return $this->respond([
            'status'  => 200,
            'message' => 'Endorsement type updated successfully'
        ]);
    }

    public function updateEndorsementStatus($id)
    {
        $input = $this->request->getJSON(true);

        if (!isset($input['is_active'])) {
            return $this->response->setJSON([
                'status' => 404,
                'message' => 'is_active field is required'
            ]);
        }

        $record = $this->EndorsementTypeModel->find((int)$id);
        if (!$record) {
            return $this->response->setJSON(['status' => 404, 'message' => 'Record not found']);
        }

        $status = ($input['is_active'] == 1) ? 0 : 1;

        $this->EndorsementTypeModel->update($id, [
            'is_active'  => $status, 
            'updated_by' => $input['updated_by'] ?? null,
        ]);

        return $this->response->setJSON([
            'status' => 200,
            'message' => 'Status updated successfully'
        ]);
    }
   
    //---------------------------------------------------------------------------------------


    public function getHistoryOld()
    {
        $db = \Config\Database::connect();

        // -----------------------------
        // REQUEST VALIDATION
        // -----------------------------
        $tableName = $this->request->getGet('table_name');
        $pk        = $this->request->getGet('pk');

        if (!$tableName || !$pk) {
            return $this->response->setJSON([
                'status'  => 'failed',
                'message' => 'table_name and pk are required'
            ]);
        }

        // -----------------------------
        // QUERY
        // -----------------------------
        $history = $db->table('partner_audit_history pah')
            ->select("
                pah.column_name,
                pah.old_val,
                pah.new_val,
                pah.changed_on,
                ps.name AS changed_by
            ")
            ->join('partner_staff ps', 'ps.id = pah.user_id', 'left')
            ->where('pah.table_name', $tableName)
            ->where('pah.pk', $pk)
            ->orderBy('pah.changed_on', 'DESC')
            ->get()
            ->getResultArray();

        if (empty($history)) {
            return $this->response->setJSON([
                'status'  => 'success',
                'data'    => [],
                'message' => 'No audit history found'
            ]);
        }

        // -----------------------------
        // FORMAT RESPONSE (READABLE)
        // -----------------------------
        $result = [];

        foreach ($history as $row) {
            $result[] = [
                'column_name' => $row['column_name'],
                'message'     => "{$row['column_name']} data changed from "
                                . ($row['old_val'] ?? 'NULL')
                                . " to "
                                . ($row['new_val'] ?? 'NULL')
                                . " by "
                                . ($row['changed_by'] ?? 'System'),
                'changed_on'  => $row['changed_on'],
                'changed_by'  => $row['changed_by']
            ];
        }

        return $this->response->setJSON([
            'status' => 'success',
            'data'   => $result
        ]);
    }

    public function getHistory()
    {
        $db = \Config\Database::connect();

        $tableName = $this->request->getGet('table_name');
        $pk        = $this->request->getGet('pk');

        if (!$tableName || !$pk) {
            return $this->response->setJSON(['status' => 'failed', 'message' => 'table_name and pk are required']);
        }

        $history = $db->table('partner_audit_history pah')
            ->select("pah.column_name, pah.old_val, pah.new_val, pah.changed_on, ps.name AS changed_by")
            ->join('partner_staff ps', 'ps.id = pah.user_id', 'left')
            ->where(['pah.table_name' => $tableName, 'pah.pk' => $pk])
            ->orderBy('pah.changed_on', 'DESC')
            ->get()->getResultArray();

        if (empty($history)) {
            return $this->response->setJSON(['status' => 'success', 'data' => [], 'message' => 'No audit history found']);
        }

        $result = [];

        $ignoreColumns = [
            'updated_on', 
            'created_on', 
            'updated_by', 
            'created_by', 
            'client_id',
            'client_policy_id',
            'vehicle_id',
            'policy_transaction_id',
            'pt_oc_share_details_id',
            'id' // Usually PKs are ignored too
        ];

        foreach ($history as $row) {
            $column = $row['column_name'];

            // SKIP the iteration if the column is in our ignore list
            if (in_array($column, $ignoreColumns)) {
                continue; 
            }

            $formatted = $this->formatAuditRow($row);
            $label = $formatted['label'];
            $old   = $formatted['old'];
            $new   = $formatted['new'];
            $by    = $row['changed_by'] ?? 'System';

            // Professional Message logic
            if ($old === '-' || $old === '') {
                $message = "{$label} was set to **{$new}** by {$by}";
            } else {
                $message = "{$label} updated from '{$old}' to '{$new}' by {$by}";
            }

            $result[] = [
                // 'column_name' => $label,
                'column_name' => $column,
                'message'     => $message,
                'changed_on'  => $row['changed_on'] ? date("d-m-Y", strtotime($row['changed_on'])) : '',
                'changed_by'  => $by
            ];
        }

            return $this->response->setJSON(['status' => 'success', 'data' => $result]);
    }

    private function formatAuditRow($row)
    {
        $col = $row['column_name'];
        $old = $row['old_val'];
        $new = $row['new_val'];

        // Default formatting
        $label = ucwords(str_replace('_', ' ', $col));
        $fOld  = $old ?? '-';
        $fNew  = $new ?? '-';

        switch ($col) {
            // --- ID to Name Lookups ---
            case 'enquiry_id':
                $label = "Enquiry";
                $fOld = $this->fetchName('partner_enquiry', 'name', $old);
                $fNew = $this->fetchName('partner_enquiry', 'name', $new);
                break;

            case 'insurance_plan_type_id':
                $label = "Insurance Plan Type";
                $fOld = $this->fetchName('partner_insurance_plan_type_master', 'insurance_plan_type', $old);
                $fNew = $this->fetchName('partner_insurance_plan_type_master', 'insurance_plan_type', $new);
                break;

            case 'manager_id':
                $label = "Manager";
                $fOld = $this->fetchName('partner_staff', 'name', $old, ['role_id' => 1]);
                $fNew = $this->fetchName('partner_staff', 'name', $new, ['role_id' => 1]);
                break;

            case 'updated_by':
            case 'created_by':
            case 'assigned_to':
                $fOld = $this->fetchName('partner_staff', 'name', $old);
                $fNew = $this->fetchName('partner_staff', 'name', $new);
                break;

            case 'pos_id':
                $label = "POS";
                $fOld = $this->fetchName('partner_pos', 'name', $old);
                $fNew = $this->fetchName('partner_pos', 'name', $new);
                break;

            // --- Date Formatting ---
            case 'created_on':
            case 'updated_on':
            case 'issued_date':
            case 'start_date':
            case 'end_date':
            case 'date_of_registration':
            case 'enquiry_created_on':
                if($col == 'enquiry_created_on') $label = "Received Date";
                $fOld = ($old && $old != '0000-00-00') ? date("d-m-Y", strtotime($old)) : '-';
                $fNew = ($new && $new != '0000-00-00') ? date("d-m-Y", strtotime($new)) : '-';
                break;

            // --- Status / Boolean Mapping ---
            case 'is_active':
                $label = "Data Status";
                $fOld = ($old == 1) ? "ACTIVE" : "INACTIVE";
                $fNew = ($new == 1) ? "ACTIVE" : "INACTIVE";
                break;

            case 'is_invoice_generated':
            case 'is_data_accuracy_checked':
                $label = ($col == 'is_invoice_generated') ? "Invoice Generated" : "Data Accuracy Checked";
                $fOld = ($old == 1) ? "YES" : "NO";
                $fNew = ($new == 1) ? "YES" : "NO";
                break;

            case 'is_data_created_by_handler':
            case 'is_data_created_by_staff':
                $label = str_replace('Is ', '', $label);
                $map = [null => "-", 1 => "Yes", 0 => "No"];
                $fOld = $map[$old] ?? "-";
                $fNew = $map[$new] ?? "-";
                break;
            case 'broker_id':
                $label = "Broker";
                $fOld = $this->fetchName('partner_brokers', 'name', $old);
                $fNew = $this->fetchName('partner_brokers', 'name', $new);
                break;
            case 'insurer_id':
                $label = "Insurer";
                $fOld = $this->fetchName('insurers', 'name', $old);
                $fNew = $this->fetchName('insurers', 'name', $new);
                break;
             case 'payment_mode_id':
                $label = "Payment Mode";
                $fOld = $this->fetchName('partner_payment_mode_master', 'value', $old);
                $fNew = $this->fetchName('partner_payment_mode_master', 'value', $new);

            case 'insurer_branch_id':
                $label = "Insurer Branch";
                $fOld = $this->fetchName('insurer_branch', 'branch_name', $old);
                $fNew = $this->fetchName('insurer_branch', 'branch_name', $new);
            case 'vehicle_type_id':
                $label = "Vehicle Type";
                $fOld = $this->fetchName('vehicle_type', 'vehicle_type', $old);
                $fNew = $this->fetchName('vehicle_type', 'vehicle_type', $new);
            case 'agent_id':
                $label = "Partner";
                $fOld = $this->fetchName('partner_agent', 'name', $old);
                $fNew = $this->fetchName('partner_agent', 'name', $new);
        }

        return ['label' => $label, 'old' => $fOld, 'new' => $fNew];
    }

    private function fetchName($table, $nameCol, $id, $additionalWhere = [])
    {
        if (!$id) return '-';
        $db = \Config\Database::connect();
        $builder = $db->table($table);
        $builder->select($nameCol)->where('id', $id);
        foreach ($additionalWhere as $col => $val) {
            $builder->where($col, $val);
        }
        $result = $builder->get()->getRowArray();
        return $result[$nameCol] ?? '-';
    }


   
    













}
