<?php
// =============================================================
//  POST /api/v1/admin_allocations/school_unit_update
//
//  Wraps app/manage_clinical_unit_assignment.php's own
//  'edit_school_unit' action — same duplicate-pair check excluding the
//  current row (school_name is fixed once created; only unit_id and
//  duration are editable, matching the desktop's own edit dialog).
//
//  Body: { "id": 5, "unit_id": 3, "duration_value": 6, "duration_unit": "weeks" }
// =============================================================

require_once __DIR__ . '/../_bootstrap.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);
$unitId = (int)($body['unit_id'] ?? 0);
$durationValue = (int)($body['duration_value'] ?? 0);
$durationUnit = in_array($body['duration_unit'] ?? 'weeks', ['days', 'weeks', 'months'], true) ? $body['duration_unit'] : 'weeks';

if (!$id || !$unitId || $durationValue < 1) {
    Api::error(422, 'ValidationError', 'Invalid data provided');
}

$chk = $conn->prepare("
    SELECT sua.id FROM school_unit_assignments sua
    JOIN school_unit_assignments target ON target.id = ?
    WHERE LOWER(sua.school_name) = LOWER(target.school_name)
      AND sua.unit_id     = ?
      AND sua.is_active   = 'Active'
      AND sua.id         != ?
");
$chk->bind_param('iii', $id, $unitId, $id);
$chk->execute();
$chk->store_result();
if ($chk->num_rows > 0) {
    $chk->close();
    Api::error(409, 'DuplicateAssignment', 'This unit is already assigned to this school');
}
$chk->close();

$userId = $account->getId();
$stmt = $conn->prepare("
    UPDATE school_unit_assignments
    SET unit_id = ?, duration_value = ?, duration_unit = ?,
        updated_by = ?, updated_at = NOW()
    WHERE id = ? AND is_active = 'Active'
");
$stmt->bind_param('iisii', $unitId, $durationValue, $durationUnit, $userId, $id);
if (!$stmt->execute() || $stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Assignment not found or update failed.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'update_school_unit', 'school_unit_assignments', $id, null, json_encode(['unit_id' => $unitId, 'duration_value' => $durationValue, 'duration_unit' => $durationUnit]));

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