<?php
// Get the list of files in the current directory
$files = scandir(__DIR__);

// Filter the files to include only text files
$textFiles = array_filter($files, function($file) {
    return strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'txt';
});

// Sort the files by modified time in ascending order
usort($textFiles, function($a, $b) {
    return filemtime($a) - filemtime($b);
});

// Get the five newest text files
$newestFiles = array_slice($textFiles, -5);

// Check if there are at least five text files
if (count($newestFiles) < 2) {
    echo "There are not enough text files in the current directory.";
    exit;
}

$baseFile = $newestFiles[0];
$differences = [];

// Compare the contents of the text files with the base file
for ($i = 1; $i < count($newestFiles); $i++) {
    $file = $newestFiles[$i];
    $baseLines = file($baseFile, FILE_IGNORE_NEW_LINES);
    $lines = file($file, FILE_IGNORE_NEW_LINES);

    $difference = array_diff($lines, $baseLines);

    if (!empty($difference)) {
        $differences[] = [
            'baseFile' => $baseFile,
            'file' => $file,
            'difference' => $difference
        ];
    }
}

// Display the differences
echo "<h3>Differences between the five newest text files and the base file ($baseFile):</h3>";

echo "<div style='display: flex;'>";

foreach ($differences as $difference) {
    $baseFile = $difference['baseFile'];
    $file = $difference['file'];
    $differenceLines = $difference['difference'];

    echo "<table style='margin-right: 20px;'>";
    echo "<th>$file</th>";

    foreach ($differenceLines as $line) {
        echo "<tr>";
        echo "<td>$line</td>";
        echo "</tr>";
    }

    echo "</table>";
}

echo "</div>";