<?php
// =============================================================
//  POST /api/v1/admin_allocations/specialty_department_update
//
//  Wraps app/specialty_department.php's own 'edit_specialty_dept'
//  action for the full edit path (specialty + department + weeks all
//  passed together) — the same duplicate-combination check excluding
//  the current row, then a direct UPDATE of all three fields. Unlike
//  editSpecialtyDepartment() in include/db_functions.php (a weeks-only
//  path used when specialty/department aren't supplied), this endpoint
//  always sends all three, matching how the mobile edit form always
//  shows the specialty/department pickers pre-filled rather than
//  offering a weeks-only shortcut the desktop page also has.
//
//  Note: this full-edit path does NOT check whether the new weeks total
//  is still >= the weeks already assigned to units under this
//  allocation — the desktop page's own inline handler for this exact
//  action (specialty_id/department_id both passed) doesn't either; that
//  safety check exists only in editSpecialtyDepartment()'s weeks-only
//  path, used by the separate manage_specialty_department.php page.
//  Reproduced faithfully rather than added here, since fixing it would
//  make this endpoint stricter than the desktop feature it ports.
//
//  Body: { "id": 5, "specialty_id": 1, "department_id": 2, "weeks": 8 }
// =============================================================

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

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

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

$body = Api::body();
$id = (int)($body['id'] ?? 0);
$specialtyId = (int)($body['specialty_id'] ?? 0);
$departmentId = (int)($body['department_id'] ?? 0);
$weeks = (int)($body['weeks'] ?? 0);

if (!$id) Api::error(422, 'ValidationError', 'Invalid allocation');
if (!$specialtyId) Api::error(422, 'ValidationError', 'Specialty is required');
if (!$departmentId) Api::error(422, 'ValidationError', 'Department is required');
if ($weeks < 1) Api::error(422, 'ValidationError', 'Weeks must be at least 1');

$chk = $conn->prepare("SELECT id FROM specialty_department_weeks WHERE specialty_id=? AND department_id=? AND id!=? AND is_active='Active' LIMIT 1");
$chk->bind_param('iii', $specialtyId, $departmentId, $id);
$chk->execute();
$dup = $chk->get_result()->fetch_assoc();
$chk->close();
if ($dup) {
    Api::error(409, 'DuplicateAllocation', 'This specialty–department combination already exists.');
}

$stmt = $conn->prepare("UPDATE specialty_department_weeks SET specialty_id=?, department_id=?, weeks=?, updated_at=NOW() WHERE id=? AND is_active='Active'");
$stmt->bind_param('iiii', $specialtyId, $departmentId, $weeks, $id);
if (!$stmt->execute() || $stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Allocation not found or update failed.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'update_specialty_department', 'specialty_department_weeks', $id, null, json_encode(['specialty_id' => $specialtyId, 'department_id' => $departmentId, 'weeks' => $weeks]));

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