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

class CannedReply extends Model
{
    public function all(?string $channel = null): array
    {
        if ($channel) {
            $stmt = $this->db->prepare('SELECT * FROM canned_replies WHERE channel = ? ORDER BY id DESC');
            $stmt->execute([$channel]);
            return $stmt->fetchAll();
        }
        return $this->db->query('SELECT * FROM canned_replies ORDER BY id DESC')->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO canned_replies (title, channel, subject, body, created_by) VALUES (?, ?, ?, ?, ?)');
        $stmt->execute([
            trim((string)($data['title'] ?? 'Quick Reply')),
            $data['channel'] ?? 'email',
            trim((string)($data['subject'] ?? '')) ?: null,
            trim((string)($data['body'] ?? '')),
            current_user()['id'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM canned_replies WHERE id = ?');
        $stmt->execute([$id]);
    }
}
