<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  
class contacts_model extends CI_Model {
 
    function __construct() {
        parent::__construct();
        $this->load->database();
    }
 
    function find($where='', $limit='10', $offset='', $q='') {
        $this ->db->from('contacts');
        if(!empty($where)){
            $this->db->where($where);
        }
        if(!empty($q)){
            $fields = $this->db->list_fields('contacts');
            $keyword = array();
            foreach ($fields as $field)
            {
               $keyword[$field] = $q;
            }
            $this->db->or_like($keyword);
        }
        $order = 'id desc';
        $this->db->order_by($order);
      
        if(!empty($offset) && !empty($limit)){
            $this->db->limit($limit, $offset);
        }
        elseif(!empty($limit)){
            $this->db->limit($limit);
        }
        
        $query =  $this->db -> get();
        
        return $query;
    }
    
    public function add($data)
    {		
            $result = $this->db->insert('contacts', $data); 
            return $result;
    }
    
    public function edit($where, $data)
    {
            $this->db->where($where);

            $result = $this->db->update('contacts', $data); 

            return $result;
    }
    
    public function replace($where, $data)
    {
            $this->db->where($where);

            $result = $this->db->update('contacts', $data); 
            return $result;
    }
    
    public function delete($where)
    {		
            $this->db->where($where);
            $result = $this->db->delete('contacts'); 
            
            return $result;
    }
    
    public function getTotalRows($where='', $limit='10', $offset='', $q=''){
        $this ->db->from('contacts');
        if(!empty($where)){
            $this->db->where($where);
        }
        if(!empty($q)){
            $fields = $this->db->list_fields('contacts');
            $keyword = array();
            foreach ($fields as $field)
            {
               $keyword[$field] = $q;
            }
            $this->db->or_like($keyword);
        }
        $order = 'id asc';
        $this->db->order_by($order);
        
        $query =  $this->db -> get()->num_rows();
        
        return $query;
    }
    
    public function affectedRows(){
        return $this->db->affected_rows();
    }
    
    public function getErrorMessage(){
        return $this->db->_error_message();
    }
}