<?php
// ajax_get_next_po_code.php
include("../classes/manager.class.php");
header('Content-Type: application/json');
$m = new Manager();
if (!isset($_SESSION['sess_userid'])) {
  echo json_encode(['ok' => false, 'error' => 'auth']);
  exit;
}

$date = isset($_GET['date']) ? $_GET['date'] : ''; // expected: YYYY-MM-DD
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
  echo json_encode(['ok' => false, 'error' => 'bad_date']);
  exit;
}

$ymd = date('Ymd', strtotime($date));
global $db;
$tbl = TABLE_PURCHASEORDER;

// Get the highest 2-digit suffix for this date
$query = "
  SELECT po_code
  FROM {$tbl}
  WHERE po_date = '$date'
    AND po_code LIKE 'PO-{$ymd}%'
  ORDER BY CAST(RIGHT(po_code, 2) AS UNSIGNED) DESC
  LIMIT 1
";
$row = $db->query_first($query);

$last = 0;
if ($db->affected_rows > 0 && $row) {
  $poCode = is_object($row) ? $row->po_code : (isset($row['po_code']) ? $row['po_code'] : '');
  $last   = (int)substr($poCode, -2); // last two digits
}
$next = $last + 1;
$code = 'PO-' . $ymd . str_pad($next, 2, '0', STR_PAD_LEFT);

echo json_encode(['ok' => true, 'code' => $code]);
