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

#[AllowDynamicProperties]
class Basetable {
	public function __construct ()
	{
	}
}

#[AllowDynamicProperties]
class Base_table {

	public $CI;

	public $db;

	public $tbl;

	public $tbl_key;

	public $cur_time;

	public $cId;

	public $bId;

	public $userId;

	public $isFranchise = false;

	public $isBranch = false;

	public $stkItemTypes = array('G','R','S','T');

	public function __construct ($params)
	{
		$this->CI =& get_instance();

		$this->db = $this->CI->db;
		
		if (!empty($params['tbl_key']))
		{
			$this->tbl_key = $params['tbl_key'];
		}
		$this->tbl = $params['tbl'];

		$this->cur_time = gmdate('Y-m-d H:i:s');
		$this->cId 	= get_company("id");
		$this->userId = get_user_data('id');
		$this->bId 	= get_user_data("defaultbId");

		$this->isFranchise = get_company("isFranchise");
		$this->isBranch 	= get_company("isBranch");
	}

	public function save($data, $params= array())
	{
		if (!canSave())
		{
			return false;
		}

		$this->CI->load->database();

		if ($data)
		{
			unset($data['crdByUserId']);
			unset($data['crdDate']);
			// table store access direct
			if (!empty($data["tbl_key"]) && !empty($data["tbl"]))
			{
				$this->tbl_key = $data["tbl_key"];
				$this->tbl = $data["tbl"];
			}
			else
			{
				$this->formatdata($data);
			}
			// set created | last updated details
			if (!empty($data[$this->tbl_key]))
			{
				$data['updDate'] = $this->cur_time;
			}
			else
			{
				$data['crdByUserId'] = $this->userId ? $this->userId : 0;
				$data['crdDate'] = $this->cur_time;
			}

			

			// Get value of primary id
			$id = (int)((!empty($data[$this->tbl_key]))?$data[$this->tbl_key]:0);

			if (!$this->check($data))
			{
				return false;
			}
			
			$data = $this->strip_fields($data);
			// insert
			if (!$id)
			{
				$this->CI->db->insert($this->tbl, $data);
				return $this->CI->db->insert_id();
			}
			// update
			else
			{
				$where[$this->tbl_key] = $id;
				
				if (!empty($data['cId'])) {
					$where['cId']	= $data['cId'];
				}

				if (isset($params['where']) && $params['where'])
				{
					$where = array_merge($where, $params['where']);	
				}

				$this->CI->db->where($where);

				if (isset($params['where_str']) && $params['where_str'])
				{
					$this->CI->db->where($params['where_str']);
				}

				$values = $data;
				unset($values[$this->tbl_key]);
				if (!empty($values['cId'])) {
					unset($values['cId']);
				}
				// updateon tables
				if (in_array($this->tbl,array('items','account','contacts','category')))
				{
					$this->CI->db->set('updatedOn','CURRENT_TIMESTAMP',false);
				}
				$this->CI->db->update($this->tbl, $values);
				unset($values);

//				return $this->CI->db->affected_rows()?$id:false;
				return $id;
			}
		}
	}

	public function strip_fields($data, $fields=array())
	{
		if (empty($fields)) {
			// get fields of from table
			$fields = $this->list_fields($this->tbl);
		}

		if (in_array('cId',$fields)) {
			$data['cId']	= $this->cId;
		}

		// check posted data is in fields
		foreach ($data as $field => $value)
		{
			if (@!in_array($field, $fields) || is_null($data[$field]))
			{
				unset($data[$field]);
			}
		}

		return $data;
	}

	public function check($data)
	{
		return true;
	}

	public function formatdata (&$data)
	{
		return true;
	}

	public function list_fields() {
		return $this->CI->db->list_fields($this->tbl);
	}

	public function check_duplicate($data, $where)
	{
		$where[$this->tbl_key.' != '] = $data[$this->tbl_key];		
		$this->CI->db->select('count(*) as duplicate_count');
		$this->CI->db->from($this->tbl);
		$this->CI->db->where($where);

		$query = $this->CI->db->get();
		$result = $query->row();

		return $result->duplicate_count;
	}

	public function get_list($select='*', $where=null)
	{
		return $this->_get_data($select, $where, false);
	}

	public function get_item($select='*', $where=null)
	{
		return $this->_get_data($select, $where, true);
	}

	private function _get_data($select='*', $where=null, $isSingle=false)
	{
		$this->CI->db->select($select);
		$this->CI->db->from($this->tbl);

		if (!empty($where) && is_array($where))
		{
			$this->CI->db->where($where);
		}

		$query = $this->CI->db->get();

		if ($isSingle)
		{
			return $query->row_array();
		}

		return $query->result_array();
	}

	public function delete_item($where)
	{
		if (!canSave())
		// if (getExpireDue() < -2)
		{
			return false;
		}

		if (is_array($where))
		{
			$this->CI->db->where($where);
			$this->CI->db->delete($this->tbl);
		}
	}
}

