<?php 

session_start();

include("include/settings.php");

$db = new SQLite3('ask.db');

$p_user = $db->query("SELECT * FROM users WHERE username = '" . $_GET["q"] . "';")->fetchArray(SQLITE3_ASSOC);
if(!$p_user || $p_user["id"] == 0){ // Test if user exists or if it is the id 0, anonymous
	include("404.php");
	die();
}

if(isset($_SESSION["uid"])){
	if($_SESSION["uid"] == $p_user["id"]){
		$is_current_user = true;
	}
}
?>

<html>
<head>
	<?php include("themes/$theme_name/user.php"); ?>
	<title><?= $p_user["username"] ?> | LibreCat</title>
</head>
<body> 
	<?php // print_profile($p_user); ?>
	<?php include("include/header.php"); ?>
	<div id="parent-container">
		<div id="user-container">
			<p id="user-name"><?= $p_user["username"] ?></p>
			<p class="user-bio"><?php
//			if($p_user["bio"]) echo($p_user["bio"]);
//			else echo("This is a sample bio, please change me, this is just to test the layout.");
		?></p>
	<?php
		if($is_current_user){
			echo("<br/>");
			if($fancy_urls){
				echo("<a href='/config/profile'>config</a>");
				echo(" - ");
			 	echo('<a target="_blank" href="https://twitter.com/share?text=Ask%20me%20something&url=https%3A%2F%2Fask.fai.su%2Fuser%2F' . $p_user["username"] . '&ref_src=twsrc%5Etfw">share on twitter</a>');
			}
			else{
				echo("<a href='/config.php?q=profile'>config</a>");
			}
		}
	?>
	</div>
	<?php


		/** QUESTION HIGHLIGHT **/

if(isset($_GET["p"])){

		//Get info about the question
	$h_question = $db->query("SELECT * FROM questions WHERE id = " . $_GET["p"] . ";")->fetchArray(SQLITE3_ASSOC);
	$h_user = $db->query("SELECT * FROM users WHERE id = " . $h_question["by"] . ";")->fetchArray(SQLITE3_ASSOC);

	$q_key = md5($h_question["question"]);
	if($p_user["id"] == $h_question["user"] and ($h_question["private"] != 1 or $q_md5 != $_GET["key"] or $is_current_user)){ // Only show question that are for this user

		echo('<div class="highlighted-post">');

		echo('<div class="question-body">');

		$time = new DateTime("@0");

			// Title
		echo("<p class='question-username'>");
		if($h_user["id"] == 0){ // no link if anonymous
			echo($h_user["name"]);
		}
		else{
			$new_get["q"] = $h_user["name"];
			echo("<a href='" . redirect("user", $new_get) . "'>" . $h_user["name"] ."</a>\n");
		}
		echo(" asked:</p>");

			// Actual question text
		echo("\t<p class='question-text'>". $h_question["question"] ."</p>\n");
			
			// Footer	
		if($is_current_user){
			echo("\t<a href='/action/reply.php?q=".$h_question["id"]."'>reply</a> ");
			echo("\t<a href='/action/delete-question.php?q=".$h_question["id"]."'>delete</a> ");
			echo("fav ignore ");
		}
			
			// Time
		$time->settimestamp($h_question["q_date"]);
		echo('<p class="question-date">');
		echo('<a href="?p=' . $h_question["id"] . '">' . $time->format('Y-m-d h:i:s') . '</a>');
		echo('</p>');

		echo('</div>'); // question-body
	
			
			/* Answer */

		if($h_question["answer"]){
			echo("<div class='answer'>");
				echo('<p class="title">' . $p_user["name"] . ' answered:');

				echo("<p class='answer-text'>" . $h_question["answer"] . "</p>");

				$time->settimestamp($h_question["a_date"]);
				echo("<p class='answer-date'>" . $time->format("Y-m-d h:i:s") . "</p>");
			echo("</div>");
		}


		echo('</div>'); // highlighted-post
	}
}
	?>

		<div class="columns-container">
			<div class="column form-column">
			<form name="input" action="/action/publish-question.php" method="post">
				<textarea placeholder="Ask me anything!" id="post-text" name="post-text"></textarea>
				<br/>
				<input type="hidden" name="uid" value="<?= $p_user["id"] ?>"/>
				<p><input type="checkbox" <?php if(!isset($_SESSION["uid"])) echo("checked disabled"); ?> name="anon"/> Post anonymously</p>
				<p><input type="checkbox" name="priv"/> Private</p>
				<?php if(isset($errorMsg)) echo "<p>$errorMsg</p>\n"; ?>
				<input type="submit" value="Ask" name="post-submit"/>
			</form>
		</div>
		
		<div class="question-container column">
<?php
		if(!$_GET["page"]) $_GET["page"] = 1;
		$p_limit = 10; // TODO: Make the limit variable
		$p_offset = ($_GET['page'] - 1) * $p_limit; // SQLite3 unsertands offsets in units, not pages

		if(!$p_offset || $p_offset <= 0) $p_offset = 0;
		// TODO: Build a mechanism to make off-limits pages show as the last one
		


		$private_filter = "";
		if(!$is_current_user) $private_filter = "AND private IS NOT 1 AND answer IS NOT NULL";
		

		$q_count = $db->query('SELECT COUNT(*) FROM questions WHERE user = "' . $p_user["id"] . '";')->fetchArray(SQLITE3_ASSOC)['COUNT(*)'];

		$u_prep = $db->prepare("SELECT * FROM users WHERE id = :id");
		$qs = $db->query("SELECT * FROM questions WHERE user = '". $p_user["id"] . "' " . $private_filter . " ORDER BY id DESC LIMIT ". $p_limit ." OFFSET ". $p_offset .";");


				/** QUESTIONS MAIN LOOP **/


		$time = new DateTime("@0");
		$tmp_get = $_GET;
		while($current = $qs->fetchArray(SQLITE3_ASSOC)){

				// Execute prepared statement
			$u_prep->bindValue(":id", $current["by"], SQLITE3_INTEGER);
			$q_user = $u_prep->execute()->fetchArray(SQLITE3_ASSOC);

			echo("\t\t\t");
			echo("<div class='question'>\n");

				// Question username
			echo("\t\t\t\t");
			echo("<p class='question-username'>" );
			if($q_user["id"] == 0){ // no link if anonymous
				echo($q_user["name"]);
			}
			else{
				$new_get["q"] = $q_user["name"];
				echo("<a href='" . redirect("user", $new_get) . "'>" . $q_user["name"] ."</a>");
			}
			if($current["private"] == 1){
				echo(" ");
				echo("<span class='question-private'>(private)</span>");
			}
			echo("</p>\n");


				// Actual text body
			echo("\t\t\t\t");
			echo("<p class='question-text'>". $current["question"] ."</p>\n");


				/* Question footer */

			echo("\t\t\t\t");
			echo('<div class="question-footer">');
			echo("\n");
					// Actions
			if($is_current_user){
				echo("\t\t\t\t\t");
				echo("<a href='/action/reply.php?q=".$current["id"]."'>reply</a>\n");
				echo("\t\t\t\t\t");
				echo("<a href='/action/delete-question.php?q=".$current["id"]."'>delete</a>\n");
				echo("\t\t\t\t\t");
				echo("fav\n");
			}
					// Time
			$time->settimestamp($current["q_date"]);
			echo("\t\t\t\t\t");
			$tmp_get["p"] = $current["id"];
			if($current["private"] == 1) $tmp_get["key"] = md5($current["question"]);
			echo('<a href="' . redirect("user", $tmp_get) . '">');
			echo("<p class='question-date'>" . $time->format("Y-m-d h:i:s") . "</p>");
			echo("</a>\n");
			
			echo("\t\t\t\t");
			echo("</div>\n"); // Footer


				/* Answer */
	
			if($current["answer"]){
				echo("\t\t\t\t");
				echo("<div class='answer'>\n");

				echo("\t\t\t\t\t");
				echo(nl2br("<p class='answer-text'>" . $current["answer"] . "</p>\n"));

				$time->settimestamp($current["a_date"]);
				echo("\t\t\t\t\t");
				echo("<p class='answer-date'>" . $time->format("Y-m-d h:i:s") . "</p>\n");

				echo("\t\t\t\t");
				echo("</div>\n");
			}

			echo("\t\t\t");
			echo("</div>\n"); // Question
			echo("\n");
		}


			/* PAGE SELECTOR */
		// ps_* means Page Selector

		$p_total = ceil($q_count / $p_limit);
		$ps_margin = 2; // Amount of page numbers to show after and before the actual one
		
			// Limit displayed numbers to the existing ones (bound logic)
		if($_GET["page"] - $ps_margin <= 1) $ps_init = 1;
		else if($_GET["page"] + $ps_margin > $p_total) $ps_init = $p_total - $ps_margin * 2;
		else $ps_init = $_GET["page"] - $ps_margin;

		$ps = "";
		$ps .= "<div class='page-selector'>\n";

		function ps_item($label, $link){
			$ps_item = "";

			if($link){
				$tmp_get = $_GET;
				$tmp_get["page"] = $link;
				$link_init = "<a href='" . redirect("user", $tmp_get) . "'>";

				$label = $link_init . $label . "</a>";
			}

			$ps_item = "\t<div class='ps_item'>" . $label . "</div>\n";

			return $ps_item;
		}

		// "|<" and "<"
		if($ps_init > 1)						$ps .= ps_item("|<", 1);
		if($_GET["page"] > 1)						$ps .= ps_item("<", $_GET["page"] - 1);

		// Numbers
		for($i = $ps_init;  $i <= $ps_init + $ps_margin * 2 && $i <= $p_total && $p_total != 1; $i++){
			if($i == $_GET["page"]) 				$ps .= ps_item($i, "");
			else							$ps .= ps_item($i, $i);
		}

		// ">" and ">|"
		if($_GET["page"] < $p_total)					$ps .= ps_item(">", $_GET["page"] + 1);
		if($ps_init + $ps_margin * 2 < $p_total)			$ps .= ps_item(">|",$p_total);

		$ps .= "</div>\n";

		echo $ps;
	?>
	</div>
</div>
</div>
	<div id="footer">
		<p>
			Powered by Librecat, under the GPL3 license.
			Source code: <a href="https://git.fai.su/dendy/librecat">https://git.fai.su/dendy/librecat</a>
		</p>
	</div>
</body>
</html>