<?php
header("Content-Type: application/json");
require_once "../config.php";

$response = ["status" => "error", "message" => "Unable to generate code"];

try {
    $sql = "SELECT CategoryCode 
            FROM tblcategory 
            WHERE CategoryCode IS NOT NULL 
            ORDER BY id DESC 
            LIMIT 1";
    $query = $dbh->prepare($sql);
    $query->execute();
    $row = $query->fetch(PDO::FETCH_ASSOC);

    if ($row && !empty($row['CategoryCode'])) {
        $lastCode = $row['CategoryCode'];
        $num = intval(substr($lastCode, 3)) + 1;
        $nextCode = "CAT" . str_pad($num, 3, "0", STR_PAD_LEFT);
        $response = ["status" => "success", "nextCode" => $nextCode];
    } else {
        $response = ["status" => "success", "nextCode" => "CAT001"];
    }
} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);
exit;
