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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Layanan Pasien - RS Ananda</title>

    <script src="https://cdn.tailwindcss.com"></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 src="https://unpkg.com/@phosphor-icons/web"></script>

    <style>
        /* Custom Scrollbar */
        .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: #1e293b; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #475569; border-radius: 2px; }
        
        body { 
            background-color: #0f172a; 
            color: white; 
            overflow-y: auto; 
            overflow-x: hidden;
        }

        @media (min-height: 700px) and (min-width: 1024px) { body { overflow: hidden; } }
        @media (max-height: 800px) { body { font-size: 11px; } }
    </style>
</head>

<body class="h-screen flex flex-col font-sans text-sm">

    <header class="relative flex h-12 items-center justify-center bg-emerald-900 px-4 shadow-lg border-b border-emerald-700 z-10 flex-shrink-0 sticky top-0">
        <div class="flex items-center gap-3">
            <img src="<?= base_url('assets_/assets/img/logo-mini.png') ?>" alt="Logo RS" class="h-10 w-auto object-contain bg-white rounded-full p-0.5 shadow-md">
            <div class="text-center">
                <h1 class="text-lg font-bold tracking-wide uppercase leading-tight">Dashboard Layanan Pasien</h1>
                <p class="text-[10px] text-emerald-200 tracking-wider leading-none">RUMAH SAKIT UMUM ANANDA PURWOKERTO</p>
            </div>
        </div>
        <div class="absolute right-4 top-1/2 -translate-y-1/2 text-right hidden sm:block">
            <div id="clock-time" class="text-lg font-bold font-mono text-emerald-100 leading-none">--:--:--</div>
            <div id="clock-date" class="text-[10px] text-emerald-300 uppercase leading-none">...</div>
        </div>
    </header>

    <main class="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-2 p-2 h-full overflow-y-auto custom-scrollbar">

        <section class="col-span-1 lg:col-span-4 flex flex-col gap-2 h-auto lg:h-full lg:min-h-[400px]">
            <div class="flex items-center gap-2 text-emerald-400 flex-shrink-0 h-6">
                <i class="ph-bold ph-users text-lg"></i>
                <h2 class="text-base font-bold uppercase tracking-wider">Rawat Jalan</h2>
            </div>

            <div class="grid grid-cols-3 gap-2 flex-shrink-0">
                <div class="bg-slate-800 p-2 rounded border-l-4 border-blue-500 shadow-sm">
                    <span class="text-[10px] text-slate-400 uppercase block">Total Daftar</span>
                    <span id="rajal-daftar" class="text-xl font-bold text-white leading-none">-</span>
                </div>
                <div class="bg-slate-800 p-2 rounded border-l-4 border-emerald-500 shadow-sm">
                    <span class="text-[10px] text-slate-400 uppercase block">Terlayani</span>
                    <span id="rajal-layan" class="text-xl font-bold text-emerald-400 leading-none">-</span>
                </div>
                <div class="bg-slate-800 p-2 rounded border-l-4 border-red-500 shadow-sm">
                    <span class="text-[10px] text-slate-400 uppercase block">Batal</span>
                    <span id="rajal-batal" class="text-xl font-bold text-red-400 leading-none">-</span>
                </div>
            </div>

            <div class="bg-slate-800 rounded-lg border border-slate-700 overflow-hidden shadow-inner flex-shrink-0 overflow-x-auto">
                <div class="bg-slate-700/50 px-3 py-1.5 border-b border-slate-600 flex justify-between items-center">
                    <span class="font-semibold text-[11px] text-slate-200 uppercase tracking-wide">Pendaftaran Online & MJKN</span>
                    <i class="ph-fill ph-globe text-slate-400"></i>
                </div>
                <div class="p-0 min-w-[300px]">
                    <table class="w-full text-xs text-left">
                        <thead class="text-[10px] text-slate-400 uppercase bg-slate-900/50">
                            <tr>
                                <th class="px-3 py-1 font-semibold">Jenis</th>
                                <th class="px-2 py-1 text-center">Total</th>
                                <th class="px-2 py-1 text-center">Dilayani</th>
                                <th class="px-2 py-1 text-center">Batal</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700/50">
                            <?php 
                                $data_online = ['total' => 0, 'layan' => 0, 'batal' => 0];
                                $data_mjkn   = ['total' => 0, 'layan' => 0, 'batal' => 0];
                                
                                if(isset($rekap_daftar_online) && is_array($rekap_daftar_online)) {
                                    foreach($rekap_daftar_online as $row) {
                                        $nama = isset($row->nm_pendaftaran) ? $row->nm_pendaftaran : (isset($row->status) ? $row->status : '');
                                        $total = isset($row->total) ? (int)$row->total : 0;
                                        $layan = isset($row->dilayani) ? (int)$row->dilayani : 0;
                                        $batal = isset($row->batal) ? (int)$row->batal : 0;

                                        if (stripos($nama, 'MJKN') !== false || stripos($nama, 'MOBILE') !== false) {
                                            $data_mjkn['total'] += $total;
                                            $data_mjkn['layan'] += $layan;
                                            $data_mjkn['batal'] += $batal;
                                        } 
                                        elseif (stripos($nama, 'ONLINE') !== false || stripos($nama, 'WEB') !== false) {
                                            $data_online['total'] += $total;
                                            $data_online['layan'] += $layan;
                                            $data_online['batal'] += $batal;
                                        }
                                    }
                                }

                                function renderRow($label, $data, $colorClass) {
                                    $percentLayan = ($data['total'] > 0) ? ($data['layan'] / $data['total']) * 100 : 0;
                                    echo '
                                    <tr class="hover:bg-slate-700/30 transition group">
                                        <td class="px-3 py-2">
                                            <div class="flex items-center gap-2">
                                                <div class="w-1.5 h-1.5 rounded-full '.$colorClass.'"></div>
                                                <span class="font-medium text-slate-200 text-[11px]">'.$label.'</span>
                                            </div>
                                            <div class="mt-1 w-full bg-slate-700 h-1 rounded-full overflow-hidden">
                                                <div class="h-full '.$colorClass.'" style="width: '.$percentLayan.'%"></div>
                                            </div>
                                        </td>
                                        <td class="px-2 py-2 text-center font-bold text-white">'.$data['total'].'</td>
                                        <td class="px-2 py-2 text-center text-emerald-400 font-semibold bg-emerald-500/5 rounded">'.$data['layan'].'</td>
                                        <td class="px-2 py-2 text-center text-red-400 font-semibold bg-red-500/5 rounded">'.$data['batal'].'</td>
                                    </tr>';
                                }

                                renderRow("DAFTAR ONLINE (RS)", $data_online, "bg-emerald-500");
                                renderRow("MOBILE JKN (BPJS)", $data_mjkn, "bg-blue-500");
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="bg-slate-800 rounded-lg border border-slate-700 overflow-hidden shadow-inner flex-shrink-0 overflow-x-auto">
                <div class="bg-slate-700/50 px-3 py-1.5 border-b border-slate-600 flex justify-between items-center">
                    <span class="font-semibold text-[11px] text-slate-200 uppercase tracking-wide">Kunjungan Pasien</span>
                    <i class="ph-fill ph-users-three text-slate-400"></i>
                </div>
                <div class="p-0 min-w-[300px]">
                    <table class="w-full text-xs text-left">
                        <thead class="text-[10px] text-slate-400 uppercase bg-slate-900/50">
                            <tr>
                                <th class="px-3 py-1 font-semibold">Status Pasien</th>
                                <th class="px-2 py-1 text-center">Total</th>
                                <th class="px-2 py-1 text-center">Dilayani</th>
                                <th class="px-2 py-1 text-center">Batal</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700/50">
                            <?php 
                                if(isset($rajal_lama_baru) && is_array($rajal_lama_baru) && count($rajal_lama_baru) > 0) {
                                    foreach($rajal_lama_baru as $row) {
                                        $nama = strtoupper($row->nm_pendaftaran ?? $row->jenis_pasien ?? 'PASIEN');
                                        $total = isset($row->total) ? (int)$row->total : (isset($row->daftar) ? (int)$row->daftar : 0);
                                        $layan = isset($row->dilayani) ? (int)$row->dilayani : (isset($row->terlayani) ? (int)$row->terlayani : 0);
                                        $batal = isset($row->batal) ? (int)$row->batal : 0;
                                        
                                        $colorClass = 'text-slate-300';
                                        if (strpos($nama, 'LAMA') !== false) {
                                            $colorClass = 'text-pink-400';
                                        } elseif (strpos($nama, 'BARU') !== false) {
                                            $colorClass = 'text-purple-400';
                                        }

                                        echo '
                                        <tr class="hover:bg-slate-700/30 transition group">
                                            <td class="px-3 py-1.5 font-medium text-[10px] '.$colorClass.'">'.$nama.'</td>
                                            <td class="px-2 py-1.5 text-center font-bold text-white">'.$total.'</td>
                                            <td class="px-2 py-1.5 text-center text-emerald-400 font-semibold bg-emerald-500/5">'.$layan.'</td>
                                            <td class="px-2 py-1.5 text-center text-red-400 font-semibold bg-red-500/5">'.$batal.'</td>
                                        </tr>';
                                    }
                                } else {
                                    echo '<tr><td colspan="4" class="px-3 py-2 text-center text-[10px] text-slate-500">Tidak ada data</td></tr>';
                                }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="flex-1 bg-slate-800 rounded-lg border border-slate-700 overflow-hidden flex flex-col shadow-inner min-h-[250px] lg:min-h-0">
                <div class="bg-slate-700/50 px-3 py-1.5 border-b border-slate-600 flex justify-between items-center flex-shrink-0">
                    <span class="font-semibold text-xs text-slate-200">Monitoring Poliklinik</span>
                    <span class="text-[10px] bg-slate-600 px-1.5 py-0.5 rounded text-slate-300 animate-pulse">Realtime</span>
                </div>
                <div class="overflow-y-auto flex-1 custom-scrollbar relative">
                    <table class="w-full text-xs text-left">
                        <thead class="text-[10px] text-slate-400 uppercase bg-slate-900 sticky top-0 z-10 shadow-md">
                            <tr>
                                <th class="px-3 py-2 font-semibold bg-slate-900">Nama Klinik</th>
                                <th class="px-1 py-2 text-center bg-slate-900">Daftar</th>
                                <th class="px-1 py-2 text-center bg-slate-900">Layan</th>
                                <th class="px-1 py-2 text-center bg-slate-900">Batal</th>
                            </tr>
                        </thead>
                        <tbody id="tabel-rajal" class="divide-y divide-slate-700/50">
                            <tr><td colspan="4" class="text-center py-10 text-slate-500 italic">Memuat data...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <section class="col-span-1 lg:col-span-5 flex flex-col gap-2 h-auto lg:h-full lg:min-h-[400px]">
            <div class="flex items-center gap-2 text-emerald-400 flex-shrink-0 h-6">
                <i class="ph-bold ph-bed text-lg"></i>
                <h2 class="text-base font-bold uppercase tracking-wider">Rawat Inap</h2>
            </div>

            <div class="min-h-[120px] lg:min-h-0 lg:h-[18%] bg-slate-800 rounded-lg p-2 border border-slate-700 shadow-sm flex items-center gap-2">
                <div class="w-1/2 h-full flex flex-col justify-center">
                    <h3 class="text-[10px] text-slate-400 font-semibold uppercase mb-1 border-b border-slate-700 pb-0.5">Pasien Inap</h3>
                    <p class="text-[9px] text-slate-500 leading-tight">Status Kunjungan</p>
                </div>
                <div class="flex flex-col gap-1.5 mt-1.5 w-1/4">
                    <div class="flex items-center gap-1.5">
                        <span class="w-2 h-2 rounded-full bg-pink-500 shadow-[0_0_5px_rgba(236,72,153,0.5)]"></span>
                        <span class="text-[9px] text-slate-300 leading-none">Lama</span>
                    </div>
                    <div class="flex items-center gap-1.5">
                        <span class="w-2 h-2 rounded-full bg-purple-500 shadow-[0_0_5px_rgba(168,85,247,0.5)]"></span>
                        <span class="text-[9px] text-slate-300 leading-none">Baru</span>
                    </div>
                </div>
                <div class="w-1/2 h-full relative flex justify-center items-center">
                    <canvas id="chartInapLamaBaru"></canvas>
                </div>
            </div>

            <?php $total_ranap = isset($ranap_sum[0]->jumlah) ? $ranap_sum[0]->jumlah : 0; ?>
            <div class="flex-1 bg-slate-800 rounded-lg p-3 border border-slate-700 shadow-sm relative flex flex-col min-h-[250px] lg:min-h-0">
                <div class="flex justify-between mb-1">
                    <h3 class="text-[10px] text-slate-400 font-semibold uppercase">Okupansi per Kelas</h3>
                    <div class="text-right leading-none">
                        <span class="text-[20px] text-slate-400">Total: </span>
                        <span class="text-[20px] font-bold text-emerald-400"><?= $total_ranap ?></span>
                    </div>
                </div>
                <div class="flex-1 relative w-full h-full">
                    <canvas id="chartRanapKelas"></canvas>
                </div>
            </div>

            <div class="min-h-[400px] lg:min-h-0 lg:h-[45%] bg-slate-800 rounded-lg p-2 border border-slate-700 shadow-sm flex flex-col">
                <h3 class="text-[10px] text-slate-400 font-semibold uppercase mb-1 border-b border-slate-700 pb-0.5">Proporsi Penjamin</h3>
                <div class="flex-1 flex flex-col lg:flex-row w-full h-full gap-4 lg:gap-2">
                    
                    <div class="w-full lg:w-1/2 relative flex flex-col min-h-[180px] lg:min-h-0">
                        <span class="text-[9px] text-slate-400 font-medium absolute top-0 left-0 z-10">Rawat Inap</span>
                        <div class="flex-1 relative w-full h-full pt-4 pb-1">
                            <canvas id="chartRanapPenjamin"></canvas>
                        </div>
                    </div>
                    
                    <div class="w-full h-px lg:w-px lg:h-auto bg-slate-700 my-2 lg:my-0 lg:mx-2"></div>
                    
                    <div class="w-full lg:w-1/2 relative flex flex-col min-h-[180px] lg:min-h-0">
                        <span class="text-[9px] text-slate-400 font-medium absolute top-0 left-0 z-10">Rawat Jalan</span>
                        <div class="flex-1 relative w-full h-full pt-4 pb-1">
                            <canvas id="chartRajalPenjamin"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="col-span-1 lg:col-span-3 flex flex-col gap-2 h-auto lg:h-full lg:min-h-[400px]">

            <?php $total_igd = isset($igd_sum[0]->total_igd) ? $igd_sum[0]->total_igd : 0; ?>
            <div class="flex-1 bg-slate-800 rounded-lg border border-slate-700 p-3 shadow-sm flex flex-col min-h-[250px] lg:min-h-0">
                <div class="flex items-center justify-between mb-1 text-amber-400">
                    <div class="flex items-center gap-1.5">
                        <i class="ph-bold ph-siren text-lg"></i>
                        <h2 class="text-base font-bold uppercase">IGD</h2>
                    </div>
                    <span class="bg-amber-500/20 text-amber-300 px-1.5 py-0.5 rounded text-[20px] font-bold">Total: <?= $total_igd ?></span>
                </div>
                <div class="flex-1 relative w-full h-full">
                    <canvas id="chartIGD"></canvas>
                </div>
            </div>

            <div class="min-h-[120px] lg:min-h-0 lg:h-[20%] bg-slate-800 rounded-lg p-2 border border-slate-700 shadow-sm flex items-center gap-2">
                <div class="w-1/2 h-full flex flex-col justify-center">
                    <h3 class="text-[10px] text-slate-400 font-semibold uppercase mb-1 border-b border-slate-700 pb-0.5">Pasien IGD</h3>
                    <p class="text-[9px] text-slate-500 leading-tight">Status Kunjungan</p>
                </div>
                <div class="flex flex-col gap-1.5 mt-1.5 w-1/4">
                    <div class="flex items-center gap-1.5">
                        <span class="w-2 h-2 rounded-full bg-pink-500 shadow-[0_0_5px_rgba(236,72,153,0.5)]"></span>
                        <span class="text-[9px] text-slate-300 leading-none">Lama</span>
                    </div>
                    <div class="flex items-center gap-1.5">
                        <span class="w-2 h-2 rounded-full bg-purple-500 shadow-[0_0_5px_rgba(168,85,247,0.5)]"></span>
                        <span class="text-[9px] text-slate-300 leading-none">Baru</span>
                    </div>
                </div>
                <div class="w-1/2 h-full relative flex justify-center items-center">
                    <canvas id="chartIGDLamaBaru"></canvas>
                </div>
            </div>

            <?php $total_ikbs = isset($ikbs_total[0]->qty) ? $ikbs_total[0]->qty : 0; ?>
            <div class="min-h-[80px] lg:min-h-0 lg:h-[18%] bg-slate-800 rounded-lg border border-slate-700 p-3 shadow-sm flex items-center justify-between relative overflow-hidden group">
                <div class="absolute right-0 top-0 h-full w-1 bg-cyan-500 transition-all group-hover:w-2"></div>
                <div>
                    <div class="flex items-center gap-1.5 text-cyan-400 mb-0.5">
                        <i class="ph-bold ph-knife text-lg"></i>
                        <h2 class="font-bold uppercase text-sm">IKBS / Bedah</h2>
                    </div>
                    <p class="text-[10px] text-slate-400">Pasien Operasi</p>
                </div>
                <div class="text-3xl font-bold text-white transition-transform group-hover:scale-110 group-hover:text-cyan-300 mr-2">
                    <?= $total_ikbs ?>
                </div>
            </div>

            <?php $total_icu = isset($icu_total[0]->count) ? $icu_total[0]->count : 0; ?>
            <div class="min-h-[80px] lg:min-h-0 lg:h-[18%] bg-slate-800 rounded-lg border border-slate-700 p-3 shadow-sm flex items-center justify-between relative overflow-hidden group">
                <div class="absolute right-0 top-0 h-full w-1 bg-rose-500 transition-all group-hover:w-2"></div>
                <div>
                    <div class="flex items-center gap-1.5 text-rose-400 mb-0.5">
                        <i class="ph-bold ph-heartbeat text-lg"></i>
                        <h2 class="font-bold uppercase text-sm">ICU</h2>
                    </div>
                    <p class="text-[10px] text-slate-400">Pasien Intensif</p>
                </div>
                <div class="text-3xl font-bold text-white transition-transform group-hover:scale-110 group-hover:text-rose-300 mr-2">
                    <?= $total_icu ?>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-slate-900 text-center py-0.5 text-[9px] text-slate-600 flex-shrink-0 border-t border-slate-800">
        IT RSU ANANDA Purwokerto © <script>document.write(new Date().getFullYear())</script>
    </footer>

    <script>
        // FUNGSI WARNA PENJAMIN OTOMATIS
        function getPenjaminColor(name, index) {
            const n = String(name).toUpperCase();
            if (n.includes('BPJS')) return '#22C55E'; // HIJAU TERANG
            if (n.includes('UMUM')) return '#3B82F6'; // BIRU TERANG
            if (n.includes('ASURANSI')) return '#F59E0B'; // ORANYE 
            if (n.includes('INHEALTH')) return '#8B5CF6'; // UNGU
            if (n.includes('RAHARJA')) return '#EF4444'; // MERAH
            
            const fallbackColors = ['#0EA5E9', '#14B8A6', '#F43F5E', '#A855F7', '#D946EF', '#06B6D4'];
            return fallbackColors[index % fallbackColors.length];
        }

        // 1. KONFIGURASI CHART
        Chart.register(ChartDataLabels);
        Chart.defaults.font.size = 9;
        Chart.defaults.color = '#94a3b8';
        Chart.defaults.borderColor = '#334155';
        
        // PERBAIKAN: Seting DataLabels
        Chart.defaults.set('plugins.datalabels', {
            color: 'white',
            font: { weight: 'bold', size: 10 },
            clamp: true, // Menjaga label tetap berada di dalam area canvas
            display: function(context) { 
                const value = context.dataset.data[context.dataIndex];
                return value > 0; // Tampilkan SELALU jika angka lebih dari 0
            }
        });

        // 2. JAM DIGITAL
        function updateClock() {
            const now = new Date();
            const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
            document.getElementById('clock-date').textContent = now.toLocaleDateString('id-ID', options);
            document.getElementById('clock-time').textContent = now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        }
        setInterval(updateClock, 1000);
        updateClock();

        // 3. FETCH RAJAL DATA (LIVE)
        async function fetchRawatJalan() {
            try {
                const urlRekap = "<?= base_url('dashboardlayanan/rawatjalanrekap') ?>";
                const urlData = "<?= base_url('dashboardlayanan/rawatjalan') ?>";
                const [resRekap, resData] = await Promise.all([fetch(urlRekap), fetch(urlData)]);
                
                if(!resRekap.ok || !resData.ok) throw new Error("Gagal mengambil data API");

                const jsonRekap = await resRekap.json();
                const jsonData = await resData.json();

                if (jsonRekap && jsonRekap.length > 0) {
                    document.getElementById('rajal-daftar').innerText = jsonRekap[0].daftar || 0;
                    document.getElementById('rajal-layan').innerText = jsonRekap[0].terlayani || 0;
                    document.getElementById('rajal-batal').innerText = jsonRekap[0].batal || 0;
                }

                const tbody = document.getElementById('tabel-rajal');
                tbody.innerHTML = '';
                
                if (jsonData && jsonData.length > 0) {
                    jsonData.forEach(row => {
                        const batalVal = parseInt(row.batal);
                        const batalText = batalVal > 0 ? `<span class="text-red-400 font-bold">${batalVal}</span>` : '<span class="text-slate-600">-</span>';
                        
                        const tr = `
                            <tr class="hover:bg-slate-700/50 transition-colors border-b border-slate-700/50 last:border-0 group">
                                <td class="px-2 py-1 font-medium text-slate-200 border-l-2 border-transparent group-hover:border-emerald-500 truncate max-w-[150px]">
                                    ${row.nm_ruang}
                                </td>
                                <td class="px-1 py-1 text-center font-bold text-blue-300 bg-blue-900/10 rounded-sm">
                                    ${row.daftar}
                                </td>
                                <td class="px-1 py-1 text-center font-bold text-emerald-300 bg-emerald-900/10 rounded-sm">
                                    ${row.terlayani}
                                </td>
                                <td class="px-1 py-1 text-center">
                                    ${batalText}
                                </td>
                            </tr>
                        `;
                        tbody.insertAdjacentHTML('beforeend', tr);
                    });
                } else {
                    tbody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-slate-500">Tidak ada antrean</td></tr>';
                }
            } catch (error) { console.error("Dashboard Error:", error); }
        }
        fetchRawatJalan();

        // 4. CHART RENDERING
        const dataRanapKelas = <?= isset($ranap_data) ? json_encode($ranap_data) : '[]' ?>;
        const dataRanapPenjamin = <?= isset($penjamin_data) ? json_encode($penjamin_data) : '[]' ?>;
        const dataRajalPenjamin = <?= isset($penjamin_poli) ? json_encode($penjamin_poli) : '[]' ?>;
        const dataIGD = <?= isset($igd_data) ? json_encode($igd_data) : '[]' ?>;
        const dataIGDLamaBaru = <?= isset($igd_datapasienlamabaru) ? json_encode($igd_datapasienlamabaru) : '[]' ?>;
        const dataInapLamaBaru = <?= isset($inap_lama_baru) ? json_encode($inap_lama_baru) : '[]' ?>;

        if (dataRanapKelas.length) {
            new Chart(document.getElementById('chartRanapKelas'), {
                type: 'bar',
                data: {
                    labels: dataRanapKelas.map(d => d.nm_kelas),
                    datasets: [{ label: 'Jml', data: dataRanapKelas.map(d => d.qty), backgroundColor: '#10B981', borderRadius: 3, barThickness: 'flex', maxBarThickness: 15 }]
                },
                options: { 
                    indexAxis: 'y', 
                    responsive: true, 
                    maintainAspectRatio: false, 
                    // PERBAIKAN: Beri ruang kosong di kanan agar label angka tidak mentok
                    layout: {
                        padding: { right: 25 }
                    },
                    plugins: { 
                        legend: { display: false }, 
                        // PERBAIKAN: Set spesifik untuk chart bar horizontal
                        datalabels: { 
                            anchor: 'end',    // Posisi patokan di ujung batang
                            align: 'right',   // Teks diletakkan di sebelah kanan patokan
                            offset: 4,        // Jarak dari ujung batang
                            color: '#e2e8f0', // Warna abu-abu terang agar kontras dengan background gelap
                            display: function(context) { return context.dataset.data[context.dataIndex] > 0; }
                        } 
                    }, 
                    scales: { 
                        x: { grid: { color: '#334155' }, ticks: { font: { size: 8 } }, grace: '10%' }, // grace: 10% menambah panjang sumbu X sedikit ekstra
                        y: { grid: { display: false }, ticks: { font: { size: 9 }, color: '#e2e8f0' } } 
                    } 
                }
            });
        }

        if (dataRanapPenjamin.length) {
            new Chart(document.getElementById('chartRanapPenjamin'), {
                type: 'doughnut',
                data: {
                    labels: dataRanapPenjamin.map(d => d.penjamin),
                    datasets: [{ 
                        data: dataRanapPenjamin.map(d => d.qty), 
                        backgroundColor: dataRanapPenjamin.map((d, i) => getPenjaminColor(d.penjamin, i)), 
                        borderWidth: 0, cutout: '45%'
                    }]
                },
                options: { 
                    responsive: true, maintainAspectRatio: false, layout: { padding: 0 }, 
                    plugins: { 
                        legend: { position: 'bottom', labels: { font: { size: 7 }, boxWidth: 6, padding: 5, color: '#cbd5e1' } } 
                    } 
                }
            });
        }

        if (dataRajalPenjamin.length) {
            new Chart(document.getElementById('chartRajalPenjamin'), {
                type: 'doughnut',
                data: {
                    labels: dataRajalPenjamin.map(d => d.nm_pembayaran),
                    datasets: [{ 
                        data: dataRajalPenjamin.map(d => d.qty), 
                        backgroundColor: dataRajalPenjamin.map((d, i) => getPenjaminColor(d.nm_pembayaran, i)), 
                        borderWidth: 0, cutout: '45%' 
                    }]
                },
                options: { 
                    responsive: true, maintainAspectRatio: false, layout: { padding: 0 }, 
                    plugins: { 
                        legend: { position: 'bottom', labels: { font: { size: 7 }, boxWidth: 6, padding: 5, color: '#cbd5e1' } } 
                    } 
                }
            });
        }

        if (dataIGD.length) {
            new Chart(document.getElementById('chartIGD'), {
                type: 'bar',
                data: {
                    labels: dataIGD.map(d => d.nm_jenis_pasien),
                    datasets: [{ label: 'Layan', data: dataIGD.map(d => d.dilayani), backgroundColor: '#F59E0B', maxBarThickness: 40 }, { label: 'Batal', data: dataIGD.map(d => d.batal), backgroundColor: '#EF4444', maxBarThickness: 40 }]
                },
                options: { responsive: true, maintainAspectRatio: false, scales: { x: { grid: { display: false }, ticks: { font: { size: 8 }, color: '#cbd5e1' } }, y: { grid: { color: '#334155' }, ticks: { font: { size: 9 } }, grace: '15%' } }, plugins: { legend: { position: 'bottom', labels: { font: { size: 9 }, boxWidth: 8, padding: 5, color: '#cbd5e1' } }, datalabels: { anchor: 'end', align: 'top', offset: -2, color: 'white' } } }
            });
        }

        if (dataIGDLamaBaru.length) {
            new Chart(document.getElementById('chartIGDLamaBaru'), {
                type: 'pie',
                data: {
                    labels: dataIGDLamaBaru.map(d => d.nm_pendaftaran || d.nm_pasien || 'Pasien'),
                    datasets: [{ data: dataIGDLamaBaru.map(d => d.total || d.jumlah || 0), backgroundColor: dataIGDLamaBaru.map(d => String(d.nm_pendaftaran).toLowerCase().includes('lama') ? '#ec4899' : '#a855f7'), borderWidth: 0 }]
                },
                options: { responsive: true, maintainAspectRatio: false, layout: { padding: 0 }, plugins: { legend: { display: false }, datalabels: { color: 'white', font: { size: 10, weight: 'bold' } } } }
            });
        }

        if (dataInapLamaBaru.length) {
            new Chart(document.getElementById('chartInapLamaBaru'), {
                type: 'pie',
                data: {
                    labels: dataInapLamaBaru.map(d => d.nm_pendaftaran || 'Pasien'),
                    datasets: [{ 
                        data: dataInapLamaBaru.map(d => d.qty_dilayani || 0), 
                        backgroundColor: dataInapLamaBaru.map(d => String(d.nm_pendaftaran).toLowerCase().includes('lama') ? '#ec4899' : '#a855f7'), 
                        borderWidth: 0 
                    }]
                },
                options: { responsive: true, maintainAspectRatio: false, layout: { padding: 0 }, plugins: { legend: { display: false }, datalabels: { color: 'white', font: { size: 10, weight: 'bold' } } } }
            });
        }

        setTimeout(() => window.location.reload(), 60000);
    </script>
</body>
</html>