<?php /*! anamo/market-dummy-deployment v1.0.0 | © 2006-present Anamo Inc. MIT License | bitbucket.org/anamo/market-dummy-deployment */

/**
 * Set error reporting.
 */
// ERROR REPORTING
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ERROR | E_PARSE);

set_error_handler(function($errno, $errstr, $errfile, $errline) {
	file_get_contents('https://api.telegram.org/bot178153406:AAEmBXf4gjvO577bp25eBXKhDCPnKyBJ0Iw/sendMessage?chat_id=178163713&text='.urlencode($errno.' MARKET DUMMY DEPLOYMENT '.$errfile.'@'.$errline.': "'.$errstr.'"'));
	http_response_code(500);
	echo (string)(include stream_resolve_include_path('build/error.php'))([]);
	return false;
}, E_ERROR | E_PARSE | E_USER_ERROR);

set_exception_handler(function(Throwable $ex) use(&$document) {
	trigger_error($ex->getFile().'@'.$ex->getLine().': '.$ex->getMessage(), E_USER_ERROR);
});

// MANIFEST
define('MANIFEST', (array)json_decode(file_get_contents(stream_resolve_include_path('webstore.json')), true));

// SETTINGS
$user_settings = (array)json_decode(file_get_contents(stream_resolve_include_path('config/settings.json')), true);
define('SETTINGS', array_merge((array)json_decode(file_get_contents(__DIR__.'/../../config/settings.'.$user_settings['preset'].'.defaults.json'), true), $user_settings));
unset($user_settings);

// PAGES
define('PAGES', (array)json_decode(file_get_contents(stream_resolve_include_path('config/pages.json')), true));

// LOCALE
locale_set_default(MANIFEST['default_locale']); // en-001@currency=EUR (BCP 47 locale)
setlocale(LC_ALL, locale_canonicalize(locale_get_default())); // en_001@currency=EUR (ICU locale)

// TIMEZONE
date_default_timezone_set(MANIFEST['default_timezone']?? 'UTC');

/**
 * Set various global vars inside $_SERVER scope.
 */
// REQUEST_PATH
$length = empty($_SERVER['QUERY_STRING'])? mb_strlen($_SERVER['REQUEST_URI']): -mb_strlen($_SERVER['QUERY_STRING']);
$_SERVER['REQUEST_PATH'] = rtrim(mb_substr($_SERVER['REQUEST_URI'], 0, $length), '?'); // /path/to/file/englesio /englesio / /path/to/dir
unset($length);

// APP_PATH_SUFFIX
$prefix_path = mb_substr($_SERVER['REQUEST_PATH'], 1); // path/to/file '' '' /path/to/dir
foreach((array)MANIFEST['locales'] as $possible_suffix => $locale) {
	$path_suffix = '/'.$possible_suffix;
	if($path_suffix === mb_substr($_SERVER['REQUEST_PATH'], -1 * mb_strlen($path_suffix))) {
		$_SERVER['APP_PATH_SUFFIX'] = $path_suffix; // /englesio /s OR ""
		$_SERVER['APP_SUFFIX'] = $possible_suffix; // englesio s OR ""
		$prefix_path = mb_substr($_SERVER['REQUEST_PATH'], 1, mb_strlen($path_suffix) * -1); // path/to/file
		break;
	}
	unset($path_suffix);
}

// APP_SELF
$_SERVER['APP_SELF'] = '/'.$prefix_path; // /path/to/file / / /path/to/dir

// APP_SCRIPT_FILENAME APP_SCRIPT_NAME
$script_name = (!empty($prefix_path)? '/': '').$prefix_path.'.php';
if(!($real_path = stream_resolve_include_path('build/'.$prefix_path.'.php'))) { // check file first then dir
	if(is_dir(stream_resolve_include_path('build/'.$prefix_path))) {
		$script_name = (!empty($prefix_path)? '/': '').$prefix_path.'/index.php';
		$real_path = stream_resolve_include_path('build/'.$prefix_path.'/index.php');
  }
}
if(strpos($_SERVER['REQUEST_PATH'], '//') === false && $real_path) {
  $_SERVER['APP_SCRIPT_FILENAME'] = $real_path; // C:\path\to\real\file.php
  $_SERVER['APP_SCRIPT_NAME'] = $script_name; // /path/to/file.php /index.php /index.php /path/to/dir/index.php
}
unset($script_name, $real_path, $prefix_path);

/**
 * Perform various actions before routing.
 */
// ENFORCE LOCALE
if(array_key_exists('APP_SUFFIX', $_SERVER)) {
	locale_set_default(MANIFEST['locales'][$_SERVER['APP_SUFFIX']]);
	setlocale(LC_ALL, locale_canonicalize(locale_get_default()));
}

// APP_LANGUAGE
$_SERVER['APP_LANGUAGE'] = reset(explode('@', locale_get_default(), 2)); // en-001 (CLDR lang tag of locale id)

// TRANSLATIONS
$_SERVER['APP_DOMAIN'] = stream_resolve_include_path('strings/'.$_SERVER['APP_LANGUAGE'].'/LC_MESSAGES/strings.po')?: stream_resolve_include_path('strings/en-001/LC_MESSAGES/strings.po');
$t = new Gettext\Translator;
$t->loadTranslations(Gettext\Translations::fromPoFile($_SERVER['APP_DOMAIN']));
$t->register();
unset($t);

// Redirect to first suffix if no suffix is set.
if(!empty(MANIFEST['locales']) && !array_key_exists('APP_PATH_SUFFIX', $_SERVER)) {
	header('Location: '.$_SERVER['APP_SELF'].('/' == $_SERVER['APP_SELF']? '': '/').key(MANIFEST['locales']).(!empty($_SERVER['QUERY_STRING'])? '?': '').$_SERVER['QUERY_STRING']);
	exit;
}

// WEBSTORE
if(!class_exists('\Webstore')) {
  final class Webstore {
		protected static $categories = NULL;
		protected static $checkoutZone = NULL;
		protected static $instance = NULL;
		protected static $metas = [];
		protected static $model = NULL;
		protected static $pixel = NULL;

		protected static $pageview_batch = [];

    public static function init() {
			self::$instance = new Market\Webstore([
				'override_olympian_host' => getenv('OLYMPIAN_HOST')
			]);

			// pixel
			self::$pixel = '';

			// metas
			//TODO: add links rel="alternate"
			// canonical metas
			array_push(
				self::$metas,
				'<link rel="canonical" href="'.$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['APP_SELF'].'">'
			);
			// cart metas
			array_push(
				self::$metas,
				'<link rel="dns-prefetch" href="//anamo.solutions">',
				'<link rel="prefetch" href="https://anamo.azureedge.net/bootstrap-for-market/5/assets/SF-Compact-Text-Regular.otf">',
				'<link rel="prerender" href="/cart/summary">'
			);
			// rest metas
			array_push(
				self::$metas,
				'<meta http-equiv="Content-Script-Type" content="text/javascript">',
				'<meta http-equiv="Content-Style-Type" content="text/css">'
			);
		}

		public static function mount(array &$batch) : void {
			$batch['router-webstore'] = self::$instance->request('GET', '/webstores/'.MANIFEST['webstore_id'].'?'.http_build_query([
				'include' => 'product-design',
			]), [], NULL, 'etag_by_memcache');
			$batch['router-browsenodes'] = self::$instance->request('GET', '/browsenodes?'.http_build_query([
				'page' => [
					'size' => 100
				],
				'include' => 'i18ns',
			]), [], NULL, 'etag_by_memcache');
			$batch['router-checkout-zone'] = self::$instance->request('GET', '/checkout-zones?'.http_build_query([
				'page' => [
					'size' => 1
				],
			]), [], NULL, 'etag_by_memcache');
		}

		public static function unmount(\Market\MarketBatchResponse $batchResponse) : void {
			$responses = $batchResponse->getResponses();

			if(array_key_exists('router-webstore', $responses)) {
				self::$model = $responses['router-webstore']->getOlympianNode();
			}
			if(array_key_exists('router-browsenodes', $responses)) {
				self::$categories = $responses['router-browsenodes']->getOlympianNodes();
			}
			if(array_key_exists('router-checkout-zone', $responses)) {
				self::$checkoutZone = $responses['router-checkout-zone']->getOlympianNodes();
			}
		}

		public static function getPageviewsBatch() : array {
			return self::$pageview_batch;
		}

		public static function pageviewBatch(?string $query) {
			if(empty($query)) {
				return NULL;
			}
			$key = 'context-hash~'.md5($query);
			if(!array_key_exists($key, self::$pageview_batch)) {
				self::$pageview_batch[$key] = self::$instance->request('GET', $query, [], NULL, 'etag_by_memcache');
				return NULL;
			}
			return self::$pageview_batch[$key];
		}

		public static function unmountPageview(\Market\MarketBatchResponse $batchResponse) : void {
			$responses = $batchResponse->getResponses();

			foreach(array_filter($responses, function($k) {
				return 'context-hash~' == mb_substr($k, 0, 13);
			}, ARRAY_FILTER_USE_KEY) as $k => $v) {
				self::$pageview_batch[$k] = $v->getOlympianNodeOrCollection();
			}
		}

		public static function getModel() : ?\Market\OlympianNodes\OlympianNodeWebstore {
			return self::$model;
		}

		public static function getCategories() : ?\Market\OlympianNodes\Collection {
			return self::$categories;
		}

		public static function getCheckoutZone() : ?\Market\OlympianNodes\OlympianNodeCheckoutZone {
			return self::$checkoutZone[0];
		}

		public static function getPixel() : ?string {
			return self::$pixel;
		}

		public static function getMetas() : string {
			return implode('', self::$metas);
		}

		public static function __callStatic(string $name, array $arguments) {
			if(method_exists(self::$instance, $name)) {
				return call_user_func(array(self::$instance, $name), ...$arguments);
			}
		}
  }
}
Webstore::init();

// PRE-DEFINED PATHS
if(0 === stripos($_SERVER['APP_SELF'], '/cart/') ||
0 === stripos($_SERVER['APP_SELF'], '/order/')) { // cart/* and order/*
	$token = base64_encode(
		($nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES)).
		sodium_crypto_secretbox(
			$message = session_id(),
			$nonce,
			$key = hex2bin(MANIFEST['access_key_secret'])
		)
	);
	sodium_memzero($message);
	sodium_memzero($key);
	die('
	<!DOCTYPE html>
	<html class="no-js" dir="ltr">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no, user-scalable=no">
		<meta name="format-detection" content="telephone=no">
		<meta name="robots" content="noindex">
		<meta name="description" content="Cart">
		<link rel="shortcut icon" href="/favicon.ico">

		<title>Loading&hellip;</title>


	<meta name="@anamo/cart-web-app/config/environment" content="%7B%22modulePrefix%22%3A%22@anamo/cart-web-app%22%2C%22podModulePrefix%22%3A%22@anamo/cart-web-app/pods%22%2C%22environment%22%3A%22development%22%2C%22rootURL%22%3A%22/%22%2C%22locationType%22%3A%22auto%22%2C%22EmberENV%22%3A%7B%22FEATURES%22%3A%7B%7D%2C%22EXTEND_PROTOTYPES%22%3A%7B%22Date%22%3Afalse%2C%22Array%22%3Afalse%7D%2C%22_APPLICATION_TEMPLATE_WRAPPER%22%3Afalse%7D%2C%22optionsConfig%22%3A%7B%7D%2C%22APP%22%3A%7B%22name%22%3A%22@anamo/cart-web-app%22%2C%22version%22%3A%221.0.0+d6e87512%22%7D%2C%22COLDSTART%22%3A%7B%22keys%22%3A%22d_css%20d_font%20d_js%20d_model%20d_globalize%20d_intl%22%7D%2C%22API_HOST%22%3A%22http%3A//192.168.1.2%3A8022%22%2C%22CART_MAX_ORDERABLE_QTY%22%3A%2299%22%2C%22exportApplicationGlobal%22%3Atrue%7D" />
	<link integrity="" rel="stylesheet" href="http://192.168.1.2:8023/assets/coldstart-spinner.css">

		<meta name="@anamo/cart-web-app/initializers/csrfParam" content="Bearer">
		<meta name="@anamo/cart-web-app/initializers/csrfToken" content="'.$token.'">
		<meta name="@anamo/cart-web-app/initializers/locale" content="'.locale_get_default().'">
		<meta name="@anamo/cart-web-app/initializers/suffix" content="'.$_SERVER['APP_SUFFIX'].'">
		<meta name="@anamo/cart-web-app/initializers/GaId" content="UA-62084763-43">
		<meta name="@anamo/cart-web-app/initializers/SaId" content="SA-2422-6270">

		<link integrity="" rel="preload" href="http://192.168.1.2:8023/assets/vendor.css" as="style">
		<link integrity="" rel="preload" href="http://192.168.1.2:8023/assets/app.css" as="style">


	</head>

	<body>
		<div id="coldstart-spinner"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" data-icon="cog-solid" viewBox="0 0 38 38" width="100" height="100" stroke="currentColor"><g fill="none" fill-rule="evenodd"><g transform="translate(1 1)" stroke-width="2"><circle stroke-opacity=".5" cx="18" cy="18" r="18"/><path d="M36 18c0-9.94-8.06-18-18-18"/></g></g></svg></div>
	<noscript><div class="dialog"><div><h1>This requires JavaScript to work</h1><p>Please <a href="http://192.168.1.2:8013/article/594520871964338/fi">enable JavaScript</a> and reload the page to continue and reload the page to continue.</p></div></div><link integrity="" rel="stylesheet" href="http://192.168.1.2:8023/assets/no-js.css"></noscript>

		<script src="http://192.168.1.2:8023/assets/vendor.js"></script>
		<script src="http://192.168.1.2:8023/assets/app.js"></script>


	</body>

	</html>
	');
}

// SERVER BATCH 1
$server_batch = [];
Webstore::mount($server_batch);

// SERVER BATCH -> product.php
if('/product.php' == $_SERVER['APP_SCRIPT_NAME']) {
	if(!empty($_GET['variant'])) {
		$server_batch['router-product-variant-id'] = Webstore::request('GET', '/products?'.http_build_query([
			'page' => [
				'size' => 1
			],
			'anid' => $_GET['anid'],
			'variant' => $_GET['variant'],
			'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option,variants.descriptions,variants.descriptions.variant'
		]), [], NULL, 'etag_by_memcache');

	} else {
		$server_batch['router-product-anid'] = Webstore::request('GET', '/products/'.$_GET['anid'].'?'.http_build_query([
			'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option,variants.descriptions,variants.descriptions.variant'
		]), [], NULL, 'etag_by_memcache');
	}
}

// SERVER BATCH -> browse.php
if('/browse.php' == $_SERVER['APP_SCRIPT_NAME']) {
	if(!empty($_GET['category'])) {
		$server_batch['router-browse-bnid'] = Webstore::request('GET', '/browsenodes/'.$_GET['category'].'?include=i18ns', [], NULL, 'etag_by_memcache');
	}
}

// SERVER BATCH -> unknown route
if(!array_key_exists('APP_SCRIPT_FILENAME', $_SERVER)) {
	$slug_suffix = mb_substr_count($_SERVER['APP_SELF'], '/') < 3? '': mb_strrev(reset(explode('/', mb_strrev($_SERVER['APP_SELF']), 2))); // reverse string and detect product variant -> /test1/89b5ecac491df44/81928858885939772389838429523/gr/el

	$server_batch['router-slug-product'] = Webstore::request('GET', '/products?'.http_build_query([
		'page' => [
			'size' => 1
		],
		'filter' => array_merge(
			[
				'slug' => ltrim($_SERVER['APP_SELF'], '/'),
				'slug_variant' => $slug_suffix,
			],
			(!empty(MANIFEST['locales'])?
				(!in_array(MANIFEST['default_locale'], MANIFEST['locales']) && !array_key_exists('APP_PATH_SUFFIX', $_SERVER)?
					['slug_exclude_locales' => array_values(MANIFEST['locales'])]:
					['slug_locale' => setlocale(LC_ALL, 0)]
				):
			[])
		),
		'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option,variants.descriptions,variants.descriptions.variant'
	]), [], NULL, 'etag_by_memcache');

	$server_batch['router-slug-browse'] = Webstore::request('GET', '/browsenodes?'.http_build_query([
		'page' => [
			'size' => 1
		],
		'filter' => array_merge(
			[
				'slug' => ltrim($_SERVER['APP_SELF'], '/')
			],
			(!empty(MANIFEST['locales'])?
				(!in_array(MANIFEST['default_locale'], MANIFEST['locales']) && !array_key_exists('APP_PATH_SUFFIX', $_SERVER)?
					['slug_exclude_locales' => array_values(MANIFEST['locales'])]:
					['slug_locale' => setlocale(LC_ALL, 0)]
				):
			[])
		),
		'include' => 'i18ns'
	]), [], NULL, 'etag_by_memcache');
}

// hit server first time
try {
	$batchResponse = Webstore::sendBatchRequest($server_batch);
	foreach($batchResponse as $key => $response) {
		if($response->isError()) {
			throw $response->getThrownException();
		}
	}
} catch(\Market\Exceptions\MarketResponseException $e) { // When Olympian returns an error
	trigger_error('Olympian returned an error: '.$e->getMessage(), E_USER_ERROR);
} catch(Market\Exceptions\MarketSDKException | Exception $e) { // When validation fails or other local issues
	trigger_error('Market SDK returned an error: '.$e->getMessage(), E_USER_ERROR);
}

Webstore::unmount($batchResponse);










// CONTEXT PATHS
$context = [];

// SLUGS -> figure out template to render
if(!array_key_exists('APP_SCRIPT_FILENAME', $_SERVER)) {
	$slugger = $batchResponse->getResponses()['router-slug-product']->getOlympianNodeOrCollection();
	if($slugger->count() > 0) {
		if($slugger->offsetGet(0)->hasMany('variants')->count() > 0) {
			$context['product'] = $slugger->offsetGet(0);

			$variants = $slugger->offsetGet(0)->hasMany('variants')->asArray();
			usort($variants, function($a, $b) {
				return $a->getAttr('order') <=> $b->getAttr('order');
			});
			$context['variant'] = end(array_filter($variants, function($v) use(&$slug_suffix) {
				return $v->getId() == $slug_suffix;
			}))?: reset($variants);
			unset($variants);

			$_SERVER['APP_SCRIPT_FILENAME'] = stream_resolve_include_path('build/product.php');
  		$_SERVER['APP_SCRIPT_NAME'] = '/product.php';
		}
	} else {
		$slugger = $batchResponse->getResponses()['router-slug-browse']->getOlympianNodeOrCollection();
		if($slugger->count() > 0) {
			$context['category'] = $slugger->offsetGet(0);
			$_SERVER['APP_SCRIPT_FILENAME'] = stream_resolve_include_path('build/browse.php');
			$_SERVER['APP_SCRIPT_NAME'] = '/browse.php';
		}
	}
	unset($slug_suffix);
}

// 302 ERROR ROUTE
if(!array_key_exists('APP_SCRIPT_FILENAME', $_SERVER)) {
	if('/404' == $_SERVER['APP_SELF']) {
		die('404');
	}
  header('Location: /404'.(array_key_exists('APP_PATH_SUFFIX', $_SERVER)? $_SERVER['APP_PATH_SUFFIX']: ''));
  exit;
}

// ENFORCE PAGE VISIBILITY BASED ON pages.json
if(array_key_exists(mb_substr($_SERVER['APP_SELF'], 1), PAGES)) {
	if(!array_key_exists($_SERVER['APP_LANGUAGE'], PAGES[mb_substr($_SERVER['APP_SELF'], 1)])) {
		if('/404' == $_SERVER['APP_SELF']) {
			die('404');
		}
		header('Location: /404'.(array_key_exists('APP_PATH_SUFFIX', $_SERVER)? $_SERVER['APP_PATH_SUFFIX']: ''));
		exit;
	}
}


// PRODUCT PAGE CONTEXT
if('/product.php' == $_SERVER['APP_SCRIPT_NAME']) {
	if(empty($context['product'])) {
		$anid = new Market\OlympianNodes\Collection;
		if(!empty($_GET['anid'])) {
			if(!empty($_GET['variant'])) {
				$anid = $batchResponse->getResponses()['router-product-variant-id']->getOlympianNodeOrCollection();
				if($anid->count() == 0) {
					header('Location: /404'.(array_key_exists('APP_PATH_SUFFIX', $_SERVER)? $_SERVER['APP_PATH_SUFFIX']: ''));
					exit;
				}
				$context['product'] = $anid->offsetGet(0);

				$variants = $anid->offsetGet(0)->hasMany('variants')->asArray();
				usort($variants, function($a, $b) {
					return $a->getAttr('order') <=> $b->getAttr('order');
				});
				$context['variant'] = end(array_filter($variants, function($v) {
					return $v->getId() == $_GET['variant'];
				}))?: reset($variants);
				unset($variants);

			} else {
				$anid = $batchResponse->getResponses()['router-product-anid']->getOlympianNodeOrCollection();
				if(empty($anid)) {
					header('Location: /404'.(array_key_exists('APP_PATH_SUFFIX', $_SERVER)? $_SERVER['APP_PATH_SUFFIX']: ''));
					exit;
				}
				$context['product'] = $anid;

				$variants = $anid->hasMany('variants')->asArray();
				usort($variants, function($a, $b) {
					return $a->getAttr('order') <=> $b->getAttr('order');
				});
				$context['variant'] = reset($variants);
				unset($variants);
			}
		}
	}
}

// BROWSE PAGE CONTEXT
if('/browse.php' == $_SERVER['APP_SCRIPT_NAME']) {
	if(empty($context['category'])) {
		$category_id = new Market\OlympianNodes\OlympianNode;
		if(!empty($_GET['category'])) {
			$anid = $batchResponse->getResponses()['router-browse-bnid']->getOlympianNodeOrCollection();
			if(empty($anid)) {
				header('Location: /404'.(array_key_exists('APP_PATH_SUFFIX', $_SERVER)? $_SERVER['APP_PATH_SUFFIX']: ''));
				exit;
			}
			$context['category'] = $anid;
		}
	}
	unset($anid);

	$context['order'] = (in_array($_GET['sort'], ['release-date', '-release-date', 'presentment-price', '-presentment-price'])? $_GET['sort']: '-release-date');
}





// SERVER BATCH 2
$server_batch2 = [];


// ADD TO BATCH ALL ROUTE FIXED API REQUESTS
(include $_SERVER['APP_SCRIPT_FILENAME'])($context); // run with empty context, debug crashes here
$server_batch2 = array_merge($server_batch2, Webstore::getPageviewsBatch());


// PRODUCT PAGE CONTEXT
if('/product.php' == $_SERVER['APP_SCRIPT_NAME']) {
	// related-products
	/*if(empty($context['related-products'])) {
		$server_batch2['related-products'] = Webstore::request('GET', '/products?'.http_build_query([
			'page' => [
				'size' => 16
			],
			'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option'
		]), [], NULL, 'etag_by_memcache');
	}

	// prev-next
	$category_id = reset($context['product']->hasMany('categories')->map(function($v) {
		return $v->getRel('category')['data']['id'];
	})->asArray());
	$http_filters = array_filter(array_merge((array)$_GET['prev-next-filters'], (!empty($category_id)? ['category' => $category_id]: [])));
	// temp fix -> $http_filters['sortBy'] = 'releasedate';
	$curl_params = [
		'page' => [
			'size' => 1,
			'number' => 1
		],
		'search' => $http_filters,
		'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option'
	];
	if(empty($context['prev'])) {
		$server_batch2['prev'] = Webstore::request('GET', '/products?'.http_build_query(array_merge(
			$curl_params,
			['before' => $context['product']->getId()]
		)), [], NULL, 'etag_by_memcache');
	}
	if(empty($context['next'])) {
		$server_batch2['next'] = Webstore::request('GET', '/products?'.http_build_query(array_merge(
			$curl_params,
			['after' => $context['product']->getId()]
		)), [], NULL, 'etag_by_memcache');
	}
	unset($category_id, $http_filters, $curl_params, $resp);*/
}

// BROWSE PAGE CONTEXT
if('/browse.php' == $_SERVER['APP_SCRIPT_NAME']) {
	$http_filters = array_filter(array_merge((array)$_GET['filters'], (!empty($context['category'])? ['category' => $context['category']->getId()]: [])));

	if(empty($context['filters'])) {
		$server_batch2['filters'] = Webstore::request('GET', '/filters?'.http_build_query([
			'page' => [
				'size' => 100
			],
      'search' => !empty($http_filters)? $http_filters: ['yes'],
			'include' => 'i18ns,items,items.i18ns',
		]), [], NULL, 'etag_by_memcache');
	}

	// get products
	$curl_params = [
		'page' => [
			'size' => 12,
			'number' => (int)$_GET['page']
		],
		'filter' => $http_filters,
		'sort' => $context['order'],
		'include' => 'attributes,attributes.product,browsenodes,browsenodes.product,browsenodes.i18ns,slugs,slugs.product,variants,variants.product,variants.titles,variants.titles.variant,variants.prices,variants.prices.variant,variants.images,variants.images.variant,variants.options,variants.options.variant,variants.options.i18ns,variants.options.i18ns.option'
	];
	$server_batch2['products'] = Webstore::request('GET', '/products?'.http_build_query($curl_params), [], NULL, 'etag_by_memcache');

	unset($curl_params, $resp);
}


// hit server second time
if(!empty($server_batch2)) {
	try {
		$batchResponse2 = Webstore::sendBatchRequest($server_batch2);
		foreach($batchResponse2 as $key => $response) {
			if($response->isError()) {
				throw $response->getThrownException();
			}
		}
	} catch(\Market\Exceptions\MarketResponseException $e) { // When Olympian returns an error
		trigger_error('Olympian returned an error: '.$e->getMessage(), E_USER_ERROR);
	} catch(Market\Exceptions\MarketSDKException | Exception $e) { // When validation fails or other local issues
		trigger_error('Market SDK returned an error: '.$e->getMessage(), E_USER_ERROR);
	}
}


if(!empty($batchResponse2)) {
	// PRODUCT PAGE CONTEXT
	if('/product.php' == $_SERVER['APP_SCRIPT_NAME']) {
		// related-products
		if(array_key_exists('related-products', $batchResponse2->getResponses())) {
			$context['related-products'] = $batchResponse2->getResponses()['related-products']->getOlympianNodeOrCollection();
		}

		// prev-next
		if(array_key_exists('prev', $batchResponse2->getResponses())) {
			$context['prev'] = $batchResponse2->getResponses()['prev']->getOlympianNodeOrCollection();
		}
		if(array_key_exists('next', $batchResponse2->getResponses())) {
			$context['next'] = $batchResponse2->getResponses()['next']->getOlympianNodeOrCollection();
		}
	}

	// BROWSE PAGE CONTEXT
	if('/browse.php' == $_SERVER['APP_SCRIPT_NAME']) {
		// filters
		if(array_key_exists('filters', $batchResponse2->getResponses())) {
			$context['filters'] = $batchResponse2->getResponses()['filters']->getOlympianNodes();
		}

		// get products
		$resp = $batchResponse2->getResponses()['products'];
		$context['productsMeta'] = $resp->getDecodedBody()['meta'];
		$context['products'] = $resp->getOlympianNodeOrCollection();
		unset($resp);
	}

	Webstore::unmountPageview($batchResponse2);
}





// ROUTE
$context['__render'] = true;
echo (include $_SERVER['APP_SCRIPT_FILENAME'])($context);
