<?php
// =============================================================
//  POST /api/v1/admin_reference/specialty_update
//
//  Wraps app/edit_specialty.php field-for-field.
//  Body: { "id": 1, "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();
$id          = (int)($body['id'] ?? 0);
$name        = trim((string)($body['name'] ?? ''));
$description = trim((string)($body['description'] ?? ''));

if ($id <= 0) Api::error(422, 'ValidationError', 'A valid specialty id is required');
if ($name === '') Api::error(422, 'ValidationError', 'Specialty name is required');

$exists = $conn->prepare("SELECT id FROM specialty WHERE id = ?");
$exists->bind_param('i', $id);
$exists->execute();
$exists->store_result();
if ($exists->num_rows === 0) {
    $exists->close();
    Api::error(404, 'NotFound', 'Specialty not found');
}
$exists->close();

$check = $conn->prepare("SELECT id FROM specialty WHERE LOWER(name) = LOWER(?) AND id != ?");
$check->bind_param('si', $name, $id);
$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, $id];
if (strlen($types) !== count($vals)) {
    error_log('specialty_update.php: type string length (' . strlen($types) . ') != value count (' . count($vals) . ')');
    Api::error(500, 'ServerError', 'Internal error preparing the specialty record.');
}

$stmt = $conn->prepare("UPDATE specialty SET name = ?, description = ? WHERE id = ?");
$stmt->bind_param($types, $name, $description, $id);

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

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

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