= CONCAT(YEAR(NOW()) - IF(MONTH(NOW()) >= 1 AND MONTH(NOW()) <= 3, 1, 0), "-01-01")', 'created_on < CONCAT(YEAR(NOW()) + IF(MONTH(NOW()) >= 1 AND MONTH(NOW()) <= 3, 1, 0), "-01-01")' ]; if (!empty($session_role) && $session_role !== "sadmin") { $this->logger->info("Donor: Listing In admin role . BID = ".$session_bid); $where = ['isactive' => 1, 'business_id' => (int)$session_bid]; } else { $this->logger->info("Donor: Listing In Super-admin role ."); $where = ['isactive != ' => NULL]; } // $where = array_merge($where, $default_financial_year_condition); $CustomerModel = new CustomerModel(); $data['page_name'] = 'Contributor Details'; $data['customer'] = $CustomerModel->where($where)->orderBy('donor_id', 'DESC')->findAll(); // echo '
';
            // print_r($data); die();

            $this->render_page('customer_list', $data);
        } else {
            return redirect()->to('login');
        }
    }

    ## To Load Donor Form (Add/Update)
    public function new_Donor($id)
    {
        helper('session');
        $session_bid = get_business_id();
    
        if ($id === '0') {
            // Add Donor
            $data['page_name'] = 'Add Contributor Details';
            $data['customer'] = [];

        } else if ($id !== '0') {
            
            // Edit Donor
            $data['page_name'] = 'Edit Contributor Details';    
            $customerModel = new CustomerModel();
    
            // Retrieve customer details by customer ID
            $edit_user_details = $customerModel->where(['donor_id' => $id])->first();
            $data['customer'] = $edit_user_details;
        }
    
        $data['session_bid'] = $session_bid;
        $data['country_details'] = $this->get_country_details();
        $data['state_details'] = $this->get_state_details();
         
        // echo '
';
        // print_r($data); die;

        $this->render_page('customer_form', $data);
    }


    
    public function insert_ajaxdonor(){
        
        helper('session');
        $model = new CustomerModel();

        $session_uid = get_logged_user_id();
        $session_bid = get_business_id();

        $pan = ($this->request->getPost('pan_no') == '') ? $this->request->getPost('o_pan_no') : $this->request->getPost('pan_no');
          
        $existingDonor = $model->where('pan_no', $pan)->first();

        if ($existingDonor) {
            $results = ['status' => false, 'message' => 'The PAN number already exists.','donor_id' => ''];   
            return $this->response->setJSON(['data' => $results]);        
        }
        try {
            $data = [
                'first_name'     => $this->request->getPost('cfname'),
                'mobile_no'      => $this->request->getPost('mobile'),
                'email'          => $this->request->getPost('cmail'),
                'pan_no'         => $pan,
                'donor_type'     => $this->request->getPost('DonorType'),
                'org_name'       => $this->request->getPost('org_name') !== '' ||  $this->request->getPost('org_name') !== null  ? $this->request->getPost('org_name') : NULL,
                'org_reg_details'=> $this->request->getPost('org_reg_Details'),
                'business_id'    => $session_bid,
                'isactive'       => 1,
                'created_by'     => $session_uid
            ];

            if ($model->insert($data)) {
                $results = ['status' => true, 'message' => 'added successfully','donor_id' => $model->insertID()];
            }else {
                $results = ['status' => false, 'message' => 'could not be added','donor_id' => ''];   
            }
            
            $donor_where = ['business_id' => (int)get_business_id() , 'isactive' => 1, 'donor_type'=>$this->request->getPost('DonorType')];
            $results['donor'] = $model->getData('donor', $donor_where);
            return $this->response->setJSON(['data' => $results]); 
        } catch (DatabaseException $e) {
            $results = ['status' => false, 'message' => 'could not be added DB Error Occur','donor_id' => '','error'=>$e->getMessage()];   
            return $this->response->setJSON(['data' => $results]); 
        }       
    }
    public function insert_donor()
    {
        $requestData = $this->request->getPost();
        // print_r($requestData);die;
        $this->logger->info("Donor: Inserting/Updating Details");
        try {
            helper('session');
            $session_bid = get_business_id();
            $session_uid = get_logged_user_id();
            $session_role = get_user_role();
            $model = new CustomerModel();
            $dob = $this->request->getPost('dob');
            $pan = ($this->request->getPost('pan_no') == '') ? $this->request->getPost('o_pan_no') : $this->request->getPost('pan_no');
            $dob = (isset($dob) && $dob != "") ? $dob : NULL ;
            $data = [
                'first_name'    => $this->request->getPost('cfname'),
                'last_name'     => $this->request->getPost('csname'),
                'mobile_no'     => $this->request->getPost('mobile'),
                'email'         => $this->request->getPost('cmail'),
                'date_of_birth' => $dob,
                'pan_no'        => $pan,
                'adhar_no'      => $this->request->getPost('adhar_no'),
                'passport_no'   => $this->request->getPost('DonorType') == 'individual' && $this->request->getPost('passport_no') ? $this->request->getPost('passport_no') : null,
                'donor_type'    => $this->request->getPost('DonorType'),
                'org_name'      => $this->request->getPost('org_name') !== '' ||  $this->request->getPost('org_name') !== null  ? $this->request->getPost('org_name') : NULL,
                'org_reg_details'=> $this->request->getPost('org_reg_Details'),
                'address'       => $this->request->getPost('address'),
                'city'          => $this->request->getPost('city'),
                'state'         => $this->request->getPost('state') ? $this->request->getPost('state') : $this->request->getPost('state_text'),
                'postal_code'   => $this->request->getPost('zip'),
                'country'       => $this->request->getPost('country'),
                'business_id'   => $this->request->getPost('business_id'),
                
            ];
            
            // print_r($data); 
            // echo  $this->db->getLastQuery();die();
            $donor_id = $this->request->getPost('donor_id'); // Get the business ID for update
            if (empty($donor_id)) {

                // It's an insert operation
                $data['isactive'] = 1;
                $data['created_by'] = $session_uid;
                if ($model->insert($data)) {
                    session()->setFlashdata('success', 'Donor successfully created.');
                    $this->logger->info("Donor : has been added successfully. Inserted ID = " . $model->insertID());
                    $donor_id_for_addresses = $model->insertID();// for Donor ADDRESS Table
                } else {
                    session()->setFlashdata('error', 'Donor could not be added. Please try again..');
                    $this->logger->error("Donor: Err could not be added. Please try again.");
                    $donor_id_for_addresses = "";
                }
            } else {
                // It's an update operation
                if ($session_role !== 'volunteer') {
                    $isactive = $this->request->getPost('isactive');
                    $data['isactive'] = ($isactive == 'on') ? 1 : 0;
                }
                $data['updated_by'] = $session_uid;
                $data['isactive'] = 1;
                $donor_id_for_addresses = $donor_id;
               // for Customer ADDRESS Table
                if ($model->update($donor_id, $data)) {
                    session()->setFlashdata('success', 'Donor successfully updated');
                    $this->logger->info("Donor: has been updated successfully. Updated Donor ID = " . $donor_id_for_addresses);
                } else {
                    session()->setFlashdata('error', 'Donor updation failed. Please try again.');
                    $this->logger->error("Donor: Err Failed to update ID =" . $donor_id_for_addresses);
                }
            }
            
            
        } catch (\Exception $e) {
            $this->logger->error("Donor : Err Occur =" . $e->getMessage());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
        }

        if(isset($requestData['new_receipt']))
        {
            // return redirect()->route('new_receipt');
            return redirect()->back();
        }
        else
        {
            return redirect()->route('Contributor_list');
        }
    }



    ## For delete the customer details (Which means inactive the details)
    public function delete_donor($id)
    {
        try {
            helper('session');
            $session_uid = get_logged_user_id();
            $CustomerModel = new CustomerModel();
            $where = ['donor_id' => (int)$id, 'isactive =' => 1];

            // Check if the business ID exists
            $existingCustomer = $CustomerModel->where($where)->find($id);
            if ($existingCustomer) {
                $this->logger->Info("Donor: Going to Inactive ID = ".$id);
                $data = ['isactive' => 0 , 'updated_by' => $session_uid];
                // Delete the business record
                if ($CustomerModel->update($id, $data)) {
                    session()->setFlashdata('success', 'Donor successfully deleted.');
                    $this->logger->info("Donor: has been Inactived successfully. Inactived ID = " . $id);
                } else {
                    $this->logger->error("Donor: Not able to Inactive ID =" . $id);
                    throw new \Exception("Data Not able to Deleted");
                }
            }
        } catch (\Exception $e) {
            $this->logger->error("Customer: Err Occur = " . $e->getMessage());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
        }
        return redirect()->route('Contributor_list');
    }

    public function get_customer_address($id,$type){
        $model = new CustomerModel();
        $model->setTable('customer_addresses');
        $where = ['isactive' => 1, 'donor_id' => (int)$id,'address_type'=>(int)$type];
        $address_details = $model->where($where)->findAll();
        return $address_details;
    }

    public function get_country_details()
    {
        $model = new CustomerModel();
        $model->setTable('countries');
        $country_details = $model->orderBy('country_id', 'ASC')->findAll();
        return $country_details;
    }

    public function get_state_details()
    {
        $model = new CustomerModel();
        $model->setTable('states');
        $state_details = $model->orderBy('state_id', 'ASC')->findAll();
        return $state_details;
    }

    public function donor_group(){

        $session_bid = get_business_id();
        $data['page_name'] = 'Contributor Group Details';
        $model = new CustomerModel();
        $data['donor_group'] = $model->getGroupDetails($session_bid);
        $this->render_page('customer_group', $data);
    }


    public function view_donor_group($id){ 

        helper('session');
        $session_bid = get_business_id();
        
        $data['field'] = [
            ['value'=>'',               'fieldflag'=>1, 'text'=> 'Choose the Field', 'disable' => false],
            ['value'=>'C.donor_type',   'fieldflag'=>1, 'text'=> 'Donor Type',       'disable' => false],
            ['value'=>'C.city',         'fieldflag'=>1, 'text'=> 'City',             'disable' => false],
            ['value'=>'C.postal_code',  'fieldflag'=>1, 'text'=> 'Postal Code',      'disable' => false],
            ['value'=>'I.receipt_date', 'fieldflag'=>2, 'text'=> 'Receipt Date',     'disable' => false],
      ];

        $data['operator'] = [
            '' => 'Choose the operator',
            'equal' => 'Equal to (=)',
            'not equal' => 'Not Equal (!=)',
            'like' => 'Like (%)',
            'greater than' => 'Greater than (>)',
            'greater than or equal to' => 'Greater than or Equal to (>=)',
            'less than' => 'Less than (<)',
            'less than or equal to' => 'Less than or Equal to (<=)',
            'contain' => 'Contain (in)',
            'not contain' => 'Not Contain (not in)',
            'between' => 'Between',
            'is null' => 'Is NULL',
            'is not null' => 'Is Not NULL',
        ];
        $data['donor_group'] = [];

        if ($id === '0') {
            // Add Customer
            $data['page_name'] = 'Add Contributor Group';
        } else if ($id !== '0') {
            // Edit Customer
            $data['page_name'] = 'Edit Contributor Group';
    
            // Load your Customer Model
          $model = new CustomerModel();
          $model->setTable('donor_groups');
          $where = ['group_id'=>$id];
          $result = $model->where($where)->findAll();
          
          if (!empty($result)) {
            $data['donor_group']['groupname'] = $result[0]['group_name'];
            $data['donor_group']['column'] = $result[0]['column'] ? unserialize($result[0]['column']) : [];
            $data['donor_group']['operator'] = $result[0]['operator'] ? unserialize($result[0]['operator']) : [];
            $data['donor_group']['values'] = $result[0]['value'] ? unserialize($result[0]['value']) : [];
            $data['donor_group']['group_id'] =  $result[0]['group_id'];
            $data['donor_group']['isactive'] =  $result[0]['isactive'];
         } 
        }
        $this->render_page('customer_group_form', $data);
    }


    public function preview_donor_group($id){
        try {
        helper('session');
        $model = new CustomerModel();
        $model->setTable('donor_groups');
        $where = ['isactive' => 1,'group_id'=>$id];
        $result = $model->where($where)->findAll();
        $db = \Config\Database::connect();            
        $sql = (string)$result[0]['group_query'];

        if($sql){
            $query = $db->query($sql);
            $results = $query->getResultArray();
            if(empty($results)){
                throw new \Exception("Data Not Available");    
            }else{
                return $this->response->setJSON($results);
            }
        }else{
            return $this->response->setJSON([]);
        }
        
      } catch (\Exception $e) {
            $this->logger->error("Donor Group: Err Occur = ".$e->getMessage()." File = ". $e->getFile() . " Line = " . $e->getLine());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
      }
    }
    public function delete_donor_group($id){ 
        try {
            helper('session');
            $session_uid = get_logged_user_id();
            $model = new CustomerModel();
            $model->setTable('donor_groups');
            $where = ['isactive' => 1,'group_id'=>(int)$id];
            $result = $model->where($where)->findAll();
            if ($result) {
                $this->logger->Info("Donor Group: Going to Inactive ID = ".$id);
                $data = ['isactive' => 0 , 'updated_by' => $session_uid,'group_id'=>(int)$id];
                $statement = $model->saveGroupDetails($data);// just updating Inactive status only.
                if ($statement['success']) {
                    session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : "" );
                    $this->logger->info($statement['log']);    
                } else if ($statement['error']) { 
                    session()->setFlashdata('error', $statement['error']);
                    $this->logger->error($statement['log']);
                }else{
                    throw new \Exception("Donor Group: Err Occur on data the Donor Group Inactive");    
                }
            }
        } catch (\Exception $e) {
            $this->logger->error("Donor Group: Err Occur = ".$e->getMessage()." File = ". $e->getFile() . " Line = " . $e->getLine());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
        }
        return redirect()->route('donor_group');
        
    }
    public function insert_donor_group(){        
        try {
            $this->logger->info("Donor Group: Inserting/Updating Details");
            helper('session');
            $session_uid = get_logged_user_id();
            $request_data = $this->request->getPost();
            $string_flag = $request_data['string_flag'];
            // $this->logger->info("Customer Group: Request data = ".json_encode($request_data));
            
            $session_bid = get_business_id();
            $model = new CustomerModel();
            // Array ( [groupname] => nil [column] => Array ( [0] => city [1] => state ) [operator] => Array ( [0] => not contain [1] => not equal ) [values] => Array ( [0] => 2 [1] => 3 ) )
            $data = [
                'group_name'  => $request_data['groupname'],
                'column'      => serialize($request_data['column']),
                'operator'    => serialize($request_data['operator']),
                'value'       => serialize($request_data['values']),
            ];

            $data['business_id'] = $session_bid;

            // Initialize an empty array to store the conditions
            $conditions = array();

            // Loop through the elements and build the conditions
            for ($i = 0; $i < count($request_data['column']); $i++) {
                $column = $request_data['column'][$i];
                $operator = $request_data['operator'][$i];
                $value = $request_data['values'][$i];
                // Handle different operators and build corresponding conditions
                switch ($operator) {
                    case 'equal':
                        $conditionStrings[] = "LOWER($column) = LOWER('$value') ";
                        break;
                    case 'not equal':
                        $conditionStrings[] = "LOWER($column) <> LOWER('$value') ";
                        break;
                    case 'like':
                        $conditionStrings[] = "LOWER($column) LIKE '%$value%'";
                        break;
                    case 'contain':
                    case 'in':
                        $values = explode(',', $value);
                        $conditionStrings[] = "LOWER($column) IN ('" . implode("', '", $values) . "')";
                        break;
                    case 'not contain':
                    case 'not in':
                        $values = explode(',', $value);
                        $conditionStrings[] = "LOWER($column) NOT IN ('" . implode("', '", $values) . "')";
                        break;
                    case 'between':
                        $dates = explode(',', $value);
                        $conditionStrings[] = "$column BETWEEN '$dates[0]' AND '$dates[1]'";
                        break;
                    case 'greater than':
                        $conditionStrings[] = "$column > $value";
                        break;
                    case 'greater than or equal to':
                        $conditionStrings[] = "$column >= $value";
                        break;
                    case 'less than':
                        $conditionStrings[] = "$column < $value";
                        break;
                    case 'less than or equal to':
                        $conditionStrings[] = "$column <= $value";
                        break;
                    case 'is null':
                        $conditionStrings[] = "$column IS NULL";
                        break;
                    case 'is not null':
                        $conditionStrings[] = "$column IS NOT NULL";
                        break;
                    case '':
                        throw new \Exception("Data Not Found");
                }
            }

            // Join the conditions with 'AND'
            $whereCondition = implode(' AND ', $conditionStrings);
            // echo "*************** whereCondition =>>> ";
            // echo $whereCondition;
            // If a groupname is specified, include it in the condition
            // if ($conditionsArray['groupname'] !== 'nil') {
            //     $whereCondition = "($whereCondition) AND groupname = '{$conditionsArray['groupname']}'";
            // }

            // Now you can use $whereCondition in your SQL query
            $db = \Config\Database::connect();
            // $sql = "SELECT donor_id,CONCAT(first_name,'',last_name) as customer_name,email,mobile_no FROM donor WHERE ".$whereCondition;
            $sql = "SELECT C.city, C.state, I.receipt_date, C.donor_id, CONCAT(C.first_name, ' ', C.last_name) as customer_name, C.email, C.mobile_no, C.isactive, COUNT(I.receipt_id) as invoice_count_raised_by_customer FROM donor as C
            LEFT JOIN receipt I ON I.donor_id = C.donor_id and I.isactive = 1
            WHERE C.isactive = 1 AND " . $whereCondition . "
            GROUP BY C.donor_id";

            $this->logger->info("Customer Group: SQL = ".$sql);
             
            // echo "$sql"; die;

            // Execute the query
            $query = $db->query($sql);

            // Get the result
            $results = $query->getResult();
            $this->logger->info("Customer Group: ".json_encode($results));
            $group_id = $request_data['group_id']; // Get the ID for update
            $isactive = $group_id != "" ? $request_data['isactive'] : 'on';
            if($string_flag == "save"){
                $data['group_query'] = $sql;
                $data['group_id'] = $group_id;
                $data['isactive'] = (($isactive == 'on') ? 1 : 0);
                $data['created_by'] = $session_uid;
                $data['updated_by'] = $session_uid;
                $statement = $model->saveGroupDetails($data);
                if ($statement['success']) {
                    session()->setFlashdata('success', $statement['success']);
                    $this->logger->info($statement['log']);
                    
                } else if ($statement['error']) { 
                    session()->setFlashdata('error', $statement['error']);
                    $this->logger->error($statement['log']);
                }else{
                    throw new \Exception("Donor Group: Err Occur on data the Save");    
                }

            }else if($string_flag == "preview"){
                return $this->response->setJSON($results);
            }else{
                throw new \Exception("Data Not Found");
            }
        } catch (\Exception $e) {
            $this->logger->error("Donor Group: Err Occur = ".$e->getMessage()." File = ". $e->getFile() . " Line = " . $e->getLine());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
        }
        return redirect()->route('donor_group');
    }

    public function getReceiptDetails($donorId)
    {
        $CustomerModel = new CustomerModel();

        $receiptDetails = $CustomerModel->getReceiptDetailsByDonorId($donorId);

        return $this->response->setJSON($receiptDetails);
    }
   
    public function export_donor()
    {
        helper('session');

        $session_bid = get_business_id();   

        $CustomerModel = new CustomerModel();  
        
        $data = $CustomerModel->export_excel($session_bid);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('B3:P3');
        $sheet->getStyle('B3')->getAlignment()->setHorizontal('center');    
        $sheet->setTitle('Contributor details');

        $headers = [
            'B3' =>  'Contributor Details',
            'A5' =>  'Contributor Name',
            'B5' =>  'Contributor Type',
            'C5' =>  'Organization Name',
            'D5' =>  'Organization Reg Details',
            'E5' =>  'Contact Number',
            'F5' =>  'Email Address',
            'G5' =>  'PAN',
            'H5' =>  'Aadhaar Number',
            'I5' =>  'Passport Number',
            'J5' =>  'Address',
            'K5' =>  'Country',
            'L5' =>  'State',
            'M5' =>  'City',
            'N5' =>  'Postal Code',
            'O5' =>  'CreatedBy',
            'P5' =>  'UpdatedBy',
            'Q5' =>  'CreatedAt',
            'R5' =>  'UpdatedAt',
            'S5' =>  'IsActive'
        ];

        foreach ($headers as $cell => $value) {
            $sheet->setCellValue($cell, $value);
            $sheet->getStyle($cell)->getFont()->setSize($cell == 'B3' ? 14 : 12);
            $sheet->getStyle($cell)->getFont()->setBold(true);
        }

        if ($data) {
            $row = 6; 
            foreach ($data as $d) {
                $col = 'A'; // Start from column A
                foreach ($d as $value) {
                   

                    if (is_numeric($value)) {
                        $sheet->setCellValueExplicit($col . $row, $value, DataType::TYPE_STRING);
                        $sheet->getStyle($col . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER);   
                    } else {
                        $sheet->setCellValue($col . $row, $value);
                    }
                    $sheet->setCellValue($col . $row, $value);
                    $col++;
                }
                $row++;
            }
        }

        ob_clean();

        $writer = new Xlsx($spreadsheet);
        $filename = 'exportDonor.xlsx';

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'. $filename .'"');
        header('Cache-Control: max-age=0');
        header('Expires: 0');
        header('Pragma: public');

        $writer->save('php://output');
        exit;
    } 
    
    public function import_donor()
    {
        
        $ip_address = $_SERVER['REMOTE_ADDR'];
        helper('session');
        $session_uid = get_logged_user_id();
        $session_bid = get_business_id();

        $response = []; // Arr - response For Message FrontEnd
        $list = []; // Arr - Store on DB
        $path = ROOTPATH . 'public/import/donor/';
        $fileNewName = "";

        $file = $this->request->getFile('file');
        
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $fileName = $file->getName();
        if ($fileName !== "") {
            if ($file->isValid() && !$file->hasMoved()) {        
                $newName = $file->getRandomName();
                $file->move($path, $newName);    
                $fileNewName = $newName;
            }
        }
        if (!$fileNewName) {
            $response = ['error_message' => "Failed to upload file"];
            return $this->response->setJSON($response);
        }

        $arr_file = explode('.', $fileName);
        $extension = $arr_file[1];
        if ('csv' == $extension) {
                $reader = new ReaderCsv();
        } else if ('xlsx' == $extension) {
                $reader = new ReaderXlsx();
        } else {
            $response = ['error_message' => "Unsupported file type"];
            return $this->response->setJSON($response);
        }

        if (!$reader) {
            $response = ['error_message' => "Failed to initialize reader"];
            return $this->response->setJSON($response);
        }
    
        $spreadsheet    = $reader->load($path.$fileNewName);
        $sheet_data     = $spreadsheet->getActiveSheet()->toArray();     
        if (!empty($sheet_data)) {
            $final_notes = [];
            $list = [];   
                foreach ($sheet_data as $key => $val) {

                    if ($key != 0 && trim($val[0]) && trim($val[1])) { // key zero - header
                        // $flag = 0;
                        $is_duplicate = false;
                        $notes = [];
                        $invalid_fields = []; 
                        if($val[6] != ""){
                            if ($this->check_existing($val[6], 'donor', 'pan_no')) {
                                $is_duplicate = true;
                                $invalid_fields[] = "PAN number";
                            }
                        }
                        if($val[7] != ""){
                            if ($this->check_existing($val[7], 'donor', 'adhar_no')) {
                                $is_duplicate = true;
                                $invalid_fields[] = "Aadhar number";
                            }
                        }
                        if($val[8] != ""){
                            if ($this->check_existing($val[8], 'donor', 'passport_no')) {
                                $is_duplicate = true;
                                $invalid_fields[] = "passport number";
                            }  
                        }
                        if ($is_duplicate) {
                            $notes[] = $val[0] . " is invalid because " . implode(" and ", $invalid_fields) . " (already exists)";
                    }
                  

                    if ($is_duplicate) {
                        $final_notes = array_merge($final_notes, $notes);
                    } else {
                            $list[] = [
                                'business_id' => $session_bid,
                                'first_name' => $val[0],
                                'donor_type' => strtolower($val[1]),
                                'org_name' => $val[2] ? $val[2] : null,
                                'org_reg_details' => $val[3] ? $val[3] : null,
                                'mobile_no' => $val[4] ? $val[4] : null,
                                'email' => $val[5],
                                'pan_no' => $val[6],
                                'adhar_no' => $val[7] ? $val[7] : null,
                                'passport_no' => $val[8] ? $val[8] : null,
                                'address' => $val[9] ? $val[9] : null,
                                'country' => $val[10] ? $val[10] : null,
                                'state' => $val[11] ? $val[11] : null,
                                'city' => $val[12] ? $val[12] : null,
                                'postal_code' => $val[13] ? $val[13] : null,
                                'created_by' => $session_uid,
                                'XL_file_name' => $fileNewName,
                                'ip_address' => $ip_address
                            ];
                        }
                    }
                }
        
                
                if (count($list) > 0) {
                    $CustomerModel = new CustomerModel();
                    $result = $CustomerModel->bulkInsert($list);
                    $response = $result ? [
                        'success_message' => count($list) . " Contributors imported successfully.".(count($final_notes) > 0 ? count($final_notes) . "  duplicate entries found.  
" : ""), ] : ['error_message' => "Something went wrong. Please try again."]; $response['message_in_details'] = implode("
", $final_notes); } else { $response = [ 'error_message' => "No new record is found.", 'message_in_details' => implode("
", $final_notes), ]; } } else { $response = ['error_message' => "There is no record to import", 'message_in_details' => '']; } return $this->response->setJSON($response); } public function check_existing($value, $table, $field) { $model = new CustomerModel(); $model->setTable($table); $where = [$field => $value]; $check_existing = $model->where($where)->findAll(); $statement_string = ucfirst(str_replace('_', ' ', $field)); $notes = ''; if (!empty($check_existing)) { $notes = $statement_string . " already exists"; } return $notes; } }