<style>
    /* 1. KUNCI ANTI-JEBOL: Mengunci Lebar Layar Max 100% */
    html, body {
        max-width: 100vw;
        overflow-x: hidden !important;
    }

    #layoutSidenav_content {
        width: 100%;
        max-width: 100vw;
        overflow-x: hidden !important;
    }

    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
        }
    }

    /* 2. KUNCI TABEL: Membatalkan CSS min-width dari header.php */
    table, table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse !important;
        margin-top: 10px !important;
    }

    .table-responsive {
        width: 100%;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

    /* 3. CARD CONTAINER */
    .card {
        width: 100%;
        min-width: 0;
        overflow: hidden; /* Mencegah isi card bocor */
    }

    .filter-wrapper {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }

    /* --- 4. CSS SWITCH MODERN (Tetap dipertahankan) --- */
    .switch-container {
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
    }
    .switch {
        position: relative;
        display: inline-block;
        width: 50px;
        height: 28px;
        margin-right: 12px;
        flex-shrink: 0;
    }
    .switch input { opacity: 0; width: 0; height: 0; }
    .slider {
        position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
        background-color: #ccc; transition: .4s; border-radius: 34px;
    }
    .slider:before {
        position: absolute; content: ""; height: 20px; width: 20px; left: 4px; bottom: 4px;
        background-color: white; transition: .4s; border-radius: 50%;
    }
    input:checked + .slider { background-color: #dc3545; }
    input:focus + .slider { box-shadow: 0 0 1px #dc3545; }
    input:checked + .slider:before { transform: translateX(22px); }
    
    #labelSwitch {
        font-weight: 600;
        font-size: 1rem;
        transition: color 0.3s ease; 
        white-space: nowrap;
    }
    
    /* Perbaikan jarak elemen Form Filter untuk HP */
    @media (max-width: 768px) {
        .switch-container { margin-top: 10px; margin-bottom: 10px; }
        div.dataTables_wrapper div.dataTables_filter input { width: 140px !important; }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 mb-5">
            <h1 class="mt-4 fs-3 fw-bold text-dark" id="judulHalaman">Rekap Asuransi Tahunan (Rajal)</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="#" class="text-decoration-none">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampilan Rekap Asuransi Tahunan</li>
            </ol>

            <div class="row">
                <div class="col-12">
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterForm">
                                <div class="row g-3 align-items-center">
                                    
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label for="tanggal_awal" class="form-label text-muted small fw-bold mb-1">Pilih Tahun</label>
                                        <input type="number" id="tanggal_awal" name="tanggal_awal" 
                                               class="form-control" placeholder="YYYY" 
                                               min="2020" max="2099" value="<?= date('Y') ?>" required />
                                    </div>

                                    <div class="col-12 col-md-4 col-lg-4 mt-md-4 pt-md-2">
                                        <div class="switch-container">
                                            <label class="switch">
                                                <input type="checkbox" id="switchTipePasien">
                                                <span class="slider"></span>
                                            </label>
                                            <span id="labelSwitch">Mode: Rawat Jalan</span>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-5 col-lg-6 mt-md-4 pt-md-2">
                                        <div class="d-grid gap-2 d-md-flex justify-content-md-start">
                                            <button type="submit" class="btn btn-primary px-4">
                                                <i class="fas fa-search me-1"></i> Tampilkan
                                            </button>
                                            <button type="button" id="downloadButton" class="btn btn-success px-4" style="display: none;">
                                                <i class="fas fa-file-excel me-1"></i> Excel
                                            </button>
                                        </div>
                                    </div>
                                    
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div id="result" class="card border-0 shadow-sm mb-4" style="min-width: 0;">
                <div class="card-body p-2 p-md-3">
                    <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: 40px;" />
                        <p class="text-muted mt-2 small">Memuat data...</p>
                    </div>
                    
                    <div id="tableContainer" style="display: none;">
                        </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() {
            
        // 1. Logika Ubah Teks dan Warna Label Switch
        $('#switchTipePasien').change(function() {
            if($(this).is(':checked')) {
                $('#labelSwitch').text('Mode: Rawat Inap (Ranap)');
                $('#labelSwitch').css('color', '#dc3545'); 
                $('#judulHalaman').text('Rekap Asuransi Tahunan (Ranap)');
            } else {
                $('#labelSwitch').text('Mode: Rawat Jalan (Rajal)');
                $('#labelSwitch').css('color', ''); 
                $('#judulHalaman').text('Rekap Asuransi Tahunan (Rajal)');
            }
        });

        // 2. Event Submit Filter
        $('#filterForm').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIcon').show(); 
            $('#tableContainer').hide(); 
            $('#downloadButton').hide(); 

            const isRanap = $('#switchTipePasien').is(':checked');
            let targetUrl = isRanap 
                ? '<?= base_url("rekapkeutahunan/tampildatarekapkeuinap") ?>' 
                : '<?= base_url("rekapkeutahunan/tampildatarekapkeurajal") ?>'; 
            
            $.ajax({
                url: targetUrl,
                type: 'POST',
                data: { TANGGAL_AWAL: $('#tanggal_awal').val() },
                success: function(response) {
                    $('#loadingIcon').hide();

                    try {
                        const data = JSON.parse(response);
                        const currentIsRanap = $('#switchTipePasien').is(':checked');

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

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

                            if (list.length > 0) {
                                // PENTING: Pembungkus <div class="table-responsive w-100"> HARUS ADA
                                let html = `
                                <div class="table-responsive w-100">
                                    <table id="datatablesSimple" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                `;

                                if (currentIsRanap) {
                                    // HEADER RAWAT INAP
                                    html += `
                                        <thead class="table-light">
                                            <tr>
                                                <th>Bulan</th>
                                                <th>Nama Asuransi</th>
                                                <th>Jumlah</th>
                                                <th>Tarif (Rp)</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;
                                    
                                    list.forEach(item => {
                                        let tarifFormat = parseFloat(item.tarif || 0).toLocaleString('id-ID'); 
                                        html += `
                                            <tr>
                                                <td>${item.bulan}</td>
                                                <td class="text-wrap" style="min-width: 200px;">${item.nama_asuransi}</td>
                                                <td class="text-center">${item.qty}</td>
                                                <td class="text-end fw-bold">${tarifFormat}</td>
                                            </tr>`;
                                    });

                                } else {
                                    // HEADER RAWAT JALAN
                                    html += `
                                        <thead class="table-light">
                                            <tr>
                                                <th>Bulan</th>
                                                <th>Nama Asuransi</th>
                                                <th>Jumlah (Qty)</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;
                                    
                                    list.forEach(item => {
                                        html += `
                                            <tr>
                                                <td>${item.bulan}</td>
                                                <td class="text-wrap" style="min-width: 200px;">${item.nama_asuransi}</td>
                                                <td class="text-center fw-bold">${item.qty}</td>
                                            </tr>`;
                                    });
                                }

                                html += '</tbody></table></div>';
                                
                                $('#tableContainer').html(html).show();

                                // INISIALISASI DATATABLES DENGAN scrollX: false
                                $('#datatablesSimple').DataTable({
                                    responsive: false, 
                                    scrollX: false, // Dimatikan agar tidak konflik, scroll dikendalikan class table-responsive
                                    autoWidth: false,
                                    dom: 'Bfrtip',
                                    buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
                                    language: {
                                        search: "Cari:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_ - _END_ dari _TOTAL_"
                                    }
                                });

                                $('#downloadButton').fadeIn();

                            } else {
                                $('#tableContainer').html('<div class="alert alert-info text-center m-3 small">Tidak ada data ditemukan untuk tahun ini.</div>').show();
                            }
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning text-center m-3 small">Respon data kosong atau tidak valid.</div>').show();
                        }

                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data server.</div>').show();
                    }
                },
                error: function(xhr, status, error) { 
                    $('#loadingIcon').hide(); 
                    $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small">Gagal koneksi ke server.</div>').show(); 
                }
            });
        });

        // 3. Event Download
        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const isRanap = $('#switchTipePasien').is(':checked');
            
            let urlDownload = isRanap 
                ? '<?= base_url("rekapkeutahunan/unduhrekapkeuranap") ?>' 
                : '<?= base_url("rekapkeutahunan/unduhrekapkeurajal") ?>'; 

            window.location.href = `${urlDownload}?TANGGAL_AWAL=${tanggalAwal}`;
        });
    });
</script>