<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 agar menyesuaikan layar */
    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 Halus untuk Tabel di HP */
    .table-responsive {
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

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

    /* Responsif Form */
    @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>

<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 overflow-hidden">
            <h1 class="mt-4 fs-3" id="judulPasien">Data Hasil MCU</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">Tampilkan Data Hasil MCU</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="<?php echo isset($tgl_awal) ? $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="<?php echo isset($tgl_akhir) ? $tgl_akhir : ''; ?>" required />
                            </div>

                            <div class="col-12 col-md-6 col-lg-4">
                                <label for="kd_grupmcu" class="form-label text-muted small fw-bold mb-1">Grup MCU</label>
                                <select id="kd_grupmcu" name="KD_GROUP_MCU" class="form-select" required>
                                    <option value="" disabled selected>Memuat Grup MCU...</option>
                                    </select>
                            </div>

                            <div class="col-12 col-lg-12 mt-3 mt-lg-0">
                                <div class="btn-group-custom mt-3">
                                    <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                    <button type="button" id="downloadSummaryButton" class="btn btn-info px-3 shadow-sm text-white" style="display: none;"><i class="fas fa-file-excel me-1"></i> Data MCU</button>
                                    <button type="button" id="downloadDetailButton" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Data Pemeriksaan</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="<?php echo 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 class="table-responsive w-100" 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 src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        
        // FUNGSI MEMUAT DATA GRUP MCU
        function loadGrupmcu() { 
            const grupmcuDropdown = $('#kd_grupmcu');
            $.ajax({
                url: '<?php echo base_url("mcu/refgrupMCU"); ?>',
                type: 'POST',
                dataType: 'json',
                success: function(data) {
                    grupmcuDropdown.empty().append('<option value="" disabled selected>Pilih Nama Grup</option>');
                    if (data && Array.isArray(data.response)) {
                        $.each(data.response, function(index, grupmcu) {
                            const option = new Option(grupmcu.institusi_asal, grupmcu.kd_group_mcu);
                            grupmcuDropdown.append(option);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("AJAX Error:", status, error);
                    grupmcuDropdown.empty().append('<option value="" disabled selected>Gagal memuat Data Grup</option>');
                }
            });
        }
        loadGrupmcu();

        // FUNGSI SUBMIT FILTER
        $('#filterForm').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon').show();
            $('#tableContainer').hide();
            $('#downloadSummaryButton, #downloadDetailButton').hide();

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

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

                    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 (Ditambah class text-nowrap agar rapi)
                            let headerHtml = '<tr>';
                            headers.forEach(header => {
                                headerHtml += `<th>${header}</th>`;
                            });
                            headerHtml += '</tr>';

                            // 2. Buat Body Tabel
                            let bodyHtml = '';
                            list.forEach(item => {
                                bodyHtml += '<tr>';
                                
                                let jenisKelamin = '';
                                if (item.alamat_kantor) {
                                    const lines = item.alamat_kantor.split(/\r\n|\n|\r/);
                                    if (lines.length > 2 && lines[2]) {
                                        jenisKelamin = lines[2].split('/')[0].trim();
                                    }
                                }
                                if (!jenisKelamin && item.jenis_kelamin) {
                                    jenisKelamin = item.jenis_kelamin;
                                }
                                
                                headers.forEach(header => {
                                    let cellValue = '';
                                    if (header === 'No Registrasi') cellValue = item.kd_registrasi;
                                    else if (header === 'Nama Perusahaan') cellValue = item.institusi_asal;
                                    else if (header === 'Nama Pasien') cellValue = item.nm_pasien;
                                    else if (header === 'Usia') cellValue = item.usia;
                                    else if (header === 'Jenis Kelamin') cellValue = jenisKelamin;
                                    else if (header === 'Tgl Periksa') cellValue = item.tgl_registrasi;
                                    else if (header === 'No RM') cellValue = item.kd_rekam_medis;
                                    else if (header === 'Jabatan') cellValue = item.divisi;
                                    else if (header === 'Paket MCU') cellValue = item.kd_paket_mcu;
                                    else {
                                        cellValue = item[header] || '-';
                                    }
                                    bodyHtml += `<td>${cellValue}</td>`;
                                });
                                bodyHtml += '</tr>';
                            });

                            // 3. Gabungkan dan Tampilkan (Penting: class text-nowrap ditambahkan)
                            const tableHtml = `<table id="datatablesSimple" class="table table-striped table-bordered text-nowrap w-100"><thead class="table-dark text-center">${headerHtml}</thead><tbody>${bodyHtml}</tbody></table>`;
                            
                            $('#tableContainer').html(tableHtml).show();
                            
                            // 4. Inisialisasi DataTable dengan scrollX karena kolom dinamis MCU biasanya sangat panjang
                            $('#datatablesSimple').DataTable({
                                scrollX: true,
                                autoWidth: false,
                                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_"
                                }
                            });
                            
                            $('#downloadSummaryButton, #downloadDetailButton').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();
                        }
                    } else {
                        const message = data.error || 'Format data balasan tidak sesuai.';
                        $('#tableContainer').html(`<div class="alert alert-warning text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> ${message}</div>`).show();
                    }
                },
                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-times-circle me-1"></i> Gagal terhubung ke server.</div>').show();
                }
            });
        });

        // FUNGSI DOWNLOAD EXCEL
        $('#downloadSummaryButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            const kdgrupmcu = $('#kd_grupmcu').val();
            window.location.href = `<?php echo base_url("mcu/unduhdataMCU1"); ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_GROUP_MCU=${kdgrupmcu}`;
        });

        $('#downloadDetailButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            const kdgrupmcu = $('#kd_grupmcu').val();
            window.location.href = `<?php echo base_url("mcu/unduhdataMCU2"); ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_GROUP_MCU=${kdgrupmcu}`;
        });
    });
</script>