<?php
// ============================================================
//  admin/email-message.php — view a single message
// ============================================================
//
//  Permissions: user must be assigned to the message's account.
//
//  Body source:
//    - If body_text/body_html still in DB → use that
//    - If body_evicted_at is set (older than 90 days) → fetch
//      from IMAP on demand
//
//  HTML sanitisation: always strip dangerous tags. Remote images
//  blocked unless sender is whitelisted, OR user clicks "Show
//  images" button (one-time, per-page-load).
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/email_sync.php';
require_once __DIR__ . '/../includes/email_sanitize.php';
auth_require_admin();

$me = auth_admin_user();
$id = (int)($_GET['id'] ?? 0);

// Fetch with permission join
$msg = db_row(
    "SELECT m.*, a.imap_host, a.imap_port, a.imap_encryption,
            a.imap_username, a.imap_password, a.display_name AS account_name,
            a.email_address AS account_email, a.colour AS account_colour
       FROM email_messages m
       JOIN email_account_users u ON u.account_id = m.account_id
       JOIN email_accounts a      ON a.id        = m.account_id
      WHERE m.id=:id AND u.user_id=:uid",
    ['id' => $id, 'uid' => $me['id']]
);
if (!$msg) { http_response_code(404); exit('Message not found.'); }

// ── POST handlers ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'whitelist_sender') {
        $sender = strtolower(trim((string)$msg['from_email']));
        if ($sender) {
            $exists = db_row(
                'SELECT id FROM email_sender_whitelist WHERE account_id=:a AND sender=:s',
                ['a' => $msg['account_id'], 's' => $sender]
            );
            if (!$exists) {
                db_insert('email_sender_whitelist', [
                    'account_id' => $msg['account_id'],
                    'sender'     => $sender,
                    'note'       => $msg['from_name'] ?: null,
                    'added_by'   => $me['id'],
                ]);
            }
        }
        header('Location: email-message.php?id=' . $id);
        exit;
    }

    if ($action === 'mark_unseen') {
        db_exec('UPDATE email_messages SET is_seen=0 WHERE id=:id', ['id' => $id]);
        header('Location: email.php?account=' . (int)$msg['account_id']);
        exit;
    }

    if ($action === 'flag_toggle') {
        db_exec('UPDATE email_messages SET is_flagged = 1 - is_flagged WHERE id=:id', ['id' => $id]);
        header('Location: email-message.php?id=' . $id);
        exit;
    }
}

// Mark as seen on open (if not already)
if (!$msg['is_seen']) {
    db_exec('UPDATE email_messages SET is_seen=1 WHERE id=:id', ['id' => $id]);
    $msg['is_seen'] = 1;
}

// Is the sender whitelisted?
$is_whitelisted = false;
if (!empty($msg['from_email'])) {
    $w = db_row(
        'SELECT 1 FROM email_sender_whitelist WHERE account_id=:a AND sender=:s',
        ['a' => $msg['account_id'], 's' => strtolower($msg['from_email'])]
    );
    $is_whitelisted = (bool)$w;
}

// Show images? Whitelist OR one-time ?show_images=1 OR explicit user override
$show_images = $is_whitelisted || !empty($_GET['show_images']);

// Body source
$body_text = $msg['body_text'];
$body_html = $msg['body_html'];
$body_was_refetched = false;
$refetch_error = '';

// Treat NULL and empty strings the same — "no body"
$body_is_missing = (!is_string($body_text) || trim($body_text) === '')
                && (!is_string($body_html) || trim($body_html) === '');

// Diagnostic info — shown if ?debug=1 is in the URL
$debug = !empty($_GET['debug']);
$debug_info = [];
$debug_info['initial body_text'] = $body_text === null ? 'NULL' : 'len=' . strlen((string)$body_text);
$debug_info['initial body_html'] = $body_html === null ? 'NULL' : 'len=' . strlen((string)$body_html);
$debug_info['body_evicted_at']   = $msg['body_evicted_at'] ?? 'NULL';
$debug_info['snippet']           = ($msg['snippet'] ?? '') === '' ? '(empty)' : 'len=' . strlen((string)$msg['snippet']);
$debug_info['body_is_missing']   = $body_is_missing ? 'true' : 'false';
$debug_info['attachment_count']  = !empty($msg['has_attachments']) ? 'yes' : 'no';

if ($body_is_missing) {
    try {
        $acct_full = [
            'imap_host'       => $msg['imap_host'],
            'imap_port'       => $msg['imap_port'],
            'imap_encryption' => $msg['imap_encryption'],
            'imap_username'   => $msg['imap_username'],
            'imap_password'   => $msg['imap_password'],
        ];
        $parts = email_fetch_body_on_demand($acct_full, $msg['folder'], (int)$msg['uid']);
        $body_text = $parts['text'] ?: null;
        $body_html = $parts['html'] ?: null;
        $body_was_refetched = true;

        $debug_info['refetch text']  = $body_text === null ? 'NULL' : 'len=' . strlen((string)$body_text);
        $debug_info['refetch html']  = $body_html === null ? 'NULL' : 'len=' . strlen((string)$body_html);
        $debug_info['refetch attachments'] = count($parts['attachments'] ?? []);

        // Save the recovered body back to the DB (only if not already evicted)
        if (empty($msg['body_evicted_at']) && ($body_text !== null || $body_html !== null)) {
            $update_set = [];
            $update_params = ['id' => $msg['id']];
            if ($body_text !== null) { $update_set[] = 'body_text = :bt'; $update_params['bt'] = $body_text; }
            if ($body_html !== null) { $update_set[] = 'body_html = :bh'; $update_params['bh'] = $body_html; }
            try {
                db_exec("UPDATE email_messages SET " . implode(', ', $update_set) . " WHERE id = :id", $update_params);
            } catch (Throwable $_) { /* non-fatal */ }
        }
    } catch (Throwable $e) {
        $refetch_error = $e->getMessage();
        $debug_info['refetch error'] = $e->getMessage();
    }
}

// Render body
$render_html = '';
$images_blocked = 0;
if ($body_html !== null && $body_html !== '') {
    $r = email_sanitize_html($body_html, $show_images);
    $render_html = email_render_html($r['html']);
    $images_blocked = $r['images_blocked'];
} elseif ($body_text !== null && $body_text !== '') {
    $render_html = email_render_plain($body_text);
}

// Attachments (metadata only — bytes fetched on download click)
$attachments = !empty($msg['attachment_meta']) ? json_decode($msg['attachment_meta'], true) : [];
if (!is_array($attachments)) $attachments = [];

$page_title = 'Email · ' . ($msg['subject'] ?: '(no subject)');
require __DIR__ . '/_guard.php';
?>

<style>
.em-wrap{max-width:920px;margin:0 auto;}
.em-back{display:inline-flex;align-items:center;gap:.35rem;color:var(--ink-muted);text-decoration:none;font-size:.86rem;margin-bottom:.75rem;}
.em-back:hover{color:var(--ink);}

.em-head{
    background:#fff;border:1px solid var(--line);border-radius:8px 8px 0 0;
    padding:1.25rem 1.5rem;border-bottom:0;
}
.em-subject{margin:0 0 .85rem;font-size:1.3rem;line-height:1.3;}
.em-meta{display:grid;grid-template-columns:80px 1fr;gap:.25rem .85rem;font-size:.85rem;color:var(--ink);}
.em-meta dt{color:var(--ink-muted);font-weight:normal;}
.em-meta dd{margin:0;}

.em-account-strip{
    display:inline-flex;align-items:center;gap:.45rem;
    padding:.2rem .65rem;border-radius:999px;
    background:var(--surface-alt);font-size:.75rem;color:var(--ink-muted);margin-bottom:.5rem;
}
.em-account-strip .dot{width:8px;height:8px;border-radius:50%;display:inline-block;}

.em-actions{
    background:var(--surface-alt);border:1px solid var(--line);border-bottom:0;
    padding:.6rem 1.5rem;display:flex;gap:.4rem;flex-wrap:wrap;align-items:center;
}
.em-actions form{display:inline;margin:0;}
.em-actions .btn-mini{
    padding:.35rem .75rem;font-size:.78rem;border:1px solid var(--line);background:#fff;
    border-radius:5px;text-decoration:none;color:var(--ink);font-family:inherit;cursor:pointer;
}
.em-actions .btn-mini:hover{background:#f5f3ee;}
.em-actions .btn-mini.primary{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.em-actions .btn-mini.primary:hover{filter:brightness(0.9);}

.em-banner{
    padding:.55rem 1rem;font-size:.82rem;background:#fff7ed;color:#9a3412;
    border:1px solid #fed7aa;border-bottom:0;display:flex;justify-content:space-between;
    align-items:center;gap:1rem;flex-wrap:wrap;
}
.em-banner.info{background:#eff6ff;color:#1e40af;border-color:#bfdbfe;}
.em-banner form{display:inline;margin:0;}

.em-body{
    background:#fff;border:1px solid var(--line);border-radius:0 0 8px 8px;
    padding:1.5rem;font-size:.92rem;line-height:1.55;
}
.email-body-isolate{
    all:initial;font-family:inherit;font-size:.92rem;line-height:1.55;color:#1f2937;
    display:block;
}
.email-body-isolate *{max-width:100%;}
.email-body-isolate img{height:auto;}
.email-body-isolate a{color:#1e40af;}
.email-body-isolate table{border-collapse:collapse;}
.email-body-plain{
    white-space:pre-wrap;font-family:ui-monospace,Menlo,Consolas,monospace;
    font-size:.86rem;line-height:1.5;margin:0;background:transparent;
}

.em-atts{margin-top:1rem;padding-top:1rem;border-top:1px solid var(--line);}
.em-atts h4{margin:0 0 .5rem;font-size:.85rem;color:var(--ink-muted);text-transform:uppercase;letter-spacing:.04em;}
.em-att-row{
    display:inline-flex;align-items:center;gap:.45rem;
    background:var(--surface-alt);border:1px solid var(--line);border-radius:5px;
    padding:.4rem .7rem;font-size:.82rem;margin:0 .3rem .3rem 0;text-decoration:none;color:var(--ink);
}
.em-att-row:hover{background:#f0ede4;}
.em-att-size{color:var(--ink-muted);font-size:.74rem;}
</style>

<section class="section"><div class="container em-wrap">

<a href="email.php?account=<?= (int)$msg['account_id'] ?>" class="em-back">← Back to inbox</a>

<div class="em-account-strip">
    <span class="dot" style="background:<?= htmlspecialchars($msg['account_colour']) ?>;"></span>
    <span><?= htmlspecialchars($msg['account_name']) ?> · <?= htmlspecialchars($msg['account_email']) ?></span>
</div>

<div class="em-head">
    <h1 class="em-subject"><?= htmlspecialchars($msg['subject'] ?: '(no subject)') ?></h1>
    <dl class="em-meta">
        <dt>From:</dt>
        <dd>
            <?php if ($msg['from_name']): ?>
                <strong><?= htmlspecialchars($msg['from_name']) ?></strong>
                &lt;<?= htmlspecialchars((string)$msg['from_email']) ?>&gt;
            <?php else: ?>
                <strong><?= htmlspecialchars((string)$msg['from_email']) ?></strong>
            <?php endif; ?>
        </dd>
        <dt>To:</dt>
        <dd><?= htmlspecialchars((string)$msg['to_list']) ?></dd>
        <?php if (!empty($msg['cc_list'])): ?>
            <dt>Cc:</dt>
            <dd><?= htmlspecialchars((string)$msg['cc_list']) ?></dd>
        <?php endif; ?>
        <dt>Date:</dt>
        <dd>
            <?= htmlspecialchars($msg['sent_at']
                ? date('j F Y · H:i', strtotime($msg['sent_at']))
                : '—') ?>
        </dd>
    </dl>
</div>

<div class="em-actions">
    <a href="email-compose.php?mode=reply&id=<?= $id ?>" class="btn-mini primary">↩ Reply</a>
    <a href="email-compose.php?mode=reply_all&id=<?= $id ?>" class="btn-mini">↩↩ Reply all</a>
    <a href="email-compose.php?mode=forward&id=<?= $id ?>" class="btn-mini">↪ Forward</a>

    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="flag_toggle">
        <button type="submit" class="btn-mini">
            <?= $msg['is_flagged'] ? '⚑ Unflag' : '⚐ Flag' ?>
        </button>
    </form>

    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="mark_unseen">
        <button type="submit" class="btn-mini">Mark unread</button>
    </form>
</div>

<?php if ($body_was_refetched): ?>
    <div class="em-banner info">
        <?php if (!empty($msg['body_evicted_at'])): ?>
            <span>📥 This message body was fetched from IMAP just now (older than <?= EMAIL_BODY_KEEP_DAYS ?> days).</span>
        <?php else: ?>
            <span>📥 Body fetched from server — saved for next time.</span>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if (!empty($refetch_error)): ?>
    <div class="em-banner">
        ⚠ Could not fetch message body: <?= htmlspecialchars($refetch_error) ?>
    </div>
<?php endif; ?>

<?php if ($images_blocked > 0): ?>
    <div class="em-banner">
        <span>🛡 <?= $images_blocked ?> remote image<?= $images_blocked === 1 ? '' : 's' ?> blocked for privacy.</span>
        <span style="display:flex;gap:.5rem;flex-wrap:wrap;">
            <a href="?id=<?= $id ?>&show_images=1" class="btn-mini">Show images this time</a>
            <?php if (!empty($msg['from_email'])): ?>
                <form method="post">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="whitelist_sender">
                    <button type="submit" class="btn-mini">Always trust <?= htmlspecialchars($msg['from_email']) ?></button>
                </form>
            <?php endif; ?>
        </span>
    </div>
<?php elseif ($is_whitelisted && $body_html): ?>
    <div class="em-banner info">
        <span>✓ Sender is on your whitelist — images shown.</span>
    </div>
<?php endif; ?>

<div class="em-body">
    <?php if ($debug): ?>
        <div style="background:#fef3c7;border:1px solid #fbbf24;padding:.75rem 1rem;border-radius:6px;margin-bottom:1rem;font-size:.78rem;font-family:monospace;">
            <strong>🔧 DEBUG (remove ?debug=1 from URL to hide)</strong><br>
            <?php foreach ($debug_info as $k => $v): ?>
                <?= htmlspecialchars($k) ?> = <?= htmlspecialchars((string)$v) ?><br>
            <?php endforeach; ?>
            <br>
            <strong>render_html length:</strong> <?= strlen($render_html) ?><br>
            <strong>render_html (first 500 chars):</strong><br>
            <pre style="white-space:pre-wrap;background:#fff;padding:.5rem;border-radius:4px;margin:.25rem 0;"><?= htmlspecialchars(mb_substr($render_html, 0, 500)) ?></pre>
        </div>
    <?php endif; ?>
    <?php if ($render_html === ''): ?>
        <p class="muted" style="text-align:center;">(This message has no readable body.)</p>
    <?php else: ?>
        <?= $render_html ?>
    <?php endif; ?>

    <?php if (!empty($attachments)): ?>
        <div class="em-atts">
            <h4>📎 Attachments (<?= count($attachments) ?>)</h4>
            <?php foreach ($attachments as $i => $att):
                $size = (int)($att['size'] ?? 0);
                $size_disp = $size >= 1048576 ? round($size/1048576, 1) . ' MB'
                          : ($size >= 1024 ? round($size/1024) . ' KB' : $size . ' B');
            ?>
                <a class="em-att-row"
                   href="email-attachment.php?id=<?= $id ?>&part=<?= urlencode((string)$att['part_id']) ?>">
                    <span>📄 <?= htmlspecialchars($att['name'] ?: 'attachment') ?></span>
                    <span class="em-att-size"><?= $size_disp ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

</div></section>

<?php require __DIR__ . '/_footer.php'; ?>