<?php
require_once __DIR__ . '/../Core.php';

class MailDraft extends Model
{
    public function findForUser(int $userId, string $draftType = 'compose', ?string $conversationKey = null): ?array
    {
        $conversationKey = $conversationKey !== null && $conversationKey !== '' ? $conversationKey : null;
        $sql = 'SELECT * FROM mail_drafts WHERE user_id = ? AND draft_type = ? AND ' . ($conversationKey === null ? 'conversation_key IS NULL' : 'conversation_key = ?') . ' ORDER BY updated_at DESC LIMIT 1';
        $stmt = $this->db->prepare($sql);
        $params = [$userId, $draftType];
        if ($conversationKey !== null) {
            $params[] = $conversationKey;
        }
        $stmt->execute($params);
        return $stmt->fetch() ?: null;
    }

    public function saveForUser(int $userId, string $draftType, ?string $conversationKey, array $data): int
    {
        $conversationKey = $conversationKey !== null && $conversationKey !== '' ? $conversationKey : null;
        $existing = $this->findForUser($userId, $draftType, $conversationKey);
        $payload = [
            'contact_id' => (int)($data['contact_id'] ?? 0) ?: null,
            'to_address' => trim((string)($data['to_address'] ?? '')) ?: null,
            'subject' => trim((string)($data['subject'] ?? '')) ?: null,
            'body' => (string)($data['body'] ?? ''),
        ];
        if ($existing) {
            $stmt = $this->db->prepare('UPDATE mail_drafts SET contact_id = ?, to_address = ?, subject = ?, body = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$payload['contact_id'], $payload['to_address'], $payload['subject'], $payload['body'], (int)$existing['id']]);
            return (int)$existing['id'];
        }
        $stmt = $this->db->prepare('INSERT INTO mail_drafts (user_id, draft_type, conversation_key, contact_id, to_address, subject, body) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([$userId, $draftType, $conversationKey, $payload['contact_id'], $payload['to_address'], $payload['subject'], $payload['body']]);
        return (int)$this->db->lastInsertId();
    }

    public function deleteForUser(int $userId, int $draftId): void
    {
        $stmt = $this->db->prepare('DELETE FROM mail_drafts WHERE id = ? AND user_id = ?');
        $stmt->execute([$draftId, $userId]);
    }
}
