<?php
$tempname = $_FILES['datei']['tmp_name'];
$name = $_FILES['datei']['name'];
$type = $_FILES['datei']['type'];
$size = $_FILES['datei']['size'];
session_start();

$tbl_name="forum_answer"; // Table name
$moduleurl = $_POST["path"];


// Connect to server and select database.
include ($_SERVER["DOCUMENT_ROOT"]."/Config/_dbconfig_.php");
@$y = mysql_connect($MYSQL_HOST,$MYSQL_USER,$MYSQL_PASS);
@$x = mysql_select_db($MYSQL_DATABASE);
if (empty($x)) 
{ 
  die ("Keine Verbindung zur Datenbank! [<b><font color=red>FAIL</b></font>]<br>"); 
} 

// Get value of id that sent from hidden field
$id=mysql_real_escape_string($_POST['id']);

// Find highest answer number.
$sql="SELECT MAX(a_id) AS Maxa_id FROM ". $tbl_name ." WHERE question_id='".$id."'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
// add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1
if ($rows) 
{
    $Max_id = $rows['Maxa_id']+1;
}
else 
{
    $Max_id = 1;
}

//----------------- Uploads
if($type == "php" || $type == "application/x-httpd-php" || $type == "htm" || $type == "html" || $type == "text/html")
	die("NO HTML OR PHP FILES ALLOWED!");
if($tempname != "" && $name != "")
{
	move_uploaded_file($tempname, $_SERVER["DOCUMENT_ROOT"]."/Modules/Forum/uploads/".$id."-".$Max_id."-".$name);
}
//die("tmP:".$tempname." name:".$name);

//-----------------


// get values that sent from form
$a_name=mysql_real_escape_string($_SESSION["user_nickname"]);
if($a_name == "" || !$_SESSION['user_nickname'])
{
	$a_name = "guest";
}
$a_avatar=mysql_real_escape_string($_SESSION["user_avatar"]);
$a_answer=mysql_real_escape_string($_POST['a_answer']);

$datetime=date("d-m-y H:i:s"); // create date and time

if($tempname != "" && $tempname != "")
{
	$dbeintrag= $id.'-'.$Max_id.'-'.$name;
}
else
{
	$dbeintrag = "";
}
if($a_answer != "")
{
	// Insert answer
	$sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_avatar, a_answer, a_datetime, a_attachment)VALUES('$id', '$Max_id', '$a_name', '$a_avatar', '$a_answer', '$datetime', '$dbeintrag')";
	$result2=mysql_query($sql2);

	if($result2)
	{
		// If added new answer, add value +1 in reply column
		$tbl_name2="forum_question";
		$sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'";
		$result3=mysql_query($sql3);
		$datetime=date('Y-m-d H:i:s');
		$sql3="UPDATE $tbl_name2 SET `lastupdate` = NOW( ) WHERE `forum_question`.`id`='$id'";
		$result3=mysql_query($sql3);
		header ("Location: ".$moduleurl."&uebergabe=1&uebergabe2=".$id); 
	}
	else 
	{
		echo "ERROR";
	}
}
else
{
	header ("Location: ".$moduleurl."&uebergabe=1&uebergabe2=".$id); 
}
mysql_close();
?>
