<?php

include_once './core/metatag.class.php';

class admin_metatag_editor { 
	private $base_object;
	private $layout_object;
	private $metatag_object;
	
	function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->layout_object = $layout_object;
		$this->metatag_object = new Metatag();
	}
	
	public function run() {
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} else {
			$action = false;
		}
		
		if (isset($_GET['id'])) {
			$id = $_GET['id'];
		} else {
			$id = false;
		}
		
		if ($action == 'save') {
			$this->save();
		} elseif ($action == 'delete') {
			$this->delete($id);
		} else {
			return $this->default_action($id);
		}
	}
	
	private function default_action($id) {
		if ($id) {
			$data = $this->metatag_object->get_by_id($id);
			
			if ($data) {
				$this->layout_object->assign('form_data', $data);
			} else {
				$this->layout_object->assign('error_message', "Dieser meta tag existiert nicht oder ist nicht freigeschalten.");
			}
		}
		// implied else, no action taken when you create something new
		
		return $this->layout_object->fetch('admin_metatag_editor.tpl');
	}
	
	// only used in ajax, so i terminate whith exit
	private function save() {
		if (isset($_POST['form_field'])) {
			$data = $_POST['form_field'];
			
			$result = $this->metatag_object->save($data);
		
			var_dump($result);
		} else {
			$data = false;
		}
		
		
		//echo json_encode($return);
		exit();
	}
	
	// only used in ajax, so i terminate whith exit
	private function delete($id) {
		if (id) {
			// delete
			if ($this->metatag_object->delete($id)) {
				$return = array('status' => 'success');
			} else {
				$return = array('status' => 'error', 'message' => 'database error');
			}
		} else {
			// error
			$return = array('status' => 'error', 'message' => 'id error');
		}
		
		echo json_encode($return);
		exit();
	}
}