<?php
class GenericPage implements IPage {
	public static function getInstance() {
		return new GenericPage(new Rest(), MySqliWrapper::getInstance(), new TwigWrapper(), BusinessLogicProcessor::getInstance());
	}
	private $rest;
	private $mysqli;
	private $twig;
	private $businessLogicProcessor;
	private function __construct(Rest $rest, MySqliWrapper $mysqli, TwigWrapper $twig, BusinessLogicProcessor $businessLogicProcessor) {
		$this->rest = $rest;
		$this->mysqli = $mysqli;
		$this->twig = $twig;
		$this->businessLogicProcessor = $businessLogicProcessor;
	}
	public function process() {
		$id = $this->rest->getDefaulted('id', 1);
		
		$sql = sprintf("SELECT *
				FROM page_settings
				WHERE page_id = %s", $id);
		$pageSettings = $this->mysqli->get($sql)[0];
		if(!$pageSettings) {
			throw new PageDataNotValidException("Page data invalid");
		}
		
		$path = $pageSettings['template_path'];
		$filename = $pageSettings['template_filename'];
		
		$options = $this->businessLogicProcessor->processLoad($id);
		
		$options['error'] = isset($_SESSION['error']) ? $_SESSION['error'] : "";
		unset($_SESSION['error']);
		$options['session'] = $_SESSION;
		$options['id'] = $id;
		$options['image_domain'] = "//" . IMAGE_DOMAIN;
		$options['image_path'] = $options['image_domain'] . "/" . $path;
		
		return $this->twig->render($path . "/" . $filename, $options);
	}
}
class PageDataNotValidException extends Exception {
}