<?php

namespace MailerPress\Services;

class BounceFolderFinder
{
    public static function findFolderWithUnseenMessages(array $config): ?string
    {
        $host = sprintf('{%s:%s/imap/ssl/novalidate-cert}', $config['host'], $config['port']);
        $inboxFolder = $host . 'INBOX';

        $mbox = @imap_open($inboxFolder, $config['username'], $config['password']);

        if (!$mbox) {
            return null;
        }

        if (!$mbox instanceof \IMAP\Connection) {
            // Optional: Log or debug the last IMAP error
            return null;
        }


        $unseen = imap_search($mbox, 'UNSEEN');
        imap_close($mbox);
        return (is_array($unseen) && count($unseen) > 0) ? $inboxFolder : null;

    }
}
