<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'kader') {
    header("Location: ../login.php"); exit;
}

$id_balita = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$stmt = $pdo->prepare("SELECT * FROM balita WHERE id_balita = ? AND id_posyandu = ?");
$stmt->execute([$id_balita, $_SESSION['posyandu']]);
$balita = $stmt->fetch();

if (!$balita) { die("Data balita tidak ditemukan."); }

$tgl_lahir = new DateTime($balita['tgl_lahir']);
$sekarang = new DateTime();
$diff = $sekarang->diff($tgl_lahir);
$usia_bulan = ($diff->y * 12) + $diff->m;
$is_lulus = $usia_bulan > 60;

$stmt_riwayat = $pdo->prepare("SELECT * FROM pemeriksaan_balita WHERE id_balita = ? ORDER BY tgl_periksa ASC");
$stmt_riwayat->execute([$id_balita]);
$riwayat = $stmt_riwayat->fetchAll();

$labels = [];

$bb_values = [];
$z_bbu_values = [];
$status_bbu = [];

$tb_values = [];
$z_tbu_values = [];
$status_tbu = [];

$z_bbtb_values = [];
$status_bbtb = [];

foreach($riwayat as $r) {
    $labels[] = date('d/m/y', strtotime($r['tgl_periksa']));

    // BB/U
    $bb_values[] = (float)$r['bb'];
    $z_bbu_values[] = isset($r['z_bbu']) ? (float)$r['z_bbu'] : null;
    $status_bbu[] = $r['z_score_bbu'] ?? '-';

    // TB/U
    $tb_values[] = (float)$r['tb'];
    $z_tbu_values[] = isset($r['z_tbu']) ? (float)$r['z_tbu'] : null;
    $status_tbu[] = $r['status_stunting'] ?? '-';

    // BB/TB
    $z_bbtb_values[] = isset($r['z_bbtb']) ? (float)$r['z_bbtb'] : null;
    $status_bbtb[] = $r['status_bbtb'] ?? '-';
}

$riwayat_tabel = array_reverse($riwayat);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Detail - <?= htmlspecialchars($balita['nama_balita']) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.table td a {
    text-decoration: none !important;
}

.table td a:hover,
.table td a:focus,
.table td a:active {
    text-decoration: none !important;
    outline: none !important;
    box-shadow: none !important;
}
body { background-color: #f4f7f6; font-family: 'Segoe UI', sans-serif; }
.header-profile { background: linear-gradient(135deg, #0d6efd 0%, #004db3 100%); color: white; border-radius: 0 0 25px 25px; padding: 30px 20px; margin-bottom: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.card-custom { border-radius: 15px; border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px; background: white; }
.table th { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; background: #f8f9fa; color: #666; }
.table td { font-size: 0.85rem; vertical-align: middle; white-space: nowrap; }
.btn-input { border-radius: 12px; font-weight: bold; }
.dot{
    height:8px;
    width:8px;
    margin:0 4px;
    background:#ccc;
    border-radius:50%;
    display:inline-block;
    transition:.3s;
}
.dot.active{
    width:20px;
    background:#0d6efd;
    border-radius:20px;
}

#grafikCard {
    overflow: hidden;
}

#animatedArea {
    transition: opacity .25s ease, transform .25s cubic-bezier(.4,0,.2,1);
}
</style>
</head>
<body>

<div class="header-profile text-center">
<div class="container">
<div class="d-flex justify-content-between align-items-start mb-3">
<a href="balita_index.php" class="text-white"><i class="fa fa-arrow-left fa-lg"></i></a>
<div class="flex-grow-1">
<h3 class="fw-bold mb-1"><?= htmlspecialchars($balita['nama_balita']) ?></h3>
<p class="mb-0 opacity-75">Nama Ibu: <?= htmlspecialchars($balita['nama_ibu']) ?></p>
</div>
</div>
<div class="d-flex justify-content-center gap-2">
<span class="badge bg-white text-primary rounded-pill px-3"><?= $balita['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan' ?></span>
<span class="badge bg-warning text-dark rounded-pill px-3"><?= $usia_bulan ?> Bulan</span>
</div>
</div>
</div>

<div class="container pb-2">


<div class="card card-custom mb-2" id="grafikCard">
    <div class="card-body p-2">

        <!-- AREA YANG DIANIMASIKAN -->
        <div id="animatedArea" class="text-center mb-2">
            <h6 class="fw-bold text-secondary mb-1">
                <i class="fa fa-line-chart me-2"></i>
                <span id="judulGrafik">BB/U (Berat Badan Menurut Umur)</span>
            </h6>
            <small class="text-muted d-block" id="subJudulGrafik">
                Grafik standar WHO dengan Z-Score
            </small>
        </div>

        <!-- CANVAS TIDAK IKUT ANIMASI -->
        <div style="height:170px;">
            <canvas id="chartPertumbuhan"></canvas>
        </div>

        <!-- DOT -->
        <div class="text-center mt-2" id="indikatorGrafik">
            <span class="dot active"></span>
            <span class="dot"></span>
            <span class="dot"></span>
        </div>

    </div>
</div>

<?php if(!$is_lulus): ?>

<a href="balita_tambah_periksa.php?id=<?= $id_balita ?>" 
   class="btn btn-primary w-100 py-3 btn-input mb-4 shadow">
   <i class="fa fa-plus-circle me-2"></i> TIMBANG BADAN SEKARANG
</a>

<?php else: ?>

<a href="javascript:void(0);" 
   class="btn btn-danger w-100 py-3 btn-input mb-4 shadow"
   onclick="alert('Balita ini sudah lulus/ berusia lebih dari 60 bulan!')">
   <i class="fa fa-lock me-2"></i> BALITA SUDAH LULUS (TERKUNCI)
</a>

<?php endif; ?>

<div class="card card-custom">
<div class="card-body p-0">
<h6 class="fw-bold text-secondary p-3 mb-0">
<i class="fa fa-history me-2"></i>Riwayat Pemeriksaan Lengkap
</h6>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
<th>Tgl</th>
<th>BB</th>
<th>TB</th>
<th>Lika</th>
<th>LILA</th>
<th>BB/U</th>
<th>TB/U</th>
<th>BB/TB</th>
<th>IMT/U</th>
<th>Vit A</th>
<th>Cacing</th>
<th>ASI</th>
<th>Keterangan</th> <!-- TAMBAHAN -->
<th class="text-center">Aksi</th>
</tr>
</thead>
<tbody>

<?php if($riwayat_tabel): foreach($riwayat_tabel as $row): ?>

<?php
$tgl_periksa = new DateTime($row['tgl_periksa']);
$today = new DateTime();
$selisih_hari = $today->diff($tgl_periksa)->days;
$boleh_edit = $selisih_hari <= 14;
?>

<tr>
<td class="fw-bold"><?= date('d/m/y', strtotime($row['tgl_periksa'])) ?></td>
<td class="text-primary fw-bold"><?= $row['bb'] ?></td>
<td><?= $row['tb'] ?></td>
<td><?= $row['lika'] ?></td>
<td><?= $row['lila'] ?: '-' ?></td>

<td>
<?php
$s = $row['z_score_bbu'];
if ($s == 'Normal') $bg='success';
elseif ($s == 'BB Sangat Kurang') $bg='danger';
else $bg='warning';
echo "<span class='badge bg-$bg'>$s</span>";
?>
</td>

<td>
<?php
$s = $row['status_stunting'];
if ($s == 'Normal') $bg='success';
elseif ($s == 'Sangat Pendek') $bg='danger';
else $bg='warning';
echo "<span class='badge bg-$bg'>$s</span>";
?>
</td>

<td>
<?php
$s = $row['status_bbtb'];
if ($s == 'Gizi Baik') $bg='success';
elseif ($s == 'Gizi Buruk' || $s=='Obesitas') $bg='danger';
else $bg='warning';
echo "<span class='badge bg-$bg'>$s</span>";
?>
</td>

<td>
<?php
$s = $row['status_imtu'];
if ($s == 'Gizi Baik') $bg='success';
elseif ($s == 'Gizi Buruk' || $s=='Obesitas') $bg='danger';
else $bg='warning';
echo "<span class='badge bg-$bg'>$s</span>";
?>
</td>

<td><?= $row['vit_a'] ?></td>
<td><?= $row['obat_cacing'] ?></td>
<td><?= $row['asi_eksklusif'] ?></td>

<!-- KOLOM KETERANGAN -->
<td><?= htmlspecialchars($row['keterangan'] ?: '-') ?></td>

<td class="text-center">
<?php if($boleh_edit): ?>
    <a href="balita_edit_periksa.php?id_periksa=<?= $row['id_periksa_balita'] ?>&id_balita=<?= $id_balita ?>" 
       class="text-warning me-2">
       <i class="fa fa-edit"></i>
    </a>
<?php else: ?>
    <span class="text-secondary me-2" 
          onclick="alert('Edit hanya bisa dilakukan maksimal 14 hari setelah tanggal pemeriksaan.')"
          style="cursor:not-allowed;">
        <i class="fa fa-edit"></i>
    </span>
<?php endif; ?>
<a href="balita_hapus_periksa.php?id_periksa=<?= $row['id_periksa_balita'] ?>&id_balita=<?= $id_balita ?>" class="text-danger" onclick="return confirm('Hapus?')"><i class="fa fa-trash"></i></a>
</td>

</tr>
<?php endforeach; else: ?>
<tr><td colspan="14" class="text-center py-4 text-muted">Belum ada data pemeriksaan</td></tr>
<?php endif; ?>

</tbody>
</table>
</div>
</div>
</div>

</div>

<!-- SCRIPT GRAFIK LENGKAP -->
<script>
document.addEventListener("DOMContentLoaded", function() {

    const labels = <?= json_encode($labels) ?>;

    const dataSets = {
        bbu: {
            nilai: <?= json_encode($bb_values) ?>,
            z: <?= json_encode($z_bbu_values) ?>,
            status: <?= json_encode($status_bbu) ?>,
            satuan: "kg",
            yTitle: "Berat Badan (kg)"
        },
        tbu: {
            nilai: <?= json_encode($tb_values) ?>,
            z: <?= json_encode($z_tbu_values) ?>,
            status: <?= json_encode($status_tbu) ?>,
            satuan: "cm",
            yTitle: "Tinggi Badan (cm)"
        },
        bbtb: {
            nilai: <?= json_encode($bb_values) ?>,
            z: <?= json_encode($z_bbtb_values) ?>,
            status: <?= json_encode($status_bbtb) ?>,
            satuan: "kg",
            yTitle: "Berat Badan (kg)"
        }
    };

    const grafikList = ["bbu","tbu","bbtb"];
    let grafikIndex = 0;
    let currentType = grafikList[grafikIndex];

    const judulMap = {
        bbu:{
            title:"BB/U (Berat Badan Menurut Umur)",
            sub:"Deteksi gizi kurang & berat badan"
        },
        tbu:{
            title:"TB/U (Status Stunting)",
            sub:"Deteksi pendek & sangat pendek"
        },
        bbtb:{
            title:"BB/TB (Status Gizi)",
            sub:"Deteksi kurus, normal & obesitas"
        }
    };

    const zonePlugin = {
        id: 'zoneBackground',
        beforeDraw(chart) {
            const {ctx, chartArea:{top,bottom,left,right}, scales:{y1}} = chart;
            if (!y1) return;

            ctx.save();

            function zone(min, max, color){
                const yMin = y1.getPixelForValue(min);
                const yMax = y1.getPixelForValue(max);
                ctx.fillStyle = color;
                ctx.fillRect(left, yMax, right-left, yMin-yMax);
            }

            zone(-5,-3,'rgba(220,53,69,0.40)');
            zone(-3,-2,'rgba(255,193,7,0.40)');
            zone(-2,2,'rgba(25,135,84,0.40)');
            zone(2,3,'rgba(255,193,7,0.40)');
            zone(3,5,'rgba(220,53,69,0.40)');

            ctx.restore();
        }
    };

    const ctx = document.getElementById('chartPertumbuhan').getContext('2d');

    const chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: "Nilai",
                    data: dataSets[currentType].nilai,
                    borderColor: '#0d6efd',
                    borderWidth: 1,
                    tension: 0.3,
                    yAxisID: 'y'
                },
                {
                    label: "Z-Score",
                    data: dataSets[currentType].z,
                    borderColor: '#6f42c1',
                    borderWidth: 3,
                    tension: 0.3,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            events: ['click'],
            interaction: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                y: {
                    type: 'linear',
                    position: 'left',
                    title: { 
                        display: true, 
                        text: dataSets[currentType].yTitle 
                    }
                },
                y1: {
                    type: 'linear',
                    position: 'right',
                    min: -5,
                    max: 5,
                    grid: { drawOnChartArea: false },
                    title: { 
                        display: true, 
                        text: 'Z-Score WHO' 
                    }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    enabled: true,
                    callbacks: {
                        label: function(context){
                            const i = context.dataIndex;
                            return [
                                "Nilai: " + dataSets[currentType].nilai[i] + " " + dataSets[currentType].satuan,
                                "Z-Score: " + dataSets[currentType].z[i],
                                "Status: " + dataSets[currentType].status[i]
                            ];
                        }
                    }
                }
            }
        },
        plugins: [zonePlugin]
    });

   function updateChart(direction=1){

    const animated = document.getElementById("animatedArea");

    animated.style.opacity="0";
    animated.style.transform=`translateX(${direction*-15}px)`;

    setTimeout(()=>{

        currentType = grafikList[grafikIndex];

        chart.data.datasets[0].data = dataSets[currentType].nilai;
        chart.data.datasets[1].data = dataSets[currentType].z;
        chart.options.scales.y.title.text = dataSets[currentType].yTitle;

        chart.update();

        document.getElementById("judulGrafik").innerText = judulMap[currentType].title;
        document.getElementById("subJudulGrafik").innerText = judulMap[currentType].sub;

        document.querySelectorAll(".dot").forEach((d,i)=>{
            d.classList.toggle("active", i===grafikIndex);
        });

        animated.style.transform=`translateX(${direction*15}px)`;

        setTimeout(()=>{
            animated.style.opacity="1";
            animated.style.transform="translateX(0)";
        },50);

    },150);
}

    // SWIPE
    let startX = 0;
    const swipeArea = document.querySelector(".card-custom.mb-2");

    swipeArea.addEventListener("touchstart", e=>{
        startX = e.touches[0].clientX;
    });

    swipeArea.addEventListener("touchend", e=>{
        handleSwipe(e.changedTouches[0].clientX);
    });

    swipeArea.addEventListener("mousedown", e=>{
        startX = e.clientX;
    });

    swipeArea.addEventListener("mouseup", e=>{
        handleSwipe(e.clientX);
    });

    function handleSwipe(endX){
        let diff = endX - startX;
        if(Math.abs(diff) < 50) return;

        if(diff < 0){
            grafikIndex = (grafikIndex + 1) % 3;
        }else{
            grafikIndex = (grafikIndex - 1 + 3) % 3;
        }

        updateChart(diff < 0 ? 1 : -1);
    }

});
</script>

</body>
</html>