<?= $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 Mutasi</li>
    </ol>
</nav>

<div class="d-flex align-items-center justify-content-between border p-3 rounded flex-wrap gap-3">
    <!-- Filter Tanggal -->
    <div class="d-flex align-items-center gap-2 flex-wrap">

        <label for="tanggal" class="mb-0">Tanggal Awal</label>
        <div class="input-group flatpickr w-auto" id="flatpickr-date">
            <input type="text" name="tanggal_awal" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
            <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
        </div>

        <label for="tanggal" class="mb-0">Tanggal Akhir</label>
        <div class="input-group flatpickr w-auto" id="flatpickr-date">
            <input type="text" name="tanggal_akhir" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
            <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
        </div>

        <label for="filter_nis_siswa" class="mb-0">Filter NIS atau Nama</label>
        <select id="filter_nis_siswa" class="form-select flatpickr w-auto form-select" data-width="200px">
            <option value="" disable selected>Pilih NIS Atau Nama</option>
            <?php foreach ($siswa as $row): ?>
                <option value="<?= $row['id_siswa'] ?>"><?= $row['nis'] ?> | | <?= $row['nama'] ?></option>
            <?php endforeach; ?>
        </select>
    </div>


    <!-- Tombol Export -->
    <div class="d-flex gap-2">
        <button type="button" class="btn btn-danger btn-sm" title="Export PDF" onclick="exportPDF()">
            <i class="icon-md" data-feather="file"></i> Print PDF
        </button>
        <button type="button" class="btn btn-success btn-sm" title="Export Excel" onclick="exportExcel()">
            <i class="icon-md" data-feather="file-text"></i> Excel Excel
        </button>
    </div>
</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</th>
                <th>Jenistransaksi</th>
                <th>keterangan</th>
                <th>jumlahsetor</th>
                <th>jumlahtarik</th>
                <th>Saldo Akhir</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $totalSetor = 0;
            $totalTarik = 0;
            $saldo = 0;
            ?>
            <?php if (!empty($transaksi)): ?>
                <?php foreach ($transaksi as $row): ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= date('d F Y', strtotime($row['tanggal'])) ?></td>
                        <td><?= ucfirst($row['jenis']) ?></td>
                        <td><?= $row['keterangan'] ?></td>
                        <td>
                            <?php if ($row['jenis'] == 'setor'): ?>
                                Rp <?= number_format($row['jumlah'], 0, ',', '.') ?>
                                <?php $totalSetor += $row['jumlah'];
                                $saldo += $row['jumlah'];
                                ?>

                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($row['jenis'] == 'tarik'): ?>
                                Rp <?= number_format($row['jumlah'], 0, ',', '.') ?>
                                <?php $totalTarik += $row['jumlah'];
                                $saldo -= $row['jumlah'];
                                ?>
                            <?php endif; ?>
                        </td>
                        <td><strong>Rp <?= number_format($saldo, 0, ',', '.') ?></strong></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="4" class="text-right font-weight-bold">Total</td>
                <td>Rp <?= number_format($totalSetor, 0, ',', '.') ?></td>
                <td>Rp <?= number_format($totalTarik, 0, ',', '.') ?></td>
                <td><strong>Rp <?= number_format($saldo, 0, ',', '.') ?></strong></td>
            </tr>
        </tfoot>
    </table>
</div>


<!-- Aktifkan Select2 -->
<script>
    $(document).ready(function() {
        $('#filter_nis_siswa').select2({
            placeholder: "Pilih NIS Atau Nama",
            allowClear: true,
            width: 'resolve' // otomatis mengikuti CSS width (dari style)
        });

        // Optional: Event ketika filter berubah
        $('#filter_nis_siswa').on('change', function() {
            var idSiswa = $(this).val();
            console.log("ID Siswa terpilih:", idSiswa);
            // Jalankan fungsi filter atau AJAX sesuai kebutuhan
        });
    });
</script>

<!-- script load laporan -->
<script>
    $(document).ready(function() {
        function loadData() {
            let tanggal_awal = $('input[name="tanggal_awal"]').val();
            let tanggal_akhir = $('input[name="tanggal_akhir"]').val();
            let id_siswa = $('#filter_nis_siswa').val();

            $.ajax({
                url: "<?= base_url('Laporan/filterMutasi') ?>",
                type: "POST",
                data: {
                    tanggal_awal: tanggal_awal,
                    tanggal_akhir: tanggal_akhir,
                    id_siswa: id_siswa
                },
                dataType: "json",
                success: function(response) {
                    let tbody = $("#dataTableExample tbody");
                    tbody.empty();

                    let totalSetor = 0;
                    let totalTarik = 0;
                    let saldo = 0;

                    if (response.length > 0) {
                        $.each(response, function(index, row) {
                            let jumlahSetor = '';
                            let jumlahTarik = '';

                            if (row.jenis === 'setor') {
                                jumlahSetor = `Rp ${parseInt(row.jumlah).toLocaleString('id-ID')}`;
                                totalSetor += parseInt(row.jumlah);
                                saldo += parseInt(row.jumlah);
                            } else if (row.jenis === 'tarik') {
                                jumlahTarik = `Rp ${parseInt(row.jumlah).toLocaleString('id-ID')}`;
                                totalTarik += parseInt(row.jumlah);
                                saldo -= parseInt(row.jumlah);
                            }

                            let tr = `
                                <tr>
                                    <td>${index + 1}</td>
                                    <td>${row.tanggal}</td>
                                    <td>${row.jenis}</td>
                                    <td>${row.keterangan ?? '-'}</td>
                                    <td>${jumlahSetor}</td>
                                    <td>${jumlahTarik}</td>
                                    <td><strong>Rp ${saldo.toLocaleString('id-ID')}</strong></td>
                                </tr>
                            `;
                            tbody.append(tr);
                        });

                        // Tambahkan footer
                        $("#dataTableExample tfoot").html(`
                            <tr>
                                <td colspan="4" class="text-end font-weight-bold">Total</td>
                                <td>Rp ${totalSetor.toLocaleString('id-ID')}</td>
                                <td>Rp ${totalTarik.toLocaleString('id-ID')}</td>
                                <td><strong>Rp ${saldo.toLocaleString('id-ID')}</strong></td>
                            </tr>
                        `);
                    } else {
                        tbody.append(`
                            <tr>
                                <td colspan="7" class="text-center">
                                    <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>
                                </td>
                            </tr>
                        `);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Error:", error);
                }
            });
        }

        // Trigger loadData jika ada perubahan filter
        $('input[name="tanggal_awal"], input[name="tanggal_akhir"], #filter_nis_siswa').on("change", loadData);

        // Load awal
        loadData();
    });
</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 Mutasi", 14, 15);

        // Header tabel yang sesuai dengan laporan tagihan
        let headers = [
            ["NO", "Tanggal", "jenis transaksi", "keterangan", "jumlah setor", "jumlah tarik", "saldo akhir"]
        ];

        // 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 
            row.push($(this).find("td:eq(2)").text().trim()); // jenis transaksi
            row.push($(this).find("td:eq(3)").text().trim()); // keterangan
            row.push($(this).find("td:eq(4)").text().trim()); // jumlah setor
            row.push($(this).find("td:eq(5)").text().trim()); // jumlah tarik
            row.push($(this).find("td:eq(6)").text().trim()); // saldo akhir
            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();
        let saldo = $("#dataTableExample tfoot td:eq(3)").text().trim();

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

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

        // 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_mutasi.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", "jenis transaksi", "keterangan", "jumlah setor", "jumlah tarik", "saldo akhir"]
        ];
        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 
            row.push($(this).find("td:eq(2)").text().trim()); // jenis transaksi
            row.push($(this).find("td:eq(3)").text().trim()); // keterangan
            row.push($(this).find("td:eq(4)").text().trim()); // jumlah setor
            row.push($(this).find("td:eq(5)").text().trim()); // jumlah tarik
            row.push($(this).find("td:eq(6)").text().trim()); // saldo akhir
            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();
        let saldo = $("#dataTableExample tfoot td:eq(3)").text().trim();

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

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

        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 mutasi");

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


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