<?php

namespace MailerPress\Services;

use MailerPress\Core\Enums\Tables;

class BounceParser
{
    public static function parse(): void
    {
        $bounceManager = get_option('mailerpress_bounce_config');

        // Si la configuration n'existe pas ou est vide, on ne fait rien
        if (empty($bounceManager)) {
            return;
        }

        if (is_string($bounceManager)) {
            $decoded = json_decode($bounceManager, true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $bounceManager = $decoded;
            } else {
                return;
            }
        }

        // Vérifier que la configuration contient les champs nécessaires
        if (!is_array($bounceManager) || empty($bounceManager['username']) || empty($bounceManager['password'])) {
            return;
        }

        $folder = \MailerPress\Services\BounceFolderFinder::findFolderWithUnseenMessages($bounceManager);

        if (null === $folder) {
            return;
        }

        $mailbox = @imap_open($folder, $bounceManager['username'], $bounceManager['password']);

        if (!$mailbox instanceof \IMAP\Connection) {
            return;
        }

        $emails = imap_search($mailbox, 'UNSEEN');

        if (!is_array($emails)) {
            imap_close($mailbox);
            return;
        }

        foreach ($emails as $email_number) {
            $body = imap_body($mailbox, $email_number);
            $originalEmail = self::extractOriginalRecipient($body);
            if ($originalEmail) {
                self::markContactAsBounced($originalEmail);
            }
            imap_setflag_full($mailbox, $email_number, "\\Seen");
        }

        imap_close($mailbox);
    }

    private static function extractOriginalRecipient(string $body): ?string
    {
        // Very basic regex, refine with better parsing later
        if (preg_match('/Final-Recipient: rfc822;(.*)/i', $body, $matches)) {
            return trim($matches[1]);
        }
        return null;
    }

    private static function markContactAsBounced(string $email): void
    {
        global $wpdb;
        $table = Tables::get(Tables::MAILERPRESS_CONTACT);

        $contact = $wpdb->get_row(
            $wpdb->prepare("SELECT contact_id FROM $table WHERE email = %s", $email)
        );

        if ($contact) {
            $wpdb->update(
                $table,
                [
                    'subscription_status' => 'bounced',
                ],
                ['contact_id' => $contact->contact_id]
            );
        }
    }
}
