<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<nav class="page-breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">Laporan</li>
        <li class="breadcrumb-item active" aria-current="page">Laporan Data Kas</li>
    </ol>
</nav>

<!-- Filter Form -->
<!-- <form id="filterForm">
    <div class="row">
        <div class="col-md-4">
            <label for="tanggal_awal">Tanggal Awal:</label>
            <input type="date" name="tanggal_awal" required class="form-control">
        </div>
        <div class="col-md-4">
            <label for="tanggal_akhir">Tanggal Akhir:</label>
            <input type="date" name="tanggal_akhir" required class="form-control">
        </div>
        <div class="col-md-4">
            <button type="submit" class="btn btn-primary mt-4">Filter</button>
        </div>
    </div>
</form> -->

<!-- Action Buttons -->
<!-- <div class="mt-3">
    <button id="cetakPDF" class="btn btn-danger" disabled>Cetak PDF</button>
    <button id="exportExcel" class="btn btn-success" disabled>Export Excel</button>
</div> -->

<!-- Tombol Export -->
<div class="d-flex justify-content-end  ms-auto mb-3">
    <!-- Tombol Export PDF -->
    <button type="button" class="btn btn-danger btn-sm me-2" title="Export PDF" onclick="exportPDF()">
        <i class="icon-md" data-feather="file"></i> Export PDF
    </button>

    <!-- Tombol Export Excel -->
    <button type="button" class="btn btn-success btn-sm ml-3" title="Export Excel" onclick="exportExcel()">
        <i class="icon-md" data-feather="file-text"></i> Export Excel
    </button>
</div>

<!-- Data Table -->
<div class="table-responsive">
    <table id="dataTableExample" class="table table-bordered table-hover">
        <thead class="table-info text-dark">
            <tr>
                <th style="width: 5%;">No</th>
                <th>Tanggal Mulai</th>
                <th>Tanggal Akhir</th>
                <th>Nama Pelanggan</th>
                <th>Nama Paket</th>
                <th>Lunas</th>
                <th>Belum Lunas</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $totalLunas = 0;
            $totalBelumLunas = 0;
            ?>
            <?php if (!empty($tagihanList)): ?>
                <?php foreach ($tagihanList as $index => $tagihan): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td><?= date('d F Y', strtotime($tagihan['tanggal_mulai'])) ?></td>
                        <td><?= date('d F Y', strtotime($tagihan['tanggal_akhir'])) ?></td>
                        <td><?= $tagihan['nama_pelanggan'] ?></td>
                        <td><?= $tagihan['nama_paket'] ?></td>
                        <td>
                            <?php if ($tagihan['status_tagihan'] == 'Lunas'): ?>
                                Rp <?= number_format($tagihan['total'], 0, ',', '.') ?>
                                <?php $totalLunas += $tagihan['total']; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($tagihan['status_tagihan'] == 'Belum Lunas'): ?>
                                Rp <?= number_format($tagihan['total'], 0, ',', '.') ?>
                                <?php $totalBelumLunas += $tagihan['total']; ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center" style="background-color: #f9f9f9; color: #888; font-style: italic; padding: 20px;">
                        <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i>
                        <br>
                        <span style="font-size: 16px; font-weight: bold;">Tidak ada data yang tersedia.</span>
                        <br>
                        <span style="font-size: 14px;">Silakan tambahkan data baru untuk mengisi tabel ini.</span>
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5" class="text-right font-weight-bold">Total</td>
                <td>Rp <?= number_format($totalLunas, 0, ',', '.') ?></td>
                <td>Rp <?= number_format($totalBelumLunas, 0, ',', '.') ?></td>
            </tr>
        </tfoot>
    </table>
</div>

<script>
    $(document).ready(function() {
        // Filter Form Submit
        $('#filterForm').submit(function(event) {
            event.preventDefault();

            $.ajax({
                url: "<?= base_url('/laporan/filter') ?>",
                type: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    let rows = '';
                    data.forEach((b, index) => {
                        rows += `<tr>
                        <td>${index + 1}</td>
                        <td>${b.nama}</td>
                        <td>${b.nik}</td>
                        <td>${b.alamat}</td>
                        <td>${b.nama_ibu}</td>
                        <td>${b.nama_ayah}</td>
                        <td>${b.jenis_kelamin}</td>
                        <td>${b.tanggal_lahir}</td>
                        <td>${b.berat_badan}</td>
                        <td>${b.tinggi_badan}</td>
                        <td>${b.status_imunisasi}</td>
                        <td>${b.created_at}</td>
                    </tr>`;
                    });
                    $('#laporanTable tbody').html(rows);


                    // Aktifkan tombol setelah data berhasil dimuat
                    $('#cetakPDF').prop('disabled', false);
                    $('#exportExcel').prop('disabled', false);
                }
            });
        });

        // Print PDF
        $('#cetakPDF').click(function() {
            const params = $('#filterForm').serialize();

            // Cek apakah filter sudah dipilih
            if ($('#tanggal_awal').val() === "" || $('#tanggal_akhir').val() === "") {
                alert("Harap pilih tanggal awal dan tanggal akhir sebelum mencetak PDF!");
                return; // Hentikan eksekusi jika filter belum dipilih
            }

            window.open('<?= base_url('') ?>/laporan/cetakPDF?' + params, '_blank');
        });

        // Export to Excel
        $('#exportExcel').click(function() {
            const params = $('#filterForm').serialize();
            window.open('<?= base_url('') ?>/laporan/exportExcel?' + params, '_blank');
        });
    });
</script>

<!-- untuk script export pdf dan excel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.3/xlsx.full.min.js"></script>

<script>
    function exportPDF() {
        if (!window.jspdf || !window.jspdf.jsPDF) {
            alert("Library jsPDF tidak ditemukan! Coba refresh halaman.");
            return;
        }

        const {
            jsPDF
        } = window.jspdf;
        let doc = new jsPDF('p', 'mm', 'a4');

        // Judul PDF
        doc.setFont("helvetica", "bold");
        doc.setFontSize(16);
        doc.text("Laporan Tagihan Pelanggan", 14, 15);

        // Header tabel yang sesuai dengan laporan tagihan
        let headers = [
            ["NO", "TANGGAL MULAI", "TANGGAL AKHIR", "NAMA PELANGGAN", "NAMA PAKET", "LUNAS", "BELUM LUNAS"]
        ];

        // Ambil data tabel yang terlihat setelah filter
        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim()); // No
            row.push($(this).find("td:eq(1)").text().trim()); // Tanggal Mulai
            row.push($(this).find("td:eq(2)").text().trim()); // Tanggal Akhir
            row.push($(this).find("td:eq(3)").text().trim()); // Nama Pelanggan
            row.push($(this).find("td:eq(4)").text().trim()); // Nama Paket
            row.push($(this).find("td:eq(5)").text().trim()); // Lunas
            row.push($(this).find("td:eq(6)").text().trim()); // Belum Lunas
            data.push(row);
        });

        // Ambil total dari footer
        let totalLunas = $("#dataTableExample tfoot td:eq(1)").text().trim();
        let totalBelumLunas = $("#dataTableExample tfoot td:eq(2)").text().trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        // Tambahkan baris total ke PDF
        data.push(["", "", "", "", "Total", totalLunas, totalBelumLunas]);

        // Gunakan autoTable untuk membuat tabel di PDF
        doc.autoTable({
            head: headers,
            body: data,
            startY: 25,
            styles: {
                fontSize: 10
            },
            theme: 'grid',
            headStyles: {
                fillColor: [22, 160, 133]
            },
            margin: {
                top: 30
            }
        });

        doc.save("Laporan_Tagihan.pdf");
    }

    function exportExcel() {
        if (typeof XLSX === 'undefined') {
            alert("XLSX tidak ditemukan!");
            return;
        }

        let ws = XLSX.utils.aoa_to_sheet([]);

        // Header tabel yang sesuai dengan laporan tagihan
        let headers = [
            ["NO", "TANGGAL MULAI", "TANGGAL AKHIR", "NAMA PELANGGAN", "NAMA PAKET", "LUNAS", "BELUM LUNAS"]
        ];
        XLSX.utils.sheet_add_aoa(ws, headers, {
            origin: "A1"
        });

        // Ambil data tabel yang terlihat
        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim()); // No
            row.push($(this).find("td:eq(1)").text().trim()); // Tanggal Mulai
            row.push($(this).find("td:eq(2)").text().trim()); // Tanggal Akhir
            row.push($(this).find("td:eq(3)").text().trim()); // Nama Pelanggan
            row.push($(this).find("td:eq(4)").text().trim()); // Nama Paket
            row.push($(this).find("td:eq(5)").text().trim()); // Lunas
            row.push($(this).find("td:eq(6)").text().trim()); // Belum Lunas
            data.push(row);
        });

        // Ambil total dari footer
        let totalLunas = $("#dataTableExample tfoot td:eq(1)").text().trim();
        let totalBelumLunas = $("#dataTableExample tfoot td:eq(2)").text().trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        // Tambahkan baris total ke Excel
        data.push(["", "", "", "", "Total", totalLunas, totalBelumLunas]);

        XLSX.utils.sheet_add_aoa(ws, data, {
            origin: "A2"
        });

        // Buat workbook dan simpan sebagai file Excel
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Laporan Tagihan");

        XLSX.writeFile(wb, "Laporan_Tagihan.xlsx");
    }
</script>


<?= $this->endSection(); ?>