<?php
function getNextReference($prefix) {
    $year = date('Y');
    $counterFile = __DIR__ . "/{$prefix}-counter.txt";

    $handle = fopen($counterFile, 'c+');

    if (!$handle) {
        throw new Exception("Unable to open counter file");
    }

    flock($handle, LOCK_EX);

    rewind($handle);
    $lastNumber = trim(stream_get_contents($handle));
    $lastNumber = $lastNumber === '' ? 0 : (int)$lastNumber;
    $nextNumber = $lastNumber + 1;

    ftruncate($handle, 0);
    rewind($handle);
    fwrite($handle, (string)$nextNumber);
    fflush($handle);

    flock($handle, LOCK_UN);
    fclose($handle);

    return sprintf('%s-%06d', $prefix, $nextNumber);
}
