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

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

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM templates WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function save(array $data): bool
    {
        if (!empty($data['id'])) {
            $stmt = $this->db->prepare('UPDATE templates SET name=?, type=?, subject=?, body=?, media_path=?, updated_at=NOW() WHERE id=?');
            return $stmt->execute([
                $data['name'],
                $data['type'],
                $data['subject'] ?? null,
                $data['body'],
                $data['media_path'] ?? null,
                $data['id'],
            ]);
        }

        $stmt = $this->db->prepare('INSERT INTO templates (name, type, subject, body, media_path) VALUES (?, ?, ?, ?, ?)');
        return $stmt->execute([
            $data['name'],
            $data['type'],
            $data['subject'] ?? null,
            $data['body'],
            $data['media_path'] ?? null,
        ]);
    }

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