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

class MailInternalNote extends Model
{
    public function byConversation(string $conversationKey): array
    {
        $stmt = $this->db->prepare('SELECT n.*, u.name AS created_by_name FROM mail_internal_notes n LEFT JOIN users u ON u.id = n.created_by WHERE n.conversation_key = ? ORDER BY n.created_at DESC');
        $stmt->execute([$conversationKey]);
        return $stmt->fetchAll();
    }

    public function create(string $conversationKey, string $noteBody, ?int $createdBy = null): int
    {
        $noteBody = trim($noteBody);
        if ($noteBody === '') {
            throw new RuntimeException('Note body is required.');
        }
        $stmt = $this->db->prepare('INSERT INTO mail_internal_notes (conversation_key, note_body, created_by) VALUES (?, ?, ?)');
        $stmt->execute([$conversationKey, $noteBody, $createdBy ?: null]);
        return (int)$this->db->lastInsertId();
    }
}
