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');
        $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
        $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath);
        $data   = $this->request->getPost();

        if($this->request->getPost('addition_add_day')){
            $data['addition_add_day'] = 1;
        }

        if($this->request->getPost('deletion_add_day')){
            $data['deletion_add_day'] = 1;
        }

        if($this->request->getPost('is_multi_event')){
            $data['is_multi_event'] = 1;
        }

        $data['created_by'] = get_session_userid();
        $data['insurer_logo'] = $file_name;
        
        $insert = $this->insurerModel->insert($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');
        $data   = $this->request->getPost();
        $data['created_by'] = get_session_userid();
        $insert = $this->insurerBranchModel->insert($data);
        
        if($insert){
            for ($i = 0; $i < count($this->request->getPost('name')); $i++) {
                // Prepare data to insert
                $data = [
                    'contact_type' => 'insurer',
                    'ref_id'       => $insert,
                    'created_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if($insert){
            $branchData = $this->insurerBranchModel->where('insurer_id', $this->request->getPost('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');

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

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

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

        if($this->request->getPost('addition_add_day')){
            $data['addition_add_day'] = 1;
        }else{
            $data['addition_add_day'] = 0;
        }

        if($this->request->getPost('deletion_add_day')){
            $data['deletion_add_day'] = 1;
        }else{
            $data['deletion_add_day'] = 0;
        }

        if($this->request->getPost('is_multi_event')){
            $data['is_multi_event'] = 1;
        }else{
            $data['is_multi_event'] = 0;
        }

        $update             = $this->insurerModel->update($id,$data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $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 CREATE function called');
        $id     = $this->request->getPost('PrimaryKey');
        $data   = $this->request->getPost();
        $update = $this->insurerBranchModel->update($id, $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($this->request->getPost('name')); $i++) {
                // Prepare data to update
                $data = [
                    'contact_type' => 'insurer',
                    'ref_id'       => $id,
                    'created_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if($update){
            $branchData = $this->insurerBranchModel->where('insurer_id', $this->request->getPost('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');

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

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


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

        $tpa_name = (string) $this->request->getPost('name');
        $short_name = (string) $this->request->getPost('short_name');

        $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
        $data = file_put_contents($file_path, $eCardTemplate);
        
        
        if ($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');
        $data   = $this->request->getPost();
        $data['created_by'] = get_session_userid();
        $insert = $this->tpaBranchModel->insert($data);
        
        if($insert){
            for ($i = 0; $i < count($this->request->getPost('name')); $i++) {
                // Prepare data to insert
                $data = [
                    'contact_type' => 'tpa',
                    'ref_id'       => $insert,
                    'created_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if($insert){
            $branchData = $this->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 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');

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

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

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

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

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

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

        $data['network_hospitals'] = $this->request->getPost('network_hospitals');
        $update             = $this->tpaModel->update($id,$data);


        $tpa_name = (string) $this->request->getPost('name');
        $short_name = (string) $this->request->getPost('short_name');
        $eCardTemplate = $this->request->getPost('ecard_content');

        $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
        $data = file_put_contents($file_path, $eCardTemplate);
        
        
        if ($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' => $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');
        $id     = $this->request->getPost('PrimaryKey');
        $data   = $this->request->getPost();
        $update = $this->tpaBranchModel->update($id, $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($this->request->getPost('name')); $i++) {
                // Prepare data to update
                $data = [
                    'contact_type' => 'tpa',
                    'ref_id'       => $id,
                    'created_by'   => get_session_userid(),
                    'name'         => $this->request->getPost('name')[$i],
                    'email'        => $this->request->getPost('email')[$i],
                    'mobile'       => $this->request->getPost('mobile')[$i],
                    'designation'  => $this->request->getPost('designation')[$i]
                ];
                $contacts = $this->levelContactModel->insert($data);
            }
        }

        if($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');
        $data   = $this->request->getPost();
        $data['created_by'] = get_session_userid();
        
        $insert = $this->kycEntityTypeModel->insert($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');
        $data   = $this->request->getPost();
        // print_r($data);die;

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

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

        if($insert){
            $kycDocsData = $this->kycDocsModel->where('kyc_type_id', $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');
        $id                 = $this->request->getPost('PrimaryKey');
        $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $update             = $this->kycEntityTypeModel->update($id,$data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $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');
        $data   = $this->request->getPost();

        $data['created_by'] = get_session_userid();
        $insert = $this->policyTypeModel->insert($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');
        $id                 = $this->request->getPost('PrimaryKey');
        $data               = $this->request->getPost();
        $data['updated_by'] = get_session_userid();
        $update             = $this->policyTypeModel->update($id,$data);
        if($update){
            echo json_encode(array("status" => true , 'data' => $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');
        $id                 = $this->request->getPost('PrimaryKey');
        $data               = $this->request->getPost();
        $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();
        $this->myLogger->logme("error", 'Received POST data: ' . json_encode($data));

        $id = $data['PrimaryKey'] ?? null;
        $date = (string) ($data['opening_date'] ?? '');
        $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', $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);
            }

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

            if ($insert) {

                $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_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', $data['client_id'])
                                        ->where('insurer_id', $data['insurer_id'])
                                        ->where('insurer_branch_id', $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($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)
    {

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

        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 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');
       
        $data = [
            'insurer_id' => $this->request->getPost('insurer_id'),
            'policy_type_id' => $this->request->getPost('policy_type'),
            'event_name' => $this->request->getPost('event'),
            'type_name' => 'export',
            'jsoncolumns' => $this->request->getPost('json_data'),
            'is_active' => 1,
            'created_by' => get_session_userid(),
        ];

        if($template_id){

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

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

        }else{

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

            if($insert){
                return $this->respond(['status' => true, 'message' => 'Template created successfully',  $data]);
            }else{
                return $this->respond(['status' => true, 'message' => 'Failed to create template',  $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/',
            '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') { $id = $this->request->getPost('pk') ?? null; $data = $this->request->getPost(); if (empty($id)) { $update_status = $nhanceBranchModel->insert($data); } else { $update_status = $nhanceBranchModel->where('id', $id)->set($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') { $id = $this->request->getPost('pk') ?? null; $data = $this->request->getPost(); if (empty($id)) { $update_status = $vehicleTypeModel->insert($data); } else { $update_status = $vehicleTypeModel->where('id', $id)->set($data)->update(); } if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'Vehicle Type 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 = $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') { $id = $this->request->getPost('pk') ?? null; $data = $this->request->getPost(); if (empty($id)) { $update_status = $rtoModel->insert($data); } else { $update_status = $rtoModel->where('id', $id)->set($data)->update(); } if ($update_status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'RTO 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 = $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') { $id = $this->request->getPost('pk'); $data = $this->request->getPost(); unset($data['pk']); try { // Certificate $certificate = $this->uploadPOSFile('certificate_file_name', 'pos_certificate_files'); if ($certificate !== null) { $data['certificate_file_name'] = $certificate; } else { unset($data['certificate_file_name']); } // PAN file $panFile = $this->uploadPOSFile('pan_file_name', 'pos_certificate_files'); if ($panFile !== null) { $data['pan_file_name'] = $panFile; } else { unset($data['pan_file_name']);} // Aadhaar file $aadharFile = $this->uploadPOSFile('aadhar_file_name', 'pos_certificate_files'); if ($aadharFile !== null) { $data['aadhar_file_name'] = $aadharFile; } else { unset($data['aadhar_file_name']);} } catch (\RuntimeException $e) { return $this->respond([ 'status' => false, 'code' => 400, 'message' => $e->getMessage(), 'data' => $data ], 400); } foreach ($data as $k => $v) { if ($v === '' || $v === null) { unset($data[$k]); } } // INSERT / UPDATE if (empty($id)) { $status = $posModel->insert($data); } else { $status = $posModel->update($id, $data); } if ($status) { return $this->respond([ 'status' => true, 'code' => 200, 'message' => 'POS updated successfully', 'data' => $data ], 200); } return $this->respond([ 'status' => false, 'code' => 400, 'message' => 'Failed to update', 'data' => $data ], 400); } 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 || !$file->isValid()) { return null; } $allowedMime = [ 'image/jpg', 'image/jpeg', 'image/png', 'image/webp', 'application/pdf']; if (!in_array($file->getMimeType(), $allowedMime)) { throw new \RuntimeException('Invalid file format'); } $path = ROOTPATH . 'public/uploads/' . $uploadDir . '/'; if (!is_dir($path)) { mkdir($path, 0755, true); } $newName = $file->getRandomName(); $file->move($path, $newName); return $newName; } }