<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Stock_alocation_model extends Base_Model
{

	function __construct()
	{

		parent::__construct();
		$this->set_table('stock_alocation');
		$this->set_pk('stockroom_id','location_id');
		$this->set_log(false);
	}

	function count()
	{
		$data = array();

		$this->db->distinct();

		$this->db->where($this->where);
		$this->db->or_like($this->like);

		$query = $this->db->get($this->schema.'.'.$this->table.' tbl');
	
		return $query->num_rows();
	}

	function get_list()
	{
		$this->db->select('tbl.*');
		
		if($this->where)
		$this->db->where($this->where);
		if($this->like)
		$this->db->or_like($this->like);
		
		foreach ($this->order_by as $key => $value)
		{
			$this->db->order_by($key, $value);
		}

		if (!$this->limit AND !$this->offset)
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl');
		else
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl',$this->limit,$this->offset);
		
        if($query->num_rows()>0)
		{
			return $query;
        
		}else
		{
			$query->free_result();
            return $query;
        }
	}

    function get_list_sum_alocation_buyer()
	{
		$this->db->select('tbl.buyer_name');
		$this->db->select('sum(tbl.stock_in) as received',false);
		$this->db->select('sum(tbl.stock_out) as delivered',false);
		$this->db->select('sum(tbl.stock_total) as total',false);
		$this->db->group_by(array('tbl.buyer_name'));
		
		if($this->where)
		$this->db->where($this->where);
		if($this->like)
		$this->db->or_like($this->like);
		
		foreach ($this->order_by as $key => $value)
		{
			$this->db->order_by($key, $value);
		}

		if (!$this->limit AND !$this->offset)
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl');
		else
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl',$this->limit,$this->offset);
		
        if($query->num_rows()>0)
		{
			return $query;
        
		}else
		{
			$query->free_result();
            return $query;
        }
	}

    function get_list_sum_total_alocation_buyer()
	{
		$this->db->select('sum(tbl.stock_in) as total_received',false);
		$this->db->select('sum(tbl.stock_out) as total_delivered',false);
		$this->db->select('sum(tbl.stock_total) as grand_total',false);
		
		if($this->where)
		$this->db->where($this->where);
		if($this->like)
		$this->db->or_like($this->like);
		
		foreach ($this->order_by as $key => $value)
		{
			$this->db->order_by($key, $value);
		}

		if (!$this->limit AND !$this->offset)
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl');
		else
			$query = $this->db->get($this->schema.'.'.$this->table.' tbl',$this->limit,$this->offset);
		
        if($query->num_rows()>0)
		{
			return $query;
        
		}else
		{
			$query->free_result();
            return $query;
        }
	}


}
