<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Rekap Keuangan SIRUS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <style>
        /* --- CSS PERBAIKAN TAMPILAN --- */
        .summary-table-container {
            border: 1px solid #dee2e6;
            border-radius: .25rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, .075);
        }

        .summary-table-container table {
            margin-bottom: 0;
        }
        
        .summary-table-container thead th {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            z-index: 1;
        }

        .summary-table-container .table-title th {
            font-size: 1rem;
            border-bottom: 1px solid #ccc !important;
        }

        .summary-table-container .table td,
        .summary-table-container .table th {
            padding: 0.5rem 1.25rem;
            font-size: 0.875rem;
            vertical-align: middle; /* <-- PERBAIKAN: Menambahkan perataan vertikal */
        }

        .summary-table-container .bank-name-column {
            /* width: 70%; */ /* <-- PERBAIKAN: Hapus lebar 70% agar lebar otomatis */
            border-right: 1px solid #dee2e6; /* Garis vertikal pemisah */
        }
        /* --- AKHIR DARI CSS PERBAIKAN --- */

        /* PERUBAHAN: Mengganti ID dan memberi jarak */
        #downloadBillingButton {
            margin-left: 10px;
        }
        #downloadDokterButton {
            margin-left: 10px;
        }


        @media (max-width: 768px) {
            .form-group {
                margin-bottom: 10px;
            }
        }

        .daily-chart-wrapper {
            position: relative;
            width: 100%;
            height: 300px;
            max-height: 300px;
            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>
</head>

<body>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4" id="judulPasien">Data Rekap Keuangan SIRUS NON BPJS-UMUM</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                    <li class="breadcrumb-item active">Tampilkan Rekap Keuangan SIRUS NON BPJS-UMUM</li>
                </ol>

                <div class="row mb-4 align-items-start">
                    <div class="col-lg-5">
                        <div class="card h-100">
                            <div class="card-body">
                                <form id="filterForm">
                                    <div class="row">
                                        <div class="col-md-9 form-group">
                                            <label for="tanggal_awal" class="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-md-9 form-group">
                                            <label for="tanggal_akhir" class="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-md-9 form-group">
                                            <label for="kd_jenis_pasien" class="mb-1">Jenis Pasien</label>
                                            <select id="kd_jenis_pasien" name="kd_jenis_pasien" class="custom-select" value="<?= $kd_jenis_pasien ?? '' ?>" required>
                                                <option value="" disabled selected>Pilih Jenis Pasien</option>
                                                <option value="1">Rawat Jalan</option>
                                                <option value="2">Rawat Inap</option>
                                                <option value="3">IGD</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-12 text-left">
                                            <button type="submit" class="btn btn-primary">Submit</button>
                                            
                                            <!-- PERUBAHAN: Ada 2 Tombol Download -->
                                            <button id="downloadBillingButton" type="button" class="btn btn-success" style="display: none;">Download Rekap KEU</button>
                                            <button id="downloadDokterButton" type="button" class="btn btn-info" style="display: none;">Unduh Data RekapInap DPJP_ANAK</button>
                                            <!-- AKHIR PERUBAHAN -->

                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-7">
                        <div id="summaryContainer" style="display: none;">
                            <!-- Tabel ringkasan akan dimasukkan di sini oleh JavaScript -->
                        </div>
                    </div>
                </div>

                <!-- Button 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 mr-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 mr-1"></i> Tarif RS
                        </button>
                    </div>
                </div>

                <div id="result">
                    <div id="loadingIcon" style="display: none; text-align: center;">
                        <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                    </div>
                    <div id="chartSection" class="mb-4" style="display: none;">
                        <div class="card shadow-sm">
                            <div class="card-body">
                                <h5 class="card-title">Grafik Per DPJP Jumlah Pasien & Total Pendapatan Non BPJS - Umum</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;">
                        <!-- Tabel utama akan dimasukkan di sini oleh JavaScript -->
                    </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 Support RSU Ananda Purwokerto 2024</div>
                    <div>
                        <a href="#">Privacy Policy</a>
                        &middot;
                        <a href="#">Terms &amp; Conditions</a>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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) => {
                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();
            };

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

                // PERUBAHAN: Sembunyikan kedua tombol saat filter baru
                $('#downloadBillingButton').hide();
                $('#downloadDokterButton').hide();

                $.ajax({
                    url: '<?= base_url("keuangan/tampildatarekapkeunonbpjs_umum") ?>',
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: $('#tanggal_awal').val(),
                        TANGGAL_AKHIR: $('#tanggal_akhir').val(),
                        KD_JENIS_PASIEN: $('#kd_jenis_pasien').val()
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIcon').hide();

                        if (data.status === 'error') {
                            Swal.fire('Error', data.message, 'error');
                            return;
                        }

                        // PERUBAHAN: Tampilkan tombol download DOKTER jika data summary ada
                        if (data.summary && data.summary.length > 0) {
                            let summaryHtml = '<div class="summary-table-container">' +
                                '<table class="table table-sm table-hover">' +
                                '<thead>' +
                                '<tr class="table-title">' +
                                '</tr>' +
                                '<tr>' +
                                '<th class="bank-name-column">Nama Dokter</th>' +
                                '<th class="text-right">Jumlah Pasien RANAP</th>' +
                                '<th class="text-right">Jumlah Pembayar Px UMUM</th>' +
                                '<th class="text-right">Jumlah Px Gabung tidak ditagih </th>' +
                                '</tr>' +
                                '</thead>' +
                                '<tbody>';

                            data.summary.forEach(item => {
                                summaryHtml += `<tr>
                                                <td class="bank-name-column"><strong>${item.nm_dokter}</strong></td>
                                                <td class="text-right">${item.jlm_ri}</td>
                                                <td class="text-right">${item.pasien_umum_bayar_umum}</td>
                                                <td class="text-right">${item.pasien_umum_gabung_ibu_alias_tidak_di_tagih}</td>
                                            </tr>`;
                            });

                            summaryHtml += '</tbody></table></div>';
                            $('#summaryContainer').html(summaryHtml).show();
                            $('#downloadDokterButton').show(); // Tampilkan tombol
                        } else {
                             $('#downloadDokterButton').hide(); // Sembunyikan jika tidak ada data
                        }


                        // PERUBAHAN: Tampilkan tombol download BILLING jika data response ada
                        if (data.response && data.response.length > 0) {
                            const list = data.response;

                            currentList = list;
                            buildDailyChart(list, currentMetric);
                            $('#chartMetricButtons').show();

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

                            let html = '<table id="datatablesSimple" class="table table-striped table-bordered"><thead><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>Obat</th><th>BMHP</th></tr></thead><tbody>';
                            
                            list.forEach(item => {
                                html += `<tr>
                                            <td>${item.dpjp}</td>
                                            <td>${item.jlm_ri}</td>
                                            <td>${item.tarif_rs}</td>
                                            <td>${item.prosedur_non_bedah}</td>
                                            <td>${item.prosedur_bedah}</td>
                                            <td>${item.konsultasi}</td>
                                            <td>${item.keperawatan}</td>
                                            <td>${item.tenaga_ahli}</td>
                                            <td>${item.laboratorium}</td>
                                            <td>${item.radiologi}</td>
                                            <td>${item.kamar_akomodasi}</td>
                                            <td>${item.obat}</td>
                                            <td>${item.bmhp}</td>
                                        </tr>`;
                            });
                            html += '</tbody></table>';
                            $('#tableContainer').html(html).show();

                            $('#datatablesSimple').DataTable({
                                responsive: true
                            });

                            $('#downloadBillingButton').show(); // Tampilkan tombol
                        } else {
                            $('#chartSection').hide();
                            $('#chartMetricButtons').hide();
                            $('#tableContainer').html('<div class="alert alert-warning text-center">Tidak ada data billing yang ditemukan.</div>').show();
                            $('#downloadBillingButton').hide();
                        }
                    },
                    error: function() {
                        $('#loadingIcon').hide();
                        Swal.fire('Oops...', 'Terjadi kesalahan saat menghubungi server. Silakan coba lagi.', 'error');
                    }
                });
            });

            // Event toggle metrik chart
            $(document).on('click', '.metric-btn', function() {
                const metric = $(this).data('metric');
                currentMetric = metric;

                $('.metric-btn').removeClass('btn-primary btn-warning active')
                                .addClass(function() {
                                    return $(this).data('metric') === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
                                });
                if (metric === 'jumlah')   { $(this).removeClass('btn-outline-primary').addClass('btn-primary active'); }
                if (metric === 'tarif_rs') { $(this).removeClass('btn-outline-warning').addClass('btn-warning active'); }

                if (currentList.length > 0) {
                    buildDailyChart(currentList, metric);
                }
            });

            // PERUBAHAN: Event listener untuk tombol download BILLING
            $('#downloadBillingButton').on('click', function() {
                const tanggalAwal = $('#tanggal_awal').val();
                const tanggalAkhir = $('#tanggal_akhir').val();
                const kdJenisPasien = $('#kd_jenis_pasien').val(); // <-- PENTING: kirim juga jenis pasien

                if (!kdJenisPasien) {
                    Swal.fire('Info', 'Silakan pilih Jenis Pasien terlebih dahulu.', 'info');
                    return;
                }
                // Arahkan ke fungsi controller baru
                window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_umumanak1") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_JENIS_PASIEN=${kdJenisPasien}`;
            });

            // PERUBAHAN: Event listener BARU untuk tombol download DOKTER
            $('#downloadDokterButton').on('click', function() {
                const tanggalAwal = $('#tanggal_awal').val();
                const tanggalAkhir = $('#tanggal_akhir').val();
                const kdJenisPasien = $('#kd_jenis_pasien').val(); // <-- PENTING: kirim juga jenis pasien

                if (!kdJenisPasien) {
                    Swal.fire('Info', 'Silakan pilih Jenis Pasien terlebih dahulu.', 'info');
                    return;
                }
                // Arahkan ke fungsi controller baru
                window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_umumanak2") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}&KD_JENIS_PASIEN=${kdJenisPasien}`;
            });
        });
    </script>

</body>
</html>

