<?php
	namespace Main\Core;
	
	class Seo {
		
		private string $page;
		private string $title;
		private ?string $description;
		private ?string $image;
		private array $data;
		
		public function __construct(string $page, string $title, ?string $description, ?string $image, ?array $data = []) {
			$this->page = $page;
			$this->title = $title;
			$this->description = $description === null || $description === "" ? settings("siteDescription") : $description;
			$this->image = $image;
			$this->data = $data;
		}
		
		private function replaceData($text) {
			// Translate placeholders first
			$text = $this->translatePlaceholders($text);
			
			$data = array_merge($this->data, [
				"site_title" => settings("serverName"),
				"tagline" => settings("siteSlogan"),
			]);
			foreach ($data as $key => $value) {
				$text = str_replace("%" . $key . "%", $value, $text);
			}
			
			return $text;
		}
		
		private function translatePlaceholders($text) {
			// Find all translate placeholders in the format %translate:TEXT%
			$pattern = '/%translate:"([^"]+)"%/';
			if (preg_match_all($pattern, $text, $matches)) {
				// Loop through all found placeholders and replace with translations
				foreach ($matches[1] as $key => $placeholder) {
					$translation = t__($placeholder);
					$fullPlaceholder = $matches[0][$key];
					$text = str_replace($fullPlaceholder, $translation, $text);
				}
			}
			return $text;
		}
		
		public function page(): string {
			return $this->page;
		}
		
		public function title(): string {
			return escape($this->replaceData($this->title));
		}
		
		public function description(): ?string {
			return escape($this->replaceData($this->description));
		}
		
		public function image(): ?string {
			return escape($this->replaceData($this->image));
		}
	}
