<?php

namespace Models;

use \DB\Cortex;

abstract class DB_Resource extends Cortex {

	// persistence settings
	protected $table, $db, $fieldConf, $ttl, $fluid;

	protected $response;

	public function __construct($db = 'DB') {
		$f3 = \Base::instance();
		$this->table = 'mysa_' . $this->table;
		$this->db = $db;
		$this->ttl = 900;
		$this->fluid = false;
		parent::__construct();

	}

	protected function getFieldNames() {
		return (array_keys($this->fieldConf));
	}

	public function setRepresentation($presenter) {
		$this->response = $presenter;
	}

	/**
	 * @param $f3 \Base
	 * @param $param
	 */
	public function getSingle($f3, $param) {
		$f3->error(403);
	}

	/**
	 * @param $f3 \Base
	 * @param $param
	 */
	public function getList($f3, $param) {
		$f3->error(403);
	}

	/**
	 * @param $f3 \Base
	 * @param $params
	 * @param $nullUnSet bool True to set any unpassed field to null
	 * @param $fieldsToIgnoreOnClear array List of fields not to set to null if not POSTed
	 */
	public function post($f3, $params, $nullUnSet=true, $fieldsToIgnoreOnClear=array()) {

		$msg = \FlashMessage::instance();
		$this->reset();

		if (isset($params['id'])) {
			// update existing
			$this->load(array('_id = ?', $params['id']));
			if ($this->dry()) {
				$msg->addMessage("No record found with this ID.", 'danger');
			//	$f3->reroute('/admin/' . $params['module']);
				return false;
			}
		}

		// Map Post data (set functions will then get called)
		$data = $f3->get('POST');
		$fieldNames = $this->getFieldNames();
		$set = array();

		foreach ($data as $key => $val) {

			if (!in_array($key, $fieldNames)) continue;
			if (is_array($val)){
				$val = implode(',', $val);
			}
			$this->$key = $val;
			$set[] = $key;
		}

		// Set remaining unset fields to null
		if ($nullUnSet){
			$diff = array_diff($fieldNames, $set);
			foreach ($diff as $key){
				if (in_array($key, $fieldsToIgnoreOnClear)) continue;
				try {
					$this->$key = null;
				} catch (\Exception $e) {}
			}
		}

		// Set username
		if (in_array('user_id', $fieldNames)) $this->user_id=$f3->get('SESSION.user_id');


		$requiredError = false;
		foreach ($this->fieldConf as $name => $conf) {
			if (isset($conf['required']) && $conf['required'] == TRUE
					&& empty($this->{$name})
			) {
				\Utils::Logger('db_resource:post:Missing required param:'.$name, 'debug');
				$requiredError = true;
			}
		}
		if ($requiredError) {
			if ($requiredError)
				$msg->addMessage($f3->get('lang_please_fill_out_all_required_fields'));
			$f3->copy('POST', 'form');
			\Utils::Logger('db_resource:post:Please fill out all required fields', 'debug');
			return false;
		}

		$this['last_updated'] = time();

		$out = $this->save();
		if ($out) {
			// display the list again after saving
			$msg->addMessage($f3->get('lang_successfully_saved'), 'success');

			// clear all cached sql/code files
			\Utils::CleanCache();

			return true;
		} else {
			$msg->addMessage($f3->get('lang_there_was_a_problem_saving__please_check_and_try_again'), 'danger');
			\Utils::Logger('db_resource:post:Operation failed', 'debug');
			return false;
		}
	}

	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function delete($f3, $params) {
		$this->reset();
		$msg = \FlashMessage::instance();
		$result = '0';
		if (isset($params['id'])) {
			$this->load(array('_id = ?', $params['id']));
			if ($this->dry()) {
				//$msg->addMessage("No record found with this ID.", 'danger');
			} else {
				$this->erase();
				//$msg->addMessage("Record deleted.", 'success');
				$result = '1';
			}
		}
		return ($result);
	}

	public function updateProperty($filter, $key, $value) {
		$this->load($filter);
		if ($this->dry()) {
			return false;
		} else {
			while (!$this->dry()) {
				$this->set($key, $value);
				$this->save();
				$this->next();
			}
			return true;
		}
	}

	public function save() {
		//$this['last_updated'] = time();
		return parent::save();
	}
}