<?php
// =============================================================
//  POST /api/v1/admin_nurses/toggle_rotation  { "id": 5, "rotation_status": "On_hold" }
//
//  Manually overrides a Rotation Nurse's rotation_status — wraps
//  app/manage_rotation_nurses.php's toggle_rotation action exactly,
//  including the same 5-value allow-list (no "Reassigned" here — that
//  value is edit-form-only, matching the desktop quick action).
// =============================================================

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

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

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

$allowed = ['Not_started', 'In_progress', 'Completed', 'On_hold', 'Cancelled'];

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$userId = (int)($body['id'] ?? 0);
$newRotation = (string)($body['rotation_status'] ?? '');

if (!$userId) Api::error(422, 'ValidationError', 'id is required');
if (!in_array($newRotation, $allowed, true)) Api::error(422, 'ValidationError', 'Invalid rotation status');

// Same as the desktop action: no existence check before the UPDATE — an
// unmatched id is a silent no-op, matching app/manage_rotation_nurses.php's
// own toggle_rotation handler exactly.
$stmt = $conn->prepare('UPDATE rotation_nurses SET rotation_status = ? WHERE id = ?');
$stmt->bind_param('si', $newRotation, $userId);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not update rotation status. Please try again.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'edit_user', 'rotation_nurses', $userId, null, json_encode(['rotation_status' => $newRotation]));

Api::success(['id' => $userId, 'rotation_status' => $newRotation]);
