<?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;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
        exit;
    }

    $accountId = (int)($_POST['account_id'] ?? 0);
    $to = trim($_POST['to'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $bodyPlain = (string)($_POST['body'] ?? '');

    if ($accountId <= 0) {
        echo json_encode(['success' => false, 'error' => 'No mailbox account selected.']);
        exit;
    }
    if (empty($to) || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'error' => 'A valid recipient address is required.']);
        exit;
    }
    if (empty($subject)) {
        echo json_encode(['success' => false, 'error' => 'Subject is required.']);
        exit;
    }

    $bodyHtml = nl2br(htmlspecialchars($bodyPlain));

    $mailboxService = new MailboxService($conn, $accountId);
    $mailboxService->sendMail($to, $subject, $bodyHtml, $bodyPlain);

    echo json_encode(['success' => true]);
} catch (Throwable $e) {
    error_log('Mailbox send failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
