<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 7.0.10
// Randem Systems: https://randemsystems.support
// BotBanish Lanuage Subroutines
// Date: 12/28/2025
// Usage:
//
// Function: Common location for common settings
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishSetLanguage($lang = '') {

	global $BotBanishSettings, $BotBanishText;

	$lang = !empty($lang) ? $lang : '';
	$lang = empty($lang) && isset($BotBanishSettings['BOTBANISH_LANGUAGE_SELECT']) && !empty($BotBanishSettings['BOTBANISH_LANGUAGE_SELECT']) ? $BotBanishSettings['BOTBANISH_LANGUAGE_SELECT'] : 'english';

	$lang = BotBanishLanguageSupported($lang);
	$useLanguageFiles = true;	// Default to language files

	// If we are processing an install, DO NOT attempt to use the database. Use the language file.

	$servername = '';
	$servername = isset($BotBanishSettings['BOTBANISH_DB_SERVERNAME']) ? $BotBanishSettings['BOTBANISH_DB_SERVERNAME'] : $servername;
	$servername = empty($servername) && isset($_POST['BOTBANISH_DB_SERVERNAME']) ? $_POST['BOTBANISH_DB_SERVERNAME'] : $servername;

	if (!empty($servername) && (isset($BotBanishSettings['BOTBANISH_INSTALL']) && !$BotBanishSettings['BOTBANISH_INSTALL'])) {

		$table = 'botbanish_language_text_' . strtolower($lang);
		$tables = BotBanishGetTableNames($table, true);

		if (!empty($tables)) {

			$sql = 'SELECT `language` FROM `botbanish_languages` WHERE 1';
			$rows = BotBanishExecuteSQL($sql);

			if (is_array($rows) && !empty($rows)) {

				BotBanishDefineGlobals('BOTBANISH_LANGUAGES', BotBanishAdjustDatabaseRows($rows));

				$sql = 'SELECT `lang_id` FROM `botbanish_languages` WHERE `language` = "'. $lang . '" LIMIT 1';
				$rows = BotBanishExecuteSQL($sql);

				if (is_array($rows) && (count($rows) == 1)) {

					$row = BotBanishLimitReturn($rows);
					$sql = 'SELECT `lang_key`, `lang_text` FROM `' . $table .'` WHERE `lang_id` = '. $row['lang_id'];
					$rows = BotBanishExecuteSQL($sql);

					if (is_array($rows) && (count($rows) > 0)) {

						foreach ($rows as $row)
							$BotBanishText[$row['lang_key']] = html_entity_decode($row['lang_text'], ENT_QUOTES, 'utf-8');

						$useLanguageFiles = false;
					}
				}
			}
		}
	}

	if ($useLanguageFiles) {

		// If language table is not present or empty, use the language file

		if (!isset($BotBanishSettings['BOTBANISH_LANGUAGES']) || empty($BotBanishSettings['BOTBANISH_LANGUAGES']))
			BotBanishLanguageSupported();

		$lang = BotBanishGetLanguageFile($lang);  // This will populate $BotBanishText
	}

	BotBanishDefineGlobals('BOTBANISH_LANGUAGE_SELECT', $lang);
}

function BotBanishGetLanguageFile($lang = 'english') {

	global $BotBanishSettings, $BotBanishText;

	// If the language file does not exist OR the global 'BOTBANISH_LANGUAGE_DATABASE' does not exist
	// OR the global exists and is marked false we will be using the database instead of the flat files for languages

	$language = empty($lang) && isset($BotBanishSettings['BOTBANISH_LANGUAGE_SELECT']) ? $BotBanishSettings['BOTBANISH_LANGUAGE_SELECT'] : $lang;
	$filename = $BotBanishSettings['BOTBANISH_LANGUAGE_DIR'] . 'BotBanishLanguage.' . $language . '.php';

	if (file_exists($filename)) {

		include $filename;

		foreach ($txt as $key => $value)
			$BotBanishText[$key] = html_entity_decode($value, ENT_QUOTES, 'utf-8');
	}

	return $language;
}

function BotBanishDatabaseSetLanguage($language) {

	global $BotBanishText;

	$table = 'botbanish_language_text_' . strtolower($language);
	$sql = 'SELECT `lang_key`, `lang_text` FROM `' . $table . '`';
	$rows = BotBanishExecuteSQL($sql);

	$txt = array();

	foreach ($rows as $row)
		$txt[$row['lang_key']] = html_entity_decode($row['lang_text']);

	$table = 'botbanish_country_code';
	$sql = 'SELECT `country_code`, `country` FROM `' . $table . '`';
	$txt['CCodes'] = BotBanishExecuteSQL($sql);

	if (!empty($txt))
		$BotBanishText = $txt;

	return $language;
}

function BotBanishUpdateLanguage($full = false, $language_table = false) {

	// Start with English and match with other languages that are missing

	$source = 'en';
	$count = 0;

	$lang_table = 'botbanish_languages';
	$table = $lang_table;
	$sql = 'SELECT `lang_id`, `language`, `lang_code` FROM ' . $table . ' WHERE `lang_id` > 1 ORDER BY `lang_id`';
	$lang_rows = BotBanishExecuteSQL($sql);

	// if we are in a restart, locate the language id for the starting language then add 1 to get to the next language

	if ($language_table !== false) {

		foreach ($lang_rows as $row) {

			if ($row['language'] == $language_table) {

				$language_id = $row['lang_id'] + 1;
				break;
			}
		}
	}

	// Get all English starting entries

	$text_table = 'botbanish_language_text_';
	$table1 = $text_table . 'english';
	$sql = 'SELECT `lang_key`, `lang_text` FROM ' . $table1 . ' WHERE `lang_id` = 1';
	$text_rows = BotBanishExecuteSQL($sql);

	foreach ($lang_rows as $lang_row) {

		$id = $lang_row['lang_id'];

		// If we are in a restart skip to the proper language

		if (isset($language_id)) {

			if ($language_id != $id)
				continue;
		}

		$target = $lang_row['lang_code'];
		$language = strtolower($lang_row['language']);
		$id = $lang_row['lang_id'];

		BotBanishDisplayIt(date('m-d-Y h:i:s') . ' - Start ' . $lang_row['language'] . ' Language Update</br></br>');

		$table2 = $text_table . $language;

		// If in a restart, we will start at the next language table

		if (($language_table === false) || (isset($language_id))) {

			if (!$full) {

				$sql = 'SELECT table1.`lang_id`, table1.`lang_key`, table1.`lang_text`, table2.`lang_key` as lang_key_' . $language . ',
					table2.`lang_text` as lang_text_' . $language . ' FROM ' . $table1 . ' as table1
						LEFT JOIN ' . $table2 . ' as table2 ON table1.`lang_key` = table2.lang_key';

			} else {

				BotBanishExecuteSQL('TRUNCATE TABLE `' . $table2 . '`', true, true);
				$sql = 'SELECT `lang_id`, `lang_key`, `lang_text` FROM ' . $table1;
			}

			$rows = BotBanishExecuteSQL($sql);

			foreach ($rows as $row) {

				if ($full || empty($row['lang_text_' . $language])) {

					$key = $row['lang_key'];
					$text = $row['lang_text'];

					if (!BotBanishInsertTextData($source, $target, $id, $key, $text, $table2))
						return false;
				}
			}

			BotBanishDisplayIt(date('m-d-Y h:i:s') . ' - Finish ' . $lang_row['language'] . ' Language Update</br></br>');
		}

		// Restart program after each language table that is processed to by-pass the execution timeout.

		if ($id !== $lang_rows[count($lang_rows) - 1]['lang_id']) {

			BotBanishFlushOutputBuffer();
			$type = ($full === true) ? '&full=true' : '';
			$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . '?table=' . $lang_row['language'] . $type;
			header('Location: ' . $url);
			exit();
		}
	}

	return true;
}

function BotBanishInsertTextData($source, $target, $id, $key, $text, $table) {

	$txt = GoogleTranslate($text, $source, $target);

	// If Google Translate is not active just return

	if ($txt === false)
		return false;

	$row = array();
	$row['lang_id'] = $id;
	$row['lang_key'] = $key;
	$row['lang_text'] = htmlentities($txt);

	$params = BotBanishBuildSQLStatementInsert($row, $table);

	$sql = 'INSERT INTO `' . $table . '` (' . $params['columns'] . ') VALUES (' . $params['values'] . ')' .
			' ON DUPLICATE KEY UPDATE ' . $params['updates'];

	BotBanishExecuteSQL($sql, true, true);
	return true;
}

function GoogleTranslate($text, $source, $target) {

    $apiKey = 'AIzaSyBdaA6ZsExyG5KWXTDXDMxsMcftlQ-aQKc';

	$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=' . $source . '&target=' . $target;

	$fields = array(
		'sl' => urlencode($source),
		'tl' => urlencode($target),
		'q' => urlencode($text)
	);

	// URL-ify the data for the POST
	$fields_string = "";
	foreach ($fields as $key => $value) {
		$fields_string .= '&' . $key . '=' . $value;
	}

	rtrim($fields_string, '&');

	// Open connection
	$ch = curl_init();

	// Set the url, number of POST vars, POST data
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, count($fields));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

	// Execute post
	$result = curl_exec($ch);

	// Close connection
	curl_close($ch);

	// Array ( [data] => Array ( [translations] => Array ( [0] => Array ( [translatedText] => Ändringsperiod ) [1] => Array ( [translatedText] => Ändringsperiod ) ) ) )
    $translated = (json_decode($result, true));

	if (!isset($translated['error'])) {

		return $translated['data']['translations'][0]['translatedText'];

	} else {

		$error = var_export($translated['error'], true);
		BotBanishLogError('Translation Error:', $error, 'Error');
		return false;
	}
}

function BotBanishLoadLanguage() {

	loadLanguage('BotBanish/BotBanishLanguage');
}
?>