false, 'ERROR' => 'missing_params', 'MESSAGE' => 'OrderID and StationID are required.']); } try { $qOrder = queryOne(" SELECT o.ID, o.StatusID, o.BusinessID, o.ServicePointID, sp.Name FROM Orders o LEFT JOIN ServicePoints sp ON sp.ID = o.ServicePointID WHERE o.ID = ? LIMIT 1 ", [$OrderID]); if (!$qOrder) { apiAbort(['OK' => false, 'ERROR' => 'not_found', 'MESSAGE' => 'Order not found.']); } $oldStatusID = (int) $qOrder['StatusID']; // Mark root line items for this station as done (StatusID = 1) queryTimed(" UPDATE OrderLineItems oli INNER JOIN Items i ON i.ID = oli.ItemID SET oli.StatusID = 1 WHERE oli.OrderID = ? AND i.StationID = ? AND oli.ParentOrderLineItemID = 0 AND oli.IsDeleted = 0 ", [$OrderID, $StationID]); // Also mark children (modifiers) of those root items as done queryTimed(" UPDATE OrderLineItems oli SET oli.StatusID = 1 WHERE oli.OrderID = ? AND oli.IsDeleted = 0 AND oli.ParentOrderLineItemID IN ( SELECT sub.ID FROM ( SELECT oli2.ID FROM OrderLineItems oli2 INNER JOIN Items i2 ON i2.ID = oli2.ItemID WHERE oli2.OrderID = ? AND i2.StationID = ? AND oli2.ParentOrderLineItemID = 0 AND oli2.IsDeleted = 0 ) sub ) ", [$OrderID, $OrderID, $StationID]); // Auto-promote to status 2 if was at status 1 if ($oldStatusID === 1) { queryTimed("UPDATE Orders SET StatusID = 2, LastEditedOn = NOW() WHERE ID = ?", [$OrderID]); $oldStatusID = 2; } // Check if ALL station-assigned root items are now done $qRemaining = queryOne(" SELECT COUNT(*) AS RemainingCount FROM OrderLineItems oli INNER JOIN Items i ON i.ID = oli.ItemID WHERE oli.OrderID = ? AND oli.ParentOrderLineItemID = 0 AND oli.IsDeleted = 0 AND i.StationID > 0 AND oli.StatusID = 0 ", [$OrderID]); $allStationsDone = ((int) ($qRemaining['RemainingCount'] ?? 0) === 0); $NewStatusID = $oldStatusID; $taskCreated = false; // Auto-promote to status 3 and create tasks if ($allStationsDone && $oldStatusID < 3) { $NewStatusID = 3; queryTimed("UPDATE Orders SET StatusID = 3, LastEditedOn = NOW() WHERE ID = ?", [$OrderID]); require __DIR__ . '/_createOrderTasks.php'; } jsonResponse([ 'OK' => true, 'ERROR' => '', 'MESSAGE' => 'Station items marked as done.', 'OrderID' => $OrderID, 'StationID' => $StationID, 'StationDone' => true, 'AllStationsDone' => $allStationsDone, 'NewOrderStatusID' => $NewStatusID, 'TaskCreated' => $allStationsDone && $taskCreated, ]); } catch (Exception $e) { jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => 'Error marking station done', 'DETAIL' => $e->getMessage()]); }