<?php 
if(check_permission('siswa', 'can_view')):

$fotoSiswa = ($siswa->foto) ? base_url('uploads/siswa/'.$siswa->foto) : base_url('uploads/siswa/foto.jpg') ;

?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<div class="container mt-4">
    <?php if(check_permission('siswa', 'can_update')): ?>
    <div class="text-end mb-3">
        <button class="btn btn-success btn-eximport d-none d-lg-inline" id="downloadPdfBtn">
            <i class="bi bi-file-earmark-pdf-fill me-1"></i> Export PDF Halaman Ini
        </button>
    </div>
    <?php endif; ?>
    <div id="containerDownload">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0 fw-bold">Detail Santri</h4>
    </div>

    <div class="row align-items-stretch">

        <!-- ================== DETAIL SANTRI ================== -->
        <div class="col-md-6 mb-3">
            <div class="card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h5 class="fw-semibold">Informasi Santri</h5>
                    <hr>

                    <center>
                        <img class="foto-santri rounded-4 shadow-sm mb-3"
                             src="<?= $fotoSiswa; ?>"
                             style="width:160px;height:200px;object-fit:cover;">
                    </center>

                    <table class="table table-borderless">
                        <tr>
                            <th width="200">Nama</th>
                            <td>: <?= $siswa->nama; ?></td>
                        </tr>
                        <tr>
                            <th>NIS</th>
                            <td>: <?= $siswa->nis; ?></td>
                        </tr>
                        <tr>
                            <th>Kelas</th>
                            <td>: <?= $siswa->nama_kelas; ?></td>
                        </tr>
                        <tr>
                            <th>Kamar</th>
                            <td>: <?= $siswa->nama_kamar . ' ('.$siswa->nama_gedung_kamar.')'; ?></td>
                        </tr>
                        <tr>
                            <th>Tahun Masuk</th>
                            <td>: <?= $siswa->tahun_masuk; ?></td>
                        </tr>
                        <tr>
                            <th>Alamat</th>
                            <td>: <?= $siswa->alamat; ?></td>
                        </tr>
                        <tr>
                            <th>Nama Wali Santri</th>
                            <td>: <?= $siswa->nama_wali; ?></td>
                        </tr>
                        <tr>
                            <th>No Whatsapp Wali Santri</th>
                            <td>: <?= $siswa->nomor_whatsapp; ?></td>
                        </tr>
                        <tr>
                            <th>Email Wali Santri</th>
                            <td>: <?= $siswa->email; ?></td>
                        </tr>
                        <tr>
                            <th>Jumlah Kunjungan</th>
                            <td>: <?= $siswa->jumlah_kunjungan; ?></td>
                        </tr>
                    </table>

                </div>
            </div>
        </div>

        <!-- ================== KARTU WALI SANTRI ================== -->
        <div class="col-md-6 mb-3">
            <div class="card shadow-sm border-0 rounded-4 h-100">
                <div class="card-body p-4">

                    <h5 class="fw-semibold">Kartu Tanda Wali Santri</h5>
                    <hr>

                    <div class="items-card-center">
                        <img id="defaultBg" src="<?= base_url($setting->card_background) ?>" hidden>
                        <div id="cardPreview"></div>
                    </div>

                    <div class="text-center mt-4">
                        <?php if(check_permission('siswa', 'can_update')): ?>
                        <button class="btn btn-success btn-add rounded-3 mt-4" onclick="printCardPDF()">
                            <i class="bi bi-printer me-1"></i> Print ID Card
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>

    </div>

      <div class="card modern-card shadow-sm border-0 rounded-4 mt-3 mb-4">
          <div class="card-body p-4">
              
              <div class="d-flex justify-content-between align-items-center">
                  <h5 class="mb-1">Riwayat Kunjungan</h5>
              </div>

              <div class="table-responsive">
                  <table id="tableHistory" class="table modern-table align-middle w-100">
                      <thead>
                          <tr>
                              <th>No</th>
                              <th>Nama</th>
                              <th>NIS</th>
                              <th>Kelas</th>
                              <th>Kamar</th>
                              <th>Nama Wali</th>
                              <th>Alamat</th>
                              <th>Jam Masuk</th>
                              <th>Petugas Masuk</th>
                              <th>Jam Keluar</th>
                              <th>Petugas Keluar</th>
                          </tr>
                      </thead>
                      <tbody></tbody>
                  </table>
              </div>

          </div>
      </div>
    </div>
</div>




<script>
$(document).ready(function() {

    let isInitialLoad = true;
    $('#dateRangeFilter').val('');

    $('#dateRangeFilter').daterangepicker({
        autoUpdateInput: false,
        locale: { cancelLabel: false, format: 'YYYY-MM-DD' },
        linkedCalendars: false
    });

    $('#dateRangeFilter').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        table.ajax.reload();
    });

    $('#dateRangeFilter').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
        table.ajax.reload();
    });

    let table = $('#tableHistory').DataTable({
        dom: '<"dataTables_top d-flex justify-content-between mb-3"l f>rtip',
        processing: true,
        serverSide: true,
        responsive: false,
        autoWidth: false,
        order: [],
        ajax: {
            url: "<?= base_url('siswa/get_kunjungan'); ?>",
            type: "POST",
            data: function(d) {

                // Tambahkan id_siswa dari PHP
                d.id_siswa = `<?= $siswa->id; ?>`;

                // Tambahkan filter tanggal
                var picker = $('#dateRangeFilter').data('daterangepicker');
                if (picker && picker.startDate && picker.startDate.isValid()) {
                    d.startDate = picker.startDate.format('YYYY-MM-DD');
                }
                if (picker && picker.endDate && picker.endDate.isValid()) {
                    d.endDate = picker.endDate.format('YYYY-MM-DD');
                }
            }
        },
        columns: [
            { data: 0, orderable: false }, // No
            { data: 1 }, // Nama
            { data: 2 }, // NIS
            { data: 3 }, // Kelas
            { data: 4 }, // Kamar
            { data: 5 }, // Nama Wali
            { data: 6 }, // Alamat
            { 
                data: 7, // Jam Masuk
                render: function(data) {
                    return data ? data : '';
                }
            },
            { 
                data: 8, // Media Masuk
                orderable: false,
                render: function(data) {
                    return data ? data : '';
                }
            },
            { 
                data: 9, // Jam Keluar
                render: function(data) {
                    return data ? data : '';
                }
            },
            { 
                data: 10, // Media Keluar
                orderable: false,
                render: function(data) {
                    return data ? data : '';
                }
            }
        ],
        language: {
            processing: `<div class="d-flex justify-content-center"><div class="spinner-border text-success"></div></div>`
        }
    });

    $('.dataTables_filter input').attr('placeholder', 'Cari nama, nis, kelas...').css({
        'padding': '6px 12px',
        'border-radius': '6px',
        'border': '1px solid #ced4da',
        'font-size': '0.9rem',
        'box-sizing': 'border-box'
    });

    table.on('draw', function() {
        $('#tableHistory tbody tr').each(function() {
            $(this).find('td').each(function(index) {
                let header = $('#tableHistory thead th').eq(index).text().trim();
                $(this).attr('data-label', header + ' : ');
            });
        });
    });

});
</script>

<script>

/* ============================================================
   1. DETEKSI ORIENTASI BACKGROUND & LOAD TEMPLATE OTOMATIS
============================================================ */
window.addEventListener("DOMContentLoaded", function () {
    let bg = document.getElementById("defaultBg");

    if (!bg) {
        console.error("defaultBg tidak ditemukan!");
        return;
    }

    // Tunggu gambar background selesai diload
    bg.onload = function () {
        let isPortrait = bg.naturalHeight > bg.naturalWidth;

        console.log("Background orientation:",
            isPortrait ? "POTRAIT" : "LANDSCAPE"
        );

        loadCardPreviewFromImage(bg.src, isPortrait);
    };

    // Jika gambar sudah cached & tidak trigger onload
    if (bg.complete) {
        bg.onload();
    }
});


/* ============================================================
   2. LOAD TEMPLATE CARD
============================================================ */
function loadCardPreviewFromImage(imgSrc, isPortrait) {
    let preview = document.getElementById("cardPreview");
    if (!preview) return;

    preview.style.backgroundImage = "url('" + imgSrc + "')";
    preview.className = "";

    if (isPortrait) {
        preview.classList.add("id-card-potret");
        preview.innerHTML = portraitTemplate();
    } else {
        preview.classList.add("id-card-lemscape");
        preview.innerHTML = landscapeTemplate();
    }
}


/* ============================================================
   3. TEMPLATE POTRAIT
============================================================ */
function portraitTemplate() {
    return `
        <div class="card-inner">

            <div class="card-logo">
                <img src="<?= base_url('assets/img/logo.png'); ?>">
            </div>

            <div class="card-title">Kartu Tanda Wali Santri</div>

            <div class="photo-wrapper">
                <img src="<?= $fotoSiswa; ?>">
            </div>

            <div class="card-info">
                <div class="nama"><?= $siswa->nama; ?></div>
                <div class="nis">NIS: <?= $siswa->nis; ?></div>
                <div class="kelas">Tahun Masuk: <?= $siswa->tahun_masuk; ?></div>
                <div class="alamat"><?= $siswa->alamat; ?></div>
            </div>

            <div class="qr-wrapper">
                <img src="<?= base_url('qr/show/' . urlencode($siswa->qr_id)) ?>" width="100%">
            </div>

        </div>
    `;
}


/* ============================================================
   4. TEMPLATE LANDSCAPE
============================================================ */
function landscapeTemplate() {
    return `
        <div class="card-inner">

            <div class="card-logo">
                <img src="<?= base_url('assets/img/logo.png'); ?>">
            </div>

            <div class="card-title">Kartu Tanda Wali Santri</div>

            <div class="landscape-content">

                <div class="photo-wrapper">
                    <img src="<?= $fotoSiswa; ?>">
                </div>

                <div class="card-info">
                    <div class="nama"><?= $siswa->nama; ?></div>
                    <div class="nis">NIS: <?= $siswa->nis; ?></div>
                    <div class="kelas">Tahun Masuk: <?= $siswa->tahun_masuk; ?></div>
                    <div class="alamat"><?= $siswa->alamat; ?></div>
                </div>

                <div class="qr-wrapper">
                    <img src="<?= base_url('qr/show/' . urlencode($siswa->qr_id)) ?>" width="100%">
                </div>

            </div>

        </div>
    `;
}


/* ============================================================
   5. PRINT CARD DALAM MODE PDF
============================================================ */
function printCardPDF() {
    let card = document.getElementById("cardPreview");
    if (!card) {
        alert("Card Preview tidak ditemukan!");
        return;
    }

    // Ambil semua CSS di halaman
    let styles = "";
    document.querySelectorAll("style, link[rel='stylesheet']").forEach((el) => {
        styles += el.outerHTML;
    });

    // Buka jendela print
    let w = window.open("", "_blank");

    w.document.write(`
        <html>
        <head>
            <title>Cetak Kartu Santri</title>
            ${styles} <!-- COPY semua CSS -->
            <style>
                body { 
                    margin: 0;
                    padding: 20px;
                    display: flex;
                    zoom: 69%;
                    background: #fff !important;
                }

                /* Pastikan background ikut ke print */
                @media print {
                    #cardPreview {
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                    * {
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                }
            </style>
        </head>
        <body>
            ${card.outerHTML}
        </body>
        </html>
    `);

    w.document.close();

    // Tunggu elemen selesai render
    setTimeout(() => {
        w.print();
        // w.close(); // Kalau mau ditutup otomatis
    }, 500);
}

</script>

<?php endif; ?>

<script>
document.getElementById('downloadPdfBtn').addEventListener('click', function() {
    // Ambil seluruh container
    const container = document.getElementById('containerDownload'); 
    if (!container) {
        alert("Container tidak ditemukan!");
        return;
    }

    // Opsi PDF
    const opt = {
        margin:       0.5,            // Margin dalam inch
        filename:     'Detail_Santri_<?= $siswa->nama ?>.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2, logging: true, letterRendering: true, useCORS: true },
        jsPDF:        { unit: 'in', format: 'a4', orientation: 'landscape' }
    };

    // Generate PDF
    html2pdf().set(opt).from(container).save();
});
</script>
