<!DOCTYPE html>
<html>
	<head>
		<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>
		<?php
			require 'settings.php';

			if ($password && (!isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_PW'] != $password)) {
				header('WWW-Authenticate: Basic realm="bbn"');
				header('HTTP/1.0 401 Unauthorized');
				echo '<p>Access denied.</p>';
				exit;
			}

			session_start();

			function savenote($title, $content)
			{
				global $dir;
				file_put_contents($dir . '/' . $title, $content);
				$key = array_search($dir . '/' . $title, $_SESSION['index']);
				if ($key)
				{
					// handle the rename case
					array_splice($_SESSION['index'], $key, 1);
					array_unshift($_SESSION['index'], $dir . '/' . $title);
				}
			}

			$action = '';

			if (isset($_GET['open']))
			{
			  $action = 'open';
			}
			else if (isset($_GET['search']))
			{
			$action = 'search';
			}
			else if (isset($_GET['tags']))
			{
			$action = 'tags';
			}
			else if (isset($_GET['clip']))
			{
			$action = 'clip';
			}
			else if (isset($_POST['save']))
			{
			$action = 'save';
			}
			else if (isset($_POST['delete']))
			{
			$action = 'delete';
			}
			else if (isset($_POST['home']))
			{
				$action = 'save';
			}
			else if(isset($_GET['home']))
			{
				$action = '';
			}
			else if (isset($_POST['preview']))
			{
			  $action = 'preview';
			}

			$content = '';
			if ($action == 'clip' && $_GET['param'])
			{
			 	$content = $_GET['param'] . "\r\n" . file_get_contents($dir . '/todo');
				savenote('todo', $content);
				$_GET['param'] = '';
			}
			if ($action == 'save')
			{
				$title = $_POST['title'];
				$content = $_POST['content'];
				savenote($title, $content);

				$previoustitle = $_POST['previoustitle'];
				if ($title != $previoustitle)
				{
					rename($dir . '/' . $previoustitle, $dir . '/' . $previoustitle . '.del');
				}

				if (isset($_POST['home']))
				{
					$action = '';
				}
				else
				{
					$action = 'open';
					$_GET['param'] = $title;
				}
			}
			else if ($action == 'delete')
			{
				$title = $_POST['title'];
				rename($dir . '/' . $title, $dir . '/' . $title . '.del');
				// reindex!
			}

			if ($action == 'preview')
			{
				require 'libs/Parsedown.php';
				$title = $_POST['title'];
				$content = $_POST['content'];
				$pos = 0;
				if (str_starts_with($content, '---'))
				{
					$pos = strpos($content, '---', 3);
				}
				$Parsedown = new Parsedown();
				$Parsedown->setBreaksEnabled(true);
				echo $Parsedown->text('# ' . $title . "\r\n" . substr($content, $pos + 3));
			}
			else if ($action == 'open')
			{
			  $title = $_GET['param'];
				$now = date("Y-m-d H.i.s", time());
				if (!$title)
				{
					$title = $now;
				}

				if (!file_exists($dir . '/' . $title))
				{
					$content = "---\r\ndate: " . substr($now, 0, 10) . "\r\ntags: \r\n---\r\n";
					savenote($title, $content);
				}
				else if (!$content)
				{
					$content = file_get_contents($dir . '/' . $title);
				}

				$lines = substr_count($content, "\r\n") + 1;
				$words = $lines + substr_count($content, " ");
				$rows = max(20, $lines) * 2;
				$length = strlen($content);

				require('note.php');

				$links = array();
				if (preg_match_all('/\[\[(.*)\]\]/', $content, $links, PREG_SET_ORDER))
				{
					echo '<div>Internal links:</div>';
					foreach($links as $link)
					{
						echo '<div>
						<a href="index.php?open=true&param=' . urlencode($link[1]) . '">' . $link[1] . '</a>
						</div>';
					}
					echo '<br>';
				}
				$links = array();
				if (preg_match_all('/https:(.*)[ \r]/', $content, $links, PREG_SET_ORDER))
				{
					echo '<div>External links:</div>';
					foreach($links as $link)
					{
						echo '<div>
						<a target="_blank" href="https:' . $link[1] . '">https:' . $link[1] . '</a>
						</div>';
					}
					echo '<br>';
				}

				echo '<span class="grey">' . $title . ' - ' . $now . ' - ' . $length . 'c - ' . $words . 'w - ' . $lines . 'l </span>';
			}
			else
			{
				if (isset($_GET['param']))
				{
					$param = $_GET['param'];
				}
				require('home.php');

				echo '<div>';

				if (!isset($_SESSION['index']) || isset($_GET['reindex']))
				{
					$files = glob($dir . '/*');
					usort($files, function($a, $b)
					{
						return filemtime($b) - filemtime($a);
					});
					$_SESSION['index'] = $files;
				}

				foreach($_SESSION['index'] as $path)
				{
					$tags = '';
					$name = basename($path);
					if (!str_ends_with($name, '.del'))
					{
						if ($action == 'search' || $action == 'tags')
						{
							$content = file_get_contents($path);

							if (($action == 'search' && !str_contains(strtolower($content), strtolower($param)) && !str_contains(strtolower($name), strtolower($param)))
								|| ($action == 'tags' && !preg_match('/tags:.*' . $param . '/i', $content)))
							{
								continue;
							}
						}
						echo '<div><a href=index.php?open=true&param=' . urlencode($name) . '>' . $name .'</a>';
						if ($action == 'tags')
						{
							$tags = array();
							$hastags = preg_match_all('/tags:(.*)/i', $content, $tags, PREG_SET_ORDER);
							if ($hastags)
							{
								$tagslist = explode(',', $tags[0][1]);
								echo '<span class="grey"> ';
								foreach ($tagslist as $tag)
								{
									$tag = trim($tag);
									echo('<a class="grey" href="index.php?tags=true&param=' . $tag . '">' . $tag . '</a> ');
								}
								echo '</span>';
							}
						}
						else if ($action == 'search' && str_contains(strtolower($content), strtolower($param)))
						{
							$pos = strpos(strtolower($content), strtolower($param));
							echo '<span class="grey"> ' . $param . substr($content, $pos + strlen($param), 42) . '</span>';
						}
						echo'</div>';
					}
				}

				echo '</div>';
			}
		?>
	</body>
</html>