<?php
class Product_model extends CI_Model {
	

    public function GetAllProduct()
    {
       
        $query = $this->db->query("SELECT * FROM products");
        $result = $query->result();
        return $result;
    }
	 
	
    function GetProductById($id)
    {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->where('id',$id); 
        $query = $this->db->get();
        return $query->result();
    } 

    function AllProductCount()
    {   
        $query = $this->db->get('products');
        return $query->num_rows();  
    }

    function AllProduct($limit,$start,$col,$dir)
    {  
       
        $this->db->select('z.id
                ,z.product_code
                ,z.product_name
                ,z.isactive');
        $this->db->from('products z'); 
        $this->db->limit($limit,$start);
        $this->db->order_by($col,$dir);
        $query = $this->db->get(); 
      

        if($query->num_rows()>0)
        {
            return $query->result(); 
        }
        else
        {
            return null;
        }
    }

    function ProductSearch($limit,$start,$search,$col,$dir)
    {
        
        $sql="SELECT A.id, 
                     A.product_code, 
                     A.product_name, 
                     A.price
              FROM products A 
              WHERE A.product_code like '%$search%' OR A.product_name like '%$search%' 
             OR A.price like '%$search%' 
              order by $col $dir limit " . $start . ", " . $limit;
        $query = $this->db->query($sql);
        if($query->num_rows()>0)
        {
            return $query->result();  
        }
        else
        {
            return null;
        }
    }

    function ProductSearchCount($search)
    {
        $query = $this->db->like('id',$search)
                 ->or_like('product_code',$search)
                ->or_like('product_name',$search)
                ->get('products');

        if(!empty($query))
        {
            return $query->num_rows();
        }

        return null;
    } 

    public function InsertProduct($data)
    {
        $result = $this->db->insert('products', $data);
        return $result;
    }
  
    public function UpdateProduct($id, $data)
    {
        $this->db->where('id',$id);
        $result = $this->db->update('products', $data);
        return $result;
    }

    public function checkAvailability($code)
    {
        $result = 0;
      try 
      {
        $query = $this->db->query("SELECT * FROM products WHERE product_code='$code'");
        if ($query->num_rows() > 0)
            $result =1;
      }
      catch(Exception $e) 
      {
        echo 'Message: ' .$e->getMessage();
      }
      return $result;
    }
  


}