<?php
// ============================================================
//  admin/email-attachment.php — download an attachment
// ============================================================
//
//  Fetches the attachment bytes from IMAP on demand (we don't
//  store attachment bodies). Streams them as a file download.
// ============================================================

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

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

if (!$id || $part === '') { http_response_code(400); exit('Bad request.'); }

$msg = db_row(
    "SELECT m.*, a.imap_host, a.imap_port, a.imap_encryption,
            a.imap_username, a.imap_password
       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.'); }

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'],
    ];
    $att = email_fetch_attachment($acct_full, $msg['folder'], (int)$msg['uid'], $part);
} catch (Throwable $e) {
    http_response_code(500);
    exit('Could not fetch attachment: ' . htmlspecialchars($e->getMessage()));
}

// Stream as download
$name = preg_replace('/[\r\n"\\\\]/', '_', $att['name']);
$mime = $att['mime'] ?: 'application/octet-stream';

header('Content-Type: ' . $mime);
header('Content-Length: ' . strlen($att['data']));
header('Content-Disposition: attachment; filename="' . $name . '"');
header('X-Content-Type-Options: nosniff');
echo $att['data'];