myLogger = \Config\Services::mylogger(); $this->clientModel = new ClientModel(); $this->userModel = new UserModel(); $this->clientBranchModel = new ClientBranchModel(); $this->clientKYCDocsModel = new ClientKYCDocsModel(); $this->clientDepositModel = new ClientDepositModel(); $this->clientPolicyModel = new ClientPolicyModel(); $this->clientRMModel = new ClientRMModel(); $this->insurerBranchModel = new InsurerBranchModel(); $this->insurerModel = new InsurerModel(); $this->kycDocsModel = new KYCDocsModel(); $this->kycEntityTypeModel = new KYCEntityTypeModel(); $this->levelContactModel = new LevelContactModel(); $this->policesModel = new PolicesModel(); $this->tpaBranchModel = new TPABranchModel(); $this->tpaModel = new TPAModel(); $this->stateModel = new StateModel(); $this->policyGridModel = new PolicyGridModel(); $this->policyPremium1Model = new PolicyPremium1Model(); $this->policyPremium2Model = new PolicyPremium2Model(); $this->employeeModel = new EmployeeModel(); $this->employeePolicyModel = new EmployeePolicyModel(); $this->notificationModel = new NotificationModel(); $this->CDMasterModel = new CDMasterModel(); $this->policyTypeModel = new PolicyTypeModel(); $this->policyTransactionModel = new PolicyTransactionModel(); $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); $this->vehicleModel = new VehicleModel(); } public function Testing() //this function for only tsesting some logics not use for business logic { $emp_code = 'MGL-004'; $client_id = 77; $client_policy_id = 206; $array_list = []; $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $client_policy_id, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled']); if (count($find) > 0) { $array_list[] = $find; } // dd($array_list); $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_review_and_summary_mail')->first(); // dd($notification); if (isset($notification) && $notification['enabled'] == 1) { $params['array_list'] = $array_list; $params['client_policy_id'] = $client_policy_id; $params['emp_code'] = $emp_code; $params['client_id'] = $client_id; $params['notification'] = $notification; // print_r($params);die; $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); // print_r($wholeData); die; $mail_send_return = MailHelper::send_email($wholeData[0]); $this->myLogger->logme("info", $mail_send_return); if (isset($wholeData[0])) { $account_manager_wholeData = sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params); // print_r($account_manager_wholeData); die; if ($account_manager_wholeData) { foreach ($account_manager_wholeData as $key => $value) { $mail_send_return1 = MailHelper::send_email($value); $this->myLogger->logme("info", $mail_send_return1); $this->myLogger->logme("info", $mail_send_return1); } } $client_hr_wholeData = sendMailNotification::sendMailNotification('client_hr_summary_mail', $params); // print_r($client_hr_wholeData); die; if ($client_hr_wholeData) { foreach ($client_hr_wholeData as $key => $value) { $mail_send_return2 = MailHelper::send_email($value); $this->myLogger->logme("info", $mail_send_return2); } } } } return $this->respond(['status' => 'success', 'code' => 200, 'data' => []], 200); } public function index() { $this->myLogger->logme('error', 'Client list function called'); $headerData['page_name'] = 'Client List'; $data['clientList'] = $this->clientModel->getCreatedByUserName(); $data['client_rm'] = $this->clientRMModel->getAllClientRM(); // dd($data); echo view('layout/header', $headerData); echo view('client_list', $data); echo view('layout/footer'); // $this->loadLayout('client_onboarding', $data); } public function updateEmpAndPolicyStatus() { $return = $this->clientPolicyModel->updateStatus(); $this->myLogger->logme('error', 'Client Policy Status Update Count: {data}', ['data' => $return['client']]); $this->myLogger->logme('error', 'Employee Policy Status Update Count: {data}', ['data' => $return['emp']]); } public function updatePolicyTermsForCorrections() { $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(); $client_policy_ids = []; 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) { $client_policy_ids[] = $client_policy_id; $policy_terms['family_floaters']['parents'] = 0; $policy_terms['family_floaters']['parents-in-law'] = 0; $policy_terms['family_floaters']['either-parents-pil'] = 2; $results[$key]['policy_terms'] = json_encode($policy_terms); // Update the policy_terms in the database $this->clientPolicyModel ->where('id', $client_policy_id) ->set('policy_terms', $results[$key]['policy_terms']) ->update(); } } } if (count($client_policy_ids) > 0) { echo 'There are ' . count($client_policy_ids) . ' records to be updated.'; echo '
'; dd($client_policy_ids); } else { echo 'There is no records to be update.'; } // dd($results); } public function removeClient($id = null) { $this->myLogger->logme('error', 'Client Remove function called'); $client_policy_data = $this->clientPolicyModel ->where('policy_status', 1) ->where('Is_active', 1) ->where('client_id', $id) ->countAllResults(); if ($client_policy_data == 0) { $data['updated_by'] = get_session_userid(); $data['is_active'] = 0; $update = $this->clientModel->update($id, $data); return $this->respond(['status' => true, 'code' => 200], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Client has active policy'], 200); } } public function removeClientBranch($id = null) { $this->myLogger->logme('error', 'Client Branch Remove function called'); $data = [ 'updated_by' => get_session_userid(), 'is_active' => 0 ]; $config_count = $this->clientPolicyModel->where('client_branch_id', $id)->countAllResults(); if ($config_count > 0) { $update = $this->clientBranchModel->where('id', $id)->set($data)->update(); if ($update) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'Client branch removed successfully'], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove client branch'], 200); } } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'The client branch configuration with policy cannot be deleted.'], 200); } } public function clientOnboarding() { $this->myLogger->logme('error', 'Client Onboarding function called'); $headerData['page_name'] = 'Client Onboarding'; $data['entity'] = $this->kycEntityTypeModel->findAll(); $data['kyc_docs'] = $this->kycDocsModel->findAll(); $data['police'] = $this->policesModel->findAll(); $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $data['state'] = $this->stateModel->getAllStates(); $data['RM'] = $this->userModel->findAll(); $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;
        $data['placeHolders'] = ['member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];

        // dd($data['placeHolders']);

        echo view('layout/header', $headerData);
        echo view('client_onboarding', $data);
        echo view('layout/footer');
    }

    // In your controller
    public function deposit($id = null)
    {
        $headerData['page_name'] = 'Client Deposit';

        $data['clientName'] = $this->clientModel->where('id', $id)->find();
        $data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id);
        $data['depositsummary'] = $this->clientPolicyModel->getDepositlistsummary($id);

        // Fetch associated insurer names and balances
        $balances = $this->clientPolicyModel->getBalances($id);
        $data['balances'] = $balances;

        echo view('layout/header', $headerData);
        echo view('client_deposit_list', $data);
        echo view('layout/footer');
    }

    public function view_Deposit($insurerId)
    {
        // Load your model to fetch data based on $clientId and $insurerId
        // $subTypeOptions = [
        //     1 => 'Deposit',
        //     2 => 'Adjustment',
        //     3 => 'Refund',
        //     4 => 'Debit',
        // ];

        $subTypeOptions = [
            1 => 'Replenishment By Client',
            2 => 'Adjustment',
            3 => 'Refund From Deletion',
            4 => 'Debit',
            5 => 'Non EB',
            6 => 'Refund By Insurer',
            7 => 'Opening Amount',
            8 => 'Truncated',
        ];

        $data['subTypeOptions'] = $subTypeOptions;
        $headerData['page_name'] = 'Client Deposit';
        $loggedInUserID = get_session_userid();
        // $data['clientData']= $this->clientPolicyModel->getinsurerswithinsurenceid($insurerId);
        $clientId = $this->request->getGet('client_id');
        $data['insurerName'] = $this->insurerModel->getInsurerName($insurerId, $clientId);
        $data['depositdata'] = $this->clientPolicyModel->getdepositData($clientId, $insurerId);
        $data['clientData'] = $this->clientPolicyModel->getClientById($clientId);
        $data['deposiamount'] = $this->clientPolicyModel->getDepositSummary($clientId, $insurerId);

        // dd($data['depositdata']);

        // print_r($data['depositdata'] );die;
        // Load the view for the new list page;
        echo view('layout/header', $headerData);
        echo view('view_deposit', $data);
        echo view('layout/footer');
    }

    public function saveDeposit()
    {
        // Retrieve form data from POST request
        $loggedInUserID = get_session_userid();

        $client_id = $this->request->getPost('client_id');
        $insurer_id = $this->request->getPost('insurer_id');

        $CD_Account_Number = $this->CDMasterModel
            ->where('client_id', $client_id)
            ->where('insurer_id', $insurer_id)
            ->first();

        // Prepare the array with data
        $data = [
            'amount' => $this->request->getPost('amount'),
            'sub_type_id' => $this->request->getPost('sub_type_id'),
            'client_id' => $this->request->getPost('client_id'),
            'client_policy_id' => null,
            'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
            'endorsement_no' => null,
            'insurer_id' => $this->request->getPost('insurer_id'),
            'description' => $this->request->getPost('description'),
            'transaction_type' => $this->request->getPost('transaction_type') ?: 'Credit',
            'updated_by' => 1,
        ];


        // Call the saveDeposit function from DepositHelper
        $response = DepositHelper::saveDeposit($data, $loggedInUserID);


        // Return a boolean value based on success
        return $this->response->setJSON(['success' => $response['success']]);
    }

    public function editClientOnboarding($id = null)
    {

        $this->myLogger->logme('error', 'Edit Client Onboarding function called');
        $headerData['page_name'] = 'Edit Client Onboarding';

        $editData['RM']             = $this->userModel->findAll();
        $editData['tpa']            = $this->tpaBranchModel->getTpaBranchesWithTpaNames();
        $editData['state']          = $this->stateModel->getAllStates();
        $editData['police']         = $this->policesModel->findAll();
        $editData['entity']         = $this->kycEntityTypeModel->findAll();
        $editData['insurer']        = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
        $editData['kyc_docs']       = $this->kycDocsModel->findAll();
        $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']);

        $editData['client']           = $this->clientModel->where(['id' => $id])->first();
        $editData['client_kyc']       = $this->clientKYCDocsModel->where('client_id', $id)->findAll();
        $editData['client_branch']    = $this->clientBranchModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
        $editData['client_relation']  = $this->clientRMModel->where(['client_id' => $id, 'is_active' => 1])->findAll();
        $editData['client_branch']['role'] = get_role_id();
        $clientPoliceData = $this->clientPolicyModel->getClientPolicyByClientId($id);

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

            $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
            $clientPoliceData[$key]->open_date = date('d-M-Y', strtotime($value->open_date));
            $clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
            $clientPoliceData[$key]->close_date = date('d-M-Y', strtotime($value->close_date));
        }

        $editData['client_policy']    = $clientPoliceData;
        $editData['client_policy']['role'] = get_role_id();
        $editData['notification'] = $this->notificationModel->select('template_name,enabled')->where('client_id', $id)->findAll();
        $editData['placeHolders'] = ['member_name', 'nhance_logo', 'tpa_id', 'ecard_download_link', 'client_logo', 'policy_no', 'member_summary', 'app_link', 'post_enrollment_app_link', 'client_name'];

        // dd($editData);
        echo view('layout/header', $headerData);
        echo view('client_onboarding', $editData);
        echo view('layout/footer');
    }

    public function createClientGeneralInfo()
    {

        $this->myLogger->logme('error', 'Client general info function called');
        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath);
        $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'])) {
            $data['is_download_btn'] = 0;
        } elseif ($data['is_download_btn']) {
            $data['is_download_btn'] = 1;
        }

        $insert = $this->clientModel->insert($data);
        if ($insert) {
            $client_data = $this->clientModel->where(['id' => $insert, 'is_active' => 1])->first();
            return $this->respond(['status' => true, 'code' => 200, 'data' => $client_data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function editClientGeneralInfo()
    {
        $this->myLogger->logme('error', 'edit client general info function called');
        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath);
        $id                 = $this->request->getPost('PrimaryKey');

        $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();

        if (!empty($file_name)) {
            $data['client_logo'] = $file_name;
        }

        if (!isset($data['is_download_btn'])) {
            $data['is_download_btn'] = 0;
        } elseif ($data['is_download_btn']) {
            $data['is_download_btn'] = 1;
        }

        // print_r($data);die;

        $update             = $this->clientModel->update($id, $data);


        if ($update) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }



    public function createClientKYCInfo()
    {
        $this->myLogger->logme('error', 'create Client kyc function called');
        $data = $this->request->getPost();
        // print_r($data); die;
        unset($data['file_name']);
        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
        $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath);
        if (!empty($File)) {

            $data['file_name'] = $File;
            // $uploadFilePath = $uploadFilePath . '/' . $File;
            // $GoogleDriveController = new GoogleDriveController();
            // $GoogleDriveController->uploadFiletoGdrive(client_id: $data['client_id'], doc_type: 'KYC', file_path: $uploadFilePath, file_name: $data['file_name']);
        }

        $data['created_by'] = get_session_userid();
        $insert = $this->clientKYCDocsModel->insert($data);
        if ($insert) {

            $kycDocs = $this->clientKYCDocsModel->where('client_id', $this->request->getPost('client_id'))->findAll();
            return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs, 'file_name' => $File], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function editClientKYCInfo()
    {

        $this->myLogger->logme('error', 'edit client kyc function called');
        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
        $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath);
        if (!empty($File)) {
            $data['file_name'] = $File;
        }
        $id                 = $this->request->getPost('PrimaryKey');
        $data['client_id']  = $id;
        $data['kyc_doc_type_id'] = $this->request->getPost('kyc_doc_id');
        $data['updated_by'] = get_session_userid();
        $insert = $this->clientKYCDocsModel->insert($data);
        if ($insert) {
            $kycDocs = $this->clientKYCDocsModel->getKycDocsName($id);
            return $this->respond(['status' => true, 'code' => 200, 'data' => $kycDocs], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function deleteClientKycDocs($id = null)
    {

        $delete = $this->clientKYCDocsModel->where('kyc_doc_type_id', $id)->delete();
        if ($delete) {
            return $this->respond(['status' => true, 'code' => 200, 'id' => $id], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function deleteClientKycOtherDocs($id = null)
    {

        $delete = $this->clientKYCDocsModel->where('id', $id)->delete();
        if ($delete) {
            return $this->respond(['status' => true, 'code' => 200, 'id' => $id], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }



    public function createClientRelation()
    {

        $this->myLogger->logme('error', 'Client relation function called');

        $data['client_id'] = $this->request->getPost('client_id');
        $data['created_by'] = get_session_userid();
        $inserted = false;

        if ($this->request->getPost('head')) {
            $data['level'] = "1";
            $data['user_id'] = $this->request->getPost('head');
            $inserted = $this->clientRMModel->insert($data);
        }

        if ($this->request->getPost('manager')) {
            $data['level'] = "2";
            $data['user_id'] = $this->request->getPost('manager');
            $inserted = $this->clientRMModel->insert($data);
        }

        if ($this->request->getPost('account_manager')) {
            $data['level'] = "3";
            foreach ($this->request->getPost('account_manager') as $value) {
                $data['user_id'] = $value;
                $inserted = $this->clientRMModel->insert($data);
            }
        }

        if ($inserted) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $this->request->getPost()], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function editClientRelation()
    {
        $this->myLogger->logme('error', 'Client relation function called');

        $id                 = $this->request->getPost('PrimaryKey');
        $data['client_id']  = $this->request->getPost('client_id');
        $data['updated_by'] = get_session_userid();
        $inserted = false;

        if ($this->request->getPost('head')) {
            $data['user_id'] = $this->request->getPost('head');
            $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('head'), 1);
            if ($checkHead) {
                $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 1)->set($data)->update();
            } else {
                $data['level'] = "1";
                $data['user_id'] = $this->request->getPost('head');
                $inserted = $this->clientRMModel->insert($data);
            }
        }

        if ($this->request->getPost('manager')) {
            $data['user_id'] = $this->request->getPost('manager');
            $checkHead = $this->clientRMModel->checkExistenceOfClientRelation($id, $this->request->getPost('manager'), 2);
            if ($checkHead) {
                $inserted = $this->clientRMModel->where('client_id', $id)->where('level', 2)->set($data)->update();
            } else {
                $data['level'] = "2";
                $data['user_id'] = $this->request->getPost('manager');
                $inserted = $this->clientRMModel->insert($data);
            }
        }

        if ($this->request->getPost('account_manager')) {

            $this->clientRMModel->where('client_id', $id)->where('level', 3)->delete();
            $data['level'] = "3";
            foreach ($this->request->getPost('account_manager') as $value) {
                $data['user_id'] = $value;
                $inserted = $this->clientRMModel->insert($data);
            }
        }

        $lastQuery = $this->clientRMModel->getLastQuery();

        if ($inserted) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $this->request->getPost(), "place" => 'edit'], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, "place" => 'edit', 'message' => 'no data found'], 200);
        }
    }


    public function createClientBranch()
    {

        $this->myLogger->logme('error', 'Client branch CREATE function called');
        $data   = $this->request->getPost();
        // var_dump($data); die;
        if (!isset($data['sez'])) {
            $data['sez'] = 0;
        } elseif ($data['sez']) {
            $data['sez'] = 1;
        }

        $units = json_decode($data['units'], true) ?? [];

        if (!is_array($units) || empty($units)) {
            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
            $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
            $data['units'] = json_encode([$default_unit]);
        }

        $data['created_by'] = get_session_userid();
        $insert = $this->clientBranchModel->insert($data);

        if ($insert) {
            for ($i = 0; $i < count($this->request->getPost('name')); $i++) {
                // Prepare data to insert
                $data = [
                    'contact_type' => 'client',
                    'ref_id'       => $insert,
                    'created_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if ($insert) {
            $branchData = $this->clientBranchModel->where('client_id', $this->request->getPost('client_id'))->findAll();
            $branchData['role'] = get_role_id();
            return $this->respond([
                'status' => true,
                'code' => 200,
                'data' => $branchData,
                'message' => 'Client branch created successfully',
            ], 200);
        } else {
            return $this->respond([
                'status' => false,
                'code' => 404,
                'message' => 'Failed to create client branch ',
            ], 200);
        }
    }

    public function editClientBranch()
    {

        $this->myLogger->logme('error', 'Client branch EDIT function called');
        $id     = $this->request->getPost('branch_id_primarykey');
        $client_id     = $this->request->getPost('client_id');
        $data   = $this->request->getPost();
        $units   = $this->request->getPost('units');

        $emp_unit_count = 0;
        $rr_unit_count = 0;
        $rr_unit_count2 = 0;
        $total_count = 0;

        $list_of_branch_units = $this->clientBranchModel->find($id);
        $units = json_decode($list_of_branch_units['units']);

        if (!is_array($units) || empty($units)) {
            $client_data = $this->clientModel->where('id', $data['client_id'])->first();
            $default_unit = trim(($client_data['short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-');
            $data['units'] = json_encode([$default_unit]);
        }

        if (!empty($units)) {
            foreach ($units as $unit) {
                $emp_unit_count += $this->employeeModel->where('unit', $unit)->countAllResults();
                $rr_unit_count += $this->policyPremium2Model->where('unit', $unit)->countAllResults();
                $rr_unit_count2 += $this->policyPremium1Model->where('unit', $unit)->countAllResults();
            }

            $total_count = $emp_unit_count + $rr_unit_count + $rr_unit_count2;
        }

        $uncommonValues = [];

        if ($total_count > 0) {
            $units = (string) $this->request->getPost('units'); // Assuming 'units' is an array

            $list_of_branch_units = $this->clientBranchModel->find($id);
            $branch_units = json_decode($list_of_branch_units['units'], true);
            $units = json_decode($units);

            $uncommonValues = array_diff($branch_units, $units);

            if (count($uncommonValues) > 0) {

                $branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();

                return $this->respond([
                    'status' => false,
                    'code' => 404,
                    'message' => "Deleted unit(s) in use. couldn't complete this operation.",
                    'uncommonValues' => $uncommonValues,
                    'data' => $branchData,
                ], 200);
            }
        }

        if (!isset($data['sez'])) {
            $data['sez'] = 0;
        } elseif ($data['sez']) {
            $data['sez'] = 1;
        }

        $data['updated_by'] = get_session_userid();
        $insert = $this->clientBranchModel->update($id, $data);
        $this->myLogger->logme('error', 'Client branch EDITED by {data}', ['data' => get_session_userid()]);


        if ($insert) {

            $this->levelContactModel->where('ref_id', $id)->where('contact_type', 'client')->delete();
            for ($i = 0; $i < count($this->request->getPost('name')); $i++) {
                $data = [
                    'contact_type' => 'client',
                    'ref_id'       => $id,
                    'updated_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if ($insert) {
            $branchData = $this->clientBranchModel->where('client_id', $client_id)->findAll();
            return $this->respond([
                'status' => true,
                'code' => 200,
                'data' => $branchData,
                'emp_unit_count' => $emp_unit_count,
                'rr_unit_count' => $rr_unit_count,
                'list_of_branch_units' => $list_of_branch_units,
                'total_count' => $total_count,
                'uncommonValues' => $uncommonValues,
                'message' => 'Client branch updated successfully'

            ], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update client branch'], 200);
        }
    }



    public function createClientPolicy()
    {

        // print_r($this->request->getPost()); die;


        $this->myLogger->logme('error', 'Client policy CREATE function called');

        $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');
        $base_policy      = $this->request->getPost('base_policy');


        $insurerValue  = (string) $this->request->getPost('insurer');
        list($insurerBranchId, $insurerId) = explode('-', $insurerValue);


        $data['insurer_branch_id'] = $insurerBranchId;
        $data['insurer_id']        = $insurerId;

        $tpaValue = (string) $this->request->getPost('tpa');

        if ($tpaValue === null || $tpaValue === '') {
            $tpaBranchId = null;
            $tpaId = null;
        } else {
            list($tpaBranchId, $tpaId) = explode('-', $tpaValue);
        }


        $data['client_id']         = $client_id;
        $data['tpa_branch_id']     = $tpaBranchId;
        $data['tpa_id']            = $tpaId;
        $data['policy_type_id']    = $this->request->getPost('policy_type_id');

        $data['no_of_lives']                        = $this->request->getPost('no_of_lives');
        $data['policy_status']                      = $this->request->getPost('policy_status');
        $data['no_of_employees']                    = $this->request->getPost('no_of_employees');
        $data['earned_premium_date']                = change_date_format($this->request->getPost('earned_premium_date'), 'd-m-Y', 'Y-m-d')  ?? null;
        $data['claims_incurred_date']               = change_date_format($this->request->getPost('claims_incurred_date'), 'd-m-Y', 'Y-m-d') ?? null;
        $data['incurred_claims_ratio']              = $this->request->getPost('incurred_claims_ratio');
        $data['no_lives_at_inception']              = $this->request->getPost('no_lives_at_inception');
        $data['premium_paid_at_inception']          = $this->request->getPost('premium_paid_at_inception');
        $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years');
        $data['earned_premium_amount']              = $this->request->getPost('earned_premium_amount');
        $data['claims_incurred_amount']             = $this->request->getPost('claims_incurred_amount');
        $data['base_policy']                        = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy');
        $data['policy_status']                      = 1;
        $data['inception_type']                     = $this->request->getPost('inception_type') ? 2 : 1;
        $data['client_branch_id']                   = $this->request->getPost('client_branch_id');
        $data['cd_ac_no']                           = $this->request->getPost('cd_ac_no');
        $data['gst']                                = $this->request->getPost('gst');


        if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {

            $data['is_addon'] = 1; // Base Policy

        } else if ($policy_type_id == 4 || $policy_type_id == 5) {

            $data['is_addon'] = 2; // SI TOPUP

        } else if ($policy_type_id == 3) {

            if ($base_policy) {
                $data['is_addon'] = 3; // Dependent Addon
            } else {
                $data['is_addon'] = 1;
            }
        }


        $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');
        $data['policy_no'] = $this->request->getPost('policy_no');
        if ($data['inception_type'] == 2) {
            $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d');
            $data['close_date']   = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d');
            $data['reminder_date']   = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d');
        } else {
            $data['open_date'] = null;
            $data['closedate'] = null;
            $data['reminder_date'] = null;
        }

        $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);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function editClientPolicy()
    {

        $this->myLogger->logme('error', 'Client policy function called');


        $id        = $this->request->getPost('PrimaryKey');
        $client_id = $this->request->getPost('client_id');
        $policy_type_id = $this->request->getPost('policy_type_id');
        $base_policy      = $this->request->getPost('base_policy');


        $insurerValue                      = (string) $this->request->getPost('insurer');
        list($insurerBranchId, $insurerId) = explode('-', $insurerValue);

        $data['insurer_branch_id'] = $insurerBranchId;
        $data['insurer_id']        = $insurerId;

        $tpaValue                  = (string) $this->request->getPost('tpa');
        list($tpaBranchId, $tpaId) = explode('-', $tpaValue);

        $data['tpa_branch_id']     = $tpaBranchId;
        $data['client_id']         = $client_id;
        $data['tpa_id']            = $tpaId;
        $data['policy_type_id']    = $this->request->getPost('policy_type_id');
        $data['policy_no'] = $this->request->getPost('policy_no');
        // $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');

        $data['insured']                            = $this->request->getPost('insured');
        $data['no_of_lives']                        = $this->request->getPost('no_of_lives');
        $data['policy_status']                      = $this->request->getPost('policy_status');
        $data['no_of_employees']                    = $this->request->getPost('no_of_employees');
        $data['earned_premium_date']                = change_date_format($this->request->getPost('earned_premium_date'), 'd-m-Y', 'Y-m-d') ?? null;
        $data['claims_incurred_date']               = change_date_format($this->request->getPost('claims_incurred_date'), 'd-m-Y', 'Y-m-d') ?? null;
        $data['incurred_claims_ratio']              = $this->request->getPost('incurred_claims_ratio');
        $data['no_lives_at_inception']              = $this->request->getPost('no_lives_at_inception');
        $data['premium_paid_at_inception']          = $this->request->getPost('premium_paid_at_inception');
        $data['claims_experience_for_last_3_years'] = $this->request->getPost('claims_experience_for_last_3_years');
        $data['earned_premium_amount']              = $this->request->getPost('earned_premium_amount');
        $data['claims_incurred_amount']             = $this->request->getPost('claims_incurred_amount');
        $data['base_policy']                        = ($this->request->getPost('base_policy') === '' || $this->request->getPost('base_policy') == 0) ? null : $this->request->getPost('base_policy');
        $data['policy_status']                      = 1;
        $data['inception_type']                     = $this->request->getPost('inception_type') ? 2 : 1;
        $data['enrolment_visibility']               = $this->request->getPost('enrolment_visibility') ? 1 : 0;
        $data['client_branch_id']                   = $this->request->getPost('client_branch_id');
        $data['cd_ac_no']                           = $this->request->getPost('cd_ac_no');
        $data['gst']                                = $this->request->getPost('gst');
        $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');

        if ($data['inception_type'] == 2) {
            $data['open_date'] = change_date_format($this->request->getPost('open_date'), 'd-m-Y', 'Y-m-d');
            $data['close_date']   = change_date_format($this->request->getPost('close_date'), 'd-m-Y', 'Y-m-d');
            $data['reminder_date']   = change_date_format($this->request->getPost('reminder_date'), 'd-m-Y', 'Y-m-d');
        } else {
            $data['open_date'] = null;
            $data['close_date'] = null;
            $data['reminder_date'] = null;
        }

        // if($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 3 || $policy_type_id == 6 || $policy_type_id == 7){

        //     $data['is_addon'] = 1;

        // }else if($policy_type_id == 4){

        //     $data['is_addon'] = 2;

        // }else if($policy_type_id == 5){

        //     $data['is_addon'] = 3;
        // }

        if ($policy_type_id == 1 || $policy_type_id == 2 || $policy_type_id == 6 || $policy_type_id == 7) {

            $data['is_addon'] = 1; // Base Policy

        } else if ($policy_type_id == 4 || $policy_type_id == 5) {

            $data['is_addon'] = 2; // SI TOPUP

        } else if ($policy_type_id == 3) {

            if ($base_policy) {
                $data['is_addon'] = 3; // Dependent Addon
            } else {
                $data['is_addon'] = 1;
            }
        }



        $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 {
        //         $data['policy_terms'] =  $policy_terms['policy_terms'];
        //     }


        // } 

        // dd($data);
        $data['updated_by'] = get_session_userid();
        // print_r(json_encode($data));die;
        $insert = $this->clientPolicyModel->update($id, $data);
        $lastQuery = $this->clientPolicyModel->getLastQuery();

        // echo '
';
        // print_r($data); die;

        if ($insert) {
            $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
            $clientPoliceData['role'] = get_role_id();
            // foreach ($clientPoliceData as $key => $value) {

            //     $clientPoliceData[$key]->policy_start_date = date('d-M-Y', strtotime($value->policy_start_date));
            //     $clientPoliceData[$key]->policy_end_date = date('d-M-Y', strtotime($value->policy_end_date));
            // }
            return $this->respond(['status' => true, 'code' => 200, 'data' => $clientPoliceData, 'method' => 'EDIT'], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function removePolicy($id = null)
    {
        $this->myLogger->logme('error', 'Client Policy Remove function called');

        $data = [
            'updated_by' => get_session_userid(),
            'is_active' => 0
        ];

        $emp_details = $this->employeePolicyModel
            ->join('employees', 'employees.id = employee_polices.employee_id')
            ->where('client_policy_id', $id)
            ->where('employee_polices.status', 'active')
            ->where('employee_polices.is_active', 1)
            ->where('employees.emp_status', 'active')
            ->where('employees.is_active', 1)
            ->countAllResults();
        if ($emp_details == 0) {

            $update = $this->clientPolicyModel->where('id', $id)->set($data)->update();

            if ($update) {
                return $this->respond(['status' => true, 'code' => 200], 200);
            } else {
                return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove policy'], 200);
            }
        } else {

            return $this->respond(['status' => false, 'code' => 404, 'message' => 'The policy has active employees'], 200);
        }
    }

    public function createClientPolicyPremium()
    {

        // echo json_encode(['key' => $this->request->getPost()]); die;

        try {
            $client_id = $this->request->getPost('client_id');
            $client_policy_id = $this->request->getPost('client_policy_id');
            $record    = $this->clientPolicyModel->where('client_policy.id', $client_policy_id)->first();
            $premium_type = $this->request->getPost('premium_type');
            if (!empty($client_id) && $client_id != null) {
                $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
                $client_id =  $client_policy_data['client_id'];
            }

            $branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']);
            $branch_units = json_decode($branch_units);

            $policy_grid_id = $this->request->getPost('policy_grid_id');
            $rack_rate_name = $this->request->getPost('rack_rate_name');

            $relation_data = [
                'self'          => $this->request->getPost('self') ?? 'NA',
                'spouse'        => $this->request->getPost('spouse') ?? 'NA',
                'childrens'     => $this->request->getPost('childrens') ?? 'NA',
                'parents'       => $this->request->getPost('parents') ?? 'NA',
                'parents-in-law' => $this->request->getPost('parents-in-law') ?? 'NA',
            ];

            $relation_data_for_form_submit_check = [
                $rack_rate_name => [
                    'self'          => $this->request->getPost('self') ?? 'NA',
                    'spouse'        => $this->request->getPost('spouse') ?? 'NA',
                    'childrens'     => $this->request->getPost('childrens') ?? 'NA',
                    'parents'       => $this->request->getPost('parents') ?? 'NA',
                    'parents-in-law' => $this->request->getPost('parents-in-law') ?? 'NA',
                ]
            ];

            if ($policy_grid_id == 1 || $policy_grid_id == 2) {
                $relation_data = [
                    'self'          => 1,
                    'spouse'        => 'NA',
                    'childrens'     => 'NA',
                    'parents'       => 'NA',
                    'parents-in-law' => 'NA',
                ];
            }

            // Convert to JSON
            $jsonDataForRelation = json_encode($relation_data);
            $json_data_relation_data_for_form_submit_check = json_encode($relation_data_for_form_submit_check);

            $si_or_bp = $this->request->getPost('si_or_bp');
            $basic_multiplier = str_replace(',', '', $this->request->getPost('basic_multiplier'));
            $premium_multiplier = str_replace(',', '', $this->request->getPost('premium_multiplier'));
            $multiplier = str_replace(',', '', $this->request->getPost('multiplier'));
            $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay'));

            $data = [];
            $data['client_id'] = $client_id;
            $data['client_policy_id'] = $client_policy_id;
            $data['policy_grid_id'] = $policy_grid_id;
            $data['premium_type'] = $premium_type;
            $data['rack_rate_name'] = $rack_rate_name;
            $data['additional_relationship'] = $jsonDataForRelation;

            $premium = [];

            if ($policy_grid_id == '1' || $policy_grid_id == '2') {
                $this->policyPremium1Model->where('client_id', $client_id)->where('client_policy_id', $client_policy_id)->set('is_active', 0)->update();
            } else {
                $this->policyPremium2Model->where('client_id', $client_id)->where('client_policy_id', $client_policy_id)->where('rack_rate_name', $rack_rate_name)->set('is_active', 0)->update();
            }

            if ($policy_grid_id == '1') {

                if ($si_or_bp == '1') {

                    $premium = str_replace(',', '', $this->request->getPost('gpa_sum_premium[]'));
                    $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si[]'));
                    $multiplier = $this->request->getPost('gpa_sum_multiplier');
                    $unit = $this->request->getPost('gpa_unit_1[]');

                    for ($i = 0; $i < count($premium); $i++) {
                        $data['si'] = $sum_insure[$i];
                        $data['premium'] = $premium[$i];
                        $data['multiplier'] = $multiplier;
                        $data['si_or_bp'] = $this->request->getPost('si_or_bp');
                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                            $data['unit'] = $branch_units[0];
                        } else {
                            $data['unit'] = $unit[$i];
                        }

                        $policyPremium = $this->policyPremium1Model->insert($data);
                    }
                } else if ($si_or_bp == '3') {

                    $premium = str_replace(',', '', $this->request->getPost('gpa_sum_premium2[]'));
                    $sum_insure = str_replace(',', '', $this->request->getPost('gpa_sum_si2[]'));
                    $multiplier = $this->request->getPost('gpa_sum_multiplier2');
                    $grade = $this->request->getPost('gpa_band[]');
                    $unit = $this->request->getPost('gpa_unit_3[]');


                    for ($i = 0; $i < count($premium); $i++) {
                        $data['si'] = $sum_insure[$i];
                        $data['premium'] = $premium[$i];
                        $data['grade'] = $grade[$i];
                        $data['multiplier'] = $multiplier;
                        $data['si_or_bp'] = $this->request->getPost('si_or_bp');
                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                            $data['unit'] = $branch_units[0];
                        } else {
                            $data['unit'] = $unit[$i];
                        }

                        $policyPremium = $this->policyPremium1Model->insert($data);
                    }
                } else if ($si_or_bp == '2') {

                    $premium = str_replace(',', '', $this->request->getPost('gpa_basic_premium[]'));
                    $sum_insure = str_replace(',', '', $this->request->getPost('gpa_basic_si[]'));
                    $basic_pay = str_replace(',', '', $this->request->getPost('basic_pay[]'));
                    $unit = $this->request->getPost('gpa_unit[]');


                    for ($i = 0; $i < count($premium); $i++) {

                        $data['si_or_bp'] = $this->request->getPost('si_or_bp');
                        $data['basic_multiplier'] = str_replace(',', '', $this->request->getPost('basic_multiplier'));
                        $data['multiplier'] = $this->request->getPost('premium_multiplier');
                        $data['basic_pay'] = $basic_pay[$i];
                        $data['si'] = $sum_insure[$i];
                        $data['premium'] = $premium[$i];
                        if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                            $data['unit'] = $branch_units[0];
                        } else {
                            $data['unit'] = $unit[$i];
                        }

                        $policyPremium = $this->policyPremium1Model->insert($data);
                    }
                } else {

                    $data['premium'] = str_replace(',', '', $this->request->getPost('gpa_basic_premium'));
                    $data['si'] = str_replace(',', '', $this->request->getPost('gpa_basic_si'));
                    $data['basic_multiplier'] = str_replace(',', '', $this->request->getPost('basic_multiplier'));
                    $data['multiplier'] = $this->request->getPost('premium_multiplier');
                    $data['basic_pay'] = str_replace(',', '', $this->request->getPost('basic_pay'));
                    $data['si_or_bp'] = $this->request->getPost('si_or_bp');

                    $policyPremium = $this->policyPremium1Model->insert($data);
                }

                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '2') {

                $premium = $this->request->getPost('gpa_premium29[]');
                $sum_insure = $this->request->getPost('gpa_si29[]');
                $unit = $this->request->getPost('gpa_unit29[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }
                    $dataa = $this->policyPremium1Model->insert($data);
                }

                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '3') {

                $premium = $this->request->getPost('3_premium[]');
                $sum_insure = $this->request->getPost('3_si[]');
                $unit = $this->request->getPost('3_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }
                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '4') {

                $premium = $this->request->getPost('4_premium[]');
                $sum_insure = $this->request->getPost('4_si');
                $age_from = $this->request->getPost('4_age_from[]');
                $age_to = $this->request->getPost('4_age_to[]');
                $unit = $this->request->getPost('4_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '5') {

                $premium = $this->request->getPost('5_premium[]');
                $sum_insure = $this->request->getPost('5_si[]');
                $age_from = $this->request->getPost('5_age_from[]');
                $age_to = $this->request->getPost('5_age_to[]');
                $unit = $this->request->getPost('5_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i] || $unit[$i] == 'undefined')) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }

                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '6') {

                $premium = $this->request->getPost('6_premium[]');
                $sum_insure = $this->request->getPost('6_si');
                $age_from = $this->request->getPost('6_age_from[]');
                $age_to = $this->request->getPost('6_age_to[]');
                $unit = $this->request->getPost('6_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '7') {
                $premium = $this->request->getPost('7_premium[]');
                $sum_insure = $this->request->getPost('7_si[]');
                $age_from = $this->request->getPost('7_age_from[]');
                $age_to = $this->request->getPost('7_age_to[]');
                $unit = $this->request->getPost('7_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '8') {
                $premium = $this->request->getPost('8_premium[]');
                $sum_insure = $this->request->getPost('8_si[]');
                $grade = $this->request->getPost('8_grade[]');
                $unit = $this->request->getPost('8_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['grade'] = $grade[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '9') {

                $premium = $this->request->getPost('gpa_premium29[]');
                $sum_insure = $this->request->getPost('gpa_si29[]');
                $unit = $this->request->getPost('gpa_unit29[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }
                    $dataa = $this->policyPremium2Model->insert($data);
                }

                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '10') {
                $premium = $this->request->getPost('10_premium[]');
                $sum_insure = $this->request->getPost('10_si[]');
                $age_from = $this->request->getPost('10_age_from[]');
                $age_to = $this->request->getPost('10_age_to[]');
                $unit = $this->request->getPost('10_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }


                    $policyPremium = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '11') {

                $premium = $this->request->getPost('11_premium[]');
                $sum_insure = $this->request->getPost('11_si[]');
                $grade = $this->request->getPost('11_grade[]');
                $max_sum_insure = $this->request->getPost('11_max_si[]');
                $unit = $this->request->getPost('11_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['grade'] = $grade[$i];
                    $data['max_si'] = str_replace(',', '', $max_sum_insure[$i]);
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '12') {

                $premium = $this->request->getPost('12_premium[]');
                $sum_insure = $this->request->getPost('12_si[]');
                $relationship = $this->request->getPost('12_relationship[]');
                $unit = $this->request->getPost('12_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['relationship'] = $relationship[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            } else if ($policy_grid_id == '13') {

                $premium = $this->request->getPost('13_premium[]');
                $sum_insure = $this->request->getPost('13_si[]');
                $age_from = $this->request->getPost('13_age_from[]');
                $age_to = $this->request->getPost('13_age_to[]');
                $relationship = $this->request->getPost('13_relationship[]');
                $unit = $this->request->getPost('13_unit[]');

                for ($i = 0; $i < count($premium); $i++) {
                    $data['premium'] = str_replace(',', '', $premium[$i]);
                    $data['si'] = str_replace(',', '', $sum_insure[$i]);
                    $data['age_from'] = $age_from[$i];
                    $data['age_to'] = $age_to[$i];
                    $data['relationship'] = $relationship[$i];
                    if (empty($unit) || !isset($unit[$i]) || empty($unit[$i])) {
                        $data['unit'] = $branch_units[0];
                    } else {
                        $data['unit'] = $unit[$i];
                    }

                    $dataa = $this->policyPremium2Model->insert($data);
                }
                $data = $this->request->getPost();
                $insert = true;
            }

            if ($insert) {
                return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'rack_rate_json' => $json_data_relation_data_for_form_submit_check,], 200);
            } else {
                return $this->respond(['status' => false, 'code' => 404, 'data' => $data, 'message' => 'no data found'], 200);
            }
        } catch (\Exception $e) {
            echo 'Error: ' . $e->getMessage() . ' at line no ' . $e->getLine();
        }
    }



    public function uploadVehicleFile()
    {
        $this->myLogger->logme('error', 'uploadVehicleFile function called');
        $data = $this->request->getPost();
        $files = $this->request->getFiles();
        // $data['client_id'] = 12;
        // $data['vehicle_id'] = 1;

        // upload path
        $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';

        $insertedDocs = [];

        // Check  document names and files
        if (isset($data['other_docs_name']) && isset($files['file_name'])) {
            foreach ($data['other_docs_name'] as $key => $docName) {
                // Get the corresponding file for this document name
                $file = $files['file_name'][$key];

                if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
                    // Upload the file
                    $uploadedFileName = file_Upload($file, $uploadFilePath);

                    if ($uploadedFileName) {
                        // Prepare data for each document upload
                        $docData = [
                            'client_id' => $data['client_id'],
                            'vehicle_id' => $data['vehicle_id'],
                            'other_docs_name' => $docName,
                            'file_name' => $uploadedFileName,
                            'created_by' => get_session_userid(),
                        ];

                        // Insert into database
                        $insert = $this->clientKYCDocsModel->insert($docData);

                        if ($insert) {
                            $insertedDocs[] = $docData; // Collect successfully inserted docs
                        }
                    }
                }
            }

            if (!empty($insertedDocs)) {
                // Fetch all documents for the client
                $vehicleDocs = $this->clientKYCDocsModel
                    ->where('client_id', $data['client_id'])
                    ->where('vehicle_id', $data['vehicle_id'])
                    ->findAll();
                return $this->respond(['status' => true, 'code' => 200, 'vehicle_docs' => $vehicleDocs, 'inserted_docs' => $insertedDocs], 200);
            } else {
                return $this->respond(['status' => false, 'code' => 400, 'message' => 'No documents uploaded or inserted'], 200);
            }
        } else {
            return $this->respond(['status' => false, 'code' => 400, 'message' => 'Invalid data submission'], 200);
        }
    }


    public function editUploadVehicleFile() {}

    public function listVehicleFiles() {}

    public function deleteVehicleFiles() {}





    public function getKycDocsById($id = null)
    {

        $this->myLogger->logme('error', 'getKycDocsById function called');
        if ($id) {
            $kyc_docs_data = $this->kycDocsModel->where(['kyc_type_id' => $id, 'is_active' => 1])->findAll();
            $this->myLogger->logme('error', 'getKycDocs status TRUE');
            return $this->respond(['status' => true, 'code' => 200, 'data' => $kyc_docs_data], 200);
        } else {
            $this->myLogger->logme('error', 'getKycDocs status FALSE');
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function getPolicesByInsurerId($id = null)
    {
        $this->myLogger->logme('error', 'getPolicesByInsurerId function called');
        if ($id) {
            $police_data = $this->policesModel
                ->select('policies.*, policy_type.policy_type')
                ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                ->where(['insurer_id' => $id, 'policies.is_active' => 1])->findAll();
            return $this->respond(['status' => true, 'code' => 200, 'data' => $police_data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function getSingleBranchDataById($id = null)
    {

        $this->myLogger->logme('error', 'getSingleBranchDataById function called');
        if ($id) {
            $branch_data = $this->clientBranchModel->where(['id' => $id, 'is_active' => 1])->first();
            $branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->findAll();
            return $this->respond(['status' => true, 'code' => 200, 'data' => $branch_data, 'contact' => $branch_contact_data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function getClientPolicyById($id = null)
    {
        $this->myLogger->logme('error', 'getClientPolicyById function called');

        if ($id) {
            $client_policy_data = $this->clientPolicyModel->where(['id' => $id, 'is_active' => 1])->first();
            $insurer_id = $client_policy_data['insurer_id'];
            $client_id = $client_policy_data['client_id'];

            $polices = $this->policesModel
                ->select('policies.*, policy_type.policy_type')
                ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                ->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])
                ->findAll();
            $client_policy_list = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
            $cd_data = $this->CDMasterModel->where('client_id', $client_id)->where('insurer_id', $insurer_id)->findAll();

            return $this->respond([
                'status' => true,
                'code' => 200,
                'data' => $client_policy_data,
                'cd_data' => $cd_data,
                "insurer_id" => $client_policy_data['insurer_id'],
                'policy' => $polices,
                'client_policy_list' =>  $client_policy_list
            ], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200);
        }
    }

    public function getpolicyGridData()
    {

        $client_policy_id = $this->request->getGet('client_policy_id');
        $terms_si_amount_array = $this->getPolicyTerms($client_policy_id);

        $record    = $this->clientPolicyModel
            ->select('client_policy.*, policy_type.policy_type')
            ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
            ->where('client_policy.id', $client_policy_id)
            ->first();
        $family_floater = '';
        if (isset(json_decode($record['policy_terms'])->family_floater)) {
            $family_floater = json_decode($record['policy_terms'])->family_floater;
        }

        $policy_terms_data = json_decode($record['policy_terms']);
        $self = "";
        if ($policy_terms_data !== null && isset($policy_terms_data->family_floaters)) {
            $self = $policy_terms_data->family_floaters;
        }

        $branch_units = $this->getBranchUnitsByBranchId($record['client_branch_id']);

        $emp_count = $this->employeePolicyModel
            ->join('client_policy cp', "cp.id = employee_polices.client_policy_id")
            ->where("employee_polices.client_policy_id", $client_policy_id)
            ->where("employee_polices.status", 'active')
            ->where("employee_polices.is_active", 1)
            ->countAllResults();

        $gmc_pattern = '/gmc/i';
        $gpa_pattern = '/gpa/i';
        $subject = $record['policy_type'];
        $policy_type_id = $record['policy_type_id'];

        if (preg_match($gmc_pattern, $subject)) {
            $search_term = 'GMC';
        } else if (preg_match($gpa_pattern, $subject)  || $policy_type_id == 6 || $policy_type_id == 7) {
            $search_term = 'GPA';
        } else {
            $search_term = "";
        }

        $results = $this->policyGridModel->like('policy_type', $search_term)->findAll();
        $jsonArray = [];

        if ($search_term === 'GPA' || $policy_type_id == 6 || $policy_type_id == 7) {

            $premiumData = $this->policyPremium1Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->findAll();
        } else if ($search_term === 'GMC') {

            $premiumData = $this->policyPremium2Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->findAll();

            $rackRateJson = $this->policyPremium2Model
                ->where('client_policy_id', $client_policy_id)
                ->where('is_active', 1)
                ->groupBy('rack_rate_name')
                ->orderBy('id')
                ->findAll();

            foreach ($rackRateJson as $value) {
                $jsonArray[$value['rack_rate_name']] = json_decode($value['additional_relationship']);
            }
        } else {

            $premiumData = "";
        }


        // echo '
';
        // print_r($premiumData); die;

        // echo $record['client_id'];
        // echo "-----";
        // echo $client_policy_id;
        // print_r($premiumData);die;
        // echo '
';
        // echo $family_floater;

        if ($search_term === 'GMC') {

            // $resultss = [];
            $resultss = $results;

            // try {
            //     foreach ($results as $index => $record) {
            //         // if ($self->self == 1 &&  $self->spouse == 0 &&  $self->childrens == 0 &&  $self->parents == 0 &&  $self->{'parents-in-law'} == 0 && $self->{'either-parents-pil'} == 0 && $family_floater == 0) {
            //         if ($family_floater == 1) {
            //             if ($index == '7' || $index == '8' || $index == '9' || $index == '10') {
            //                 $resultss[$index] = $record;
            //             }
            //         } else {
            //             if ($index == '0' || $index == '1' || $index == '2' || $index == '3' || $index == '4' || $index == '5' || $index == '6') {
            //                 $resultss[$index] = $record;
            //             }
            //         }
            //     }
            // } catch (\Exception $e) {
            //     $resultss = $results; // Reset $resultss to an empty array if an exception occurs
            // }



            $premiumDataa = '';
            if ($family_floater == 0) {
                // print_r($premiumData);die;
                if (count($premiumData) == 0) {
                    $premiumDataa = $premiumData;
                } else if ($premiumData[0]['policy_grid_id'] == '3' || $premiumData[0]['policy_grid_id'] == '4' || $premiumData[0]['policy_grid_id'] == '5' || $premiumData[0]['policy_grid_id'] == '6' || $premiumData[0]['policy_grid_id'] == '7' || $premiumData[0]['policy_grid_id'] == '8' || $premiumData[0]['policy_grid_id'] == '9') {
                    $premiumDataa = $premiumData;
                }
            } else if ($family_floater == 1) {
                if (count($premiumData) == 0) {
                    $premiumDataa = $premiumData;
                } else if ($premiumData[0]['policy_grid_id'] == '10' || $premiumData[0]['policy_grid_id'] == '11') {
                    $premiumDataa = $premiumData;
                }
            } else {
                $premiumDataa = $premiumData;
            }

            if ($premiumDataa  == "") {
                $premiumDataa = $premiumData;
            }

            // $premium1 = [];
            // $premium2 = [];

            // foreach ($premiumDataa as $key => $item) {
            //     if ($item['rack_rate_type'] == 0) {
            //         $premium1[] = $item;
            //     } elseif ($item['rack_rate_type'] == 1) {
            //         $premium2[] = $item;
            //     }
            // }

            // print_r($premium1);
            // print_r($premium2); die;

            return $this->respond([
                'status' => true,
                'code' => 200,
                'data' => $resultss,
                'premiumData' => json_encode($premiumDataa),
                'count' => $emp_count,
                'family_floater' => $family_floater,
                'self' => $self,
                'client_policy_id' => $client_policy_id,
                'terms_si_amount_array' => $terms_si_amount_array,
                'branch_units' => $branch_units,
                'jsonArray' => $jsonArray,
            ], 200);
        } else if ($search_term === 'GPA' || $policy_type_id == 6 || $policy_type_id == 7) {

            return $this->respond([
                'status' => true,
                'code' => 200,
                'data' => $results,
                'premiumData' => json_encode($premiumData),
                'count' => $emp_count,
                'family_floater' => $family_floater,
                'self' => $self,
                'client_policy_id' => $client_policy_id,
                'terms_si_amount_array' => $terms_si_amount_array,
                'branch_units' => $branch_units,
                'jsonArray' => $jsonArray,
            ], 200);
        } else {

            return $this->respond([
                'status' => false,
                'code' => 200,
                'data' => $results,
                'premiumData' => json_encode($premiumData),
                'count' => $emp_count,
                'family_floater' => $family_floater,
                'self' => $self,
                'client_policy_id' => $client_policy_id,
                'terms_si_amount_array' => $terms_si_amount_array,
                'branch_units' => $branch_units,
                'jsonArray' => $jsonArray,
            ], 200);
        }
    }

    public function policyGMCTerms()
    {
        try {
            // echo "
";
            // print_r($this->request->getPost());die;
            $this->myLogger->logme('error', 'Terms CREATE function called');

            /*** Client Policy Table Primary Key(ID) ***/
            $client_policy_id = $this->request->getPost("client_policy_id");

            $data['sum_insured']   = str_replace(',', '', $this->request->getPost("sum_insured"));
            $data['family_floater']   = $this->request->getPost("family_floater") ? $this->request->getPost("family_floater") : 0;
            // $data['corporatebuffer'] = $this->request->getPost("corporatebuffer") ? $this->request->getPost("corporatebuffer") : 0;
            $data['family_floaters'] = $this->request->getPost("family_floaters") ?? [];

            $data['age_ratio']['self']['min'] =  $this->request->getPost("self_min_age") ? $this->request->getPost("self_min_age") : 0;
            $data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age") ? $this->request->getPost("self_max_age") : 0;
            $data['age_ratio']['spouse']['min'] = $this->request->getPost("spouse_min_age") ? $this->request->getPost("spouse_min_age") : 0;
            $data['age_ratio']['spouse']['max'] = $this->request->getPost("spouse_max_age") ? $this->request->getPost("spouse_max_age") : 0;
            $data['age_ratio']['child']['min'] = $this->request->getPost("child_min_age") ? $this->request->getPost("child_min_age") : 0;
            $data['age_ratio']['child']['max'] = $this->request->getPost("child_max_age") ? $this->request->getPost("child_max_age") : 0;
            $data['age_ratio']['elders']['min'] = $this->request->getPost("other_member_min_age") ? $this->request->getPost("other_member_min_age") : 0;
            $data['age_ratio']['elders']['max'] = $this->request->getPost("other_member_max_age") ? $this->request->getPost("other_member_max_age") : 0;



            // if (!in_array("self", $data['family_floaters'])) {
            //     array_unshift($data['family_floaters'], "self");
            // }
            $temp_family_floaters = $data['family_floaters'];
            $data['family_floaters'] = [];
            if (in_array("self", $temp_family_floaters) == 1) {
                $data['family_floaters']['self'] = 1;
            } else {
                $data['family_floaters']['self'] = 0;
            }

            if (in_array("spouse", $temp_family_floaters) == 1) {
                $data['family_floaters']['spouse'] = 1;
            } else {
                $data['family_floaters']['spouse'] = 0;
            }

            // $data['family_floaters']['either-parents-pil'] =0;

            if (count($temp_family_floaters)) {
                $children_value = 0;
                $value = 0;

                if (count($temp_family_floaters) == 2) {
                    $children_value = 0;
                    $value = 1;
                } else if (count($temp_family_floaters) == 3) {
                    $children_value = 1;
                    $value = 2;
                } else {
                    $children_value = 2;
                    $value = 3;
                }
                $data['family_floaters']['childrens'] = (int)$temp_family_floaters[$children_value];

                if ($temp_family_floaters[$value] == '1P') {
                    $data['family_floaters']['parents'] = 1;
                    $data['family_floaters']['parents-in-law'] = 0;
                    $data['family_floaters']['either-parents-pil'] = 0;
                } else if ($temp_family_floaters[$value] == '2P') {
                    $data['family_floaters']['parents'] = 2;
                    $data['family_floaters']['parents-in-law'] = 0;
                    $data['family_floaters']['either-parents-pil'] = 0;
                } else if ($temp_family_floaters[$value] == '1PIL') {
                    $data['family_floaters']['parents'] = 0;
                    $data['family_floaters']['parents-in-law'] = 1;
                    $data['family_floaters']['either-parents-pil'] = 0;
                } else if ($temp_family_floaters[$value] == '2PIL') {
                    $data['family_floaters']['parents'] = 0;
                    $data['family_floaters']['parents-in-law'] = 2;
                    $data['family_floaters']['either-parents-pil'] = 0;
                } else if ($temp_family_floaters[$value] == '2EPORPIL') {
                    //Parents or PIL (Any two of Father, Mother, MIl, FIL)
                    $data['family_floaters']['parents'] = 0;
                    $data['family_floaters']['parents-in-law'] = 0;
                    $data['family_floaters']['either-parents-pil'] = 2;
                } else if ($temp_family_floaters[$value] == 'EPORPIL') {
                    //Either Parents or PIL (Parents or Parents In Law)
                    $data['family_floaters']['parents'] = 0;
                    $data['family_floaters']['parents-in-law'] = 0;
                    $data['family_floaters']['either-parents-pil'] = 1;
                } else if ($temp_family_floaters[$value] == '4EPORPIL') {
                    $data['family_floaters']['parents'] = 2;
                    $data['family_floaters']['parents-in-law'] = 2;
                    $data['family_floaters']['either-parents-pil'] = 0;
                } else {
                    $data['family_floaters']['parents'] = 0;
                    $data['family_floaters']['parents-in-law'] = 0;
                    $data['family_floaters']['either-parents-pil'] = 0;
                }
            }

            $data['family_floaters']['elders_count'] = $this->request->getPost("elder_member_count") ? $this->request->getPost("elder_member_count") : 0;

            // print_r($data);die;

            $data['waiverofpreexistingdiseases']   = $this->request->getPost("waiverofpreexistingdiseases");
            if ($data['waiverofpreexistingdiseases'] == 1) {
                $data['maternitycoverage']   = str_replace(',', '', $this->request->getPost("maternitycoverage"));
                $data['twindelivery']   = str_replace(',', '', $this->request->getPost("twindelivery"));
                $data['preandpostnatal']   = str_replace(',', '', $this->request->getPost("preandpostnatal"));
                $data['babyday1cover']   = str_replace(',', '', $this->request->getPost("babyday1cover"));
            } else {
                $data['maternitycoverage']   = "";
                $data['twindelivery']   = "";
                $data['preandpostnatal']   = "";
                $data['babyday1cover']   = "";
            }
            $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
            $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
            $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
            $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
            $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
            // $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
            $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
            // $data['congenitaldiseasesexternal'] =$this->request->getPost("congenitaldiseasesexternal");
            $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
            $data['bioabsorbablestenttoriclensmultifocallens'] = $this->request->getPost("bioabsorbablestenttoriclensmultifocallens");
            $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
            $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
            // $data['nursingallowance'] =str_replace(',', '',$this->request->getPost("nursingallowance"));
            $data['ailmentcapping'] = str_replace(',', '', $this->request->getPost("ailmentcapping"));
            $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
            $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
            $data['familytransportationbenefit'] = str_replace(',', '', $this->request->getPost("familytransportationbenefit"));
            $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
            $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));

            $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
            $data['optionalparentalcopay'] = str_replace(',', '', $this->request->getPost("optionalparentalcopay"));
            $data['posthospitalizationcover'] = str_replace(',', '', $this->request->getPost("posthospitalizationcover"));
            $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
            $data['sublimitofcorporatebuffer'] = str_replace(',', '', $this->request->getPost("sublimitofcorporatebuffer"));

            if ($data['ayudhtreatmentcover'] == 1) {
                $data['ayushTreatmentCoverData']   = str_replace(',', '', $this->request->getPost("ayushTreatmentCoverData"));
            } else {
                $data['ayushTreatmentCoverData']   = "";
            }

            $data['armdcovered'] = str_replace(',', '', $this->request->getPost("armdcovered"));
            $data['suminsuredenhancement'] = str_replace(',', '', $this->request->getPost("suminsuredenhancement"));
            $data['automaticsuminsuredreinstatement'] = str_replace(',', '', $this->request->getPost("automaticsuminsuredreinstatement"));
            $data['additionalsicknessbenefit'] = str_replace(',', '', $this->request->getPost("additionalsicknessbenefit"));
            $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
            $data['midterminclusion'] = str_replace(',', '', $this->request->getPost("midterminclusion"));
            $data['capd'] = str_replace(',', '', $this->request->getPost("capd"));
            $data['organdonorexpenses'] = str_replace(',', '', $this->request->getPost("organdonorexpenses"));
            $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
            $data['Wellness'] = str_replace(',', '', $this->request->getPost("Wellness"));
            $data['days_of_discharge'] = str_replace(',', '', $this->request->getPost("days_of_discharge"));
            $data['days_from_dod'] = str_replace(',', '', $this->request->getPost("days_from_dod"));
            $data['special_condition_label'] = str_replace(',', '', $this->request->getPost("special_condition_label")) ?? [];
            $data['special_condition_input'] = str_replace(',', '', $this->request->getPost("special_condition_input")) ?? [];
            $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];

            $data['cataract'] = str_replace(',', '', $this->request->getPost("cataract"));

            if ($data['cataract'] == 1) {
                $data['cataractData']   = str_replace(',', '', $this->request->getPost("cataractData"));
            } else {
                $data['cataractData']   = "";
            }


            $jsonData = json_encode($data);
            $dataa = array(
                'policy_terms' => $jsonData,
            );

            $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();


            // print_r($data);die;
            if ($record) {
                $update = $this->clientPolicyModel->update($client_policy_id, $dataa);
                if ($update) {
                    return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data updated successfully'], 200);
                } else {
                    return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update data'], 200);
                }
            } else {
                $insert = $this->clientPolicyModel->insert($dataa);
                if ($insert) {
                    return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data stored successfully'], 200);
                } else {
                    return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data'], 200);
                }
            }
        } catch (\Exception $e) {

            echo "Failed to insert data: " . $e->getMessage();
            // Log the error
            log_message('error', 'Failed to insert data: ' . $e->getMessage());
        }
    }

    public function getterms()
    {
        $client_policy_id = $this->request->getVar('client_policy_id');
        $record    = $this->clientPolicyModel->where('id', $client_policy_id)->first();

        // $emp_count = $this->employeeModel ->join('client_policy cp',"employees.client_id = cp.client_id")
        //     ->join('employee_polices ep',"cp.id = ep.client_policy_id AND employees.id = ep.employee_id")
        //     ->where("employees.client_id", $record['client_id'])
        //     ->where("employees.emp_status",'active')
        //     ->countAllResults();

        $emp_count_by_policy = $this->employeePolicyModel
            ->where('client_policy_id', $client_policy_id)
            ->where("status", 'active')
            ->where('is_active', 1)
            ->countAllResults();


        if ($record) {
            return $this->respond(
                [
                    'Status' => true,
                    'code' => 200,
                    'data' => $record['policy_terms'],
                    'policy_addon' => $record['is_addon'],
                    'emp_count_by_policy' => $emp_count_by_policy
                ],
                200
            );
        } else {
            return $this->respond(['Status' => false, 'code' => 200, 'message' => 'Record not found.'], 200);
        }
    }

    public function policyGPATerms()
    {
        try {
            $this->myLogger->logme('error', 'Policy GPA Terms CREATE function called');

            /*** Client Policy Table Primary Key(ID) ***/
            $client_policy_id = $this->request->getPost("client_policy_id");

            $data['sumInsured2']   = str_replace(',', '', $this->request->getPost("sumInsured2"));
            $data['totalSumInsured'] = str_replace(',', '', $this->request->getPost("totalSumInsured"));
            $data['age_ratio']['self']['min'] = $this->request->getPost("self_min_age");
            $data['age_ratio']['self']['max'] = $this->request->getPost("self_max_age");
            $data['accidentalDeathBenefit'] = str_replace(',', '', $this->request->getPost("accidentalDeathBenefit"));
            $data['permanentTotalDisablement'] = str_replace(',', '', $this->request->getPost("permanentTotalDisablement"));
            $data['permanentPartialDisablement'] = $this->request->getPost("permanentPartialDisablement");
            $data['temporaryTotalDisablementBenefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
            $data['accidentalHospitalizationExpenses'] = str_replace(',', '', $this->request->getPost("accidentalHospitalizationExpenses"));
            $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));

            $data['compassionateVisitExpenses']   = $this->request->getPost("compassionateVisitExpenses");
            if ($data['compassionateVisitExpenses'] == 1) {
                $data['compassionateVisitExpensesData']   = $this->request->getPost("compassionateVisitExpensesData");
            } else {
                $data['compassionateVisitExpensesData']   = "";
            }

            $data['brokenBoneExpenses']   = str_replace(',', '', $this->request->getPost("brokenBoneExpenses"));
            if ($data['brokenBoneExpenses'] == 1) {
                $data['brokenBoneExpensesData']   = str_replace(',', '', $this->request->getPost("brokenBoneExpensesData"));
            } else {
                $data['brokenBoneExpensesData']   = "";
            }

            $data['ambulanceCharges']   = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
            if ($data['ambulanceCharges'] == 1) {
                $data['ambulanceChargesData']   = str_replace(',', '', $this->request->getPost("ambulanceChargesData"));
            } else {
                $data['ambulanceChargesData']   = "";
            }

            $data['burnExpenses']   = $this->request->getPost("burnExpenses");
            if ($data['burnExpenses'] == 1) {
                $data['burnExpensesData']   = $this->request->getPost("burnExpensesData");
            } else {
                $data['burnExpensesData']   = "";
            }

            $data['carriageOfDeadBody']   = $this->request->getPost("carriageOfDeadBody");
            if ($data['carriageOfDeadBody'] == 1) {
                $data['carriageOfDeadBodyData']   = $this->request->getPost("carriageOfDeadBodyData");
            } else {
                $data['carriageOfDeadBodyData']   = "";
            }

            $data['animalSnakeInsectBite'] = $this->request->getPost("animalSnakeInsectBite");
            $data['terrorism']             = $this->request->getPost("terrorism");
            $data['worldwideCover']        = $this->request->getPost("worldwideCover");
            $data['gpa_special_condition_label'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_label")) ?? [];
            $data['gpa_special_condition_input'] = str_replace(',', '', $this->request->getPost("gpa_special_condition_input")) ?? [];
            $data['multiple_sum_insured'] = str_replace(',', '', $this->request->getPost("multiple_sum_insured")) ?? [];



            $jsonData = json_encode($data);
            $dataa = array(
                'policy_terms' => $jsonData,
            );

            $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();
            if ($record) {
                $update = $this->clientPolicyModel->update($client_policy_id, $dataa);
                if ($update) {
                    return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data updated successfully', 'client_policy_id' => $client_policy_id], 200);
                } else {
                    return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update data'], 200);
                }
            } else {
                $insert = $this->clientPolicyModel->insert($dataa);
                if ($insert) {
                    return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data stored successfully', 'client_policy_id' => $client_policy_id], 200);
                } else {
                    return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data'], 200);
                }
            }
        } catch (\Exception $e) {

            echo "Failed to insert data: " . $e->getMessage();
            log_message('error', 'Failed to insert data: ' . $e->getMessage());
        }
    }

    public function getPolicyGPATerms()
    {

        $client_id = $this->request->getVar('client_id');
        $policy_id = $this->request->getVar('policy_id');
        $record = $this->clientPolicyModel->where(['client_id' => $client_id, 'policy_id' => $policy_id])->first();

        if ($record) {
            echo $record['policy_terms'];
        } else {
            echo "Record not found.";
        }
    }

    public function updateClientPolicyStatus()
    {

        $client_policy_id = $this->request->getGet('client_policy_id');
        $message = 'Policy updated Successfully';


        $record    = $this->clientPolicyModel->where('id', $client_policy_id)->first();

        if ($record['open_for_enrollment'] == 0) {
            $open_for_enrollment_update_value = 1;
            $message = 'Enrolment Opened  Successfully';
        } else if ($record['open_for_enrollment'] == 1) {
            $open_for_enrollment_update_value = 0;
            $message = 'Enrolment Closed Successfully';
        }

        $data = $this->policesModel->getPolicyPremium($client_policy_id);
        $pattern = '/gmc/i';
        $subject = $data[0]->policy_type;
        if (preg_match($pattern, $subject)) {
            $search_term = 'GMC';
        } else {
            $search_term = 'GPA';
        }

        if ($search_term === 'GPA') {
            $racRate = $this->policyPremium1Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->countAllResults();
        } else if ($search_term === 'GMC') {
            $racRate = $this->policyPremium2Model->where(['client_id' => $record['client_id'], 'client_policy_id' => $client_policy_id, 'is_active' => 1])->countAllResults();
        }

        $termsData = $this->clientPolicyModel->where(['id' => $client_policy_id, 'is_active' => 1])->first();
        if (empty($termsData['policy_terms'])) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'Please define policy terms '], 200);
        }


        $termsData = json_decode($termsData['policy_terms']);

        if (isset($termsData->sum_insured) && empty($termsData->sum_insured)) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty', 'data' => $record], 200);
        }

        if (isset($termsData->SumInsured) && empty($termsData->sum_insured)) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty'], 200);
        }

        // Check if 'family_floater' key exists and has a value
        if (isset($termsData->family_floater) && $termsData->family_floater === null) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Family Floater field is empty', 'termsData' => $termsData, 'family_floater' => $termsData->family_floater], 200);
        }

        // Check if 'family_floaters' key exists and has a value
        if (isset($termsData->family_floaters) && is_array($termsData->family_floaters) && count($termsData->family_floaters) <= 0) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Family Members field is empty'], 200);
            $familyFloatersCount = count($termsData->family_floaters);
        }

        if ($racRate == 0) {

            return $this->respond(['status' => false, 'code' => 200, 'message' => 'Please define  policy premium'], 200);
        }

        // $policy_status = $this->clientPolicyModel->where('id', $client_policy_id )->set('policy_status', 1)->update();

        $json_data = '';
        $open_for_enrollment = $this->clientPolicyModel->where('id', $client_policy_id)->set('open_for_enrollment', $open_for_enrollment_update_value)->update();
        if ($open_for_enrollment) {
            $open_for_enrollment_1 = $this->clientPolicyModel->where('id', $client_policy_id)->find();
            $open_for_enrollment_value = $open_for_enrollment_1[0]['open_for_enrollment'];
            $client_policy_id_value = $client_policy_id;

            $json_data = json_encode(['open_for_enrollment' => $open_for_enrollment_value, 'client_policy_id' => $client_policy_id_value]);
        }



        return $this->respond(['status' => true, 'code' => 200, 'message' => $message, 'data' => $termsData, 'racRate' => $racRate, 'open_for_enrollment' => $json_data, 'client_policy_data' => $record], 200);
    }

    public function getClientPolicyList($client_id = null)
    {

        $record = $this->clientPolicyModel->getpolicyWithPattern($client_id);

        if ($record) {
            return $this->respond(['Status' => true, 'code' => 200, 'data' => $record], 200);
        } else {
            return $this->respond(['Status' => false, 'code' => 200, 'message' => 'Record not found.'], 200);
        }
    }

    public function fetchPolicyDataForPolicyType($client_policy_id)
    {

        $client_policy_id = $this->request->getGet('client_policy_id');
        $policy_type = $this->request->getGet('policy_type');

        $client_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
        $insurer_id = $client_id['insurer_id'];

        if ($policy_type == 2) {

            $polices = $this->policesModel
                ->select('policies.*')
                ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                ->where('policy_type.policy_type', 'GMC - Top-up')
                ->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])->findAll();
        } else  if ($policy_type == 3) {

            $polices = $this->policesModel
                ->select('policies.*')
                ->join('policy_type', 'policy_type.id = policies.policy_type_id')
                ->whereIn('policy_type.policy_type', ['GMC - Parents', 'GMC - Top-up(Parents)'])
                ->where(['policies.insurer_id' => $insurer_id, 'policies.is_active' => 1])->findAll();
        }


        $data = $this->clientPolicyModel->getClientPolicyByPolicyType($client_id['client_id'], $policy_type);

        return $this->respond(['Status' => true, 'code' => 200, 'data' => $data, 'client_policy_id' => $client_policy_id, 'policy' => $polices], 200);
    }

    public function downloadKYCDocument($file_name)
    {

        $file = WRITEPATH . 'uploads/client_kyc_documents/' . $file_name; // Example file path

        if (file_exists($file)) {
            return $this->response->download($file, null)->setFileName($file_name);
        } else {
            return "File not found.";
        }
    }

    public function getClientBranch($client_id)
    {

        $branchs = $this->clientBranchModel
            ->select('*')
            ->where('client_id', $client_id)
            ->findAll();

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

    public function getClientAllDetailsByUsingClientID($client_id)
    {

        $db = \Config\Database::connect();

        $builder = $db->table('clients');
        $builder->select('

            policy_type.policy_type,
            insurers.name as insurer_name,
            insurers.short_name as insurer_short_name,
            tpa.name as tpa_name,
            tpa.short_name as tpa_short_name,
            client_policy.policy_terms,

            DATE_FORMAT(client_policy.policy_start_date, "%d-%b-%Y") as policy_start_date,
            DATE_FORMAT(client_policy.policy_end_date, "%d-%b-%Y") as policy_end_date,

            CASE
            WHEN client_policy.base_policy IS NULL THEN "Not Appear"
            WHEN client_policy.base_policy = 0 THEN "Not Appear"
            ELSE (SELECT policy_type.policy_type 
                  FROM client_policy AS base_client_policy 
                  JOIN policy_type ON policy_type.id = base_client_policy.policy_type_id 
                  WHERE base_client_policy.id = client_policy.base_policy)
            END as base_policy_name,

            CASE
                WHEN client_policy.is_addon = 1 THEN "Base Policy"
                WHEN client_policy.is_addon = 2 THEN "SI Topup"
                WHEN client_policy.is_addon = 3 THEN "Dependent Addon"
                ELSE "n/a"
            END as is_addon,

            CASE
                WHEN client_policy.policy_status = 1 THEN "Active"
                WHEN client_policy.policy_status = 0 THEN "Expired"
                ELSE "n/a"
            END as policy_status,

            CASE
                WHEN client_policy.inception_type = 1 THEN "File Upload"
                WHEN client_policy.inception_type = 2 THEN "Enrolment"
                ELSE "n/a"
            END as inception_type,

            CASE
                WHEN client_policy.open_for_enrollment = 1 THEN "Open"
                WHEN client_policy.open_for_enrollment = 0 THEN "Closed"
                ELSE "n/a"
            END as open_for_enrollment,
            client_branch.branch_name 

        ', false);
        $builder->join('client_policy', 'client_policy.client_id = clients.id');
        $builder->join('client_branch', 'client_policy.client_branch_id = client_branch.id');
        $builder->join('policy_type', 'policy_type.id = client_policy.policy_type_id');
        $builder->join('insurers', 'insurers.id = client_policy.insurer_id');
        $builder->join('tpa', 'tpa.id = client_policy.tpa_id');
        $builder->where('clients.is_active', 1);
        $builder->where('client_policy.is_active', 1);
        $builder->where('policy_type.is_active', 1);
        $builder->where('client_policy.policy_status', 1);
        $builder->where('clients.id', $client_id);

        $query = $builder->get();
        $client_policy = $query->getResultArray();

        $gmc_keys = [
            "sum_insured" => "Sum Insured",
            "family_floater" => "Family Floater",
            "family_floaters" => "Family Floaters",
            "elders_count" => "Elders Count:",
            "other_member_min_age" => "Min Age:",
            "other_member_max_age" => "Min Age:",
            "waiverofpreexistingdiseases" => "Waiver of Pre-existing Diseases",
            "9monthwaitingperiodwaived" => "9-month waiting Period –waived",
            "coverfromthedateofjoining" => "Cover from the date of Joining",
            "waiverof1,2,3&4thyearexclusions" => "Waiver of 1, 2, 3 & 4th year Exclusions",
            "waiverof30dayswaitingperiod" => "Waiver of 30 days waiting period",
            "prehospitalizationcover" => "Pre Hospitalization Cover",
            "congenitaldiseasesinternal" => "Congenital Diseases - Internal",
            "copayzonewisecopay" => "Co-Pay/Zone wise Co Pay",
            "bioabsorbablestenttoriclensmultifocallens" => "Bio absorbable stent / Toric lens/ Multi Focal lens",
            "roomrentlimit" => "Room Rent Limit",
            "proportionatedeductionclause" => "Proportionate Deduction Clause",
            "nursingallowance" => "Nursing Allowance",
            "ailmentcapping" => "Ailment capping",
            "ambulancecharges" => "Ambulance Charges",
            "airambulance" => "Air Ambulance",
            "familytransportationbenefit" => "Family Transportation Benefit",
            "reasonableandcustomarycharges" => "Reasonable and Customary Charges",
            "daycaretreatment" => "Day Care Treatment",
            "ayudhtreatmentcover" => "AYUSH treatment cover",
            "armdcovered" => "ARMD Covered",
            "suminsuredenhancement" => "Sum Insured enhancement",
            "automaticsuminsuredreinstatement" => "Automatic Sum Insured reinstatement",
            "additionalsicknessbenefit" => "Additional Sickness Benefit",
            "lasiksurgery" => "Lasik Surgery",
            "midterminclusion" => "Mid Term inclusion",
            "capd" => "CAPD",
            "organdonorexpenses" => "Organ donor expenses",
            "moderntreatmentsasperirdai" => "Modern treatments as per IRDAI",
            "Wellness" => "Wellness",
            "days_of_discharge" => "Claim Intimation Clause",
            "days_from_dod" => "Claim Submission",
            "cataract" => "Cataract"
        ];

        $gpa_keys = [
            "sumInsured2" => "Sum Insured",
            "totalSumInsured" => "Total Sum Assured",
            "self" => "Self",
            "self_min_age" => "Min Age",
            "self_max_age" => "Max Age",
            "accidentalDeathBenefit" => "Accidental Death Benefit",
            "permanentTotalDisablement" => "Permanent Total Disablement",
            "permanentPartialDisablement" => "Permanent Partial Disablement",
            "temporaryTotalDisablementBenefit" => "Temporary Total Disablement benefit",
            "accidentalHospitalizationExpenses" => "Accidental Hospitalization Expenses",
            "childrenEducationWelfareFund" => "Children Education Welfare Fund",
            "compassionateVisitExpenses" => "Compassionate Visit Expenses",
            "compassionateVisitExpensesData" => "Compassionate Visit Expenses Data",
            "brokenBoneExpenses" => "Broken Bone Expenses",
            "brokenBoneExpensesData" => "Broken Bone Expenses Data",
            "ambulanceCharges" => "Ambulance charges",
            "ambulanceChargesData" => "Ambulance charges Data",
            "burnExpenses" => "Burn Expenses",
            "burnExpensesData" => "Burn Expenses Data",
            "carriageOfDeadBody" => "Carriage of Dead Body",
            "carriageOfDeadBodyData" => "Carriage of Dead Body Data",
            "animalSnakeInsectBite" => "Animal/Snake/Insect bite",
            "terrorism" => "Terrorism",
            "worldwideCover" => "Worldwide Cover"
        ];


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

            $policy_terms = json_decode($value['policy_terms'], true);

            $mapping = $gmc_keys;
            if ($value['policy_type'] == 'GPA') {
                $mapping = $gpa_keys;
            }

            $client_policy[$key]['policy_terms'] = $this->transformArray($policy_terms, $mapping);
        }


        $data['client_policy'] = $client_policy;
        $data['client_branch'] = $this->clientModel

            ->select('

                    client_branch.branch_name,
                    client_branch.branch_code,
                    client_branch.city,
                    level_contacts.name as hr_name,
                    level_contacts.designation,
                    level_contacts.mobile,
                    level_contacts.email
            ')
            ->join('client_branch', 'client_branch.client_id = clients.id')
            ->join('level_contacts', 'level_contacts.ref_id = client_branch.id')
            ->where('clients.is_active', 1)
            ->where('client_branch.is_active', 1)
            ->where('level_contacts.is_active', 1)
            ->where('level_contacts.contact_type', 'client')
            ->where('clients.id', $client_id)
            ->get()->getResultArray();


        $data['client'] = $this->clientModel->where('clients.id', $client_id)->first();


        $client_rm = $this->clientRMModel
            ->select('client_rm.*, user_profiles.first_name as user_name')
            ->join('user_profiles', 'user_profiles.id = client_rm.user_id')
            ->where('client_id', $client_id)->get()->getResultArray();


        $account_managers = [];
        $managers = [];
        $heads = [];

        foreach ($client_rm as $key => $value) {
            if ($value['level'] == 3) {
                $account_managers[] = $value['user_name'];
            } elseif ($value['level'] == 2) {
                $managers[] = $value['user_name'];
            } elseif ($value['level'] == 1) {
                $heads[] = $value['user_name'];
            }
        }

        $data['account_managers'] = $account_managers;
        $data['managers'] = $managers;
        $data['heads'] = $heads;

        // dd($data);
        // $this->loadLayout('client_info', $data);


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

    public function transformArray($data, $mapping)
    {

        // dd($data);
        $transformedData = [];

        if (!is_array($data)) {
            return json_encode($transformedData, JSON_PRETTY_PRINT);
        }

        foreach ($data as $key => $value) {
            if ($key == 'family_floaters') {
                $transformedData[$key] = $this->transformFamilyFloaters($value, $data);
            } else if (array_key_exists($key, $mapping)) {
                $transformedData[$mapping[$key]] = $value;
            } else if ($key == 'special_condition_label') {

                if (is_array($value)) {
                    foreach ($value as $key => $value) {
                        $transformedData[$value] = $data['special_condition_input'][$key];
                    }
                }
            } else if ($key == 'gpa_special_condition_label') {
                if (is_array($value)) {
                    foreach ($value as $key => $value) {
                        $transformedData[$value] = $data['gpa_special_condition_input'][$key];
                    }
                }
            } else if ($key == 'other_special_condition_label') {
                if (is_array($value)) {
                    foreach ($value as $key => $value) {
                        $transformedData[$value] = $data['other_special_condition_label'][$key];
                    }
                }
            } else if ($key == 'age_ratio') {
                if (isset($data['sumInsured2'])) {
                    $transformedData['Self'] = "(Min: " . $data['age_ratio']['self']['min'] . ", Max: " . $data['age_ratio']['self']['max'] . ")";
                }
            } else {
                $transformedData[$key] = $value;
            }
        }

        return json_encode($transformedData, JSON_PRETTY_PRINT);
    }

    public function transformFamilyFloaters($familyFloaters, $json)
    {
        $result = [];

        $min = $json['age_ratio']['self'];
        $max = $json['age_ratio']['self'];

        $spouse_min = $json['age_ratio']['spouse'];
        $spouse_max = $json['age_ratio']['spouse'];

        $child_min = $json['age_ratio']['child'];
        $child_max = $json['age_ratio']['child'];

        $elders_min = $json['age_ratio']['elders'];
        $elders_max = $json['age_ratio']['elders'];

        foreach ($familyFloaters as $key => $value) {
            if ($value !== 0) {
                switch ($key) {
                    case 'self':
                        $result[] = "Self (Min: {$min['min']}, Max: {$max['max']})";
                        break;
                    case 'spouse':
                        $result[] = "Spouse (Min: {$spouse_min['min']}, Max: {$spouse_max['max']})";
                        break;
                    case 'childrens':
                        $result[] = "Children(s) - $value  (Min: {$child_min['min']}, Max: {$child_max['max']})";
                        break;
                    case 'parents':
                        $result[] = "Parent(s) - $value (Min: {$elders_min['min']}, Max: {$elders_max['max']})";
                        break;
                    case 'parents-in-law':
                        $result[] = "Parents-in-Law - $value  (Min: {$elders_min['min']}, Max: {$elders_max['max']})";
                        break;
                    case 'either-parents-pil':
                        $result[] = "Either Parents Nor Parents-in-Law - $value  (elders_min: {$elders_min['min']}, Max: {$elders_max['max']})";
                        break;
                }
            }
        }

        return implode(", ", $result);
    }

    public function deleteAdditionalRackRate($client_id, $client_policy_id, $rack_rate_type)
    {
        try {
            $result = $this->policyPremium2Model
                ->where('client_id', $client_id)
                ->where('client_policy_id', $client_policy_id)
                ->where('rack_rate_type', $rack_rate_type)
                ->set('is_active', 0)
                ->update();

            if (!$result) {

                return $this->respond(['status' => false, 'code' => 200, 'message' => 'Failed to update the record.'], 200);
            }
        } catch (\Exception $e) {

            log_message('error', $e->getMessage());
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'Failed to update the record.'], 200);
        }

        return $this->respond(['status' => true, 'code' => 200, 'message' => 'Additionaly Rack Rate Data Remove Successfully'], 200);
    }

    public function get_cd_ac($client_id, $insurer_id)
    {

        $cd_data = $this->CDMasterModel
            ->where('client_id', $client_id)
            ->where('insurer_id', $insurer_id)
            ->where('is_active', 1)
            ->findAll();

        if ($cd_data) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404, 'insurer_id' => $insurer_id, 'client_id' => $client_id], 200);
        }
    }

    public function otherPolicyTermsFormSubmit()
    {

        $client_policy_id = $this->request->getPost("client_policy_id");
        $policy_terms = $this->request->getPost("policy_terms");

        $record = $this->clientPolicyModel->where('id', $client_policy_id)->first();

        if ($record) {

            $update = $this->clientPolicyModel->where('id', $client_policy_id)->set('policy_terms',  $policy_terms)->update();

            if ($update) {
                return $this->respond(['status' => true, 'code' => 200, 'message' => 'Data updated successfully', 'client_policy_id' => $client_policy_id], 200);
            } else {
                return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update data', 'formdata' => $this->request->getPost()], 200);
            }
        } else {

            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to store data. The client policy does not exist', 'formdata' => $this->request->getPost()], 200);
        }
    }

    public function checkPolicyType($policy_type_id, $client_branch_id, $client_id)
    {

        $policyCount = $this->clientPolicyModel
            ->where('policy_type_id', $policy_type_id)
            ->where('client_branch_id', $client_branch_id)
            ->where('client_id', $client_id)
            ->countAllResults();

        if ($policyCount > 0) {
            $clientPoliceData =  $this->clientPolicyModel->getClientPolicyByClientId($client_id);
            return $this->respond(['status' => true, 'code' => 200, 'count' =>  $policyCount, 'data' => $clientPoliceData, 'method' => 'CERATE', 'client_id' => $client_id, 'client_branch_id' => $client_branch_id, 'policy_type_id' => $policy_type_id], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 200, 'client_id' => $client_id, 'client_branch_id' => $client_branch_id, 'policy_type_id' => $policy_type_id], 200);
        }
    }

    public function getPolicyTerms($client_policy_id)
    {
        $policy_terms = $this->clientPolicyModel->where('id', $client_policy_id)->first();

        if (!$policy_terms) {
            // return $this->respond(['status' => false, 'error' => 'Policy not found'], 404);
            return [];
        }

        if (is_array($policy_terms)) {
            if (!isset($policy_terms['policy_terms'])) {
                // return $this->respond(['status' => false, 'error' => 'Policy terms not found in array'], 500);
                return [];
            }
            $JSON = json_decode($policy_terms['policy_terms']);
        } elseif (is_object($policy_terms)) {
            if (!isset($policy_terms->policy_terms)) {
                // return $this->respond(['status' => false, 'error' => 'Policy terms not found in object'], 500);
                return [];
            }
            $JSON = json_decode($policy_terms->policy_terms);
        } else {
            // return $this->respond(['status' => false, 'error' => 'Unexpected data type for policy terms'], 500);
            return [];
        }

        if (!$JSON) {
            // return $this->respond(['status' => false, 'error' => 'Invalid JSON format in policy terms'], 500);
            return [];
        }

        $multi_si = [];

        if (isset($JSON->sum_insured) && !empty($JSON->sum_insured)) {
            $multi_si[] = $JSON->sum_insured;
        } elseif (isset($JSON->sumInsured2) && !empty($JSON->sumInsured2)) {
            $multi_si[] = $JSON->sumInsured2;
        }

        if (isset($JSON->multiple_sum_insured) && is_array($JSON->multiple_sum_insured)) {
            foreach ($JSON->multiple_sum_insured as $msi) {
                if (!empty($msi)) {
                    $multi_si[] = $msi;
                }
            }
        }

        // return $this->respond(['status' => true, 'data' => $multi_si], 200);
        return $multi_si;
    }

    public function getPolicyTermsFormJson($policy_type_id)
    {

        $JSON = $this->policyTypeModel->where('id', $policy_type_id)->first();
        return $this->respond(['status' => true, 'data' => $JSON], 200);
    }

    public function createPolicyTermsHtmlAsJSON()
    {

        echo 'hi';
    }

    public function checkHRNumber($mobileNumber)
    {
        try {
            $mobileNumberCount = $this->levelContactModel
                ->join('client_branch', 'client_branch.id = level_contacts.ref_id')
                ->join('clients', 'clients.id = client_branch.client_id')
                ->where('clients.is_active', 1)
                ->where('client_branch.is_active', 1)
                ->where('level_contacts.is_active', 1)
                ->where('level_contacts.contact_type', 'client')
                ->where('level_contacts.mobile', $mobileNumber)
                ->countAllResults();
            return $this->respond(['status' => true, 'data' => $mobileNumberCount, 'message' => "try"], 200);
        } catch (\Exception $e) {
            log_message('error', 'Error checking mobile number: ' . $e->getMessage());
            return $this->respond(['status' => false, 'data' => 0, 'message' => 'An error occurred while checking the mobile number. Please try again later.'], 500);
        }
    }

    public function checkAdditionPremiumJSON($client_id, $client_policy_id)
    {

        $get_additional_rack_rate_relationship_json = $this->policyPremium2Model
            ->where('client_id', $client_id)
            ->where('client_policy_id', $client_policy_id)
            ->where('is_active', 1)
            ->where('additional_relationship IS NOT NULL', null, false)
            ->countAllResults();

        return $this->respond(['status' => true, 'data' => $get_additional_rack_rate_relationship_json, 'message' => "try"], 200);
    }

    public function getPolicyTypeForBasePolicy($client_id)
    {

        $result = $this->clientPolicyModel->getPolicyTypeForPolicyBinding($client_id);
        return $this->respond(['status' => true, 'data' => $result], 200);
    }

    public function getClientDetails($client_id)
    {
        $result = $this->clientModel->where('id', $client_id)->first();
        return $this->respond(['status' => true, 'data' => $result], 200);
    }

    public function getBranchUnitsByBranchId($branch_id)
    {

        $units = $this->clientBranchModel->select('units')->where('id', $branch_id)->first();

        if ($units) {
            return $units['units'];
        } else {
            return [];
        }
    }

    public function updateRackRateJson()
    {
        // $client_policy_id = 12;

        $results = $this->policyPremium2Model
            ->select('*')
            // ->where('client_policy_id', $client_policy_id)
            ->where('is_active', 1)
            ->groupBy('client_policy_id')
            ->get()
            ->getResultArray();


        $results2 = $this->policyPremium1Model
            ->select('*')
            // ->where('client_policy_id', $client_policy_id)
            ->where('is_active', 1)
            ->groupBy('client_policy_id')
            ->get()
            ->getResultArray();

        // dd($results, $results2);

        $client_policy_ids = [];
        $json = [];
        $json1 = [];

        foreach ($results as $key => $result) {
            $client_policy_id = $result['client_policy_id'];
            $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();
            $policy_terms = [];

            if (isset($client_policy_data['policy_terms'])) {
                $policy_terms = json_decode($client_policy_data['policy_terms'], true);
            }

            if (isset($policy_terms['family_floaters'])) {
                $family_floaters = $policy_terms['family_floaters'];

                if (isset($family_floaters['self']) && isset($family_floaters['spouse']) && isset($family_floaters['childrens']) && isset($family_floaters['parents']) && isset($family_floaters['parents-in-law']) && isset($family_floaters['either-parents-pil']) && isset($family_floaters['elders_count'])) {

                    $json1[] = $family_floaters;

                    $self = 1;
                    $spouse = 'any';
                    $childrens = 'any';
                    $parents = 'any';
                    $parents_in_law = 'any';

                    if ($family_floaters['self'] == 0) {
                        $self = 'NA';
                    }
                    if ($family_floaters['spouse'] == 0) {
                        $spouse = 'NA';
                    }
                    if ($family_floaters['childrens'] == 0) {
                        $childrens = 'NA';
                    }
                    if ($family_floaters['parents'] == 0) {
                        $parents = 'NA';
                    }
                    if ($family_floaters['parents-in-law'] == 0) {
                        $parents_in_law = 'NA';
                    }

                    $transformed_family_floaters = [
                        "self" => $self,
                        "spouse" => $spouse,
                        "childrens" => $childrens,
                        "parents" =>  $parents,
                        "parents-in-law" => $parents_in_law,
                    ];

                    $formatedJSON = json_encode($transformed_family_floaters);
                    $json[] = $formatedJSON;

                    $forUpdateData = [
                        "additional_relationship" => $formatedJSON,
                        "rack_rate_name" => 'Primary',
                    ];

                    $this->policyPremium2Model
                        ->where('client_policy_id', $client_policy_id)
                        ->set($forUpdateData)
                        ->update();
                }

                $client_policy_ids[] = $client_policy_id;
            }
        }

        foreach ($results2 as $key => $result) {
            $client_policy_id = $result['client_policy_id'];
            $client_policy_data = $this->clientPolicyModel->where('id', $client_policy_id)->first();

            // dd($client_policy_data);

            if (isset($client_policy_data) && $client_policy_data['policy_terms']) {

                $self = 1;
                $spouse = 'NA';
                $childrens = 'NA';
                $parents = 'NA';
                $parents_in_law = 'NA';

                $transformed_family_floaters = [
                    "self" => $self,
                    "spouse" => $spouse,
                    "childrens" => $childrens,
                    "parents" =>  $parents,
                    "parents-in-law" => $parents_in_law,
                ];

                $formatedJSON = json_encode($transformed_family_floaters);
                $json[] = $formatedJSON;

                $forUpdateData = [
                    "additional_relationship" => $formatedJSON,
                    "rack_rate_name" => 'Primary',
                ];

                $this->policyPremium1Model
                    ->where('client_policy_id', $client_policy_id)
                    ->set($forUpdateData)
                    ->update();
            }
        }

        $client_policy_ids[] = $client_policy_id;


        if (count($client_policy_ids) > 0) {
            echo 'There are ' . count($client_policy_ids) . ' records to be updated.';
            echo '
'; dd($client_policy_ids); } else { echo 'There is no records to be update.'; } } public function removeRackRate($rack_rate_name = null, $client_policy_id = null) { $this->myLogger->logme('error', 'Rack Rate Remove function called'); $data = [ 'updated_by' => get_session_userid(), 'is_active' => 0 ]; $rackRateData = $this->policyPremium2Model ->where('rack_rate_name', $rack_rate_name) ->where('client_policy_id', $client_policy_id) ->where('is_active', 1) ->countAllResults(); if ($rackRateData > 0) { $update = $this->policyPremium2Model ->where('rack_rate_name', $rack_rate_name) ->where('client_policy_id', $client_policy_id) ->set($data)->update(); if ($update) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'Rack Rate removed successfully', 'rr_count' => $rackRateData], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove Rack Rate', 'rr_count' => $rackRateData], 200); } } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Rack Rate not available', 'rr_count' => $rackRateData], 200); } } public function renameRackRateTab($rack_rate_name = null, $new_rack_rate_name = null, $client_policy_id = null) { $this->myLogger->logme('error', 'Rack Rate renameRackRateTab function called'); $data = [ 'updated_by' => get_session_userid(), 'rack_rate_name' => $new_rack_rate_name ]; $rackRateData = $this->policyPremium2Model ->where('rack_rate_name', $rack_rate_name) ->where('client_policy_id', $client_policy_id) ->where('is_active', 1) ->countAllResults(); if ($rackRateData > 0) { $update = $this->policyPremium2Model ->where('rack_rate_name', $rack_rate_name) ->where('client_policy_id', $client_policy_id) ->where('is_active', 1) ->set($data) ->update(); $affectedRows = $this->policyPremium2Model->affectedRows(); if ($update) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'Rack Rate renamed successfully', 'rr_count' => $affectedRows], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to rename Rack Rate', 'rr_count' => $affectedRows], 200); } } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'Rack Rate not available', 'rr_count' => $rackRateData, 'rack_rate_name' => $rack_rate_name, 'client_policy_id' => $client_policy_id, 'new_rack_rate_name' => $new_rack_rate_name,], 200); } } public function getBranchByClientID($client_id) { $branch_list = $this->clientBranchModel->where('client_id', $client_id)->where('is_active', 1)->findAll(); $policy_list = []; foreach ($branch_list as $value) { $policy_data = $this->clientPolicyModel ->select('client_policy.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.client_id', $value['client_id']) ->where('client_policy.client_branch_id', $value['id']) ->where('client_policy.is_active', 1) ->findAll(); $policy_list[$value['id']] = $policy_data; } if ($branch_list) { return $this->respond(['status' => true, 'data' => $branch_list, 'policy_data' => $policy_list], 200); } else { return $this->respond(['status' => false], 200); } } public function getClientAndBranchAndPolicy() { $clients = $this->clientModel->where('is_active', 1)->findAll(); $vehicles = $this->vehicleModel ->select('vehicle.*, clients.client_type') ->join('clients', 'clients.id=vehicle.owner') ->where('vehicle.is_active', 1)->findAll(); $clientIds = array_column($clients, 'id'); // Fetch branches in a single query $branches = $this->clientBranchModel ->whereIn('client_id', $clientIds) ->where('is_active', 1) ->findAll(); // Fetch policies in a single query $policies = $this->clientPolicyModel ->select(" client_policy.*, policy_type.policy_type, policy_type.ebp, policy_type.etp, policy_type.iep, policy_type.itp, policy_type.bap, DATE_FORMAT(client_policy.policy_start_date, '%d/%m/%Y') as policy_start_date, DATE_FORMAT(client_policy.policy_end_date, '%d/%m/%Y') as policy_end_date ") ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->whereIn('client_policy.client_id', $clientIds) ->where('client_policy.is_active', 1) ->findAll(); $branchList = []; $policyList = []; $policyListByClient = []; $unitList = []; foreach ($branches as $branch) { $branchList[$branch['client_id']][] = $branch; $unitList[$branch['id']][] = json_decode($branch['units']); } foreach ($policies as $policy) { $policyList[$policy['client_branch_id']][] = $policy; $policyListByClient[$policy['client_id']][] = $policy; if (isset($policyCount[$policy['client_id']])) { $policyCount[$policy['client_id']]++; } else { $policyCount[$policy['client_id']] = 1; } } foreach ($clients as &$client) { $client['client_policy_count'] = $policyCount[$client['id']] ?? 0; } if (!empty($branchList)) { return $this->respond([ 'status' => true, 'client_data' => $clients, 'vehicle_data' => $vehicles, 'branch_data' => $branchList, 'policy_data' => $policyList, 'policyListByClient' => $policyListByClient, 'unit_data' => $unitList, ], 200); } else { return $this->respond(['status' => false], 200); } } public function getCDAccNoByClientAndInsurer($client, $insurer) { $cdmData = $this->CDMasterModel->where('client_id', $client)->where('insurer_id', $insurer)->findAll(); if ($cdmData) { return $this->respond(['status' => true, 'data' => $cdmData], 200); } else { return $this->respond(['status' => false], 200); } } public function createClientWithMinimalData() { $postData = $this->request->getPost(); // print_r($postData); die; $client_type = $postData['client_type']; $client_data = [ 'client_type' => $postData['client_type'], 'client_name' => $postData['client_name'], 'short_name' => $postData['short_name'], 'pan' => $postData['pan'], 'client_code' => generate_client_code(), ]; // Add additional fields if client type is 2 if ($client_type == 2) { $client_data = array_merge($client_data, [ 'dob' => $postData['dob'], 'aadhar' => $postData['aadhar'], 'phone' => $postData['phone'], 'email' => $postData['email'], 'entity_type_id' => 7 ]); } else { $client_data['entity_type_id'] = $postData['entity_type_id']; } // Insert client data $client_insert = $this->clientModel->insert($client_data); if (!$client_insert) { return $this->respond(['status' => false, 'message' => 'Failed to create client'], 200); } // Additional logic for non-individual clients (client_type != 2) if ($client_type != 2) { $unit = $postData['short_name'] . '-' . $postData['branch_code']; $branch_data = [ 'client_id' => $client_insert, 'branch_name' => $postData['branch_name'], 'branch_code' => $postData['branch_code'], 'gst' => $postData['gst'], 'units' => $unit, ]; $branch_insert = $this->clientBranchModel->insert($branch_data); if ($branch_insert) { $contact_data = [ 'ref_id' => $branch_insert, 'contact_type' => 'client', 'name' => $postData['name'], 'mobile' => $postData['mobile'], ]; $this->levelContactModel->insert($contact_data); } } return $this->respond([ 'status' => true, 'data' => $postData, 'client_id' => $client_insert, 'branch_id' => $branch_insert ?? null, 'message' => 'Client created successfully' ], 200); } public function createVehicleWithMinimalData() { $data = $this->request->getPost(); $id = $this->request->getPost('vehicle_primary_key'); if ($id) { $vehicle_update = $this->vehicleModel->where('id', $id)->set($data)->update(); if ($vehicle_update) { return $this->respond(['status' => true, 'message' => 'Vehicle details updated successfully'], 200); } else { return $this->respond(['status' => false, 'message' => 'Failed to update vehicle details'], 200); } } else { $vehicle_insert = $this->vehicleModel->insert($data); if ($vehicle_insert) { $vehicles = $this->vehicleModel->where('is_active', 1)->findAll(); return $this->respond([ 'status' => true, 'vehicle_id' => $vehicle_insert, 'owner_id' => $data['owner'], 'owner_branch_id' => $data['branch_id'] ?? null, 'owner_type' => $data['Owner_type'], 'vehicles' => $vehicles, 'message' => 'Vehicle created successfully ' ], 200); } else { return $this->respond(['status' => false, 'message' => 'Failed to created vehicle'], 200); } } } public function createClientPolicyWithMinimalData() { $data = $this->request->getPost(); $insurerValue = (string) $this->request->getPost('insurer'); list($insurerBranchId, $insurerId) = explode('-', $insurerValue); $data['insurer_branch_id'] = $insurerBranchId; $data['insurer_id'] = $insurerId; $data['policy_status'] = 1; $data['is_addon'] = 1; $data['gst'] = 18; $data['created_by'] = get_session_userid(); $data['policy_start_date'] = change_date_format($this->request->getPost('policy_start_date'), 'd-m-Y', 'Y-m-d'); $data['policy_end_date'] = change_date_format($this->request->getPost('policy_end_date'), 'd-m-Y', 'Y-m-d'); $insert = $this->clientPolicyModel->insert($data); if ($insert) { $policies = $this->clientPolicyModel ->select('client_policy.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.client_id', $data['client_id']) ->where('client_policy.client_branch_id', $data['client_branch_id']) ->where('client_policy.is_active', 1) ->findAll(); return $this->respond(['status' => true, 'data' => $policies, 'client_policy_id' => $insert, 'message' => 'Client policy created successfully'], 200); } else { return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200); } } public function getPolicyDetailsByPolicyId($id) { $policies = $this->clientPolicyModel ->select('client_policy.*, policy_type.policy_type') ->join('policy_type', 'policy_type.id = client_policy.policy_type_id') ->where('client_policy.id', $id) ->where('client_policy.is_active', 1) ->findAll(); if ($policies) { return $this->respond(['status' => true, 'data' => $policies, 'message' => 'Client policy created successfully'], 200); } else { return $this->respond(['status' => false, 'message' => 'Failed to created client policy'], 200); } } public function check_cost_center($cost_center) { $uniqueAC = $this->clientModel ->where('cost_center', $cost_center) ->where('is_active', 1) ->findAll(); if ($uniqueAC != null) { return $this->respond(['status' => true, 'message' => 'The Cost Center is Already Exist', 'code' => 200], 200); } else { return $this->respond(['status' => false, 'code' => 404], 200); } } public function check_policy_no($policy_no) { $uniqueAC = $this->clientPolicyModel ->where('policy_no', $policy_no) ->where('is_active', 1) ->findAll(); if ($uniqueAC != null) { return $this->respond(['status' => true, 'message' => 'The Policy Number is Already Exist', 'code' => 200], 200); } else { return $this->respond(['status' => false, 'code' => 404], 200); } } public function get_client_policy_data_using_policy_no($policy_no) { $data = $this->clientPolicyModel ->select('client_policy.*, clients.client_type') ->join('clients', 'client_policy.client_id = clients.id') ->where('client_policy.policy_no', $policy_no) ->where('client_policy.is_active', 1) ->first(); if ($data) { return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200); } else { return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200); } } public function get_client_policy_data_using_policy_no_and_endo_no($policy_no, $endorsement_no) { $data = $this->clientPolicyModel ->select('client_policy.*, endorsement.endorsement_type') ->join('endorsement', 'client_policy.id = endorsement.client_policy_id') ->where('client_policy.policy_no', $policy_no) ->where('endorsement.endorsement_no', $endorsement_no) ->where('client_policy.is_active', 1) ->first(); if ($data) { return $this->respond(['status' => true, 'data' => $data, 'code' => 200], 200); } else { return $this->respond(['status' => false, 'message' => 'No Data Found', 'code' => 404], 200); } } }