<?php
include 'auth.php';

header('Content-Type: application/json');

$meta_file = __DIR__ . '/invoices/meta.json';
$meta = file_exists($meta_file) ? json_decode(file_get_contents($meta_file), true) : [];

if (empty($meta)) {
    echo json_encode(['latest_number' => '0000']);
    exit;
}

// 获取所有账单编号并找到最大的数字编号
$numbers = array_keys($meta);
$max_number = 0;

foreach ($numbers as $number) {
    // 提取数字部分
    if (preg_match('/(\d+)/', $number, $matches)) {
        $num = intval($matches[1]);
        if ($num > $max_number) {
            $max_number = $num;
        }
    }
}

// 返回下一个编号（当前最大编号+1），格式化为4位数
$next_number = str_pad($max_number + 1, 4, '0', STR_PAD_LEFT);
echo json_encode(['latest_number' => $next_number]);
?>