Duplicating/Wrong photos visualizing in php with Firebase Storage/DB

I’m working on a system where ESP32 cameras send images to Firebase Storage upon detecting motion. A Python script runs YOLOv8 on these images to detect objects and saves the results in Firebase. On my PHP website, I’m trying to display the results and match the images with their corresponding detection message. However, I’m encountering two issues:

The first photo displayed is incorrect and doesn't match the result.
The message is duplicated in the list.
    <h2>Last Messages</h2>
    <?php if ($results): ?>
        <ul>
            <?php
            // Get all the user devices' MAC addresses
            $userMacAddresses = array_column(array_filter($userDevices, function ($device) use ($username) {
                return isset($device['username']) && $device['username'] === $username;
            }), 'macAddress');

            $messagesWithTimestamp = [];
            $lastPhotos = []; // Initialize an array to store the last photos

            // Firebase Storage bucket name
            $bucketName = "*****";
            $folder = "checkedPhotos";

            // API URL to list items in the folder
            $url = "https://firebasestorage.googleapis.com/v0/b/$bucketName/o?prefix=$folder/";

            // Initialize cURL session to fetch photos from Firebase Storage
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute cURL request
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                echo "cURL Error: " . curl_error($ch);
            } else {
                $data = json_decode($response, true);

                // Check if items exist
                if (isset($data['items'])) {
                    foreach ($data['items'] as $item) {
                        // Generate the download URL for each item
                        $fileName = $item['name']; // Full filename (e.g., "checkedPhotos/80:7D:3A:EA:FE:F8_18_11_11_19_18.jpg")
                        $imageUrl = "https://firebasestorage.googleapis.com/v0/b/$bucketName/o/" . urlencode($fileName) . "?alt=media";

                        // Extract MAC address and timestamp from the filename
                        if (preg_match('/([^/]+)_(d{2}_d{2}_d{2}_d{2}_d{2}).jpg$/', $fileName, $matches)) {
                            $macAddress = $matches[1]; // Extracted MAC address
                            $timestampPart = $matches[2]; // Extracted timestamp (e.g., "18_11_11_19_18")

                            // Store the photo along with its MAC address and timestamp
                            $lastPhotos[] = [
                                'macAddress' => $macAddress,
                                'timestamp' => $timestampPart,
                                'url' => $imageUrl
                            ];
                        }
                    }
                }
            }
            curl_close($ch);

            // Loop through each result and prepare the messages with their timestamps
            foreach ($results as $key => $message) {
                $keyParts = explode('_', $key);
                $macAddress = $keyParts[0];

                if (in_array($macAddress, $userMacAddresses)) {
                    if (count($keyParts) >= 6) {
                        $timestamp = implode('_', array_slice($keyParts, 1, 5)); // Create timestamp (e.g., "18_11_11_19_18")
                    } else {
                        $timestamp = null;
                    }

                    $nickname = null;
                    foreach ($cameraInfo as $camera) {
                        if ($camera['macAddress'] === $macAddress) {
                            $nickname = $camera['nickname'];
                            break;
                        }
                    }

                    $displayName = $nickname ? $nickname : $macAddress;

                    $alreadyDisplayed = false;
                    foreach ($messagesWithTimestamp as $existingMessage) {
                        if ($existingMessage['macAddress'] === $macAddress && $existingMessage['timestamp'] === $timestamp) {
                            $alreadyDisplayed = true;
                            break;
                        }
                    }

                    if (!$alreadyDisplayed) {
                        $messagesWithTimestamp[] = [
                            'message' => $message,
                            'nickname' => $displayName,
                            'macAddress' => $macAddress,
                            'timestamp' => $timestamp
                        ];
                    }
                }
            }

            // Match messages to photos
            foreach ($messagesWithTimestamp as &$message) {
                $matchedPhoto = null;

                foreach ($lastPhotos as $photo) {
                    if ($photo['macAddress'] === $message['macAddress'] && $photo['timestamp'] === $message['timestamp']) {
                        $matchedPhoto = $photo['url'];
                        break;
                    }
                }

                $message['photo'] = $matchedPhoto ?: 'No matching photo available.';
            }

            // Display messages and matched photos
            foreach ($messagesWithTimestamp as $message): ?>
                <li>
                    Camera in <strong><?= htmlspecialchars($message['nickname']); ?></strong> detected:
                    <?= htmlspecialchars($message['message']); ?>
                    (Time: <?= htmlspecialchars($message['timestamp']); ?>)
                </li>
                <?php if ($message['photo'] !== 'No matching photo available.'): ?>
                    <img src="<?= htmlspecialchars($message['photo']); ?>" alt="Matched Photo" style="width: 50%; height: auto;">
                <?php else: ?>
                    <p>No matching photo available.</p>
                <?php endif; ?>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>No messages available.</p>
    <?php endif; ?>
</div>    ```


Expected Behavior:

    The image should match the result correctly using the MAC address and timestamp from Firebase.
    Each detection message should only appear once.

Actual Behavior:

    The first image displayed on the website doesn’t match the detection result.
    The message gets duplicated.

What I’ve Tried:

    I’ve verified the consistency of the filenames and timestamps.
    I ensured that the photos are fetched and stored correctly from Firebase Storage.
    I checked for duplicates in the messages array before displaying them, but the issue persists.

Any advice on how to debug this or how to fix the matching logic?