<style>
    /* ========================================================
       1. CSS CORE RESPONSIVE (ANTI HALAMAN JEBOL)
       ======================================================== */
    body, html {
        overflow-x: hidden !important;
        width: 100%;
        max-width: 100vw;
    }

    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
            width: 100% !important;
            max-width: 100vw !important;
        }
        .container-fluid {
            padding-left: 10px !important;
            padding-right: 10px !important;
        }
    }

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

    /* Memaksa Tabel dan Card agar menyesuaikan layar */
    table, table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse !important;
    }

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

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

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

    /* Responsive Grid Button */
    @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%; margin-left: 0 !important;}
        div.dataTables_wrapper div.dataTables_filter input { width: 140px !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">Total Data Detail Pasien Inap All</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 text-muted">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Total Data Pasien Rawat Inap</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" 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 fw-bold 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-6 col-lg-8">
                                <div class="btn-group-custom mt-3 mt-md-0">
                                    <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Filter</button>
                                    <button type="button" id="downloadButton" class="btn btn-success px-4 shadow-sm" 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-5">
                <div class="card-body p-2 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="mt-2 text-muted small fw-bold">Mengambil Data...</p>
                        </div>
                        <div id="tableContainer" style="display: none;">
                            </div>
                    </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 class="d-none d-md-block">
                    <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(); 

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

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

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

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

                            if (list.length > 0) {
                                // PERBAIKAN: Bungkus tabel dengan div responsive dan gunakan class text-nowrap
                                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-dark">
                                            <tr>
                                            <th>Kode Registrasi</th>
                                            <th>Kode RM</th>
                                            <th>Nama Pasien</th>
                                            <th>Jenis Kelamin (Detail)</th>
                                            <th>Tgl Lahir</th>
                                            <th>Umur (Thn/Bln/Hari)</th>
                                            <th>Alamat Lengkap</th>
                                            <th>Desa</th>
                                            <th>Kecamatan</th>
                                            <th>Kota / Kabupaten</th>
                                            <th>Provinsi</th>

                                            <th>Tanggal Regist</th>
                                            <th>Jam Regist</th>
                                            <th>Tanggal Keluar</th>
                                            <th>Jam Keluar</th>
                                            <th>Nama Pendaftaran (Kd)</th>
                                            <th>Cara Masuk (Kd)</th>
                                            <th>Nama Pembayaran (Kd)</th>
                                            <th>Jenis Pasien (Kd)</th>
                                            <th>Nama Poli (Kd)</th>
                                            <th>Nama Dokter (NIP)</th>
                                            <th>Status Periksa (Kd)</th>
                                            <th>Keterangan DPJP</th>
                                            <th>Nama Dokter DPJP Utama</th>
                                            <th>Asal PPK</th>

                                            <th>Nama Ruang (Kd)</th>
                                            <th>Grup Ruang (Kd)</th>
                                            <th>Nama Bed</th>
                                            <th>Nama Kelas</th>
                                            <th>Hari Rawat</th>
                                            <th>Tagih Hari Rawat</th>
                                            <th>Nama Item</th>
                                            <th>No Tagihan</th>
                                            
                                            <th>Total Billing</th>
                                            <th>Total Pribadi</th>
                                            <th>Total Penjamin</th>
                                            <th>NIP Petugas Input</th>

                                            <th>DX Primer (ICD-10)</th>
                                            <th>DX Sekunder (ICD-10)</th>
                                            <th>Nama Penyakit Primer</th>
                                            <th>Nama Penyakit Sekunder</th>
                                            <th>Kondisi Keluar</th>
                                            <th>Assesmen Klinis</th>
                                            <th>Alasan Ranap / Riwayat Kelahiran</th>
                                            
                                            <th>Tindakan OP</th>
                                            <th>Realisasi Tindakan</th>
                                            <th>Tgl OP Selesai</th>
                                            <th>Nama Perujuk</th>
                                            <th>Diagnosa Awal</th>
                                            <th>Ket Rujuk</th>
                                            </tr>
                                        </thead>
                                    <tbody>`;

                                list.forEach(item => {
                                    const formattedDate = new Date(item.tgl_registrasi).toISOString().split('T')[0];

                                    html += `<tr>
                                    <td class="fw-bold text-primary">${item.kd_registrasi ?? '-'}</td>
                                    <td class="fw-bold">${item.kd_rekam_medis ?? '-'}</td>
                                    <td class="fw-bold text-dark">${item.nm_pasien ?? '-'}</td>
                                    <td>${item.nm_jenis_kelamin ?? '-'} (${item.jenis_kelamin ?? '-'})</td>
                                    <td>${item.tgl_lahir ?? '-'}</td>
                                    <td>${item.umur_tahun ?? '0'} Thn / ${item.umur_bulan ?? '0'} Bln / ${item.umur_hari ?? '0'} Hari</td>
                                    <td class="text-wrap" style="min-width:250px;">${item.alamat ?? '-'}</td>
                                    <td>${item.nm_kec ?? '-'}</td>
                                    <td>${item.nm_kec ?? '-'}</td>
                                    <td>${item.nm_kota ?? '-'}</td>
                                    <td>${item.kd_prov ?? '-'}</td>

                                    <td>${item.tgl_registrasi ?? '-'}</td>
                                    <td>${item.jam_registrasi ?? '-'}</td>
                                    <td>${item.tgl_keluar ?? '-'}</td>
                                    <td>${item.jam_keluar ?? '-'}</td>
                                    <td>${item.nm_pendaftaran ?? '-'} (${item.kd_pendaftaran ?? '-'})</td>
                                    <td>${item.nm_cara_masuk ?? '-'} (${item.kd_cara_masuk ?? '-'})</td>
                                    <td>${item.nm_pembayaran ?? '-'}</td>
                                    <td>${item.nm_jenis_pasien ?? '-'} (${item.kd_jenis_pasien ?? '-'})</td>
                                    <td>${item.nm_poliklinik ?? '-'} (${item.kd_poliklinik ?? '-'})</td>
                                    <td>${item.nm_dokter ?? '-'}</td>
                                    <td>${item.nm_status_periksa ?? '-'} (${item.kd_status_periksa ?? '-'})</td>
                                    <td>${item.keterangan ?? '-'}</td>
                                    <td class="fw-bold text-success">${item.dpjp ?? '-'}</td>
                                    <td>${item.ppk ?? '-'}</td>

                                    <td>${item.nama_ruang ?? '-'} (${item.kd_ruang ?? '-'})</td>
                                    <td>${item.kd_grup_ruang ?? '-'}</td>
                                    <td>${item.nama_bed ?? '-'}</td>
                                    <td>${item.nama_kelas ?? '-'}</td>
                                    <td class="text-center">${item.hari_rawat ?? '0'}</td>
                                    <td class="text-center">${item.tagih_hari_rawat ?? '0'}</td>
                                    <td>${item.nama_item ?? '-'}</td>
                                    <td>${item.no_tagihan ?? '-'}</td>
                                    
                                    <td class="fw-bold text-end">${parseFloat(item.total ?? 0).toLocaleString('id-ID')}</td>
                                    <td class="text-end">${parseFloat(item.total_pribadi ?? 0).toLocaleString('id-ID')}</td>
                                    <td class="text-end text-danger">${parseFloat(item.total_penjamin ?? 0).toLocaleString('id-ID')}</td>
                                    <td>${item.nip_petugas ?? '-'}</td>

                                    <td class="fw-bold text-danger text-center">${item.dx_primer ?? '-'}</td>
                                    <td class="text-center">${item.dx_sekunder ?? '-'}</td>
                                    <td class="text-wrap" style="min-width:200px;"><small>${item.nm_penyakit_primer ?? '-'}</small></td>
                                    <td class="text-wrap" style="min-width:150px;"><small>${item.nm_penyakit_sekunder ?? '-'}</small></td>
                                    <td class="fw-bold text-info">${item.kondisi_keluar ?? '-'}</td>
                                    <td class="text-wrap" style="min-width:250px;"><small><pre style="font-family:inherit; margin:0;">${item.assesmen ?? '-'}</pre></small></td>
                                    <td class="text-wrap" style="min-width:300px;"><small><pre style="font-family:inherit; margin:0;">${item.alasan_ranap ?? '-'}</pre></small></td>
                                    
                                    <td>${item.tindakan_op ?? '-'}</td>
                                    <td>${item.realisasi_tindakan ?? '-'}</td>
                                    <td>${item.tgl_op_selesai ?? '-'}</td>
                                    <td>${item.nm_perujuk ?? '-'}</td>
                                    <td>${item.diagnosa ?? '-'}</td>
                                    <td>${item.ket_rujuk ?? '-'}</td>
                                    </tr>`;
                                });
                                html += '</tbody></table></div>';
                                
                                $('#tableContainer').html(html).show(); 

                                // INISIALISASI DATATABLES DENGAN DOM KHUSUS HP (scrollX dimatikan)
                                $('#datatablesSimple').DataTable({
                                    responsive: false,
                                    scrollX: false, 
                                    autoWidth: false,
                                    columnDefs: [{
                                        targets: 2, 
                                        type: "date"
                                    }],
                                    order: [[2, "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 Data:",
                                        lengthMenu: "Tampil _MENU_"
                                    }
                                });

                                $('#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 yang ditemukan.</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(); 
                        }

                        history.replaceState(null, '', '<?= base_url("rawatinap/tampilpasieninaptotal") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>').show();
                        $('#downloadButton').hide(); 
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide(); 
                    console.error("AJAX Error: ", 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();
                }
            });
        });

        // Event download Excel
        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            window.location.href = `<?= base_url("detailpxinapall/downloaddata") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });
    });
</script>