<?php
function generatePjnum() {
    require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
    $pdo = db_connect();

    $today = date('ymd');
    $prefix = "KD-PR-$today";

    $sql = "SELECT pjnum FROM estimate WHERE pjnum LIKE :likepattern AND is_deleted IS NULL ORDER BY pjnum DESC LIMIT 1";
    $stmh = $pdo->prepare($sql);
    $stmh->bindValue(':likepattern', "$prefix%", PDO::PARAM_STR);
    $stmh->execute();

    $lastPjnum = $stmh->fetchColumn();

    if ($lastPjnum && preg_match('/-(\d{2})$/', $lastPjnum, $matches)) {
        $lastSerial = (int)$matches[1];
        $newSerial = str_pad($lastSerial + 1, 2, '0', STR_PAD_LEFT);
        return "$prefix-$newSerial";
    } else {
        return "$prefix-01";
    }
}
