<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>

<body>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4" id="judulPasien">Data Coding ICD Rawat Jalan</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="">Dashboard</a></li>
                    <li class="breadcrumb-item active">Tampilkan Data Hasil ICD Rawat Jalan</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();
                $('#downloadButton').hide();

                $.ajax({
                    url: '<?= base_url("icdrawatjalan/datatampilicd") ?>',
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIcon').hide();

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

                        // --- PERUBAHAN TOTAL: Logika untuk membangun tabel dinamis ---
                        if (data && data.response && Array.isArray(data.response.headers) && Array.isArray(data.response.data)) {
                            
                            const headers = data.response.headers;
                            const list = data.response.data;

                            if (list.length > 0) {
                                // 1. Buat Header Tabel
                                let headerHtml = '<tr>';
                                headers.forEach(header => {
                                    headerHtml += `<th>${header}</th>`;
                                });
                                headerHtml += '</tr>';

                                // 2. Buat Body Tabel
                                let bodyHtml = '';
                                list.forEach(item => {
                                    bodyHtml += '<tr>';
                                    // Loop sesuai urutan header untuk memastikan data di kolom yang benar
                                    headers.forEach(header => {
                                        let key = '';
                                        // Mapping dari header ke key di data JSON
                                        switch(header) {
                                            case 'Kode Registrasi': key = 'kd_registrasi'; break;
                                            case 'Pembayaran': key = 'nm_pembayaran'; break;
                                            case 'DX Primer': key = 'dx_primer'; break;
                                            case 'DX Sekunder': key = 'dx_sekunder'; break;
                                            case 'Petugas': key = 'petugas'; break;
                                            case 'Dokter': key = 'nm_dokter'; break;
                                            case 'Poliklinik': key = 'nm_poliklinik'; break;
                                            case 'Waktu': key = 'waktu'; break;
                                            case 'Total Pasien': key = 'total_pasien'; break;
                                            case 'Coding RM': key = 'coding_rm'; break;
                                            case 'Coding Dokter': key = 'coding_dokter'; break;
                                            case 'Tidak Terisi': key = 'tidak_terisi'; break;
                                            case 'Prosentase Coding RM': key = 'prosentase_coding_rekam_medis'; break;
                                            case 'Prosentase Coding Dokter': key = 'prosentase_coding_dokter'; break;
                                            case 'Prosentase Tidak Terisi': key = 'prosentase_tidak_terisi'; break;
                                        }
                                        bodyHtml += `<td>${item[key] || '-'}</td>`;
                                    });
                                    bodyHtml += '</tr>';
                                });

                                // 3. Gabungkan dan Tampilkan
                                const tableHtml = `<table id="datatablesSimple" class="table table-striped table-bordered"><thead>${headerHtml}</thead><tbody>${bodyHtml}</tbody></table>`;
                                $('#tableContainer').html(tableHtml).show();
                                
                                // Inisialisasi DataTable dengan scroll horizontal
                                $('#datatablesSimple').DataTable({
                                    scrollX: true 
                                });
                                $('#downloadButton').show();

                            } else {
                                $('#tableContainer').html('<p class="text-center">Tidak ada data yang ditemukan.</p>').show();
                            }
                        } else {
                            const message = data.error || 'Terjadi kesalahan: Format data tidak sesuai.';
                            $('#tableContainer').html(`<p class="text-center">${message}</p>`).show();
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#loadingIcon').hide();
                        console.error("AJAX Error: ", error);
                        $('#tableContainer').html('<p class="text-center">Gagal terhubung ke server.</p>').show();
                    }
                });
            });

            $('#downloadButton').on('click', function() {
                const tanggalAwal = $('#tanggal_awal').val();
                const tanggalAkhir = $('#tanggal_akhir').val();
                window.location.href = `<?php echo base_url("icdrawatjalan/unduhdataicd"); ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
            });
        });
    </script>
</body>

</html>

