<?php
// =============================================================
//  POST /api/v1/admin_reference/specialty_create
//
//  Wraps app/create_specialty.php field-for-field.
//  Body: { "name": "...", "description": "..." }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('manage_specialties');

$body = Api::body();
$name        = trim((string)($body['name'] ?? ''));
$description = trim((string)($body['description'] ?? ''));

if ($name === '') Api::error(422, 'ValidationError', 'Specialty name is required');

$check = $conn->prepare("SELECT id FROM specialty WHERE LOWER(name) = LOWER(?)");
$check->bind_param('s', $name);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    Api::error(409, 'DuplicateSpecialty', 'A specialty with this name already exists');
}
$check->close();

$types = 'ssi';
$vals  = [$name, $description, $account->getId()];
if (strlen($types) !== count($vals)) {
    error_log('specialty_create.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the specialty record.');
}

$stmt = $conn->prepare("INSERT INTO specialty (name, description, created_by) VALUES (?, ?, ?)");
$createdById = $account->getId();
$stmt->bind_param($types, $name, $description, $createdById);

if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not create the specialty. Please try again.');
}
$newId = $conn->insert_id;
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'create_specialty', 'specialty', $newId, null, json_encode(['name' => $name]));

Api::success(['id' => $newId], [], 201);
