<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.05
// Randem Systems: https://randemsystems.support
// BotBanish Prepare Cache Upload File
// Date: 08/12/2026
// Usage:
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishPrepareCacheFile() {
	
	global $BotBanishSettings;

	$table = 'bbc_botbanishclient_geo';

	// If the "Uploaded" field does not exist, create it with the index.

	$table_columns = BotBanishGetTableColumns($table);
	$field = 'uploaded';
	$zipFile = false;

	if (!isset($table_columns[$field])) {

		$sql = 'ALTER TABLE `' . $table . '` ADD `' . $field . '` INT NOT NULL DEFAULT "0" AFTER `updated`';
		BotBanishExecuteSQL($sql, true, true);

		$sql = 'ALTER TABLE `' . $table . '` ADD KEY `' . $field . '` (`' . $field . '`)';
		BotBanishExecuteSQL($sql, true, true);
	}

	$sql = 'SELECT `bot_ip`, `country`, `country_code`, `geo_info` FROM `' . $table . '` WHERE `' . $field . '` = 0 AND `country` != ""';
	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows)) {

		$basename = 'BotBanish_Cache_' . BotBanishGetCorrectDateTimeB();
		$filename = $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'] . $basename . '.php';
		$str = '<?php' . PHP_EOL . '$cacheData = ' . var_export($rows, true) . ';' . PHP_EOL . 'return $cacheData;' . PHP_EOL . '?>';

		if (file_exists($filename))
			@unlink($filename);

		BotBanishWriteFile($filename, $str);

		$zipFile = $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'] . $basename . '.zip';
		$selections = array($filename);
		
		ZipArchiveIt($selections, $zipFile);
		
		// Update all rows that we have processed
		
		foreach ($rows as $row) {

			$sql = 'UPDATE `' . $table . '` SET `uploaded` = 1 WHERE `bot_ip` = "' . $row['bot_ip'] . '"';
			BotBanishExecuteSQL($sql);
		}

		if (file_exists($filename))
			@unlink($filename);
	}

	return $zipFile;
}
?>