<?php

namespace App\Controllers;

use App\Models\AbsensiModel;
use Dompdf\Dompdf;

class Laporan extends BaseController
{
    public function absensiPdf()
    {
        $startDate = $this->request->getGet('start_date');
        $endDate   = $this->request->getGet('end_date');
        $rombel    = $this->request->getGet('rombel');

        $absensiModel = new AbsensiModel();
        $builder = $absensiModel;

        if ($startDate && $endDate) {
            $builder = $builder->where('tanggal >=', $startDate)
                               ->where('tanggal <=', $endDate);
        }
        if ($rombel) {
            $builder = $builder->join('siswa', 'siswa.nisn = absensi.nisn')
                               ->where('siswa.rombel', $rombel);
        }

        $dataAbsensi = $builder->orderBy('tanggal', 'DESC')->findAll();

        // === Panggil Dompdf ===
        $dompdf = new Dompdf();

        $html = view('laporan_absensi_pdf', [
            'data'      => $dataAbsensi,
            'startDate' => $startDate,
            'endDate'   => $endDate,
            'rombel'    => $rombel
        ]);

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $this->response->setHeader('Content-Type', 'application/pdf')
                              ->setHeader('Content-Disposition', 'attachment; filename="laporan_absensi.pdf"')
                              ->setBody($dompdf->output());
    }
}