<?php
final class ReportPresetService {
    public function all(): array {
        return Database::pdo()->query('SELECT id, name, description, config_json, created_at FROM report_presets ORDER BY id DESC')->fetchAll();
    }
    public function save(array $input, int $userId): array {
        $name = trim((string)($input['name'] ?? ''));
        if ($name === '') throw new RuntimeException('Informe um nome para o modelo.');
        $description = trim((string)($input['description'] ?? ''));
        $config = $input['config'] ?? [];
        if (!is_array($config)) throw new RuntimeException('Configuração inválida.');
        $pdo=Database::pdo();
        $st=$pdo->prepare('INSERT INTO report_presets (name, description, config_json, created_by, created_at) VALUES (?, ?, ?, ?, NOW())');
        $st->execute([$name, $description ?: null, json_encode($config, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES), $userId]);
        return ['id'=>(int)$pdo->lastInsertId(),'name'=>$name,'description'=>$description,'config'=>$config];
    }
    public function delete(int $id): void {
        $st=Database::pdo()->prepare('DELETE FROM report_presets WHERE id=?'); $st->execute([$id]);
    }
}
