myLogger = \Config\Services::mylogger(); // $this->insurerModel = new ClientModel(); $this->userModel = new UserModel(); // $this->insurerBranchModel = new ClientBranchModel(); $this->insurerKYCDocsModel = new ClientKYCDocsModel(); $this->clientPolicyModel = new ClientPolicyModel(); $this->insurerRMModel = 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->policyTypeModel = new PolicyTypeModel(); $this->CDMasterModel = new CDMasterModel(); $this->clientModel = new ClientModel(); $this->clientDepositModel = new ClientDepositModel(); $this->insurerTemplateModel = new InsurerExcelExportTemplateModel(); $this->vehicleModel = new VehicleModel(); $this->cli_colors = [ 'red' => "\033[31m", 'green' => "\033[32m", 'yellow' => "\033[33m", 'blue' => "\033[34m", 'reset' => "\033[0m" ]; } //start insurer public function insurerList() { $this->myLogger->logme('error','Insurer list function called'); $headerData['tab_name'] = 'Insurer Masters'; $headerData['page_name'] = 'Insurers'; $data['insurerList'] = $this->insurerModel->where('is_active',1)->findAll(); $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM(); // echo '
';
        // print_r($data['insurerList']); die;

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

        // $this->loadLayout('insurer_onboarding', $data);
    }

    public function insurerRemove($id = null)
    {   
        $this->myLogger->logme('error','Insurer Remove function called');
        // $id                 = $this->request->getPost('PrimaryKey');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->insurerModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function removeInsurerBranch($id = null)
    {   
        $this->myLogger->logme('error','Insurer Branch Remove function called');
        // $id                 = $this->request->getPost('PrimaryKey');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->insurerBranchModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function editInsurerOnboarding($id = null)
    {

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

        $types = array(
            (object) array('id' => 'pvt', 'name' => 'PVT'),
            (object) array('id' => 'psu', 'name' => 'PSU')
        );
    
        $editData['types'] = $types;
        $editData['RM']            = $this->userModel->findAll();
        $editData['tpa']           = $this->tpaBranchModel ->getTpaBranchesWithTpaNames();
        $editData['state']         = $this->stateModel->getAllStates();
        $editData['insurer']       = $this->insurerBranchModel ->getInsurerBranchesWithInsurerNames();


        $editData['insurer']           = $this->insurerModel->where(['id' => $id, 'is_active' => 1])->first();
        $editData['insuer_branch']     = $this->insurerBranchModel->where(['insurer_id' => $id, 'is_active' => 1])->findAll();
        $editData['insurer_templete_count']  = $this->insurerTemplateModel->where(['insurer_id' => $id, 'is_active' => 1])->countAllResults();
        $editData['insurer_templete_list']   = $this->insurerModel->getInsurerTemplateByInsurerID($id);


        $editData['policy_type']   = $this->policyTypeModel->whereIn('id', [1,2,6,7])->findAll();
        $editData['events'] = ['inception' => 'Inception', 'missed_inception' => 'Missed Inception', 'addition' => 'Addition', 'dependent_addition' => 'Dependent Addition', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement', 'all' => 'All'];
        $editData['action'] = ['import' => 'Import', 'export' => 'Export'];
        $editData['db_column_name'] = [

            'S.No.' => 'index',
            'Employee Name' => 'emp_name',
            'Employee ID' => 'emp_code',
            'Date of Birth' => 'emp_dob',
            'Gender' => 'emp_gender',
            'Change Event' => 'change_event',
            'Relationship' => 'emp_relationship',
            'Relationship Code' => 'emp_relationship_code',
            'Event Type' => 'event_type_data',
            'Date of Joining' => 'emp_doj',
            'Mobile' => 'emp_mobile',
            'Corporate Email' => 'emp_email_c',
            'Personal Email' => 'emp_email_p',
            'Grade' => 'emp_grade',
            'Designation' => 'emp_designation',
            'Basic Pay' => 'emp_basic_pay',
            'Age' => 'emp_age',
            'Employee Type' => 'emp_type',
            'Primary Key' => 'primaryKey',
            'TPA ID' => 'tpa_id',
            'UHID' => 'uhid',
            'Pre-existing Alignments' => 'pre_existing_alignments',
            'Basic Cover SI' => 'basic_cover_si',
            'Date of Coverage' => 'date_coverage',
            'Policy End Date' => 'policy_end_date',
            'Number of Days' => 'no_of_days',
            'Premium' => 'premium',
            'Pro Rata Premium' => 'pro_rata_premium',
            'GST' => 'gst',
            'Total' => 'total',
            'Policy ID' => 'emp_policy_id',
            'SEZ' => 'sez',
            'Endorsement ID' => 'endorsement_id',
            'Old Value' => 'old_value',
            'New Value' => 'new_value',
            'Field Name' => 'field_name',
            'Remarks' => 'remarks',
            'Actions' => 'actions',
            'Date of Exit' => 'dateofexit',
            'Reason for Exit' => 'reasonforexit', 
            'Status' => 'status',
            'Old Basic Cover SI' => 'old_basic_cover_si', 
            'Old SI Premium' => 'old_si_premium',
            'New Basic Cover SI' => 'new_basic_cover_si',
            'New SI Premium' => 'new_si_premium',
            'Date of Coverage' => 'date_of_coverage',
            'Age Band' => 'age_band',

        ];
        



        // echo "
";
        // print_r($editData); die;

        echo view('layout/header', $headerData);
        echo view('insurer_onboarding', $editData);
        echo view('layout/footer');

    }

    public function insurerOnboarding()
    {
        
        $this->myLogger->logme('error','Insurer Onboarding function called');
        $headerData['tab_name'] = 'Insurer Masters';
        $headerData['page_name'] = 'Insurers';
 
        $types = array(
            (object) array('id' => 'pvt', 'name' => 'PVT'),
            (object) array('id' => 'psu', 'name' => 'PSU')
        );
    
        $data['types'] = $types;
        // print_r($data['types']);die();
        $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();
                
        // echo "
";
        // print_r($data); die;

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

    }

    public function createInsurerGeneralInfo()
    {

        $this->myLogger->logme('error', 'Insurer general info function called');
        $rules = [
            'name' => [
                'label'  => 'Insurer Name',
                'rules'  => ['required', 'regex_match[/^[a-zA-Z0-9\s\-_]+$/]'],
                'errors' => [
                    'required'    => 'Insurer Name is required.',
                    'regex_match' => 'Insurer Name can only contain letters, numbers, spaces, hyphens, and underscores.',
                ]
            ],
            'short_name' => [
                'label'  => 'Insurer Short Name',
                'rules'  => ['required', 'regex_match[/^[a-zA-Z0-9\-_]+$/]'],
                'errors' => [
                    'required'    => 'Short Name is required.',
                    'regex_match' => 'Short Name can only contain letters, numbers, hyphens, and underscores.',
                ]
            ],
            'type' => [
                'label'  => 'Insurer Type',
                'rules'  => 'permit_empty|in_list[pvt,psu]',
                'errors' => [
                    'in_list' => 'Please select a valid Insurer Type (PVT or PSU).'
                ]
            ],
            'category' => [
                'label'  => 'Insurer Category',
                'rules'  => 'permit_empty|in_list[life,general]',
                'errors' => [
                    'in_list' => 'Please select a valid Category (Life or General).'
                ]
            ],
            'addition_add_day' => [
                'rules' => 'permit_empty' // Checkboxes return null if unchecked
            ],
            'deletion_add_day' => [
                'rules' => 'permit_empty'
            ],
            'is_multi_event' => [
                'rules' => 'permit_empty'
            ],
            'insurer_logo' => [
                'rules' => 'if_exist|is_image[insurer_logo]|max_size[insurer_logo,200]|ext_in[insurer_logo,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'The uploaded file must be an image',
                    'max_size' => 'File size should not exceed 200 KB',
                    'ext_in'   => 'Allowed file types: jpg, jpeg, png',
                ]
            ],
        ];
        // $rules = [
        //     'name' => [
        //         'rules'  => 'required',
        //         'errors' => [
        //             'required' => 'Name is required'
        //         ]
        //     ],
        //     'short_name' => [
        //         'rules'  => 'required|min_length[3]|max_length[8]',
        //         'errors' => [
        //             'required'   => 'Short name is required',
        //             'min_length' => 'Short name must be at least 3 characters',
        //             'max_length' => 'Short name cannot exceed 8 characters'
        //         ]
        //     ],
        //     'insurer_logo' => [
        //         'rules' => 'if_exist|is_image[insurer_logo]|max_size[insurer_logo,200]|ext_in[insurer_logo,jpg,jpeg,png]',
        //         'errors' => [
        //             'is_image' => 'The uploaded file must be an image',
        //             'max_size' => 'File size should not exceed 200 KB',
        //             'ext_in'   => 'Allowed file types: jpg, jpeg, png',
        //         ]
        //     ],
        // ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }

        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);

        $sanitized_post_data['addition_add_day'] = (!empty($sanitized_post_data['addition_add_day'])) ? 1 : 0;
        $sanitized_post_data['deletion_add_day'] = (!empty($sanitized_post_data['deletion_add_day'])) ? 1 : 0;
        $sanitized_post_data['is_multi_event'] = (!empty($sanitized_post_data['is_multi_event'])) ? 1 : 0;
        $sanitized_post_data['created_by'] = get_session_userid();
        $sanitized_post_data['insurer_logo'] = $file_name;
        
        $insert = $this->insurerModel->insert($sanitized_post_data);

        if($insert){
            $insurer_data = $this->insurerModel->where(['id' => $insert, 'is_active' => 1])->first();
            $insurer_templete_count = $this->insurerTemplateModel->where(['insurer_id' => $insert, 'is_active' => 1])->countAllResults();
            echo json_encode(array("status" => true , 'data' => $insurer_data, 'templete_count' => $insurer_templete_count));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function createInsurerBranch()
    {

        $this->myLogger->logme('error','Client branch CREATE function called');
        $rules = [

            // ======================
            // Branch Details
            // ======================
            'branch_name' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch name is required'
                ]
            ],

            'branch_code' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch code is required'
                ]
            ],

            'address1' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Address Line 1 is required'
                ]
            ],

            'state' => [
                        'label'  => 'State',
                        'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-\_\.\s]+$/]',
                        'errors' => [
                            'required'    => 'State is required.',
                            'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
                        ]
                    ],
                    'district' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'required' => 'District is required.',
                            'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'city' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'pincode' => [
                        'rules'  => 'required|numeric|exact_length[6]',
                        'errors' => [
                            'required' => 'Pincode is required.',
                            'numeric'      => 'Pincode must be digits only.',
                            'exact_length' => 'Pincode must be exactly 6 digits.'
                        ]
                    ],

            // ======================
            // Contact Details (Array)
            // ======================
            'name.*' => [
                'rules'  => 'required|trim|min_length[2]|regex_match[/^[a-zA-Z0-9\s_-]+$/]',
                'errors' => [
                    'required'   => 'Contact name is required',
                    'min_length' => 'Contact name must be at least 2 characters',
                    'regex_match' => 'Contact name is invalid Format'
                ]
            ],

            'designation.*' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Designation is required'
                ]
            ],

            'email.*' => [
                'rules'  => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
                'errors' => [
                    'required'    => 'Email address is required.',
                    'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
                ]
            ],

            'mobile.*' => [
                'rules'  => 'required|numeric|exact_length[10]',
                'errors' => [
                    'required'     => 'Mobile number is required',
                    'numeric'      => 'Mobile must contain only digits',
                    'exact_length' => 'Mobile number must be exactly 10 digits'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $sanitized_post_data['created_by'] = get_session_userid();
        $insert = $this->insurerBranchModel->insert($sanitized_post_data);
        
        if($insert){
            for ($i = 0; $i < count($sanitized_post_data['name']); $i++) {
                // Prepare data to insert
                $sanitized_post_data_for_level = [
                    'contact_type' => 'insurer',
                    'ref_id'       => $insert,
                    'created_by'   => get_session_userid(),
                    'name'         => $sanitized_post_data['name'][$i] ?? null,
                    'email'        => $sanitized_post_data['email'][$i] ?? null,
                    'mobile'       => $sanitized_post_data['mobile'][$i] ?? null,
                    'designation'  => $sanitized_post_data['designation'][$i] ?? null
                ];
                $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level);
            }
        }

        if($insert){
            $branchData = $this->insurerBranchModel->where('insurer_id', $sanitized_post_data['insurer_id'])->findAll();
            echo json_encode(array("status" => true , 'data' => $branchData));
        }else{
            echo json_encode(array("status" => false));
        }
    }
    
    public function insurerBranchList($id = null)
    {
        $this->myLogger->logme('error','Edit Insurer Onboarding function called');

        $editData['insuer_branch'] = $this->insurerBranchModel->where(['insurer_id' => $id, 'is_active' => 1])->findAll();

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function getInsurerBranchList()
    {
        $id = $this->request->getPost('insurer_id');

        $insurer_branch_list = $this->insurerBranchModel->where(['insurer_id' => $id, 'is_active' => 1])->findAll()??[];

        return $this->response->setJSON([ 'data' => $insurer_branch_list ])->setStatusCode(200);
    }

    public function editInsurerGeneralInfo()
    {

        $this->myLogger->logme('error','Edit Insurer general info function called');
        $postData = $this->request->getPost();
        $logoFile = $this->request->getFile('insurer_logo');
        
        $rules = [
            'name' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Name is required'
                ]
            ],
            'short_name' => [
                'rules'  => 'required|min_length[3]|max_length[8]',
                'errors' => [
                    'required'   => 'Short name is required',
                    'min_length' => 'Short name must be at least 3 characters',
                    'max_length' => 'Short name cannot exceed 8 characters'
                ]
            ],
            'insurer_logo' => [
                'rules' => 'permit_empty|is_image[insurer_logo]|max_size[insurer_logo,200]|ext_in[insurer_logo,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'The uploaded file must be an image',
                    'max_size' => 'File size should not exceed 200 KB',
                    'ext_in'   => 'Only JPG, JPEG, and PNG files are allowed.',
                ]
            ],
        ];

        if (!$this->validateData($postData, $rules)) {
                $errors = $this->validator->getErrors();
        
                $mainMessage = 'Input validation failed';
    
                if (isset($errors['insurer_logo']) && (strpos($errors['insurer_logo'], 'Security') !== false || strpos($errors['insurer_logo'], 'Forbidden') !== false)) {
                    $mainMessage = 'File upload rejected: Security policy violation.';
                }

                return $this->response->setStatusCode(400)->setJSON([
                    'status'  => false,
                    'message' => $mainMessage, // This will change based on the error
                    'code'    => 400,
                    'errors'  => $this->validator->getErrors()
                ]);
        }

        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name      = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
        $data           = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id                  = $sanitized_post_data['PrimaryKey'];
        
        $sanitized_post_data['addition_add_day'] = (!empty($sanitized_post_data['addition_add_day'])) ? 1 : 0;
        $sanitized_post_data['deletion_add_day'] = (!empty($sanitized_post_data['deletion_add_day'])) ? 1 : 0;
        $sanitized_post_data['is_multi_event']   = (!empty($sanitized_post_data['is_multi_event'])) ? 1 : 0;
        $sanitized_post_data['updated_by']       = get_session_userid();
        
        if(!empty($file_name)){
            $sanitized_post_data['insurer_logo'] = $file_name;
        }

        $update = $this->insurerModel->update($id,$sanitized_post_data);

        if($update){
            echo json_encode(array("status" => true , 'data' => $sanitized_post_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editInsurerGet($id = null)
    {
        $this->myLogger->logme('error','Edit TPA Onboarding function called');

        
        $editData['insurerbranch'] = $this->insurerBranchModel->where(['id' => $id, 'is_active' => 1])->first();
        $editData['levelcontact'] = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'insurer' , 'is_active' => 1])->findAll();
        // print_r($editData['tpa']);
        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function editInsurerBranch()
    {
        $this->myLogger->logme('error','Insurer branch EDIT function called');
        $rules = [

            // ======================
            // Branch Details
            // ======================
            'branch_name' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch name is required'
                ]
            ],

            'branch_code' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch code is required'
                ]
            ],

            'address1' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Address Line 1 is required'
                ]
            ],

            'state' => [
                        'label'  => 'State',
                        'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-\_\.\s]+$/]',
                        'errors' => [
                            'required'    => 'State is required.',
                            'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
                        ]
                    ],
                    'district' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'required' => 'District is required.',
                            'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'city' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'pincode' => [
                        'rules'  => 'required|numeric|exact_length[6]',
                        'errors' => [
                            'required' => 'Pincode is required.',
                            'numeric'      => 'Pincode must be digits only.',
                            'exact_length' => 'Pincode must be exactly 6 digits.'
                        ]
                    ],

            // ======================
            // Contact Details (Array)
            // ======================
            'name.*' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'Contact name is required',
                    'min_length' => 'Contact name must be at least 2 characters'
                ]
            ],

            'designation.*' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Designation is required'
                ]
            ],

            'email.*' => [
                'rules'  => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
                'errors' => [
                    'required'    => 'Email address is required.',
                    'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
                ]
            ],

            'mobile.*' => [
                'rules'  => 'required|numeric|exact_length[10]',
                'errors' => [
                    'required'     => 'Mobile number is required',
                    'numeric'      => 'Mobile must contain only digits',
                    'exact_length' => 'Mobile number must be exactly 10 digits'
                ]
            ],
        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data           = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id                  = $sanitized_post_data['PrimaryKey'] ?? null;
        $update = $this->insurerBranchModel->update($id, $sanitized_post_data);

        if($update){
            $contactsToDelete = $this->levelContactModel->where(['ref_id' => $id,'contact_type' => 'insurer', 'is_active' => 1])->get()->getResult();
            foreach ($contactsToDelete as $contact) {
                $this->levelContactModel->delete($contact->id);
            }
            for ($i = 0; $i < count($sanitized_post_data['name']); $i++) {
                // Prepare data to update
                $sanitized_post_data_for_level = [
                    'contact_type' => 'insurer',
                    'ref_id'       => $id,
                    'created_by'   => get_session_userid(),
                    'name'         => $sanitized_post_data['name'][$i] ?? null,
                    'email'        => $sanitized_post_data['email'][$i] ?? null,
                    'mobile'       => $sanitized_post_data['mobile'][$i] ?? null,
                    'designation'  => $sanitized_post_data['designation'][$i] ?? null                
                    ];
                $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level);
            }
        }

        if($update){
            $branchData = $this->insurerBranchModel->where('insurer_id', $sanitized_post_data['insurer_id'])->findAll();
            echo json_encode(array("status" => true , 'data' => $branchData, 'edit'));
        }else{
            echo json_encode(array("status" => false, 'edit'));
        }
    }

    public function getInsurerByExportTemplete()
    {
        $insurer_data = $this->insurerModel
            ->select('insurers.name as insurer_name, insurers.id, insurers.is_multi_event')
            ->join('insurer_excel_export_template', 'insurer_excel_export_template.insurer_id = insurers.id')
            ->where('insurer_excel_export_template.is_active', 1)
            ->where('insurers.is_active', 1)
            ->groupBy('insurers.id')
            ->findAll();

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

    public function copyInsurerTemplete($existing_insurer_id, $copy_insurer_id)
    {
        $insurer_templete_data = $this->insurerTemplateModel->where('insurer_id', $existing_insurer_id)->where('is_active', 1)->findAll();
        $existing_insurer_templete_data =  $this->insurerTemplateModel->where('insurer_id', $copy_insurer_id)->set('is_active', 0)->update();

        $data_to_insert = [];
        foreach ($insurer_templete_data as $value) {
            $data_to_insert[] = [
                "insurer_id" => $copy_insurer_id,
                "policy_type_id" => $value['policy_type_id'],
                "event_name" => $value['event_name'],
                "type_name" => $value['type_name'],
                "jsoncolumns" => $value['jsoncolumns'],
                "created_by" => get_session_user(),
                "is_active" => 1,
            ];
        }

        $insert_result = $this->insurerTemplateModel->insertBatch($data_to_insert);

        if($insert_result){
            return $this->respond(['status' => true, 'message' => 'Template added successfully',  $insurer_templete_data]);
        }else{
            return $this->respond(['status' => false, 'message' => 'Failed to add template',  $insurer_templete_data]);
        }
    }

    public function getSingleExcelTemplate($id = null)
    {
        $insurer_templete_data = $this->insurerTemplateModel
                ->where('id', $id)
                ->where('is_active', 1)
                ->first();

        if($insurer_templete_data){

            return $this->respond(['status' => true, 'code' => 200, 'data' => $insurer_templete_data, 'message' => 'data found'], 200);

        }else{

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

    }
    // Insurer Ends




    // TPA Start
    public function tpaList()
    {   
        $this->myLogger->logme('error','TPA list function called');
        $headerData['tab_name'] = 'TPA Masters';
        $headerData['page_name'] = 'TPA';
        $data['tpaList'] = $this->tpaModel->where('is_active',1)->findAll();
        // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
        // echo '
';
        // print_r($data['insurerList']); die;

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

        // $this->loadLayout('insurer_onboarding', $data);
    }
    
    public function tpaRemove($id = null)
    {   
        $this->myLogger->logme('error','TPA Remove function called');
        $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->tpaModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function removeTPABranch($id = null)
    {   
        $this->myLogger->logme('error','TPA Branch Remove function called');
        // $id                 = $this->request->getPost('PrimaryKey');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->tpaBranchModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function tpaOnboarding()
    {
        
        $this->myLogger->logme('error','TPA Onboarding function called');
        $headerData['tab_name'] = 'TPA Masters';
        $headerData['page_name'] = 'TPA';


        // print_r($data['types']);die();
        $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();
                
        // echo "
";
        // print_r($data); die;

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

    } 

    public function createTPAGeneralInfo()
    {

        $this->myLogger->logme('error','TPA general info function called');
        $rules = [

            // ======================
            // TPA Basic Details
            // ======================
            'name' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'TPA name is required',
                    'min_length' => 'TPA name must be at least 2 characters'
                ]
            ],

            'short_name' => [
                'rules'  => 'required|trim|min_length[3]',
                'errors' => [
                    'required'   => 'TPA short name is required',
                    'min_length' => 'Short name must be at least 3 characters',
                ]
            ],

            'network_hospitals' => [
                'rules'  => 'required|valid_url',
                'errors' => [
                    'required'  => 'Network hospitals URL is required',
                    'valid_url' => 'Please enter a valid URL'
                ]
            ],
            'tpa_logo' => [
                'rules' => 'if_exist|is_image[tpa_logo]|max_size[tpa_logo,200]|ext_in[tpa_logo,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'TPA logo must be an image',
                    'max_size' => 'TPA logo should not exceed 200 KB',
                    'ext_in'   => 'Allowed logo types: jpg, jpeg, png'
                ]
            ],

            'fc' => [
                'rules' => 'if_exist|is_image[fc]|max_size[fc,500]|ext_in[fc,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'Front card must be an image',
                    'max_size' => 'Front card image should not exceed 500 KB',
                    'ext_in'   => 'Allowed types: jpg, jpeg, png'
                ]
            ],

            'bc' => [
                'rules' => 'if_exist|is_image[bc]|max_size[bc,500]|ext_in[bc,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'Back card must be an image',
                    'max_size' => 'Back card image should not exceed 500 KB',
                    'ext_in'   => 'Allowed types: jpg, jpeg, png'
                ]
            ],
        ];


        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);


        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);

        $template_bg_path = ROOTPATH . 'public/uploads/template_bg';
        $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES);
        $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES);


        $eCardTemplate = $sanitized_post_data['ecard_content'];
        
        $sanitized_post_data['created_by'] = get_session_userid();
        $sanitized_post_data['tpa_logo'] = $file_name;
        $sanitized_post_data['front_card'] = $front_card_file_name;
        $sanitized_post_data['back_card'] = $back_card_file_name;
        $sanitized_post_data['network_hospitals'] = $sanitized_post_data['network_hospitals'];
        
        $insert = $this->tpaModel->insert($sanitized_post_data);

        $tpa_name = ((string) $sanitized_post_data['name']) ?? null;
        $short_name = ((string) $sanitized_post_data['short_name']) ?? null;

        $filename = strtolower(str_replace(' ', '_', $short_name)) . '.html';
        $file_directory = WRITEPATH . 'e_card_template/';
        $file_path = $file_directory . $filename;
        
        // Ensure that the directory exists, if not, create it
        if (!is_dir($file_directory)) {
            mkdir($file_directory, 0777, true);
        }
        
        // Set the appropriate content type
        header('Content-type:text/html; charset=utf-8');
        
        // Write the HTML content to the file
        $html_data = file_put_contents($file_path, $eCardTemplate);
        
        
        if ($html_data !== false) {
            $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file saved successfully: {data}, filepath is: {path}', ['data' => $filename, 'tpa' => $tpa_name, 'path' => $file_path]);
        } else {
            $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file unable to save: {data}', ['data' => $filename, 'tpa' => $tpa_name]);
        }
        

        if($insert){
            $tpa_data = $this->tpaModel->where(['id' => $insert, 'is_active' => 1])->first();
            echo json_encode(array("status" => true , 'data' => $tpa_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function createTPABranch()
    {

        $this->myLogger->logme('error','TPA branch CREATE function called');
        $rules = [

            // ======================
            // Branch Details
            // ======================
            'branch_name' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch name is required'
                ]
            ],

            'branch_code' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch code is required'
                ]
            ],

            'address1' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Address Line 1 is required'
                ]
            ],

            'state' => [
                        'label'  => 'State',
                        'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-\_\.\s]+$/]',
                        'errors' => [
                            'required'    => 'State is required.',
                            'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
                        ]
                    ],
                    'district' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'required' => 'District is required.',
                            'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'city' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'pincode' => [
                        'rules'  => 'required|numeric|exact_length[6]',
                        'errors' => [
                            'required' => 'Pincode is required.',
                            'numeric'      => 'Pincode must be digits only.',
                            'exact_length' => 'Pincode must be exactly 6 digits.'
                        ]
                    ],

            // ======================
            // Contact Details (Array)
            // ======================
            'name.*' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'Contact name is required',
                    'min_length' => 'Contact name must be at least 2 characters'
                ]
            ],

            'designation.*' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Designation is required'
                ]
            ],

            'email.*' => [
                'rules'  => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
                'errors' => [
                    'required'    => 'Email address is required.',
                    'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
                ]
            ],

            'mobile.*' => [
                'rules'  => 'required|numeric|exact_length[10]',
                'errors' => [
                    'required'     => 'Mobile number is required',
                    'numeric'      => 'Mobile must contain only digits',
                    'exact_length' => 'Mobile number must be exactly 10 digits'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $sanitized_post_data['created_by'] = get_session_userid();
        $insert = $this->tpaBranchModel->insert($sanitized_post_data);
        
        if($insert){
            for ($i = 0; $i < count($sanitized_post_data['name']); $i++) {
                // Prepare data to insert
                $sanitized_post_data_for_level = [
                    'contact_type' => 'tpa',
                    'ref_id'       => $insert,
                    'created_by'   => get_session_userid(),
                    'name'         => $sanitized_post_data['name'][$i] ?? null,
                    'email'        => $sanitized_post_data['email'][$i] ?? null,
                    'mobile'       => $sanitized_post_data['mobile'][$i] ?? null,
                    'designation'  => $sanitized_post_data['designation'][$i] ?? null
                ];
                $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level);
            }
        }

        if($insert){
            $branchData = $this->tpaBranchModel->where('tpa_id', $sanitized_post_data['tpa_id'])->findAll();
            echo json_encode(array("status" => true , 'data' => $branchData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editTPAOnboarding($id = null)
    {

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

        $tpa_data = $this->tpaModel->where(['id' => $id, 'is_active' => 1])->first();

        $editData['tpa']           =  $tpa_data;
        $editData['tpa_branch']    = $this->tpaBranchModel->where(['tpa_id' => $id, 'is_active' => 1])->findAll();
        $editData['state']         = $this->stateModel->getAllStates();

        $filename = strtolower(str_replace(' ', '_', $tpa_data['short_name'])) . '.html';
        $template_data_path =  WRITEPATH . 'e_card_template/';
        $final_path =  $template_data_path . $filename;


        if (file_exists($final_path)) {

            $tmplt_data = file_get_contents($final_path); 
            $editData['template_data'] = $tmplt_data;
        } 
       
        // echo "
";
        // print_r($editData); die;

        echo view('layout/header', $headerData);
        echo view('tpa_onboarding', $editData);
        echo view('layout/footer');

    }

    public function editTPAGeneralInfo()
    {
        $this->myLogger->logme('error','edit TPA general info function called');
        $rules = [

            // ======================
            // TPA Basic Details
            // ======================
            'name' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'TPA name is required',
                    'min_length' => 'TPA name must be at least 2 characters'
                ]
            ],

            'short_name' => [
                'rules'  => 'required|trim|min_length[3]',
                'errors' => [
                    'required'   => 'TPA short name is required',
                    'min_length' => 'Short name must be at least 3 characters',
                ]
            ],

            'network_hospitals' => [
                'rules'  => 'required|valid_url',
                'errors' => [
                    'required'  => 'Network hospitals URL is required',
                    'valid_url' => 'Please enter a valid URL'
                ]
            ],
            'tpa_logo' => [
                'rules' => 'if_exist|is_image[tpa_logo]|max_size[tpa_logo,200]|ext_in[tpa_logo,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'TPA logo must be an image',
                    'max_size' => 'TPA logo should not exceed 200 KB',
                    'ext_in'   => 'Allowed logo types: jpg, jpeg, png'
                ]
            ],

            'fc' => [
                'rules' => 'if_exist|is_image[fc]|max_size[fc,500]|ext_in[fc,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'Front card must be an image',
                    'max_size' => 'Front card image should not exceed 500 KB',
                    'ext_in'   => 'Allowed types: jpg, jpeg, png'
                ]
            ],

            'bc' => [
                'rules' => 'if_exist|is_image[bc]|max_size[bc,500]|ext_in[bc,jpg,jpeg,png]',
                'errors' => [
                    'is_image' => 'Back card must be an image',
                    'max_size' => 'Back card image should not exceed 500 KB',
                    'ext_in'   => 'Allowed types: jpg, jpeg, png'
                ]
            ],
        ];


        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);


        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);

        $template_bg_path = ROOTPATH . 'public/uploads/template_bg';
        $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES);
        $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES);

        $id                 = $sanitized_post_data['PrimaryKey'] ?? null;
        
        $sanitized_post_data['updated_by'] = get_session_userid();

        if(!empty($file_name)){
            $sanitized_post_data['tpa_logo'] = $file_name;
        }

        if(!empty($front_card_file_name)){
            $sanitized_post_data['front_card'] = $front_card_file_name;
        }

        if(!empty($back_card_file_name)){
            $sanitized_post_data['back_card'] = $back_card_file_name;
        }

        $sanitized_post_data['network_hospitals'] = $sanitized_post_data['network_hospitals'] ?? null;
        $update             = $this->tpaModel->update($id,$sanitized_post_data);


        $tpa_name = ((string) $sanitized_post_data['name']) ?? null;
        $short_name = ((string) $sanitized_post_data['short_name']) ?? null;
        $eCardTemplate = $sanitized_post_data['ecard_content'] ?? null;

        $filename = strtolower(str_replace(' ', '_', $short_name)) . '.html';
        $file_directory = WRITEPATH . 'e_card_template/';
        $file_path = $file_directory . $filename;
        
        // Ensure that the directory exists, if not, create it
        if (!is_dir($file_directory)) {
            mkdir($file_directory, 0777, true);
        }
        
        // Set the appropriate content type
        header('Content-type:text/html; charset=utf-8');
        
        // Write the HTML content to the file
        $html_data = file_put_contents($file_path, $eCardTemplate);
        
        
        if ($html_data !== false) {
            $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file saved successfully: {data}, filepath is: {path}', ['data' => $filename, 'tpa' => $tpa_name, 'path' => $file_path]);
        } else {
            $this->myLogger->logme('error', 'TPA: {tpa}, e-Card HTML template file unable to save: {data}', ['data' => $filename, 'tpa' => $tpa_name]);
        }
        


        if($update){
            echo json_encode(array("status" => true , 'data' => $sanitized_post_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editTPAGet($id = null)
    {
        $this->myLogger->logme('error','Edit TPA Onboarding function called');

        
        $editData['tpabranch'] = $this->tpaBranchModel->where(['id' => $id, 'is_active' => 1])->first();
        $editData['levelcontact'] = $this->levelContactModel->where(['ref_id' => $id, 'contact_type' => 'tpa' , 'is_active' => 1])->findAll();
        // print_r($editData['tpa']);
        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function editTPABranch()
    {
        $this->myLogger->logme('error','TPA branch CREATE function called');
        $rules = [

            // ======================
            // Branch Details
            // ======================
            'branch_name' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch name is required'
                ]
            ],

            'branch_code' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Branch code is required'
                ]
            ],

            'address1' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Address Line 1 is required'
                ]
            ],

            'state' => [
                        'label'  => 'State',
                        'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-\_\.\s]+$/]',
                        'errors' => [
                            'required'    => 'State is required.',
                            'regex_match' => 'State name can only contain letters, spaces, and hyphens.'
                        ]
                    ],
                    'district' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'required' => 'District is required.',
                            'regex_match' => 'District can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'city' => [
                        'rules'  => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]',
                        'errors' => [
                            'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.'
                        ]
                    ],
                    'pincode' => [
                        'rules'  => 'required|numeric|exact_length[6]',
                        'errors' => [
                            'required' => 'Pincode is required.',
                            'numeric'      => 'Pincode must be digits only.',
                            'exact_length' => 'Pincode must be exactly 6 digits.'
                        ]
                    ],
            // ======================
            // Contact Details (Array)
            // ======================
            'name.*' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'Contact name is required',
                    'min_length' => 'Contact name must be at least 2 characters'
                ]
            ],

            'designation.*' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Designation is required'
                ]
            ],

            'email.*' => [
                'rules'  => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]',
                'errors' => [
                    'required'    => 'Email address is required.',
                    'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).'
                ]
            ],

            'mobile.*' => [
                'rules'  => 'required|numeric|exact_length[10]',
                'errors' => [
                    'required'     => 'Mobile number is required',
                    'numeric'      => 'Mobile must contain only digits',
                    'exact_length' => 'Mobile number must be exactly 10 digits'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id     = $sanitized_post_data['PrimaryKey'] ?? null;
        $update = $this->tpaBranchModel->update($id, $sanitized_post_data);

        // print_r($this->request->getPost('name[]'));
        // print_r($this->request->getPost('email[]'));
        // print_r($this->request->getPost('mobile[]'));
        // print_r($this->request->getPost('designation[]'));

        if($update){
            $contactsToDelete = $this->levelContactModel->where(['ref_id' => $id,'contact_type' => 'tpa', 'is_active' => 1])->get()->getResult();
            foreach ($contactsToDelete as $contact) {
                $this->levelContactModel->delete($contact->id);
            }
            for ($i = 0; $i < count($sanitized_post_data['name']); $i++) {
                // Prepare data to update
                $sanitized_post_data_for_level = [
                    'contact_type' => 'tpa',
                    'ref_id'       => $id,
                    'created_by'   => get_session_userid(),
                    'name'         => $sanitized_post_data['name'][$i] ?? null,
                    'email'        => $sanitized_post_data['email'][$i] ?? null,
                    'mobile'       => $sanitized_post_data['mobile'][$i] ?? null,
                    'designation'  => $sanitized_post_data['designation'][$i] ?? null
                ];
                $contacts = $this->levelContactModel->insert($sanitized_post_data_for_level);
            }
        }

        if($update){
            $branchData = $this->tpaBranchModel->where('tpa_id', $this->request->getPost('tpa_id'))->findAll();
            echo json_encode(array("status" => true , 'data' => $branchData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

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

        $editData['tpa_branch'] = $this->tpaBranchModel->where(['tpa_id' => $id, 'is_active' => 1])->findAll();

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }
    //Ends TPA Models
    



    
    //Start KYC 
    public function kycList()
    {   
        $this->myLogger->logme('error','KYC list function called');
        $headerData['tab_name'] = 'KYC Masters';
        $headerData['page_name'] = 'KYC';
        $data['kycList'] = $this->kycEntityTypeModel->where('is_active',1)->findAll();
        // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
        // echo '
';
        // print_r($data['insurerList']); die;

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

        // $this->loadLayout('insurer_onboarding', $data);
    }

    public function kycRemove($id = null)
    {   
        $this->myLogger->logme('error','KYC Remove function called');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->kycEntityTypeModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function removeKYCDocs($id = null)
    {   
        $this->myLogger->logme('error','KYC Docs Remove function called');
        // $id                 = $this->request->getPost('PrimaryKey');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->kycDocsModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function kycOnboarding()
    {
        
        $this->myLogger->logme('error','KYC Onboarding function called');
        $headerData['tab_name'] = 'KYC Masters';
        $headerData['page_name'] = 'KYC';


        // print_r($data['types']);die();
        $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();
                
        // echo "
";
        // print_r($data); die;

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

    }

    public function createKYCInfo()
    {

        $this->myLogger->logme('error','KYC Entity Type general info function called');
        $rules = [
            'name' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'KYC Entity Type Name is required'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $sanitized_post_data['created_by'] = get_session_userid();
        
        $insert = $this->kycEntityTypeModel->insert($sanitized_post_data);
        if($insert){
            $kyc_data = $this->kycEntityTypeModel->where(['id' => $insert, 'is_active' => 1])->first();
            echo json_encode(array("status" => true , 'data' => $kyc_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function createKycDocs()
    {

        $this->myLogger->logme('error','Kyc Docs CREATE function called');
        $rules = [
            'file_name' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'KYC Docs File Name is required'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        
        // print_r($data);die;

        if($sanitized_post_data['kyc_type_id'] == ''){
            // PrimaryKey
            $sanitized_post_data['kyc_type_id'] =$data['PrimaryKey'];
        }
        // print_r($data);die;

        $sanitized_post_data['created_by'] = get_session_userid();
        $insert = $this->kycDocsModel->insert($sanitized_post_data);

        if($insert){
            $kycDocsData = $this->kycDocsModel->where('kyc_type_id', $sanitized_post_data['kyc_type_id'])->where('is_active',1)->findAll();
            echo json_encode(array("status" => true , 'data' => $kycDocsData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editKYCOnboarding($id = null)
    {

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

        $editData['kyc']           = $this->kycEntityTypeModel->where(['id' => $id, 'is_active' => 1])->first();
        $editData['kyc_docs']    = $this->kycDocsModel->where(['kyc_type_id' => $id, 'is_active' => 1])->findAll();


        // echo "
";
        // print_r($editData); die;

        echo view('layout/header', $headerData);
        echo view('kyc_onboarding', $editData);
        echo view('layout/footer');

    }

    public function kycDocsList($id = null)
    {

        $this->myLogger->logme('error','Edit KYC Docs Onboarding function called');


        $editData['kyc_docs'] = $this->kycDocsModel->where(['kyc_type_id' => $id, 'is_active' => 1])->findAll();

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function editKYCInfo()
    {
        $this->myLogger->logme('error','edit KYC general info function called');
        $rules = [
            'file_name' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'KYC Docs File Name is required'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id                 = $sanitized_post_data['PrimaryKey'] ?? null;
        $sanitized_post_data['updated_by'] = get_session_userid();
        $update             = $this->kycEntityTypeModel->update($id,$sanitized_post_data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $sanitized_post_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editKYCGet($id = null)
    {
        $this->myLogger->logme('error','Edit KYC Onboarding function called');

        $editData['policies'] = $this->kycDocsModel->where(['id' => $id, 'is_active' => 1])->first();

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function editKYCDocs()
    {
        $this->myLogger->logme('error','edit KYC Docs function called');
        $id                 = $this->request->getPost('PrimaryKey');
        $data['file_name']  = $this->request->getPost('file_name');
        $data['updated_by'] = get_session_userid();
        $update             = $this->kycDocsModel->update($id,$data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $data));
        }else{
            echo json_encode(array("status" => false));
        }
    }
    //Ends KYC 





    //Start Policy  
    public function policyTypeList()
    {   
        $this->myLogger->logme('error','Policy Type list function called');
        $headerData['tab_name'] = 'Policy Type Masters';
        $headerData['page_name'] = 'Policy Type';
        $data['policyList'] = $this->policyTypeModel->where('is_active',1)->findAll();
        // $data['insurer_rm'] = $this->insurerRMModel->getAllClientRM();
        // echo '
';
        // print_r($data['insurerList']); die;

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

        // $this->loadLayout('insurer_onboarding', $data);
    }

    public function policyTypeRemove($id = null)
    {   
        $this->myLogger->logme('error','Policy Type Remove function called');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->policyTypeModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }
    
    public function removePolicyPolicies($id = null)
    {   
        $this->myLogger->logme('error','Policies Remove function called');
        // $id                 = $this->request->getPost('PrimaryKey');
        // $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $update             = $this->policesModel->update($id,$data);
        if($update){
            return $this->respond(['status' => true,'code' => 200], 200);
        }else{
            return $this->respond(['status' => false,'code' => 404], 200);
        }
    }

    public function policyTypeOnboarding()
    {
        
        $this->myLogger->logme('error','Policy Type Onboarding function called');
        $headerData['tab_name'] = 'Policy Type Masters';
        $headerData['page_name'] = 'Policy Type';


        // print_r($data['types']);die();
        $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['policy_type']   = $this->policyTypeModel->findAll();
        $data['insurer']       = $this->insurerModel ->findAll();
        // echo "
";

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

    }

    public function createPolicies()
    {
        $this->myLogger->logme('error','Policies CREATE function called');
        $data   = $this->request->getPost();
        // print_r($data);
        // die();
        $data['created_by'] = get_session_userid();
        $insert = $this->policesModel->insert($data);
        if($insert){
            $policiesData = $this->policesModel->select('policies.*, insurers.name as insurer_name')
                ->join('insurers', 'insurers.id = policies.insurer_id')
                ->where('policies.policy_type_id', $this->request->getPost('policy_type_id'))
                ->where('policies.is_active', 1)
                ->findAll();
            // $policiesData = $this->policesModel->where('policy_type_id', $this->request->getPost('policy_type_id'))->findAll();
            echo json_encode(array("status" => true , 'data' => $policiesData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function createPolicyType()
    {
        $this->myLogger->logme('error','Policy Type CREATE function called');
        $rules = [
            'policy_type' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'Policy type name is required',
                    'min_length' => 'Policy type name must be at least 2 characters'
                ]
            ],

            'bap' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'BAP is required'
                ]
            ],

            'allocg' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Category is required'
                ]
            ],

            'alloci' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'BAP category is required'
                ]
            ],

    
                'ebp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group base premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'etp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group third-party premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'etep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group terrorism premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'iep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual base premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'itp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual third-party premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'itep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual terrorism premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],
        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $sanitized_post_data['created_by'] = get_session_userid();
        $insert = $this->policyTypeModel->insert($sanitized_post_data);
        if($insert){
            $policyTypeData = $this->policyTypeModel->where('id', $insert)->first();
            echo json_encode(array("status" => true , 'data' => $policyTypeData));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function editPolicyTypeOnboarding($id = null)
    {

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

        $editData['policytype']   = $this->policyTypeModel->where(['id' => $id, 'is_active' => 1])->first();
        $editData['policies']     = $this->policesModel->select('policies.*, insurers.name as insurer_name')
                                                        ->join('insurers', 'insurers.id = policies.insurer_id')
                                                        ->where('policies.policy_type_id', $id)
                                                        ->where('policies.is_active', 1)
                                                        ->findAll();
        // $editData['policies']     = $this->policesModel->where(['policy_type_id' => $id, 'is_active' => 1])->findAll();
        $editData['insurer']      = $this->insurerModel-> findAll();
        echo view('layout/header', $headerData);
        echo view('policy_type_onboarding', $editData);
        echo view('layout/footer');

    }

    public function editPolicyType()
    {
        $this->myLogger->logme('error','edit Policy general info function called');
        $rules = [
            'policy_type' => [
                'rules'  => 'required|trim|min_length[2]',
                'errors' => [
                    'required'   => 'Policy type name is required',
                    'min_length' => 'Policy type name must be at least 2 characters'
                ]
            ],

            'bap' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'BAP is required'
                ]
            ],

            'allocg' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Category is required'
                ]
            ],

            'alloci' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'BAP category is required'
                ]
            ],

    
                'ebp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group base premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'etp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group third-party premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'etep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Group terrorism premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'iep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual base premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'itp' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual third-party premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],

                'itep' => [
                    'rules'  => 'permit_empty|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'numeric' => 'Individual terrorism premium must be numeric',
                        'greater_than_equal_to' => 'Value cannot be negative'
                    ]
                ],
        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        
        $id                 = $sanitized_post_data['PrimaryKey'] ?? null;
        $sanitized_post_data['updated_by'] = get_session_userid();
        $update             = $this->policyTypeModel->update($id,$sanitized_post_data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $sanitized_post_data));
        }else{
            echo json_encode(array("status" => false));
        }
    }

    public function policesList($id = null)
    {
        $this->myLogger->logme('error','Edit Policies Onboarding function called');

        // $editData['policies'] = $this->policesModel->where(['policy_type_id' => $id, 'is_active' => 1])->findAll();

        $policies = $this->policesModel->where(['policy_type_id' => $id, 'is_active' => 1])->findAll();

        // print_r($id);die;
            foreach ($policies as $policy) {
                // Retrieve the insurer information
                $insurer = $this->insurerModel->find((int)$policy['insurer_id']);

                // print_r($insurer);die;
                // Add the insurer information to the editData array
                if ($insurer) {
                    $editData['policies'][$policy['id']] = [
                        'policy' => $policy,
                        'insurer' => $insurer
                    ];
                }
            }

        
        // Return JSON response
        // header('Content-Type: application/json');
        // echo json_encode($editData);
        exit();
    }

    public function editPoliciesGet($id = null)
    {
        $this->myLogger->logme('error','Edit Policies Onboarding function called');
        $editData['policies'] = $this->policesModel->where(['id' => $id, 'is_active' => 1])->first();
        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($editData);
        exit();
    }

    public function editPolicies()
    {
        $this->myLogger->logme('error','edit Policy general info function called');
        $request_post_data   = $this->request->getPost();
        $data = sanitizeInputArrayAdvanced($request_post_data);

        $id                 = $data['PrimaryKey'] ?? null;
        $data['updated_by'] = get_session_userid();
        $update             = $this->policesModel->update($id,$data);
        if($update){
            $policyData = $this->policesModel->where(['id' => $id, 'is_active' => 1])->findAll();
            echo json_encode(array("status" => true , 'data' => $policyData));
        }else{
            echo json_encode(array("status" => false));
        }
    }
    //end policies




    //start CD Master list
    public function CDMasterList()
    {   
        $data['tab_name'] = 'CD Masters';
        $data['page_name'] = 'CD Master';
        $data['CD_Master_Data'] = $this->CDMasterModel->getCDMasterList();
        $data['insurers'] = $this->insurerModel->where('is_active', 1)->findAll();
        $data['insurer_branch'] = $this->insurerBranchModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $this->loadLayout('cd_master_list', $data);
    }

    // public function createCDMasterData()
    // {

    //     $data = $this->request->getPost();
    //     $id =  $data['PrimaryKey'];
    //     $date = (string) $this->request->getPost('opening_date');
    //     $data['opening_date'] = date('Y-m-d', strtotime($date));
    //     // print_rr($data);die();

    //     $loggedInUserID = get_session_userid();

    //     if (empty($id)) {

    //         if ($data) {

    //             $insert = $this->CDMasterModel->insert($data);

    //             if ($insert) {

    //                 // Prepare the array with data
    //                 $cd_tranction_data = [
    //                     'amount' => $data['opening_bal'],
    //                     'sub_type_id' => 7,
    //                     'client_id' => $data['client_id'],
    //                     'client_policy_id' => null,
    //                     'cd_ac_no' => $data['cd_ac_no'],
    //                     'endorsement_no' => null,
    //                     'insurer_id' => $data['insurer_id'],
    //                     'description' => 'opening Amount',
    //                     'transaction_type' => 'Credit',
    //                     'event_name' => null,
    //                     'updated_by' => 1,
    //                 ];

    //                 $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID();
    //                 $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);

    //                 session()->setFlashdata('success', "Cash Deposite Master Added Successfully");
    //                 return redirect()->to(base_url('/master/cash_deposite/list'));
    //             } else {

    //                 session()->setFlashdata('error', "Cash Deposite Master Added Failed");
    //                 return redirect()->to(base_url('/master/cash_deposite/list'));
    //             }
    //         } else {

    //             session()->setFlashdata('error', "Cash Deposite Master Added Failed. Data Not Found");
    //             return redirect()->to(base_url('/master/cash_deposite/list'));
    //         }

    //     } else {

    //         if ($data) {

    //             $insert = $this->CDMasterModel->where('id', $id)->set($data)->update();

    //             $data = $this->CDMasterModel->where('id', $id)->first();

    //             $cd_transaction_updated_data = [
    //                 'balance' => $data['opening_bal'],
    //                 'amount' => $data['opening_bal']
    //             ];

    //             $cd_tranction = $this->clientDepositModel
    //                 ->where('client_id', $data['client_id'])
    //                 ->where('insurer_id', $data['insurer_id'])
    //                 ->where('cd_ac_no', $data['cd_ac_no'])
    //                 ->where('sub_type', 7)
    //                 ->set($cd_transaction_updated_data)->update();

    //             if ($insert) {

    //                 session()->setFlashdata('success', "Cash Deposite Master Updated Successfully");
    //                 return redirect()->to(base_url('/master/cash_deposite/list'));
    //             } else {

    //                 session()->setFlashdata('error', "Cash Deposite Master Update Failed");
    //                 return redirect()->to(base_url('/master/cash_deposite/list'));
    //             }
    //         } else {

    //             session()->setFlashdata('error', "Cash Deposite Master Update Failed. Data Not Found");
    //             return redirect()->to(base_url('/master/cash_deposite/list'));
    //         }
    //     }
    // }

    public function createCDMasterData()
    {   
        $this->myLogger->logme("error", 'Create CD Master Data API called.');
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id = $sanitized_post_data['PrimaryKey'] ?? null;
        if($id === null){
            $rules = [

                // ======================
                // Client / Insurer Mapping
                // ======================
                'client_id' => [
                    'rules'  => 'required|is_natural_no_zero',
                    'errors' => [
                        'required' => 'Client is required'
                    ]
                ],

                'insurer_id' => [
                    'rules'  => 'required|is_natural_no_zero',
                    'errors' => [
                        'required' => 'Insurer is required'
                    ]
                ],

                'insurer_branch_id' => [
                    'rules'  => 'required|is_natural_no_zero',
                    'errors' => [
                        'required' => 'Insurer branch is required'
                    ]
                ],

                // ======================
                // CD Account Details
                // ======================
                'opening_date' => [
                    'rules'  => 'required|valid_date[d-m-Y]',
                    'errors' => [
                        'required'   => 'Opening date is required',
                        'valid_date' => 'Opening date must be in DD-MM-YYYY format'
                    ]
                ],

                'cd_ac_no' => [
                    'rules'  => 'required|trim',
                    'errors' => [
                        'required' => 'CD account number is required'
                    ]
                ],

                'opening_bal' => [
                    'rules'  => 'required|numeric|greater_than_equal_to[0]',
                    'errors' => [
                        'required' => 'Opening amount is required',
                        'numeric'  => 'Opening amount must be numeric',
                        'greater_than_equal_to' => 'Opening amount cannot be negative'
                    ]
                ],
            ];
            if (!$this->validate($rules)) {
                return $this->response->setStatusCode(400)->setJSON([
                    'status' => false,
                    'message' => 'Input validation failed',
                    'code' => 400,
                    'errors' => $this->validator->getErrors()
                ]);
            }
        }
        $this->myLogger->logme("error", 'Received POST data: ' . json_encode($data));

        $date = (string) ($sanitized_post_data['opening_date'] ?? '');
        $sanitized_post_data['opening_date'] = date('Y-m-d', strtotime($date));
        $this->myLogger->logme("error", 'Formatted opening_date: ' . $data['opening_date']);

        $loggedInUserID = get_session_userid();
        $this->myLogger->logme("error", 'Logged in user ID: ' . $loggedInUserID);

        // === INSERT ===
        if (empty($id)) {

            $cd_acc_count = $this->CDMasterModel->where('is_active', 1)
                ->where('client_id', $sanitized_post_data['client_id'])
                ->where('insurer_id', $sanitized_post_data['insurer_id'])
                ->where('insurer_branch_id', $sanitized_post_data['insurer_branch_id'])
                ->countAllResults();
        
            if($cd_acc_count > 0){
                return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
            }

            $this->myLogger->logme("error", 'Performing INSERT operation.');
            $insert = $this->CDMasterModel->insert($sanitized_post_data);
            $this->myLogger->logme("error", 'Insert result: ' . json_encode($insert));

            if ($insert) {

                $cd_tranction_data = [
                    'amount' => $sanitized_post_data['opening_bal'] ?? null,
                    'sub_type_id' => 7,
                    'client_id' => $sanitized_post_data['client_id'] ?? null,
                    'client_policy_id' => null,
                    'cd_ac_no' => $sanitized_post_data['cd_ac_no'] ?? null,
                    'endorsement_no' => null,
                    'insurer_id' => $sanitized_post_data['insurer_id'] ?? null,
                    'description' => 'Opening Amount',
                    'transaction_type' => 'Credit',
                    'event_name' => null,
                    'updated_by' => 1,
                    'cd_ac_pk' => $insert,
                ];

                $this->myLogger->logme("error", 'Saving initial deposit with data: ' . json_encode($cd_tranction_data));
                $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);
                $this->myLogger->logme("error", 'Deposit save response: ' . json_encode($response));

                $cd_master_data = $this->CDMasterModel->where('is_active', 1)->where('id', $insert)->first();
                $this->myLogger->logme("error", 'Inserted CD Master data: ' . json_encode($cd_master_data));

                $cd_master_full_data = $this->CDMasterModel->where('is_active', 1)
                                        ->where('client_id', $sanitized_post_data['client_id'])
                                        ->where('insurer_id', $sanitized_post_data['insurer_id'])
                                        ->where('insurer_branch_id', $sanitized_post_data['insurer_branch_id'])
                                        ->findAll();

                return $this->respond([
                    'status' => true,
                    'code' => 500,
                    'message' => "CD Master Added Successfully",
                    'cd_master_data' => $cd_master_data,
                    'data' => $cd_master_full_data
                ]);

            } else {

                 $this->myLogger->logme('error', 'CD Master Insert Failed.');
                 return $this->respond([
                    'status' => true,
                    'code' => 500,
                    'message' => "CD Master Add Failed",
                 ], 200);
            }
        }

        // === UPDATE ===
        $this->myLogger->logme("error", 'Performing UPDATE operation for ID: ' . $id);

        $updated = $this->CDMasterModel->where('id', $id)->set($sanitized_post_data)->update();
        $this->myLogger->logme("error", 'Update result: ' . json_encode($updated));

        $existingData = $this->CDMasterModel->where('is_active', 1)->where('id', $id)->first();
        $this->myLogger->logme("error", 'Existing data after update: ' . json_encode($existingData));

        $cd_transaction_updated_data = [
            'balance' => $existingData['opening_bal'],
            'amount' => $existingData['opening_bal']
        ];

        $updateDeposit =$this->clientDepositModel
            ->where('client_id', $existingData['client_id'])
            ->where('insurer_id', $existingData['insurer_id'])
            ->where('cd_ac_no', $existingData['cd_ac_no'])
            ->where('sub_type', 7)
            ->set($cd_transaction_updated_data)
        ->update();
        $this->myLogger->logme("error", 'Client Deposit Update result: ' . json_encode($updateDeposit));

        if ($updated) {
            $this->myLogger->logme("error", 'CD Master Updated Successfully.');
            return $this->respond([
                'status' => true,
                'message' => "CD Master Updated Successfully"
            ]);
        } else {
           $this->myLogger->logme('error', 'CD Master Update Failed.');
           return $this->respond([
                'status' => true,
                'code' => 500,
                'message' => "CD Master Updated Failed",
            ], 200);
        }
    }

    public function editCDMasterData($id = null)
    {
        $this->myLogger->logme("error", 'Edit CD Master Data API called.');
        $rules = [

            // ======================
            // Client / Insurer Mapping
            // ======================
            'client_id' => [
                'rules'  => 'required|is_natural_no_zero',
                'errors' => [
                    'required' => 'Client is required'
                ]
            ],

            'insurer_id' => [
                'rules'  => 'required|is_natural_no_zero',
                'errors' => [
                    'required' => 'Insurer is required'
                ]
            ],

            'insurer_branch_id' => [
                'rules'  => 'required|is_natural_no_zero',
                'errors' => [
                    'required' => 'Insurer branch is required'
                ]
            ],

            // ======================
            // CD Account Details
            // ======================
            'opening_date' => [
                'rules'  => 'required|valid_date[d-m-Y]',
                'errors' => [
                    'required'   => 'Opening date is required',
                    'valid_date' => 'Opening date must be in DD-MM-YYYY format'
                ]
            ],

            'cd_ac_no' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'CD account number is required'
                ]
            ],

            'opening_bal' => [
                'rules'  => 'required|numeric|greater_than_equal_to[0]',
                'errors' => [
                    'required' => 'Opening amount is required',
                    'numeric'  => 'Opening amount must be numeric',
                    'greater_than_equal_to' => 'Opening amount cannot be negative'
                ]
            ],
        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status' => false,
                'message' => 'Input validation failed',
                'code' => 400,
                'errors' => $this->validator->getErrors()
            ]);
        }
        $data   = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);
        $id = $sanitized_post_data['PrimaryKey'] ?? null;
        $date = ((string) $sanitized_post_data['opening_date']) ?? null;
        $sanitized_post_data['opening_date'] = date('Y-m-d', strtotime($date));

        if ($data) {

            $insert = $this->CDMasterModel->where('id', $id)->set($sanitized_post_data)->update();

            $get_data = $this->CDMasterModel->where('id', $id)->first();

            $cd_transaction_updated_data = [
                'balance' => $get_data['opening_bal'],
                'amount' => $get_data['opening_bal']
            ];

            $cd_tranction = $this->clientDepositModel
                ->where('client_id', $sanitized_post_data['client_id'])
                ->where('insurer_id', $sanitized_post_data['insurer_id'])
                ->where('cd_ac_no', $sanitized_post_data['cd_ac_no'])
                ->where('sub_type', 7)
                ->set($cd_transaction_updated_data)->update();
                        
            if ($insert) {

                session()->setFlashdata('success', "Cash Deposite Master Updated Successfully");
                return redirect()->to(base_url('/master/cash_deposite/list'));
            } else {

                session()->setFlashdata('error', "Cash Deposite Master Update Failed");
                return redirect()->to(base_url('/master/cash_deposite/list'));
            }
        } else {

            session()->setFlashdata('error', "Cash Deposite Master Update Failed. Data Not Found");
            return redirect()->to(base_url('/master/cash_deposite/list'));
        }
    }

    public function getCDMasterDataByID($id = null)
    {

        $cd_data = $this->CDMasterModel
            ->where('id', $id)
            ->where('is_active', 1)
            ->first();

        $db = db_connect();
        $builder = $db->table('cd_master');
        $builder->select('cd_master.cd_ac_no, cd_master.id, COUNT(cash_deposit.cd_ac_no) AS cd_ac_no_count_cd_tranction');
        $builder->join('cash_deposit', 'cash_deposit.cd_ac_pk = cd_master.id');
        $builder->where('cash_deposit.is_active', 1);
        $builder->where('cd_master.is_active', 1);
        $builder->where('cd_master.id', $id);
        $builder->groupBy('cd_master.id');
        
        $query = $builder->get();
        $result = $query->getResultArray();

        // print_r($result); die;

        $count = 0;
        if(isset($result[0])){
            $count = $result[0]['cd_ac_no_count_cd_tranction'];
        }
        
        // convert the date formate 2000-01-01  to  01-01-2000
        $cd_data['opening_date'] = date('d-m-Y', strtotime($cd_data['opening_date']));

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

    public function checkUniqueCDAccountNumber($AccountNumber)
    {
        $uniqueAC = $this->CDMasterModel
            ->where('cd_ac_no', $AccountNumber)
            ->where('is_active', 1)
            ->findAll();

        if($uniqueAC != null){
            return $this->respond(['status' => true, 'message' => 'The CD Account Number is Already Exist', 'code' => 200], 200);
        }else{
            return $this->respond(['status' => false, 'code' => 404], 200);
        }
    }

    public function removeCDMaster($id)
    {

        $this->myLogger->logme('error','CDMaster Remove function called');
        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        $cash_transaction_data = $this->CDMasterModel->where('id', $id)->first();

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

        $cd_tranction_update = $this->clientDepositModel
            ->where('client_id', $cash_transaction_data['client_id'])
            ->where('insurer_id', $cash_transaction_data['insurer_id'])
            ->where('cd_ac_no', $cash_transaction_data['cd_ac_no'])
            ->where('sub_type', 7)
            ->set($data)
            ->update();

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

    public function createCDAccountNumberUsingAjax()
    {
        $data = $this->request->getPost();
        $date = (string) $this->request->getPost('opening_date');
        $data['opening_date'] = date('Y-m-d', strtotime($date));

        $insurer_id = null;
        $insurer_branch_id = null;
        if(isset($data['insurer_and_insurer_branch']) && !empty($data['insurer_and_insurer_branch'])){
            list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer_and_insurer_branch']);
        }

        $data['insurer_branch_id'] = $insurer_branch_id;

        $cd_acc_count = $this->CDMasterModel->where('is_active', 1)
                        ->where('client_id', $data['client_id'])
                        ->where('insurer_id', $data['insurer_id'])
                        ->where('insurer_branch_id', $data['insurer_branch_id'])
                        ->countAllResults();
        
        if($cd_acc_count > 0){
            return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
        }

        // array with data for CD Traction table
        $cd_tranction_data = [
            'amount' => $data['opening_bal'],
            'sub_type_id' => 7,
            'client_id' => $data['client_id'],
            'client_policy_id' => null,
            'cd_ac_no' => $data['cd_ac_no'],
            'endorsement_no' => null,
            'insurer_id' => (int) $data['insurer_id'],
            'description' => 'opening Amount',
            'transaction_type' => 'Credit',
            'event_name' => null,
            'updated_by' => 1,
        ];

        $loggedInUserID = get_session_userid();
    
        $insert = $this->CDMasterModel->insert($data);

        if ($insert) {

            //for CD Tranction Table
            $cd_tranction_data['cd_ac_pk'] = $this->CDMasterModel->insertID();
            $response = DepositHelper::saveDeposit($cd_tranction_data, $loggedInUserID);
            
            $cd_data = $this->CDMasterModel->where('client_id', $data['client_id'])->where('insurer_id', $data['insurer_id'])->findAll();

            return $this->respond([
                'status' => true, 
                'cd_ac_pk' => $insert, 
                'data' => $cd_data, 
                'received_data' => $data, 
                'cd_ac_no'=>$data['cd_ac_no'], 
                'message' => 'CD Account number created successfully', 
                "FOR BDS PURPOSE"
            ], 200);

        }else{
            return $this->respond(['status' => false, 'message' => 'Failed to created CD Account number'], 200);
        }
    }

    public function checkDuplicateCdAccount()
    {   
        $data = $this->request->getGet();

        $cd_acc_count = $this->CDMasterModel
            ->where('is_active', 1)
            ->where('client_id', $data['client_id'])
            ->where('insurer_id', $data['insurer_id'])
            ->where('insurer_branch_id', $data['insurer_branch_id'])
            ->countAllResults();
    
        if($cd_acc_count > 0){
            return $this->respond(['status' => false, 'message' => 'A CD account has already been created for this client, insurer, and insurer branch combination.'], 200);
        }else{
            return $this->respond(['status' => true], 200);
        }
    }


    //Vehicle Master data Function

    public function VehicleMasterList()
    {   
        $data['tab_name'] = 'Vehicle Masters';
        $data['page_name'] = 'Vehicles';
        $data['vehicle_type'] = [
            'two_wheeler' => 'Two Wheeler',
            'four_wheeler' => 'Four Wheeler',
            'truck' => 'Truck',
            'bus' => 'Bus',
            'van' => 'Van',
            'suv' => 'SUV',
            'motorcycle' => 'Motorcycle',
            'bicycle' => 'Bicycle'
        ];
        $data['vehicle_des'] = [
            'commercial' => 'Commercial',
            'private' => 'Private',
        ];
        $data['entity']  = $this->kycEntityTypeModel->where('is_active', 1)->findAll();
        $data['clients'] = $this->clientModel->where('is_active', 1)->findAll();
        $data['vehicle_Master_Data'] = $this->vehicleModel->getVehicleMasterList();
        $this->loadLayout('vehicle_master_list', $data);
    }

    public function getVehicleMasterDataByID($id = null)
    {
        $vehicle_data = $this->vehicleModel
            ->select('vehicle.*, clients.client_type')
            ->join('clients', 'vehicle.owner = clients.id')
            ->where('vehicle.id', $id)
            ->where('vehicle.is_active', 1)
            ->first();
        
        if ($vehicle_data) {
            return $this->respond(['status' => true, 'code' => 200, 'data' => $vehicle_data], 200);
        } else {
            return $this->respond(['status' => false, 'code' => 404], 200);
        }
    }
    
    public function deactiveVehicleData($id)
    {

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

        $data['updated_by'] = get_session_userid();
        $data['is_active'] = 0;
        
        $update = $this->vehicleModel->where('id', $id)->set($data)->update();

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


    //excel export template 
    public function createExcelTemplate()
    {   
        // return $this->respond($this->request->getPost());
        $template_id = $this->request->getPost('template_id');

        $rules = [
            'policy_type' => [
                'rules'  => 'required|is_natural_no_zero',
                'errors' => [
                    'required' => 'Policy type is required'
                ]
            ],

            'event' => [
                'rules'  => 'required|trim',
                'errors' => [
                    'required' => 'Event is required'
                ]
            ],

    
            'json_data' => [
                'rules'  => 'required',
                'errors' => [
                    'required' => 'Template mapping data is required'
                ]
            ],
        ];

        if (! $this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'status'  => false,
                'message' => 'Input validation failed',
                'code'    => 400,
                'errors'  => $this->validator->getErrors()
            ]);
        }
        $data           = $this->request->getPost();
        $sanitized_post_data = sanitizeInputArrayAdvanced($data);


       
        $fetch_data = [
            'insurer_id' => $sanitized_post_data['insurer_id'] ?? null ,
            'policy_type_id' => $sanitized_post_data['policy_type'] ?? null,
            'event_name' => $sanitized_post_data['event'] ?? null,
            'type_name' => 'export',
            'jsoncolumns' => $sanitized_post_data['json_data'] ?? null,
            'is_active' => 1,
            'created_by' => get_session_userid(),
        ];

        if($template_id){

            $update = $this->insurerTemplateModel->where('id', $template_id)->set($fetch_data)->update();

            if($update){
                return $this->respond(['status' => true, 'message' => 'Template updated successfully',  $fetch_data]);
            }else{
                return $this->respond(['status' => true, 'message' => 'Failed to update template',  $fetch_data]);
            }

        }else{

            $insert = $this->insurerTemplateModel->insert($fetch_data);

            if($insert){
                return $this->respond(['status' => true, 'message' => 'Template created successfully',  $fetch_data]);
            }else{
                return $this->respond(['status' => true, 'message' => 'Failed to create template',  $fetch_data]);
            }
        }


    }

    // Duplicate the insuer same policy type other events template
    public function duplicateTemplate($template_id, $event_name, $insurer_id)
    {

        // Fetch the template data based on the provided ID and ensure it is active
        $insurer_template_data = $this->insurerTemplateModel->where('id', $template_id)
            ->where('is_active', 1)
            ->first();

        // Check if the event name matches the existing template's event name
        $insurer_template_data_check_duplicate = $this->insurerTemplateModel
            ->where('insurer_id', $insurer_id)
            ->where('event_name', $event_name)
            ->where('policy_type_id', $insurer_template_data['policy_type_id'])
            ->where('is_active', 1)
            ->findAll();

        //if the template already exist than return the message
        if (!empty($insurer_template_data_check_duplicate) && count($insurer_template_data_check_duplicate) > 0) {
            return $this->respond([
                'status' => false,
                'message' => 'Template with the same event already exists.',
                'data' => $insurer_template_data_check_duplicate
            ]);
        }

        if ($insurer_template_data) {

            // Prepare data for insertion as a duplicate
            $data_to_insert = [
                "insurer_id" => $insurer_template_data['insurer_id'],
                "policy_type_id" => $insurer_template_data['policy_type_id'],
                "event_name" => $event_name,
                "type_name" => $insurer_template_data['type_name'],
                "jsoncolumns" => $insurer_template_data['jsoncolumns'],
                "created_by" => get_session_user(),
                "is_active" => 1,
            ];

            // Insert the duplicate template data
            $insert_result = $this->insurerTemplateModel->insert($data_to_insert);

            if ($insert_result) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Template duplicated successfully.',
                    'data' => $insurer_template_data
                ]);
            } else {
                return $this->respond([
                    'status' => false,
                    'message' => 'Failed to duplicate template.',
                    'data' => $insurer_template_data
                ]);
            }
        } else {
            // No matching active template found
            return $this->respond([
                'status' => false,
                'message' => 'No active template data found.',
                'data' => null
            ]);
        }
    }

    public function generateNewGmailAPIToken()
    {
        $gmailapi = \Config\Services::gmailapi();
        $gmailapi->generateNewToken();

    }

    //testing a sample mail from front end
    public function testGmailAPI()
    {

        if ($this->request->getMethod() == 'post') {
            // $gmailapi = \Config\Services::gmailapi();

            $to = $this->request->getPost('to');
            $subject = $this->request->getPost('subject');
            $mail_content = $this->request->getPost('content');
            $common = ['mail_type' => 'test_mail_ui'];
            /*****CHOOSE ANY ONE AT A TIME, COMMENT ANOTHER ONE******/

            /*****CALLING DIRECLT USING LIB******/
            // $res = $gmailapi->sendMessage($to, $subject, $mail_content, 'info@nhanceindia.in', 'info@nhanceindia.in', $cc = [], $bcc = []);

            // if($res['status'])
            // {
            //   return $this->respond(['status' => 'success','code' => 200,'data' => $res],200);
            // }
            // else
            // {
            //      $this->respond(['status' => 'failed','code' => 500,'data' => $res],200);
            // }
            /*****CALLING DIRECLT USING LIB******/

            /*****CALLING VIA MAIL HELPER******/
            $res = MailHelper::send_email(['mail' => $to, 'subject' => $subject, 'common' => $common, 'message' => $mail_content]);
            return $this->respond(['status' => 'success', 'code' => 200, 'data' => $res], 200);
            /*****CALLING VIA MAIL HELPER******/
        }

        $this->loadLayout('mail_test');
    }
    
    //testing a sample mail from cli
    public function testGmailAPIViaCLI(string $email_id = 'velmurugan.s@venbainfotech.com')
    {

        $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id;
        // print_r($email_id);die();
        // $gmailapi = \Config\Services::gmailapi();
        $message = '';

        // $attachments = [
        //     ["filePath" => WRITEPATH."uploads/excel/sample/correction.xls","fileName" => "correction.xls"],
        //     ["filePath" => WRITEPATH."uploads/excel/sample/deletion.xls","fileName" => "deletion.xls"],
        //     ["filePath" => "C:\\Users\\Venba\\Desktop\\IQ.pdf","fileName" => "Questions.pdf"],
        //     ["filePath" => "C:\\Users\\Venba\\Desktop\\config_age.png","fileName" => "config_age.png"]
        // ];

        $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"]
        ];
        $common = ['mail_type' => 'test_mail_cli'];
        $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id;
        $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message, 'attachments' => $attachments, 'common' => $common]);
        echo "Inside the master controller";
        print_r($res);
    }

    public function testZeptoSMTP()
    {
        $message = '';
        $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"]
        ];
        $email_id = ['srinivas.saravanan@venbainfotech.com', 'srinivassaravanan2002@gmail.com'];
        $params = ['mail' => $email_id];
        $common = ['mail_type' => 'test_mail_cli'];
        // $bcc = "vijayalakshmi@nhanceindia.in,vitvelz@gmail.com,velmurugan.s@venbainfotech.com,hariharan@nhanceindia.in,hariharan@jubiliant.in,srinivas.saravanan@venbainfotech.com";
        // Send email and get response
        $result = MailHelper::send_email(['mail' => $email_id, 'params' => $params, 'subject' => 'Mail Via CLI', 'message' => $message, 'attachments' => $attachments, 'common' => $common]);


        log_message('error', json_encode($result));
        // Format the response for display/debugging
        $response = [
            'success' => $result['success'] ?? false,
            'smtp_data' => [
                'last_reply' => $result['smtp_data']['last_reply'] ?? '',
                'error_info' => $result['smtp_data']['error_info'] ?? ''
            ],
            'message_id' => $result['message_id'] ?? '',
            'timestamp' => $result['timestamp'] ?? ''
        ];

        // Return JSON response
        return $this->response->setJSON($result);
    }

    public function testCheckBounceMails()
    {
        $gmailapi = \Config\Services::gmailapi();
        $from_date = CLI::getOption('from') ? CLI::getOption('from') : null;
        $to_date = CLI::getOption('to') ? CLI::getOption('to') : null;
        $count = CLI::getOption('count') ? CLI::getOption('count') : null;
        $page = CLI::getOption('page') ? CLI::getOption('page') : null;
        $res = $gmailapi->checkBounceStatus(from_date: $from_date, to_date: $to_date, count: $count, page: $page);
        print_r($res);
    }

    public function appCheckList()
    {
        //check temprory folders in writeable and public/uploads folder
        $this->checkAndCreateDirectories();
        $this->checkGoogleOAuthCredentialsinDB();
        $this->getCronJobsList();
        $this->checkGdriveRootFolderID();
        $this->checkEnv();
    }

    public function checkAndCreateDirectories()
    {
        echo "#################### CHECKING TEMP DIRECTORIES ############################\n";
        // Array of folder names and their respective paths
        $folders = [
            'e_card_template' => WRITEPATH . 'e_card_template/',
            'uploads' => WRITEPATH . 'uploads/',
            'excel' => WRITEPATH . 'uploads/excel/',
            'statements' => WRITEPATH . 'uploads/statements/',
            'import_excel' => WRITEPATH . 'uploads/import_excel/',
            'logs' => WRITEPATH . 'logs',
            'session' => WRITEPATH . 'session',
            'client_kyc_documents' => WRITEPATH . 'uploads/client_kyc_documents/',
            'tmp' => WRITEPATH . 'tmp/',
            'e_card_imgs' => ROOTPATH . 'public/e_card_imgs',
            'uploads' => ROOTPATH . 'public/uploads',
            'add_image_upload' => ROOTPATH . 'public/uploads/add_image_upload/', //adverdisement images for enrollment app
            'logo' => ROOTPATH . 'public/uploads/logo/',
            'template_bg' => ROOTPATH . 'public/uploads/template_bg/',
            'attachments' => WRITEPATH . 'uploads/attachments/',
            'cache' => WRITEPATH . 'cache',
            'sample_import_excel' => ROOTPATH . 'public/sample_import_excel',
            'lead_files' => WRITEPATH . 'uploads/lead_files/',
            'claim_files' => WRITEPATH . 'uploads/claim_files/',
            'claim_dump_excel' => WRITEPATH . 'uploads/claim_dump_excel/',
            'commission' => WRITEPATH . 'uploads/commission/',
            'files' => WRITEPATH . 'uploads/commission/files',
            'rules' => WRITEPATH . 'uploads/commission/rules',
            'claim_sample_forms' => ROOTPATH . 'public/claim_sample_forms/',
            'tmp' => ROOTPATH . 'public/tmp/',
            'bds_dump_excel' => WRITEPATH . 'uploads/bds_dump_excel/',
            'claims_mis' => WRITEPATH . 'uploads/claims_mis/',
        ];

        foreach ($folders as $folderName => $folderPath) {
            // Check if the folder exists
            if (!is_dir($folderPath)) {
                // Try to create the folder
                if (mkdir($folderPath, 0777, true)) {
                    // Set permissions to 0777
                    chmod($folderPath, 0777);
                    echo "\nDirectory '$folderPath' created successfully with 0777 permissions.\n";
                } else {
                    // Handle error in directory creation
                    echo "Failed to create directory '$folderPath'.\n";
                }
            } else {
                echo "Directory '$folderPath' already exists.\n";
            }
        }
        echo "################################################################\n\n";
    }

    public function checkGoogleOAuthCredentialsinDB()
    {
        $settingsModel = new SettingsModel();
        $token = $settingsModel->where('id', 1)->first();

        echo "################ CHECKING GMAIL OAUTH FOR EMAIL ###################\n";
        if (is_array($token) &&  is_null($token['gmail_api_oauth_credentials'])) {

            echo "Email OAuth credentials not found in database.\n";
            echo "Check the following..!\n";
            echo "1. Update Gmail Oauth credentials in 'gmail_api_oauth_credentials' field in 'settings' table in JSON format.\n";
            echo "2. Call this cli route to generate new access token: 'php public/index.php cli/new_gmail_token' from root of the project.\n";
            echo "3. Call this cli route : 'php public/index.php cli/send_mail_cli --to someone@gmail.com' to send test mail to testGmailAPIViaCLI ( replace someone@gmail.com with real time mail).\n";
        } else {
            echo "Gmail OAuth for sending email is set in DB\n";
        }
        echo "################################################################\n\n";
    }

    function getCronJobsList()
    {
        // Execute the shell command to get cron jobs
        $output = null;
        $resultCode = null;
        echo "#################### CHECKING CRONJOBS ############################\n";
        // Use shell_exec to get cron jobs from the current user's crontab
        $output = shell_exec('crontab -l 2>&1');

        // Check if the command was successful
        if (strpos($output, 'no crontab') !== false) {
            echo  "No cron jobs are set for this user.\n";
        } elseif ($output) {
            // Return the cron job list
            echo nl2br($output);
            echo "\n"; // Convert newlines to 
for easier HTML rendering } else { echo "Error retrieving cron jobs or no cron jobs set.\n"; } echo "################################################################\n\n"; } //check gdrive root folder id in env file function checkGdriveRootFolderID() { echo "#################### CHECKING GDRIVE FOLDER ID IN ENV FILE ############################\n"; $id = getenv('GDRIVE_ROOT_FOLDER_ID'); if ($id) { echo $this->cli_colors['green'] . "ID is :" . $id . $this->cli_colors['reset'] . "\n"; } else { echo $this->cli_colors['red'] . "Gdrive Folder id not set in env file. set it under 'GDRIVE_ROOT_FOLDER_ID' in env file." . $this->cli_colors['reset'] . "\n"; } echo "################################################################\n\n"; } public function sendMutipleToEmails() { $message = ''; $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"] ]; $email_id = 'venkateshraman786@gmail.com'; $params = ['mail' => $email_id]; $multi_mails = ['venkateshraman786@gmail.com', 'gowtham.manavalan.la@gmail.com', 'venkatesh.r@venbainfotech.com']; $common = ['mail_type' => 'test_mail_cli']; $bcc = "vitvelz@gmail.com,velmurugan.s@venbainfotech.com,srinivas.saravanan@venbainfotech.com"; $result = MailHelper::send_email(['mail' => $multi_mails, 'bcc' => $bcc, 'params' => $params, 'subject' => 'Send Multiple " To " emails', 'message' => $message, 'attachments' => $attachments, 'common' => $common]); dd($result); } public function checkEnv() { $root = ROOTPATH; $sample_file_name = '.env.sample'; $sample_file_path = $root . $sample_file_name; $envFile = $root . '.env'; // echo ($exampleFile);//die(); if (!file_exists($sample_file_path)) { echo ("$sample_file_path file not found"); exit(); } if (!file_exists($envFile)) { echo('.env file not found'); exit(); } $example = $this->parseEnv($sample_file_path); $actual = $this->parseEnv($envFile); $missing = array_diff_key($example, $actual); $extra = array_diff_key($actual, $example); CLI::write("#################### CHECKING ENV ##############################\n"); if ($extra) { CLI::write('⚠️ Extra ENV keys (not in .env.example)', 'yellow'); foreach (array_keys($extra) as $key) { CLI::write(" - $key", 'yellow'); } } CLI::newLine(); if ($missing) { CLI::error('❌ Missing ENV keys'); foreach (array_keys($missing) as $key) { CLI::write(" - $key", 'red'); } } CLI::newLine(); if (!$missing && !$extra) { CLI::write('✅ ENV configuration is clean', 'green'); return CLI::EXIT_SUCCESS; } CLI::write("#################### END OF CHECKING ENV ############################\n"); } private function parseEnv(string $file): array { $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $env = []; foreach ($lines as $line) { $line = trim($line); if ($line === '' || str_starts_with($line, '#')) { continue; } if (strpos($line, '=') !== false) { [$key] = explode('=', $line, 2); $env[trim($key)] = true; } } return $env; } //---------------------------------------------------------------------------------------------------------- public function nhanceBranchMaster() { $nhanceBranchModel = new NhanceBranchModel(); $method = $this->request->getMethod(); if ($method === 'post') { $rules = [ 'branch_name' => [ 'rules' => 'required', 'errors' => [ 'required' => 'Branch Name is required' ] ] ]; if (! $this->validate($rules)) { return $this->response->setStatusCode(400)->setJSON([ 'status' => false, 'message' => 'Input validation failed', 'code' => 400, 'errors' => $this->validator->getErrors() ]); } $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['pk'] ?? null; unset($sanitized_post_data['pk']); if (empty($id)) { $update_status = $nhanceBranchModel->insert($sanitized_post_data); } else { $update_status = $nhanceBranchModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Nhance Branch Master updated successfully', 'data' => $data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $data ], 200); } } elseif ($method === 'get') { $id = $this->request->getGet('pk') ?? null; if (!empty($id)) { $data = $nhanceBranchModel->where('is_active', 1)->where('id', $id)->findAll(); if (!empty($data)) { return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } $data = $nhanceBranchModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll(); return $this->loadLayout('nhance_branch_list', ['data' => $data,'tab_name' => 'Nhance Branchs','page_name' => 'Nhance Branchs']); } elseif ($method === 'delete') { $input = $this->request->getRawInput(); $id = $input['pk'] ?? null; if (empty($id)) { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No ID provided for deletion' ], 200); } $update_status = $nhanceBranchModel->where('id', $id)->set(['is_active' => 0])->update(); if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data removed successfully', 'pk' => $id ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to remove data', 'pk' => $id ], 200); } } } public function vehicleTypeMaster() { $vehicleTypeModel = new VehicleTypeModel(); $method = $this->request->getMethod(); if ($method === 'post') { $rules = [ 'vehicle_type' => [ 'rules' => 'required', 'errors' => [ 'required' => 'Vehicle Type is required' ] ] ]; if (! $this->validate($rules)) { return $this->response->setStatusCode(400)->setJSON([ 'status' => false, 'message' => 'Input validation failed', 'code' => 400, 'errors' => $this->validator->getErrors() ]); } $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['pk'] ?? null; unset($sanitized_post_data['pk']); if (empty($id)) { $update_status = $vehicleTypeModel->insert($sanitized_post_data); } else { $update_status = $vehicleTypeModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Vehicle Type Master updated successfully', 'data' => $sanitized_post_data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $sanitized_post_data ], 200); } } elseif ($method === 'get') { $id = $this->request->getGet('pk') ?? null; if (!empty($id)) { $data = $vehicleTypeModel->where('is_active', 1)->where('id', $id)->findAll(); if (!empty($data)) { return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } $data = $vehicleTypeModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll(); return $this->loadLayout('vehicle_type_master_list', ['data' => $data,'tab_name' => 'Vehicle Types','page_name' => 'Vehicle Types']); } elseif ($method === 'delete') { $input = $this->request->getRawInput(); $id = $input['pk'] ?? null; if (empty($id)) { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No ID provided for deletion' ], 200); } $update_status = $vehicleTypeModel->where('id', $id)->set(['is_active' => 0])->update(); if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data removed successfully', 'pk' => $id ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to remove data', 'pk' => $id ], 200); } } } public function rtoMaster() { $rtoModel = new RTOModel(); $method = $this->request->getMethod(); if ($method === 'post') { $rules = [ // ====================== // RTO Office Name // ====================== 'rto_name' => [ 'rules' => 'required|trim|min_length[3]|max_length[100]|alpha_numeric_space', 'errors' => [ 'required' => 'RTO Office Name is required', 'min_length' => 'RTO Office Name must be at least 3 characters' ] ], // ====================== // RTO Code (2 digits only) // ====================== 'rto_code' => [ 'rules' => 'required|exact_length[2]|numeric', 'errors' => [ 'required' => 'RTO Code is required', 'exact_length' => 'RTO Code must be exactly 2 digits', 'numeric' => 'RTO Code must contain only numbers' ] ], // ====================== // RTO State (2 letters only) // ====================== 'rto_state' => [ 'rules' => 'required|exact_length[2]|alpha', 'errors' => [ 'required' => 'RTO State is required', 'exact_length' => 'RTO State must be exactly 2 letters', 'alpha' => 'RTO State must contain only alphabets' ] ], ]; if (! $this->validate($rules)) { return $this->response->setStatusCode(400)->setJSON([ 'status' => false, 'message' => 'Input validation failed', 'code' => 400, 'errors' => $this->validator->getErrors() ]); } $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['pk'] ?? null; unset($sanitized_post_data['pk']); if (empty($id)) { $update_status = $rtoModel->insert($sanitized_post_data); } else { $update_status = $rtoModel->where('id', $id)->set($sanitized_post_data)->update(); } if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'RTO Master updated successfully', 'data' => $sanitized_post_data ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $sanitized_post_data ], 200); } } elseif ($method === 'get') { $id = $this->request->getGet('pk') ?? null; if (!empty($id)) { $data = $rtoModel->where('is_active', 1)->where('id', $id)->findAll(); if (!empty($data)) { return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } $data = $rtoModel->where('is_active', 1)->orderBy('id', 'DESC')->findAll(); return $this->loadLayout('rto_master_list', ['data' => $data,'tab_name' => 'RTO Masters','page_name' => 'RTO']); } elseif ($method === 'delete') { $input = $this->request->getRawInput(); $id = $input['pk'] ?? null; if (empty($id)) { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No ID provided for deletion' ], 200); } $update_status = $rtoModel->where('id', $id)->set(['is_active' => 0])->update(); if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data removed successfully', 'pk' => $id ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to remove data', 'pk' => $id ], 200); } } } public function partnerPOS() { $posModel = new PartnerPosModel(); $method = $this->request->getMethod(); if ($this->request->getMethod() === 'post') { try { $rules = [ 'manager_id' => [ 'rules' => 'required|integer', 'errors' => [ 'required' => 'Manager is required', 'integer' => 'Invalid Manager selected' ] ], 'name' => [ 'rules' => 'required|min_length[3]|max_length[100]|alpha_space', 'errors' => [ 'required' => 'Name is required', 'min_length' => 'Name must be at least 3 characters', 'max_length' => 'Name cannot exceed 100 characters', 'alpha_space' => 'Name can contain only letters and spaces' ] ], 'pos_code' => [ 'rules' => 'required|alpha_numeric|max_length[20]', 'errors' => [ 'required' => 'POS Code is required', 'alpha_numeric' => 'POS Code must be alphanumeric', 'max_length' => 'POS Code cannot exceed 20 characters' ] ], 'email' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]', 'errors' => [ 'required' => 'Email address is required.', 'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).' ] ], 'mobile' => [ 'rules' => 'required|numeric|exact_length[10]', 'errors' => [ 'required' => 'Mobile number is required', 'numeric' => 'Mobile number must contain only digits', 'exact_length' => 'Mobile number must be exactly 10 digits' ] ], 'address' => [ 'rules' => 'required|min_length[5]', 'errors' => [ 'required' => 'Address is required', 'min_length' => 'Address must be at least 5 characters' ] ], 'state' => [ 'label' => 'State', 'rules' => 'required|regex_match[/^[a-zA-Z0-9\/\-\_\.\s]+$/]', 'errors' => [ 'required' => 'State is required.', 'regex_match' => 'State name can only contain letters, spaces, and hyphens.' ] ], 'city' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s\-]+$/]', 'errors' => [ 'regex_match' => 'City can contain letters, numbers, spaces, and hyphens.' ] ], 'pincode' => [ 'rules' => 'required|numeric|exact_length[6]', 'errors' => [ 'required' => 'Pincode is required.', 'numeric' => 'Pincode must be digits only.', 'exact_length' => 'Pincode must be exactly 6 digits.' ] ], 'aadhar' => [ 'rules' => 'required|numeric|exact_length[12]', 'errors' => [ 'required' => 'Aadhaar number is required', 'numeric' => 'Aadhaar must contain only digits', 'exact_length' => 'Aadhaar must be exactly 12 digits' ] ], 'pan' => [ 'rules' => 'required|regex_match[/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/]', 'errors' => [ 'required' => 'PAN number is required', 'regex_match' => 'Enter a valid PAN number (ABCDE1234F)' ] ], 'gst' => [ 'rules' => 'permit_empty|max_length[15]', 'errors' => [ 'max_length' => 'GST number cannot exceed 15 characters' ] ], 'aadhar_file_name' => [ 'rules' => 'if_exist|max_size[aadhar_file_name,5120]|ext_in[aadhar_file_name,pdf,jpg,jpeg,png]', 'errors' => [ 'max_size' => 'Aadhaar file size should not exceed 5MB', 'ext_in' => 'Aadhaar must be PDF or image (jpg, jpeg, png)' ] ], 'pan_file_name' => [ 'rules' => 'if_exist|max_size[pan_file_name,5120]|ext_in[pan_file_name,pdf,jpg,jpeg,png]', 'errors' => [ 'max_size' => 'PAN file size should not exceed 5MB', 'ext_in' => 'PAN must be PDF or image (jpg, jpeg, png)' ] ], 'certificate_file_name' => [ 'rules' => 'if_exist|max_size[certificate_file_name,5120]|ext_in[certificate_file_name,pdf,jpg,jpeg,png]', 'errors' => [ 'max_size' => 'Certificate file size should not exceed 5MB', 'ext_in' => 'Certificate must be PDF or image (jpg, jpeg, png)' ] ], ]; if (! $this->validate($rules)) { return $this->response->setStatusCode(400)->setJSON([ 'status' => false, 'message' => 'Input validation failed', 'code' => 400, 'errors' => $this->validator->getErrors() ]); } $data = $this->request->getPost(); $sanitized_post_data = sanitizeInputArrayAdvanced($data); $id = $sanitized_post_data['pk'] ?? null; unset($sanitized_post_data['pk']); try { // Certificate $certificate = $this->uploadPOSFile('certificate_file_name', 'pos_certificate_files'); if ($certificate !== null) { $sanitized_post_data['certificate_file_name'] = $certificate; } else { unset($sanitized_post_data['certificate_file_name']); } // PAN file $panFile = $this->uploadPOSFile('pan_file_name', 'pos_certificate_files'); if ($panFile !== null) { $sanitized_post_data['pan_file_name'] = $panFile; } else { unset($sanitized_post_data['pan_file_name']); } // Aadhaar file $aadharFile = $this->uploadPOSFile('aadhar_file_name', 'pos_certificate_files'); if ($aadharFile !== null) { $sanitized_post_data['aadhar_file_name'] = $aadharFile; } else { unset($sanitized_post_data['aadhar_file_name']); } } catch (\Exception $e) { log_message('error', 'File upload error: ' . $e->getMessage() . ' | POST data: ' . json_encode($sanitized_post_data) . $e->getTraceAsString()); return $this->respond(['status' => false, 'code' => 400, 'message' => $e->getMessage(), 'data' => $sanitized_post_data], 400); } foreach ($sanitized_post_data as $k => $v) { if ($v === '' || $v === null) { unset($sanitized_post_data[$k]); } } // INSERT / UPDATE try { if (empty($id)) { $status = $posModel->insert($sanitized_post_data); } else { $status = $posModel->update($id, $sanitized_post_data); } if ($status) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'POS updated successfully', 'data' => $sanitized_post_data], 200); } $modelErrors = method_exists($posModel, 'errors') ? $posModel->errors() : []; return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'errors' => $modelErrors, 'data' => $sanitized_post_data ], 400); } catch (\Throwable $e) { log_message('error', 'partnerPOS DB error: ' . $e->getMessage() . ' | payload: ' . json_encode($sanitized_post_data) . ' | trace: ' . $e->getTraceAsString()); $message = 'Something went wrong while saving POS details.'; $statusCode = 500; if (stripos($e->getMessage(), 'Duplicate entry') !== false) { $statusCode = 400; if (stripos($e->getMessage(), 'email') !== false) { $message = 'Email already exists.'; } elseif (stripos($e->getMessage(), 'mobile') !== false) { $message = 'Mobile number already exists.'; } else { $message = 'Duplicate data found. Please check email/mobile.'; } } return $this->respond([ 'status' => false, 'code' => $statusCode, 'message' => $message ], $statusCode); } } catch (\Throwable $e) { log_message( 'error', 'partnerPOS fatal error: ' . $e->getMessage() . ' | file: ' . $e->getFile() . ' | line: ' . $e->getLine() . ' | trace: ' . $e->getTraceAsString() ); return $this->respond([ 'status' => false, 'code' => 500, 'message' => 'Internal server error while processing POS request.' ], 500); } } elseif ($method === 'get') { $id = $this->request->getGet('pk') ?? null; $db = db_connect(); $builder = $db->table('partner_staff'); $data['manager_list'] = $builder->select('partner_staff.id, partner_staff.name') ->where('partner_staff.is_active', 1) ->where('partner_staff.role_id', 1) ->get() ->getResultArray(); if (!empty($id)) { $data['pos_list'] = $posModel ->select('partner_pos.*, partner_staff.name AS manager_name') ->join('partner_staff', 'partner_staff.id = partner_pos.manager_id', 'left') ->where('partner_pos.id', $id) ->orderBy('partner_pos.id', 'DESC') ->findAll(); if (!empty($data)) { return $this->respond(['status' => true, 'code' => 200, 'data' => $data], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'No data found'], 200); } } $data['pos_list'] = $posModel ->select('partner_pos.*, ps.name AS manager_name') ->join('partner_staff ps', 'ps.id = partner_pos.manager_id', 'left') ->orderBy('partner_pos.id', 'DESC') ->findAll(); return $this->loadLayout('pos_list', ['data' => $data, 'tab_name' => 'POS details', 'page_name' => 'POS details']); } elseif ($method === 'delete') { // $input = $this->request->getRawInput(); $id = $this->request->getGet('pk'); // ✅ THIS $id = $id ?? null; if (empty($id)) { return $this->respond([ 'status' => false, 'code' => 404, 'message' => 'No ID provided for deletion' ], 200); } $update_status = $posModel->where('id', $id)->set(['is_active' => 0])->update(); if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Data removed successfully', 'pk' => $id ], 200); } else { return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to remove data', 'pk' => $id ], 200); } } } private function uploadPOSFile(string $fieldName, string $uploadDir) { $file = $this->request->getFile($fieldName); if (!$file) { return null; } // No file selected for this optional input. if ($file->getError() === UPLOAD_ERR_NO_FILE) { return null; } if (!$file->isValid()) { throw new \RuntimeException('File upload failed for ' . $fieldName); } $allowedMime = [ 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/webp', 'application/pdf' ]; $mimeType = (string) $file->getMimeType(); if (!in_array($mimeType, $allowedMime, true)) { throw new \RuntimeException('Invalid file format for ' . $fieldName); } $path = ROOTPATH . 'public/uploads/' . $uploadDir . '/'; if (!is_dir($path)) { mkdir($path, 0755, true); } $newName = $file->getRandomName(); $file->move($path, $newName); return $newName; } }