<?php
require '../assets/db_connect.php';
header('Content-Type: application/json');

$prefix = "INV";
$today = date('Ymd');

// Get the last invoice for today
$stmt = $pdo->prepare("SELECT invoice_no FROM sales WHERE invoice_no LIKE ? ORDER BY id DESC LIMIT 1");
$stmt->execute(["$prefix-$today-%"]);
$last = $stmt->fetch(PDO::FETCH_ASSOC);

if ($last) {
    // Extract sequence number
    $parts = explode('-', $last['invoice_no']);
    $seq = intval(end($parts)) + 1;
} else {
    $seq = 1;
}

$invoice_no = $prefix . '-' . $today . '-' . str_pad($seq, 4, '0', STR_PAD_LEFT);

echo json_encode(['invoice_no' => $invoice_no]);
