<?php
class DevtoolPages
{

	public static function getInstance()
	{
		return new DevtoolPages();
	}
	private $twig;
	private $mysqli;

	private function __construct()
	{
		$this->twig = new TwigWrapper();
		$this->mysqli = MySqliWrapper::getInstance();
	}

	public function process()
	{
		$command = isset($_GET['command']) ? $_GET['command'] : null;
		switch ($command)
		{
			
			case "save":
				$this->save();
			case "edit":
				return $this->edit();
			case "add":
				$this->add();
			case "delete":
				$this->delete();
			default:
				return $this->displayList();
		}
	}

	private function displayList()
	{
		$sql = "SELECT *
				FROM page_settings ORDER BY page_id ASC";
		$pageInfo = $this->mysqli->get($sql);
		$options = array("pages" => $pageInfo, "title" => "Pages");
		return $this->twig->render("devtool_pages.html", $options);
	}

	private function add()
	{
		$templatePath = $_POST['template_path'];
		$templateFilename = $_POST['template_filename'];
		
		$sql = sprintf("INSERT INTO page_settings
				(`template_path`, `template_filename`) VALUES
				('%s', '%s')", $templatePath, $templateFilename, $pageId);
		$pageInfo = $this->mysqli->set($sql, null);
		header("Location: /editor.php?a=pages");
	}

	private function delete()
	{
		$pageId = isset($_GET['id']) ? $_GET['id'] : 0;
		$sql = sprintf("DELETE
				FROM page_settings
				WHERE page_id = %s", $pageId);
		$pageInfo = $this->mysqli->delete($sql, null);
		header("Location: /editor.php?a=pages");
	}

	private function save()
	{
		$pageId = isset($_GET['id']) ? $_GET['id'] : 0;
		
		$templatePath = $_POST['template_path'];
		$templateFilename = $_POST['template_filename'];
		
		$sql = sprintf("UPDATE page_settings
				SET template_path='%s',
				template_filename='%s'
				WHERE page_id = %s", $templatePath, $templateFilename, $pageId);
		$pageInfo = $this->mysqli->set($sql, null);
		echo "saved";
	}

	private function edit()
	{
		$pageId = isset($_GET['id']) ? $_GET['id'] : 0;
		$sql = sprintf("SELECT *
				FROM page_settings
				WHERE page_id = %s", $pageId);
		$pageInfo = $this->mysqli->get($sql);
		$options = array("pageData" => $pageInfo[0], "title" => "Devtool Page Editor #" . $pageId);
		return $this->twig->render("devtool_pageedit.html", $options);
	}
}