<?php

if (!function_exists('m_current_admin_lang')) {
	function m_current_admin_lang() {
		$code = function_exists('m_get_session') ? m_get_session('admin_lang') : null;
		if (!$code || !preg_match('/^[a-z]{2}(-[A-Z]{2})?$/', $code)) {
			$code = 'tr';
		}
		return $code;
	}
}

if (!function_exists('lang')) {
	function lang(string $key, array $params = [], ?string $fallback = null) {
		static $cache = [];
		$code = m_current_admin_lang();
		$baseCode = 'tr';
		// Sözlükleri cache'le
		if (!isset($cache[$baseCode])) {
			$cache[$baseCode] = m_i18n_load($baseCode);
		}
		if (!isset($cache[$code])) {
			$cache[$code] = m_i18n_load($code);
		}
		$value = null;
		// Sözlükleri birleştir (base -> locale override). Böylece fallback her zaman çalışır.
		$dict = $cache[$baseCode] ?? [];
		if ($code !== $baseCode) {
			$dict = array_replace($dict, $cache[$code] ?? []);
		}
		if (isset($dict[$key])) {
			$value = $dict[$key];
		}
		// Tanım bulunamazsa define sabitlerine düş
		if ($value === null) {
			// Dot-notation anahtarını sabit ismine dönüştür (hem orijinal hem UPPERCASE dene)
			$constKey = str_replace(['.', '-'], ['_', '_'], $key);
			if (defined($constKey)) {
				$value = constant($constKey);
			} else {
				$constUpper = strtoupper($constKey);
				if (defined($constUpper)) {
					$value = constant($constUpper);
				}
			}
		}
		if ($value === null) {
			$value = $fallback !== null ? $fallback : $key;
		}
		// Basit yer tutucu değişimi: {name}
		foreach ($params as $pKey => $pVal) {
			$value = str_replace('{' . $pKey . '}', (string)$pVal, $value);
		}
		return $value;
	}
}

if (!function_exists('m_i18n_load')) {
	function m_i18n_load(string $code): array {
		$jsonPath = ROOT_FOLDER . '/admin/lang/' . $code . '.json';
		if (is_file($jsonPath)) {
			$raw = file_get_contents($jsonPath);
			if ($raw !== false) {
				$decoded = json_decode($raw, true);
				if (is_array($decoded)) {
					return $decoded;
				}
			}
		}
		$phpPath = ROOT_FOLDER . '/admin/lang/' . $code . '.php';
		if (is_file($phpPath)) {
			$dict = include $phpPath;
			if (is_array($dict)) {
				return $dict;
			}
		}
		$phpArrayPath = ROOT_FOLDER . '/admin/lang/' . $code . '.array.php';
		if (is_file($phpArrayPath)) {
			$dict = include $phpArrayPath;
			if (is_array($dict)) {
				return $dict;
			}
		}
		return [];
	}
}

