<!-- Widget "Archiv" -->

<?php
	function FillWidgetArchive()
	{
		global $locale;

		global $indexFile;
		global $fileTypes;
		global $filePublished;
		global $fileDates;

		$filterMonth = htmlspecialchars($_GET['month'] ?? '');
		$filterYear = !empty($filterMonth) ? substr($filterMonth, 0, 4) : '';

		$years = [];
		$monthNamesShort = [];
		for ($m = 0; $m <12; $m++)
		{
			$formatter = new IntlDateFormatter($locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE);
			$formatter->setPattern("LLL");
			$monthNamesShort[$m] = $formatter->format(new DateTime("2000-" . $m +1 . "-01"));
		}

		if (count($fileDates) > 0)
		{
			foreach ($fileDates as $file => $date)
			{
				$type = def_type($fileTypes[$file] ?? null);
				$published = def_published($filePublished[$file] ?? null);

				if (($type === 'post' || $type === 'page') && $published)
				{
					$date_parts = explode('-', $date);
					$year = $date_parts[0];
					$month = $date_parts[1] + 0;

					if (!array_key_exists($year, $years))
						$years[$year] = [];
					if (!array_key_exists(0, $years[$year]))
						$years[$year][0] = 1;
					else
						$years[$year][0]++;
					if (!array_key_exists($month, $years[$year]))
						$years[$year][$month] = 1;
					else
						$years[$year][$month]++;
				}
			}

			foreach ($years as $year => $months)
			{
				$open = ($year == $filterYear) ? 'open' : '';
				echo '<details class="archive" ' . $open . '>';
				echo '<summary><span class="summary">' . $year . '</span> (' . $months[0] . ')</summary>';
				echo "<div>";
				for ($m = 12; $m >= 1; $m--)
				{
					$monthNameShort = array_key_exists($m - 1, $monthNamesShort) ? $monthNamesShort[$m - 1] : '???';
					if (array_key_exists($m, $months))
						echo '<span class="item"><a href="./' . $indexFile . '?month=' . sprintf('%04d-%02d', $year, $m) . '" title="' . $months[$m] . ' ' . GetString('Articles') . '">' . $monthNameShort  . '</a></span>';
					else
						echo '<span class="item">' . $monthNameShort  . '</span>';
				}
				echo '</div>';
				echo '</details>';
			}
		}
	}

	FillWidgetArchive();
?>

