<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 & IOS) */
    .table-responsive {
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

    /* ========================================================
       2. STYLING TAB / PILLS (Mengikuti Style Modern Farmasi)
       ======================================================== */
    .nav-pills .nav-link {
        border-radius: 50px;
        padding: 8px 16px;
        font-weight: 500;
        margin-right: 10px;
        margin-bottom: 10px;
        border: 1px solid #e3e6f0;
        color: #5a5c69;
        background-color: #fff;
        white-space: nowrap; 
        cursor: pointer;
    }
    
    .nav-pills .nav-link.active, .nav-pills .nav-link:hover {
        background-color: #007bff;
        color: #fff;
        border-color: #007bff;
    }

    .nav-pills {
        flex-wrap: nowrap;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        padding-bottom: 5px;
    }
    .nav-pills::-webkit-scrollbar { height: 4px; }
    .nav-pills::-webkit-scrollbar-track { background: #f1f1f1; }
    .nav-pills::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; }

    /* ========================================================
       3. 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="mainTitle">Data Pasien Rawat Inap</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" id="breadcrumbActive">Pasien Rawat Inap</li>
            </ol>

            <ul class="nav nav-pills mb-4" id="inapTabs" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active shadow-sm" id="tab-total-inap" data-bs-toggle="pill" href="#pane-total-inap" role="tab">
                        <i class="fas fa-bed me-2"></i>Pasien Inap Total
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="tab-detail-inap" data-bs-toggle="pill" href="#pane-detail-inap" role="tab">
                        <i class="fas fa-clipboard-list me-2"></i>Pasien Inap Detail
                    </a>
                </li>
            </ul>

            <div class="tab-content" id="inapTabsContent">
                
                <div class="tab-pane fade show active" id="pane-total-inap" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormTotal">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" name="tanggal_awal" class="form-control tgl-awal-sync" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" name="tanggal_akhir" class="form-control tgl-akhir-sync" 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="downloadButtonTotal" 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="loadingIconTotal" 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 Pasien Total...</p>
                            </div>
                            <div id="tableContainerTotal" class="table-responsive w-100" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="pane-detail-inap" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormDetail">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" name="tanggal_awal" class="form-control tgl-awal-sync" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" name="tanggal_akhir" class="form-control tgl-akhir-sync" 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="downloadButtonDetail" 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="loadingIconDetail" 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 Detail Pasien...</p>
                            </div>
                            <div id="tableContainerDetail" class="table-responsive w-100" style="display: none;"></div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </main>
</div>

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

<script>
    $(document).ready(function() {
        
        // Sinkronisasi input tanggal antar tab saat user mengubah nilainya
        $('.tgl-awal-sync').on('change', function() { $('.tgl-awal-sync').val($(this).val()); });
        $('.tgl-akhir-sync').on('change', function() { $('.tgl-akhir-sync').val($(this).val()); });

        // ========================================================
        // SCRIPT LOGIC JAVASCRIPT: PANEL 1 (PASIEN INAP TOTAL)
        // ========================================================
        $('#filterFormTotal').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIconTotal').show(); 
            $('#tableContainerTotal').hide(); 
            $('#downloadButtonTotal').hide();

            $.ajax({
                url: '<?= base_url("rawatinap/tampilpasieninaptotal") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#pane-total-inap input[name="tanggal_awal"]').val(),
                    TANGGAL_AKHIR: $('#pane-total-inap input[name="tanggal_akhir"]').val()
                },
                success: function(response) {
                    $('#loadingIconTotal').hide(); 

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

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

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

                            if (list.length > 0) {
                                let html = `
                                <table id="dtTableTotal" 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>Tanggal Regist</th>
                                            <th>Tanggal Keluar</th>
                                            <th>No Antrian</th>
                                            <th>Nama Pasien</th>
                                            <th>Alamat</th>
                                            <th>Nama Pendaftaran</th>
                                            <th>Cara Masuk</th>
                                            <th>Nama Pembayaran</th>
                                            <th>Jenis Pasien</th>
                                            <th>Nama Poli</th>
                                            <th>Nama Dokter</th>
                                            <th>Status Pemeriksaan</th>
                                            <th>DPJP</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;

                                list.forEach(item => {
                                    html += `<tr>
                                        <td class="fw-bold">${item.kd_registrasi}</td>
                                        <td>${item.kd_rekam_medis}</td>
                                        <td>${item.tgl_registrasi}</td>
                                        <td>${item.tgl_keluar}</td>
                                        <td class="text-center">${item.no_antri}</td>
                                        <td class="text-wrap" style="min-width:150px;">${item.nm_pasien}</td>
                                        <td class="text-wrap" style="min-width:200px;">${item.alamat}</td>
                                        <td>${item.nm_pendaftaran}</td>
                                        <td>${item.nm_cara_masuk}</td>
                                        <td>${item.nm_pembayaran}</td>
                                        <td>${item.nm_jenis_pasien}</td>
                                        <td>${item.nm_poliklinik}</td>
                                        <td>${item.nm_dokter}</td>
                                        <td>${item.nm_status_periksa}</td>
                                        <td>${item.dpjp}</td>
                                    </tr>`;
                                });
                                html += '</tbody></table>';
                                
                                $('#tableContainerTotal').html(html).show(); 

                                $('#dtTableTotal').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_" }
                                });

                                $('#downloadButtonTotal').fadeIn();
                            } else {
                                $('#tableContainerTotal').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();
                            }
                        } else {
                            $('#tableContainerTotal').html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>').show();
                        }

                        history.replaceState(null, '', '<?= base_url("rawatinap/tampilpasieninaptotal") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerTotal').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIconTotal').hide(); 
                    console.error("AJAX Error: ", error);
                    $('#tableContainerTotal').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal terhubung ke server.</div>').show();
                }
            });
        });

        // Event download Excel Panel Total
        $('#downloadButtonTotal').on('click', function() {
            const tanggalAwal = $('#pane-total-inap input[name="tanggal_awal"]').val();
            const tanggalAkhir = $('#pane-total-inap input[name="tanggal_akhir"]').val();
            window.location.href = `<?= base_url("rawatinap/unduhpasienranaptotal") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });


        // ========================================================
        // SCRIPT LOGIC JAVASCRIPT: PANEL 2 (PASIEN INAP DETAIL ALL)
        // ========================================================
        $('#filterFormDetail').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIconDetail').show(); 
            $('#tableContainerDetail').hide(); 
            $('#downloadButtonDetail').hide();

            $.ajax({
                url: '<?= base_url("detailpxinapall/viewdata") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#pane-detail-inap input[name="tanggal_awal"]').val(),
                    TANGGAL_AKHIR: $('#pane-detail-inap input[name="tanggal_akhir"]').val()
                },
                success: function(response) {
                    $('#loadingIconDetail').hide(); 

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

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

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

                            if (list.length > 0) {
                                let html = `
                                <table id="dtTableDetail" 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>No Antrian</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</th>
                                        <th>Cara Masuk</th>
                                        <th>Nama Pembayaran</th>
                                        <th>Jenis Pasien</th>
                                        <th>Nama Poli</th>
                                        <th>Nama Dokter</th>
                                        <th>Status Periksa</th>
                                        <th>Keterangan DPJP</th>
                                        <th>Nama Dokter DPJP Utama</th>
                                        <th>Asal PPK</th>

                                        <th>Nama Ruang</th>
                                        <th>Grup Ruang</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 => {
                                    html += `<tr>
                                    <td class="fw-bold text-primary">${item.kd_registrasi ?? '-'}</td>
                                    <td class="fw-bold">${item.kd_rekam_medis ?? '-'}</td>
                                    <td class="text-center bg-light fw-bold">${item.no_antri ?? '-'}</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 ?? '-'}</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 ?? '-'}</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 ?? '-'}</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>';
                                
                                $('#tableContainerDetail').html(html).show(); 

                                $('#dtTableDetail').DataTable({
                                    responsive: false,
                                    scrollX: false, 
                                    autoWidth: false,
                                    columnDefs: [{ targets: 5, type: "date" }],
                                    order: [[5, "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_" }
                                });

                                $('#downloadButtonDetail').fadeIn();
                            } else {
                                $('#tableContainerDetail').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();
                            }
                        } else {
                            $('#tableContainerDetail').html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>').show();
                        }

                        history.replaceState(null, '', '<?= base_url("detailpxinapall/viewdata") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerDetail').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIconDetail').hide(); 
                    console.error("AJAX Error: ", error);
                    $('#tableContainerDetail').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 Panel Detail
        $('#downloadButtonDetail').on('click', function() {
            const tanggalAwal = $('#pane-detail-inap input[name="tanggal_awal"]').val();
            const tanggalAkhir = $('#pane-detail-inap input[name="tanggal_akhir"]').val();
            window.location.href = `<?= base_url("detailpxinapall/downloaddata") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });
    });
</script>