<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Absensi <?php echo e(ucfirst($type)); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

    <?php
        $minggu_req = $minggu ?? request('minggu');
        $isMingguan = !empty($minggu_req);
        $ambangAlpaMingguan = $ambangAlpaMingguan ?? 4;
        $ambangFlagBulananUntukCetak = $ambangFlagBulananUntukCetak ?? 3;
    ?>

    <style>
        @page { size: A4 landscape; margin: 1.5cm 1cm; }

        body {
            font-family: "Times New Roman", Times, serif;
            font-size: 11px;
            color: #000;
            margin: 0;
            background-color: #f1f5f9;
        }

        .document-container {
            background-color: #fff;
            width: 27.7cm;
            margin: 20px auto;
            padding: 1.5cm 1cm;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }

        /* ACTION BAR */
        .action-bar {
            background: #ffffff;
            padding: 15px;
            display: flex;
            justify-content: center;
            gap: 15px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            border: 1px solid #cbd5e1;
            cursor: pointer;
            font-size: 13px;
            font-weight: 700;
            transition: 0.2s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .btn:hover { transform: translateY(-1px); box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
        .btn-back   { background: #fff; color: #334155; }
        .btn-print  { background: #0f172a; color: #fff; border: none; }
        .btn-pdf    { background: #dc2626; color: #fff; border: none; }
        .btn-pdf:hover { background: #b91c1c; }

        /* Spinner loading */
        .spinner {
            display: none;
            width: 16px;
            height: 16px;
            border: 2px solid #fff;
            border-top-color: transparent;
            border-radius: 50%;
            animation: spin 0.7s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* KOP SURAT */
        .kop-surat table { width: 100%; border-collapse: collapse; border: none; }
        .kop-surat td { border: none; padding: 2px; vertical-align: middle; }
        .teks-kop { text-align: center; line-height: 1.2; }
        .garis-kop {
            border-top: 3px solid #000;
            border-bottom: 1px solid #000;
            height: 2px;
            margin-top: 10px;
            margin-bottom: 15px;
        }

        /* JUDUL */
        .judul { text-align: center; margin-bottom: 20px; line-height: 1.4; }
        .judul h3 { margin: 0; font-size: 14px; text-decoration: underline; font-weight: bold; }
        .judul p  { margin: 3px 0 0 0; font-size: 11px; font-weight: bold; }

        /* Keterangan tanda merah */
        .ket-flag {
            margin-bottom: 12px;
            font-size: 10px;
            font-family: Arial, Helvetica, sans-serif;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .ket-flag .kotak {
            display: inline-block;
            width: 14px;
            height: 14px;
            background: #fee2e2;
            border: 1px solid #ef4444;
            vertical-align: middle;
        }

        /* TABEL */
        .table-absen {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            font-family: Arial, Helvetica, sans-serif;
            margin-bottom: 20px;
        }
        .table-absen th,
        .table-absen td {
            border: 1px solid #000;
            text-align: center;
            padding: 4px 2px;
            overflow: hidden;
            vertical-align: top;
        }
        .table-absen th {
            background: #e9ecef !important;
            font-size: 9px;
            font-weight: bold;
            text-transform: uppercase;
            vertical-align: middle;
        }
        .table-absen tr { page-break-inside: avoid; }

        /* Baris yang kena tanda merah (perlu evaluasi / sudah berulang kali) */
        .row-flag-cetak td {
            background: #fee2e2 !important;
        }
        .row-flag-cetak .col-nama strong { color: #991b1b; }
        .icon-flag-cetak { color: #991b1b; font-size: 10px; margin-left: 3px; }

        /* Ukuran kolom */
        .col-no   { width: 22px; }
        .col-id   { width: 80px; }

        /* ✅ FIX: hapus white-space nowrap, ganti word-break */
        .col-nama {
            text-align: left !important;
            padding-left: 6px !important;
            word-break: break-word;   /* ← nama panjang akan wrap */
            width: 130px;             /* ← beri lebar fixed agar tidak terlalu sempit */
            font-size: 10px;
        }

        .col-lp   { width: 22px; font-size: 9px; }
        .col-jml  { width: 30px; font-weight: bold; background: #f8f9fa !important; font-size: 10px; vertical-align: middle; }

        .col-hari {
            width: <?php echo e($isMingguan ? '58px' : '18px'); ?>;
            font-size: 9px;
        }

        /* Scan stack */
        .scan-sesi {
            font-size: 7.5px;
            color: #555;
            line-height: 1.1;
            display: block;
        }
        .scan-jam {
            font-size: 9px;
            font-weight: bold;
            line-height: 1.3;
            display: block;
        }
        .scan-divider {
            border: none;
            border-top: 1px dashed #ccc;
            margin: 2px 0;
        }

        /* Libur */
        .libur-head { background: #ef4444 !important; color: #fff !important; }
        .libur-cell { background: #fee2e2 !important; color: #ef4444; font-weight: bold; vertical-align: middle; }

        /* Tanda tangan */
        .ttd-container { margin-top: 30px; width: 100%; page-break-inside: avoid; }
        .ttd-box { float: right; width: 250px; text-align: center; font-size: 12px; line-height: 1.4; }
        .ttd-box p { margin: 2px 0; }
        .ttd-space { height: 65px; }
        .nama-kepsek { font-weight: bold; text-decoration: underline; }

        @media print {
            body { background-color: #fff; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
            .document-container { box-shadow: none; margin: 0; padding: 0; width: 100%; }
            .action-bar { display: none !important; }
            .table-absen th { background-color: #e9ecef !important; }
            .libur-head { background-color: #ef4444 !important; color: white !important; }
            .libur-cell { background-color: #fee2e2 !important; }
            .row-flag-cetak td { background-color: #fee2e2 !important; }
        }
    </style>
</head>
<body>

<div class="action-bar">
    <button class="btn btn-back" onclick="goBack()">
        <i class="bi bi-arrow-left"></i> Kembali
    </button>

    <button class="btn btn-pdf" id="btnPdf" onclick="downloadPDF()">
        <i class="bi bi-file-earmark-pdf-fill" id="iconPdf"></i>
        <div class="spinner" id="spinnerPdf"></div>
        <span id="labelPdf">Download PDF</span>
    </button>

    <button class="btn btn-print" onclick="window.print()">
        <i class="bi bi-printer-fill"></i> Cetak Laporan (A4)
    </button>
</div>

<div class="document-container" id="areaCetak">

<?php
    $namaBulan = [
        1=>'Januari',2=>'Februari',3=>'Maret',4=>'April',
        5=>'Mei',6=>'Juni',7=>'Juli',8=>'Agustus',
        9=>'September',10=>'Oktober',11=>'November',12=>'Desember'
    ];
    $namaHariSingkat = ['Min','Sen','Sel','Rab','Kam','Jum','Sab'];

    $isSiswa        = ($type ?? 'siswa') === 'siswa';
    $labelIdentitas = $isSiswa ? 'NISN' : 'IDENTITAS';
    $labelNama      = $isSiswa ? 'Nama Siswa' : 'Nama Guru / Staff';
    $labelSubJudul  = $isSiswa
        ? 'KELAS: ' . strtoupper($kelas ?? '-')
        : 'UNIT KERJA: MTs KH ZUMRATUL MUTTAQIN';

    $arrayLibur = [];
    if (isset($dataLibur)) {
        foreach ($dataLibur as $lb) {
            $start = strtotime($lb->tanggal_mulai);
            $end   = strtotime($lb->tanggal_selesai);
            for ($t = $start; $t <= $end; $t += 86400) {
                $arrayLibur[] = date('Y-m-j', $t);
            }
        }
    }

    $startDay = 1;
    $endDay   = $jumlahHari ?? 31;
    if ($isMingguan) {
        $startDay = ($minggu_req - 1) * 7 + 1;
        $endDay   = $minggu_req * 7;
        if ($endDay   > $jumlahHari) $endDay   = $jumlahHari;
        if ($startDay > $jumlahHari) $startDay = $jumlahHari;
    }
?>

    
    <div class="kop-surat">
        <table>
            <tr>
                <td style="width:110px; text-align:center;">
                    <img src="<?php echo e(asset('img/logokhz.png')); ?>" style="width:85px; height:auto;">
                </td>
                <td class="teks-kop">
                    <div style="font-size:13pt; font-weight:bold;">YAYASAN KIYAI HAJI ZUMRATUL MUTTAQIN</div>
                    <div style="font-size:10pt;">SK. MENTERI HUKUM DAN HAK ASASI MANUSIA RI</div>
                    <div style="font-size:10pt;">Nomor : AHU-0022733.AH.01.04.Tahun 2015</div>
                    <div style="font-size:18pt; font-weight:900; margin:4px 0; font-family:Arial,sans-serif;">MTs KH ZUMRATUL MUTTAQIN</div>
                    <div style="font-size:10pt;">NPSN: 60728096</div>
                    <div style="font-size:9.5pt; font-style:italic;">Kp. Gunungpari No.108 Desa Sukamenak Kec. Sukarame Kab. Tasikmalaya</div>
                </td>
                <td style="width:110px; text-align:center;">
                    <img src="<?php echo e(asset('img/logo.png')); ?>" style="width:85px; height:auto;">
                </td>
            </tr>
        </table>
        <div class="garis-kop"></div>
    </div>

    
    <div class="judul">
        <h3>DAFTAR HADIR <?php echo e($isSiswa ? 'PESERTA DIDIK' : 'GURU & STAFF'); ?></h3>
        <p>
            BULAN <?php echo e(strtoupper($namaBulan[(int)$bulan])); ?> <?php echo e($tahun); ?>

            <?php echo e($isMingguan ? '| MINGGU KE-'.$minggu_req : ''); ?>

            | <?php echo e($labelSubJudul); ?>

        </p>
    </div>

    
    <div class="ket-flag">
        <span class="kotak"></span>
        <?php if($isMingguan): ?>
            <span>
                = Alpa ≥ <?php echo e($ambangAlpaMingguan); ?>x pada Minggu ke-<?php echo e($minggu_req); ?> ini (perlu evaluasi / pemanggilan).
            </span>
        <?php else: ?>
            <span>
                = Sudah kena flag "Perlu Perhatian" di ≥ <?php echo e($ambangFlagBulananUntukCetak); ?> minggu berbeda dalam bulan ini
                (kasus berulang, perlu tindak lanjut lebih serius).
            </span>
        <?php endif; ?>
    </div>

    
    <table class="table-absen">
        <thead>
            <tr>
                <th class="col-no"   rowspan="2">No</th>
                <th class="col-id"   rowspan="2"><?php echo e($labelIdentitas); ?></th>
                <th class="col-nama" rowspan="2"><?php echo e($labelNama); ?></th>
                <th class="col-lp"   rowspan="2">L/P</th>

                <?php for($i = $startDay; $i <= $endDay; $i++): ?>
                    <?php
                        $tglKey        = "$tahun-$bulan-$i";
                        $isMingguLibur = date('w', strtotime($tglKey)) == 0;
                        $isLiburInput  = in_array($tglKey, $arrayLibur);
                    ?>
                    <th class="col-hari <?php echo e(($isMingguLibur || $isLiburInput) ? 'libur-head' : ''); ?>">
                        <?php echo e($i); ?>

                    </th>
                <?php endfor; ?>

                <th class="col-jml" rowspan="2">Hdr</th>
            </tr>
            <tr>
                <?php for($i = $startDay; $i <= $endDay; $i++): ?>
                    <?php
                        $tglKey        = "$tahun-$bulan-$i";
                        $isMingguLibur = date('w', strtotime($tglKey)) == 0;
                        $isLiburInput  = in_array($tglKey, $arrayLibur);
                        $hariIdx       = (int) date('w', strtotime($tglKey));
                    ?>
                    <th class="col-hari <?php echo e(($isMingguLibur || $isLiburInput) ? 'libur-head' : ''); ?>"
                        style="font-weight:normal; font-size:8px;">
                        <?php echo e($namaHariSingkat[$hariIdx]); ?>

                    </th>
                <?php endfor; ?>
            </tr>
        </thead>

        <tbody>
            <?php $__currentLoopData = $data_rekap; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php
                // ── Penentuan tanda merah, KONSISTEN dengan halaman web
                //    rekap bulanan (pakai data yang sama: minggu_kena_flag_list). ──
                //
                // - Cetak MINGGUAN: merah kalau minggu yang SEDANG dicetak ini
                //   ada di daftar minggu yang kena flag (alpa >= ambang &
                //   minggunya sudah selesai).
                // - Cetak BULANAN (full bulan): merah kalau sudah kena flag
                //   di >= $ambangFlagBulananUntukCetak minggu BERBEDA dalam
                //   bulan ini — pola berulang yang serius, bukan cuma sekali.
                $mingguKenaFlagList = $d['minggu_kena_flag_list'] ?? [];
                $perluTandaMerah = $isMingguan
                    ? in_array((int) $minggu_req, $mingguKenaFlagList)
                    : (($d['minggu_kena_flag'] ?? 0) >= $ambangFlagBulananUntukCetak);
            ?>
            <tr class="<?php echo e($perluTandaMerah ? 'row-flag-cetak' : ''); ?>">
                <td style="vertical-align:middle;"><?php echo e($index + 1); ?></td>
                <td style="font-size:9px; letter-spacing:0.5px; vertical-align:middle;">
                    <?php echo e($isSiswa
                        ? ($d['nisn'] ?? '-')
                        : (($d['jenis_identitas'] ?? 'ID') . ': ' . ($d['nomor_identitas'] ?? '-'))); ?>

                </td>
                <td class="col-nama" style="vertical-align:middle;">
                    <strong><?php echo e(strtoupper($d['nama'])); ?></strong>
                    <?php if($perluTandaMerah): ?>
                        <i class="bi bi-exclamation-triangle-fill icon-flag-cetak"></i>
                    <?php endif; ?>
                </td>
                <td style="vertical-align:middle;"><?php echo e($d['jk'] ?? '-'); ?></td>

                <?php for($i = $startDay; $i <= $endDay; $i++): ?>
                    <?php
                        $tglKey        = "$tahun-$bulan-$i";
                        $isMingguLibur = date('w', strtotime($tglKey)) == 0;
                        $isLiburInput  = in_array($tglKey, $arrayLibur);
                        $dayData       = $d['detail'][$i] ?? [];
                    ?>

                    <?php if($isMingguLibur || $isLiburInput): ?>
                        <td class="col-hari libur-cell">X</td>
                    <?php elseif($dayData === 'libur'): ?>
                        <td class="col-hari libur-cell">X</td>
                    <?php elseif(is_array($dayData) && count($dayData) > 0): ?>
                        <td class="col-hari" style="padding:2px;">
                            <?php $__currentLoopData = $dayData; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $scanIdx => $scan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php if($scanIdx > 0): ?><hr class="scan-divider"><?php endif; ?>
                                <?php if($isMingguan): ?>
                                    <span class="scan-sesi"><?php echo e($scan['sesi']); ?></span>
                                    <span class="scan-jam"><?php echo e($scan['jam']); ?></span>
                                <?php else: ?>
                                    <span style="font-size:10px; font-weight:bold;">✓</span>
                                <?php endif; ?>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </td>
                    <?php else: ?>
                        <td class="col-hari"></td>
                    <?php endif; ?>
                <?php endfor; ?>

                <td class="col-jml" style="vertical-align:middle;"><?php echo e($d['hadir']); ?></td>
            </tr>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </tbody>
    </table>

    
    <div class="ttd-container">
        <div class="ttd-box">
            <p>Tasikmalaya, <?php echo e(date('d')); ?> <?php echo e($namaBulan[(int)date('m')]); ?> <?php echo e(date('Y')); ?></p>
            <p>Kepala Sekolah,</p>
            <div class="ttd-space"></div>
            <p class="nama-kepsek">( Drs.H.GAOSUL ADOM, M.M.Pd. )</p>
            <p style="margin-top:3px;">NIP. 196607172007011029</p>
        </div>
        <div style="clear:both;"></div>
    </div>

</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
function goBack() {
    window.history.back();
}

async function downloadPDF() {
    const btn      = document.getElementById('btnPdf');
    const icon     = document.getElementById('iconPdf');
    const spinner  = document.getElementById('spinnerPdf');
    const label    = document.getElementById('labelPdf');

    // Tampilkan loading
    btn.disabled      = true;
    icon.style.display   = 'none';
    spinner.style.display = 'block';
    label.innerText   = 'Memproses...';

    try {
        const { jsPDF } = window.jspdf;
        const area = document.getElementById('areaCetak');

        const canvas = await html2canvas(area, {
            scale: 2,           // kualitas tinggi
            useCORS: true,      // agar logo/gambar ikut ke-render
            backgroundColor: '#ffffff',
            logging: false,
        });

        const imgData = canvas.toDataURL('image/jpeg', 0.95);

        // A4 landscape dalam mm
        const pdf = new jsPDF('landscape', 'mm', 'a4');
        const pageW = pdf.internal.pageSize.getWidth();   // 297mm
        const pageH = pdf.internal.pageSize.getHeight();  // 210mm

        // Hitung rasio agar gambar muat di halaman
        const imgW  = canvas.width;
        const imgH  = canvas.height;
        const ratio = Math.min(pageW / imgW, pageH / imgH);
        const finalW = imgW * ratio;
        const finalH = imgH * ratio;

        // Tengahkan secara vertikal & horizontal
        const offsetX = (pageW - finalW) / 2;
        const offsetY = (pageH - finalH) / 2;

        pdf.addImage(imgData, 'JPEG', offsetX, offsetY, finalW, finalH);

        // Nama file otomatis
        const namaFile = 'Laporan_Absensi_<?php echo e(ucfirst($type)); ?>_<?php echo e($bulan); ?>_<?php echo e($tahun); ?>.pdf';
        pdf.save(namaFile);

    } catch (e) {
        alert('Gagal membuat PDF. Coba lagi.');
        console.error(e);
    } finally {
        // Kembalikan tombol
        btn.disabled         = false;
        icon.style.display   = 'inline';
        spinner.style.display = 'none';
        label.innerText      = 'Download PDF';
    }
}
</script>
</body>
</html><?php /**PATH C:\laragon\www\absensi_muttaqin_v2\resources\views/laporan/cetak.blade.php ENDPATH**/ ?>