

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Demografi Pasien</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    
    <style>
        .nav-pills .nav-link { border-radius: 50px; padding: 10px 20px; font-weight: 500; margin-right: 10px; border: 1px solid #e3e6f0; color: #5a5c69; background-color: #fff; }
        .nav-pills .nav-link.active { background-color: #007bff; color: #fff; border-color: #007bff; }
        .card { border: none; border-radius: 10px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); margin-bottom: 20px;}
        .chart-area { position: relative; height: 350px; width: 100%; }
        .table-responsive { overflow-x: hidden !important; }
        .table { width: 100% !important; table-layout: fixed; }
        .table td, .table th { font-size: 0.85rem; word-wrap: break-word; vertical-align: middle; }
    </style>
</head>

<body>
<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4">Dashboard Demografi Pasien</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Data</li>
            </ol>

            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <form action="<?= base_url('demografiusia/tampildata') ?>" method="POST" id="formFilterDemografi">
                        <input type="hidden" name="active_tab" id="active_tab" value="<?= $this->input->post('active_tab') ?? '#tab-usia' ?>">
                        
                        <div class="row align-items-end">
                            <div class="col-md-3">
                                <label class="small font-weight-bold">TANGGAL AWAL</label>
                                <input type="date" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="small font-weight-bold">TANGGAL AKHIR</label>
                                <input type="date" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required>
                            </div>
                            <div class="col-md-6">
                                <button type="submit" class="btn btn-primary"><i class="fas fa-sync-alt"></i> Update Data</button>
                                
                                <button type="button" id="downloadButton_usia" class="btn btn-success ml-2 tab-download-btn">
                                    <i class="fas fa-file-excel"></i> Download Excel Usia
                                </button>
                                <button type="button" id="downloadButton_gender" class="btn btn-info ml-2 tab-download-btn" style="display: none;">
                                    <i class="fas fa-file-excel"></i> Download Excel Gender
                                </button>
                                <button type="button" id="downloadButton_alamat" class="btn btn-warning ml-2 tab-download-btn" style="display: none;">
                                    <i class="fas fa-file-excel"></i> Download Excel Alamat
                                </button>
                                <button type="button" id="downloadButton_pekerjaan" class="btn btn-secondary ml-2 tab-download-btn" style="display: none;">
                                    <i class="fas fa-file-excel"></i> Download Excel Pekerjaan 
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-toggle="pill" href="#tab-usia"><i class="fas fa-user-clock mr-2"></i>Demografi Usia</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#tab-gender"><i class="fas fa-venus-mars mr-2"></i>Demografi Jenis Kelamin</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#tab-alamat"><i class="fas fa-map-marked-alt mr-2"></i>Demografi Alamat</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#tab-pekerjaan"><i class="fas fa-briefcase mr-2"></i>Pekerjaan</a>
                </li>
            </ul>

            <div class="tab-content">
                <div class="tab-pane fade show active" id="tab-usia">
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Grafik Distribusi Usia</h6>
                                    <button onclick="donwloadChartImgUsia('chartUsia', 'Grafik_Usia.jpeg')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartUsia"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Ringkasan Usia</div>
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered mb-0">
                                            <thead class="bg-light text-center"><tr><th>Kategori</th><th>Jumlah</th></tr></thead>
                                            <tbody id="bodyUsia">
                                                <tr><td>&lt; 1 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usiakurang1thn->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                                <tr><td>1 - 3 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usia1sampai3thn->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                                <tr><td>3 - 5 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usia3sampai5thn->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                                <tr><td>5 - 18 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usia5sampai18thn->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                                <tr><td>18 - 58 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usia18sampai58thn->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                                <tr><td>&gt; 58 Tahun</td><td class="text-center font-weight-bold"><?= array_sum(array_column($usia58thnlebih->response ?? [], 'qty')) ?: 0 ?></td></tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-gender">
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Proporsi Jenis Kelamin</h6>
                                    <button onclick="donwloadChartImgGender('chartGender', 'Grafik_Gender.jpeg')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartGender"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Ringkasan Gender</div>
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered mb-0">
                                            <thead class="bg-light text-center"><tr><th>Jenis Kelamin</th><th>Jumlah</th></tr></thead>
                                            <tbody id="bodyGender">
                                                <tr><td colspan="2" class="text-center">Memuat data...</td></tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-alamat">
                    
                    <div class="row align-items-center mb-4">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Demografi Kabupaten (Top 10)</h6>
                                    <button onclick="downloadChartImage('chartKabupaten', 'Grafik_Kabupaten.png')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartKabupaten"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-2 font-weight-bold text-primary">Ringkasan Kabupaten (All Data)</div>
                                <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light"><tr><th>Kabupaten</th><th>Jumlah</th></tr></thead>
                                        <tbody id="bodyKab">
                                            <?php if(isset($demokabupatenkota->response)) { 
                                                foreach($demokabupatenkota->response as $k) { ?>
                                                <tr><td><?= $k->nm_kabupaten ?? $k->nm_kota ?? '-' ?></td><td class="text-center font-weight-bold"><?= $k->qty ?></td></tr>
                                            <?php }} else { echo "<tr><td colspan='2' class='text-center'>Data Kosong</td></tr>"; } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row align-items-center mb-4">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Demografi Kecamatan (Top 10)</h6>
                                    <button onclick="downloadChartImage('chartKecamatan', 'Grafik_Kecamatan.png')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartKecamatan"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-2 font-weight-bold text-primary">Ringkasan Kecamatan (All Data)</div>
                                <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light"><tr><th>Kecamatan</th><th>Jumlah</th></tr></thead>
                                        <tbody id="bodyKec">
                                            <?php if(isset($demokecamatan->response)) { 
                                                foreach($demokecamatan->response as $k) { ?>
                                                <tr><td><?= $k->nm_kecamatan ?? $k->nama_kecamatan ?? '-' ?></td><td class="text-center font-weight-bold"><?= $k->qty ?></td></tr>
                                            <?php }} ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row align-items-center mb-4">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Demografi Desa (Top 10)</h6>
                                    <button onclick="downloadChartImage('chartDesa', 'Grafik_Desa.png')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartDesa"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-2 font-weight-bold text-primary">Ringkasan Desa (All Data)</div>
                                <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light"><tr><th>Desa</th><th>Jumlah</th></tr></thead>
                                        <tbody id="bodyDesa">
                                            <?php if(isset($demodesa->response)) { 
                                                foreach($demodesa->response as $d) { ?>
                                                <tr><td><?= $d->nm_desa ?? $d->nama_desa ?? '-' ?></td><td class="text-center font-weight-bold"><?= $d->qty ?></td></tr>
                                            <?php }} ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="tab-pekerjaan">
                    <div class="row">
                         <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Grafik Distribusi Usia</h6>
                                    <button onclick="donwloadChartImgPekerjaan('chartPekerjaan', 'Grafik_Pekerjaan.jpeg')" class="btn btn-sm btn-success shadow-sm">
                                        <i class="fas fa-download fa-sm text-white-50"></i> Unduh Gambar
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div style="width: 100%; height: 300px;"><canvas id="chartPekerjaan"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Ringkasan Pekerjaan</div>
                                <div class="card-body p-0 scroll-table">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light text-center">
                                            <tr><th>Pekerjaan</th><th>Jumlah</th></tr>
                                        </thead>
                                        <tbody id="bodyPekerjaan">
                                            <tr><td colspan="2" class="text-center">Memuat data...</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.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>

    // --- 1. REGISTER PLUGIN (PENTING: Agar plugin label aktif) ---
    Chart.register(ChartDataLabels);

    $(document).ready(function() {

      // --- 1. DEFINISI ROUTES ---
        const url_usia = "<?= base_url('demografiusia/tampildata') ?>";
        // Pastikan URL ini sesuai dengan routes di Config Anda
        const url_alamat = "<?= base_url('demografi/tampilalamat') ?>"; 
        const url_pekerjaan_ajax = "<?= base_url('demografiusia/tampilpekerjaan') ?>";

        // --- 2. EVENT LISTENER SUBMIT FORM (PINDAHKAN KE SINI - JANGAN DI DALAM FUNGSI LAIN) ---
        // Ini mencegah event menumpuk (double submit)
        $('#formFilterDemografi').on('submit', function(event) {
            var activeTab = $('#active_tab').val();

            // LOGIKA: Jika di Tab Alamat -> Gunakan AJAX, Jangan Reload
            if (activeTab === '#tab-alamat') {
                event.preventDefault(); // Stop reload halaman
                
                // Tampilkan loading di tombol agar user tahu sedang proses
                var btn = $(this).find('button[type="submit"]');
                var originalText = btn.html();
                btn.html('<i class="fas fa-spinner fa-spin"></i> Loading...').prop('disabled', true);

                // Panggil data baru
                loadAlamatData(function() {
                    // Callback saat selesai: Kembalikan tombol
                    btn.html(originalText).prop('disabled', false);
                });
            } 
            // Jika di Tab Lain -> Biarkan reload normal
            else {
                // Pastikan action form mengarah ke URL default (Usia)
                $(this).attr('action', url_usia);
                return true;
            }
        });

        // --- 3. LOGIKA PINDAH TAB ---
        $('a[data-toggle="pill"]').on('shown.bs.tab', function(e) {
            var target = $(e.target).attr("href"); 
            $('#active_tab').val(target);
            updateButtonsVisibility(target);
            
            // Render ulang chart jika masuk tab alamat (agar animasi main lagi)
            if(target === '#tab-alamat') {
                setTimeout(initChartAlamat, 200);
            }
        });

        // Cek tab terakhir saat reload
        var lastTab = $('#active_tab').val();
        if (lastTab) {
            $('.nav-pills a[href="' + lastTab + '"]').tab('show');
            updateButtonsVisibility(lastTab);
        }

        // Fungsi Atur Tombol Download (Dipisahkan agar rapi)
        function updateButtonsVisibility(tabId) {
            $('.tab-download-btn').hide();
            if (tabId === '#tab-usia') $('#downloadButton_usia').show();
            else if (tabId === '#tab-gender') $('#downloadButton_gender').show();
            else if (tabId === '#tab-alamat') $('#downloadButton_alamat').show();
            else if (tabId === '#tab-pekerjaan') $('#downloadButton_pekerjaan').show();
        }

        



        // --- 4. RENDER CHART USIA & GENDER (Standard) ---
        const ctxUsia = document.getElementById('chartUsia').getContext('2d');
        new Chart(ctxUsia, {
            type: 'bar',
            data: {
                labels: ['< 1 Thn', '1-3 Thn', '3-5 Thn', '5-18 Thn', '18-58 Thn', '> 58 Thn'],
                datasets: [{
                    label: 'Jumlah Pasien',
                    data: [
                        <?= array_sum(array_column($usiakurang1thn->response ?? [], 'qty')) ?: 0 ?>,
                        <?= array_sum(array_column($usia1sampai3thn->response ?? [], 'qty')) ?: 0 ?>,
                        <?= array_sum(array_column($usia3sampai5thn->response ?? [], 'qty')) ?: 0 ?>,
                        <?= array_sum(array_column($usia5sampai18thn->response ?? [], 'qty')) ?: 0 ?>,
                        <?= array_sum(array_column($usia18sampai58thn->response ?? [], 'qty')) ?: 0 ?>,
                        <?= array_sum(array_column($usia58thnlebih->response ?? [], 'qty')) ?: 0 ?>
                    ],
                    backgroundColor: '#4e73df'
                }]
            },

            // TAMBAHKAN BAGIAN PLUGINS INI UNTUK BACKGROUND PUTIH
            plugins: [{
                id: 'custom_canvas_background_color',
                beforeDraw: (chart) => {
                    const ctx = chart.canvas.getContext('2d');
                    ctx.save();
                    ctx.globalCompositeOperation = 'destination-over';
                    ctx.fillStyle = 'white'; // Set warna background jadi PUTIH
                    ctx.fillRect(0, 0, chart.width, chart.height);
                    ctx.restore();
                }
            }],
            options: { maintainAspectRatio: false, scales: { y: { beginAtZero: true } } }
        });

        loadGenderData();
        function loadGenderData() {
            var tAwal = $('input[name="tanggal_awal"]').val();
            var tAkhir = $('input[name="tanggal_akhir"]').val();
            $.ajax({
                url: '<?= base_url("demografijeniskelamin/tampiljeniskelamin") ?>',
                type: 'POST',
                data: { TANGGAL_AWAL: tAwal, TANGGAL_AKHIR: tAkhir },
                dataType: 'json',
                success: function(data) {
                    let labels = [], counts = [], tableHtml = '';
                    if (data.response && data.response.length > 0) {
                        data.response.forEach(item => {
                            labels.push(item.nm_jenis_kelamin);
                            counts.push(item.qty);
                            tableHtml += `<tr><td>${item.nm_jenis_kelamin}</td><td class="text-center font-weight-bold">${item.qty}</td></tr>`;
                        });
                        $('#bodyGender').html(tableHtml);
                        new Chart(document.getElementById('chartGender'), {
                            type: 'doughnut',
                            data: { labels: labels, datasets: [{ data: counts, backgroundColor: ['#4e73df', '#e74a3b'] }] },
                            // TAMBAHKAN BAGIAN PLUGINS INI UNTUK BACKGROUND PUTIH
                        plugins: [{
                            id: 'custom_canvas_background_color',
                            beforeDraw: (chart) => {
                                const ctx = chart.canvas.getContext('2d');
                                ctx.save();
                                ctx.globalCompositeOperation = 'destination-over';
                                ctx.fillStyle = 'white'; // Set warna background jadi PUTIH
                                ctx.fillRect(0, 0, chart.width, chart.height);
                                ctx.restore();
                            }
                        }],
                            options: { maintainAspectRatio: false, cutout: '70%' }
                        });
                    }
                }
            });
        }

        // --- 5. LOGIKA DATA ALAMAT (AJAX & CHART DINAMIS) ---
        
        // Load data saat pertama kali buka halaman
        loadAlamatData();

        function loadAlamatData(callback = null) {
            var tAwal = $('input[name="tanggal_awal"]').val();
            var tAkhir = $('input[name="tanggal_akhir"]').val();

            $.ajax({
                url: url_alamat,
                type: 'POST',
                data: { TANGGAL_AWAL: tAwal, TANGGAL_AKHIR: tAkhir },
                dataType: 'json',
                success: function(response) {
                    updateTableAlamat('bodyKab', response.kabupaten || [], 'nm_kabupaten', 'nm_kota');
                    updateTableAlamat('bodyKec', response.kecamatan || [], 'nm_kecamatan', 'nama_kecamatan');
                    updateTableAlamat('bodyDesa', response.desa || [], 'nm_desa', 'nama_desa');

                    // Render chart dengan delay sedikit agar transisi halus
                    setTimeout(function() {
                        initChartAlamat();
                        if (callback) callback(); // Panggil callback jika ada (untuk stop loading button)
                    }, 300);
                },
                error: function(xhr, status, error) {
                    console.error("Gagal load alamat:", error);
                    if (callback) callback();
                }
            });
        }

        function updateTableAlamat(tbodyId, dataList, key1, key2) {
            let html = '';
            if (dataList && dataList.length > 0) {
                dataList.sort((a, b) => parseInt(b.qty) - parseInt(a.qty));
                dataList.forEach(item => {
                    let nama = item[key1] || item[key2] || '-';
                    let qty = item.qty || 0;
                    html += `<tr><td>${nama}</td><td class="text-center font-weight-bold">${qty}</td></tr>`;
                });
            } else {
                html = '<tr><td colspan="2" class="text-center">Data Kosong</td></tr>';
            }
            $('#' + tbodyId).html(html);
        }

        function initChartAlamat() {
            renderPieAlamat('chartKabupaten', 'bodyKab');
            renderPieAlamat('chartKecamatan', 'bodyKec');
            renderPieAlamat('chartDesa', 'bodyDesa');
        }

        // FUNGSI RENDER PIE CHART YANG DIPERBAIKI (ANIMASI DINAMIS)
        function renderPieAlamat(canvasId, bodyId) {
            var canvasElement = document.getElementById(canvasId);
            if (!canvasElement) return;

            // 1. Ambil Data dari Tabel
            let rawData = [];
            $('#' + bodyId + ' tr').each(function() {
                let label = $(this).find('td:first').text().trim();
                let val = parseInt($(this).find('td:last').text()) || 0;
                if (label && label !== 'Data Kosong' && val > 0) {
                    rawData.push({ label: label, value: val });
                }
            });

            // 2. Sorting & Slice Top 10
            let finalLabels = [], finalValues = [];
            if (rawData.length > 0) {
                rawData.sort((a, b) => b.value - a.value);
                let top10Data = rawData.slice(0, 10);
                finalLabels = top10Data.map(item => item.label);
                finalValues = top10Data.map(item => item.value);
            }

            // 3. HAPUS CHART LAMA (PENTING UNTUK ANIMASI)
            let chartInstance = Chart.getChart(canvasId);
            if (chartInstance) {
                chartInstance.destroy();
            }

            // 4. BUAT CHART BARU (Otomatis akan ada Entry Animation)
            const ctx = canvasElement.getContext('2d');
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: finalLabels,
                    datasets: [{
                        data: finalValues,
                        backgroundColor: [
                            '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', 
                            '#858796', '#5a5c69', '#f8f9fc', '#6f42c1', '#fd7e14'
                        ],
                        borderWidth: 1,
                        hoverOffset: 10
                    }]
                },
                // --- MULAI DARI SINI (GANTI SELURUH BLOK PLUGINS) ---
                plugins: [{
                    id: 'custom_canvas_background_color',
                    beforeDraw: (chart) => {
                        const ctx = chart.canvas.getContext('2d');
                        ctx.save();
                        ctx.globalCompositeOperation = 'destination-over';
                        ctx.fillStyle = 'white';
                        ctx.fillRect(0, 0, chart.width, chart.height);
                        ctx.restore();
                    }
                },
                {
                    // PLUGIN UNTUK TOOLTIP & LEGENDA
                    legend: {
                        display: true,
                        position: 'right',
                        labels: {
                            boxWidth: 12,
                            font: { size: 11 },
                            
                            // FUNGSI CUSTOM GENERATE LABELS (MANUAL MAP)
                            generateLabels: function(chart) {
                                var data = chart.data;
                                if (data.labels.length && data.datasets.length) {
                                    return data.labels.map(function(label, i) {
                                        // Ambil Nilai (Jumlah)
                                        var value = data.datasets[0].data[i];
                                        // Ambil Warna Background
                                        var fill = data.datasets[0].backgroundColor[i];
                                        
                                        // Status apakah item ini sedang di-hide (diklik user)
                                        var meta = chart.getDatasetMeta(0);
                                        var hidden = meta.data[i].hidden;

                                        return {
                                            // FORMAT: "Nama : Jumlah"
                                            text: label + ' : ' + value, 
                                            fillStyle: fill,
                                            strokeStyle: fill,
                                            lineWidth: 0,
                                            hidden: isNaN(value) || hidden,
                                            index: i // Penting agar bisa diklik untuk filter
                                        };
                                    });
                                }
                                return [];
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.label || '';
                                let value = context.parsed;
                                let total = context.chart._metasets[context.datasetIndex].total;
                                let percentage = ((value / total) * 100).toFixed(1) + '%';
                                return label + ': ' + value + ' (' + percentage + ')';
                            }
                        }
                    },
                    datalabels: { display: false }
                }] 
                // --- AKHIR BLOK PLUGINS ---
                ,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    },
                    layout: { padding: 10 }
                }
        });
        }



        // --- 6. DATA PEKERJAAN (AJAX) ---
        loadPekerjaanData();
        function loadPekerjaanData() {
            var tAwal = $('input[name="tanggal_awal"]').val();
            var tAkhir = $('input[name="tanggal_akhir"]').val();
            $.ajax({
                url: '<?= base_url("demografi/tampildatapekerjaan") ?>',
                type: 'POST',
                data: { TANGGAL_AWAL: tAwal, TANGGAL_AKHIR: tAkhir },
                dataType: 'json',
                success: function(data) {
                    let labels = [], counts = [], tableHtml = '';
                    if (data.response && data.response.length > 0) {
                        data.response.sort((a, b) => b.qty - a.qty);
                        data.response.forEach(item => {
                            let nama = item.pekerjaan || item.nm_pekerjaan || '-';
                            labels.push(nama);
                            counts.push(item.qty);
                            tableHtml += `<tr><td>${nama}</td><td class="text-center font-weight-bold">${item.qty}</td></tr>`;
                        });
                        $('#bodyPekerjaan').html(tableHtml);
                        renderChartPekerjaan(labels, counts);
                    } else {
                        $('#bodyPekerjaan').html('<tr><td colspan="2" class="text-center">Data Kosong</td></tr>');
                    }
                }
            });
        }

        function renderChartPekerjaan(labels, data) {
            let chartInstance = Chart.getChart("chartPekerjaan");
            if (chartInstance) chartInstance.destroy();

            const ctx = document.getElementById('chartPekerjaan').getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Jumlah Pasien',
                        data: data,
                        backgroundColor: '#36b9cc',
                        borderColor: '#2c9faf',
                        borderWidth: 1,
                        barPercentage: 0.7,
                    }]
                },

                plugins: [{
                    id: 'custom_canvas_background_color',
                    beforeDraw: (chart) => {
                        const ctx = chart.canvas.getContext('2d');
                        ctx.save();
                        ctx.globalCompositeOperation = 'destination-over';
                        ctx.fillStyle = 'white'; // Set warna background jadi PUTIH
                        ctx.fillRect(0, 0, chart.width, chart.height);
                        ctx.restore();
                    }
                }],
                options: {
                    indexAxis: 'y',
                    maintainAspectRatio: false,
                    responsive: true,
                    animation: { duration: 1000 },
                    scales: { x: { beginAtZero: true } },
                    plugins: { legend: { display: false } }
                }
            });
        }



        // --- 4. TOMBOL DOWNLOAD ---
        
        $('#downloadButton_usia').on('click', function() {
            var ta = $('input[name="tanggal_awal"]').val();
            var tak = $('input[name="tanggal_akhir"]').val();
            window.location.href = "<?= base_url('demografiusia/unduhdata') ?>?tanggal_awal=" + ta + "&tanggal_akhir=" + tak;
        });

        $('#downloadButton_gender').on('click', function() {
            var ta = $('input[name="tanggal_awal"]').val();
            var tak = $('input[name="tanggal_akhir"]').val();
            window.location.href = "<?= base_url('demografi/unduhdatagender') ?>?TANGGAL_AWAL=" + ta + "&TANGGAL_AKHIR=" + tak;
        });

        $('#downloadButton_alamat').on('click', function() {
            var ta = $('input[name="tanggal_awal"]').val();
            var tak = $('input[name="tanggal_akhir"]').val();
            window.location.href = "<?= base_url('demografi/unduhalamat') ?>?tanggal_awal=" + ta + "&tanggal_akhir=" + tak;
        });

        $('#downloadButton_pekerjaan').on('click', function() {
            var ta = $('input[name="tanggal_awal"]').val();
            var tak = $('input[name="tanggal_akhir"]').val();
            window.location.href = "<?= base_url('demografi/unduhdatapekerjaan') ?>?tanggal_awal=" + ta + "&tanggal_akhir=" + tak;
        });

    });

    function downloadChartImage(canvasId, filename) {
        var canvas = document.getElementById(canvasId);
        
        if (!canvas) {
            alert("Grafik belum dimuat!");
            return;
        }

        // 1. Konversi Canvas ke URL Data (Format PNG)
        // PNG dipilih karena mendukung transparansi & kualitas lebih tajam untuk grafik
        var image = canvas.toDataURL("image/png", 1.0);

        // 2. Buat elemen Link <a> sementara untuk memicu download
        var link = document.createElement('a');
        link.download = filename;
        link.href = image;
        
        // 3. Klik link secara virtual
        link.click();
        
        // 4. Hapus link (cleanup)
        link.remove();
    }

    function donwloadChartImgGender(canvasId, filename) {
        var canvas = document.getElementById(canvasId);
        
        if (!canvas) {
            alert("Grafik belum dimuat!");
            return;
        }

        // Simpan sebagai PNG
        var image = canvas.toDataURL("image/jpeg", 1.0);
        
        var link = document.createElement('a');
        link.download = filename;
        link.href = image;
        link.click();
        link.remove();
    }

    function donwloadChartImgUsia(canvasId, filename) {
        var canvas = document.getElementById(canvasId);
        
        if (!canvas) {
            alert("Grafik belum dimuat!");
            return;
        }

        // Simpan sebagai PNG
        var image = canvas.toDataURL("image/jpeg", 1.0);
        
        var link = document.createElement('a');
        link.download = filename;
        link.href = image;
        link.click();
        link.remove();
    }
    function donwloadChartImgPekerjaan(canvasId, filename) {
        var canvas = document.getElementById(canvasId);
        
        if (!canvas) {
            alert("Grafik belum dimuat!");
            return;
        }

        // Simpan sebagai PNG
        var image = canvas.toDataURL("image/jpeg", 1.0);
        
        var link = document.createElement('a');
        link.download = filename;
        link.href = image;
        link.click();
        link.remove();
    }
</script>
</body>
</html>