query( 'SELECT o.*, (SELECT COUNT(*) FROM users u WHERE u.organization_id = o.id) AS member_count FROM organizations o ORDER BY o.name' )->fetchAll(); api_json(['items' => array_map(fn(array $o) => [ 'id' => (int) $o['id'], 'name' => $o['name'], 'notes' => $o['notes'], 'memberCount' => (int) $o['member_count'], ], $organizations)]); } $body = api_request_body(); $action = $body['action'] ?? ''; if ($action === 'save') { $id = (int) ($body['id'] ?? 0); $name = trim((string) ($body['name'] ?? '')); $notes = trim((string) ($body['notes'] ?? '')); if ($name === '') api_error(422, 'NAME_REQUIRED', 'Bitte einen Namen angeben.'); if ($id === 0) { $pdo->prepare('INSERT INTO organizations (name, notes, created_at) VALUES (?,?,?)') ->execute([$name, $notes, db_now()]); $newId = (int) $pdo->lastInsertId(); audit_log($staff['id'], "Organisation erstellt: {$name} (Mobile App)"); } else { $pdo->prepare('UPDATE organizations SET name=?, notes=? WHERE id=?')->execute([$name, $notes, $id]); $newId = $id; audit_log($staff['id'], "Organisation aktualisiert: {$name} (Mobile App)"); } api_json(['id' => $newId]); } if ($action === 'delete') { $id = (int) ($body['id'] ?? 0); $pdo->prepare('UPDATE users SET organization_id = NULL WHERE organization_id = ?')->execute([$id]); $pdo->prepare('DELETE FROM organizations WHERE id = ?')->execute([$id]); audit_log($staff['id'], "Organisation gelöscht: #{$id} (Mobile App)"); api_json(['ok' => true]); } api_error(422, 'INVALID_ACTION', 'Unbekannte Aktion.');