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

    /* 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: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }

    /* 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%;
        }
    }
    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
    }

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

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

    @media (max-width: 768px) {
        .daily-chart-wrapper {
            height: 240px;
            max-height: 240px;
        }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4" id="judulPasien">Data Rekap Keuangan SIRUS NON BPJS - ASURANSI</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampilkan Data Rekap Keuangan SIRUS NON BPJS - ASURANSI</li>
            </ol>
            
            <div class="row">
                <div class="col-md-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-end">
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label for="tanggal_awal" class="form-label text-muted small mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3 col-lg-2">
                                        <label for="tanggal_akhir" class="form-label text-muted small mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" 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 small mb-1">Jenis Pasien</label>
                                        <select id="kd_jenis_pasien" name="kd_jenis_pasien" class="form-select" 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"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton" class="btn btn-success px-4" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tombol Pilih Metrik Grafik -->
            <div class="mb-3" id="chartMetricButtons" style="display:none;">
                <div class="d-flex flex-wrap" style="gap:8px;">
                    <button type="button" class="btn btn-sm btn-primary active metric-btn" data-metric="jumlah">
                        <i class="fas fa-users me-1"></i> Jumlah
                    </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>
            </div>

            <div id="result" class="card border-0 shadow-sm mb-4">
                <div class="card-body p-0 p-md-3">
                    <div id="loadingIcon" style="display: none;" class="py-5 text-center">
                        <center><img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;"/></center>
                        <p class="text-muted mt-2">Memuat data...</p>
                    </div>
                    <div id="chartSection" class="p-3" style="display: none;">
                        <div class="card shadow-sm border-0">
                            <div class="card-body">
                                <h5 class="card-title">Grafik Rekap Per DPJP Jumlah Pasien & Total Pendapatan Non BPJS - Asuransi</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 karena data tidak ditemukan.</div>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive" id="tableContainer" style="display: none;">
                        </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="py-4 bg-light mt-auto">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small">
                <div class="text-muted">Copyright &copy; By IT RSU Ananda Purwokerto 2024</div>
                <div>
                    <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://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 buildChart = (list, metric) => {
            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_rs: 0 };
                }
                grouped[dpjp].count    += parseNumericValue(item.jlm_ri);
                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: 'Jumlah Pasien',  fmt: v => v },
                tarif_rs: { label: 'Total Tarif RS', field: 'tarif_rs', color: 'rgba(255,193,7,0.7)',   border: 'rgba(255,193,7,1)',   yTitle: 'Tarif RS (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]);

            if (labels.length === 0) {
                chartContainer.hide();
                noDataMessage.show();
                return;
            }

            const values = labels.map(dpjp => grouped[dpjp][cfg.field]);

            if (dailyChart) {
                dailyChart.destroy();
            }

            dailyChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: cfg.label,
                        data: values,
                        backgroundColor: cfg.color,
                        borderColor: cfg.border,
                        borderWidth: 1,
                        maxBarThickness: 20,
                        categoryPercentage: 0.72,
                        barPercentage: 0.82,
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        legend: { position: 'top' },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const v = context.parsed.y;
                                    return context.dataset.label + ': ' + cfg.fmt(v);
                                }
                            }
                        },
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            offset: 2,
                            font: { size: 9, weight: 'bold' },
                            color: '#333',
                            formatter: function(value) { return cfg.fmt(value); },
                            clip: false
                        }
                    },
                    layout: {
                        padding: { top: 30 }
                    },
                    scales: {
                        x: {
                            title: { display: true, text: 'DPJP' },
                            ticks: { autoSkip: false, maxRotation: 45, minRotation: 30, font: { size: 10 } }
                        },
                        y: {
                            type: 'linear',
                            position: 'left',
                            title: { display: true, text: cfg.yTitle },
                            beginAtZero: true,
                            ticks: metric !== 'jumlah' ? { callback: function(v) { return 'Rp ' + Number(v).toLocaleString('id-ID'); } } : {}
                        }
                    }
                }
            });

            noDataMessage.hide();
            chartContainer.show();
        };

        // Handler tombol metrik
        $(document).on('click', '.metric-btn', function() {
            currentMetric = $(this).data('metric');
            $('.metric-btn').removeClass('btn-primary btn-warning').addClass('btn-outline-primary btn-outline-warning');
            $(this).removeClass('btn-outline-primary btn-outline-warning');
            if (currentMetric === 'jumlah') {
                $(this).addClass('btn-primary').removeClass('btn-outline-primary');
            } else {
                $(this).addClass('btn-warning').removeClass('btn-outline-warning');
            }
            buildChart(currentList, currentMetric);
        });

        $('#filterForm').on('submit', function(event) {
            event.preventDefault(); 
            $('#loadingIcon').show(); 
            $('#tableContainer').hide();
            $('#chartSection').hide();
            $('#chartMetricButtons').hide();

            $.ajax({
                url: '<?= base_url("keuangan/tampildatarekapkeunonbpjs_asuransi") ?>',
                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;
                            currentList = list;

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

                            if (list.length > 0) {
                                // Reset tombol metrik ke default
                                currentMetric = 'jumlah';
                                $('.metric-btn').removeClass('btn-primary btn-warning btn-outline-primary btn-outline-warning');
                                $('[data-metric="jumlah"]').addClass('btn-primary');
                                $('[data-metric="tarif_rs"]').addClass('btn-outline-warning');
                                $('#chartMetricButtons').show();
                                buildChart(list, currentMetric);
                                // KUNCI 2: MENGGUNAKAN text-nowrap DAN w-100 AGAR TABEL RAPI & BISA DIGESER
                                let html = `
                                <div class="table-responsive">
                                    <table id="datatablesSimple" class="table table-striped table-hover table-bordered w-100 text-nowrap">
                                        <thead class="table-light">
                                            <tr>
                                                <th>DPJP</th>
                                                <th>Jumlah</th>
                                                <th>Tarif RS</th>
                                                <th>Prosedur Non Bedah</th>
                                                <th>Prosedur Bedah</th>
                                                <th>Konsultasi</th>
                                                <th>Keperawatan</th>
                                                <th>Tenaga Ahli</th>
                                                <th>Laboratorium</th>
                                                <th>Radiologi</th>
                                                <th>Kamar & Akomodasi</th>
                                                <th>Konsultasi (2)</th>
                                                <th>Obat</th>
                                                <th>BMHP</th>
                                            </tr>
                                        </thead>
                                    <tbody>
                                `;

                                list.forEach(item => {
                                    // KUNCI 3: MENAMBAHKAN class="text-end" pada kolom uang agar rata kanan
                                    html += `<tr>
                                        <td>${item.dpjp}</td>
                                        <td class="text-center">${item.jlm_ri}</td>
                                        <td class="text-end">${item.tarif_rs}</td>
                                        <td class="text-end">${item.prosedur_non_bedah}</td>
                                        <td class="text-end">${item.prosedur_bedah}</td>
                                        <td class="text-end">${item.konsultasi}</td>
                                        <td class="text-end">${item.keperawatan}</td>
                                        <td class="text-end">${item.tenaga_ahli}</td>
                                        <td class="text-end">${item.laboratorium}</td>
                                        <td class="text-end">${item.radiologi}</td>
                                        <td class="text-end">${item.kamar_akomodasi}</td>
                                        <td class="text-end">${item.konsultasi}</td>
                                        <td class="text-end">${item.obat}</td>
                                        <td class="text-end">${item.bmhp}</td>
                                    </tr>`;
                                });
                                html += '</tbody></table>';
                                
                                $('#tableContainer').html(html).fadeIn(); 

                                // INISIALISASI DATATABLES
                                $('#datatablesSimple').DataTable({
                                    responsive: false, // Dimatikan agar tidak konflik dengan table-responsive
                                    autoWidth: false,
                                    language: {
                                        search: "Cari:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_-_END_ dari _TOTAL_"
                                    }
                                });

                                $('#downloadButton').fadeIn();
                            } else {
                                currentList = [];
                                $('#chartSection').hide();
                                $('#chartMetricButtons').hide();
                                $('#tableContainer').html('<div class="alert alert-info text-center m-3">Tidak ada data yang ditemukan.</div>').show();
                                $('#downloadButton').hide();
                            }
                        } else {
                            currentList = [];
                            $('#chartSection').hide();
                            $('#chartMetricButtons').hide();
                            $('#tableContainer').html('<div class="alert alert-warning text-center m-3">Tidak ada data yang ditemukan.</div>').show();
                            $('#downloadButton').hide();
                        }

                        history.replaceState(null, '', '<?= base_url("keuangan/tampildatarekapkeunonbpjs_asuransi") ?>');
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger text-center m-3">Terjadi kesalahan saat memproses data.</div>').show();
                        $('#downloadButton').hide();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide(); 
                    console.error("AJAX Error: ", error);
                    $('#tableContainer').html('<div class="alert alert-danger text-center m-3">Koneksi ke server gagal.</div>').show();
                }
            });
        });

        // Event untuk tombol download
        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            const kdjenispasien = $('#kd_jenis_pasien').val();
            window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_asuransi") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_JENIS_PASIEN=${kdjenispasien}`;
        });
    });
</script>