<?php
declare(strict_types=1);

$postsDir = __DIR__ . '/posts/';
$posts = [];

// scan markdown files
foreach (glob($postsDir . '*.md') as $file) {
    $filename = basename($file, '.md');
    $content = file_get_contents($file);

    // extract first markdown H1
    if (preg_match('/^#\s+(.+)$/m', $content, $matches)) {
        $title = trim($matches[1]);
    } else {
        $title = $filename;
    }

    $posts[] = [
        'slug' => $filename,
        'title' => $title,
        'time' => filemtime($file),
    ];
}

// sort newest first
usort($posts, fn($a, $b) => $b['time'] <=> $a['time']);
?>
<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog</title>
    <link rel="stylesheet" href="../style.css">
<script src="https://unpkg.com/cursor-effects@latest/dist/browser.js"></script>

<script>
window.addEventListener("load", (event) => {
  new cursoreffects.ghostCursor();
});
</script>

</head>
<body>
<div class="container bio">
  <h1>📝 Blog 💻</h1>

<img src="../shutdown.gif" class="small-pic">
<p class="center">Blog posts:</p>
  <?php if (empty($posts)): ?>
    <p>Brak wpisów.</p>
  <?php else: ?>
    <ul class="post-list">
      <?php foreach ($posts as $post): ?>
          <a href="/blog/blog.php?b=<?= htmlspecialchars($post['slug']) ?>">
            <?= htmlspecialchars($post['title']) ?>
          </a>
          <time datetime="<?= date('c', $post['time']) ?>">
            <?= date('Y-m-d', $post['time']) ?>
          </time>
            <br>
      <?php endforeach; ?>
    </ul>
  <?php endif; ?>
<p class="center">Other thingies:</p>
          <a href="/blog/video_games.php">Video Game ranking          </a>
            <br>

</div>
</main>

    <footer>
        <p class="center"><img src="../favicon.ico">(c) computer_glamour</p>
    
    <img src="../buttons/-18.gif" class="footer-button">
    <img src="../buttons/xmpp.gif" class="footer-button">
    <img src="../buttons/notread.gif" class="footer-button">
    <img src="../buttons/right2repair.gif" class="footer-button">

    </footer>

</body>
</html>
