<?php
// PHP logic untuk mengambil data

session_start(); // Pastikan sesi dimulai untuk mengakses user_id

// Untuk debugging (opsional, hapus di produksi)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Sertakan file koneksi database
// Sesuaikan path ini dari lokasi file HTML ini ke db_connect.php
require_once '../api/db_connect.php';

$data_kehamilan_table = []; // Data untuk tabel (terbalik)
$data_tumbuh_kembang_table = []; // Variabel baru untuk data tabel tumbuh kembang
$data_tumbuh_kembang_chart = []; // Variabel baru untuk data chart tumbuh kembang

// Data untuk Chart.js - Tekanan Darah (berdasarkan Usia Kehamilan Minggu)
$bp_chart_data = []; // Array of objects { x: usia_kehamilan_minggu, y_systole: systole, y_diastole: diastole, date: tanggal_periksa }

// Data untuk Chart.js - TFU (berdasarkan Usia Kehamilan Minggu)
$tfu_chart_data = []; // Array of objects { x: usia_kehamilan_minggu, y: tfu, date: tanggal_periksa }

// Data untuk Chart.js - DJJ (Denyut Jantung Janin) (berdasarkan Usia Kehamilan Minggu)
$djj_chart_data = []; // Array of objects { x: usia_kehamilan_minggu, y: djj, date: tanggal_periksa }

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];

    // --- Ambil Data Kehamilan ---
    try {
        $stmt_kehamilan = $pdo->prepare("
            SELECT
                id,
                tanggal_periksa,
                systole,
                diastole,
                usia_kehamilan_minggu,
                denyut_jantung_janin,
                tinggi_fundus_uteri
            FROM
                data_kehamilan_pemeriksaan
            WHERE
                user_id = :user_id
            ORDER BY
                tanggal_periksa ASC
        "); // Urutkan berdasarkan tanggal ASC untuk grafik yang benar
        $stmt_kehamilan->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt_kehamilan->execute();
        $data_kehamilan_raw = $stmt_kehamilan->fetchAll(PDO::FETCH_ASSOC);

        // Siapkan data untuk tabel (urutkan DESC)
        $data_kehamilan_table = array_reverse($data_kehamilan_raw);

        // Siapkan data untuk Chart.js (Kehamilan) - X-axis adalah usia_kehamilan_minggu
        foreach ($data_kehamilan_raw as $row) {
            // Hanya sertakan data jika usia kehamilan valid dan > 0
            if ($row['usia_kehamilan_minggu'] !== null && $row['usia_kehamilan_minggu'] > 0) {
                // Untuk Grafik Tekanan Darah
                $bp_chart_data[] = [
                    'x' => (int)$row['usia_kehamilan_minggu'],
                    'y_systole' => (int)$row['systole'],
                    'y_diastole' => (int)$row['diastole'],
                    'date' => date('d M Y', strtotime($row['tanggal_periksa'])) // Simpan tanggal untuk tooltip
                ];

                // For TFU Chart
                if ($row['tinggi_fundus_uteri'] !== null) {
                    $tfu_chart_data[] = [
                        'x' => (int)$row['usia_kehamilan_minggu'],
                        'y' => (float)$row['tinggi_fundus_uteri'],
                        'date' => date('d M Y', strtotime($row['tanggal_periksa'])) // Simpan tanggal untuk tooltip
                    ];
                }

                // For DJJ Chart
                if ($row['denyut_jantung_janin'] !== null) {
                    $djj_chart_data[] = [
                        'x' => (int)$row['usia_kehamilan_minggu'],
                        'y' => (int)$row['denyut_jantung_janin'],
                        'date' => date('d M Y', strtotime($row['tanggal_periksa'])) // Simpan tanggal untuk tooltip
                    ];
                }
            }
        }

    } catch (PDOException $e) {
        error_log("Error fetching pregnancy data on display page: " . $e->getMessage(), 0);
        echo "<p class='alert alert-danger'>Gagal memuat data kehamilan. Silakan coba lagi. Error: " . $e->getMessage() . "</p>";
    }

    // --- Ambil Data Tumbuh Kembang (Perubahan di sini) ---
    try {
        $stmt_tumbuh_kembang = $pdo->prepare("
            SELECT
                id,
                tanggal_periksa,
                usia_bulan,
                berat_badan,
                tinggi_badan,
                lingkar_kepala
            FROM
                data_tumbuh_kembang
            WHERE
                user_id = :user_id
            ORDER BY
                tanggal_periksa ASC, id ASC
        "); // Urutkan ASC untuk grafik
        $stmt_tumbuh_kembang->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt_tumbuh_kembang->execute();
        $data_tumbuh_kembang_raw = $stmt_tumbuh_kembang->fetchAll(PDO::FETCH_ASSOC);

        // Siapkan data untuk tabel (urutkan DESC)
        $data_tumbuh_kembang_table = array_reverse($data_tumbuh_kembang_raw);

        // Siapkan data untuk Chart.js (Tumbuh Kembang) - X-axis adalah usia_bulan
        foreach ($data_tumbuh_kembang_raw as $row) {
            if ($row['usia_bulan'] !== null && $row['usia_bulan'] >= 0) { // Usia bisa 0 bulan
                if ($row['berat_badan'] !== null) {
                    $data_tumbuh_kembang_chart['berat_badan_umur'][] = [
                        'x' => (int)$row['usia_bulan'],
                        'y' => (float)$row['berat_badan'],
                        'date' => date('d M Y', strtotime($row['tanggal_periksa']))
                    ];
                }
                if ($row['tinggi_badan'] !== null) {
                    $data_tumbuh_kembang_chart['tinggi_badan_umur'][] = [
                        'x' => (int)$row['usia_bulan'],
                        'y' => (float)$row['tinggi_badan'],
                        'date' => date('d M Y', strtotime($row['tanggal_periksa']))
                    ];
                }
            }
        }

    } catch (PDOException $e) {
        error_log("Error fetching growth data on display page: " . $e->getMessage(), 0);
        echo "<p class='alert alert-danger'>Gagal memuat data tumbuh kembang. Silakan coba lagi. Error: " . $e->getMessage() . "</p>";
    }

} else {
    echo "<p class='alert alert-warning'>Anda harus login untuk melihat data kesehatan.</p>";
}

// Encode data menjadi JSON untuk JavaScript
$bp_chart_data_json = json_encode($bp_chart_data);
$tfu_chart_data_json = json_encode($tfu_chart_data);
$djj_chart_data_json = json_encode($djj_chart_data);
$data_tumbuh_kembang_chart_json = json_encode($data_tumbuh_kembang_chart); // NEW JSON for Growth Charts

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Kesehatan</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>

    <link rel="stylesheet" href="../css/style.css">

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.min.js"></script>

</head>
<body>

    <header class="page-header">
        <h1>Data Kesehatan</h1>
    </header>

    <div class="main-content-area data-page">
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="kehamilan-tab" data-bs-toggle="tab" data-bs-target="#kehamilan" type="button" role="tab" aria-controls="kehamilan" aria-selected="true">Kehamilan</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="tumbuh-kembang-tab" data-bs-toggle="tab" data-bs-target="#tumbuh-kembang" type="button" role="tab" aria-controls="tumbuh-kembang" aria-selected="false">Tumbuh Kembang</button>
            </li>
        </ul>

        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="kehamilan" role="tabpanel" aria-labelledby="kehamilan-tab">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Systole</th>
                                <th>Diastole</th>
                                <th>UK</th>
                                <th>DJJ</th>
                                <th>TFU</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($data_kehamilan_table)): ?>
                                <?php foreach ($data_kehamilan_table as $row): ?>
                                    <tr>
                                        <td><?php echo date('d M y', strtotime($row['tanggal_periksa'])); ?></td>
                                        <td><?php echo htmlspecialchars($row['systole']); ?></td>
                                        <td><?php echo htmlspecialchars($row['diastole']); ?></td>
                                        <td><?php echo htmlspecialchars($row['usia_kehamilan_minggu']); ?>w</td>
                                        <td><?php echo ($row['denyut_jantung_janin'] !== null) ? htmlspecialchars($row['denyut_jantung_janin']) : '-'; ?></td>
                                        <td><?php echo ($row['tinggi_fundus_uteri'] !== null) ? htmlspecialchars(number_format($row['tinggi_fundus_uteri'], 1, ',', '.')) . 'cm' : '-'; ?></td>
                                        <td>
                                            <button class="action-btn edit-btn" data-id="<?php echo $row['id']; ?>" data-type="kehamilan"><i class='bx bx-edit-alt'></i></button>
                                            <button class="action-btn delete-btn" data-id="<?php echo $row['id']; ?>" data-type="kehamilan"><i class='bx bx-trash'></i></button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7">Belum ada data kehamilan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <a href="kehamilan/" class="add-data-btn btn-kehamilan">
                    <i class='bx bx-plus'></i> <span>Tambah Data Kehamilan</span>
                </a>

                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">Grafik Tekanan Darah Kehamilan</h5>
                        <div class="chart-container" style="position: relative; height:40vh;  max-width: 800px; margin: auto;">
                            <canvas id="bloodPressureChart"></canvas>
                        </div>
                        <p class="card-text text-muted small text-center mt-2">Data pasien dan garis batas atas tekanan darah.</p>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">Grafik Tinggi Fundus Uteri (TFU) & Detak Jantung Janin (DJJ)</h5>
                        <div class="chart-container" style="position: relative; height:40vh;  max-width: 800px; margin: auto;">
                            <canvas id="tfuDjjChart"></canvas>
                        </div>
                        <p class="card-text text-muted small text-center mt-2">Data pasien dan kurva pertumbuhan TFU & DJJ normal berdasarkan usia kehamilan.</p>
                    </div>
                </div>

            </div>

            <div class="tab-pane fade" id="tumbuh-kembang" role="tabpanel" aria-labelledby="tumbuh-kembang-tab">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Usia (bulan)</th>
                                <th>Berat (kg)</th>
                                <th>Tinggi (cm)</th>
                                <th>Lingkar Kepala (cm)</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($data_tumbuh_kembang_table)): ?>
                                <?php foreach ($data_tumbuh_kembang_table as $row): ?>
                                    <tr>
                                        <td><?php echo date('d M y', strtotime($row['tanggal_periksa'])); ?></td>
                                        <td><?php echo htmlspecialchars($row['usia_bulan']); ?></td>
                                        <td><?php echo htmlspecialchars(number_format($row['berat_badan'], 1, ',', '.')); ?></td>
                                        <td><?php echo htmlspecialchars(number_format($row['tinggi_badan'], 1, ',', '.')); ?></td>
                                        <td><?php echo ($row['lingkar_kepala'] !== null) ? htmlspecialchars(number_format($row['lingkar_kepala'], 1, ',', '.')) : '-'; ?></td>
                                        <td>
                                            <button class="action-btn edit-btn" data-id="<?php echo $row['id']; ?>" data-type="tumbuhkembang"><i class='bx bx-edit-alt'></i></button>
                                            <button class="action-btn delete-btn" data-id="<?php echo $row['id']; ?>" data-type="tumbuhkembang"><i class='bx bx-trash'></i></button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6">Belum ada data tumbuh kembang.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <a href="tumbuhkembang/" class="add-data-btn btn-kehamilan">
                    <i class='bx bx-plus'></i> <span>Tambah Data Tumbuh Kembang</span>
                </a>

                <div class="card mb-4 mt-4">
                    <div class="card-body">
                        <h5 class="card-title">Grafik Berat Badan menurut Usia (BB/U) Laki-laki 0-5 Tahun</h5>
                        <div class="chart-container" style="position: relative; height:50vh;  max-width: 800px; margin: auto;">
                            <canvas id="bbUmurChart"></canvas>
                        </div>
                        <p class="card-text text-muted small text-center mt-2">Garis pertumbuhan WHO (Z-score) dan data berat badan pasien.</p>
                        <div class="legend-info mt-3 text-center">
                            <div class="d-flex flex-wrap justify-content-center align-items-center gap-2">
                                <span class="legend-item" style="--bg-color: rgba(255, 0, 0, 0.2); --border-color: red;">-3 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(255, 0, 0, 0.2); --border-color: red;">-2 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(255, 255, 0, 0.2); --border-color: orange;">-1 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(0, 128, 0, 0.2); --border-color: green;">0 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(0, 128, 0, 0.2); --border-color: blue;">+1 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(0, 0, 255, 0.2); --border-color: blue;">+2 SD</span>
                                <span class="legend-item" style="--bg-color: rgba(0, 0, 255, 0.2); --border-color: darkblue;">+3 SD</span>
                            </div>
                            <div class="status-gizi-table mt-3">
                                <h6>Status gizi berdasarkan Z-Score untuk BB/U:</h6>
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>Kategori Status Gizi</th>
                                            <th>Z-Score</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr><td>Gizi buruk</td><td>< -3 SD</td></tr>
                                        <tr><td>Gizi kurang</td><td>-3 SD sampai < -2 SD</td></tr>
                                        <tr><td>Gizi baik</td><td>-2 SD sampai +2 SD</td></tr>
                                        <tr><td>Gizi lebih</td><td>> +2 SD sampai +3 SD</td></tr>
                                        <tr><td>Obesitas</td><td>> +3 SD</td></tr>
                                    </tbody>
                                </table>
                                <p class="text-muted small">Catatan: Kategori ini disederhanakan untuk tampilan grafik BB/U.</p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <nav class="nav1">
        <ul class="nav-content1">
            <li class="nav-list1">
                <a href="../" class="link-item1"> <i class='bx bx-home-alt link-icon1'></i> <span class="link-text1">Beranda</span>
                </a>
            </li>
            <li class="nav-list1">
                <a href="../dataperkembangan/" class="link-item1 active1">
                    <i class='bx bx-category link-icon1'></i> <span class="link-text1">Fitur</span>
                </a>
            </li>
            <li class="nav-list1">
                <a href="../jadwalposyandu/" class="link-item1">
                    <i class='bx bx-chart link-icon1'></i> <span class="link-text1">Jadwal Posyandu</span>
                </a>
            </li>
            <li class="nav-list1">
                <a href="../laporkehamilan/" class="link-item1 active1">
                    <i class='bx bx-chat link-icon1'></i> <span class="link-text1">Lapor Kehamilan</span>
                </a>
            </li>
            <li class="nav-list1">
                <a href="../profil/" class="link-item1">
                    <i class='bx bx-user-circle link-icon1'></i> <span class="link-text1">Profil</span>
                </a>
            </li>
        </ul>
    </nav>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="../js/script.js"></script>

    <style>
        .legend-info .legend-item {
            display: inline-flex; /* Menggunakan flexbox untuk penataan */
            align-items: center; /* Memusatkan item secara vertikal */
            gap: 5px; /* Jarak antara kotak warna dan teks */
            margin-right: 15px; /* Jarak antar item legenda */
            font-size: 0.9em;
            color: #555;
            padding: 5px 8px; /* Padding untuk area legenda per item */
            border-radius: 4px; /* Sudut sedikit membulat */
        }
        .legend-info .legend-item::before {
            content: '';
            display: inline-block;
            width: 15px;
            height: 15px;
            background-color: var(--bg-color, lightgray); /* Gunakan custom property untuk warna background */
            border: 1px solid var(--border-color, gray); /* Gunakan custom property untuk warna border */
            border-radius: 3px;
            flex-shrink: 0; /* Pastikan kotak tidak menyusut */
        }

        .status-gizi-table {
            max-width: 400px;
            margin: 20px auto;
            font-size: 0.9em;
        }
        .status-gizi-table h6 {
            font-weight: bold;
            margin-bottom: 10px;
        }
        .status-gizi-table table {
            width: 100%;
        }
        .status-gizi-table th, .status-gizi-table td {
            text-align: left;
            padding: 5px;
        }
        .status-gizi-table thead th {
            background-color: #f8f9fa;
        }
    </style>

    <script>
        // Daftarkan plugin zoom secara global (penting sebelum inisialisasi grafik)
        Chart.register(ChartZoom);

        document.addEventListener('DOMContentLoaded', function() {
            // Data diambil dari PHP
            const bpChartData = <?php echo $bp_chart_data_json; ?>;
            const tfuChartData = <?php echo $tfu_chart_data_json; ?>;
            const djjChartData = <?php echo $djj_chart_data_json; ?>;
            const growthChartData = <?php echo $data_tumbuh_kembang_chart_json; ?>; // Growth Data

            // --- Data Guidelines (Rentang Normal) ---
            const gestationWeeksRange = Array.from({length: 43}, (_, i) => i); // Weeks 0 to 42

            // BP Guidelines (re-used from previous, no change)
            const normalBpSystoleUpper = [];
            const normalBpDiastoleUpper = [];
            gestationWeeksRange.forEach(week => {
                normalBpSystoleUpper.push({ x: week, y: 130 });
                normalBpDiastoleUpper.push({ x: week, y: 80 });
            });

            // TFU Guidelines (re-used from previous, no change)
            const normalTfuUpper = [];
            const normalTfuLower = [];
            const normalTfuIdeal = [];
            gestationWeeksRange.forEach(week => {
                let tfu_ideal = null;
                let tfu_upper = null;
                let tfu_lower = null;
                if (week >= 12 && week <= 40) {
                    if (week <= 20) { tfu_ideal = 10 + (week - 12) * 1.25; tfu_lower = Math.max(0, tfu_ideal - 2.5); tfu_upper = tfu_ideal + 2.5; }
                    else if (week <= 36) { tfu_ideal = week; tfu_lower = Math.max(0, week - 3); tfu_upper = week + 3; }
                    else { tfu_ideal = 36 - (week - 36) * 0.5; tfu_lower = Math.max(0, tfu_ideal - 2); tfu_upper = tfu_ideal + 2; }
                }
                if (tfu_ideal !== null) {
                    normalTfuIdeal.push({ x: week, y: parseFloat(tfu_ideal.toFixed(1)) });
                    normalTfuUpper.push({ x: week, y: parseFloat(tfu_upper.toFixed(1)) });
                    normalTfuLower.push({ x: week, y: parseFloat(tfu_lower.toFixed(1)) });
                }
            });

            // DJJ Guidelines (re-used from previous, no change)
            const normalDjjUpper = [];
            const normalDjjLower = [];
            gestationWeeksRange.forEach(week => {
                normalDjjUpper.push({ x: week, y: 160 });
                normalDjjLower.push({ x: week, y: 110 });
            });

            // --- WHO Growth Chart Data (Berat Badan menurut Usia - Laki-laki 0-5 tahun) ---
            // PENTING: Ini adalah data SAMPLES. Anda harus mengganti ini dengan data aktual dari standar WHO.
            const whoBbuBoysData = {
                // Usia (bulan): [-3SD, -2SD, -1SD, Median, +1SD, +2SD, +3SD]
                0: [2.1, 2.5, 2.9, 3.3, 3.8, 4.3, 4.7], // Lahir
                1: [2.9, 3.4, 3.9, 4.5, 5.2, 5.8, 6.5],
                2: [3.8, 4.3, 4.9, 5.6, 6.4, 7.1, 7.9],
                3: [4.4, 5.0, 5.7, 6.4, 7.3, 8.1, 9.0],
                4: [4.8, 5.5, 6.2, 6.9, 7.9, 8.8, 9.7],
                5: [5.1, 5.8, 6.6, 7.4, 8.4, 9.3, 10.3],
                6: [5.4, 6.1, 6.9, 7.7, 8.8, 9.7, 10.8],
                7: [5.6, 6.3, 7.1, 8.0, 9.1, 10.0, 11.1],
                8: [5.7, 6.5, 7.3, 8.2, 9.3, 10.3, 11.4],
                9: [5.9, 6.7, 7.5, 8.4, 9.6, 10.6, 11.7],
                10: [6.0, 6.8, 7.7, 8.7, 9.8, 10.9, 12.0],
                11: [6.1, 7.0, 7.9, 8.8, 10.0, 11.1, 12.3],
                12: [6.2, 7.1, 8.0, 9.0, 10.2, 11.3, 12.5],
                18: [7.0, 8.0, 9.0, 10.2, 11.6, 12.9, 14.2],
                24: [7.9, 9.0, 10.2, 11.5, 13.0, 14.5, 16.1],
                36: [9.3, 10.6, 12.0, 13.6, 15.3, 17.2, 19.1],
                48: [10.5, 11.9, 13.5, 15.3, 17.3, 19.4, 21.6],
                60: [11.5, 13.1, 14.9, 16.9, 19.1, 21.4, 23.9]
            };

            // Fungsi untuk mengkonversi data WHO menjadi array yang siap untuk Chart.js
            function getWhoDataForChart(whoData, sdIndex) {
                const data = [];
                for (let month = 0; month <= 60; month++) { // Usia 0-60 bulan
                    if (whoData[month] !== undefined) {
                        data.push({ x: month, y: whoData[month][sdIndex] });
                    }
                }
                return data;
            }

            const whoBbuMinus3Sd = getWhoDataForChart(whoBbuBoysData, 0);
            const whoBbuMinus2Sd = getWhoDataForChart(whoBbuBoysData, 1);
            const whoBbuMinus1Sd = getWhoDataForChart(whoBbuBoysData, 2);
            const whoBbuMedian = getWhoDataForChart(whoBbuBoysData, 3);
            const whoBbuPlus1Sd = getWhoDataForChart(whoBbuBoysData, 4);
            const whoBbuPlus2Sd = getWhoDataForChart(whoBbuBoysData, 5);
            const whoBbuPlus3Sd = getWhoDataForChart(whoBbuBoysData, 6);


            // --- Fungsi untuk membuat tooltip kustom (diperbarui untuk tumbuh kembang) ---
            function customTooltipCallback(context) {
                const label = context.dataset.label || '';
                let value = context.parsed.y;
                let text = '';

                // Menentukan teks berdasarkan label dataset
                if (label.includes('Systole Pasien')) {
                    text = 'Systole Pasien: ' + value + ' mmHg';
                } else if (label.includes('Diastole Pasien')) {
                    text = 'Diastole Pasien: ' + value + ' mmHg';
                } else if (label.includes('Batas Atas Sistolik')) {
                    text = `Batas Atas Sistolik: ${value} mmHg`;
                } else if (label.includes('Batas Atas Diastolik')) {
                    text = `Batas Atas Diastolik: ${value} mmHg`;
                } else if (label.includes('TFU Pasien')) {
                    text = label + ': ' + value + ' cm';
                } else if (label.includes('DJJ Pasien')) {
                    text = label + ': ' + value + ' bpm';
                } else if (label.includes('Kurva Ideal TFU')) {
                     text = 'Kurva Ideal TFU: ' + value + ' cm';
                } else if (label.includes('Batas Normal TFU')) {
                    if (context.dataset.data === normalTfuUpper) text = `Batas Atas TFU: ${value} cm`;
                    if (context.dataset.data === normalTfuLower) text = `Batas Bawah TFU: ${value} cm`;
                } else if (label.includes('Batas Normal DJJ')) {
                    if (context.dataset.data === normalDjjUpper) text = `Batas Atas DJJ: ${value} bpm`;
                    if (context.dataset.data === normalDjjLower) text = `Batas Bawah DJJ: ${value} bpm`;
                } else if (label.includes('Berat Badan Pasien')) { // NEW for Tumbuh Kembang
                    text = label + ': ' + value + ' kg';
                } else if (label.includes('Z-score')) { // NEW for Tumbuh Kembang WHO lines
                    let sdLevel = label.match(/Z-score (-?\d+)/);
                    if (sdLevel) {
                         text = `WHO ${sdLevel[1]}SD: ${value} kg`;
                    } else {
                         text = `WHO Median: ${value} kg`; // For Median
                    }
                }
                else if (label.includes('Rentang Gizi') || label.includes('Rentang Normal')) { // Untuk area yang diarsir, tidak perlu tooltip label
                    return null;
                } else {
                    text = label + ': ' + value;
                }

                // Tambahkan Tanggal Pemeriksaan jika data pasien dan ada properti 'date'
                if (context.raw && context.raw.date && (
                    label.includes('Systole Pasien') ||
                    label.includes('Diastole Pasien') ||
                    label.includes('TFU Pasien') ||
                    label.includes('DJJ Pasien') ||
                    label.includes('Berat Badan Pasien') || // NEW
                    label.includes('Tinggi Badan Pasien')    // If you add TB chart
                )) {
                     text += `\nTanggal: ${context.raw.date}`;
                }
                // Tambahkan Usia (Minggu/Bulan) untuk semua titik data yang memiliki properti 'x'
                if (context.parsed.x !== null && !isNaN(context.parsed.x)) {
                    if (label.includes('Pasien') || label.includes('Z-score') || label.includes('Median')) { // For patient and WHO lines (tumbuh kembang)
                        text = `Usia ${context.parsed.x} Bulan\n` + text;
                    } else if (label.includes('TFU') || label.includes('DJJ') || label.includes('Systole') || label.includes('Diastole')) { // For pregnancy charts
                        text = `UK ${context.parsed.x} Minggu\n` + text;
                    }
                }
                return text;
            }


            // --- Grafik Tekanan Darah Kehamilan (no change) ---
            const bpCtx = document.getElementById('bloodPressureChart').getContext('2d');
            if (bpCtx) {
                new Chart(bpCtx, {
                    type: 'line',
                    data: {
                        datasets: [
                            { label: 'Batas Atas Sistolik (Max 130)', data: normalBpSystoleUpper, borderColor: 'rgb(255, 0, 0)', borderWidth: 2, borderDash: [5, 5], pointRadius: 0, fill: false, order: 1, showLine: true, spanGaps: true, },
                            { label: 'Batas Atas Diastolik (Max 80)', data: normalBpDiastoleUpper, borderColor: 'rgb(255, 0, 0)', borderWidth: 2, borderDash: [5, 5], pointRadius: 0, fill: false, order: 2, showLine: true, spanGaps: true, },
                            { label: 'Systole Pasien', data: bpChartData.map(item => ({ x: item.x, y: item.y_systole, date: item.date })), borderColor: 'rgb(0, 128, 0)', backgroundColor: 'rgb(0, 128, 0)', tension: 0.1, fill: false, pointRadius: 5, pointBackgroundColor: 'rgb(0, 128, 0)', showLine: true, order: 3, },
                            { label: 'Diastole Pasien', data: bpChartData.map(item => ({ x: item.x, y: item.y_diastole, date: item.date })), borderColor: 'rgb(255, 0, 0)', backgroundColor: 'rgb(255, 0, 0)', tension: 0.1, fill: false, pointRadius: 5, pointBackgroundColor: 'rgb(255, 0, 0)', showLine: true, order: 4, }
                        ]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false, scales: { x: { type: 'linear', min: 0, max: 42, title: { display: true, text: 'Usia Kehamilan (Minggu)' }, ticks: { stepSize: 2 } }, y: { beginAtZero: false, title: { display: true, text: 'Tekanan Darah (mmHg)' }, min: 40, max: 180 } },
                        plugins: { tooltip: { callbacks: { label: customTooltipCallback } }, legend: { labels: { filter: function(item, chart) { return !item.text.includes('Batas Atas Sistolik') && !item.text.includes('Batas Atas Diastolik'); } } } }
                    }
                });
            } else {
                const parentDiv = document.getElementById('bloodPressureChart').parentNode;
                parentDiv.innerHTML = '<p class="text-muted text-center mt-3">Tidak ada data tekanan darah untuk menampilkan grafik.</p>';
            }

            // --- Grafik TFU & DJJ Kehamilan (no change) ---
            const tfuDjjCtx = document.getElementById('tfuDjjChart').getContext('2d');
            if (tfuDjjCtx) {
                new Chart(tfuDjjCtx, {
                    type: 'line',
                    data: {
                        datasets: [
                            // TFU Data & Range (Skema Warna Oranye)
                            { label: 'Rentang Normal TFU (Area)', data: normalTfuUpper, backgroundColor: 'rgba(255, 159, 64, 0.15)', borderColor: 'transparent', pointRadius: 0, fill: '-1', order: 1, showLine: true, spanGaps: true, yAxisID: 'tfu-axis' },
                            { label: 'Batas Normal TFU', data: normalTfuLower, borderColor: 'rgba(255, 159, 64, 0.7)', borderWidth: 1, borderDash: [5, 5], pointRadius: 0, fill: false, order: 2, showLine: true, spanGaps: true, yAxisID: 'tfu-axis' },
                            { label: 'Kurva Ideal TFU', data: normalTfuIdeal, borderColor: 'rgb(255, 159, 64)', backgroundColor: 'rgb(255, 159, 64)', borderWidth: 2, tension: 0.2, pointRadius: 0, fill: false, order: 3, showLine: true, spanGaps: true, yAxisID: 'tfu-axis' },

                            // DJJ Data & Range (Skema Warna Ungu)
                            { label: 'Rentang Normal DJJ (Area)', data: normalDjjUpper, backgroundColor: 'rgba(153, 102, 255, 0.15)', borderColor: 'transparent', pointRadius: 0, fill: '-1', order: 4, showLine: true, spanGaps: true, yAxisID: 'djj-axis' },
                            { label: 'Batas Normal DJJ', data: normalDjjLower, borderColor: 'rgba(153, 102, 255, 0.7)', borderWidth: 1, borderDash: [5, 5], pointRadius: 0, fill: false, order: 5, showLine: true, spanGaps: true, yAxisID: 'djj-axis' },

                            // Data Pasien
                            { label: 'TFU Pasien (cm)', data: tfuChartData.map(item => ({ x: item.x, y: item.y, date: item.date })), borderColor: 'rgb(255, 140, 0)', backgroundColor: 'rgb(255, 140, 0)', tension: 0.1, fill: false, pointRadius: 5, pointBackgroundColor: 'rgb(255, 140, 0)', showLine: true, order: 6, yAxisID: 'tfu-axis' },
                            { label: 'DJJ Pasien (bpm)', data: djjChartData.map(item => ({ x: item.x, y: item.y, date: item.date })), borderColor: 'rgb(102, 0, 153)', backgroundColor: 'rgb(102, 0, 153)', tension: 0.1, fill: false, pointRadius: 5, pointBackgroundColor: 'rgb(102, 0, 153)', showLine: true, order: 7, yAxisID: 'djj-axis' }
                        ]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false, scales: { x: { type: 'linear', min: 0, max: 42, title: { display: true, text: 'Usia Kehamilan (Minggu)' }, ticks: { stepSize: 2 } }, 'tfu-axis': { type: 'linear', position: 'left', beginAtZero: true, title: { display: true, text: 'Tinggi Fundus Uteri (cm)' }, min: 0, max: 45 }, 'djj-axis': { type: 'linear', position: 'right', beginAtZero: false, title: { display: true, text: 'Detak Jantung Janin (bpm)' }, min: 80, max: 180, grid: { drawOnChartArea: false } } },
                        plugins: { tooltip: { callbacks: { label: customTooltipCallback } }, legend: { labels: { filter: function(item, chart) { return !item.text.includes('(Area)'); } } } }
                    }
                });
            } else {
                const parentDiv = document.getElementById('tfuDjjChart').parentNode;
                parentDiv.innerHTML = '<p class="text-muted text-center mt-3">Tidak ada data TFU/DJJ untuk menampilkan grafik.</p>';
            }

            // --- Grafik Berat Badan menurut Usia (BB/U) - Laki-laki 0-5 Tahun ---
            const bbUmurCtx = document.getElementById('bbUmurChart').getContext('2d');
            if (bbUmurCtx && growthChartData.berat_badan_umur && growthChartData.berat_badan_umur.length > 0) {
                new Chart(bbUmurCtx, {
                    type: 'line',
                    data: {
                        datasets: [
                            // Shaded area: -3SD to -2SD (Gizi Kurang/Buruk) - Red
                            {
                                label: 'Rentang Gizi Kurang/Buruk (-3SD to -2SD)',
                                data: whoBbuMinus2Sd, // Fill from -2SD down to -3SD
                                backgroundColor: 'rgba(255, 0, 0, 0.2)', // Light Red
                                borderColor: 'transparent',
                                pointRadius: 0,
                                fill: '-1', // Fills to the previous dataset (which should be -3SD if ordered correctly)
                                order: 1, // Draw order, lowest first
                                showLine: true,
                                spanGaps: true,
                            },
                            // Line: -3SD - Red border
                            {
                                label: 'WHO Z-score -3SD',
                                data: whoBbuMinus3Sd,
                                borderColor: 'red',
                                borderWidth: 1,
                                pointRadius: 0,
                                fill: false,
                                order: 2,
                                showLine: true,
                                spanGaps: true,
                            },

                            // Shaded area: -2SD to Median (Gizi Baik - part 1) - Yellow
                            {
                                label: 'Rentang Gizi Baik (-2SD to Median)',
                                data: whoBbuMedian, // Fill from Median down to -2SD
                                backgroundColor: 'rgba(255, 255, 0, 0.2)', // Light Yellow
                                borderColor: 'transparent',
                                pointRadius: 0,
                                fill: '-1', // Fills to the previous dataset (-2SD)
                                order: 3,
                                showLine: true,
                                spanGaps: true,
                            },
                            // Line: -2SD - Orange border
                            {
                                label: 'WHO Z-score -2SD',
                                data: whoBbuMinus2Sd,
                                borderColor: 'orange',
                                borderWidth: 1,
                                pointRadius: 0,
                                fill: false,
                                order: 4,
                                showLine: true,
                                spanGaps: true,
                            },

                             // Shaded area: Median to +2SD (Gizi Baik - part 2) - Green
                             {
                                label: 'Rentang Gizi Baik (Median to +2SD)',
                                data: whoBbuPlus2Sd, // Fill from +2SD down to Median
                                backgroundColor: 'rgba(0, 128, 0, 0.2)', // Light Green
                                borderColor: 'transparent',
                                pointRadius: 0,
                                fill: '-1', // Fills to the previous dataset (Median)
                                order: 5,
                                showLine: true,
                                spanGaps: true,
                            },
                            // Line: Median (0 SD) - Green border
                            {
                                label: 'WHO Z-score Median',
                                data: whoBbuMedian,
                                borderColor: 'green',
                                borderWidth: 2, // Lebih tebal untuk median
                                pointRadius: 0,
                                fill: false,
                                order: 6,
                                showLine: true,
                                spanGaps: true,
                            },

                            // Shaded area: +2SD to +3SD (Berisiko Gizi Lebih) - Blue
                            {
                                label: 'Rentang Berisiko Gizi Lebih (+2SD to +3SD)',
                                data: whoBbuPlus3Sd, // Fill from +3SD down to +2SD
                                backgroundColor: 'rgba(0, 0, 255, 0.2)', // Light Blue (untuk demo, ganti warna jika ada standar)
                                borderColor: 'transparent',
                                pointRadius: 0,
                                fill: '-1', // Fills to the previous dataset (+2SD)
                                order: 7,
                                showLine: true,
                                spanGaps: true,
                            },
                            // Line: +2SD - Blue border
                            {
                                label: 'WHO Z-score +2SD',
                                data: whoBbuPlus2Sd,
                                borderColor: 'blue',
                                borderWidth: 1,
                                pointRadius: 0,
                                fill: false,
                                order: 8,
                                showLine: true,
                                spanGaps: true,
                            },
                             // Line: +3SD - Blue border
                            {
                                label: 'WHO Z-score +3SD',
                                data: whoBbuPlus3Sd,
                                borderColor: 'darkblue',
                                borderWidth: 1,
                                pointRadius: 0,
                                fill: false,
                                order: 9,
                                showLine: true,
                                spanGaps: true,
                            },

                            // Patient Data (overlay on top)
                            {
                                label: 'Berat Badan Pasien',
                                data: growthChartData.berat_badan_umur,
                                borderColor: 'purple', // Warna untuk data pasien
                                backgroundColor: 'purple',
                                tension: 0.1,
                                fill: false,
                                pointRadius: 5,
                                pointBackgroundColor: 'purple',
                                showLine: true,
                                order: 10, // Gambar paling atas
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            x: {
                                type: 'linear',
                                min: 0,
                                max: 60, // 0-60 bulan (5 tahun)
                                title: {
                                    display: true,
                                    text: 'Usia (Bulan)'
                                },
                                ticks: {
                                    stepSize: 6 // Tampilkan setiap 6 bulan
                                }
                            },
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Berat Badan (kg)'
                                },
                                min: 0,
                                max: 25 // Sesuaikan batas maksimum Y sesuai data WHO Anda
                            }
                        },
                        plugins: {
                            tooltip: {
                                callbacks: {
                                    label: customTooltipCallback
                                }
                            },
                            legend: {
                                display: false // Ini yang akan menyembunyikan legenda Chart.js
                            },
                            zoom: { // Konfigurasi Zoom
                                pan: {
                                    enabled: true, // Aktifkan pan (geser)
                                    mode: 'xy', // Geser pada sumbu X dan Y
                                },
                                zoom: {
                                    wheel: {
                                        enabled: true, // Aktifkan zoom dengan roda mouse
                                    },
                                    pinch: {
                                        enabled: true // Aktifkan zoom dengan cubit (layar sentuh)
                                    },
                                    mode: 'xy', // Zoom pada sumbu X dan Y
                                }
                            }
                        }
                    }
                });
            } else {
                const parentDiv = document.getElementById('bbUmurChart').parentNode;
                parentDiv.innerHTML = '<p class="text-muted text-center mt-3">Tidak ada data berat badan atau grafik tumbuh kembang untuk ditampilkan.</p>';
            }
        });
    </script>
</body>
</html>