<?php
class AjaxSubmitPage implements IPage
{

	public static function getInstance()
	{
		return new AjaxSubmitPage(new Rest(), new Header(), BusinessLogicProcessor::getInstance(), MySqliWrapper::getInstance(), new TwigWrapper());
	}
	private $rest;
	private $header;
	private $businessLogicProcessor;
	private $mysqli;
	private $twig;

	private function __construct(Rest $rest, Header $header, BusinessLogicProcessor $businessLogicProcessor, MySqliWrapper $mysqli, TwigWrapper $twig)
	{
		$this->rest = $rest;
		$this->header = $header;
		$this->businessLogicProcessor = $businessLogicProcessor;
		$this->mysqli = $mysqli;
		$this->twig = $twig;
	}

	public function process()
	{
		try
		{
			$id = $this->rest->get('id');
		}
		catch (RestException $e)
		{
			return json_encode(array("error" => "Page ID not specified"));
		}
		
		$result = $this->businessLogicProcessor->processAjaxSubmit($id);
		
		if(isset($result['error']))
		{
			$_SESSION['error'] = $result;
		}
		$returnData = $result;
		$returnData['html'] = $this->buildPage($result['next']);
		return json_encode($returnData);
	}

	public function buildPage($id)
	{
		$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['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;
		
		$this->header->jsonContent();
		return $this->twig->render($path . "/" . $filename, $options);
	}
}
