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(); $this->leadsModel = new LeadsModel(); } //-------------------------------------------------------------------------------------------------------- public function checkDuplicateTableFieldValue() { $table = $this->request->getPost('table'); $field = $this->request->getPost('field'); $value = $this->request->getPost('value'); // Load the database if not already loaded $db = db_connect(); // Perform the query $builder = $db->table($table); $isDuplicate = $builder->where($field, $value)->countAllResults() > 0; // Return the result return $this->response->setJSON(['isDuplicate' => $isDuplicate]); } public function smapletest() { $headers = [ 'S.No', 'NAME OF EMP/DEP', 'EMP ID', // 'EMP/DEP TYPE', // 'RELATIONSHIP CODE', 'DOB', 'GENDER', 'PRE EXISTING AILMENTS', 'BASIC COVER SI', 'DATE OF COVERAGE', 'AGE', 'RELATIONSHIP', 'REMARKS', 'POLICY END DATE', 'NO OF DAYS', 'TPA ID', 'UHID', // 'PREMIUM', 'PRO RATA PREMIUM', 'GST', 'TOTAL AMOUNT' ]; $filePath = generateExcelWithHeader($headers); echo "Excel file created at: $filePath"; } public function testMailAttachments($email = 'venkateshraman786@gmail.com') { $message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

'; // $attachments = [ // ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], // ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], // ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] // ]; $attachments = []; $res = MailHelper::send_email(['mail' => $email, 'subject' => 'Mail Via Attachment Testing URL', 'message' => $message,'attachments' => $attachments]); print_rr($res); echo '------------------------------------------------------------------------------------------'; // print_rr($attachments); } //Function for Testing Member Review and Summery Confirmation Mail public function testingForReviewMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0) //this function for only tsesting some logics not use for business logic { // dd($client_id, $emp_code, $policy_id, $mail_active); if(empty($policy_id)){ $client_policy_ids = $this->employeeModel ->select('employee_polices.client_policy_id') ->join('employee_polices', 'employees.id = employee_polices.employee_id') ->where('employees.client_id', $client_id ) ->where('employees.emp_code', $emp_code ) ->where('employee_polices.is_active', 1 ) ->where('employees.is_active', 1 ) ->findAll(); $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id'); $client_policy_id = array_unique($client_policy_ids2); }else{ $client_policy_id = json_decode($policy_id, true); } // echo '
';
        // dd($client_policy_id);
        // print_r($unique_policy_ids); die;
        // sort($client_policy_id);

        $wholeData = '';
        $mail_send_return = '';
        $mail_send_return1 = '';
        $mail_send_return2 = '';

        if (!is_null($client_policy_id) && is_array($client_policy_id))
        {

            $empData = $this->employeeModel->where('emp_code', $emp_code )->where('client_id', $client_id ) ->where('is_active', 1 )->findAll();
            // dd($empData);
            $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self');

            // dd($filteredEmpData);

            $array_list = [];
            foreach ($client_policy_id as $key => $value) 
            {   
                $find = $this->employeeModel->getEmpFamilybyEmpCode(client_policy_id: $value,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();


            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;
                $params['common'] = [
                    'client_id' => $filteredEmpData[0]['client_id'], 
                    'client_branch_id' => $filteredEmpData[0]['client_branch_id'], 
                    'client_policy_id' => null,
                    'employee_policy_id' => null,
                    'employee_id' => $filteredEmpData[0]['id'],
                    'mail_type' => 'member_review_and_summary_mail',
                ];

                // dd($params);

                $wholeData =sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params);
                // print_r($wholeData); die;

                if($mail_active == 1){
                    $mail_send_return =  MailHelper::send_email($wholeData[0]);
                    $this->myLogger->logme("info", $mail_send_return);
                }

                // if (isset($wholeData)) {
                    
                //     $params['common']['mail_type'] = 'account_maneger_summary_mail';
                //     $account_manager_wholeData =sendMailNotification::sendMailNotification('account_maneger_summary_mail', $params);
                //     // print_r($account_manager_wholeData); die;

                //     if($account_manager_wholeData != null && $account_manager_wholeData != '' && count($account_manager_wholeData))
                //     {   
                //         if($mail_active > 0){

                //             foreach ($account_manager_wholeData as $key => $value) {
                //                 // $mail_send_return1 =  MailHelper::send_email($value);
                //                 $this->myLogger->logme("info", $mail_send_return1);
                //             }

                //         }

                //     }else{
                //         $this->myLogger->logme("error", 'Account Manager Mail Configuration not Enable for this client');
                //     }

                //     $params['common']['mail_type'] = 'client_hr_summary_mail';
                //     $client_hr_wholeData =sendMailNotification::sendMailNotification('client_hr_summary_mail', $params);
                //     // print_r($client_hr_wholeData); die;

                //     if($client_hr_wholeData != null && $client_hr_wholeData != '' &&count($client_hr_wholeData))
                //     {  
                //         if($mail_active > 0){

                //             foreach ($client_hr_wholeData as $key => $value) {
                //                 // $mail_send_return2 = MailHelper::send_email($value);
                //                 $this->myLogger->logme("info", $mail_send_return2);
                //             }
                //         }

                //     }else{
                //         $this->myLogger->logme("error", 'Client HR Mail Configuration not Enable for this client');
                //     }
                // }

            }else{
                $this->myLogger->logme("error", 'Member Review Mail Configuration not Enable for this client');
            }

        }
    
        print_r($wholeData);

        echo '
';
        echo '

member_review_and_summary_mail



'; print_r($mail_send_return); echo '

account_maneger_summary_mail



'; print_r($mail_send_return1); echo '

client_hr_summary_mail



'; print_r($mail_send_return2); // return $this->respond(['status' => 'success','code' => 200,'data' => [] ], 200); } //Function for Send Member Review and Summery Confirmation Mail public function sendMemberReviewConfirmationMail($client_id = 77, $emp_code = 'EMP001-K1', $policy_id = "", $mail_active = 0) { // dd($client_id, $emp_code, $policy_id, $mail_active); if(empty($policy_id)){ $client_policy_ids = $this->employeeModel ->select('employee_polices.client_policy_id') ->join('employee_polices', 'employees.id = employee_polices.employee_id') ->where('employees.client_id', $client_id ) ->where('employees.emp_code', $emp_code ) ->where('employee_polices.is_active', 1 ) ->where('employees.is_active', 1 ) ->findAll(); $client_policy_ids2 = array_column($client_policy_ids, 'client_policy_id'); $client_policy_id = array_unique($client_policy_ids2); }else{ $client_policy_id = json_decode($policy_id, true); } // dd($client_policy_id); if (!is_null($client_policy_id) && is_array($client_policy_id)) { $empData = $this->employeeModel ->where('emp_code', $emp_code) ->where('client_id', $client_id) ->where('is_active', 1) ->findAll(); $filteredEmpData = array_filter($empData, fn($item) => $item['relationship'] === 'Self'); if (empty($filteredEmpData)) { return $this->respond([ 'status' => 'error', 'code' => 404, 'message' => 'No active employee data found for the given criteria.', ], 404); } $array_list = []; foreach ($client_policy_id as $value) { $find = $this->employeeModel->getEmpFamilybyEmpCode( client_policy_id: $value, emp_code: $emp_code, client_id: $client_id, emp_status: ['draft', 'enrolled'], policy_status: ['draft', 'enrolled'] ); if (count($find) > 0) { $array_list[] = $find; } } $notification = $this->notificationModel ->where('client_id', $client_id) ->where('template_name', 'member_review_and_summary_mail') ->first(); if ($notification && $notification['enabled'] == 1) { $params = [ 'array_list' => $array_list, 'client_policy_id' => $client_policy_id, 'emp_code' => $emp_code, 'client_id' => $client_id, 'notification' => $notification, 'common' => [ 'client_id' => $filteredEmpData[0]['client_id'], 'client_branch_id' => $filteredEmpData[0]['client_branch_id'], 'client_policy_id' => null, 'employee_policy_id' => null, 'employee_id' => $filteredEmpData[0]['id'], 'mail_type' => 'member_review_and_summary_mail', ], ]; $wholeData = sendMailNotification::sendMailNotification('member_review_and_summary_mail', $params); if ($mail_active == 0) { // $mail_send_result = []; $mail_send_result = MailHelper::send_email($wholeData[0]); if ($mail_send_result['status'] === 'success') { return $this->respond([ 'status' => 'success', 'code' => 200, 'message' => 'Email sent successfully.', 'response' => $mail_send_result, ], 200); } else { return $this->respond([ 'status' => 'error', 'code' => 500, 'message' => 'Failed to send email.', 'details' => $mail_send_result, ], 500); } } return $this->respond([ 'status' => 'success', 'code' => 200, 'message' => 'Notification prepared but email not sent as mail_active is 0.', 'data' => $wholeData, ], 200); } return $this->respond([ 'status' => 'error', 'code' => 400, 'message' => 'Member Review Mail configuration is not enabled for this client.', ], 400); } return $this->respond([ 'status' => 'error', 'code' => 404, 'message' => 'No active client policy IDs found.', ], 404); } //-------------------------------------------------------------------------------------------------------- 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(); $data['lead_data'] = $this->leadsModel->getLeadForInsertClientList(); // 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;
        // dd($data);
        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);

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

        $CD_Account_Number = $this->CDMasterModel
            ->where('client_id', $client_id)
            ->where('insurer_id', $insurer_id)
            ->first();
        // Prepare the array with data
        $date = \DateTime::createFromFormat('d/m/Y', $record_date);
        $record_date = $date->format('Y-m-d');
        $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,
            'cd_ac_pk' => $CD_Account_Number['id'] ?? 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,
            'record_date' => $record_date
        ];
        // log_message('error','data for insert'.json_encode($data));die();
        // print_rr($data);die();


        // 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();
        $editData['lead_data'] = $this->leadsModel->getLeadForInsertClientList(2, $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', 'member_mobile', '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_pk']                           = $this->request->getPost('cd_ac_no');
        $data['gst']                                = $this->request->getPost('gst');
        $data['disclaimer']                         = $this->request->getPost('disclaimer');
        $data['is_member_modify_allowed']           = $this->request->getPost('is_member_modify_allowed') ? 1 : 0;
        $data['enrolment_visibility']               = $this->request->getPost('enrolment_visibility') ? 1 : 0;
        $data['is_lgbtq']                           = $this->request->getPost('is_lgbtq') ? 1 : 0;



        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');
            $data['reminder_date']   = $this->request->getPost('reminder_date');
        } 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_pk' => $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()
    {

        // print_r('test'); die;
        $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_pk']                           = $this->request->getPost('cd_ac_no');
        $data['gst']                                = $this->request->getPost('gst');
        $data['disclaimer']                         = $this->request->getPost('disclaimer');
        $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['is_member_modify_allowed']           = $this->request->getPost('is_member_modify_allowed') ? 1 : 0;
        $data['is_lgbtq']           = $this->request->getPost('is_lgbtq') ? 1 : 0;
        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');
            $data['reminder_date']   = $this->request->getPost('reminder_date');
        } 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 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();
            // $client_policy_data['policy_end_date'] = date('d/m/Y', strtotime($client_policy_data['policy_end_date']));
            $fromDate = new \DateTime($client_policy_data['policy_end_date']);
            $fromDate->modify('+1 year');
            $newDate = $fromDate->format('d/m/Y');


            // print_rr($client_policy_data['policy_end_date']);die();

            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,
                'end_date'  => $newDate,
                'new_start_date'  => date('d/m/Y', strtotime($client_policy_data['policy_end_date']))
            ], 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['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;

            $data['is_payable_employee']['self'] =  $this->request->getPost("is_payable_employee_for_self") ? 1 : 0;
            $data['is_payable_employee']['spouse'] = $this->request->getPost("is_payable_employee_for_spouse") ? 1 : 0;
            $data['is_payable_employee']['childern'] = $this->request->getPost("is_payable_employee_for_child") ? 1 : 0;
            $data['is_payable_employee']['elders'] = $this->request->getPost("is_payable_employee_for_elders") ? 1 : 0;


            $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;
            }

            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");
            $data['waiverof1,2,3&4thyearexclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
            $data['waiverof30dayswaitingperiod'] = $this->request->getPost("waiverof30dayswaitingperiod");
            $data['waiver_of_90_days_waiting_period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
            $data['waiver_of_other_waiting_periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
            $data['maternity_benefit'] = $this->request->getPost("maternity_benefit");
            $data['9monthwaitingperiodwaived'] = str_replace(',', '', $this->request->getPost("9monthwaitingperiodwaived"));
            $data['maternitycoverage']   = str_replace(',', '', $this->request->getPost("maternitycoverage"));
            $data['twindelivery']   = str_replace(',', '', $this->request->getPost("twindelivery"));
            $data['well_baby_well_mother_expenses']   = str_replace(',', '', $this->request->getPost("well_baby_well_mother_expenses"));
            $data['preandpostnatal']   = str_replace(',', '', $this->request->getPost("preandpostnatal"));
            $data['infertility_treatment_coverage']   = str_replace(',', '', $this->request->getPost("infertility_treatment_coverage"));
            $data['babyday1cover']   = str_replace(',', '', $this->request->getPost("babyday1cover"));
            $data['coverfromthedateofjoining'] = str_replace(',', '', $this->request->getPost("coverfromthedateofjoining"));
            $data['mid_term_addition_of_new_born_newly_wedded_spouse'] = str_replace(',', '', $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse"));
            $data['prehospitalizationcover'] = str_replace(',', '', $this->request->getPost("prehospitalizationcover"));
            $data['posthospitalizationcover'] =$this->request->getPost("posthospitalizationcover");
            $data['congenitaldiseasesinternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesinternal"));
            $data['congenitaldiseasesexternal'] = str_replace(',', '', $this->request->getPost("congenitaldiseasesexternal"));
            $data['copayzonewisecopay'] = $this->request->getPost("copayzonewisecopay");
            $data['roomrentlimit'] = str_replace(',', '', $this->request->getPost("roomrentlimit"));
            $data['icu_limit'] = str_replace(',', '', $this->request->getPost("icu_limit"));
            $data['proportionatedeductionclause'] = str_replace(',', '', $this->request->getPost("proportionatedeductionclause"));
            $data['ailmentcapping'] = $this->request->getPost("ailmentcapping");
            $data['ailment_capping_details'] = str_replace(',', '', $this->request->getPost("ailment_capping_details"));
            $data['corporatebuffer'] = str_replace(',', '', $this->request->getPost("corporatebuffer"));
            $data['non_admissible_contingency_corporate_buffer'] = str_replace(',', '', $this->request->getPost("non_admissible_contingency_corporate_buffer"));
            $data['ambulancecharges'] = str_replace(',', '', $this->request->getPost("ambulancecharges"));
            $data['airambulance'] = str_replace(',', '', $this->request->getPost("airambulance"));
            $data['reasonableandcustomarycharges'] = str_replace(',', '', $this->request->getPost("reasonableandcustomarycharges"));
            $data['daycaretreatment'] = str_replace(',', '', $this->request->getPost("daycaretreatment"));
            $data['lasiksurgery'] = str_replace(',', '', $this->request->getPost("lasiksurgery"));
            $data['ayudhtreatmentcover'] = str_replace(',', '', $this->request->getPost("ayudhtreatmentcover"));
            $data['moderntreatmentsasperirdai'] = str_replace(',', '', $this->request->getPost("moderntreatmentsasperirdai"));
            $data['opd_treatment'] = str_replace(',', '', $this->request->getPost("opd_treatment"));
            $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['terrorism'] = str_replace(',', '', $this->request->getPost("terrorism"));
            $data['widower_cover'] = str_replace(',', '', $this->request->getPost("widower_cover"));
            $data['breavement_cover'] = str_replace(',', '', $this->request->getPost("breavement_cover"));

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

            $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['enrollment_display_key'] = $this->enrollmentGMCDisplayValueTransform();

            // print_r($data);die;

            $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 enrollmentGMCDisplayValueTransform()
    {
        $data = [];

        if ($this->request->getPost("waiverofpreexistingdiseases_display")) {
            $data['Waiver of Pre-existing Diseases'] = $this->request->getPost("waiverofpreexistingdiseases");
        }
        
        if ($this->request->getPost("waiverof1234thyearexclusions_display")) {
            $data['Waiver of 1, 2, 3 & 4th year Exclusions'] = $this->request->getPost("waiverof1,2,3&4thyearexclusions");
        }
        
        if ($this->request->getPost("waiverof30dayswaitingperiod_display")) {
            $data['Waiver of 30 days waiting period'] = $this->request->getPost("waiverof30dayswaitingperiod");
        }
        
        if ($this->request->getPost("waiver_of_90_days_waiting_period_display")) {
            $data['Waiver of 90 Days Waiting Period'] = $this->request->getPost("waiver_of_90_days_waiting_period");
        }
        
        if ($this->request->getPost("waiver_of_other_waiting_periods_display")) {
            $data['Waiver of Other Waiting Periods'] = $this->request->getPost("waiver_of_other_waiting_periods");
        }
        
        if ($this->request->getPost("maternity_benefit_display")) {
            $data['Maternity Benefit'] = $this->request->getPost("maternity_benefit");
        }
        
        if ($this->request->getPost("9monthwaitingperiodwaived_display")) {
            $data['9-month waiting Period - waived'] = $this->request->getPost("9monthwaitingperiodwaived");
        }
        
        if ($this->request->getPost("maternitycoverage_display")) {
            $data['Maternity Coverage'] = $this->request->getPost("maternitycoverage");
        }
        
        if ($this->request->getPost("twindelivery_display")) {
            $data['Twin Delivery'] = $this->request->getPost("twindelivery");
        }
        
        if ($this->request->getPost("well_baby_well_mother_expenses_display")) {
            $data['Well baby / Well Mother Expenses'] = $this->request->getPost("well_baby_well_mother_expenses");
        }
        
        if ($this->request->getPost("preandpostnatal_display")) {
            $data['Pre and Post natal'] = $this->request->getPost("preandpostnatal");
        }
        
        if ($this->request->getPost("infertility_treatment_coverage_display")) {
            $data['Infertility Treatment Coverage'] = $this->request->getPost("infertility_treatment_coverage");
        }
        
        if ($this->request->getPost("babyday1cover_display")) {
            $data['Baby Day 1 Cover'] = $this->request->getPost("babyday1cover");
        }
        
        if ($this->request->getPost("coverfromthedateofjoining_display")) {
            $data['Cover from the date of Joining'] = $this->request->getPost("coverfromthedateofjoining");
        }
        
        if ($this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse_display")) {
            $data['Mid Term Addition of New Born / Newly Wedded Spouse'] = $this->request->getPost("mid_term_addition_of_new_born_newly_wedded_spouse");
        }
        
        if ($this->request->getPost("prehospitalizationcover_display")) {
            $data['Pre Hospitalization Cover'] = $this->request->getPost("prehospitalizationcover");
        }
        
        if ($this->request->getPost("posthospitalizationcover_display")) {
            $data['Post Hospitalization Cover'] = $this->request->getPost("posthospitalizationcover");
        }
        
        if ($this->request->getPost("congenitaldiseasesinternal_display")) {
            $data['Congenital Diseases - Internal'] = $this->request->getPost("congenitaldiseasesinternal");
        }
        
        if ($this->request->getPost("congenitaldiseasesexternal_display")) {
            $data['Congenital Diseases - External'] = $this->request->getPost("congenitaldiseasesexternal");
        }
        
        if ($this->request->getPost("copayzonewisecopay_display")) {
            $data['Co-Pay/Zone wise Co Pay'] = $this->request->getPost("copayzonewisecopay");
        }
        
        if ($this->request->getPost("roomrentlimit_display")) {
            $data['Room Rent Limit'] = $this->request->getPost("roomrentlimit");
        }
        
        if ($this->request->getPost("icu_limit_display")) {
            $data['ICU Limit'] = $this->request->getPost("icu_limit");
        }
        
        if ($this->request->getPost("proportionatedeductionclause_display")) {
            $data['Proportionate Deduction Clause'] = $this->request->getPost("proportionatedeductionclause");
        }
        
        if ($this->request->getPost("ailmentcapping_display")) {
            $data['Ailment capping'] = $this->request->getPost("ailmentcapping");
        }
        
        if ($this->request->getPost("ailment_capping_details_display")) {
            $data['Ailment capping Details'] = $this->request->getPost("ailment_capping_details");
        }
        
        if ($this->request->getPost("corporatebuffer_display")) {
            $data['Corporate Buffer'] = $this->request->getPost("corporatebuffer");
        }
        
        if ($this->request->getPost("non_admissible_contingency_corporate_buffer_display")) {
            $data['Non-Admissible / Contingency Corporate Buffer'] = $this->request->getPost("non_admissible_contingency_corporate_buffer");
        }
        
        if ($this->request->getPost("ambulancecharges_display")) {
            $data['Ambulance Charges'] = $this->request->getPost("ambulancecharges");
        }
        
        if ($this->request->getPost("airambulance_display")) {
            $data['Air Ambulance'] = $this->request->getPost("airambulance");
        }
        
        if ($this->request->getPost("reasonableandcustomarycharges_display")) {
            $data['Reasonable and Customary Charges'] = $this->request->getPost("reasonableandcustomarycharges");
        }
        
        if ($this->request->getPost("daycaretreatment_display")) {
            $data['Day Care Treatment'] = $this->request->getPost("daycaretreatment");
        }
        
        if ($this->request->getPost("lasiksurgery_display")) {
            $data['Lasik Surgery'] = $this->request->getPost("lasiksurgery");
        }
        
        if ($this->request->getPost("ayushtreatmentcover_display")) {
            $data['AYUSH treatment cover'] = $this->request->getPost("ayudhtreatmentcover");
        }
        
        if ($this->request->getPost("moderntreatmentsasperirdai_display")) {
            $data['Modern treatments as per IRDAI'] = $this->request->getPost("moderntreatmentsasperirdai");
        }
        
        if ($this->request->getPost("opd_treatment_display")) {
            $data['OPD Treatment'] = $this->request->getPost("opd_treatment");
        }
        
        if ($this->request->getPost("days_of_discharge_display")) {
            $data['Claim Intimation Clause'] = $this->request->getPost("days_of_discharge");
        }
        
        if ($this->request->getPost("days_from_dod_display")) {
            $data['Claim Submission'] = $this->request->getPost("days_from_dod");
        }
        
        if ($this->request->getPost("terrorism_display")) {
            $data['Terrorism'] = $this->request->getPost("terrorism");
        }
        
        if ($this->request->getPost("widower_cover_display")) {
            $data['Widower Cover'] = $this->request->getPost("widower_cover");
        }
        
        if ($this->request->getPost("breavement_cover_display")) {
            $data['Breavement Cover'] = $this->request->getPost("breavement_cover");
        }

        if ($this->request->getPost("special_condition_display_value")) {
            
            $specialConditionKeyValue = $this->request->getPost("special_condition_display_value") ?? [];
            $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);

            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
                $data = array_merge($data, $mergedArray);
            }
        }
        
        if(isset($data) && !empty($data)){
            return $data;
        }else{
            $data = [];
            return $data;
        }
    
    }

    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['is_payable_employee']['self'] = 0;

            $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['medical_expenses_medical_extension'] = str_replace(',', '', $this->request->getPost("medical_expenses_medical_extension"));
            $data['opd_treatment_cover'] = str_replace(',', '', $this->request->getPost("opd_treatment_cover"));
            $data['ambulanceCharges']   = str_replace(',', '', $this->request->getPost("ambulanceCharges"));
            $data['repatriation_of_mortal_remains']   = str_replace(',', '', $this->request->getPost("repatriation_of_mortal_remains"));
            $data['childrenEducationWelfareFund'] = str_replace(',', '', $this->request->getPost("childrenEducationWelfareFund"));
            $data['terrorism']             = $this->request->getPost("terrorism");
            $data['worldwideCover']        = $this->request->getPost("worldwideCover");
            $data['family_transportation_benefits']        = $this->request->getPost("family_transportation_benefits");
            $data['fractures_dislocation_burns']        = $this->request->getPost("fractures_dislocation_burns");
            $data['coma']        = $this->request->getPost("coma");
            $data['carriageOfDeadBody']   = $this->request->getPost("carriageOfDeadBody");
            $data['compassionateVisitExpenses']   = $this->request->getPost("compassionateVisitExpenses");
            $data['travel_expenses_for_medical_treatment']        = $this->request->getPost("travel_expenses_for_medical_treatment");
            $data['daily_cash_allowance']        = $this->request->getPost("daily_cash_allowance");
            $data['artifical_limb_and_prosthesis']        = $this->request->getPost("artifical_limb_and_prosthesis");
            $data['animalSnakeInsectBite']        = $this->request->getPost("animalSnakeInsectBite");
            $data['air_ambulance']        = $this->request->getPost("air_ambulance");


            $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")) ?? [];

            $data['enrollment_display_key'] = $this->enrollmentGPADisplayValueTransform();

            // print_r($data); die;

            $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 enrollmentGPADisplayValueTransform()
    {   
        $data = [];

        if ($this->request->getPost("accidentalDeathBenefit_display")) {
            $data['Accidental Death Benefit'] = $this->request->getPost("accidentalDeathBenefit");
        }
        if ($this->request->getPost("permanentTotalDisablement_display")) {
            $data['Permanent Total Disablement'] = $this->request->getPost("permanentTotalDisablement");
        }
        if ($this->request->getPost("permanentPartialDisablement_display")) {
            $data['Permanent Partial Disablement'] = $this->request->getPost("permanentPartialDisablement");
        }
        if ($this->request->getPost("temporaryTotalDisablementBenefit_display")) {
            $data['Temporary Total Disablement Benefit'] = $this->request->getPost("temporaryTotalDisablementBenefit");
        }
        if ($this->request->getPost("medical_expenses_medical_extension_display")) {
            $data['Medical Expenses / Medical Extension (IPD)'] = $this->request->getPost("medical_expenses_medical_extension");
        }
        if ($this->request->getPost("opd_treatment_cover_display")) {
            $data['OPD Treatment Cover'] = $this->request->getPost("opd_treatment_cover");
        }
        if ($this->request->getPost("ambulanceCharges_display")) {
            $data['Ambulance Charges'] = $this->request->getPost("ambulanceCharges");
        }
        if ($this->request->getPost("repatriation_of_mortal_remains_display")) {
            $data['Repatriation of Mortal Remains'] = $this->request->getPost("repatriation_of_mortal_remains");
        }
        if ($this->request->getPost("childrenEducationWelfareFund_display")) {
            $data['Children Education Welfare Fund'] = $this->request->getPost("childrenEducationWelfareFund");
        }
        if ($this->request->getPost("terrorism_display")) {
            $data['Terrorism'] = $this->request->getPost("terrorism");
        }
        if ($this->request->getPost("worldwideCover_display")) {
            $data['Worldwide Cover'] = $this->request->getPost("worldwideCover");
        }
        if ($this->request->getPost("family_transportation_benefits_display")) {
            $data['Family Transportation Benefits'] = $this->request->getPost("family_transportation_benefits");
        }
        if ($this->request->getPost("fractures_dislocation_burns_display")) {
            $data['Fractures / Dislocation / Burns'] = $this->request->getPost("fractures_dislocation_burns");
        }
        if ($this->request->getPost("coma_display")) {
            $data['Coma'] = $this->request->getPost("coma");
        }
        if ($this->request->getPost("carriageofDeadBody_display")) {
            $data['Carriage of Dead Body'] = $this->request->getPost("carriageOfDeadBody");
        }
        if ($this->request->getPost("compassionateVisitExpenses_display")) {
            $data['Compassionate Visit Expenses'] = $this->request->getPost("compassionateVisitExpenses");
        }
        if ($this->request->getPost("travel_expenses_for_medical_treatment_display")) {
            $data['Travel expenses for Medical Treatment'] = $this->request->getPost("travel_expenses_for_medical_treatment");
        }
        if ($this->request->getPost("daily_cash_allowance_display")) {
            $data['Daily cash Allowance'] = $this->request->getPost("daily_cash_allowance");
        }
        if ($this->request->getPost("artifical_limb_and_prosthesis_display")) {
            $data['Artifical Limb and Prosthesis'] = $this->request->getPost("artifical_limb_and_prosthesis");
        }
        if ($this->request->getPost("animalSnakeInsectBite_display")) {
            $data['Animal/Snake/Insect Bite'] = $this->request->getPost("animalSnakeInsectBite");
        }
        if ($this->request->getPost("air_ambulance_display")) {
            $data['Air Ambulance'] = $this->request->getPost("air_ambulance");
        }

        if ($this->request->getPost("gpa_special_condition_display_value")) {

            $specialConditionKeyValue = $this->request->getPost("gpa_special_condition_display_value") ?? [];
            $specialConditionKeyValue = json_decode($specialConditionKeyValue, true);

            if (is_array($specialConditionKeyValue) && count($specialConditionKeyValue) > 0) {
                $mergedArray = array_merge(...array_map(fn($item) => (array) $item, $specialConditionKeyValue));
                $data = array_merge($data, $mergedArray);
            }
        }
        // print_r($data); die;

        if (isset($data) && !empty($data)) {
            return $data;
        } else {
            $data = [];
            return $data;
        }
    }

    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) && $termsData->sum_insured == "" && $termsData->sum_insured == null) {
            return $this->respond(['status' => false, 'code' => 200, 'message' => 'The Policy terms Sum Insured field is empty', 'data' => $record], 200);
        }

        if (isset($termsData->sumInsured2) && $termsData->sumInsured2 == "" && $termsData->sumInsured2 == null) {
            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.";
        }
    }

    //for this function policy binding dropdown list use ( client policy )
    public function getClientBranch($client_id)
    {

        $branchs = $this->clientBranchModel
            ->select('*')
            ->where('client_id', $client_id)
            ->where('is_active', 1)
            ->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");

        if (!empty($policy_terms)) {
            $policy_terms = json_decode($policy_terms, true); 
            $policy_terms['is_payable_employee']['self'] = 0; 
            $policy_terms = json_encode($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) && $JSON->sum_insured != "" && $JSON->sum_insured != null) {
            $multi_si[] = $JSON->sum_insured;
        } elseif (isset($JSON->sumInsured2) && $JSON->sumInsured2 != "" && $JSON->sumInsured2 != null) {
            $multi_si[] = $JSON->sumInsured2;
        }

        if (isset($JSON->multiple_sum_insured) && is_array($JSON->multiple_sum_insured)) {
            foreach ($JSON->multiple_sum_insured as $msi) {
                if ($msi != "" && $msi != null) {
                    $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() { // ---------for client----------------------------------------------------------------------------- $clients = $this->clientModel->where('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(); // -----------for vehicle --------------------------------------------------------------------------- $vehicles = $this->vehicleModel ->select('vehicle.*, clients.client_type') ->join('clients', 'clients.id=vehicle.owner') ->where('vehicle.is_active', 1)->findAll(); // -----------for Insurer --------------------------------------------------------------------------- //fetch all insurer data $insurers = $this->insurerModel->where('is_active', 1)->findAll(); //map the insurer primary key to column $insurersIds = array_column($insurers, 'id'); // Fetch insurer branches in a single query $insurerBranches = $this->insurerBranchModel ->whereIn('insurer_id', $insurersIds) ->where('is_active', 1) ->findAll(); // -----------for Policy --------------------------------------------------------------------------- // 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 = []; $insurerBranchList = []; //for client branch mapping to the client foreach ($branches as $branch) { $branchList[$branch['client_id']][] = $branch; $unitList[$branch['id']][] = json_decode($branch['units']); } //for insurer branch mapping to the insurer foreach ($insurerBranches as $branch) { $insurerBranchList[$branch['insurer_id']][] = $branch; } //for client policy mapping to the branch and client 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; } } //get policy count 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, 'insurer_data' => $insurers, 'insurer_branch_data' => $insurerBranchList, '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, 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('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); } } public function get_client_branch_data($id = null) { if ($id) { $branch_data = $this->clientBranchModel ->select('client_branch.*, clients.pan') ->join('clients', 'client_branch.client_id = clients.id') ->where(['client_branch.id' => $id, 'client_branch.is_active' => 1]) ->first(); $branch_contact_data = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'client', 'is_active' => 1])->orderBy('id','asc')->first(); 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 getClientData() { $client_id = $this->request->getGet('client_id') ?? null; $result = $this->clientModel->getClientData($client_id); dd($result); } // --------------------------------------------------------------------------------------------------------- public function updatePolicyTermsKey() { $client_id = $this->request->getGet('client_id'); $policy_type_id = $this->request->getGet('policy_type_id'); $query = $this->clientPolicyModel ->where("policy_terms IS NOT NULL AND policy_terms <> ''") ->where('is_active', 1); if (!empty($client_id)) { $query->where('client_id', $client_id); } if (!empty($policy_type_id)) { $query->where('policy_type_id', $policy_type_id); } $data = $query->findAll(); for ($i = 0; $i < count($data); $i++) { // dd($data[$i]); if (isset($data[$i]['policy_terms']) && !empty($data[$i]['policy_terms'])) { $policyTerms = json_decode($data[$i]['policy_terms'], true); } else { continue; } // dd($policyTerms); $is_addon = $data[$i]['is_addon']; $payable_arr = []; if (in_array($data[$i]['policy_type_id'], [2,3]) && $is_addon == 1) { $payable_arr = [ "self" => 0, "spouse" => 0, "childern" => 0, "elders" => 0, ]; } else if ($data[$i]['policy_type_id'] == 3 && $is_addon == 3) { $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,]; } else if (in_array($data[$i]['policy_type_id'], [4, 5])) { $payable_arr = ["self" => 1,"spouse" => 1,"childern" => 1,"elders" => 1,]; } // Initialize an empty array for the ordered policy terms $orderedPolicyTerms = []; if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){ // Set default value of copayzonewisecopay to "empty" // $ans = isset($policyTerms['copayzonewisecopay']) ? $policyTerms['copayzonewisecopay'] : 'empty'; // add is_payable_employee for the GMC Policy if (isset($policyTerms['age_ratio'])) { if(!isset($policyTerms['is_payable_employee'])){ $aliment_index = array_search('age_ratio', array_keys($policyTerms)); $orderedPolicyTerms[] = [ "key" => "is_payable_employee", "value" => $payable_arr, "position" => $aliment_index + 1, ]; } } // // Add copayzonewisecopay and copayzonewisecopaydata if they exist_ // if (isset($policyTerms['copayzonewisecopay'])) { // if(!isset($policyTerms['co_pay_details'])){ // $co_pay_details_value = ""; // if (strtolower($ans) == "nil" || $ans == 0) { // $policyTerms['copayzonewisecopay'] = 0; // $co_pay_details_value = ""; // } elseif ($ans != 'empty' && $ans !== 'Nil' && $ans !== null && $ans != '' && $ans != 0) { // $policyTerms['copayzonewisecopay'] = 1; // $co_pay_details_value = $ans; // } // $co_pay_index = array_search('copayzonewisecopay', array_keys($policyTerms)); // $orderedPolicyTerms[] = [ // "key" => "co_pay_details", // "value" => $co_pay_details_value, // "position" => $co_pay_index + 2, // ]; // unset($policyTerms['optionalparentalcopay']); // } // } // Add ailmentcapping and ailmentcappingdata if they exist if (isset($policyTerms['ailmentcapping'])) { if(!isset($policyTerms['ailment_capping_details'])){ $aliment_index = array_search('ailmentcapping', array_keys($policyTerms)); $orderedPolicyTerms[] = [ "key" => "ailment_capping_details", "value" => "", "position" => $aliment_index + 2, ]; } } }else { // add is_payable_employee for the GMC Policy if (isset($policyTerms['age_ratio'])) { if(!isset($policyTerms['is_payable_employee'])){ $aliment_index = array_search('age_ratio', array_keys($policyTerms)); $orderedPolicyTerms[] = [ "key" => "is_payable_employee", "value" => [ "self" => 0, ], "position" => $aliment_index + 1, ]; } }else{ if(!isset($policyTerms['is_payable_employee'])){ $orderedPolicyTerms[] = [ "key" => "is_payable_employee", "value" => [ "self" => 0, ], "position" => 2, ]; } } } foreach ($orderedPolicyTerms as $term) { $position = $term['position']; $key = $term['key']; $value = $term['value']; // Insert the key-value pair at the specified index $policyTerms = array_merge( array_slice($policyTerms, 0, $position, true), [$key => $value], array_slice($policyTerms, $position, null, true) ); } foreach ($policyTerms as $key => $term) { if ($term == "0") { $policyTerms[$key] = "No"; // Use = for assignment } elseif ($term == "1") { $policyTerms[$key] = "Yes"; // Use = for assignment } } if(in_array($data[$i]['policy_type_id'], [2,3,4,5])){ if (!isset($policyTerms['waiver_of_90_days_waiting_period'])) { $policyTerms['waiver_of_90_days_waiting_period'] = ""; } if (!isset($policyTerms['waiver_of_other_waiting_periods'])) { $policyTerms['waiver_of_other_waiting_periods'] = ""; } if (!isset($policyTerms['maternity_benefit'])) { $policyTerms['maternity_benefit'] = ""; } if (!isset($policyTerms['well_baby_well_mother_expenses'])) { $policyTerms['well_baby_well_mother_expenses'] = ""; } if (!isset($policyTerms['icu_limit'])) { $policyTerms['icu_limit'] = ""; } if (!isset($policyTerms['infertility_treatment_coverage'])) { $policyTerms['infertility_treatment_coverage'] = ""; } if (!isset($policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'])) { $policyTerms['mid_term_addition_of_new_born_newly_wedded_spouse'] = ""; } if (!isset($policyTerms['non_admissible_contingency_corporate_buffer'])) { $policyTerms['non_admissible_contingency_corporate_buffer'] = ""; } if (!isset($policyTerms['terrorism'])) { $policyTerms['terrorism'] = ""; } if (!isset($policyTerms['widower_cover'])) { $policyTerms['widower_cover'] = ""; } if (!isset($policyTerms['breavement_cover'])) { $policyTerms['breavement_cover'] = ""; } if (!isset($policyTerms['enrollment_display_key'])) { $policyTerms['enrollment_display_key'] = $this->existingGMCDisplayValueTransform($policyTerms); } } else if($data[$i]['policy_type_id'] == 1){ if (!isset($policyTerms['medical_expenses_medical_extension'])) { $policyTerms['medical_expenses_medical_extension'] = ""; } if (!isset($policyTerms['opd_treatment_cover'])) { $policyTerms['opd_treatment_cover'] = ""; } if (!isset($policyTerms['repatriation_of_mortal_remains'])) { $policyTerms['repatriation_of_mortal_remains'] = ""; } if (!isset($policyTerms['family_transportation_benefits'])) { $policyTerms['family_transportation_benefits'] = ""; } if (!isset($policyTerms['fractures_dislocation_burns'])) { $policyTerms['fractures_dislocation_burns'] = ""; } if (!isset($policyTerms['coma'])) { $policyTerms['coma'] = ""; } if (!isset($policyTerms['travel_expenses_for_medical_treatment'])) { $policyTerms['travel_expenses_for_medical_treatment'] = ""; } if (!isset($policyTerms['daily_cash_allowance'])) { $policyTerms['daily_cash_allowance'] = ""; } if (!isset($policyTerms['artifical_limb_and_prosthesis'])) { $policyTerms['artifical_limb_and_prosthesis'] = ""; } if (!isset($policyTerms['air_ambulance'])) { $policyTerms['air_ambulance'] = ""; } if (!isset($policyTerms['enrollment_display_key'])) { $policyTerms['enrollment_display_key'] = $this->existingGPADisplayValueTransform($policyTerms); } } // dd($policyTerms); // Re-encode the ordered policy terms $updatedPolicyTerms = json_encode($policyTerms); // dd($updatedPolicyTerms); // dd($orderedPolicyTerms, $updatedPolicyTerms); $this->clientPolicyModel->update($data[$i]['id'], ['policy_terms' => $updatedPolicyTerms]); } } public function existingGMCDisplayValueTransform($data) { $transformedData = []; if (isset($data["waiverofpreexistingdiseases"])) { $transformedData['Waiver of Pre-existing Diseases'] = $data["waiverofpreexistingdiseases"]; } if (isset($data["waiverof1,2,3&4thyearexclusions"])) { $transformedData['Waiver of 1, 2, 3 & 4th year Exclusions'] = $data["waiverof1,2,3&4thyearexclusions"]; } if (isset($data["waiverof30dayswaitingperiod"])) { $transformedData['Waiver of 30 days waiting period'] = $data["waiverof30dayswaitingperiod"]; } if (isset($data["waiver_of_90_days_waiting_period"])) { $transformedData['Waiver of 90 Days Waiting Period'] = $data["waiver_of_90_days_waiting_period"]; } if (isset($data["waiver_of_other_waiting_periods"])) { $transformedData['Waiver of Other Waiting Periods'] = $data["waiver_of_other_waiting_periods"]; } if (isset($data["maternity_benefit"])) { $transformedData['Maternity Benefit'] = $data["maternity_benefit"]; } if (isset($data["9monthwaitingperiodwaived"])) { $transformedData['9-month waiting Period - waived'] = $data["9monthwaitingperiodwaived"]; } if (isset($data["maternitycoverage"])) { $transformedData['Maternity Coverage'] = $data["maternitycoverage"]; } if (isset($data["twindelivery"])) { $transformedData['Twin Delivery'] = $data["twindelivery"]; } if (isset($data["well_baby_well_mother_expenses"])) { $transformedData['Well baby / Well Mother Expenses'] = $data["well_baby_well_mother_expenses"]; } if (isset($data["preandpostnatal"])) { $transformedData['Pre and Post natal'] = $data["preandpostnatal"]; } if (isset($data["infertility_treatment_coverage"])) { $transformedData['Infertility Treatment Coverage'] = $data["infertility_treatment_coverage"]; } if (isset($data["babyday1cover"])) { $transformedData['Baby Day 1 Cover'] = $data["babyday1cover"]; } if (isset($data["coverfromthedateofjoining"])) { $transformedData['Cover from the date of Joining'] = $data["coverfromthedateofjoining"]; } if (isset($data["mid_term_addition_of_new_born_newly_wedded_spouse"])) { $transformedData['Mid Term Addition of New Born / Newly Wedded Spouse'] = $data["mid_term_addition_of_new_born_newly_wedded_spouse"]; } if (isset($data["prehospitalizationcover"])) { $transformedData['Pre Hospitalization Cover'] = $data["prehospitalizationcover"]; } if (isset($data["posthospitalizationcover"])) { $transformedData['Post Hospitalization Cover'] = $data["posthospitalizationcover"]; } if (isset($data["congenitaldiseasesinternal"])) { $transformedData['Congenital Diseases - Internal'] = $data["congenitaldiseasesinternal"]; } if (isset($data["congenitaldiseasesexternal"])) { $transformedData['Congenital Diseases - External'] = $data["congenitaldiseasesexternal"]; } if (isset($data["copayzonewisecopay"])) { $transformedData['Co-Pay/Zone wise Co Pay'] = $data["copayzonewisecopay"]; } if (isset($data["roomrentlimit"])) { $transformedData['Room Rent Limit'] = $data["roomrentlimit"]; } if (isset($data["icu_limit"])) { $transformedData['ICU Limit'] = $data["icu_limit"]; } if (isset($data["proportionatedeductionclause"])) { $transformedData['Proportionate Deduction Clause'] = $data["proportionatedeductionclause"]; } if (isset($data["ailmentcapping"])) { $transformedData['Ailment capping'] = $data["ailmentcapping"]; } if (isset($data["ailment_capping_details"])) { $transformedData['Ailment capping Details'] = $data["ailment_capping_details"]; } if (isset($data["corporatebuffer"])) { $transformedData['Corporate Buffer'] = $data["corporatebuffer"]; } if (isset($data["non_admissible_contingency_corporate_buffer"])) { $transformedData['Non-Admissible / Contingency Corporate Buffer'] = $data["non_admissible_contingency_corporate_buffer"]; } if (isset($data["ambulancecharges"])) { $transformedData['Ambulance Charges'] = $data["ambulancecharges"]; } if (isset($data["airambulance"])) { $transformedData['Air Ambulance'] = $data["airambulance"]; } if (isset($data["reasonableandcustomarycharges"])) { $transformedData['Reasonable and Customary Charges'] = $data["reasonableandcustomarycharges"]; } if (isset($data["daycaretreatment"])) { $transformedData['Day Care Treatment'] = $data["daycaretreatment"]; } if (isset($data["lasiksurgery"])) { $transformedData['Lasik Surgery'] = $data["lasiksurgery"]; } if (isset($data["ayushtreatmentcover"])) { $transformedData['AYUSH treatment cover'] = $data["ayushtreatmentcover"]; } if (isset($data["moderntreatmentsasperirdai"])) { $transformedData['Modern treatments as per IRDAI'] = $data["moderntreatmentsasperirdai"]; } if (isset($data["opd_treatment"])) { $transformedData['OPD Treatment'] = $data["opd_treatment"]; } if (isset($data["days_of_discharge"])) { $transformedData['Claim Intimation Clause'] = $data["days_of_discharge"]; } if (isset($data["days_from_dod"])) { $transformedData['Claim Submission'] = $data["days_from_dod"]; } if (isset($data["terrorism"])) { $transformedData['Terrorism'] = $data["terrorism"]; } if (isset($data["widower_cover"])) { $transformedData['Widower Cover'] = $data["widower_cover"]; } if (isset($data["breavement_cover"])) { $transformedData['Breavement Cover'] = $data["breavement_cover"]; } return !empty($transformedData) ? $transformedData : []; } public function existingGPADisplayValueTransform($data) { $transformedData = []; if (isset($data["accidentalDeathBenefit"])) { $transformedData['Accidental Death Benefit'] = $data["accidentalDeathBenefit"]; } if (isset($data["permanentTotalDisablement"])) { $transformedData['Permanent Total Disablement'] = $data["permanentTotalDisablement"]; } if (isset($data["permanentPartialDisablement"])) { $transformedData['Permanent Partial Disablement'] = $data["permanentPartialDisablement"]; } if (isset($data["temporaryTotalDisablementBenefit"])) { $transformedData['Temporary Total Disablement Benefit'] = $data["temporaryTotalDisablementBenefit"]; } if (isset($data["medical_expenses_medical_extension"])) { $transformedData['Medical Expenses / Medical Extension (IPD)'] = $data["medical_expenses_medical_extension"]; } if (isset($data["opd_treatment_cover"])) { $transformedData['OPD Treatment Cover'] = $data["opd_treatment_cover"]; } if (isset($data["ambulanceCharges"])) { $transformedData['Ambulance Charges'] = $data["ambulanceCharges"]; } if (isset($data["repatriation_of_mortal_remains"])) { $transformedData['Repatriation of Mortal Remains'] = $data["repatriation_of_mortal_remains"]; } if (isset($data["childrenEducationWelfareFund"])) { $transformedData['Children Education Welfare Fund'] = $data["childrenEducationWelfareFund"]; } if (isset($data["terrorism"])) { $transformedData['Terrorism'] = $data["terrorism"]; } if (isset($data["worldwideCover"])) { $transformedData['Worldwide Cover'] = $data["worldwideCover"]; } if (isset($data["family_transportation_benefits"])) { $transformedData['Family Transportation Benefits'] = $data["family_transportation_benefits"]; } if (isset($data["fractures_dislocation_burns"])) { $transformedData['Fractures / Dislocation / Burns'] = $data["fractures_dislocation_burns"]; } if (isset($data["coma"])) { $transformedData['Coma'] = $data["coma"]; } if (isset($data["carriageofDeadBody"])) { $transformedData['Carriage of Dead Body'] = $data["carriageofDeadBody"]; } if (isset($data["compassionateVisitExpenses"])) { $transformedData['Compassionate Visit Expenses'] = $data["compassionateVisitExpenses"]; } if (isset($data["travel_expenses_for_medical_treatment"])) { $transformedData['Travel expenses for Medical Treatment'] = $data["travel_expenses_for_medical_treatment"]; } if (isset($data["daily_cash_allowance"])) { $transformedData['Daily cash Allowance'] = $data["daily_cash_allowance"]; } if (isset($data["artifical_limb_and_prosthesis"])) { $transformedData['Artifical Limb and Prosthesis'] = $data["artifical_limb_and_prosthesis"]; } if (isset($data["animalSnakeInsectBite"])) { $transformedData['Animal/Snake/Insect Bite'] = $data["animalSnakeInsectBite"]; } if (isset($data["air_ambulance"])) { $transformedData['Air Ambulance'] = $data["air_ambulance"]; } return !empty($transformedData) ? $transformedData : []; } public function updateRemainderDate() { // Connect to the database and fetch the data $data = db_connect()->table('client_policy') ->where("reminder_date IS NOT NULL AND reminder_date <> ''") ->where('is_active', 1) ->get() ->getResultArray(); $days = []; foreach ($data as $value) { $reminderDate = strtotime($value['reminder_date']); if ($reminderDate) { $date_of_date = date('d', $reminderDate); $days[] = $date_of_date; $days[] = $value['reminder_date']; db_connect()->table('client_policy')->where('id', $value['id'])->set('reminder_date', $date_of_date)->update(); } } dd($days); } public function sendextraparam() { // $employeeController = new EmployeeController(); // $employeeController->truncateFileData('633'); // ---------- EMP SERVICE CONTROLLER -------------------------------------------------------------------------------- $employeeRestController = new EmployeeServiceController(); // $employeeRestController->excelFileDataValidation(['file_id' => 823]); // $employeeRestController->employeesOnboardPreprocess(['file_id' => 726]); // $employeeRestController->employeesOnboardProcess(['file_id' => 835]); // $employeeRestController->employeesEnrollmentInsert(['file_id' => 836]); // $r = Jobs::addJob(['job_name' => 'employeesEnrollmentInsert','payload' => ['file_id' => 721]]); // ----------EMP DATA SERVICE CONTROLLER-------------------------------------------------------------------------------- // $batch_data = [ // 'client_id' => 17, // 'client_policy_id' => 30, // 'client_branch_id' => 18, // 'event_type' => "inception", // ]; // $batch_data['insurer_or_tpa'] = 'insurer'; // $batch_data['insurer_or_tpa'] = 'tpa'; // $dashBoardController = new DashboardController(); // $client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id=159, $client_branch_id=126); // $dashBoardController->sendRemainderMail($client_policy_data); // $EmpDataServiceController = new EmpDataServiceController(); // $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard(12); // $ids = array_column($emp_data, 'id'); // $EmpDataServiceController->sendMailForDownloadingECard($ids); // $EmpDataServiceController = new EmpDataServiceController(); // $EmpDataServiceController->importDeletionValidation(['file_id' => 304]); //for live // $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data); // print_rr($result); die; // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->employeesOnboardPreprocess(['file_id' => '741']); // $PolicyTransactionController = new PolicyTransactionController(); // $res = $PolicyTransactionController->validateInsurerStatement(['file_id' => '36']); // $empServiceController = new EmployeeServiceController(); // $res = $empServiceController->excelFileDataValidation(['file_id' => '319']); // dd($res); // $EmpDataServiceController = new EmpDataServiceController(); // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 160]); // $EmpDataServiceController = new EmpDataServiceController(); // $EmpDataServiceController->importInceptionUpdateTPAandUHID(['file_id' => 162]); // $EmpDataServiceController->importInceptionFileValidation(['file_id' => 162]); // $EmpDataServiceController->importDeletionValidation(['file_id' => 171]); // $EmpDataServiceController->importDeletionUpdateEndorsementID(['file_id' => 171]); // $EmpDataServiceController->importCorrectionUpdateEndorsementID(['file_id' => 188]); // $array = [ // "employeeIds" => ["12800", "12798", "12797", "12799"], // "client_id" => "159", // "client_policy_id" => "336", // "client_branch_id" => "126", // "cd_ac_no" => "Apple_123", // "endorsement_no" => "ENDORSEMENT_ID", // "count" => 4, // "event_name" => "deletion", // "policy_name" => "GMC", // "user_id" => "1" // ]; // $EmpDataServiceController->cashDepositCalculationForDeletion($array); // $result = $this->employeePolicyModel->getInceptionEmployeeDataForExportExcel($batch_data); // dd(db_connect()->getLastQuery()); // ------------- LEADS CONTROLLER ---------------------------------------------------------- // $LeadsController = new LeadsController(); // $RFQModel = new RFQModel(); // $data = $RFQModel->where('is_active', 1)->where('lead_id', 40)->first(); // // dd($data); // $policy_type = 2; // $proposel_name = "Proposal 2"; // $insurer_name = "ICICI-P-ICICI002-V1"; // $jsonArray = json_decode($data['json'], true); // // dd($jsonArray); // $returndata = $LeadsController->convertQCRJsonToPolicyTerms($jsonArray, $policy_type, $proposel_name, $insurer_name); // dd($returndata); // -----------BDS REPORT CONTROLLER--------------------------------------------------------------------------------- // $BDSReportController = new BDSReportController(); // $data['data'] = $BDSReportController->getBAPInsurerData(); // return $this->loadLayout('irda_bap_insurer_report_list', $data); // $data['data'] = $BDSReportController->getBAPClientData(); // return $this->loadLayout('irda_bap_client_report_list', $data); // $data['data'] = $BDSReportController->getClientData(1); // return $this->loadLayout('irda_client_report_list', $data); // $BDSReportController->getBAPClientData(); //-------------------------------------------------------------------------------------------------------- // $email_id = 'venkateshraman786@gmail.com'; // $common = ['mail_type'=>'test_mail_cli']; // $bcc = "vitvelz@gmail.com"; // $data = db_connect() // ->table('jobs') // ->where('id', 2264) // ->get() // ->getResultArray(); // $data = json_decode($data[0]['payload'], true); // // dd($data); // // Send email and get response // $result = MailHelper::send_email($data[0]); // echo json_encode($result); // log_message('error',json_encode($result)); //-------------------------------------------------------------------------------------------------------- // $ticketModel = new TicketMasterModel(); // $reportData['data'] = $ticketModel->getTATReport(1); // print_rr($reportData); // $this->loadLayout('tat_report_band_wise_list', $reportData); // $data = $ticketModel->getTATReport(1); } // ------------------------------------------------------------------------------------------------------- public function createOtherTabContent() { $this->myLogger->logme('error', 'Client Others function called'); $data = $this->request->getPost(); $data['created_by'] = get_session_userid(); $client_id = $data['client_id']; unset($data['client_id']); $insert = $this->clientModel->where('id', $client_id)->set($data)->update(); if ($insert) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'Client others data updated', 'data' => $data], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data to update'], 200); } } // ------------------------------------------------------------------------------------------------------- public function enrollmentAddonSIAmountDropdown($client_policy_id) { if(!empty($client_policy_id)){ $client_policy_details = $this->clientPolicyModel->where('id', $client_policy_id)->where('policy_status', 1)->where('is_active', 1)->first(); if(!empty($client_policy_details) && $client_policy_details['policy_type_id'] == 3 && $client_policy_details['is_addon'] == 3){ $base_policy_id = $client_policy_details['base_policy'] ?? 0; if(!empty($base_policy_id)){ } } } } public function getCDAmount() { $cd_ac_pk = $this->request->getGet('cd_ac_pk'); $cd_amount = $this->clientDepositModel ->where('is_active', 1) ->where('cd_ac_pk', $cd_ac_pk) ->orderBy('id', 'desc') ->first(); if($cd_amount){ return $this->respond(['status' => true, 'code' => 200, 'data' => $cd_amount], 200); } else { return $this->respond(['status' => false, 'code' => 404, 'message' => 'no data found'], 200); } } // -----------Function for Claim Module-------------------------------------------------------------------------------------------- public function getTheEmpDataForClaim($param, $type = null) { // Construct the base query $data = $this->clientPolicyModel ->select(" clients.id AS client_id, clients.client_name, insurers.id AS insurer_id, insurers.name AS insurer_name, tpa.id AS tpa_id, tpa.name AS tpa_name, employees.id AS emp_id, employees.name AS emp_name, employees.emp_code, employees.mobile AS emp_mobile, employees.email_corporate AS emp_email, employees.relationship AS emp_relationship, employee_polices.uhid AS policy_no ") ->join('clients', 'client_policy.client_id = clients.id', 'left') ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('employees', 'clients.id = employees.client_id', 'left') ->join('employee_polices', 'employees.id = employee_polices.employee_id', 'left') ->where('client_policy.is_active', 1) ->where('insurers.is_active', 1) ->where('tpa.is_active', 1) ->where('employees.is_active', 1) ->where('employees.relationship', "Self") ->where('employee_polices.is_active', 1) ->where('client_policy.id', $param) ->findAll(); $dataForClientAndInsurer = $this->clientPolicyModel ->select(" clients.id AS client_id, clients.client_name, insurers.id AS insurer_id, insurers.name AS insurer_name, tpa.id AS tpa_id, tpa.name AS tpa_name, ") ->join('clients', 'client_policy.client_id = clients.id', 'left') ->join('insurers', 'client_policy.insurer_id = insurers.id', 'left') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->where('client_policy.id', $param) ->first(); $memberData = []; // Respond based on the query result if (!empty($data) || !empty($dataForClientAndInsurer)) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data found', 'data' => $data, 'param' => $param, 'type' => $type, 'dataForClientAndInsurer' => $dataForClientAndInsurer, 'memberData' => $memberData ], 200); } else { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No Employee found', 'param' => $param, 'type' => $type, 'dataForClientAndInsurer' => $dataForClientAndInsurer, 'memberData' => $memberData ], 404); } } public function getTheEmpDataForClaimSearchByMobile($param, $type = 'mobile', $client_policy_id = null, $client_id = null) { $field_name = 'employees.' . $type; // Construct the base query $query = $this->clientPolicyModel ->select(" clients.id AS client_id, clients.client_name, insurers.id AS insurer_id, insurers.name AS insurer_name, tpa.id AS tpa_id, tpa.name AS tpa_name, employees.id AS emp_id, employees.name AS emp_name, employees.emp_code, employees.mobile AS emp_mobile, employees.email_corporate AS emp_email, employees.relationship AS emp_relationship, employee_polices.uhid AS policy_no, employee_polices.tpa_id AS tpa_no, employee_polices.client_policy_id AS policy_id ") ->join('clients', 'client_policy.client_id = clients.id') ->join('insurers', 'client_policy.insurer_id = insurers.id') ->join('tpa', 'client_policy.tpa_id = tpa.id', 'left') ->join('employees', 'clients.id = employees.client_id') ->join('employee_polices', 'employees.id = employee_polices.employee_id') ->where('client_policy.is_active', 1) ->where('insurers.is_active', 1) ->where('tpa.is_active', 1) ->where('employees.is_active', 1) ->where('employees.relationship', "Self") ->where('employee_polices.is_active', 1) ->where($field_name, $param); if (!empty($client_id)) { $query->where('employees.client_id', $client_id); } if (!empty($client_policy_id)) { $query->where('employee_polices.client_policy_id', $client_policy_id); } $query->groupBy('employees.id') ->orderBy('employees.id', 'DESC'); $data = $query->get()->getRowArray(); // print_r(db_connect()->getLastQuery()); die; $memberData = []; $dataForClientAndInsurer = []; $acms = db_connect()->table('user_profiles') ->select('user_profiles.id, user_profiles.first_name') ->where('user_profiles.is_active', 1) ->where('user_profiles.role', 3) ->get() ->getResultArray(); if(!empty($data) && count($data) > 0){ $memberData = $this->employeeModel->getEmployeeByEmployeeCode($data['emp_code'], $data['policy_id'], $client_id); $acms = $this->clientRMModel ->select('user_profiles.id, user_profiles.first_name') ->join('clients', 'client_rm.client_id = clients.id', 'left') ->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left') ->where('clients.is_active', 1) ->where('client_rm.is_active', 1) ->where('user_profiles.is_active', 1) ->where('clients.id', $data['client_id']) ->findAll(); } // Respond based on the query result if (!empty($data)) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data found', 'data' => $data, 'param' => $param, 'client_policy_id' => $client_policy_id, 'type' => $type, 'dataForClientAndInsurer' => $dataForClientAndInsurer, 'memberData' => $memberData, 'acms' => $acms, ], 200); } else { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No Employee found', 'param' => $param, 'client_policy_id' => $client_policy_id, 'type' => $type, 'dataForClientAndInsurer' => $dataForClientAndInsurer, 'memberData' => $memberData, 'acms' => $acms ], 200); } } // ----------------------------------------------------------------------------------------------------- public function updateRenewalData() { $db = db_connect(); $renewalData = $db->table('old_renewal_data_copy') ->where('client_id IS NOT NULL') ->where('is_inserted != 1') ->get() ->getResultArray(); // dd($renewalData); $successData = []; foreach ($renewalData as $key => $value) { // Get branch_id properly $branch = $this->clientBranchModel->where('client_id', $value['client_id'] ?? 0)->first(); // kint::dump($branch); $value['branch_id'] = $branch['id'] ?? null; // Fix vehicle_id key (previously "vehicel_id") $value['vehicle_id'] = null; if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) { $value['vehicle_id'] = $this->prepareVehicleData($value); } // Process client policy, policy transaction, and co-share details $value['client_policy_id'] = $this->prepareClientPolicy($value); $value['pt_id'] = $this->preparePolicyData($value); $value['pt_co_id'] = $this->preparePtCoShareDetails($value); // Update is_inserted field in DB $db->table('old_renewal_data_copy') ->where('id', $value['id']) ->set(['is_inserted' => 1]) ->update(); $successData[] = ['id' => $value['id'], 'client' => $value['insured']]; } kint::dump($successData); } public function updateRenewalInsurerData() { $db = db_connect(); $renewalData = $db->table('old_renewal_data_copy') ->where('insurer_id IS NULL') ->get() ->getResultArray(); // dd($renewalData); $successData = []; foreach ($renewalData as $key => $value) { $insurer_data = $this->insurerModel->where('name', $value['insurer_name'])->where('is_active', 1)->first(); if (!empty($insurer_data)) { $insurer_branch_data = $this->insurerBranchModel->where('branch_name', $value['insurer_branch'])->first(); if (!empty($insurer_branch_data)) { $branch = $this->insurerBranchModel->where('insurer_id', $insurer_data['id'] ?? 0)->first(); $value['insurer_id'] = $insurer_data['id'] ?? null; $value['insurer_branch_id'] = $branch['id'] ?? null; } else { $value['insurer_id'] = $insurer_data['id'] ?? null; $value['insurer_branch_id'] = $this->prepareInsurerBranch($value); } } else { $value['insurer_id'] = $this->prepareinsurer($value); $value['insurer_branch_id'] = $this->prepareInsurerBranch($value); } // Update is_inserted field in DB $db->table('old_renewal_data_copy') ->where('id', $value['id']) ->set([ 'insurer_id' => $value['insurer_id'], 'insurer_branch_id' => $value['insurer_branch_id'], ]) ->update(); $successData[] = ['id' => $value['id'], 'insurer' => $value['insurer_name'], 'insurer_id' => $value['insurer_id'], 'insurer_branch_id' => $value['insurer_branch_id'],]; } kint::dump($successData); } public function updateRenewalDataNotExistingClient() { $limit = $this->request->getGet('limit') ?? 10; $group = $this->request->getGet('group') ?? 2; $db = db_connect(); $renewalData = $db->table('old_renewal_data_copy') ->where('client_id IS NULL') ->where('is_inserted = 0') ->where('client_type_id', $group) // ->limit($limit) ->get() ->getResultArray(); // dd($renewalData); $successData = []; foreach ($renewalData as $key => $value) { $client_data = $this->clientModel->where('client_name', $value['insured'])->where('is_active', 1)->first(); if (!empty($client_data)) { $branch = $this->clientBranchModel->where('client_id', $client_data['id'] ?? 0)->first(); $value['branch_id'] = $branch['id'] ?? null; $value['client_id'] = $client_data['id'] ?? null; } else { $value['client_id'] = $this->prepareClient($value); if ($value['client_type_id'] == 1) { $value['branch_id'] = $this->prepareClientBranch($value); } } // Fix vehicle_id key (previously "vehicel_id") if ($value['policy_type_id'] == 8 && !empty($value['policy_type_id'])) { $value['vehicle_id'] = $this->prepareVehicleData($value); } else { $value['vehicle_id'] = 0; } // Process client policy, policy transaction, and co-share details $value['client_policy_id'] = $this->prepareClientPolicy($value); $value['pt_id'] = $this->preparePolicyData($value); $value['pt_co_id'] = $this->preparePtCoShareDetails($value); // Update is_inserted field in DB $db->table('old_renewal_data_copy') ->where('id', $value['id']) ->set(['is_inserted' => 1]) ->update(); $successData[] = ['id' => $value['id'], 'client' => $value['insured'], 'vehicle_id' => $value['vehicle_id']]; } kint::dump($successData); } private function preparePolicyData($renewalData) { $data = [ 'issuer' => $renewalData['issuer_type_id'] ?? null, 'client_id' => $renewalData['client_id'] ?? null, 'client_branch_id' => $renewalData['branch_id'] ?? 0, 'vehicle_id' => $renewalData['vehicle_id'] ?? null, 'insurer_id' => $renewalData['insurer_id'] ?? null, 'insurer_branch_id' => $renewalData['insurer_branch_id'], 'tpa_id' => null, 'tpa_branch_id' => null, 'policy_type_id' => $renewalData['policy_type_id'] ?? null, 'client_policy_id' => $renewalData['client_policy_id'] ?? null, 'issue_type' => 1, 'source_client_policy_id' => null, 'policy_no' => $renewalData['policy_no'] ?? null, 'cd_ac_no' => null, 'policy_issue_date' => $renewalData['date_date_of_issue'], 'policy_start_date' => $renewalData['date_policy_start_date'], 'policy_end_date' => $renewalData['date_policy_end_date'], 'action_type' => 'inception', 'endorsement_no' => null, 'data_received_date' => null, 'closure_date' => null, 'emp_count' => null, 'dependent_count' => null, 'revenue_type' => $renewalData['revenue_type'] ?? null, 'co_share' => 0, 'pre_payable_by' => 1, 'bro_payable_by' => 1, 'tsi' => '500000', 'status' => 'completed', 'ct_status' => 0, 'is_active' => 1, 'co_broking_status' => null, 'installment' => 0, 'installment_data' => null, 'location' => null, 'links' => null, 'stage' => null, 'etat' => null, 'etat_band' => null, 'edate' => null, 'renewal_date' => null, 'rollover_date' => null, 'policy_holder_name' => $renewalData['insured'], 'same_as_proposer' => 1, // 1 - Yes, 0 - No 'ref' => $renewalData['ref'], 'spl' => null, 'fund_received' => null, 'listed_insurers' => null, 'ppteam' => null, 'endorse_eff_date' => null, 'month' => '2025-02-01', 'sales_generated_by' => null, 'serviced_by' => null, 'ct_type' => 1, 'ct_tran_id' => null, 'remarks' => null, 'cd_ac_pk' => $renewalData['cd_ac_pk'] ?? null, 'install_due_date' => null, 'policy_with_corr' => 0 ]; // kint::dump($data); // dd($data); $policyTransactionModel = new PolicyTransactionModel(); $id = $policyTransactionModel->insert($data); return $id; } private function prepareVehicleData($renewalData) { $VehicleModel = new VehicleModel(); if ($renewalData['client_type_id'] == 1) { $veh_no = explode(" ", $renewalData['insured'])[0] . "_veh_no"; } else { $veh_no = $renewalData['insured'] . "_veh_no"; } $vehicleData = $VehicleModel->where('owner', $renewalData['client_id']) ->where('is_active', 1) ->findAll(); if (!empty($vehicleData)) { $increment = count($vehicleData); $veh_no = $increment . "_" . $veh_no; } $vehicleData = [ 'vehicle_no' => $veh_no, 'type' => null, 'description' => null, 'owner' => $renewalData['client_id'], // client_id 'branch_id' => $renewalData['client_type_id'] == 1 ? $renewalData['branch_id'] : 0, // client_branch_id 'old_owner' => null, 'rc' => null, ]; // dd($vehicleData); $id = $VehicleModel->insert($vehicleData); return $id; } private function preparePtCoShareDetails($renewalData) { $pt_co_share_details = [ 'pt_id' => $renewalData['pt_id'], 'insurer_id' => $renewalData['insurer_id'], 'insurer_branch_id' => $renewalData['insurer_branch_id'], 'co_share_type' => 0, 'co_share_per' => 0.00, 'bp_amt' => 0.00, 'bp_gst_amt' => 0.00, 'bp_igst' => 0, 'bp_sgst' => 0, 'bp_cgst' => 0, 'tp_amt' => 0.00, 'tp_gst_amt' => 0.00, 'tp_igst' => 0.00, 'tp_sgst' => 0.00, 'tp_cgst' => 0.00, 'tep_amt' => 0.00, 'tep_gst_amt' => 0.00, 'tep_igst' => 0.00, 'tep_sgst' => 0.00, 'tep_cgst' => 0.00, 'agreed_amt' => 0.00, 'agreed_bp_per' => 0.00, 'agreed_tp_per' => 0.00, 'agreed_tep_per' => 0.00, 'standerd_bp_per' => 0.00, 'standerd_tp_per' => 0.00, 'standerd_tep_per' => 0.00, 'actual_bp_amt' => 0.00, 'actual_tp_amt' => 0.00, 'actual_tep_amt' => 0.00, 'actual_bp_per' => 0.00, 'actual_tp_per' => 0.00, 'actual_tep_per' => 0.00, 'actual_bp_brokerage_amt' => 0.00, 'actual_tp_brokerage_amt' => 0.00, 'actual_tep_brokerage_amt' => 0.00, 'reward' => 0.00, 'exp_amt' => 0.00, 'variance' => 0.00, 'remark' => null, 'cd_ac_no' => null, 'amount' => 0.00, 'stamp_duty' => 0.00, 'gst_type' => 0, 'cop_amt' => 0.00, 'statement_id' => 0, 'follower_policy_no' => $renewalData['policy_no'], 'non_comm_per_amt' => 0.00 ]; $PTCOShareDetailsModel = new PTCOShareDetailsModel(); $id = $PTCOShareDetailsModel->insert($pt_co_share_details); return $id; } private function prepareClientPolicy($renewalData) { $client_policy = [ 'client_id' => $renewalData['client_id'], 'client_branch_id' => $renewalData['branch_id'] ?? 0, 'policy_type_id' => $renewalData['policy_type_id'], 'insurer_id' => $renewalData['insurer_id'], 'insurer_branch_id' => $renewalData['insurer_branch_id'], 'tpa_id' => null, 'tpa_branch_id' => null, 'policy_start_date' => $renewalData['date_policy_start_date'], 'policy_end_date' => $renewalData['date_policy_end_date'], 'policy_no' => $renewalData['policy_no'], 'cd_ac_no' => null, 'policy_status' => 1, 'policy_terms' => null, 'is_addon' => 1, 'base_policy' => null, 'inception_type' => 1, 'open_for_enrollment' => 0, 'gst' => 18.00, 'enrolment_visibility' => 1, 'open_date' => null, 'close_date' => null, 'reminder_date' => null, 'disclaimer' => null, 'is_member_modify_allowed' => 0, 'cd_ac_pk' => $renewalData['cd_ac_pk'], 'is_lgbtq' => 0 ]; $ClientPolicyModel = new ClientPolicyModel(); $id = $ClientPolicyModel->insert($client_policy); return $id; } private function prepareClientBranch($renewalData) { $branch_code = "BRANCH001"; $short_name = explode(" ", $renewalData['insured'])[0]; $unit = $short_name . " - " . $branch_code; $clientBranchData = [ 'client_id' => $renewalData['client_id'], 'branch_name' => "Branch 1", 'branch_code' => $branch_code, 'city' => null, 'district' => null, 'state' => null, 'pincode' => null, 'address1' => null, 'address2' => null, 'gst' => null, 'sez' => 0, 'is_active' => 1, 'units' => $unit ]; $ClientBranchModel = new ClientBranchModel(); $id = $ClientBranchModel->insert($clientBranchData); return $id; } private function prepareClient($renewalData) { if ($renewalData['client_type_id'] == 1) { $short_name = explode(" ", $renewalData['insured'])[0]; } else { $short_name = $renewalData['insured']; } $clientData = [ 'client_type' => $renewalData['client_type_id'], 'entity_type_id' => null, 'client_name' => $renewalData['insured'], 'short_name' => $short_name, 'cost_center' => null, 'client_code' => null, // Auto-generated 'pan' => null, 'gst' => null, 'address1' => null, 'address2' => null, 'city' => null, 'state' => null, 'pincode' => null, 'is_download_btn' => 0, // Assuming a default value if not specified 'client_logo' => null, 'created_by' => null, 'created_at' => null, // Will be set automatically by MySQL 'updated_by' => null, 'updated_at' => null, // Will be set automatically by MySQL 'is_active' => 1, // Default value is 1 'common_mails' => null, 'hr_mails' => null, 'mail_domain' => null, 'reply_to' => null, 'dob' => null, 'aadhar' => null, 'reference' => null, 'phone' => null, 'email' => null, 'addon_subheading' => null ]; $ClientModel = new ClientModel(); $id = $ClientModel->insert($clientData); return $id; } private function prepareInsurerBranch($renewalData) { $insurerBranchData = [ 'insurer_id' => $renewalData['insurer_id'], 'branch_name' => $renewalData['insurer_branch'], 'branch_code' => $renewalData['insurer_branch'], 'address1' => null, 'address2' => null, 'city' => null, 'district' => null, 'state' => null, 'pincode' => null, ]; $InsurerBranchModel = new InsurerBranchModel(); $id = $InsurerBranchModel->insert($insurerBranchData); return $id; } private function prepareinsurer($renewalData) { $short_name1 = explode(" ", $renewalData['insurer_name'])[0]; $short_name2 = explode(" ", $renewalData['insurer_name'])[1]; $short_name = $short_name1 . ' ' . $short_name2; $insurerData = [ 'type' => "pvt", 'category' => "general", 'addition_add_day' => 0, 'deletion_add_day' => 0, 'name' => $renewalData['insurer_name'], 'short_name' => $short_name, 'insurer_logo' => null, 'is_multi_event' => 0, // Default is 0 ]; $InsurerModel = new InsurerModel(); $id = $InsurerModel->insert($insurerData); return $id; } }