<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-4">
            <h1 class="mt-4" id="judulPasien">Data Mal Nutrisi Gizi</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Data Gizi</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(); // Mencegah refresh halaman
            $('#loadingIcon').show(); // Tampilkan ikon loading
            $('#tableContainer').hide(); // Sembunyikan tabel sebelum memulai pengambilan data

            $.ajax({
                url: '<?= base_url("gizi/tampilreportgizimalnutrisi") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir').val()
                },
                success: function(response) {
                    $('#loadingIcon').hide(); // Sembunyikan ikon loading setelah permintaan selesai

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

                        // Periksa status dan data
                        if (data && Array.isArray(data.response)) {
                            const list = data.response;

                            // Hancurkan DataTable sebelumnya jika sudah ada
                            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-dark">
                                            <tr>
                                                <th>Kode Registrasi</th>
                                                <th>Kode Rekam Medis</th>
                                                <th>Nama Pasien</th>
                                                <th>Nama Kecamatan</th>
                                                <th>Umur</th>
                                                <th>Nama Diagnosa</th>
                                                <th>Nama Dokter</th>
                                            </tr>
                                        </thead>
                                    <tbody>`;

                                // Looping untuk menampilkan data
                                list.forEach(item => {

                                    //const formattedDate = new Date(item.tgl_registrasi).toISOString().split('T')[0];

                                    html += `<tr>
                                    <td>${item.kd_registrasi}</td>
                                    <td>${item.kd_rekam_medis}</td>
                                    <td>${item.nm_pasien}</td>         
                                    <td>${item.nm_kec}</td>
                                    <td>${item.umur}</td>
                                    <td>${item.nama_diagnosa}</td>
                                    <td>${item.nm_dokter}</td>
                             
                                </tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableContainer').html(html).show(); // Tampilkan tabel hasil

                                // Inisialisasi DataTable setelah tabel ditambahkan ke DOM
                                $('#datatablesSimple').DataTable({
                                    "columnDefs": [{
                                        "targets": 1, // Misalkan kolom tanggal berada di index 2
                                        "type": "date"
                                    }],
                                    "order": [
                                        [2, "asc"]
                                    ] // Urutkan tanggal ascending
                                });

                                // Tampilkan tombol download
                                $('#downloadButton').show();
                            } else {
                                $('#tableContainer').html('<p>Tidak ada data yang ditemukan.</p>').show();
                                $('#downloadButton').hide(); // Sembunyikan tombol download jika tidak ada data
                            }
                        } else {
                            $('#tableContainer').html('<p>Tidak ada data yang ditemukan.</p>').show();
                            $('#downloadButton').hide(); // Sembunyikan tombol download jika tidak ada data
                        }

                        // Ubah URL tanpa menyegarkan halaman
                        history.replaceState(null, '', '<?= base_url("gizi/tampilreportgizimalnutrisi") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<p>Terjadi kesalahan saat memproses data.</p>').show();
                        $('#downloadButton').hide(); // Sembunyikan tombol download jika terjadi kesalahan
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide(); // Sembunyikan ikon loading jika terjadi error
                    console.error("AJAX Error: ", error);
                }
            });
        });

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

</html>