<style>
    /* 1. MENCEGAH HALAMAN MELAR KE KANAN */
    body {
        overflow-x: hidden !important;
        width: 100%;
        background-color: #f4f6f9;
    }

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

    /* 3. MEMASTIKAN TABEL BISA DI-SCROLL KE SAMPING DI HP */
    .table-responsive {
        width: 100%;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

    table.dataTable {
        width: 100% !important;
        min-width: 800px !important;
        border-collapse: collapse;
        margin-top: 10px !important;
    }

    /* 4. FORM FILTER AGAR RAPI DI HP */
    .filter-wrapper {
        background-color: #ffffff;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        border: 1px solid #e0e4e8;
    }

    @media (max-width: 768px) {
        .filter-wrapper .row>div {
            margin-bottom: 12px;
        }

        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 5px;
        }

        .btn-group-custom button {
            width: 100%;
        }
    }

    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
    }

    /* 5. DESAIN TAB MENJADI KOTAK (PERMINTAAN BARU) */
    .nav-tabs-custom {
        flex-wrap: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        white-space: nowrap;
        -webkit-overflow-scrolling: touch;
        border-bottom: 1px solid #dee2e6;
        margin-bottom: 20px;
    }

    .nav-tabs-custom .nav-link {
        color: #495057;
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 6px 6px 0 0;
        /* Membuat sudut atas melengkung */
        margin-right: 5px;
        font-weight: 600;
        padding: 10px 20px;
        transition: background-color 0.3s, color 0.3s;
    }

    .nav-tabs-custom .nav-link:hover {
        background-color: #e9ecef;
    }

    .nav-tabs-custom .nav-link.active {
        color: #0d6efd;
        background-color: #ffffff;
        border-color: #dee2e6 #dee2e6 #ffffff;
        /* Menghilangkan border bawah agar menyatu dengan konten */
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 py-4">

            <div class="mb-4">
                <h2 class="mb-1 font-weight-bold text-dark">Data Pasien ISPA & PNEUMONIA</h2>
                <ol class="breadcrumb bg-transparent p-0 mb-0">
                    <li class="breadcrumb-item"><a href="#" class="text-decoration-none text-muted">Dashboard</a></li>
                    <li class="breadcrumb-item active font-weight-bold">Tampilkan Data Penyakit</li>
                </ol>
            </div>

            <ul class="nav nav-tabs nav-tabs-custom" id="penyakitTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="ispa-tab" data-bs-toggle="tab" data-bs-target="#tab-ispa" type="button" role="tab">ISPA & PNEUMONIA</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="antibiotik-tab" data-bs-toggle="tab" data-bs-target="#tab-antibiotik" type="button" role="tab">ANTIBIOTIK</button>
                </li>
            </ul>

            <div class="tab-content" id="penyakitTabsContent">

                <div class="tab-pane fade show active" id="tab-ispa" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm" style="border-radius: 10px;">
                        <div class="card-body filter-wrapper">
                            <form id="formIspa">
                                <div class="row g-3 align-items-end">
                                    <div class="col-12 col-md-4">
                                        <label class="form-label text-muted font-weight-bold small mb-1">Tanggal Awal</label>
                                        <input type="date" id="tglAwalIspa" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <label class="form-label text-muted font-weight-bold small mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tglAkhirIspa" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <div class="btn-group-custom">
                                            <button type="submit" class="btn btn-primary px-4 shadow-sm font-weight-bold"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="btnDownloadIspa" class="btn btn-success px-4 shadow-sm font-weight-bold" 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-4" style="border-radius: 10px;">
                        <div class="card-body p-3">
                            <div id="loadingIspa" 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="text-muted mt-2 font-weight-bold">Memuat data ISPA...</p>
                            </div>

                            <div id="summaryContainerIspa" style="display: none;" class="mb-4"></div>

                            <div id="tableContainerIspa" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-antibiotik" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm" style="border-radius: 10px;">
                        <div class="card-body filter-wrapper">
                            <form id="formAntibiotik">
                                <div class="row g-3 align-items-end">
                                    <div class="col-12 col-md-4">
                                        <label class="form-label text-muted font-weight-bold small mb-1">Tanggal Awal</label>
                                        <input type="date" id="tglAwalAntibiotik" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <label class="form-label text-muted font-weight-bold small mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tglAkhirAntibiotik" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <div class="btn-group-custom">
                                            <button type="submit" class="btn btn-primary px-4 shadow-sm font-weight-bold"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="btnDownloadAntibiotik" class="btn btn-success px-4 shadow-sm font-weight-bold" 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-4" style="border-radius: 10px;">
                        <div class="card-body p-3">
                            <div id="loadingAntibiotik" 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="text-muted mt-2 font-weight-bold">Memuat data Antibiotik...</p>
                            </div>
                            <div id="tableContainerAntibiotik" style="display: none;"></div>
                        </div>
                    </div>
                </div>

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

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

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.bundle.min.js"></script>

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

        const safeValue = value => (value !== undefined && value !== null && value !== '') ? value : '0';

        // =========================================================================
        // LOGIKA TAB 1: ISPA & PNEUMONIA
        // =========================================================================
        $('#formIspa').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIspa').show();
            $('#summaryContainerIspa').hide();
            $('#tableContainerIspa').hide();
            $('#btnDownloadIspa').hide();

            $.ajax({
                url: '<?= base_url("pasienispa/tampildataispa") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalIspa').val(),
                    TANGGAL_AKHIR: $('#tglAkhirIspa').val()
                },
                success: function(response) {
                    $('#loadingIspa').hide();

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

                        let list = null;
                        let agg = {};

                        if (data && Array.isArray(data.response)) {
                            list = data.response;
                            agg = data.agg && (Array.isArray(data.agg) ? data.agg[0] : data.agg) || {};
                        } else if (data && Array.isArray(data.tampil)) {
                            list = data.tampil;
                            agg = data.agg && (Array.isArray(data.agg) ? data.agg[0] : data.agg) || {};
                        }

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

                            // 1. RENDER SUMMARY CARDS
                            const summaryHtml = `
                            <div class="row gx-2 gy-3">
                                <div class="col-12 col-md-4 mb-3">
                                    <div class="card border-left-primary shadow-sm h-100" style="border-left: 4px solid #0d6efd;">
                                        <div class="card-body">
                                            <div class="text-muted small font-weight-bold text-uppercase mb-1">Jumlah Sasaran Balita</div>
                                            <div class="h5 mb-0 font-weight-bold text-primary">${safeValue(agg.jml_sasaran_balita)}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 col-md-4 mb-3">
                                    <div class="card border-left-success shadow-sm h-100" style="border-left: 4px solid #198754;">
                                        <div class="card-body">
                                            <div class="text-muted small font-weight-bold text-uppercase mb-1">Estimasi Temuan</div>
                                            <div class="h5 mb-0 font-weight-bold text-success">${safeValue(agg.estimasi_temuan)}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 col-md-4 mb-3">
                                    <div class="card border-left-warning shadow-sm h-100" style="border-left: 4px solid #ffc107;">
                                        <div class="card-body">
                                            <div class="text-muted small font-weight-bold text-uppercase mb-1">Target Penemuan Kasus</div>
                                            <div class="h5 mb-0 font-weight-bold text-warning">${safeValue(agg.target_penemuan_kasus)}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            `;

                            // 2. RENDER TABEL UTAMA ISPA
                            let tableHtml = `
                            <div class="table-responsive w-100">
                                <table id="dtIspa" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-light text-center align-middle">
                                        <tr>
                                            <th rowspan="2" class="align-middle">No</th>
                                            <th rowspan="2" class="align-middle">Kelompok Penyakit</th>
                                            <th rowspan="2" class="align-middle">Total</th>
                                            <th colspan="3"> < 1 Tahun </th>
                                            <th colspan="3"> 1 - < 5 Tahun </th>
                                            <th colspan="3"> 5 - 9 Tahun </th>
                                            <th colspan="3"> 10 - 18 Tahun </th>
                                            <th colspan="3"> 19 - 59 Tahun </th>
                                            <th colspan="3"> ≥ 60 Tahun </th>
                                            <th rowspan="2" class="align-middle">Total L</th>
                                            <th rowspan="2" class="align-middle">Total P</th>
                                        </tr>
                                        <tr>
                                            <th>L</th><th>P</th><th>Total</th>
                                            <th>L</th><th>P</th><th>Total</th>
                                            <th>L</th><th>P</th><th>Total</th>
                                            <th>L</th><th>P</th><th>Total</th>
                                            <th>L</th><th>P</th><th>Total</th>
                                            <th>L</th><th>P</th><th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;

                            list.forEach(item => {
                                tableHtml += `<tr>
                                    <td class="text-center text-muted">${safeValue(item.urut)}</td>
                                    <td class="font-weight-bold">${safeValue(item.kelompok_penyakit)}</td>
                                    <td class="text-center font-weight-bold text-primary">${safeValue(item.total)}</td>
                                    <td class="text-center">${safeValue(item.lt1_l)}</td>
                                    <td class="text-center">${safeValue(item.lt1_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.lt5_tot)}</td>
                                    <td class="text-center">${safeValue(item.lt_1_5_l)}</td>
                                    <td class="text-center">${safeValue(item.lt_1_5_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.lt_1_5_tot)}</td>
                                    <td class="text-center">${safeValue(item.usia_5_9_l)}</td>
                                    <td class="text-center">${safeValue(item.usia_5_9_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.usia_5_9_tot)}</td>
                                    <td class="text-center">${safeValue(item.usia_10_18_l)}</td>
                                    <td class="text-center">${safeValue(item.usia_10_18_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.usia_10_18_tot)}</td>
                                    <td class="text-center">${safeValue(item.usia_19_59_l)}</td>
                                    <td class="text-center">${safeValue(item.usia_19_59_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.usia_19_59_tot)}</td>
                                    <td class="text-center">${safeValue(item.l60_l)}</td>
                                    <td class="text-center">${safeValue(item.l60_p)}</td>
                                    <td class="text-center bg-light font-weight-bold">${safeValue(item.l60_tot)}</td>
                                    <td class="text-center text-success font-weight-bold">${safeValue(item.total_l)}</td>
                                    <td class="text-center text-success font-weight-bold">${safeValue(item.total_p)}</td>
                                </tr>`;
                            });
                            tableHtml += '</tbody></table></div>';

                            $('#summaryContainerIspa').html(summaryHtml).fadeIn();
                            $('#tableContainerIspa').html(tableHtml).fadeIn();

                            $('#dtIspa').DataTable({
                                scrollX: true,
                                autoWidth: false,
                                order: [
                                    [0, "asc"]
                                ],
                                language: {
                                    search: "Cari:",
                                    lengthMenu: "Tampil _MENU_",
                                    info: "_START_-_END_ dari _TOTAL_"
                                }
                            });

                            $('#btnDownloadIspa').fadeIn();
                        } else {
                            $('#tableContainerIspa').html('<div class="alert alert-info text-center m-3">Tidak ada data ISPA ditemukan.</div>').fadeIn();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerIspa').html('<div class="alert alert-danger text-center m-3">Terjadi kesalahan format data dari server.</div>').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIspa').hide();
                    $('#tableContainerIspa').html('<div class="alert alert-danger text-center m-3">Gagal terhubung ke server.</div>').fadeIn();
                }
            });
        });

        $('#btnDownloadIspa').on('click', function() {
            const tanggalAwal = $('#tglAwalIspa').val();
            const tanggalAkhir = $('#tglAkhirIspa').val();
            window.location.href = `<?= base_url("pasienispa/unduhdataispa") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });


        // =========================================================================
        // LOGIKA TAB 2: ANTIBIOTIK
        // =========================================================================
        $('#formAntibiotik').on('submit', function(event) {
            event.preventDefault();
            $('#loadingAntibiotik').show();
            $('#tableContainerAntibiotik').hide();
            $('#btnDownloadAntibiotik').hide();

            $.ajax({
                url: '<?= base_url("pasienispa/tampilantibiotik") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalAntibiotik').val(),
                    TANGGAL_AKHIR: $('#tglAkhirAntibiotik').val()
                },
                success: function(response) {
                    $('#loadingAntibiotik').hide();

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

                        // Mendukung pembacaan key JSON "response" atau "tampil"
                        let list = null;
                        if (data && Array.isArray(data.response)) {
                            list = data.response;
                        } else if (data && Array.isArray(data.tampil)) {
                            list = data.tampil;
                        }

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

                            if (list.length > 0) {
                                let tableHtml = `
                                <div class="table-responsive w-100">
                                    <table id="dtAntibiotik" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                        <thead class="table-light text-center align-middle">
                                            <tr>
                                                <th rowspan="2" class="align-middle">No</th>
                                                <th rowspan="2" class="align-middle">Kelompok Penyakit</th>
                                                <th rowspan="2" class="align-middle">Total</th>
                                                <th colspan="3"> < 1 Tahun </th>
                                                <th colspan="3"> 1 - < 5 Tahun </th>
                                                <th colspan="3"> 5 - 9 Tahun </th>
                                                <th rowspan="2" class="align-middle">Total L</th>
                                                <th rowspan="2" class="align-middle">Total P</th>
                                            </tr>
                                            <tr>
                                                <th>L</th><th>P</th><th>Tot</th>
                                                <th>L</th><th>P</th><th>Tot</th>
                                                <th>L</th><th>P</th><th>Tot</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;

                                list.forEach(item => {
                                    tableHtml += `<tr>
                                        <td class="text-center text-muted">${safeValue(item.urut)}</td>
                                        <td class="font-weight-bold">${safeValue(item.kelompok_penyakit)}</td>
                                        <td class="text-center font-weight-bold text-primary">${safeValue(item.total)}</td>
                                        
                                        <td class="text-center">${safeValue(item.lt5_l)}</td>
                                        <td class="text-center">${safeValue(item.lt5_p)}</td>
                                        <td class="text-center bg-light font-weight-bold">${safeValue(item.lt5_tot)}</td>
                                        
                                        <td class="text-center">${safeValue(item.lt_1_5_l)}</td>
                                        <td class="text-center">${safeValue(item.lt_1_5_p)}</td>
                                        <td class="text-center bg-light font-weight-bold">${safeValue(item.lt_1_5_tot)}</td>
                                        
                                        <td class="text-center">${safeValue(item.usia_5_9_l)}</td>
                                        <td class="text-center">${safeValue(item.usia_5_9_p)}</td>
                                        <td class="text-center bg-light font-weight-bold">${safeValue(item.usia_5_9_tot)}</td>
                                        
                                        <td class="text-center text-success font-weight-bold">${safeValue(item.total_laki_laki)}</td>
                                        <td class="text-center text-success font-weight-bold">${safeValue(item.total_p)}</td>
                                    </tr>`;
                                });
                                tableHtml += '</tbody></table></div>';

                                $('#tableContainerAntibiotik').html(tableHtml).fadeIn();

                                $('#dtAntibiotik').DataTable({
                                    scrollX: true,
                                    autoWidth: false,
                                    order: [
                                        [0, "asc"]
                                    ],
                                    language: {
                                        search: "Cari:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_-_END_ dari _TOTAL_"
                                    }
                                });

                                $('#btnDownloadAntibiotik').fadeIn();
                            } else {
                                $('#tableContainerAntibiotik').html('<div class="alert alert-info text-center m-3">Tidak ada data Antibiotik ditemukan.</div>').fadeIn();
                            }
                        } else {
                            $('#tableContainerAntibiotik').html('<div class="alert alert-warning text-center m-3">Format data dari server tidak valid.</div>').fadeIn();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerAntibiotik').html('<div class="alert alert-danger text-center m-3">Terjadi kesalahan format data dari server.</div>').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingAntibiotik').hide();
                    $('#tableContainerAntibiotik').html('<div class="alert alert-danger text-center m-3">Gagal terhubung ke server.</div>').fadeIn();
                }
            });
        });

        $('#btnDownloadAntibiotik').on('click', function() {
            const tanggalAwal = $('#tglAwalAntibiotik').val();
            const tanggalAkhir = $('#tglAkhirAntibiotik').val();
            window.location.href = `<?= base_url("pasienispa/unduhdantibiotik") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });

    });
</script>