<?php
	namespace Main\Middlewares;
	
	use Main\Libs\Translate\Translator;
	use PDO;
	use Pecee\Http\Middleware\IMiddleware;
	use Pecee\Http\Request;
	
	class LanguageMiddleware implements IMiddleware {
		public function handle(Request $request): void
		{
			global $lang;
			
			$languages = db()->query("SELECT * FROM Languages WHERE isActive = '1'");
			$languages = $languages->fetchAll(PDO::FETCH_ASSOC);
			$languageCodes = array_column($languages, 'code');
			$lang = settings("language");
			
			if (cookies()->has('lang')) {
				$lang = cookies()->get('lang');
			} else {
				if (settings('forceDefaultLanguage') == 0) {
					if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
						$firstLang = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0];
						$firstLang = str_replace('-', '_', $firstLang);
						if (in_array($firstLang, $languageCodes)) {
							$lang = $firstLang;
						}
						else {
							$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
						}
					}
				}
			}
			
			if ($request->getInputHandler()->get('lang')) {
				$lang = escape(strip_tags(trim($request->getInputHandler()->get('lang')->getValue())));
				if (in_array($lang, $languageCodes)) {
					cookies()->set('lang', $lang, 365 * 24 * 60 * 60);
				} else {
					$lang = settings("language");
				}
			}
			
			$customTranslate = [];
			$customTranslateQuery = db()->prepare("SELECT `key`, `value` FROM CustomTranslate WHERE language = ?");
			$customTranslateQuery->execute(array($lang));
			foreach ($customTranslateQuery as $readCustomTranslate) {
				$customTranslate[$readCustomTranslate["key"]] = $readCustomTranslate["value"];
			}
			
			$translator = new Translator(false, 'json', $lang, __ROOT__.'/apps/main/app/languages', theme()->realPath('/languages'), $customTranslate);
			$translator->register();
			
			// Add data to the template
			template()->addData(compact(
				'languages',
				'languageCodes',
				'lang',
			));
		}
	}