<style>
    /* ========================================================
       1. CSS CORE RESPONSIVE (ANTI HALAMAN JEBOL)
       ======================================================== */
    body, html {
        overflow-x: hidden !important;
        width: 100%;
        max-width: 100vw;
    }

    @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;
        background-color: #f4f6f9;
    }

    /* Memaksa Tabel agar menyesuaikan layar */
    table, table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse !important;
    }

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

    /* ========================================================
       2. STYLING KARTU & DASHBOARD
       ======================================================== */
    .card { 
        border: none; 
        box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); 
        border-radius: 0.5rem; 
        margin-bottom: 20px; 
        width: 100%;
        max-width: 100%;
    }
    .card-header { 
        background-color: #fff; 
        border-bottom: 1px solid rgba(0,0,0,0.05); 
        font-weight: 600; 
        color: #333; 
        border-top-left-radius: 0.5rem !important; 
        border-top-right-radius: 0.5rem !important; 
    }
    
    .section-title { 
        color: #2c3e50; 
        font-weight: bold; 
        margin-top: 30px; 
        margin-bottom: 15px; 
        border-left: 5px solid #198754; 
        padding-left: 10px; 
        font-size: 1.5rem; /* Responsif ukuran font */
    }

    .kpi-card { 
        color: white; 
        border-radius: 0.5rem; 
        padding: 20px; 
        display: flex; 
        align-items: center; 
        justify-content: space-between; 
        box-shadow: 0 4px 6px rgba(0,0,0,0.1); 
        transition: transform 0.2s; 
    }
    .kpi-card:hover { transform: translateY(-5px); }
    .kpi-card .inner-text h3 { font-size: 2rem; margin: 0; font-weight: bold; }
    .kpi-card .inner-text p { margin: 0; font-size: 1rem; opacity: 0.9; }
    .kpi-card i { font-size: 2.5rem; opacity: 0.3; }
    
    .bg-primary-grad { background: linear-gradient(45deg, #0d6efd, #4facfe); }
    .bg-success-grad { background: linear-gradient(45deg, #198754, #20c997); }
    .bg-danger-grad { background: linear-gradient(45deg, #dc3545, #f8d7da); color: #842029 !important;}
    .bg-danger-grad.text-white { color: #fff !important; }
    
    .chart-container { 
        position: relative; 
        margin: auto; 
        height: 350px; 
        width: 100%; 
        max-width: 100%;
    }

    /* TABS */
    .nav-tabs .nav-link { color: #495057; font-weight: 500; white-space: nowrap; }
    .nav-tabs .nav-link.active { color: #0d6efd; font-weight: bold; border-bottom: 3px solid #0d6efd; }
    
    /* Buat Tabs bisa discroll horizontal di HP */
    .nav-tabs {
        flex-wrap: nowrap;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        padding-bottom: 5px;
    }
    .nav-tabs::-webkit-scrollbar { height: 4px; }
    .nav-tabs::-webkit-scrollbar-track { background: #f1f1f1; }
    .nav-tabs::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; }

    /* FORM FILTER RESPONSIVE */
    @media (max-width: 768px) {
        .form-label { margin-top: 10px; }
        .input-group { flex-direction: column; }
        .input-group input { width: 100% !important; border-radius: 0.375rem !important; margin-bottom: 10px;}
        .input-group button { width: 100%; border-radius: 0.375rem !important; }
        div.dataTables_wrapper div.dataTables_filter input { width: 120px !important; }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 overflow-hidden">
            <h1 class="mt-4 fs-3" id="judulPasien">Dashboard SINARAN</h1>
            <ol class="breadcrumb mb-4 shadow-sm bg-white p-2 rounded">
                <li class="breadcrumb-item"><a href="#" class="text-decoration-none text-muted">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Info Dashboard SINARAN</li>
            </ol>

            <?php 
                // ======================================================================
                // LOGIKA PEMBATASAN HAK AKSES TAB BERDASARKAN NAMA USER
                // ======================================================================
                
                // Pastikan 'nama_user' sesuai dengan penamaan session login di aplikasi Anda
                $nama_user_login = $this->session->userdata('nm_user'); 
                
                // Daftar nama yang diizinkan melihat tab Perbulan dan Pertahun
                $user_diizinkan = [
                    "Deni Kurnia Widodo, S.Kom",
                    "Setya Ariani Kusumawati",
                    "DITO KUSUMO DAMAR P",
                    "dr. Dhian Shinto Hapsari",
                    "ANIEK TRISNAWATI",
                    "dr. Moch. Gita Gandhi Surya Dirgantara, Sp.An-TI"
                ];

                // Cek apakah user saat ini ada di dalam array
                $punya_akses_tab = in_array($nama_user_login, $user_diizinkan);
            ?>

            <ul class="nav nav-tabs mb-4" id="dashboardTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="tab-dashboard" data-bs-toggle="tab" data-bs-target="#content-dashboard" type="button" role="tab">
                        <i class="fas fa-home me-1"></i> Dashboard SINARAN
                    </button>
                </li>

                <?php if($punya_akses_tab): ?>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-perbulan" data-bs-toggle="tab" data-bs-target="#content-perbulan" type="button" role="tab">
                        <i class="fas fa-calendar-alt me-1"></i> Data Perbulan
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-pertahun" data-bs-toggle="tab" data-bs-target="#content-pertahun" type="button" role="tab">
                        <i class="fas fa-calendar-check me-1"></i> Data Pertahun
                    </button>
                </li>
                <?php endif; ?>
            </ul>
            
            <div class="tab-content" id="dashboardTabsContent">
                
                <div class="tab-pane fade show active" id="content-dashboard" role="tabpanel">
                    
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body bg-light rounded">
                            <form id="form-dashboard" action="<?= base_url('keuangan/dashboardlayanan') ?>" method="POST" name="form-input-data">
                                <div class="row align-items-end g-2">
                                    <div class="col-12 col-md-3">
                                        <label for="tanggal_awal" class="form-label text-muted small fw-bold">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tglawal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-5">
                                        <label for="tanggal_akhir" class="form-label text-muted small fw-bold">Tanggal Akhir</label>
                                        <div class="input-group">
                                            <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tglakhir ?>" required />
                                            <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Filter</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <h3 class="section-title">Registrasi Rawat Jalan</h3>
                    <?php 
                        $totDaftarRJ = 0; $totLayaniRJ = 0; $totBatalRJ = 0;
                        if (isset($pasienrajaltotal->response)) {
                            foreach ($pasienrajaltotal->response as $a) {
                                $totDaftarRJ += $a->daftar;
                                $totLayaniRJ += $a->terlayani;
                                $totBatalRJ += $a->batal;
                            }
                        }
                    ?>
                    <div class="row mb-3">
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-primary-grad">
                                <div class="inner-text"><p>Total Pendaftar</p><h3><?= $totDaftarRJ ?></h3></div><i class="fas fa-users"></i>
                            </div>
                        </div>
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-success-grad">
                                <div class="inner-text"><p>Telah Dilayani Pendaftaran</p><h3><?= $totLayaniRJ ?></h3></div><i class="fas fa-user-check"></i>
                            </div>
                        </div>
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-danger-grad text-white">
                                <div class="inner-text"><p>Batal</p><h3><?= $totBatalRJ ?></h3></div><i class="fas fa-user-times"></i>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-pie me-1 text-primary"></i> Jenis Pendaftaran</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartJenisDaftar"></canvas></div></div>
                            </div>
                        </div>
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-bar me-1 text-success"></i> Pasien Lama & Baru</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartLamaBaru"></canvas></div></div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-white"><i class="fas fa-table me-1 text-info"></i> Detail Pasien Per Poliklinik</div>
                        <div class="card-body p-2 p-md-3">
                            <div class="table-responsive w-100">
                                <table id="tableRajal" class="table table-striped table-bordered text-nowrap w-100">
                                    <thead class="table-light text-center">
                                        <tr><th>Nama Poliklinik</th><th>Total Pasien</th><th>Terlayani Dokter</th><th>Batal</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php if (isset($pasienrajal->response)) {
                                            foreach ($pasienrajal->response as $a) { ?>
                                                <tr>
                                                    <td><?= $a->nm_ruang ?></td>
                                                    <td class="text-center"><?= $a->daftar ?></td>
                                                    <td class="text-center text-success fw-bold"><?= $a->terlayani ?></td>
                                                    <td class="text-center text-danger"><?= $a->batal ?></td>
                                                </tr>
                                        <?php } } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <h3 class="section-title mt-5">Rawat Inap</h3>
                    <?php 
                        // 1. Menghitung Total Rawat Inap
                        $totRanap = 0;
                        if (isset($pasienranaptotal) && isset($pasienranaptotal->response)) {
                            foreach ($pasienranaptotal->response as $a) { 
                                $totRanap += $a->jumlah; 
                            }
                        }

                        // 2. Mengambil Data Lama & Baru (DIPERBAIKI)
                        $qtyInapBaru = 0;
                        $qtyInapLama = 0;
                        
                        // Pengecekan Aman: Pastikan variabel dikirim dari Controller dan memiliki data
                        if (isset($pasieninaplamabaru) && !empty($pasieninaplamabaru)) {
                            
                            // Normalnya response API dibungkus dalam 'response', kita cek dulu
                            if (isset($pasieninaplamabaru->response) && is_array($pasieninaplamabaru->response)) {
                                $dataList = $pasieninaplamabaru->response;
                            } 
                            // Jika API mengembalikan array langsung
                            elseif (is_array($pasieninaplamabaru)) {
                                $dataList = $pasieninaplamabaru;
                            } 
                            else {
                                $dataList = [];
                            }

                            // Looping data
                            foreach ($dataList as $b) {
                                // Antisipasi spasi berlebih atau perbedaan huruf besar/kecil
                                $jenis_pasien = strtolower(trim($b->nm_pendaftaran));
                                
                                // Deteksi pasien baru
                                if ($jenis_pasien === "pasien baru") {
                                    $qtyInapBaru = isset($b->qty_dilayani) ? $b->qty_dilayani : 0;
                                } 
                                // Deteksi pasien lama
                                elseif ($jenis_pasien === "pasien lama") {
                                    $qtyInapLama = isset($b->qty_dilayani) ? $b->qty_dilayani : 0;
                                }
                            }
                        }
                    ?>

                    <div class="row mb-3">
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-primary-grad">
                                <div class="inner-text">
                                    <p>Total Pasien Rawat Inap</p>
                                    <h3><?= $totRanap ?></h3>
                                </div>
                                <i class="fas fa-procedures"></i>
                            </div>
                        </div>

                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-success-grad">
                                <div class="inner-text">
                                    <p>Pasien Baru</p>
                                    <h3><?= $qtyInapBaru ?></h3>
                                </div>
                                <i class="fas fa-user-plus"></i>
                            </div>
                        </div>

                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-info" style="background: linear-gradient(45deg, #0dcaf0, #0dcaf0);">
                                <div class="inner-text">
                                    <p>Pasien Lama</p>
                                    <h3><?= $qtyInapLama ?></h3>
                                </div>
                                <i class="fas fa-user-clock"></i>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-pie me-1 text-primary"></i> Pasien Berdasarkan Kelas</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartKelasRanap"></canvas></div></div>
                            </div>
                        </div>
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-doughnut me-1 text-warning"></i> Rekap Penjamin Inap</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartPenjaminRanap"></canvas></div></div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-white"><i class="fas fa-bed me-1 text-info"></i> Ketersediaan Tempat Tidur (Bed)</div>
                        <div class="card-body p-2 p-md-3">
                            <div class="table-responsive w-100">
                                <table id="tableBed" class="table table-striped table-bordered text-nowrap w-100">
                                    <thead class="table-light text-center">
                                        <tr><th>Nama Ruang</th><th>Kelas</th><th>Jml Bed</th><th>Tersedia</th><th>Terisi</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php if (isset($ketersediantt->response)) {
                                            foreach ($ketersediantt->response as $a) { ?>
                                                <tr class="text-center">
                                                    <td class="text-start"><?= $a->ruang ?></td>
                                                    <td><span class="badge bg-secondary"><?= $a->nm_kelas ?></span></td>
                                                    <td><?= $a->jumlah_bed ?></td>
                                                    <td class="text-success fw-bold"><?= $a->tersedia ?></td>
                                                    <td class="text-danger"><?= $a->terisi ?></td>
                                                </tr>
                                        <?php } } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <h3 class="section-title mt-5">Instalasi Gawat Darurat (IGD)</h3>
                    <?php 
                        $totLayaniIGD = 0; $totBatalIGD = 0; $totSemuaIGD = 0;
                        if (isset($pasienigdtotal->response)) {
                            foreach ($pasienigdtotal->response as $a) {
                                $totLayaniIGD += $a->dilayani;
                                $totBatalIGD += $a->batal;
                                $totSemuaIGD += $a->total_igd;
                            }
                        }
                    ?>
                    <div class="row mb-3">
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-primary-grad">
                                <div class="inner-text"><p>Total Pasien IGD</p><h3><?= $totSemuaIGD ?></h3></div><i class="fas fa-ambulance"></i>
                            </div>
                        </div>
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-success-grad">
                                <div class="inner-text"><p>Telah Dilayani</p><h3><?= $totLayaniIGD ?></h3></div><i class="fas fa-stethoscope"></i>
                            </div>
                        </div>
                        <div class="col-12 col-md-4 mb-3">
                            <div class="kpi-card bg-danger-grad text-white">
                                <div class="inner-text"><p>Batal</p><h3><?= $totBatalIGD ?></h3></div><i class="fas fa-times-circle"></i>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-bar me-1 text-primary"></i> Data Jenis Pasien IGD</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartJenisIGD"></canvas></div></div>
                            </div>
                        </div>
                        <div class="col-12 col-lg-6">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-white"><i class="fas fa-chart-pie me-1 text-warning"></i> Pasien Lama & Baru (IGD)</div>
                                <div class="card-body"><div class="chart-container"><canvas id="chartLamaBaruIGD"></canvas></div></div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if($punya_akses_tab): ?>
                <div class="tab-pane fade" id="content-perbulan" role="tabpanel">
                    <div class="card mb-4 mt-2 border-0 shadow-sm">
                        <div class="card-header bg-white fw-bold"><i class="fas fa-filter me-1 text-secondary"></i> Filter Data Perbulan</div>
                        <div class="card-body bg-light rounded-bottom">
                            <form id="form-filter-perbulan">
                                <div class="row align-items-end g-2">
                                    <div class="col-12 col-md-3">
                                        <label for="bulan_awal" class="form-label text-muted small fw-bold">Tanggal Awal</label>
                                        <input type="date" id="bulan_awal" name="tanggal_awal" class="form-control" value="<?= date('Y-01-01') ?>" required />
                                    </div>
                                    <div class="col-12 col-md-5">
                                        <label for="bulan_akhir" class="form-label text-muted small fw-bold">Tanggal Akhir</label>
                                        <div class="input-group">
                                            <input type="date" id="bulan_akhir" name="tanggal_akhir" class="form-control" value="<?= date('Y-m-d') ?>" required />
                                            <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Tampilkan</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <div class="card mb-4 shadow-sm border-0 border-top border-primary border-4">
                        <div class="card-header bg-white"><i class="fas fa-chart-bar me-1 text-primary"></i> Data Kunjungan Poliklinik Perbulan (Per-Tanggal Registrasi)</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingPoliBulan" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartDashboardPoliBulan"></canvas>
                            </div>
                        </div>
                    </div>

               
                    <div class="card mb-4 shadow-sm border-0 border-top border-4" style="border-top-width: 4px !important; border-top-color: #fd7e14 !important;">
                        <div class="card-header bg-white"><i class="fas fa-file-invoice me-1 text-warning"></i> Data Kunjungan Poliklinik (Per Tanggal Billing) Non Home Care & Non Jalan to Inap</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingPoliPulang" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-warning" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartPoliPulang"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-4" style="border-top-width: 4px !important; border-top-color: #0d6efd !important;">
                        <div class="card-header bg-white"><i class="fas fa-person-walking-arrow-right me-1 text-primary"></i> Dashboard Data Rawat Jalan Ke Inap</div>
                        <div class="card-body">
                            <div id="loadingRJRI" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%,-50%); z-index:10;">
                                <div class="spinner-border text-primary" role="status" style="width:3rem;height:3rem;"></div>
                            </div>
                            <div class="row justify-content-center">
                                <div class="col-12 col-md-10">
                                    <div style="position:relative; height:500px;">
                                        <canvas id="chartRJRI"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-4" style="border-top-width: 4px !important; border-top-color: #20c997 !important;">
                        <div class="card-header bg-white"><i class="fas fa-house-medical me-1" style="color:#20c997"></i> Dashboard Home Care</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingHomeCare" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border" style="color:#20c997; width: 3rem; height: 3rem;" role="status"></div>
                                </div>
                                <canvas id="chartHomeCare"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-danger border-4">
                        <div class="card-header bg-white"><i class="fas fa-ambulance me-1 text-danger"></i> Data Kunjungan IGD (Perbulan)</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingIGDBulan" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-danger" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartDashboardIGDBulan"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-success border-4">
                        <div class="card-header bg-white"><i class="fas fa-procedures me-1 text-success"></i> Data Kunjungan Rawat Inap (Perbulan)</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingInapBulan" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartDashboardInapBulan"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-info border-4">
                        <div class="card-header bg-white"><i class="fas fa-heartbeat me-1 text-info"></i> Data Kunjungan Operasi (Perbulan)</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingOperasiBulan" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-info" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartDashboardOperasiBulan"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="content-pertahun" role="tabpanel">
                    <div class="card mb-4 mt-2 border-0 shadow-sm">
                        <div class="card-header bg-white fw-bold"><i class="fas fa-filter me-1 text-secondary"></i> Filter Data Pertahun</div>
                        <div class="card-body bg-light rounded-bottom">
                            <form id="form-filter-pertahun">
                                <div class="row align-items-end g-2">
                                    <div class="col-12 col-md-3">
                                        <label for="tahun_awal" class="form-label text-muted small fw-bold">Tanggal Awal</label>
                                        <input type="date" id="tahun_awal" name="tanggal_awal" class="form-control" value="2024-01-01" required />
                                    </div>
                                    <div class="col-12 col-md-5">
                                        <label for="tahun_akhir" class="form-label text-muted small fw-bold">Tanggal Akhir</label>
                                        <div class="input-group">
                                            <input type="date" id="tahun_akhir" name="tanggal_akhir" class="form-control" value="<?= date('Y-m-d') ?>" required />
                                            <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Tampilkan</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="card mb-4 shadow-sm border-0 border-top border-primary border-4">
                        <div class="card-header bg-white"><i class="fas fa-chart-bar me-1 text-primary"></i> Data Kunjungan Poliklinik (Pertahun)</div>
                        <div class="card-body">
                            <div class="chart-container" style="height: 350px; position: relative;">
                                <div id="loadingPoliTahun" style="display:none; position:absolute; top:40%; left:50%; transform:translate(-50%, -50%); z-index:10;">
                                    <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;"></div>
                                </div>
                                <canvas id="chartDashboardPoliTahun"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

            </div>
        </div>
    </main>
</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.0.0"></script>

<script>
    Chart.register(ChartDataLabels);
    const colorColors = ['#0d6efd', '#198754', '#ffc107', '#dc3545', '#0dcaf0', '#6f42c1', '#d63384'];
    const datalabelOption = {
        color: '#fff', font: { weight: 'bold', size: 14 },
        formatter: (value, ctx) => { return (value === 0 || value === null) ? '' : value; }
    };

    let chartInstances = {};

    // 1. Render Chart Umum (Poli, IGD, Inap)
    function renderChartUmum(canvasId, labelPendaftar, labels, dataTotal, dataDilayani, dataBatal, colorTheme) {
        const ctx = document.getElementById(canvasId);
        if(!ctx) return;
        if(chartInstances[canvasId]) chartInstances[canvasId].destroy();

        chartInstances[canvasId] = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    { label: labelPendaftar, data: dataTotal, backgroundColor: colorTheme.total, borderRadius: 4 },
                    { label: 'Dilayani', data: dataDilayani, backgroundColor: colorTheme.dilayani, borderRadius: 4 },
                    { label: 'Batal', data: dataBatal, backgroundColor: colorTheme.batal, borderRadius: 4 }
                ]
            },
            options: { 
                responsive: true, maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'top' },
                    datalabels: { color: '#444', anchor: 'end', align: 'top', offset: 10, font: { weight: 'bold', size: 11 }, formatter: (value) => { return value > 0 ? value : ''; } }
                },
                scales: { x: { grid: { display: false } }, y: { beginAtZero: true, grace: '5%' } }
            }
        });
    }

    // 2. Render Chart Operasi
    function renderChartOperasi(canvasId, labels, dataTotal) {
        const ctx = document.getElementById(canvasId);
        if(!ctx) return;
        if(chartInstances[canvasId]) chartInstances[canvasId].destroy();

        chartInstances[canvasId] = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    { label: 'Total Operasi', data: dataTotal, backgroundColor: '#0dcaf0', borderRadius: 4 } 
                ]
            },
            options: { 
                responsive: true, maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'top' },
                    datalabels: { color: '#444', anchor: 'end', align: 'top', offset: 10, font: { weight: 'bold', size: 11 }, formatter: (value) => { return value > 0 ? value : ''; } }
                },
                scales: { x: { grid: { display: false } }, y: { beginAtZero: true, grace: '5%' } }
            }
        });
    }

    // Fungsi konversi "2026-01" → "Januari 2026"
    function formatBulan(bulanStr) {
        const namaBulan = [
            'Januari', 'Februari', 'Maret', 'April',
            'Mei', 'Juni', 'Juli', 'Agustus',
            'September', 'Oktober', 'November', 'Desember'
        ];
        let parts = bulanStr.split('-');
        let tahun = parts[0];
        let bulan = parseInt(parts[1]) - 1; // index 0
        return `${namaBulan[bulan]} ${tahun}`;
    }
    
    // 3. RENDER RAJAL TO INAP
    function renderChartRajalToInap(canvasId, labels, datasets) {
        const ctx = document.getElementById(canvasId);
        if(!ctx) return;
        if(chartInstances[canvasId]) chartInstances[canvasId].destroy();

        chartInstances[canvasId] = new Chart(ctx, {
            type: 'bar',
            data: { labels: labels, datasets: datasets },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                layout: { padding: { right: 90, left: 0, top: 10, bottom: 10 } },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            font: { size: 11, weight: '600' },
                            color: '#333',
                            padding: 15,
                            usePointStyle: true,
                            pointStyleWidth: 10,
                            // Tambahkan qty total per klinik di legend
                            generateLabels: function(chart) {
                                const ds = chart.data.datasets;
                                return ds.map((dataset, i) => {
                                    let totalKlinik = dataset.data.reduce((a, b) => a + b, 0);
                                    return {
                                        text: `${dataset.label}  (${totalKlinik.toLocaleString('id-ID')})`,
                                        fillStyle: dataset.backgroundColor,
                                        strokeStyle: '#fff',
                                        pointStyle: 'circle',
                                        index: i,
                                        hidden: !chart.isDatasetVisible(i)
                                    };
                                });
                            }
                        }
                    },
                    datalabels: {
                        color: '#fff',
                        font: { weight: 'bold', size: 10 },
                        formatter: (value) => value > 0 ? value.toLocaleString('id-ID') : ''
                    },
                    tooltip: {
                        mode: 'nearest',    // ← hanya dataset yang di-hover
                        intersect: true,    // ← harus tepat di atas bar
                        callbacks: {
                            label: (item) => {
                                return item.raw > 0
                                    ? ` ${item.dataset.label}: ${item.raw.toLocaleString('id-ID')} Pasien`
                                    : null;
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        stacked: true,
                        beginAtZero: true,
                        position: 'bottom',
                        grid: { color: 'rgba(0,0,0,0.05)' },
                        ticks: { font: { size: 11 }, color: '#666' }
                    },
                    y: {
                        stacked: true,
                        grid: { display: false },
                        ticks: {
                            font: { size: 11, weight: '600' },
                            color: '#333',
                            mirror: false
                        }
                    }
                }
            },
            plugins: [{
                id: 'totalLabel',
                afterDatasetsDraw(chart) {
                    const { ctx, data, scales: { x, y } } = chart;
                    ctx.save();
                    ctx.font = 'bold 11px sans-serif';
                    ctx.fillStyle = '#333';
                    ctx.textAlign = 'left';
                    ctx.textBaseline = 'middle';

                    data.labels.forEach((label, i) => {
                        let total = data.datasets.reduce((sum, ds) => sum + (ds.data[i] || 0), 0);
                        if(total > 0) {
                            let xPos = x.getPixelForValue(total) + 6;
                            let yPos = y.getPixelForValue(i);
                            ctx.fillText(`${total.toLocaleString('id-ID')} Pasien`, xPos, yPos);
                        }
                    });
                    ctx.restore();
                }
            }]
        });
    }

    function parseNumericValue(val) {
        if (val === null || val === undefined || val === '') return 0;
        let num = parseFloat(String(val).replace(/[^0-9.-]/g, ''));
        return isNaN(num) ? 0 : num;
    }

    $(document).ready(function() {
        
        // Inisialisasi DataTables dengan perbaikan Responsif
        // $('#tableRajal').DataTable({ 
        //     pageLength: 5, 
        //     lengthMenu: [ [5, 10, 20, 50, -1], [5, 10, 20, 50, "Semua"] ],
        //     responsive: false, scrollX: false, autoWidth: false, // Perbaikan UI
        //     dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        // });
        // Inisialisasi DataTables untuk Rawat Jalan
        $('#tableRajal').DataTable({ 
            pageLength: -1, // Default load "Semua" data
            lengthMenu: [ [5, 10, 20, 50, -1], [5, 10, 20, 50, "Semua"] ], 
            scrollY: "400px", // Membatasi tinggi tabel (muncul scroll vertikal)
            scrollCollapse: true, // Tinggi tabel akan menyusut jika data kurang dari 400px
            responsive: false, 
            scrollX: false, 
            autoWidth: false,
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        });
        $('#tableBed').DataTable({ 
            pageLength: 5, 
            lengthMenu: [ [5, 10, 20, 50, -1], [5, 10, 20, 50, "Semua"] ],
            responsive: false, scrollX: false, autoWidth: false, // Perbaikan UI
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        });

        // =========================================================
        // AUTO LOAD TAB 
        // =========================================================
        let isPoliBulanLoaded = false;
        let isPoliTahunLoaded = false;

        $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
            let targetId = $(e.target).attr('id');
            
            if (targetId === 'tab-perbulan' && !isPoliBulanLoaded) {
                $('#form-filter-perbulan').trigger('submit');
                isPoliBulanLoaded = true; 
            }
            if (targetId === 'tab-pertahun' && !isPoliTahunLoaded) {
                $('#form-filter-pertahun').trigger('submit');
                isPoliTahunLoaded = true; 
            }
        });

        // =========================================================
        // AJAX: TAB DATA PERBULAN
        // =========================================================
        $('#form-filter-perbulan').on('submit', function(e) {
            e.preventDefault(); 
            
            let btn = $(this).find('button[type="submit"]');
            let originalText = btn.html();
            let tglAwal = $('#bulan_awal').val();
            let tglAkhir = $('#bulan_akhir').val();

            btn.html('<i class="fas fa-spinner fa-spin me-1"></i> Memuat...').prop('disabled', true);
            $('#loadingPoliBulan, #loadingIGDBulan, #loadingInapBulan, #loadingOperasiBulan, #loadingPoliPulang, #loadingHomeCare, #loadingRJRI').show();
            $('#chartDashboardPoliBulan, #chartDashboardIGDBulan, #chartDashboardInapBulan, #chartDashboardOperasiBulan, #chartPoliPulang, #chartHomeCare, #chartRJRI_inap').css('opacity', '0.3');

            $.ajax({
                url: '<?= base_url("keuangan/dashboardpoli") ?>', 
                type: 'POST',
                data: { tanggal_awal: tglAwal, tanggal_akhir: tglAkhir },
                dataType: 'json',
                success: function(response) {
                    if(response.error) {
                        alert(response.error);
                        return;
                    }

                    // 1. DATA POLI
                    let lblPoli = [], dTotPoli = [], dDilPoli = [], dBatPoli = [];
                    if(response.poli && response.poli.response) {
                        response.poli.response.forEach(function(item) {
                            lblPoli.push(item.bulan); dTotPoli.push(item.total); dDilPoli.push(item.dilayani); dBatPoli.push(item.batal);
                        });
                    }
                    renderChartUmum('chartDashboardPoliBulan', 'Total Pendaftar', lblPoli, dTotPoli, dDilPoli, dBatPoli, {total: '#6610f2', dilayani: '#0dcaf0', batal: '#e40606'});

                    // 2. DATA IGD
                    let lblIGD = [], dTotIGD = [], dDilIGD = [], dBatIGD = [];
                    if(response.igd && response.igd.response) {
                        response.igd.response.forEach(function(item) {
                            lblIGD.push(item.bulan); dTotIGD.push(item.total); dDilIGD.push(item.dilayani); dBatIGD.push(item.batal);
                        });
                    }
                    renderChartUmum('chartDashboardIGDBulan', 'Total Pasien IGD', lblIGD, dTotIGD, dDilIGD, dBatIGD, {total: '#ffc107', dilayani: '#20c997', batal: '#e40606'});

                    // 3. DATA INAP
                    let lblInap = [], dTotInap = [], dDilInap = [], dBatInap = [];
                    if(response.inap && response.inap.response) {
                        response.inap.response.forEach(function(item) {
                            lblInap.push(item.bulan); dTotInap.push(item.total); dDilInap.push(item.dilayani); dBatInap.push(item.batal);
                        });
                    }
                    renderChartUmum('chartDashboardInapBulan', 'Total Pasien Inap', lblInap, dTotInap, dDilInap, dBatInap, {total: '#6f42c1', dilayani: '#198754', batal: '#e40606'});

                    // 4. DATA OPERASI
                    let lblOpe = [], dTotOpe = [];
                    let dataOperasi = (response.operasi && response.operasi.response) ? response.operasi.response : response.operasi;

                    if(dataOperasi && Array.isArray(dataOperasi)) {
                        dataOperasi.forEach(function(item) {
                            lblOpe.push(item.bulan);
                            dTotOpe.push(item.total_operasi || 0); 
                        });
                    }
                    renderChartOperasi('chartDashboardOperasiBulan', lblOpe, dTotOpe);

                    //5 DATA POLI PULANG
                    let lblPulang = [], dTotPulang = [], dDilPulang = [], dBatPulang = [];
                    let dataPoliPulang = (response.polipulang && response.polipulang.response) ? response.polipulang.response : response.polipulang;

                    if(dataPoliPulang && Array.isArray(dataPoliPulang)) {
                        dataPoliPulang.forEach(function(item) {
                            lblPulang.push(item.bulan); 
                            // Pastikan key-nya membaca: total, dilayani, dan batal sesuai respon API
                            dTotPulang.push(item.total || 0); 
                            dDilPulang.push(item.dilayani || 0); 
                            dBatPulang.push(item.batal || 0);
                        });
                    }
                    
                    renderChartUmum('chartPoliPulang', 'Total Pasien', lblPulang, dTotPulang, dDilPulang, dBatPulang, {total: '#d63384', dilayani: '#20c997', batal: '#dc3545'});

                    //6 DATA HOME CARE
                    let lblHomecare = [], dTotHomecare = [], dDilHomecare = [], dBatHomecare = [];
                    
                    let dataHomecare = (response.homecare && response.homecare.response) ? response.homecare.response : response.homecare;

                    if(dataHomecare && Array.isArray(dataHomecare)) {
                        dataHomecare.forEach(function(item) {
                            lblHomecare.push(item.bulan); 
                            // Membaca key: total, dilayani, dan batal sesuai respon API Home Care
                            dTotHomecare.push(item.total || 0); 
                            dDilHomecare.push(item.dilayani || 0); 
                            dBatHomecare.push(item.batal || 0);
                        });
                    }
                    
                    // Render menggunakan fungsi renderChartUmum bawaan Anda dengan variasi warna gradasi baru
                    renderChartUmum('chartHomeCare', 'Total Pasien Homecare', lblHomecare, dTotHomecare, dDilHomecare, dBatHomecare, {total: '#f77f00', dilayani: '#198754', batal: '#6f42c1'});

            // 7 RAJAL TO INAP
            let dataConversion = (response.rajaltoinap && response.rajaltoinap.response) 
                ? response.rajaltoinap.response 
                : response.rajaltoinap;

            // Struktur: { "KLINIK ANAK": { "2026-01": 11, "2026-02": 5, ... }, ... }
            let klinikMap = {};
            let bulanSet  = new Set();

            if(dataConversion && Array.isArray(dataConversion)) {
                dataConversion.forEach(function(item) {
                    let lanjutan = (item.rawat_lanjutan || '').trim();
                    if(lanjutan !== 'Rawat Inap') return; // hanya Rawat Inap

                    let klinik = item.asal_pasien || 'Lain-lain';
                    let bulan  = item.bulan       || '';
                    let qty    = parseNumericValue(item.qty);

                    if(!klinikMap[klinik]) klinikMap[klinik] = {};
                    klinikMap[klinik][bulan] = (klinikMap[klinik][bulan] || 0) + qty;
                    bulanSet.add(bulan);
                });
            }

            // Sort bulan ascending — simpan key asli dulu untuk mapping
            let sortedBulanKey = Array.from(bulanSet).sort(); // ["2026-01", "2026-02", ...]
            let labelsBulan    = sortedBulanKey.map(b => formatBulan(b)); // ["Januari 2026", ...]

            let namaKlinik = Object.keys(klinikMap);

            let warnaKlinik = [
                '#dc3545', '#0dcaf0', '#20c997', '#ffc107',
                '#0d6efd', '#6f42c1', '#fd7e14', '#d63384',
                '#198754', '#adb5bd', '#4facfe', '#f77f00'
            ];

            // Gunakan sortedBulanKey (key asli) saat mapping data, bukan labelsBulan
            let datasetsRJRI = namaKlinik.map(function(klinik, i) {
                return {
                    label: klinik,
                    data: sortedBulanKey.map(b => klinikMap[klinik][b] || 0), // ← key asli
                    backgroundColor: warnaKlinik[i % warnaKlinik.length],
                    borderWidth: 1,
                    borderColor: '#fff',
                    borderRadius: 4,
                    borderSkipped: false
                };
            });

            renderChartRajalToInap('chartRJRI', labelsBulan, datasetsRJRI);
                                                                        

                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText); 
                    alert("Gagal mengambil data dari server.");
                },
                complete: function() {
                    btn.html(originalText).prop('disabled', false);
                    $('#loadingPoliBulan, #loadingIGDBulan, #loadingInapBulan, #loadingOperasiBulan, #loadingPoliPulang, #loadingHomeCare, #loadingRJRI').hide();
                    $('#chartDashboardPoliBulan, #chartDashboardIGDBulan, #chartDashboardInapBulan, #chartDashboardOperasiBulan, #chartPoliPulang, #chartHomeCare, #chartRJRI').css('opacity', '1');
                }
            });
        });

        // =========================================================
        // AJAX: TAB DATA PERTAHUN
        // =========================================================
        $('#form-filter-pertahun').on('submit', function(e) {
            e.preventDefault(); 
            
            let btn = $(this).find('button[type="submit"]');
            let originalText = btn.html();
            let tglAwal = $('#tahun_awal').val();
            let tglAkhir = $('#tahun_akhir').val();

            btn.html('<i class="fas fa-spinner fa-spin me-1"></i> Memuat...').prop('disabled', true);
            $('#loadingPoliTahun').show();
            $('#chartDashboardPoliTahun').css('opacity', '0.3');

            $.ajax({
                url: '<?= base_url("keuangan/dashboardpoli") ?>', 
                type: 'POST',
                data: { tanggal_awal: tglAwal, tanggal_akhir: tglAkhir },
                dataType: 'json',
                success: function(response) {
                    if(response.error) {
                        alert(response.error);
                        return;
                    }

                    // Extract Data POLI TAHUN
                    let lblPoliThn = [], dTotPoliThn = [], dDilPoliThn = [], dBatPoliThn = [];
                    let dataPoliTahun = (response.politahun && response.politahun.response) ? response.politahun.response : response.politahun;

                    if(dataPoliTahun && Array.isArray(dataPoliTahun)) {
                        dataPoliTahun.forEach(function(item) {
                            let label = item.bulan ? item.bulan : item.tahun; 
                            lblPoliThn.push(label);
                            dTotPoliThn.push(item.total || 0);
                            dDilPoliThn.push(item.dilayani || 0);
                            dBatPoliThn.push(item.batal || 0);
                        });
                    }
                    renderChartUmum('chartDashboardPoliTahun', 'Total Pendaftar', lblPoliThn, dTotPoliThn, dDilPoliThn, dBatPoliThn, {total: '#0d6efd', dilayani: '#198754', batal: '#dc3545'});
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                    alert("Gagal mengambil data Pertahun.");
                },
                complete: function() {
                    btn.html(originalText).prop('disabled', false);
                    $('#loadingPoliTahun').hide();
                    $('#chartDashboardPoliTahun').css('opacity', '1');
                }
            });
        });
    });

    // ==============================================================
    // CHART LAINNYA (RAWAT JALAN / IGD - DARI CONTROLLER UTAMA)
    // ==============================================================

    const labelJenisDaftar = [];
    const dataJenisDilayani = [];
    const dataJenisBatal = [];
    <?php if(isset($daftaronlinerekap->response)): foreach($daftaronlinerekap->response as $a): ?>
        labelJenisDaftar.push(<?= json_encode($a->status) ?>);
        dataJenisDilayani.push(<?= $a->dilayani ?>);
        dataJenisBatal.push(<?= $a->batal ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartJenisDaftar')){
        new Chart(document.getElementById('chartJenisDaftar'), {
            type: 'bar',
            data: {
                labels: labelJenisDaftar,
                datasets: [
                    { label: 'Dilayani', data: dataJenisDilayani, backgroundColor: '#198754', borderRadius: 4, borderWidth: 1, borderColor: '#fff' },
                    { label: 'Batal', data: dataJenisBatal, backgroundColor: '#dc3545', borderRadius: 4, borderWidth: 1, borderColor: '#fff' }
                ]
            },
            options: { 
                responsive: true, maintainAspectRatio: false,
                scales: { x: { stacked: true, grid: { display: false } }, y: { stacked: true, beginAtZero: true } },
                plugins: { legend: { position: 'top' }, datalabels: { color: '#fff', font: { weight: 'bold' }, formatter: (value) => { return (value === 0 || value === null || value === '0') ? '' : value; } }, tooltip: { mode: 'index', intersect: false } }
            }
        });
    }

    const labelLamaBaru = [];
    const dataDilayaniLB = [];
    const dataBatalLB = [];
    <?php if(isset($pasienpolilamabaru->response)): foreach($pasienpolilamabaru->response as $a): ?>
        labelLamaBaru.push(<?= json_encode($a->nm_pendaftaran) ?>);
        dataDilayaniLB.push(<?= $a->dilayani ?>);
        dataBatalLB.push(<?= $a->batal ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartLamaBaru')){
        new Chart(document.getElementById('chartLamaBaru'), {
            type: 'bar',
            data: {
                labels: labelLamaBaru,
                datasets: [
                    { label: 'Dilayani', data: dataDilayaniLB, backgroundColor: '#198754' },
                    { label: 'Batal', data: dataBatalLB, backgroundColor: '#dc3545' }
                ]
            },
            options: { 
                responsive: true, maintainAspectRatio: false, layout: { padding: { top: 25 } },
                plugins: { legend: { position: 'top' }, datalabels: { color: '#444', anchor: 'end', align: 'top', font: { weight: 'bold', size: 12 }, formatter: (value) => { return value > 0 ? value : ''; } } }
            }
        });
    }

    const labelKelas = [];
    const dataKelas = [];
    <?php if(isset($pasienranap->response)): foreach($pasienranap->response as $a): ?>
        labelKelas.push(<?= json_encode($a->nm_kelas) ?>);
        dataKelas.push(<?= $a->qty ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartKelasRanap')){
        new Chart(document.getElementById('chartKelasRanap'), {
            type: 'doughnut',
            data: { labels: labelKelas, datasets: [{ data: dataKelas, backgroundColor: colorColors }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { datalabels: datalabelOption } }
        });
    }

    const labelPenjamin = [];
    const dataPenjamin = [];
    <?php if(isset($inappenjamin->response)): foreach($inappenjamin->response as $a): ?>
        labelPenjamin.push(<?= json_encode($a->penjamin) ?>);
        dataPenjamin.push(<?= $a->qty ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartPenjaminRanap')){
        new Chart(document.getElementById('chartPenjaminRanap'), {
            type: 'pie',
            data: { labels: labelPenjamin, datasets: [{ data: dataPenjamin, backgroundColor: colorColors }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { datalabels: datalabelOption } }
        });
    }

    const labelJenisIGD = [];
    const dataIGDDilayani = [];
    <?php if(isset($pasienigd->response)): foreach($pasienigd->response as $a): ?>
        labelJenisIGD.push(<?= json_encode($a->nm_jenis_pasien) ?>);
        dataIGDDilayani.push(<?= $a->total ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartJenisIGD')){
        new Chart(document.getElementById('chartJenisIGD'), {
            type: 'bar',
            data: { labels: labelJenisIGD, datasets: [{ label: 'Total Pasien', data: dataIGDDilayani, backgroundColor: '#0d6efd' }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { datalabels: { color: '#fff', anchor: 'end', align: 'start', font: { weight: 'bold' } } } }
        });
    }

    const labelLamaBaruIGD = [];
    const dataLamaBaruIGD = [];
    <?php if(isset($pasienigdlamabaru->response)): foreach($pasienigdlamabaru->response as $a): ?>
        labelLamaBaruIGD.push(<?= json_encode($a->nm_pendaftaran) ?>);
        dataLamaBaruIGD.push(<?= $a->total ?>);
    <?php endforeach; endif; ?>

    if(document.getElementById('chartLamaBaruIGD')){
        new Chart(document.getElementById('chartLamaBaruIGD'), {
            type: 'doughnut',
            data: { labels: labelLamaBaruIGD, datasets: [{ data: dataLamaBaruIGD, backgroundColor: ['#ffc107', '#0dcaf0'] }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { datalabels: datalabelOption } }
        });
    }
</script>
</body>
</html>