import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';

Future<void> generatePdf(List<Map<String, String>> data, String date) async {
  final pdf = pw.Document();

  pdf.addPage(
    pw.Page(
      build: (context) => pw.Column(
        children: [
          pw.Text(
            "Liste de présence - $date",
            style: pw.TextStyle(fontSize: 20),
          ),
          pw.SizedBox(height: 20),
          pw.Table.fromTextArray(
            headers: [
              "N° Etudiant",
              "Prénom",
              "Nom",
              "Mac NFC",
              "QR",
              "Heure",
            ],
            data: data.map((e) => [
              e['N° Etudiant'] ?? '',
              e['Prénom'] ?? '',
              e['Nom'] ?? '',
              e['Mac NFC'] ?? '',
              e['QR'] ?? '',
              e['date_ajout'] ?? '',
            ]).toList(),
          ),
        ],
      ),
    ),
  );
  final bytes = await pdf.save();
  try {
    await Printing.layoutPdf(
      onLayout: (_) async => bytes,
    );
  } catch (e) {
    print("layoutPdf indisponible, fallback vers sharePdf");

    await Printing.sharePdf(
      bytes: bytes,
      filename: 'presence_$date.pdf',
    );
  }
}
