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

class Mining_recap_model extends Base_Model
{

	function __construct()
	{

		parent::__construct();
		$this->set_table('mining_recap');
		$this->set_pk('mine_recapnum');
		$this->set_log(false);
	}

	function count()
	{
		$data = array();
		$this->db->join('vendor vnd','tbl.vendor_id=vnd.vendor_id','left');
        $this->db->join('trans_status sts','tbl.mine_recapstatus=sts.trans_status','left');

		$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.*');
		$this->db->select('vnd.vendor_name');
        $this->db->select('sts.status');
		$this->db->join('vendor vnd','tbl.vendor_id=vnd.vendor_id','left');
        $this->db->join('trans_status sts','tbl.mine_recapstatus=sts.trans_status','left');
		
		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 gen_transaction_number($prefix='')
	{
		$transnumber_length	= 16;
		
		$this->db->select('RIGHT(tbl.mine_recapnum,7) mine_recapnum',false);
		$this->db->order_by('tbl.mine_recapnum','DESC');
		$this->db->group_by('tbl.mine_recapnum');
		
		$prefix_length		= strlen($prefix);
		$autonumber_length	= $transnumber_length - $prefix_length;
		
		$this->db->where("LEFT(tbl.mine_recapnum,9) = '$prefix' AND CHAR_LENGTH(tbl.mine_recapnum) = $transnumber_length");
		
		$query = $this->db->get($this->schema.'.'.$this->table.' tbl','1','0');
		// echo $this->db->last_query();
		// exit;
		
		$no_last =  $query->row_array();
		$no_next = 1;
		if ($no_last)
		{
			$no_next = $no_last['mine_recapnum']+1;
		}

		$no = $prefix.sprintf('%0'.$autonumber_length.'s', $no_next);
	
		$query->free_result();
		
		return $no;
	} 

}
