<?php

use Twig\TwigFunction;

const STATIC_PATH = '/static/build';

$root = str_replace('/public', '', $_SERVER['DOCUMENT_ROOT']);
$request = $_SERVER['REQUEST_URI'];
$templates = $root.'/templates';

$renderedFiles = [];

require_once $root.'/vendor/autoload.php';

// load templates
$loader = new \Twig\Loader\FilesystemLoader([$root, $templates]);
$twig = new \Twig\Environment($loader, array(
    'cache' => false,
    'debug' => true,
));
$twig->addExtension(new \Twig\Extension\DebugExtension());

// add twig extensions to render webpack encore script/style tags
$webpackScript = new TwigFunction('encore_entry_script_tags', 'renderWebpackScriptTags', ['is_safe' => ['html']]);;
$twig->addFunction($webpackScript);

$webpackStyle = new TwigFunction('encore_entry_link_tags', 'renderWebpackStyleTags', ['is_safe' => ['html']]);;
$twig->addFunction($webpackStyle);

$webpackStyle = new TwigFunction('encore_entry_styles_inline', 'renderWebpackStylesInlined', ['is_safe' => ['html']]);;
$twig->addFunction($webpackStyle);

// render the template
$template = trim($request, '/') ?: '01_index.html.twig';
echo $twig->render($template);

function renderWebpackScriptTags($entrypoint, $inline = false, $buildPath = STATIC_PATH) {
	global $renderedFiles;

	$result = null;
	$entrypoints = loadEntrypoints($buildPath);

	if(!$entrypoint || !$entrypoints) return $result;

	$scripts = null;
	try {
		$scripts = $entrypoints['entrypoints'][$entrypoint]['js'];
	}
	catch (Throwable $e) {}

	if (!$scripts) return $result;

	foreach($scripts as $script) {
		if(!in_array($script, $renderedFiles)) {
			$result .= '<script src="' . $script . '" defer preload></script>';
			$renderedFiles[] = $script;
		}
	}

	return $result;
}

function renderWebpackStyleTags($entrypoint, $buildPath = STATIC_PATH) {
	global $renderedFiles;

	$result = null;
	$entrypoints = loadEntrypoints($buildPath);

	if(!$entrypoint || !$entrypoints) return $result;

	$styles = null;
	try {
		$styles = $entrypoints['entrypoints'][$entrypoint]['css'];
	}
	catch (Throwable $e) {}

	if (!$styles) return $result;

	foreach($styles as $style) {
		if(!in_array($style, $renderedFiles)) {
			$result .= '<link rel="stylesheet" href="' . $style . '">';
			$renderedFiles[] = $style;
		}
	}

	return $result;
}

function renderWebpackStylesInlined($entrypoint, $buildPath = STATIC_PATH) {
	global $renderedFiles;

	$result = null;
	$entrypoints = loadEntrypoints($buildPath);

	if(!$entrypoint || !$entrypoints) return $result;

	$styles = null;
	try {
		$styles = $entrypoints['entrypoints'][$entrypoint]['css'];
	}
	catch (Throwable $e) {}

	if (!$styles) return $result;

	foreach($styles as $style) {
		if(in_array($style, $renderedFiles)) {
			continue;
		}

		$styleFilePath = $_SERVER['DOCUMENT_ROOT'] . $style;
		if(!file_exists($styleFilePath)) continue;

		$fileContent = file_get_contents($styleFilePath);

		$result .= '<style>' . PHP_EOL;
		$result .= $fileContent;
		$result .= PHP_EOL . '</style>';

		$renderedFiles[] = $style;

	}

	return $result;
}

function loadEntrypoints($buildPath) {
	$result = null;

	$entrypointsPath = $_SERVER['DOCUMENT_ROOT'] . $buildPath . '/entrypoints.json';
	if(!file_exists($entrypointsPath)) return $result;

	$content = file_get_contents($entrypointsPath);
	if ($content === false) return $result;

	$entrypoints = json_decode($content, true);

	return $entrypoints ?: $result;
}