<?php
// =============================================================
//  POST /api/v1/admin_allocations/unit_update
//
//  Wraps app/manage_unit_assignment.php's own 'edit_unit' action —
//  editUnitAssignment() unmodified: refuses a weeks total that would
//  push the specialty-department's other-unit total over its own
//  allocation, and (if the unit itself is being changed) refuses a
//  target unit already assigned elsewhere under the same pair.
//
//  Body: { "id": 5, "weeks": 4, "unit_id": 3 }  — unit_id optional,
//  omit/0 to keep the assignment's current unit and only change weeks.
// =============================================================

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

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

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

$body = Api::body();
$id = (int)($body['id'] ?? 0);
$weeks = (int)($body['weeks'] ?? 0);
$unitId = (int)($body['unit_id'] ?? 0) ?: null;

if (!$id) Api::error(422, 'ValidationError', 'Invalid assignment');
if ($weeks < 1) Api::error(422, 'ValidationError', 'Weeks must be at least 1');

$result = editUnitAssignment($conn, $id, $weeks, $account->getFullName(), $unitId);
if (!$result['success']) {
    Api::error(409, 'AssignmentConflict', $result['message']);
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'update_unit_assignment', 'department_unit_weeks', $id, null, json_encode(['weeks' => $weeks, 'unit_id' => $unitId]));

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