<?php
// lib/next_number.php
function get_next_number(mysqli $db, string $series): string {
    // map series → default prefix
    $prefixMap = ['center' => 'NEC-', 'reference' => 'EC-'];
    if (!isset($prefixMap[$series])) {
        throw new RuntimeException("Unknown series: $series");
    }

    // we need a row lock so two requests can't grab the same number
    $db->begin_transaction();

    try {
        // 1) make sure a row exists (idempotent)
        $ins = $db->prepare("
            INSERT IGNORE INTO number_counters (name, prefix, last_val)
            VALUES (?, ?, 199)
        ");
        $ins->bind_param("ss", $series, $prefixMap[$series]);
        $ins->execute();
        $ins->close();

        // 2) lock row and get current last_val
        $sel = $db->prepare("
            SELECT prefix, last_val
            FROM number_counters
            WHERE name = ?
            FOR UPDATE
        ");
        $sel->bind_param("s", $series);
        $sel->execute();
        $sel->bind_result($prefix, $last);
        if (!$sel->fetch()) {
            throw new RuntimeException("Counter row missing for $series");
        }
        $sel->close();

        // 3) bump and persist
        $next = $last + 1;
        $upd = $db->prepare("UPDATE number_counters SET last_val = ? WHERE name = ?");
        $upd->bind_param("is", $next, $series);
        $upd->execute();
        $upd->close();

        $db->commit();
        return $prefix . $next; // e.g. NEC-200
    } catch (Throwable $e) {
        $db->rollback();
        throw $e;
    }
}
