<style>
    /* 1. MENCEGAH HALAMAN MELAR KE KANAN */
    body {
        overflow-x: hidden !important;
        width: 100%;
    }

    /* 2. KUNCI PERBAIKAN: MENGATASI BUG TERGENCET SB ADMIN DI HP */
    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
            width: 100% !important;
        }
    }
    
    table.dataTable {
        /* KUNCI PERBAIKAN: Hapus table-layout: fixed; untuk tabel dengan banyak kolom */
        width: 100% !important;
        margin: 0 auto;
        clear: both;
        border-collapse: collapse;
    }

    .filter-wrapper {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }

    /* Penyesuaian tombol di layar HP */
    @media (max-width: 768px) {
        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 15px;
        }
        .btn-group-custom button {
            width: 100%;
        }
    }
    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4" id="judulPasien">Data Billing Keuangan SIRUS & BPJS</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="#" class="text-decoration-none">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampilkan Data Keuangan SIRUS & BPJS</li>
            </ol>

            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-body filter-wrapper">
                    <form id="filterForm">
                        <div class="row g-3 align-items-end">
                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_awal" class="form-label text-muted small mb-1">Tanggal Awal</label>
                                <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                            </div>
                            
                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_akhir" class="form-label text-muted small mb-1">Tanggal Akhir</label>
                                <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                            </div>

                            <div class="col-12 col-md-3 col-lg-3">
                                <label for="kd_jenis_pasien" class="form-label text-muted small mb-1">Jenis Pasien</label>
                                <select id="kd_jenis_pasien" name="kd_jenis_pasien" class="form-select" required>
                                    <option value="" disabled <?= empty($kd_jenis_pasien) ? 'selected' : '' ?>>Pilih Jenis Pasien</option>
                                    <option value="1" <?= ($kd_jenis_pasien == '1') ? 'selected' : '' ?>>Rawat Jalan</option>
                                    <option value="2" <?= ($kd_jenis_pasien == '2') ? 'selected' : '' ?>>Rawat Inap</option>
                                    <option value="3" <?= ($kd_jenis_pasien == '3') ? 'selected' : '' ?>>IGD</option>
                                </select>
                            </div>

                            <div class="col-12 col-md-3 col-lg-5">
                                <div class="btn-group-custom">
                                    <button type="submit" class="btn btn-primary px-4"><i class="fas fa-search me-1"></i> Filter</button>
                                    <button type="button" id="downloadButton" class="btn btn-success px-4" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download Excel</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-0 p-md-3">
                    <div id="result">
                        <div id="loadingIcon" style="display: none;" class="py-5 text-center">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            <p class="text-muted mt-2">Memuat data...</p>
                        </div>
                        
                        <div class="table-responsive" id="tableContainer" style="display: none;">
                            </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="py-4 bg-light mt-auto">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small">
                <div class="text-muted">Copyright &copy; By IT RSU Ananda Purwokerto 2024</div>
                <div>
                    <a href="#" class="text-decoration-none text-muted">Privacy Policy</a>
                    &middot;
                    <a href="#" class="text-decoration-none text-muted">Terms &amp; Conditions</a>
                </div>
            </div>
        </div>
    </footer>
</div>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

<script>
    $(document).ready(function() {
        $('#filterForm').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIcon').show(); 
            $('#tableContainer').hide(); 
            $('#downloadButton').hide(); 

            $.ajax({
                url: '<?= base_url("billing/billingkeuanganall") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir').val(),
                    KD_JENIS_PASIEN: $('#kd_jenis_pasien').val()
                },
                success: function(tampil) {
                    $('#loadingIcon').hide(); 

                    try {
                        const data = JSON.parse(tampil); 

                        if (data && Array.isArray(data.tampil)) {
                            const list = data.tampil;

                            if ($.fn.DataTable.isDataTable('#datatablesSimple')) {
                                $('#datatablesSimple').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                // MENGGUNAKAN text-nowrap AGAR TABEL MELEBAR KE KANAN DAN BISA DI-SCROLL
                                let html = `

                               <div class="table-responsive">
                                    <table id="datatablesSimple" class="table table-striped table-hover table-bordered w-100 text-nowrap">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Kd Regist</th>
                                                <th>Nama Pasien</th>
                                                <th>Kelas</th>
                                                <th>Tgl Regist</th>
                                                <th>Tarif INACBG</th>
                                                <th>DPJP</th>
                                                <th>Radiologi</th>
                                                <th>Obat</th>
                                                <th>Keperawatan</th>
                                                <th>Laboratorium</th>
                                                <th>Kamar & Akomodasi</th>
                                                <th>Konsultasi</th>
                                                <th>BMHP</th>
                                                <th>Nama Pembayaran</th>
                                                <th>Total Tagihan</th>
                                            </tr>
                                        </thead>
                                    <tbody>
                                `;

                                list.forEach(item => {
                                    html += `<tr>
                                        <td>${item.kd_registrasi}</td>
                                        <td>${item.nm_pasien}</td>
                                        <td>${item.kelas}</td>
                                        <td>${item.tgl_registrasi}</td>
                                        <td class="text-end">${item.tarif_inacbg}</td>
                                        <td>${item.dpjp}</td>
                                        <td class="text-end">${item.radiologi}</td>
                                        <td class="text-end">${item.obat}</td>
                                        <td class="text-end">${item.keperawatan}</td>
                                        <td class="text-end">${item.laboratorium}</td>
                                        <td class="text-end">${item.kamar_dan_akomodasi}</td>
                                        <td class="text-end">${item.konsultasi}</td>
                                        <td class="text-end">${item.bmhp}</td>
                                        <td>${item.nm_pembayaran}</td>
                                        <td class="text-end fw-bold">${item.total_tagihan}</td>
                                    </tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableContainer').html(html).fadeIn(); 

                                // INISIALISASI DATATABLES
                                $('#datatablesSimple').DataTable({
                                    responsive: false, // Dimatikan agar tidak konflik dengan table-responsive
                                    autoWidth: false,
                                    language: {
                                        search: "Cari:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_-_END_ dari _TOTAL_"
                                    }
                                });

                                $('#downloadButton').fadeIn();
                            } else {
                                $('#tableContainer').html('<div class="alert alert-info text-center m-3">Tidak ada data yang ditemukan.</div>').show();
                            }
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning text-center m-3">Tidak ada data yang ditemukan.</div>').show();
                        }

                        history.replaceState(null, '', '<?= base_url("billing/billingkeuanganall") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger text-center m-3">Terjadi kesalahan saat memproses data.</div>').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide(); 
                    console.error("AJAX Error: ", error);
                    $('#tableContainer').html('<div class="alert alert-danger text-center m-3">Koneksi ke server gagal.</div>').show();
                }
            });
        });

        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            const kdjenispasien = $('#kd_jenis_pasien').val();
            window.location.href = `<?= base_url("billing/unduhbillingkeuanganall") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_JENIS_PASIEN=${kdjenispasien}`;
        });
    });
</script>