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

	function cleanstring($string)
	{
		return iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', strtolower($string));
	}

	function downloadall()
	{
		$zip = new ZipArchive();
		$zip_name = 'bbn.zip';
		$zip->open($zip_name,  ZipArchive::CREATE);
		foreach($_SESSION['index'] as $path)
		{
			if (!str_ends_with($path, '.del'))
			{
				$path = $path . '.md';
				if (file_exists($path))
				{
					$zip->addFile($path, basename($path));
				}
			}
		}
		$zip->close();

		header('Content-disposition: attachment; filename=' . $zip_name);
		header('Content-type: application/zip');
		readfile($zip_name);

		unlink($zip_name);
	}

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

	$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>
		<div>
			<a href="note.php?new" class="grey" accesskey="n">new</a>
			<a href="index.php?download" class="grey" accesskey="d">download</a>
			<input form="home" placeholder="filter..." autofocus autocomplete="off" class="title" name="filter" value="<?php echo $filter; ?>" form="home">
			<form action="index.php" method="GET" id="home">
				<input hidden type="submit">
			</form>
		</div>

		<div>
		<?php
			$index = 1;
			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) . ' ';
				if ($index < 10)
				{
					echo 'accesskey="' . $index .'" ';
				}
				$index++;
				echo '>' . $name .'</a>';
				if ($filter && str_contains(cleanstring($content), cleanstring($filter)))
				{
					$pos = strpos(cleanstring($content), cleanstring($filter));
					$start = max($pos - 21, 0);
					echo '<span class="grey">&nbsp;';
					echo substr($content, $start, min(21, $pos));
					echo '<b>' . $filter . '</b>';
					echo substr($content, $pos + strlen($filter), 21);
					echo '</span>';
				}
				echo'</div>';
			}
		?>
		</div>
	</body>
</html>