<?php

class Base_Edit {

	protected $base_object;
	protected $db;
	protected $error;
	protected $id;

	public function __construct($base_object, $id = false) {
		$this->base_object = $base_object;
		$this->db = $base_object->db;
		$this->error = false;
		$this->id = $id;
	} // end __construct

	public function set_id($id) {
		$this->id = $id;
	} // end set_id

	public function get_id() {
		return $this->id;
	} // end get_id

	public function get_error() {
		return $this->error();
	} // end get_error

	protected function select_one($table) {
		if ($this->id) {
			$sql  = 'SELECT * FROM '.$table;
			$sql .= ' WHERE '.$this->get_id_name($table);
			$sql .= '='.$this->db->real_escape_string($this->id);

			$result = $this->db->query($sql);

			if ($result->num_rows > 0) {
				return $this->enrich($result->fetch_object());
			}
		}

		return false;
	} // end select_one

	protected function delete_one($table) {
		$sql  = 'DELETE FROM '.$table;
		$sql .= ' WHERE '.$this->get_id_name($table);
		$sql .= '='.$this->db->real_escape_string($this->id);

		return $this->db->query($sql);
	} // end delete_one

	private function set_string($data) {
		$sql = ' SET';

		$first = true;
		foreach ($data as $key => $value) {
			if ($first) {
				$first = false;
			} else {
				$sql .= ',';
			}

			$sql .= ' '.$this->db->real_escape_string($key);
			$sql .= "='".$this->db->real_escape_string($value)."'";
		}

		return $sql;
	} // end set_string

	private function save_data($sql) {
		$result = $this->db->query($sql);

		if ($result) {
			return $this->db->insert_id;
		}

		return false;
	} // end save_data

	protected function create_one($table, $data) {
		$sql = 'INSERT INTO '.$table;
		$sql .= $this->set_string($data);

		return $this->save_data($sql);
	} // end create_one

	protected function update_one($table, $data) {
		$sql = 'UPDATE '.$table;
		$sql .= $this->set_string($data);

		$sql .= ' WHERE '.$this->get_id_name($table);
		$sql .= '='.$this->db->real_escape_string($this->id);

		$this->save_data($sql);

		return $this->id;
	} // end update_one

	private function get_id_name($table) {
		return substr($table, 0, -1).'_id';
	} // end get_id_name

	protected function enrich($object) {
		return $object;
	} // end enrich
}