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

try {
    $sql = "SELECT AuthorID FROM tblauthors ORDER BY id DESC LIMIT 1";
    $query = $dbh->prepare($sql);
    $query->execute();
    $last = $query->fetch(PDO::FETCH_OBJ);

    if ($last && $last->AuthorID) {
        $num = (int) filter_var($last->AuthorID, FILTER_SANITIZE_NUMBER_INT);
        $num = $num + 1;
        $newAuthorID = "AUTH" . str_pad($num, 6, "0", STR_PAD_LEFT);
    } else {
        $newAuthorID = "AUTH000001";
    }

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