<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');

$email = $_POST['email'] ?? null;
$page = isset($_POST['page']) ? max(1, (int)$_POST['page']) : 1;
$messagesPerPage = 20;

if (!$email) {
    http_response_code(400);
    echo "No email account selected.";
    exit();
}

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

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

    foreach ($lines as $line) {
        if (strpos($line, '=') !== false && strpos(trim($line), '#') !== 0) {
            list($key, $value) = explode('=', $line, 2);
            $key = strtoupper(trim($key));
            $value = trim($value, '" ');

            if (str_ends_with($key, '_EMAIL')) {
                $prefix = substr($key, 0, -6);
                $accounts[$prefix]['email'] = $value;
            } elseif (str_ends_with($key, '_PASS')) {
                $prefix = substr($key, 0, -5);
                $accounts[$prefix]['password'] = $value;
            }
        }
    }

    $result = [];
    foreach ($accounts as $acc) {
        if (isset($acc['email'])) {
            $result[$acc['email']] = [
                'email' => $acc['email'],
                'password' => $acc['password'] ?? null
            ];
        }
    }

    return $result;
}

// === Message body extraction ===
function getMessageBody($inbox, $msgNumber) {
    $structure = imap_fetchstructure($inbox, $msgNumber);
    $body = '';
    $encoding = 0;

    if (!isset($structure->parts)) {
        $body = imap_body($inbox, $msgNumber);
        $encoding = $structure->encoding ?? 0;
    } else {
        $foundHTML = false;
        foreach ($structure->parts as $partNum => $part) {
            if ($part->type == 0 && strtolower($part->subtype) == 'html') {
                $body = imap_fetchbody($inbox, $msgNumber, $partNum + 1);
                $encoding = $part->encoding ?? 0;
                $foundHTML = true;
                break;
            }
        }

        if (!$foundHTML) {
            foreach ($structure->parts as $partNum => $part) {
                if ($part->type == 0 && strtolower($part->subtype) == 'plain') {
                    $body = imap_fetchbody($inbox, $msgNumber, $partNum + 1);
                    $encoding = $part->encoding ?? 0;
                    break;
                }
            }
        }
    }

    switch ($encoding) {
        case 3: $body = base64_decode($body); break;
        case 4: $body = quoted_printable_decode($body); break;
        default: $body = trim($body); break;
    }

    return $body;
}

$accounts = getEnvEmails();
if (!isset($accounts[$email])) {
    echo "Email not found in .env file.";
    exit();
}

$password = $accounts[$email]['password'] ?? null;
if (!$password) {
    echo "Password not found for this email in .env file.";
    exit();
}

// === Connect to Sent folder (adjust if needed) ===
$hostname = '{mail.acionlineportal.com.ng:993/imap/ssl/novalidate-cert}INBOX.Sent';
$inbox = @imap_open($hostname, $email, $password);

if (!$inbox) {
    echo "<tr><td colspan='4'>Failed to connect to mailbox.</td></tr>";
    exit();
}

// === Fetch and paginate messages ===
$numMessages = imap_num_msg($inbox);

if ($numMessages === 0) {
    echo "<tr><td colspan='4'>No messages found.</td></tr>";
    imap_close($inbox);
    exit();
}

$totalPages = ceil($numMessages / $messagesPerPage);
$start = $numMessages - (($page - 1) * $messagesPerPage);
$end = max(1, $start - $messagesPerPage + 1);

// === Render each message ===
for ($i = $start; $i >= $end; $i--) {
    $header = imap_headerinfo($inbox, $i);

    $toName = isset($header->to[0]->personal) ? imap_utf8($header->to[0]->personal) : '';
    $toEmail = $header->to[0]->mailbox . '@' . $header->to[0]->host;
    $toDisplay = $toName ? "$toName ($toEmail)" : $toEmail;

    $subject = isset($header->subject) ? imap_utf8($header->subject) : '(No Subject)';
    $date = date("d M Y H:i", strtotime($header->date));

    $rawBody = getMessageBody($inbox, $i);
    $isHTML = stripos($rawBody, '<html') !== false || stripos($rawBody, '<div') !== false;

    $dataBody = htmlspecialchars($rawBody);

    echo "<tr>
            <td>" . htmlspecialchars($toDisplay) . "</td>
            <td>" . htmlspecialchars($subject) . "</td>
            <td>" . htmlspecialchars($date) . "</td>
            <td>
                <button class='btn btn-sm btn-info view-message' 
                        data-body=\"$dataBody\" 
                        data-is-html=\"$isHTML\">
                   <i class ='fas fa-eye'></i>
                </button>
            </td>
          </tr>";
}



function renderPagination($email, $page, $totalPages) {
    $paginationHtml = "<div style='display:flex; gap:5px; align-items:center;'>";

    // Previous button
    if ($page > 1) {
        $prevPage = $page - 1;
        $paginationHtml .= "<button class='ajax-page-link btn btn-sm btn-secondary' data-email='" . htmlspecialchars($email) . "' data-page='$prevPage'>Previous</button>";
    } else {
        $paginationHtml .= "<button class='btn btn-sm btn-secondary' disabled style='opacity:0.5; cursor:not-allowed;'>Previous</button>";
    }

    // Helper function to output page button
    $pageBtn = function($p) use ($email, $page) {
        $activeClass = $p == $page ? "btn-primary" : "btn-secondary";
        $disabledAttr = $p == $page ? "disabled style='pointer-events:none;'" : "";
        return "<button class='ajax-page-link btn btn-sm $activeClass' data-email='" . htmlspecialchars($email) . "' data-page='$p' $disabledAttr>$p</button>";
    };

    // Always show first page
    $paginationHtml .= $pageBtn(1);

    // Determine start and end of page range around current page
    $start = max(2, $page - 2);
    $end = min($totalPages - 1, $page + 2);

    // Show ellipsis if gap between first and start
    if ($start > 2) {
        $paginationHtml .= "<span style='padding:0 8px;'>…</span>";
    }

    // Page numbers range
    for ($i = $start; $i <= $end; $i++) {
        $paginationHtml .= $pageBtn($i);
    }

    // Show ellipsis if gap between end and last page
    if ($end < $totalPages - 1) {
        $paginationHtml .= "<span style='padding:0 8px;'>…</span>";
    }

    // Always show last page if > 1
    if ($totalPages > 1) {
        $paginationHtml .= $pageBtn($totalPages);
    }

    // Next button
    if ($page < $totalPages) {
        $nextPage = $page + 1;
        $paginationHtml .= "<button class='ajax-page-link btn btn-sm btn-secondary' data-email='" . htmlspecialchars($email) . "' data-page='$nextPage'>Next</button>";
    } else {
        $paginationHtml .= "<button class='btn btn-sm btn-secondary' disabled style='opacity:0.5; cursor:not-allowed;'>Next</button>";
    }

    $paginationHtml .= "</div>";
    return $paginationHtml;
}






// Calculate showing entries indexes
$firstMessage = ($numMessages - $start) + 1;
$lastMessage = ($numMessages - $end) + 1;
if ($lastMessage > $numMessages) $lastMessage = $numMessages;

// Show "Showing X to Y of Z entries"
echo "<tr><td colspan='4' style='padding:10px;'>";
echo "<div style='display:flex; justify-content:space-between; align-items:center;'>";

// Left side: entries info
echo "<div style='font-weight:500;'>Showing $firstMessage to $lastMessage of $numMessages entries</div>";

// Right side: pagination buttons (smart pagination)
echo "<div>";
echo renderPagination($email, $page, $totalPages);
echo "</div>";

echo "</div>";
echo "</td></tr>";
imap_close($inbox);
?>
