<?php
require_once 'connect.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['to']) || !isset($data['subject']) || !isset($data['content'])) {
        throw new Exception('Missing required fields');
    }

    $mail = getSmtpConnection();
    
    $recipients = explode(',', $data['to']);
    foreach ($recipients as $recipient) {
        $mail->addAddress(trim($recipient));
    }

    if (isset($data['cc'])) {
        $ccRecipients = explode(',', $data['cc']);
        foreach ($ccRecipients as $cc) {
            $mail->addCC(trim($cc));
        }
    }

    if (isset($data['bcc'])) {
        $bccRecipients = explode(',', $data['bcc']);
        foreach ($bccRecipients as $bcc) {
            $mail->addBCC(trim($bcc));
        }
    }

    $mail->isHTML(true);
    $mail->Subject = $data['subject'];
    $mail->Body = $data['content'];
    $mail->AltBody = strip_tags($data['content']);

    if (isset($_FILES['attachments'])) {
        foreach ($_FILES['attachments']['tmp_name'] as $key => $tmpName) {
            $mail->addAttachment(
                $tmpName,
                $_FILES['attachments']['name'][$key],
                'base64',
                $_FILES['attachments']['type'][$key]
            );
        }
    }

    if (isset($data['inReplyTo'])) {
        $mail->addCustomHeader('In-Reply-To', $data['inReplyTo']);
        $mail->addCustomHeader('References', $data['references'] ?? $data['inReplyTo']);
    }

    $mailbox = getMailboxConnection();
    
    if ($mail->send()) {
        $sentFolder = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}Sent';
        imap_append(
            $mailbox['connection'],
            $sentFolder,
            $mail->getSentMIMEMessage(),
            "\\Seen"
        );
        
        echo json_encode([
            'success' => true,
            'message' => 'Email sent successfully'
        ]);
    } else {
        throw new Exception('Email could not be sent');
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

if (isset($mailbox['connection'])) {
    imap_close($mailbox['connection']);
}