<?php
header( 'Content-Type: text/html; charset=utf-8' );

$dataFile = __DIR__ . '/changelog-data.html';
if ( !file_exists( $dataFile ) ) {
    echo '';
    exit;
}

$html = file_get_contents( $dataFile );
if ( $html === false ) {
    echo '';
    exit;
}

// Parse entries by splitting on <hr> tags
$blocks = preg_split( '/<hr\s*\/?>/', $html );
$entries = [];

foreach ( $blocks as $block ) {
    $block = trim( $block );
    if ( empty( $block ) ) {
        continue;
    }
    // Extract version number from <b>ver. X.XXX
    if ( preg_match( '/<b>ver\.\s*([\d.]+)/', $block, $m ) ) {
        $entries[] = [
            'version_int' => (int) round( (float) $m[1] * 1000 ),
            'html'        => $block,
        ];
    }
}

// If ?ver= parameter is provided, show only 5 versions back from that version
$ver = isset( $_GET['ver'] ) ? (int) round( (float) $_GET['ver'] * 1000 ) : 0;

if ( $ver > 0 ) {
    $lowerBound = $ver - 5;

    $filtered = [];
    foreach ( $entries as $entry ) {
        if ( $entry['version_int'] > $lowerBound ) {
            $filtered[] = $entry;
        }
    }
    $entries = $filtered;
}

// Output
foreach ( $entries as $entry ) {
    echo $entry['html'] . "\n<hr>\n";
}
