<?php
// === Required ===
include(__DIR__ . '/includes/dbconnection.php');

// === Inputs ===
$email = $_GET['email'] ?? $_POST['email'] ?? null;
$msgno = $_GET['msgno'] ?? $_POST['msgno'] ?? null;

if (!$email || !$msgno) {
    http_response_code(400);
    echo "Missing parameters.";
    exit();
}

// === Load credentials ===
function getEnvEmails()
{
    $envPath = __DIR__ . '/.env';
    if (!file_exists($envPath)) return [];

    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $data = [];

    foreach ($lines as $line) {
        if (strpos($line, '=') !== false && strpos(trim($line), '#') !== 0) {
            [$k, $v] = explode('=', $line, 2);
            $data[trim($k)] = trim($v, '" ');
        }
    }

    $accounts = [];
    foreach ($data as $key => $val) {
        if (str_ends_with($key, '_EMAIL')) {
            $prefix = str_replace('_EMAIL', '', $key);
            $email = $val;
            $pass = $data[$prefix . '_PASS'] ?? null;
            if ($email && $pass) {
                $accounts[$email] = $pass;
            }
        }
    }

    return $accounts;
}

$accounts = getEnvEmails();

if (!isset($accounts[$email])) {
    http_response_code(403);
    echo "Email credentials not found.";
    exit();
}



$password = $accounts[$email];

// === Connect via IMAP ===
$inbox = @imap_open("{mail.acionlineportal.com.ng:993/imap/ssl}INBOX", $email, $password);
if (!$inbox) {
    echo "Connection failed: " . imap_last_error();
    exit();
}

// === Fetch the body ===
$structure = imap_fetchstructure($inbox, $msgno);
$body = '';

if (!$structure) {
    echo "Unable to fetch message structure.";
    exit();
}

function getPart($stream, $msgno, $mimeType, $structure = false, $partNumber = false)
{
    if (!$structure) {
        $structure = imap_fetchstructure($stream, $msgno);
    }
    if ($structure) {
        if ($structure->type == TYPETEXT && $structure->subtype == strtoupper($mimeType)) {
            if (!$partNumber) $partNumber = 1;
            $text = imap_fetchbody($stream, $msgno, $partNumber);
            return ($structure->encoding == 3) ? imap_base64($text) : (($structure->encoding == 4) ? imap_qprint($text) : $text);
        }

        if (isset($structure->parts)) {
            for ($i = 0; $i < count($structure->parts); $i++) {
                $part = $structure->parts[$i];
                $partNum = $partNumber ? $partNumber . '.' . ($i + 1) : ($i + 1);
                $data = getPart($stream, $msgno, $mimeType, $part, $partNum);
                if ($data) return $data;
            }
        }
    }

    return '';
}

// Try to get HTML first, then fallback to plain text
$body = getPart($inbox, $msgno, "HTML");
if (!$body) {
    $body = nl2br(getPart($inbox, $msgno, "PLAIN"));
}

imap_close($inbox);

// === Output HTML safely ===
echo $body ?: "No message content found.";
