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

    table.dataTable {
        width: 100% !important;
        margin: 0 auto;
        clear: both;
        border-collapse: collapse;
    }

    .filter-wrapper {
        background-color: #ffffff;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        border: 1px solid #e0e4e8;
    }

    .daily-chart-wrapper {
        position: relative;
        width: 100%;
        height: 320px;
        max-height: 320px;
        overflow: visible;
    }

    .daily-chart-wrapper canvas {
        width: 100% !important;
        height: 100% !important;
    }

    /* Penyesuaian tombol di layar HP */
    @media (max-width: 768px) {
        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 15px;
        }

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

        .daily-chart-wrapper {
            height: 260px;
            max-height: 260px;
        }

        .detail-header-controls {
            flex-direction: column;
            align-items: stretch !important;
            gap: 10px;
        }
    }

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

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

            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="mb-0 font-weight-bold text-dark">Rekap Keuangan SIRUS (BPJS)</h2>
                    <ol class="breadcrumb bg-transparent p-0 mt-2 mb-0">
                        <li class="breadcrumb-item"><a href="index.html" class="text-decoration-none">Dashboard</a></li>
                        <li class="breadcrumb-item active">Tampilan Data Rekap & Detail</li>
                    </ol>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="filter-wrapper mb-4">
                        <form id="filterForm">
                            <div class="row g-3 align-items-end">
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label for="tanggal_awal" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AWAL</label>
                                    <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label for="tanggal_akhir" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AKHIR</label>
                                    <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-3">
                                    <label for="kd_jenis_pasien" class="form-label text-muted font-weight-bold small mb-1">JENIS PASIEN</label>
                                    <select id="kd_jenis_pasien" name="kd_jenis_pasien" class="form-select custom-select shadow-sm" required>
                                        <option value="" disabled <?= empty($kd_jenis_pasien) ? 'selected' : '' ?>>Pilih Jenis Pasien</option>
                                        <option value="1" <?= ($kd_jenis_pasien == '1') ? 'selected' : '' ?>>Rawat Jalan</option>
                                        <option value="2" <?= ($kd_jenis_pasien == '2') ? 'selected' : '' ?>>Rawat Inap</option>
                                        <option value="3" <?= ($kd_jenis_pasien == '3') ? 'selected' : '' ?>>IGD</option>
                                    </select>
                                </div>
                                <div class="col-12 col-md-3 col-lg-5">
                                    <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> Tampilkan Rekap</button>
                                        <button type="button" id="downloadButton" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel Rekap</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-12 mb-3 px-0" id="chartMetricButtons" style="display:none;">
                <div class="d-flex flex-wrap gap-2 p-2 bg-white rounded shadow-sm border">
                    <button type="button" class="btn btn-sm btn-primary active metric-btn" data-metric="jumlah">
                        <i class="fas fa-users me-1"></i> Jumlah Pasien
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-success metric-btn" data-metric="tarif_bpjs">
                        <i class="fas fa-file-invoice-dollar me-1"></i> Tarif BPJS
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-warning metric-btn" data-metric="tarif_rs">
                        <i class="fas fa-hospital me-1"></i> Tarif RS
                    </button>

                    <div class="border-right mx-2 d-none d-md-block"></div>

                    <button type="button" id="btnDetailTagihan" class="btn btn-sm btn-outline-secondary font-weight-bold">
                        <i class="fas fa-list-alt me-1"></i> Detail Tagihan
                    </button>
                </div>
            </div>

            <div id="result" class="card border-0 shadow-sm mb-4" style="border-radius: 12px; overflow:hidden;">
                <div class="card-body p-0 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: 50px;" />
                        <p class="text-muted mt-2 font-weight-bold">Memproses data...</p>
                    </div>

                    <div id="chartSection" class="mb-4" style="display: none;">
                        <div class="card border-0">
                            <div class="card-body pb-0 text-center text-md-left">
                                <h5 class="card-title text-secondary font-weight-bold mb-4">Grafik Pendapatan & Pasien per DPJP</h5>
                                <div class="daily-chart-wrapper">
                                    <canvas id="dailyChart"></canvas>
                                </div>
                                <div id="chartNoData" class="text-muted small mt-3" style="display: none;">Grafik tidak tersedia.</div>
                            </div>
                        </div>
                    </div>

                    <div id="detailTagihanContainer" class="mb-4" style="display: none;">
                        <div class="card border border-info shadow-none" style="border-radius: 10px; background-color: #fafbfc;">

                            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center flex-wrap detail-header-controls">
                                <h5 class="mb-0 font-weight-bold text-info"><i class="fas fa-file-invoice mr-2"></i>Rincian Detail Tagihan Pasien</h5>

                                <div class="d-flex align-items-center flex-wrap gap-2">
                                    <label class="mb-0 mr-2 text-muted font-weight-bold small">TIPE BAYAR :</label>
                                    <select id="kd_pembayaran_detail" class="form-control form-control-sm mr-2 shadow-sm" style="width: 220px; border-radius: 6px;">
                                        <option value="A12" selected>BPJS</option>
                                        <option value="A08">UMUM</option>
                                        <option value="ASURANSI">ASURANSI</option>
                                    </select>

                                    <button type="button" id="btnDownloadDetail" class="btn btn-sm btn-success shadow-sm font-weight-bold" style="display: none;">
                                        <i class="fas fa-file-excel mr-1"></i> Excel Detail
                                    </button>
                                </div>
                            </div>

                            <div class="card-body p-0">
                                <div id="loadingDetail" 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-info mt-2 small font-weight-bold">Menarik rincian dari server...</p>
                                </div>
                                <div class="table-responsive p-3" id="tableContainerDetail" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

                    <hr class="my-2" style="border-top: 2px dashed #e9ecef;">

                    <div class="table-responsive p-3" id="tableContainer" style="display: none;"></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">
                <div class="text-muted font-weight-bold">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>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>

<script>
    Chart.register(ChartDataLabels);

    $(document).ready(function() {
        let dailyChart = null;
        let currentList = [];
        let currentMetric = 'jumlah';

        const parseNumericValue = value => {
            if (value === null || value === undefined) return 0;
            const cleaned = String(value).replace(/[^0-9\-\.]/g, '');
            return cleaned === '' ? 0 : parseFloat(cleaned);
        };

        const buildDailyChart = (list, metric = 'jumlah') => {
            const chartContainer = $('#chartSection');
            const noDataMessage = $('#chartNoData');
            const ctx = document.getElementById('dailyChart').getContext('2d');
            if (!Array.isArray(list) || list.length === 0) {
                chartContainer.hide();
                return;
            }

            const grouped = {};
            list.forEach(item => {
                const dpjp = item.dpjp || 'Tidak Diketahui';
                if (!grouped[dpjp]) {
                    grouped[dpjp] = {
                        count: 0,
                        tarif_bpjs: 0,
                        tarif_rs: 0
                    };
                }
                grouped[dpjp].count += parseNumericValue(item.jlm_ri);
                grouped[dpjp].tarif_bpjs += parseNumericValue(item.tarif_bpjs);
                grouped[dpjp].tarif_rs += parseNumericValue(item.tarif_rs);
            });

            const metricConfig = {
                jumlah: {
                    label: 'Jumlah Pasien',
                    field: 'count',
                    color: 'rgba(54, 162, 235, 0.7)',
                    border: 'rgba(54, 162, 235, 1)',
                    yTitle: 'Pasien',
                    fmt: v => v
                },
                tarif_bpjs: {
                    label: 'Tarif BPJS',
                    field: 'tarif_bpjs',
                    color: 'rgba(40, 167, 69, 0.7)',
                    border: 'rgba(40, 167, 69, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
                tarif_rs: {
                    label: 'Tarif RS',
                    field: 'tarif_rs',
                    color: 'rgba(255, 193, 7, 0.7)',
                    border: 'rgba(255, 193, 7, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
            };
            const cfg = metricConfig[metric] || metricConfig['jumlah'];
            const labels = Object.keys(grouped).sort((a, b) => grouped[b][cfg.field] - grouped[a][cfg.field]);
            const values = labels.map(dpjp => grouped[dpjp][cfg.field]);

            if (dailyChart) dailyChart.destroy();
            dailyChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [{
                        label: cfg.label,
                        data: values,
                        backgroundColor: cfg.color,
                        borderColor: cfg.border,
                        borderWidth: 1,
                        maxBarThickness: 30,
                        borderRadius: 4
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            offset: 2,
                            font: {
                                size: 9,
                                weight: 'bold'
                            },
                            color: '#555',
                            formatter: (value) => cfg.fmt(value),
                            clip: false
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                autoSkip: false,
                                maxRotation: 45,
                                minRotation: 30,
                                font: {
                                    size: 10
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: metric !== 'jumlah' ? v => `Rp ${Number(v).toLocaleString('id-ID')}` : v => v
                            }
                        }
                    }
                }
            });
            chartContainer.fadeIn();
        };

        // --- SUBMIT FILTER REKAP UTAMA ---
        $('#filterForm').on('submit', function(event) {
            event.preventDefault();
            $('#detailTagihanContainer').hide();
            $('#chartSection').hide();
            $('#tableContainer').hide();
            $('#btnDetailTagihan').removeClass('btn-secondary active').addClass('btn-outline-secondary');
            $('#loadingIcon').show();

            $.ajax({
                url: '<?= base_url("billing/tampildatarekapkeubpjs") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir').val(),
                    KD_JENIS_PASIEN: $('#kd_jenis_pasien').val()
                },
                success: function(tampil) {
                    $('#loadingIcon').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil)) {
                            const list = data.tampil;
                            if ($.fn.DataTable.isDataTable('#datatablesSimple')) {
                                $('#datatablesSimple').DataTable().destroy();
                            }
                            if (list.length > 0) {
                                currentList = list;
                                buildDailyChart(list, currentMetric);
                                $('#chartMetricButtons').fadeIn();

                                let html = `<table id="datatablesSimple" class="table table-striped table-hover table-bordered w-100 text-nowrap">
                                    <thead class="bg-light"><tr><th>DPJP</th><th class="text-center">Jumlah</th><th class="text-right">Tarif BPJS</th><th class="text-right">Tarif RS</th><th class="text-right">BMHP</th></tr></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-primary">${item.jlm_ri}</td><td class="text-right">${parseNumericValue(item.tarif_bpjs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.tarif_rs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.bmhp).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableContainer').html(html).fadeIn();
                                $('#datatablesSimple').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    language: {
                                        search: "Cari Rekap:"
                                    }
                                });
                                $('#downloadButton').fadeIn();
                            }
                        }
                    } catch (e) {
                        console.error(e);
                    }
                }
            });
        });

        function loadDetailTagihan() {
            $('#loadingDetail').show();
            $('#tableContainerDetail').hide();
            $('#btnDownloadDetail').hide();

            $.ajax({
                url: '<?= base_url("detialtagihan/tampildata") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir').val(),
                    KD_JENIS_PASIEN: $('#kd_jenis_pasien').val(),
                    KD_PEMBAYARAN: $('#kd_pembayaran_detail').val()
                },
                success: function(response) {
                    $('#loadingDetail').hide();

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

                        // === PERBAIKAN: Ubah data.tampil menjadi data.response ===
                        if (data && Array.isArray(data.response)) {
                            const list = data.response; // === UBAH JUGA DI SINI ===

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

                            if (list.length > 0) {
                                let html = `<table id="dtDetail" class="table table-striped table-hover table-bordered w-100 text-nowrap">
                                                <thead class="bg-info text-white">
                                                    <tr>
                                                        <th>DPJP</th>
                                                        <th class="text-center">Jml Pasien</th>
                                                        <th class="text-center">Pasien INACBG</th>
                                                        <th class="text-right">Total Tagihan</th>
                                                        <th class="text-right">Tagihan Pribadi</th>
                                                        <th class="text-right">Tagihan Penjamin</th>
                                                        <th class="text-right">Tarif INACBG</th>
                                                    </tr>
                                                </thead>
                                                <tbody>`;

                                list.forEach(item => {
                                    html += `<tr>
                                    <td><strong>${item.dpjp}</strong></td>
                                    <td class="text-center font-weight-bold text-info">${item.jumlah_pasien}</td>
                                    <td class="text-center">${item.jumlah_pasien_ada_inacbg}</td>
                                    <td class="text-right text-danger font-weight-bold">${parseNumericValue(item.total_tagihan).toLocaleString('id-ID')}</td>
                                    <td class="text-right">${parseNumericValue(item.total_tagihan_pribadi).toLocaleString('id-ID')}</td>
                                    <td class="text-right">${parseNumericValue(item.total_tagihan_penjamin).toLocaleString('id-ID')}</td>
                                    <td class="text-right text-success font-weight-bold">${parseNumericValue(item.total_tarif_inacbg).toLocaleString('id-ID')}</td>
                                </tr>`;
                                });
                                html += '</tbody></table>';

                                $('#tableContainerDetail').html(html).fadeIn();

                                $('#dtDetail').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    pageLength: 8,
                                    lengthMenu: [8, 10, 25, 50],
                                    language: {
                                        search: "Cari Detail:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_-_END_ dari _TOTAL_"
                                    }
                                });

                                $('#btnDownloadDetail').fadeIn();
                            } else {
                                $('#tableContainerDetail').html('<div class="alert alert-info text-center m-4">Tidak ada rincian tagihan yang ditemukan untuk tipe pembayaran ini.</div>').fadeIn();
                                $('#btnDownloadDetail').hide();
                            }
                        } else {
                            $('#tableContainerDetail').html('<div class="alert alert-warning text-center m-4">Format data detail tidak valid.</div>').fadeIn();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerDetail').html('<div class="alert alert-danger text-center m-4">Terjadi kesalahan format data dari server.</div>').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingDetail').hide();
                    console.error("AJAX Error: ", error);
                    $('#tableContainerDetail').html('<div class="alert alert-danger text-center m-4">Gagal terhubung ke server.</div>').fadeIn();
                }
            });
        }

        // --- EVENT BUTTONS ---
        $('#btnDetailTagihan').on('click', function() {
            $('.metric-btn').removeClass('btn-primary btn-success btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_bpjs' ? 'btn-outline-success' : m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $(this).removeClass('btn-outline-secondary').addClass('btn-secondary active');
            $('#chartSection').hide();
            $('#detailTagihanContainer').fadeIn();
            loadDetailTagihan();
        });

        $('#kd_pembayaran_detail').on('change', function() {
            loadDetailTagihan();
        });

        $('.metric-btn').on('click', function() {
            $('#detailTagihanContainer').hide();
            $('#chartSection').fadeIn();
            $('#btnDetailTagihan').removeClass('btn-secondary active').addClass('btn-outline-secondary');
            const metric = $(this).data('metric');
            currentMetric = metric;
            $('.metric-btn').removeClass('btn-primary btn-success btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_bpjs' ? 'btn-outline-success' : m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            if (metric === 'jumlah') {
                $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
            }
            if (metric === 'tarif_bpjs') {
                $(this).removeClass('btn-outline-success').addClass('btn-success active');
            }
            if (metric === 'tarif_rs') {
                $(this).removeClass('btn-outline-warning').addClass('btn-warning active');
            }
            if (currentList.length > 0) {
                buildDailyChart(currentList, metric);
            }
        });

        // --- DOWNLOAD ACTIONS ---
        $('#downloadButton').on('click', function() {
            window.location.href = `<?= base_url("billing/unduhrekapkeusirusbpjs") ?>?TANGGAL_AWAL=${$('#tanggal_awal').val()}&TANGGAL_AKHIR=${$('#tanggal_akhir').val()}&KD_JENIS_PASIEN=${$('#kd_jenis_pasien').val()}`;
        });

        $('#btnDownloadDetail').on('click', function() {
            window.location.href = `<?= base_url("detialtagihan/unduhdata") ?>?TANGGAL_AWAL=${$('#tanggal_awal').val()}&TANGGAL_AKHIR=${$('#tanggal_akhir').val()}&KD_JENIS_PASIEN=${$('#kd_jenis_pasien').val()}&KD_PEMBAYARAN=${$('#kd_pembayaran_detail').val()}`;
        });
    });
</script>