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

    /* 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;
        }
    }

    #layoutSidenav_content {
        width: 100%;
        max-width: 100vw;
        overflow-x: hidden !important;
    }

    /* 3. MEMAKSA TABEL DAN CARD AGAR PATUH PADA UKURAN LAYAR */
    table, table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse;
    }

    .card {
        width: 100%;
        max-width: 100%;
        min-width: 0;
        overflow-x: hidden; 
    }

    /* 4. SCROLL HORIZONTAL CSS (STABIL DI ANDROID) */
    .table-responsive {
        width: 100%;
        max-width: 100%;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

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

    /* 6. PERBAIKAN TAMPILAN SELECT2 AGAR MIRIP BOOTSTRAP 5 */
    .select2-container .select2-selection--single {
        height: 38px !important; /* Samakan dengan tinggi form-control */
        border: 1px solid #ced4da !important;
        border-radius: 0.375rem !important;
        display: flex;
        align-items: center;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 36px !important;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #6c757d;
        line-height: normal;
    }

    @media (max-width: 768px) {
        .filter-wrapper .form-group {
            margin-bottom: 12px;
        }
        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 10px;
        }
        .btn-group-custom button { width: 100%; }
        /* Membatasi input datatable search agar tidak melar di HP */
        div.dataTables_wrapper div.dataTables_filter input { width: 120px !important; }
    }

    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
            height: 100%;
            padding-bottom: 2px;
        }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 overflow-hidden">
            <h1 class="mt-4 fs-3" id="judulPasien">Data Rekap Kasir Pasien Belum Tagih</h1>
            <ol class="breadcrumb mb-4 shadow-sm bg-white p-2 rounded">
                <li class="breadcrumb-item"><a href="index.html" class="text-decoration-none">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampilan Data Rekap Kasir Pasien Belum Tertagih</li>
            </ol>

            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-body filter-wrapper">
                    <form id="filterForm">
                        <div class="row g-2 align-items-end">
                            
                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_awal" class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control form-control-solid" value="<?php echo isset($tgl_awal) ? $tgl_awal : ''; ?>" required />
                            </div>

                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_akhir" class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control form-control-solid" value="<?php echo isset($tgl_akhir) ? $tgl_akhir : ''; ?>" required />
                            </div>

                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="kd_jenis_pasien" class="form-label text-muted small fw-bold mb-1">Jenis Pasien</label>
                                <select id="kd_jenis_pasien" name="kd_jenis_pasien" class="form-select form-select-solid" required>
                                    <option value="" disabled selected>Pilih Jenis Pasien</option>
                                    <option value="1">Rawat Jalan</option>
                                    <option value="2">Rawat Inap</option>
                                    <option value="3">IGD</option>
                                </select>
                            </div>

                            <div class="col-12 col-md-3 col-lg-3">
                                <label for="kd_pembayaran" class="form-label text-muted small fw-bold mb-1">Pembayaran</label>
                                <select id="kd_pembayaran" name="kd_pembayaran" class="form-control form-select-solid" style="width: 100%;" required>
                                    <option value="" disabled selected>Memuat Pembayaran...</option>
                                </select>
                            </div>

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

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

        </div>
    </main>

    <footer class="py-4 bg-light mt-auto border-top">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small text-muted">
                <div>Copyright &copy; IT RSU Ananda Purwokerto 2024</div>
            </div>
        </div>
    </footer>
</div>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

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

        function loadPembayaran() {
            const grupPembayaran = $('#kd_pembayaran');
            $.ajax({
                url: '<?php echo base_url("kasir_nottagih/referensipembayaran"); ?>',
                type: 'POST',
                dataType: 'json',
                success: function(data) {
                    grupPembayaran.empty().append('<option value="" disabled selected>Ketik / Pilih Pembayaran...</option>');
                    if (data && Array.isArray(data.response)) {
                        $.each(data.response, function(index, gruppembayaran) {
                            const option = new Option(gruppembayaran.nm_pembayaran, gruppembayaran.kd_pembayaran);
                            grupPembayaran.append(option);
                        });
                    }
                    
                    // INISIALISASI SELECT2 SETELAH DATA AJAX BERHASIL DIMUAT
                    grupPembayaran.select2({
                        placeholder: "Ketik / Pilih Pembayaran...",
                        allowClear: false,
                        width: '100%' // Wajib agar layout tidak rusak
                    });
                },
                error: function(xhr, status, error) {
                    console.error("AJAX Error:", status, error);
                    grupPembayaran.empty().append('<option value="" disabled selected>Gagal memuat Data</option>');
                }
            });
        }
        
        loadPembayaran();

        $('#filterForm').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIcon').show(); 
            $('#tableContainer').hide(); 

            $.ajax({
                url: '<?php echo base_url("kasir_nottagih/datakasirbelumbayar"); ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir').val(),
                    KD_JENIS_PASIEN: $('#kd_jenis_pasien').val(),
                    KD_PEMBAYARAN : $('#kd_pembayaran').val() 
                },
                dataType: 'json',
                success: function(data) { 
                    $('#loadingIcon').hide(); 

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

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

                        if (list.length > 0) {
                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesSimple" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-light">
                                        <tr>
                                            <th>KD Registrasi</th>
                                            <th>Nama Pasien</th>
                                            <th>Nama Penjamin</th>
                                            <th>Nama Poliklinik</th>
                                            <th>Tgl Tagihan</th>
                                            <th>Total Tagihan</th>
                                            <th>Total Tagihan Penjamin</th>
                                            <th>Nama Dokter</th>
                                        </tr>
                                    </thead>
                                <tbody>
                            `;

                            list.forEach(item => {
                                let totalTagihan = parseFloat(item.total_tagihan || 0).toLocaleString('id-ID');
                                let totalPenjamin = parseFloat(item.total_tagihan_penjamin || 0).toLocaleString('id-ID');

                                html += `<tr>
                                    <td>${item.kd_registrasi || '-'}</td>
                                    <td>${item.nm_pasien || '-'}</td>
                                    <td>${item.nm_pembayaran || '-'}</td>
                                    <td>${item.nm_poliklinik || '-'}</td>
                                    <td>${item.tgl_tagihan || '-'}</td>
                                    <td class="text-end fw-bold">${totalTagihan}</td>
                                    <td class="text-end fw-bold text-success">${totalPenjamin}</td>
                                    <td>${item.nm_dokter || '-'}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';
                            
                            $('#tableContainer').html(html).show(); 

                            $('#datatablesSimple').DataTable({
                                responsive: false, 
                                scrollX: false,    
                                autoWidth: false,
                                columnDefs: [{
                                    targets: 4,
                                    type: "date"
                                }],
                                order: [[4, "asc"]],
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                     '<"row"<"col-sm-12"tr>>' +
                                     '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                                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 small"><i class="fas fa-info-circle me-1"></i> Tidak ada data kasir belum tertagih.</div>').show();
                            $('#downloadButton').hide(); 
                        }
                    } else {
                        $('#tableContainer').html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>').show();
                        $('#downloadButton').hide(); 
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide(); 
                    console.error("AJAX Error: ", status, error);
                    $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal terhubung ke server. Silakan coba lagi.</div>').show();
                }
            });
        });

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