<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 8.0.00
// Randem Systems: https://randemsystems.support
// BotBanish Split Very Large SQL File in Blocks to Execute Async
// Date: 06/09/2026
//
// Function: Split large SQL file
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishExecuteSQLAsync($sql, $file = false, $change = false) {

	$conn = BotBanishDatabaseOpen();

	if (!$conn)
		return;
	
	if ($file)
		$sql = file_get_contents($sql);
/*
	global $BotBanishSettings;
	BotBanishWriteFile($BotBanishSettings['BOTBANISH_STATIC_LOGS_DIR'] . 'BotBanish_Sync_SQL.txt', $sql, true);
*/
	BotBanishMultiConnect($conn, $sql, $change);

	if (property_exists($conn, 'close'))
		$conn->close;
}

function BotBanishExecuteSQLFileByLines($sql_filename, $table, $find, $size = 32767) {

	if (!file_exists($sql_filename)) return false;

	$sql = '';
	$overload = '';

	$file = fopen($sql_filename, "r");
	$buffer = fread($file, $size);

	$conn = BotBanishDatabaseOpen();

	// Change databse table collation to a supported one

	while (!feof($file)) {

		$lines = explode($find, $buffer);
		$i = count($lines) - 1;
		$overload = $lines[$i];		// Always not use the last line incase of SQL statement breaks
		unset ($lines[$i]);

		$sql = BotBanishCompleteSQLLines($lines, $find);

		BotBanishMultiConnect($conn, $sql);

		$sql = '';
		$buffer = $overload . fread($file, $size);
		$overload = '';
	}

	if (!empty($buffer)) {

		$lines = explode($find, $buffer);
		$sql = BotBanishCompleteSQLLines($lines, $find);
		BotBanishMultiConnect($conn, $sql);
	}

	if (property_exists($conn, 'close'))
		$conn->close;

	fclose($file); // Close the file
	return true;
}

function BotBanishCompleteSQLLines($lines, $find) {

	$sql = '';

	foreach ($lines as $line) {

		if (!empty(trim($line)) && (substr($line,0,2) !== '--'))
			$sql .= $find . $line;
	}

	return $sql;
}

function BotBanishMultiConnect($conn, $sql, $change = false, $logit = false) {

	if (empty($sql))
		return;

	if ($change)
		$sql = BotBanishChangeTableCollation($sql);

	if ($logit)
		BotBanishLogError('MultiConnect: Modified SQL', $sql, 'MultiConnectSQL');

	try {

		$conn->multi_query($sql);

	} catch (mysqli_sql_exception $f) {

		$msg = 'Query Failed:';
		BotBanishLogError($msg, $f . PHP_EOL . $sql . PHP_EOL, 'MultiConnectFail');
		return false;
	}

	do {
		if ($result = $conn->store_result()) {
			BotBanishLogError('MultiConnect: Store Error', var_dump($result->fetch_all(MYSQLI_ASSOC), 'MultiConnectStore'));
			$result->free();
		}
		
		if ($conn->error) {
			BotBanishLogError('MultiConnect: Error - ', $conn->error . PHP_EOL . $sql, 'MultiConnectError');		
		}
		
	} while ($conn->next_result());

	return true;
}
?>