<?php
/**
 * FreshCloud Mail — save a draft
 * PUT /api/email/compose/{id}
 * Body: { user_id, to, cc?, bcc?, subject, body_html?, body_text?, attachment_ids? }
 */

require_once __DIR__ . '/../_bootstrap.php';

$draftId = basename(ltrim($_SERVER['PATH_INFO'] ?? $_GET['draft_id'] ?? '', '/'));
$body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];
$userId = $body['user_id'] ?? null;

if (!$draftId) {
    freshcloud_mail_error(400, 'missing_draft_id', 'draft_id is required in the URL path');
}
if (!$userId) {
    freshcloud_mail_error(400, 'missing_user_id', 'user_id is required in the body');
}

// Validate emails
$badEmails = [];
foreach (['to', 'cc', 'bcc'] as $field) {
    foreach (($body[$field] ?? []) as $email) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $badEmails[] = "$field: $email";
        }
    }
}
if (!empty($badEmails)) {
    freshcloud_mail_error(400, 'invalid_email', 'Invalid email addresses: ' . implode(', ', $badEmails));
}

// Try real Composer
$composer = freshcloud_mail_composer($userId, $body['account_id'] ?? null);
if ($composer !== null) {
    try {
        $body['mode'] = $body['mode'] ?? 'new';  // default to new for save
        $request = \FreshCloud\Mail\Compose\ComposeRequest::fromArray($body);
        $composer->saveDraft($draftId, $request, $userId);
        freshcloud_mail_json(200, [
            'status' => 'draft_saved',
            'draft_id' => $draftId,
            'user_id' => $userId,
            'timestamp' => gmdate('c'),
        ]);
    } catch (\Throwable $e) {
        freshcloud_mail_error(500, 'composer_failed', $e->getMessage());
    }
}

freshcloud_mail_json(200, [
    'status' => 'draft_saved',
    'draft_id' => $draftId,
    'user_id' => $userId,
    'note' => 'v0.1.0-test stub — Composer::saveDraft not yet wired. Validation passed.',
    'timestamp' => gmdate('c'),
]);
