false, 'ERROR' => 'missing_businessid', 'MESSAGE' => 'BusinessID is required.']); } if ($name === '') { apiAbort(['OK' => false, 'ERROR' => 'missing_name', 'MESSAGE' => 'Station name is required.']); } try { if ($stationId > 0) { queryTimed("UPDATE Stations SET Name = ?, Color = ? WHERE ID = ? AND BusinessID = ?", [$name, $color, $stationId, $bizId]); } else { queryTimed(" INSERT INTO Stations (BusinessID, Name, Color, SortOrder, IsActive, AddedOn) VALUES (?, ?, ?, (SELECT COALESCE(MAX(s2.SortOrder), 0) + 1 FROM Stations s2 WHERE s2.BusinessID = ?), 1, NOW()) ", [$bizId, $name, $color, $bizId]); $stationId = (int) lastInsertId(); } $q = queryOne("SELECT ID, BusinessID, Name, Color, SortOrder FROM Stations WHERE ID = ?", [$stationId]); if (!$q) { apiAbort(['OK' => false, 'ERROR' => 'not_found', 'MESSAGE' => 'Station not found after save.']); } jsonResponse([ 'OK' => true, 'ERROR' => '', 'STATION' => [ 'StationID' => (int) $q['ID'], 'Name' => $q['Name'], 'Color' => $q['Color'], 'SortOrder' => (int) $q['SortOrder'], ], ]); } catch (Exception $e) { jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => 'Failed to save station', 'DETAIL' => $e->getMessage()]); }