<?php
require_once 'connect.php';
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['subject']) || !isset($data['content'])) {
        throw new Exception('Missing required fields');
    }

    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    $draftFolder = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}Drafts';
    
    $to = isset($data['to']) ? $data['to'] : '';
    $cc = isset($data['cc']) ? $data['cc'] : '';
    $bcc = isset($data['bcc']) ? $data['bcc'] : '';
    
    $boundary = uniqid('boundary');
    
    $headers = [
        'From: ' . $mailbox['config']['email'],
        'To: ' . $to,
        'Subject: ' . $data['subject'],
        'X-Draft-Info: ' . json_encode([
            'to' => $to,
            'cc' => $cc,
            'bcc' => $bcc,
            'draft_id' => isset($data['draft_id']) ? $data['draft_id'] : uniqid()
        ]),
        'MIME-Version: 1.0',
        'Content-Type: multipart/alternative; boundary=' . $boundary
    ];

    if ($cc) $headers[] = 'Cc: ' . $cc;
    if ($bcc) $headers[] = 'Bcc: ' . $bcc;

    $message = implode("\r\n", $headers) . "\r\n\r\n";
    $message .= "--" . $boundary . "\r\n";
    $message .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
    $message .= strip_tags($data['content']) . "\r\n\r\n";
    $message .= "--" . $boundary . "\r\n";
    $message .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
    $message .= $data['content'] . "\r\n\r\n";
    $message .= "--" . $boundary . "--";

    if (isset($data['draft_id'])) {
        $drafts = imap_search($connection, 'TEXT "' . $data['draft_id'] . '"', SE_UID, 'UTF-8');
        if ($drafts) {
            foreach ($drafts as $uid) {
                imap_delete($connection, $uid, FT_UID);
            }
            imap_expunge($connection);
        }
    }

    if (imap_append($connection, $draftFolder, $message, "\\Draft")) {
        echo json_encode([
            'success' => true,
            'message' => 'Draft saved successfully',
            'draft_id' => isset($data['draft_id']) ? $data['draft_id'] : uniqid()
        ]);
    } else {
        throw new Exception('Failed to save draft');
    }

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

if (isset($connection)) {
    imap_close($connection);
}