<?php
    require("../libs/markdown.php");
	function comments($typer, $idr) {
	    $ref = 1732684297;
 		global $username;
		global $db;
		$page = array_key_exists('page',$_GET) ? ($_GET['page']) : 0;
		if ($username) {
			form("Broadcast your thoughts...", '', array(
				array('key' => 'Your message', 'type' => 'textarea', 'name' => 'post', 'default' => ''),
				array('key' => '','type' => 'hidden','name' => 'type', 'default' => $typer),
				array('key' => '','type' => 'hidden','name' => 'id', 'default' => $idr) 
			),'/index.php');
		}
		?>

		<div>
		<?php if ($page > 0) { ?>
			<a class="form-button" href="?id=<?php echo htmlspecialchars($_GET['id'])?>&page=<?php echo $page - 1 ?>">Previous</a>
		<?php } ?>
		<a class="form-button" href="?id=<?php echo htmlspecialchars($_GET['id'])?>&page=<?php echo $page + 1 ?>">Next</a>
		</div>

		<?php
			$stmt = $db->prepare("SELECT * FROM comment WHERE targetType = ? AND targetId = ? ORDER BY date DESC LIMIT ? OFFSET ?");
			$stmt->execute([
				$typer,
				$idr,
				10,
				$page * 10
			]);
			
			$posts = $stmt->fetchAll(PDO::FETCH_DEFAULT);

			foreach ($posts as $post) { ?>
				<div class='comment'>
					<div class='avatar'>
						<img src='/pfp/<?php echo $post['username'] ?>.png' class='avatar-img'>
						<div>
							<div><b>
									<a class='link' href='/user.php?id=<?php echo $post['username'] ?>'>
										<?php echo $post['username'] ?>
									</a>
								</b></div>
							<div><b>
									<?php echo date(DATE_ATOM,$post['date'] + $ref) ?>
								</b></div>
						</div>
					</div>
					<pre><?php echo markdown(htmlspecialchars($post['content'])) ?></pre>
				</div>
			<?php }
	}		
?>