<?php
header('Content-Type: application/json');
include_once('../includes/config.php');

// Get the last customer ID from the database
$query = "SELECT CustomerID FROM tblcustomers ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($con, $query);

if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $lastCustomerID = $row['CustomerID'];
    
    // Extract the numeric part and increment
    $numericPart = (int)substr($lastCustomerID, 4); // Remove 'CUST' prefix
    $nextNumericPart = $numericPart + 1;
    $nextCustomerID = 'CUST' . str_pad($nextNumericPart, 3, '0', STR_PAD_LEFT);
} else {
    // No customers exist, start with CUST001
    $nextCustomerID = 'CUST001';
}

echo json_encode([
    'success' => true,
    'customerID' => $nextCustomerID
]);
?>
