<?php
// get_next_invoice.php
session_start();
require '../assets/db_connect.php';

try {
    // Get last invoice
    $stmt = $pdo->query("SELECT invoice_no FROM sales ORDER BY id DESC LIMIT 1");
    $last_invoice = $stmt->fetchColumn();

    $datePart = date('Ymd'); // e.g., 20251114

    if ($last_invoice && preg_match('/INV-(\d{8})-(\d+)/', $last_invoice, $matches)) {
        if ($matches[1] == $datePart) {
            $nextNumber = str_pad($matches[2]+1, 3, '0', STR_PAD_LEFT);
        } else {
            $nextNumber = '001';
        }
    } else {
        $nextNumber = '001';
    }

    $invoice_no = "INV-{$datePart}-{$nextNumber}";

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

} catch(Exception $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
