<?php 
	if (SABLE_PWA)
	{
		$proto = strtolower(trim($_SERVER['REQUEST_SCHEME']));
		if ($proto !== 'https') 
		{
			$redurl = $_SERVER['REQUEST_URI'];
			$redurl = substr($redurl, 1);
			header('Location: '.SABLE_URL_ROOT.$redurl);
			exit();
		}
	}
	if (file_exists(SABLE_THEME_WORKING_PATH.'pre_header.php')) include(SABLE_THEME_WORKING_PATH.'pre_header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
//define Javascript variables at that beginning of the document for AJAX calls:
var baseRootURL		= "<?php echo(SABLE_URL_ROOT); ?>";
var themeRootURL	= "<?php echo(SABLE_THEME_ROOT); ?>";
var themePath		= "<?php echo('themes/'.SABLE_THEME_NAME.'/'); ?>";
var DEBUGGING		= <?php if (SABLE_SITE_DEBUGGING)	echo("true"); else echo("false"); ?>;
var DEMO			= <?php if (SABLE_DEMO_SYSTEM)		echo("true"); else echo("false"); ?>;
<?php if (SABLE_PUSH_ENABLED && isset($_SESSION['user']['user_code'])){ ?>
var sablePushID 	= "<?php echo(base64_encode($_SESSION['user']['user_code'])); ?>";
<?php } ?>
</script>
<?php
	SableSystem::extractTagLines(SABLE_HEAD_TAGS);
	
	//layout the header tags here:
	SableSystem::extractTagLines(SABLE_CSS); //Sable System CSS Files
	SableSystem::extractTagLines(SABLE_THEME_STYLES);
	SableSystem::extractTagLines(SABLE_THEME_ICONS);
	
	//SableSystem::extractTagLines(SABLE_META_KEYWORDS);
	echo('<base href="'.SABLE_URL_ROOT.'" />'.PHP_EOL);
	echo('<meta name="author" content="Jona Solutions. HTML templates by third parties and Jona Solutions." />'.PHP_EOL);
	echo('<meta name="generator" content="Sable Web Application by Jona Solutions, http://www.jona.co.za" />'.PHP_EOL);

	
	if ((!SableSystem::loggedIn()) && (isset($_SESSION['og_tags'])))
	{
		//property="og:image:secure_url"
		$og = '';
		$ogImage 		= SableSystem::setOgImage($_SESSION['og_tags']['image']);
		
		SableSystem::convertURLPathToWorkPath($ogImage);	
		ltrim($ogImage, "/");
		
		$ogImageSizes 	= getimagesize(SABLE_WORKING_PATH.$ogImage);
		$og .= '<meta property="og:title"			content="'.$_SESSION['og_tags']['title'].'" />
				<meta property="og:type" 			content="website" />
				<meta property="og:url" 			content="'.$_SESSION['og_tags']['url'].'" />
				<meta property="og:image" 			content="'.SABLE_URL_ROOT.$ogImage.'"/>
				<meta property="og:image:width" 	content="'.$ogImageSizes[0].'" />
				<meta property="og:image:height" 	content="'.$ogImageSizes[1].'" />
				<meta property="og:image:alt" 		content="'.$_SESSION['og_tags']['title'].'" />
				<meta property="og:description"		content="'.$_SESSION['og_tags']['desc'].'" />';
		if (FACEBOOK_APP_ID) $og .= '<meta property="fb:app_id"		content="'.FACEBOOK_APP_ID.'" />';
		$og .= '<link rel="canonical" href="'.SABLE_URL_ROOT.'?'.$_SERVER['QUERY_STRING'].'" />'.PHP_EOL;
		echo($og);
	}
	else 
	{
		SableSystem::extractTagLines(SABLE_OG_TAGS);
	}
	//use the header.php to include any custom theme headers that belong inside the <head> tag
	file_exists(SABLE_THEME_WORKING_PATH.'header.php')?include_once(SABLE_THEME_WORKING_PATH.'header.php'):'';
	
	//although included, the below included files will only produce output if so configured. The the file content and
	//the theme's config.php file for verification:
	include_once(SABLE_INCLUDES_PATH.'google_analytics.php');
	include_once(SABLE_INCLUDES_PATH.'facebook_pixel.php');
	include_once(SABLE_INCLUDES_PATH.'sharethisjs.php');	
?>
<title>
	<?php 
		if (SABLE_DEMO_SYSTEM)
		{
			echo(SABLE_SITE_TITLE); 
		}
		else
		{
			if (SableSystem::loggedIn())
				echo(SABLE_SITE_TITLE);
			else
				echo(SableGeneralFunctions::getPageTitle()); 
		}
	?>
</title>
<?php
	SableSystem::extractTagLines(SABLE_JS); //Sable System JS Files
	
	function generateIndexedDB($idb)
	{
		global $sableDB;
		$EOL = '';//PHP_EOL;
		$js = '<script>';
		$js .= 'function getSableData(){'.$EOL;
		$js .= 'var userData = {}, userRows = [];'.$EOL;
		$js .= $EOL;
		
		foreach($idb as $rec)
		{
			if (isset($rec['selects']))
				$sels	= implode(',', $rec['selects']);
			else
				$sels	= implode(',', $rec['fields']);
				
			$fields		= implode(',', $rec['fields']);
				
			$sql = 'select '.$rec['table'].'.'.$rec['id_field'].', '.$sels.' from '.$rec['table'];
			//$sql = 'select '.$rec['id_field'].', '.$sels.' from '.$rec['table'];
			if (isset($rec['join']))	$sql .= ' '.$rec['join'];
			if (isset($rec['where']))	$sql .= ' '.$rec['where'];
			if (isset($rec['group']))	$sql .= ' '.$rec['group'];
			//SableDebug::debug($sql);
			$rows = $sableDB->getRows($sql);
			//SableDebug::debug($rows);
			foreach($rows as $row)
			{
				$js .= 'userData = {};'.$EOL;
				$js .= 'userData.table = "'.$rec['table'].'";'.$EOL;
				foreach($rec['fields'] as $fld)
				{
					$js .= 'userData.'.$fld.' = "'.$row[$fld].'";'.$EOL;
				}
				$js .= 'userData.sableID = "'.$rec['table'].'|'.$row[$rec['id_field']].'";'.$EOL;
				$js .= 'userRows.push(userData);'.$EOL;
				$js .= $EOL;
			}

		}
		$js .= 'return userRows;'.$EOL;
		$js .= '}'.$EOL;
		$js .= '</script>'.$EOL;
		echo($js);
	}

	if (SABLE_INDEXED_DB_ENABLED && !SableSystem::loggedIn()) 
	{
		/**
		build code for indexeddb herein the form of an array of struct.
		**/
		$idb				= [];
		
		//user
		$table				= [];
		$table['table']		= 'user';
		$table['id_field']	= 'user_code';
		$table['fields']	= ['user_email', 'user_password'];
		$table['where']		= 'where (user_active = 1) and (deleted = 0) and (company_id = 1) and (access_id = 4)';
		$idb[] = $table;
		
		$table				= [];
		$table['table']		= 'company';
		$table['id_field']	= 'company_id';
		$table['fields']	= ['company_name'];
		$table['where']		= 'where (deleted = 0)';
		$idb[] = $table;		
		
		generateIndexedDB($idb);
		echo('<script src="'.SABLE_URL_ROOT.'scripts/sable_db.js"></script>');
	}
	
	SableSystem::extractTagLines(SABLE_THEME_TOP_JS); //additional JS files required for the theme (listed at the top of the page)
	
	if (SABLE_PWA)
	{
?>
<script>
	if ('serviceWorker' in navigator)
	{
		navigator.serviceWorker.register('/sw.js').then
		(
			function(swRegistration)
			{
				return swRegistration.sync.getTags();
			}
		).then
		(
			function(tags)
			{
				//if (tags.includes('sableBackgroundSync')) console.log("There's already a background sync pending");
			}
		).catch
		(
			function(err)
			{
				console.log('It broke (probably sync not supported or flag not enabled)');
				console.log(err.message);
			}
		);
		
		new Promise
		(
			function(resolve, reject)
			{
				Notification.requestPermission
				(
					function(result)
					{
						if (result !== 'granted') 
						{
							//alert('Notifications not allowed.');
							return reject(Error("Denied notification permission"));
						}
						//else alert('Notifications are allowed.');
						resolve();
					}
				)
			}
		).then
		(
			function()
			{
				return navigator.serviceWorker.ready;
			}
		).then
		(
			function(swRegistration)
			{
				//return swRegistration.sync.register('sableBackgroundSync');
			}
		).then
		(
			function()
			{
				//console.log('Sync registered');
			}
		).catch
		(
			function(err)
			{
				//console.error('Sync registration failed: ', err.message);
			}
		);
	}
</script>
<?php } //if (SABLE_PWA) ?>
</head>
<body <?php echo(SABLE_BODY_TAGS); ?>>
	<div id="ajaxDiv" style="width:100vw; height:100vh;">
    	<img src="<?php SableSystem::printSableImgPath('loading_5.gif'); ?>" alt="Loading..." />       
    </div>
    <!-- Install button, hide by default -->
    <div id="installContainer" class="hide animated fadeInDown">
		<div class="row text-center">
			<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
				<img style="height:auto; width:48px;" src="<?php SableSystem::printSableImgPath('manifest_logo.png'); ?>" 
					alt="<?php echo(SABLE_SITE_TITLE); ?>" />
			</div>
		</div>
		<div class="row text-center">
			<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">Use <strong><?php echo(SABLE_SITE_TITLE); ?></strong> as an app?</div>
		</div>
		<div class="row text-center">
			<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
				<button id="installButton" type="button"><i class="fa fa-download"></i>&nbsp;Yes</button>
				&nbsp;&nbsp;
				<button id="closeButton" type="button"><i class="fa fa-ban"></i>&nbsp;No</button>
			</div>			
		</div>
    </div>	
<?php 
	if (file_exists(SABLE_THEME_WORKING_PATH.'content_top.php'))include(SABLE_THEME_WORKING_PATH.'content_top.php'); ?>
<!-- SABLE HEADER //-->