Sorting isn't working correctly with this script. Sometimes posts get "stickied" at the top instead of the proper sorting order of newest post at the top

<?php
// Include Parsedown and YAML parser
require_once __DIR__ . '/includes/Parsedown.php';
require_once __DIR__ . '/includes/YAMLParser.php';

$posts_dir = __DIR__ . '/posts/';
$posts_per_page = 5;

// Get all Markdown files from the posts directory
$all_files = glob($posts_dir . '*.md');

// Function to extract the date from the YAML front matter
function getPostDate($file) {
    $content = @file_get_contents($file);
    if ($content === false) {
        return null;
    }
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Separate YAML front matter and Markdown content
    if (preg_match('/^---(.*?)---/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        if (is_array($yaml) && isset($yaml['date'])) {
            $date = DateTime::createFromFormat('Y-m-d', $yaml['date']);
            if ($date) {
                return $date;
            }
        }
    }
    return null; // No valid date found
}

// Sort files by creation date from YAML front matter, newest first
usort($all_files, function($a, $b) {
    $dateA = getPostDate($a);
    $dateB = getPostDate($b);

    if ($dateA === null && $dateB === null) {
        return 0; // Both files have no date, treat them as equal
    }
    if ($dateA === null) {
        return 1; // Move files without dates to the end
    }
    if ($dateB === null) {
        return -1;
    }

    // Compare timestamps instead of DateTime objects directly
    return $dateB->getTimestamp() <=> $dateA->getTimestamp(); // Sort in descending order
});


// Pagination
$total_posts = count($all_files);
$total_pages = max(ceil($total_posts / $posts_per_page), 1);

// Get current page from query parameter with validation
$current_page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
    'options' => [
        'default'   => 1,
        'min_range' => 1,
        'max_range' => $total_pages,
    ],
]);

// Calculate the offset
$offset = ($current_page - 1) * $posts_per_page;

// Slice the array of files for the current page
$files = array_slice($all_files, $offset, $posts_per_page);

// Instantiate Parsedown and enable safe mode to prevent XSS
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);

// Include the header
include __DIR__ . '/header.php';

// Display posts
foreach ($files as $file) {
    $content = @file_get_contents($file);
    if ($content === false) {
        continue;
    }
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Separate YAML front matter and Markdown content
    if (preg_match('/^---(.*?)---(.*)/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        $md_content = trim($matches[2]);
    } else {
        $yaml = [];
        $md_content = $content;
    }

    // Ensure $yaml is an array
    if (!is_array($yaml)) {
        $yaml = [];
    }

    // Generate a slug or unique identifier for the post
    $slug = isset($yaml['slug']) ? $yaml['slug'] : null;
    if (!$slug) {
        // Generate slug from the title or filename
        if (!empty($yaml['title'])) {
            $slug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($yaml['title']));
            $slug = trim($slug, '-');
        } else {
            $slug = pathinfo($file, PATHINFO_FILENAME);
        }
    }

    // Ensure the slug is URL-safe
    $slug = rawurlencode($slug);

    // Extract the content before the readmore tag
    $content_parts = explode('<!--more-->', $md_content);
    $intro = $content_parts[0];

    // Parse Markdown
    $html_intro = $parsedown->text($intro);

    // Display the post
    echo '<div class="post">';
    $title = htmlspecialchars($yaml['title'] ?? 'Untitled', ENT_QUOTES, 'UTF-8');
    echo '<h2><a href="post.php?slug=' . $slug . '">' . $title . '</a></h2>';

    if (!empty($yaml['date'])) {
        $date = DateTime::createFromFormat('Y-m-d', $yaml['date']);
        if ($date) {
            echo '<p class="date">' . htmlspecialchars($date->format('F j, Y'), ENT_QUOTES, 'UTF-8') . '</p>';
        }
    }

    echo $html_intro;
    if (count($content_parts) > 1) {
        // There's more content after the readmore tag
        echo '<p><a href="post.php?slug=' . $slug . '">Read more...</a></p>';
    }
    echo '</div>';
}

// Pagination controls
echo '<div class="pagination">';
if ($current_page > 1) {
    echo '<a href="?page=' . ($current_page - 1) . '">Previous</a> ';
}
for ($i = 1; $i <= $total_pages; $i++) {
    if ($i == $current_page) {
        echo '<span class="current-page">' . $i . '</span> ';
    } else {
        echo '<a href="?page=' . $i . '">' . $i . '</a> ';
    }
}
if ($current_page < $total_pages) {
    echo '<a href="?page=' . ($current_page + 1) . '">Next</a>';
}
echo '</div>';

// Include the footer
include __DIR__ . '/footer.php';