<?php

namespace Vn\Web;

use Vn\Lib\Locale;

/**
 * Base class for services that sends response as HTML format.
 */
class HtmlService extends Service
{
	function run ()
	{
		$eFlag =
			  E_ERROR
			| E_USER_ERROR;

		set_error_handler ([$this, 'errorHandler'], $eFlag);
		set_exception_handler ([$this, 'errorHandler']);

		$this->init ();
		$db = $this->db;

		if (!$this->isHttps ()
		&& $db->getValue ('SELECT https FROM config') && !_DEV_MODE)
		{
			header ("Location: https://{$this->getUri()}");
			exit (0);
		}

		$this->startSession ();

		// Getting the requested page

		if (!empty ($_REQUEST['method']) && isHyphen ($_REQUEST['method']))
			$page = $_REQUEST['method'];
		else
			$page = 'main';

		// Checking the browser version

		if (!isset ($_SESSION['skipBrowser']) && $page != 'update-browser')
		{
			$updateBrowser = FALSE;

			if (!isset ($_GET['skipBrowser'])
			&& ($browser = get_browser ($_SERVER['HTTP_USER_AGENT'])))
			{
				$browserVersion = (double) $browser->version;
				$minVersion = $db->getValue (
					'SELECT version FROM browser WHERE name = #', [$browser->browser]);
				$updateBrowser = $browserVersion > 0
					&& isset ($minVersion) && $browserVersion < $minVersion;
			}

			if ($updateBrowser)
			{
				header ('Location: ?method=update-browser');
				exit (0);
			}
			else
				$_SESSION['skipBrowser'] = TRUE;
		}

		// If enabled, requests the user to choose between two web versions

		if (!isset ($_SESSION['skipVersionMenu'])
		&& $db->getValue ('SELECT test_domain FROM config'))
		{
			$_SESSION['skipVersionMenu'] = TRUE;
			header ('Location: ?method=version-menu');
		}

		// Setting the version

		setcookie ('vnVersion', $this->getVersion ());

		// Loading the requested page

		$basePath =  "pages/$page";

		if (file_exists ($basePath))
		{
			Locale::addPath ($basePath);

			$phpFile = "./$basePath/$page.php";

			if (file_exists ($phpFile))
				require ($phpFile);

			$this->printHeader ();
			$dir = $basePath;
			include_once __DIR__.'/html.php';
			include ("./$basePath/ui.php");
		}
		else
			header ('Location: ./');
	}
	
	function printHeader ()
	{
		header ('Content-Type: text/html; charset=UTF-8');
		//header ("Content-Security-Policy: default-src *; img-src *;");
	}

	function errorHandler ($err)
	{
		error_log("{$err->getMessage()} {$err->getTraceAsString()}");
		$this->printHeader ();
		include (__DIR__.'/unavailable.html');
		exit (0);
		return FALSE;
	}
	
	function isMobile ()
	{
		$re = '/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i';
		return preg_match ($re, $_SERVER['HTTP_USER_AGENT']);
	}
}