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

class Misel_purch_order_model extends Base_Model
{

	function __construct()
	{

		parent::__construct();
		$this->set_database('sealmis');
		$this->set_table('tblpur_orders');
		$this->set_pk('id');
		$this->set_log(false);
	}

	function count()
	{
		$data = array();
		
		$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 gen_transaction_number($prefix='')
	{
		$transnumber_length	= 16;
		
		$this->db->select('RIGHT(tbl.pur_order_number,7) pur_order_number',false);
		$this->db->order_by('tbl.pur_order_number','DESC');
		$this->db->group_by('tbl.pur_order_number');
		
		$prefix_length		= strlen($prefix);
		$autonumber_length	= $transnumber_length - $prefix_length;
		
		$this->db->where("LEFT(tbl.pur_order_number,9) = '$prefix' AND CHAR_LENGTH(tbl.pur_order_number) = $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['pur_order_number']+1;
		}

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

	// public function gen_recnum($prefix)
	// {
	// 	$this->db->select('IFNULL( MAX( id ), 0 ) + 1 last_recnum',false);
	// 	$this->db->where(array('vehicle_id'=>$prefix));
	// 	$query = $this->db->get($this->schema.'.'.$this->table.' tbl');
	// 	$query_row = $query->row_array();
	// 	return $query_row['last_recnum'];
	// }
}
