<?php
// =============================================================
//  POST /api/v1/admin_allocations/school_unit_delete
//
//  Wraps app/manage_clinical_unit_assignment.php's own
//  'soft_delete_school_unit' action — moves the assignment to trash
//  (is_active='Inactive'), recoverable via school_unit_restore.php,
//  matching the desktop's real Trash tab rather than a permanent
//  one-way delete.
//
//  Body: { "id": 5 }
// =============================================================

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);
if (!$id) Api::error(422, 'ValidationError', 'Invalid ID');

$userId = $account->getId();
$stmt = $conn->prepare("
    UPDATE school_unit_assignments
    SET is_active = 'Inactive', deleted_by = ?, deleted_at = NOW()
    WHERE id = ? AND is_active = 'Active'
");
$stmt->bind_param('ii', $userId, $id);
if (!$stmt->execute() || $stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Assignment not found or already trashed.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'trash_school_unit', 'school_unit_assignments', $id);

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