20 min with no activity) */ try { // Find open chat tasks older than 20 minutes $staleChats = queryTimed(" SELECT t.ID, t.CreatedOn, (SELECT MAX(cm.CreatedOn) FROM ChatMessages cm WHERE cm.TaskID = t.ID) as LastMessageOn FROM Tasks t WHERE t.TaskTypeID = 2 AND t.CompletedOn IS NULL AND t.CreatedOn < DATE_SUB(NOW(), INTERVAL 20 MINUTE) ", []); $expiredCount = 0; $expiredIds = []; foreach ($staleChats as $chat) { $shouldExpire = false; if (empty($chat['LastMessageOn'])) { $shouldExpire = true; } else { $lastMsgAge = (int) ((time() - strtotime($chat['LastMessageOn'])) / 60); if ($lastMsgAge > 20) { $shouldExpire = true; } } if ($shouldExpire) { queryTimed("UPDATE Tasks SET CompletedOn = NOW() WHERE ID = ?", [$chat['ID']]); $expiredCount++; $expiredIds[] = (int) $chat['ID']; } } jsonResponse([ 'OK' => true, 'MESSAGE' => "Expired $expiredCount stale chat(s)", 'EXPIRED_TASK_IDS' => $expiredIds, 'CHECKED_COUNT' => count($staleChats), ]); } catch (Exception $e) { jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => $e->getMessage()]); }