<style>
    /* 1. KUNCI ANTI JEBOL / MELAR KE KANAN */
    body, html {
        overflow-x: hidden !important;
        width: 100%;
        max-width: 100vw;
        font-family: 'Poppins', sans-serif;
        background-color: #f8f9fa;
    }

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

    /* 3. MEMAKSA TABEL DAN CARD AGAR PATUH PADA UKURAN 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; 
        border: none;
        border-radius: 15px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #eee;
        border-radius: 15px 15px 0 0 !important;
        padding: 20px;
        font-weight: 600;
    }

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

    /* --- MODERN SLIDE SWITCH CSS --- */
    .switch-wrapper {
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        height: 100%;
        padding-bottom: 2px;
    }

    .switch {
        position: relative;
        display: inline-block;
        width: 70px; 
        height: 38px; 
        margin-right: 15px;
    }

    .switch input { opacity: 0; width: 0; height: 0; }

    .slider {
        position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
        background-color: #17a2b8; transition: .4s; border-radius: 38px;
        box-shadow: inset 0 2px 5px rgba(0,0,0,0.1);
    }

    .slider:before {
        position: absolute; content: "\f554"; font-family: "Font Awesome 5 Free"; font-weight: 900;
        height: 30px; width: 30px; left: 4px; bottom: 4px; background-color: white; transition: .4s;
        border-radius: 50%; display: flex; align-items: center; justify-content: center;
        color: #17a2b8; font-size: 16px; box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }

    input:checked + .slider { background-color: #dc3545; }
    input:focus + .slider { box-shadow: 0 0 1px #dc3545; }
    input:checked + .slider:before { transform: translateX(32px); content: "\f236"; color: #dc3545; }

    #labelSwitch {
        font-weight: 600; font-size: 1rem; color: #17a2b8; transition: color 0.3s ease;
        margin-top: 5px; display: inline-block; vertical-align: middle;
    }

    /* TAMPILAN TOMBOL CUSTOM */
    .btn-custom-primary {
        background: linear-gradient(45deg, #0d6efd, #0b5ed7); border: none;
        box-shadow: 0 4px 6px rgba(13, 110, 253, 0.2); transition: all 0.3s ease;
    }
    .btn-custom-primary:hover {
        transform: translateY(-1px); box-shadow: 0 6px 8px rgba(13, 110, 253, 0.3);
    }

    /* RESPONSIVE LAYOUT UNTUK FORM FILTER */
    @media (max-width: 768px) {
        .switch-wrapper {
            margin-top: 15px; margin-bottom: 15px; align-items: flex-start;
        }
        .btn-container {
            width: 100%; display: flex; flex-direction: column; gap: 10px;
        }
        .btn-container button { width: 100%; }
        #downloadButton { margin-left: 0 !important; }
        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 overflow-hidden">
            <div class="d-flex justify-content-between align-items-center mt-4 mb-2">
                <div>
                    <h2 id="judulHalaman" style="font-weight: 600; color: #343a40;">Rekap Asuransi Tahunan (Rajal)</h2>
                    <ol class="breadcrumb mb-4 small text-muted bg-transparent p-0">
                        <li class="breadcrumb-item"><a href="#" class="text-decoration-none text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item active">Rekap Asuransi</li>
                    </ol>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-header">
                            <i class="fas fa-filter me-1"></i> Filter Data
                        </div>
                        <div class="card-body p-3 p-md-4">
                            <form id="filterForm">
                                <div class="row g-3 align-items-end"> 
                                    
                                    <div class="col-12 col-md-3">
                                        <label for="tanggal_awal" class="form-label fw-bold text-muted small mb-1">PILIH TAHUN</label>
                                        <div class="input-group shadow-sm">
                                            <span class="input-group-text bg-light border-end-0"><i class="far fa-calendar-alt"></i></span>
                                            <input type="number" id="tanggal_awal" name="tanggal_awal" 
                                                   class="form-control border-start-0 ps-0" placeholder="YYYY" 
                                                   min="2020" max="2099" value="<?= date('Y') ?>" required />
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-4">
                                        <div class="switch-wrapper">
                                            <div class="d-flex align-items-center">
                                                <label class="switch mb-0">
                                                    <input type="checkbox" id="switchTipePasien">
                                                    <span class="slider round"></span>
                                                </label>
                                                <span id="labelSwitch">Mode: Rawat Jalan</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-5">
                                        <div class="btn-container d-flex justify-content-md-end mt-3 mt-md-0"> 
                                            <button type="submit" class="btn btn-primary btn-custom-primary px-4 me-md-2 shadow-sm">
                                                <i class="fas fa-search me-1"></i> Tampilkan
                                            </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> Excel
                                            </button>
                                        </div>
                                    </div>

                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div id="result">
                <div id="loadingIcon" style="display: none;" class="py-5">
                    <center>
                        <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted fw-bold">Sedang memuat data...</p>
                    </center>
                </div>
                
                <div class="card shadow-sm border-0" id="tableCardContainer" style="display:none; border-radius: 10px; overflow: hidden;">
                    <div class="card-body p-2 p-md-3">
                        <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">
                <div class="text-muted">Copyright &copy; IT RSU Ananda Purwokerto 2024</div>
            </div>
        </div>
    </footer>
</div>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script>
    $(document).ready(function() {
            
        // 1. Logika Ubah Teks, Warna Label Switch, dan Warna Ikon
        $('#switchTipePasien').change(function() {
            if($(this).is(':checked')) {
                // ON = Ranap
                $('#labelSwitch').text('Mode: Rawat Inap (Ranap)');
                $('#labelSwitch').css('color', '#dc3545'); // Merah
                $('#judulHalaman').text('Rekap Asuransi Tahunan (Ranap)');
            } else {
                // OFF = Rajal
                $('#labelSwitch').text('Mode: Rawat Jalan (Rajal)');
                $('#labelSwitch').css('color', '#17a2b8'); // Biru
                $('#judulHalaman').text('Rekap Asuransi Tahunan (Rajal)');
            }
        });

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

            const isRanap = $('#switchTipePasien').is(':checked');

            $.ajax({
                url: $('#switchTipePasien').is(':checked') ? 
                    '<?= base_url("rekapasuransi/tampilrekap2") ?>' : 
                    '<?= base_url("rekapasuransi/tampilrekap1") ?>',
                type: 'POST',
                data: { TANGGAL_AWAL: $('#tanggal_awal').val() },
                success: function(response) {
                    $('#loadingIcon').hide();

                    try {
                        const data = JSON.parse(response);
                        const isRanap = $('#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) {
                                // PERBAIKAN: Bungkus tabel dengan div.table-responsive AGAR BISA SCROLL DI HP
                                let html = `
                                <div class="table-responsive w-100">
                                    <table id="datatablesSimple" class="table table-striped table-hover mb-0 text-nowrap w-100">
                                `;

                                if (isRanap) {
                                    // HEADER RANAP
                                    html += `
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>Urut</th>
                                                    <th>Bulan</th>
                                                    <th>Nama Asuransi</th>
                                                    <th>Nama Dokter</th>
                                                    <th>Jumlah</th>
                                                    <th class="text-end">Tarif (Rp)</th>
                                                </tr>
                                            </thead>
                                            <tbody>`;
                                        list.forEach(item => {
                                            let tarifFormat = parseFloat(item.tarif).toLocaleString('id-ID');
                                            html += `
                                                <tr>
                                                    <td>${item.urut}</td>
                                                    <td>${item.bulan}</td>
                                                    <td class="fw-bold text-primary">${item.nama_asuransi}</td>
                                                    <td class="fw-bold text-primary">${item.nm_dokter}</td>
                                                    <td class="fw-bold text-primary">${item.qty}</td>
                                                    <td class="text-end fw-bold">${tarifFormat}</td>
                                                </tr>`;
                                        });
                                } else {
                                    // HEADER RAJAL
                                    html += `
                                            <thead class="table-info"> 
                                                <tr>
                                                    <th>No Urut</th>
                                                    <th>Bulan</th>
                                                    <th>Nama Asuransi</th>
                                                    <th class="text-center">Jumlah (Qty)</th>
                                                </tr>
                                            </thead>
                                            <tbody>`;
                                        list.forEach(item => {
                                            html += `
                                                <tr>
                                                    <td>${item.urut}</td>
                                                    <td>${item.bulan}</td>
                                                    <td class="fw-bold">${item.nama_asuransi}</td>
                                                    <td class="text-center"><span class="badge bg-secondary rounded-pill">${item.qty}</span></td>
                                                </tr>`;
                                        });
                                }

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

                                $('#datatablesSimple').DataTable({
                                    dom: 'Bfrtip',
                                    responsive: false, // Wajib false agar div table-responsive yang berfungsi
                                    scrollX: false,    // Wajib false agar tidak error di Android
                                    autoWidth: false,
                                    buttons: [
                                        { extend: 'excel', className: 'btn btn-sm btn-outline-success' },
                                        { extend: 'pdf', className: 'btn btn-sm btn-outline-danger' },
                                        { extend: 'print', className: 'btn btn-sm btn-outline-secondary' }
                                    ],
                                    language: {
                                        search: "_INPUT_",
                                        searchPlaceholder: "Cari data..."
                                    }
                                });

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

                            } else {
                                $('#tableContainer').html('<div class="alert alert-warning m-3"><i class="fas fa-exclamation-triangle"></i> Tidak ada data ditemukan pada tahun tersebut.</div>').show();
                                $('#tableCardContainer').fadeIn();
                                $('#downloadButton').hide();
                            }
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning m-3">Respon data kosong.</div>').show();
                            $('#tableCardContainer').fadeIn();
                            $('#downloadButton').hide();
                        }

                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger m-3">Error: Data bukan JSON valid.<br></div>').show();
                        $('#tableCardContainer').fadeIn();
                        $('#downloadButton').hide();
                    }
                },
                error: function(xhr, status, error) { 
                    $('#loadingIcon').hide(); 
                    $('#tableContainer').html('<div class="alert alert-danger m-3">Gagal koneksi server.</div>').show(); 
                    $('#tableCardContainer').fadeIn();
                }
            });
        });

        // 3. Event Download
        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const isRanap = $('#switchTipePasien').is(':checked');
            
            let urlDownload = '';
            if(isRanap) {
                urlDownload = '<?= base_url("rekapasuransi/unduhrekapkeuranap") ?>'; 
            } else {
                urlDownload = '<?= base_url("rekapasuransi/unduhrekapkeurajal") ?>';
            }
            window.location.href = `${urlDownload}?TANGGAL_AWAL=${tanggalAwal}`;
        });
    });
</script>