<?php
declare (strict_types = 1);
namespace ProxyPay\Core;

abstract class Page
{
	protected $templatePath = '';
	protected $db;
	protected $title = '';
	protected $config = null;

	public function __construct(Db $db, string $path, Config $config)
	{
		$this->db = $db;
		$this->setTemplatePath($path);
		$this->config = $config;
	}

	abstract public function actionIndex();

	protected function render(string $name, array $data = [], $output = false): string
	{
		$name = str_replace(".", "", $name);
		extract($data, EXTR_SKIP);
		define('IN_TEMPLATE', true);
		$filePath = $this->templatePath . '/' . $name . ".php";
		if (!file_exists($filePath) && !is_readable($filePath)) {
			throw new \Exception("$filePath didnt exist");
		}
		ob_start();
		include $this->templatePath . '/' . $name . ".php";
		$result = ob_get_clean();
		if ($output) {
			echo $result;
			exit();
		}
		return $result;
	}

	protected function setTemplatePath(string $path)
	{
		if (!file_exists($path)) {
			throw new \Exception("$path didnt exist");
		}
		$this->templatePath = $path;
	}

	protected function addError(string $error)
	{
		if (!isset($_SESSION['errors'])) {
			$_SESSION['errors'] = [];
		}
		$_SESSION['errors'][] = $error;
	}

	protected function addNotice(string $notice)
	{
		if (!isset($_SESSION['notice'])) {
			$_SESSION['notice'] = [];
		}
		$_SESSION['notice'][] = $notice;
	}

	protected function setTitle(string $title)
	{
		$this->title = $title;
	}

	public function getTitle()
	{
		return $this->title;
	}

	protected function redirect($link)
	{
		header('Location: '.$link);
		exit();
	}
}
