<?php
	require('common.php');

	if (isset($_GET['download']))
	{
		downloadall();
	}

	$filter = '';
	if (isset($_GET['filter']))
	{
		$filter = $_GET['filter'];
	}
?>

<!DOCTYPE html>
<html>
	<head>
		<title>bbn</title>
		<link rel="manifest" href="manifest.json" />
		<meta name="theme-color" content="white" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="style.css">
	</head>
	<body>
		<form action="index.php" method="GET" id="home">
			<input hidden type="submit" accesskey="h">
		</form>
		<form action="note.php" method="GET" id="note"></form>

		<div>
			<input type="submit" name="new" value="new" accesskey="o" form="note">
			<input type="submit" name="download" value="download" accesskey="d" form="home">
			<br>
			<input placeholder="search..." autofocus autocomplete="off" class="title" name="filter" value="<?php echo $filter; ?>" form="home">
		</div>

		<div>
		<?php
			foreach($_SESSION['index'] as $path)
			{
				$name = basename($path);
				if (str_ends_with($name, '.del'))
				{
					continue;
				}

				if ($filter)
				{
					$content = file_get_contents($path . '.md');
					if (!str_contains(cleanstring($content), cleanstring($filter)) && !str_contains(cleanstring($name), cleanstring($filter)))
					{
						continue;
					}
				}

				echo '<div><a href=note.php?title=' . urlencode($name) . '>' . $name .'</a>';
				if ($filter && str_contains(cleanstring($content), cleanstring($filter)))
				{
					$pos = strpos(cleanstring($content), cleanstring($$filter));
					echo '<span class="grey"> ' . $filter . substr($content, $pos + strlen($filter), 42) . '</span>';
				}
				echo'</div>';
			}
		?>
		</div>
	</body>
</html>