<?php
require_once 'includes/data-access/class-dataaccess.php';

/**
 * Entity master class
 *
 * granst common operations on entity to DB
 * 
 * @author ba - Advantis Solutions
 * @version 1.0.1
 * @package Base
 */
class Entity {
	public $internal_name;
	public $id;
	private $configkey;
	
	/**
	 * construtor
	 *
	 * if id searches for the id in the supporting table with same name
	 * Config key used for other schema diferent from default
	 *
	 * @param unknown $name        	
	 * @param string $id        	
	 * @param string $configkey        	
	 */
	function Entity($name, $id = null, $configkey = null) {
		$this->internal_name = $name;
		$this->configkey = $configkey;
		if ($id) {
			$this->id = $id;
			$this->get ();
		}
	}
	
	/**
	 * get
	 */
	function get() {
		$da = new DataAccess ( $this->configkey );
		
		$r = $da->query_get ( array (
				'entity' => $this->internal_name,
				'filter' => "id=?",
				'values' => array($this->id)
		) );
		
		foreach ( $r [0] as $key => $value ) {
			
			$this->$key = $value;
		}
	}
	
	/**
	 * saves data on object to DB model
	 */
	function save() {
		if (Authorization::context_access_mode () == __ACCESS_READ) {
			
			return;
		}
		
		$da = new DataAccess ( $this->configkey );
		
		$da->update ( array (
				'entity' => $this->internal_name,
				'obj' => $this 
		) );
		
		// log
		
		LogManagement::log_entity ( $this, "update" );
		
		// ---
	}
	
	/**
	 * deletes id register on DB model
	 */
	function delete() {
		if (Authorization::context_access_mode () == __ACCESS_READ) {
			
			return;
		}
		
		$da = new DataAccess ( $this->configkey );
		
		$da->delete ( array (
				'entity' => $this->internal_name,
				'obj' => $this 
		) );
		
		// log
		
		LogManagement::log_entity ( $this, "delete" );
		
		// ---
	}
}

?>