<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/MailboxService.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    $accountId = (int)($_GET['account_id'] ?? 0);
    $uid = (int)($_GET['uid'] ?? 0);
    $folder = trim($_GET['folder'] ?? 'INBOX');
    if ($accountId <= 0) {
        echo json_encode(['success' => false, 'error' => 'No mailbox account selected.']);
        exit;
    }
    if ($uid <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid message id.']);
        exit;
    }

    $mailboxService = new MailboxService($conn, $accountId);
    $message = $mailboxService->fetchMessage($uid, $folder);

    echo json_encode([
        'success' => true,
        'message' => [
            'subject' => htmlspecialchars($message['subject']),
            'from' => htmlspecialchars($message['from']),
            'date' => htmlspecialchars($message['date']),
            'body_html' => $message['body_html'],
            'body_plain' => $message['body_plain'] ? htmlspecialchars($message['body_plain']) : '',
        ],
    ]);
} catch (Throwable $e) {
    error_log('Mailbox view message failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Unable to load message.']);
}
