<?php

include('global.php');

$Content = file_get_contents($StdOutLogFile);
$Lines = explode("\n", $Content);
$Content = ''; // Free unused memory

// Separate information from log file
$Line = 0;
while(($Line < count($Lines)) and (substr($Lines[$Line], 0, 6) != 'MaNGOS')) $Line++;
$MangosVersion = $Lines[$Line];

// Try to find start of backtrace
while(($Line < count($Lines)) and (substr($Lines[$Line], 0, 16) != 'Program received')) $Line++;
$Backtrace = array_slice($Lines, $Line, count($Lines) - $Line);   // Assume rest of file to be backtrace
$Backtrace = addslashes(implode("\n", $Backtrace));
$Lines = '';

//$Log = array_slice($Lines, 0, $Line);
//$Log = addslashes(implode("\n", $Log));

// Get used database version from database
$DbResult = $Database->query('SELECT * FROM `'.$Config['Mangos']['DatabaseMangos'].'`.`db_version`');
$DbRow = $DbResult->fetch_array();
$DbVersion = $DbRow['version'];

// Get last uptime info
$DbResult = $Database->query('SELECT * FROM `'.$Config['Mangos']['DatabaseMangos'].'`.`uptime` ORDER BY `starttime` DESC LIMIT 1');
echo($Database->error);
$DbRow = $DbResult->fetch_array();
$MaxPlayerCount = $DbRow['maxplayers'];
$Uptime = $DbRow['uptime'];

// Insert data to database
$Database->query('INSERT INTO `debug` (`Time`, `MangosVersion`, `DbVersion`, `Uptime`, `MaxPlayerCount`) VALUES (NOW(), "'.
  $MangosVersion.'", "'.$DbVersion.'", '.$Uptime.', '.$MaxPlayerCount.')');
$InsertId = $Database->insert_id;

// Insert data in separate query to partly avoid too long query packet error
$Database->query('UPDATE `debug` SET Backtrace="'.$Backtrace.'" WHERE Id='.$InsertId);
$Backtrace = '';
//echo($Database->error);
$Log = addslashes(file_get_contents($MangosLogFile));
$Database->query('UPDATE `debug` SET Log="'.$Log.'" WHERE Id='.$InsertId);
//echo($Database->error);
$Log = addslashes(file_get_contents($MangosDbErrorsLogFile));
$Database->query('UPDATE `debug` SET DbErrors="'.$Log.'" WHERE Id='.$InsertId);
//echo($Database->error);

$Configuration = array();
$Log = addslashes(file_get_contents($MangosConfFile));
$LogLines = explode("\n", $Log);
foreach($LogLines as $LogLine)
{
  if(substr($LogLine, 0, 1) != '#') $Configuration[] = $LogLine;
}
$Database->query('UPDATE `debug` SET Configuration="'.implode("\n", $Configuration).'" WHERE Id='.$InsertId);

//echo($Database->error);
$Log = addslashes(file_get_contents($ErrOutLogFile));
$Database->query('UPDATE `debug` SET ErrorLog="'.$Log.'" WHERE Id='.$InsertId);

// Clear log files
unlink($MangosLogFile);
unlink($StdOutLogFile);
unlink($ErrOutLogFile);
unlink($MangosDbErrorsLogFile);

?>