<?php
session_start();
header('content-type: text/plain; charset=utf-8');
require_once('mysql.php');
require_once('functions.php');
$loggedIn = false;
if(isset($_SESSION['uid']) && isset($_SESSION['username'])) {
	$loggedIn = true;
	$login_uid = intval($_SESSION['uid']);
	$uq = "SELECT * FROM users WHERE uid = ".$login_uid."";
	$uquery = mysql_query($uq) or die(mysql_error());
	$user_info = mysql_fetch_assoc($uquery);
	if(!$user_info) { // User dont exist, logout
		$_SESSION = array();
		session_destroy();
		exit;
	}
}



if(isset($_GET['post'])) {
	$post_id = intval($_GET['post']);
	$formatIt = false;
	if($post_id > 0) {
		$pq = "SELECT poster_uid, hidden FROM posts WHERE id = ".$post_id."";
		$pquery = mysql_query($pq) or die(mysql_error());
		$post = mysql_fetch_assoc($pquery);
		if(isset($_POST['content'])) {
			$poster_uid = intval($post['poster_uid']);
			$uq = "SELECT permissions FROM users WHERE uid = ".$poster_uid;
			$uquery = mysql_query($uq) or die(mysql_error());
			$post_user = mysql_fetch_assoc($uquery);
			if($loggedIn && !$post['hidden'] && ($poster_uid === $login_uid || (intval($user_info['permissions']) >= intval($post_user['permissions'] && intval($user_info['permissions']) > 0)))) {
				$q = "UPDATE posts SET content = \"".mysql_real_escape_string($_POST['content'])."\" WHERE id = $post_id";
				$query = mysql_query($q) or die(mysql_error());
				//$formatIt = true;
			}
		}
		$q = "SELECT content, hidden FROM posts WHERE id = $post_id";
		$query = mysql_query($q) or die(mysql_error());
		$post = mysql_fetch_assoc($query);
		if($post) {
			$originalPost = $post['content'];
			if(!$post['hidden']) {
				
				echo $originalPost;
			}
		}
	}
}
else if(isset($_GET['thread'])) {
	$thread_id = intval($_GET['thread']);
	if($thread_id > 0) {
		$tq = "SELECT creator FROM threads WHERE id = ".$thread_id."";
		$tquery = mysql_query($tq) or die(mysql_error());
		$thread = mysql_fetch_assoc($tquery);
		if($loggedIn && isset($_POST['title'])) {
			$creator = intval($thread['creator']);
			$uq = "SELECT permissions FROM users WHERE uid = ".$creator;
			$uquery = mysql_query($uq) or die(mysql_error());
			$creator_user = mysql_fetch_assoc($uquery);
			if($creator === $login_uid || (intval($user_info['permissions']) >= intval($creator_user['permissions']) && intval($user_info['permissions']) > 0)) {
				$q = "UPDATE threads SET title = \"".mysql_real_escape_string($_POST['title'])."\" WHERE id = $thread_id";
				$query = mysql_query($q) or die(mysql_error());
				//$formatIt = true;
			}
		}
		$q = "SELECT title FROM threads WHERE id = $thread_id";
		$query = mysql_query($q) or die(mysql_error());
		$thread = mysql_fetch_assoc($query);
		if($thread) {
			echo $thread['title'];
		}
	}
}
