<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  
class training_category_model extends CI_Model {
 
    function __construct() {
        parent::__construct();
        $this->load->database();
    }
 
    function find($where='', $limit='10', $offset='', $q='') {
         $this->db->select('a.*,b.title as parent');
        $this->db->from('training_category a');
        $this->db->join('training_category b', 'a.parent_id = b.id', 'left');
        if(!empty($where)){
            $this->db->where($where);
        }
        if(!empty($q)){
            $fields = $this->db->list_fields('training_category');
            $keyword = array();
            foreach ($fields as $field)
            {
               $keyword['a.'.$field] = $q;
            }
            $keyword['b.title'] = $q;
            $this->db->or_like($keyword);
        }
        $order = 'a.id asc';
        $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();
        
//        print_r($query->result());die;
        return $query;
    }
    
    public function add($data)
    {		
            $result = $this->db->insert('training_category', $data); 
            return $result;
    }
    
    public function edit($where, $data)
    {
            $this->db->where($where);

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

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

            $result = $this->db->update('training_category', $data); 
            return $result;
    }
    
    public function delete($where)
    {		
            $this->db->where($where);
            $result = $this->db->delete('training_category'); 
            
            return $result;
    }
    
    public function getTotalRows($where='', $limit='10', $offset='', $q=''){
        $this->db->from('training_category');
        $this->db->join('training_category', 'training_category.parent_id = training_category.id', 'left');
        if(!empty($where)){
            $this->db->where($where);
        }
        if(!empty($q)){
            $fields = $this->db->list_fields('training_category');
            $keyword = array();
            foreach ($fields as $field)
            {
               $keyword[$field] = $q;
            }
            $this->db->or_like($keyword);
        }
        $order = 'training_category.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();
    }
}