<?php

namespace Vn\Hedera;

require_once ('vn/hedera/init.php');
require_once ('vn/db/db.php');
require_once ('vn/web/auth.php');
require_once ('vn/web/locale.php');
require_once ('vn/hedera/util.php');

use Vn\Db\Conn;
use Vn\Web\Locale;
use Vn\Web\Auth;

class Web
{
	static $sysConn;
	static $conn;
	static $newAccess = FALSE;

	static function init ()
	{
		global $conf;
	
		session_start ();

		self::$sysConn = new Conn ();
		$sysConn = self::$sysConn;
		$sysConn->open (
			'p:'. $conf['db']['host']
			,$conf['db']['user']
			,base64_decode ($conf['db']['pass'])
			,$conf['db']['schema']
		);

		self::$conn = new Conn ();
		
		// Setting the locale

		Locale::init ();
		
		// Loading global configuration

		if (!$sysConn->isOpen ())
			return;
			
		$dbConf = $sysConn->getRow (
			'SELECT default_lang, https, cookie_life, guest_user, guest_pass FROM config'
		);
		$conf = array_merge ($conf, $dbConf);

		// Setting the version

		$_SESSION['version'] = $sysConn->getValue ('SELECT version FROM version LIMIT 1');

		// Registering the visit

		if (!isset ($_COOKIE['PHPSESSID'])
		|| isset ($_SESSION['access'])
		|| isset ($_SESSION['skipVisit']))
			return;

		$agent = $_SERVER['HTTP_USER_AGENT'];
		$browser = get_browser ($agent, TRUE);
		
		if (isset ($browser['crawler']) && $browser['crawler'])
		{
			$_SESSION['skipVisit'] = TRUE;
			return;
		}

		if (isset ($_SERVER['REMOTE_ADDR']))
			$ip = ip2long ($_SERVER['REMOTE_ADDR']);

		$row = $sysConn->getRow (
			'CALL visit_register (#, #, #, #, #, #, #, #, #)',
			[
				ifNull ($_COOKIE, 'hedera_visit')
				,ifNull ($browser, 'platform')
				,ifNull ($browser, 'browser') 
				,ifNull ($browser, 'version')
				,ifNull ($browser, 'javascript')
				,ifNull ($browser, 'cookies')
				,isset ($agent) ? $agent : NULL
				,isset ($ip) && $ip ? $ip : NULL
				,ifNull ($_SERVER, 'HTTP_REFERER')
			]
		);

		if (isset ($row['access']))
		{
			setcookie ('hedera_visit', $row['visit'], time () + 31536000); // 1 Year
			$_SESSION['access'] = $row['access'];
			self::$newAccess = TRUE;
		}
		else
			$_SESSION['skipVisit'] = TRUE;
	}

	static function deinit ()
	{
		self::$sysConn->query (
			'UPDATE user_session SET connection_id = NULL WHERE ssid = #'
			,[session_id ()]
		);
	}

	static function login ()
	{
		global $conf;
	
		$wasLoged = Auth::isLogged ();
		$useCookies = TRUE;
		$success = TRUE;
		
		if (isset ($_GET['guest']))
		{
			$row = self::$sysConn->getRow (
				'SELECT guest_user, guest_pass FROM config');

			if ($row)
			{
				$_POST['user'] = $row['guest_user'];
				$_POST['password'] = base64_decode ($row['guest_pass']);
				$useCookies = FALSE;
			}
		}

		try {
			Auth::getCredentials ();
			self::$conn->open (
				 $conf['db']['host']
				,Auth::getUser ()
				,Auth::getPassword ()
				,$conf['db']['schema']
			);
			Auth::login ($useCookies);

			$row = self::$conn->getRow (
				'SELECT account.user_get_id () user, CONNECTION_ID() conn');
			
			if (!$wasLoged)
				unset ($_SESSION['visitUser']);
		}
		catch (\Exception $e)
		{
			$row = NULL;
			$success = FALSE;
		}

		// Registering the user access

		if (isset ($_SESSION['access']))
		{
			$_SESSION['visitUser'] = self::$sysConn->getValue (
				'CALL visit_user (#, #, #, #, #)',
				[
					$_SESSION['access']
					,ifNull ($_SESSION, 'visitUser')
					,ifNull ($row, 'user')
					,ifNull ($row, 'conn')
					,session_id ()
				]
			);
		
			if (!isset ($_SESSION['visitUnknown']) && !$success)
				$_SESSION['visitUnknown'] = $_SESSION['visitUser'];
		}

		return $success;
	}
	
	static function logout ()
	{
		self::$sysConn->query (
			'DELETE FROM user_session WHERE ssid = #'
			,[session_id ()]
		);

		$_SESSION['visitUser'] = ifNull ($_SESSION, 'visitUnknown');
		
		self::$conn->close ();
		Auth::logout ();
	}
}

?>