This blog script is sorting posts alphabetically when it's supposed to sort by creation date with newest first. Any ideas why that might be?

<?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 getPostDate($file) {
    $content = file_get_contents($file);
    if ($content === false) {
        error_log("Failed to read file: $file");
        return null;
    }
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Update regex to match YAML front matter more precisely
    if (preg_match('/^---[\s\n]*(.*?)\n---/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        if (is_array($yaml) && isset($yaml['date'])) {
            $dateStr = $yaml['date'];
            // Try parsing the date with time if available
            $dateFormats = [
                'Y-m-d\TH:i:sP', // ISO 8601 format
                'Y-m-d\TH:i:s',  // ISO 8601 without timezone
                'Y-m-d H:i:s',
                'Y-m-d H:i',
                'Y-m-d',
                'D, d M Y H:i:s O', // RFC 2822
            ];
            foreach ($dateFormats as $format) {
                $date = DateTime::createFromFormat($format, $dateStr);
                if ($date && $date->getLastErrors()['warning_count'] == 0 && $date->getLastErrors()['error_count'] == 0) {
                    return $date; // Return valid DateTime
                }
            }
            // Try using strtotime() as a last resort
            $timestamp = strtotime($dateStr);
            if ($timestamp !== false) {
                return (new DateTime())->setTimestamp($timestamp); // Return DateTime from timestamp
            } else {
                error_log("Failed to parse date '$dateStr' in file: $file");
            }
        } else {
            error_log("No valid 'date' field in YAML front matter in file: $file");
        }
    } else {
        error_log("No YAML front matter found in file: $file");
    }

    // No valid date found, use file modification time
    $mtime = filemtime($file);
    if ($mtime !== false) {
        return (new DateTime())->setTimestamp($mtime); // Return DateTime from file modification time
    }
    error_log("Failed to get file modification time for file: $file");
    return null; // No valid date found
}

usort($all_files, function($a, $b) {
    $dateA = getPostDate($a);
    $dateB = getPostDate($b);

    // Both dates are null
    if ($dateA === null && $dateB === null) {
        return 0; // Treat as equal
    }
    // Only $dateA is null
    if ($dateA === null) {
        return 1; // $b is newer, so $a goes after
    }
    // Only $dateB is null
    if ($dateB === null) {
        return -1; // $a is newer, so $a goes before
    }

    // Both dates are valid, compare timestamps
    return $dateB <=> $dateA; // 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\n]*(.*?)\n---[\s\n]*(.*)/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>';

    $date = getPostDate($file);
    if ($date) {
        echo '<p class="date">' . htmlspecialchars($date->format('F j, Y, g:i A'), 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';