query( 'SELECT t.*, s.name AS lead_name, (SELECT COUNT(*) FROM team_members tm WHERE tm.team_id = t.id) AS member_count FROM teams t LEFT JOIN staff s ON s.id = t.lead_id ORDER BY t.name' )->fetchAll(); $allStaff = $pdo->query('SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name')->fetchAll(); $memberStmt = $pdo->prepare('SELECT staff_id FROM team_members WHERE team_id = ?'); $teamsOut = []; foreach ($teams as $t) { $memberStmt->execute([$t['id']]); $teamsOut[] = [ 'id' => (int) $t['id'], 'name' => $t['name'], 'leadId' => $t['lead_id'] !== null ? (int) $t['lead_id'] : null, 'leadName' => $t['lead_name'], 'notes' => $t['notes'], 'isActive' => (bool) $t['is_active'], 'noAlerts' => (bool) ($t['no_alerts'] ?? 0), 'createdAt' => $t['created_at'] ?? null, 'updatedAt' => $t['updated_at'] ?? null, 'memberCount' => (int) $t['member_count'], 'memberIds' => array_map('intval', $memberStmt->fetchAll(PDO::FETCH_COLUMN)), ]; } api_json([ 'staffOptions' => array_map(fn(array $s) => ['id' => (int) $s['id'], 'name' => $s['name']], $allStaff), 'items' => $teamsOut, ]); } $body = api_request_body(); $action = $body['action'] ?? ''; $id = (int) ($body['id'] ?? 0); try { if ($action === 'save') { $in = ['name' => $body['name'] ?? '', 'lead_id' => $body['leadId'] ?? null, 'notes' => $body['notes'] ?? '', 'members' => $body['memberIds'] ?? []]; if (array_key_exists('isActive', $body)) $in['is_active'] = $body['isActive']; if (array_key_exists('noAlerts', $body)) $in['no_alerts'] = $body['noAlerts']; $newId = team_save($pdo, $id, $in); audit_log($staff['id'], ($id === 0 ? 'Team erstellt: ' : 'Team aktualisiert: ') . trim((string) ($body['name'] ?? '')) . ' (Mobile App)'); api_json(['id' => $newId]); } if ($action === 'toggle') { $pdo->prepare('UPDATE teams SET is_active = 1 - is_active, updated_at = ? WHERE id = ?')->execute([db_now(), $id]); api_json(['ok' => true]); } if ($action === 'delete') { $deleted = team_delete($pdo, $id); audit_log($staff['id'], "Team gelöscht: {$deleted} (Mobile App)"); api_json(['ok' => true]); } } catch (AdminModelException $e) { api_error($e->httpStatus(), $e->errorCode(), $e->getMessage()); } api_error(422, 'INVALID_ACTION', 'Unbekannte Aktion.');