<?php
include "../root.class.php";
// Email credentials and server settings
$email = "chris@elegantwork.co.za";
$password = "EWG2Chr!@#";
$mailbox = "{mail.elegantwork.co.za:993/imap/ssl}INBOX"; // Change for your email provider

// Connect to the mailbox
$inbox = imap_open($mailbox, $email, $password) or die("Cannot connect: " . imap_last_error());

// Fetch the latest 10 emails
$emails = imap_search($inbox, 'ALL'); // Fetch all emails

if ($emails) {
    rsort($emails); // Sort by latest first
    $emails = array_slice($emails, 0, 10); // Get the latest 10 emails

    foreach ($emails as $email_number) {
        $header = imap_headerinfo($inbox, $email_number);
        $subject = imap_utf8($header->subject);
        $from = imap_utf8($header->fromaddress);
        $date = $header->date;

        // Fetch the complete raw headers
        $raw_headers = imap_fetchheader($inbox, $email_number);

        // Extract server details using regex
        preg_match_all('/Received: from (.*?) /', $raw_headers, $matches);
        $servers = !empty($matches[1]) ? implode(", ", $matches[1]) : "Unknown";

        // Fetch the email body
        $body = imap_fetchbody($inbox, $email_number, 1);
        $body = imap_qprint($body); // Decode quoted-printable encoding if necessary

        $keywords = array("test", "test2");
        if (preg_match('/\b(' . implode('|', $keywords) . ')\b/i', $body)) {
            echo "<strong>SUSPECTED SPAM DETECTED</strong><br>";

            // Mark the email for deletion
            // imap_delete($inbox, $email_number);
        }

        echo "<strong>From:</strong> $from <br>";
        echo "<strong>Subject:</strong> $subject <br>";
        echo "<strong>Date:</strong> $date <br>";
        echo "<strong>Originating Server(s):</strong> $servers <br>";
        echo "<strong>Full Raw Headers:</strong> <pre>$raw_headers</pre><br>";
        echo "<strong>Body:</strong> <pre>$body</pre>";
        echo "<hr>";
    }

    // Expunge the marked emails to permanently delete them
    // imap_expunge($inbox);
} else {
    echo "No emails found.";
}

// Close the connection
imap_close($inbox);
?>
