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

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

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

$stmt = $pdo->prepare("SELECT * FROM pemeriksaan_balita WHERE id_periksa_balita = ?");
$stmt->execute([$id_periksa]);
$periksa = $stmt->fetch();

$stmt_b = $pdo->prepare("SELECT * FROM balita WHERE id_balita = ?");
$stmt_b->execute([$id_balita]);
$balita = $stmt_b->fetch();

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

// FUNGSI HITUNG STATUS GIZI SESUAI PERMENKES NO 2 TAHUN 2020
function klasifikasi_gizi($tipe, $nilai, $ref, $bb = null, $tb = null) {
    if (!$ref) return "-";

    if ($tipe == 'bbu') {
        if ($nilai < $ref['min3sd']) return "BB Sangat Kurang";
        if ($nilai < $ref['min2sd']) return "BB Kurang";
        if ($nilai <= $ref['plus1sd']) return "Normal";
        return "Resiko BB Lebih";
    } 
    elseif ($tipe == 'tbu') {
        if ($nilai < $ref['min3sd']) return "Sangat Pendek";
        if ($nilai < $ref['min2sd']) return "Pendek";
        if ($nilai <= $ref['plus3sd']) return "Normal";
        return "Tinggi";
    } 
elseif ($tipe == 'bbtb' || $tipe == 'imtu') {

    if ($tipe == 'imtu') {
        if (!$bb || !$tb) return "-";
        $nilai = $bb / pow(($tb / 100), 2);
    }

    if ($nilai < $ref['min3sd']) return "Gizi Buruk";
    if ($nilai < $ref['min2sd']) return "Gizi Kurang";
    if ($nilai > $ref['plus3sd']) return "Obesitas";
    if ($nilai > $ref['plus2sd']) return "Gizi Lebih";
    if ($nilai > $ref['plus1sd']) return "Resiko Gizi Lebih";
    return "Gizi Baik";
}

    return "-";
}

function hitungStatusGizi($pdo, $nilai, $bb, $tb, $tgl_periksa, $tgl_lahir, $jk, $tipe) {

    $lahir = new DateTime($tgl_lahir);
    $periksa = new DateTime($tgl_periksa);
    $usia_bulan = ($periksa->diff($lahir)->y * 12) + $periksa->diff($lahir)->m;
    if ($usia_bulan > 60) $usia_bulan = 60;

    if ($tipe == 'bbu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$jk, $usia_bulan]);

    } elseif ($tipe == 'tbu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_tbu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$jk, $usia_bulan]);

    } elseif ($tipe == 'bbtb') {
        if ($usia_bulan <= 24) {
            $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbpb WHERE jenis_kelamin=? AND panjang_badan=? LIMIT 1");
            $stmt->execute([$jk, round($tb)]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbtb WHERE jenis_kelamin=? AND tinggi_badan=? LIMIT 1");
            $stmt->execute([$jk, round($tb)]);
        }

    } elseif ($tipe == 'imtu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_imtu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$jk, $usia_bulan]);
    }

    $ref = $stmt->fetch();
    return klasifikasi_gizi($tipe, $nilai, $ref, $bb, $tb);
}

function hitungZScore($nilai, $ref) {
    if (!$ref) return null;

    $median = $ref['median'];

    if ($nilai == $median) return 0;

    if ($nilai < $median) {

        if ($nilai >= $ref['min1sd']) {
            return round(-1 * ($median - $nilai) / ($median - $ref['min1sd']), 2);
        }
        elseif ($nilai >= $ref['min2sd']) {
            return round(-1 - ($ref['min1sd'] - $nilai) / ($ref['min1sd'] - $ref['min2sd']), 2);
        }
        elseif ($nilai >= $ref['min3sd']) {
            return round(-2 - ($ref['min2sd'] - $nilai) / ($ref['min2sd'] - $ref['min3sd']), 2);
        }
        else {
            return round(-3 - ($ref['min3sd'] - $nilai) / ($ref['min2sd'] - $ref['min3sd']), 2);
        }
    } else {

        if ($nilai <= $ref['plus1sd']) {
            return round(($nilai - $median) / ($ref['plus1sd'] - $median), 2);
        }
        elseif ($nilai <= $ref['plus2sd']) {
            return round(1 + ($nilai - $ref['plus1sd']) / ($ref['plus2sd'] - $ref['plus1sd']), 2);
        }
        elseif ($nilai <= $ref['plus3sd']) {
            return round(2 + ($nilai - $ref['plus2sd']) / ($ref['plus3sd'] - $ref['plus2sd']), 2);
        }
        else {
            return round(3 + ($nilai - $ref['plus3sd']) / ($ref['plus3sd'] - $ref['plus2sd']), 2);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tgl_periksa = $_POST['tgl_periksa'];
    $bb = (float)$_POST['bb'];
    $tb = (float)$_POST['tb'];
    
    // Hitung IMT untuk status IMT/U
    $status_bbu  = hitungStatusGizi($pdo, $bb, $bb, $tb, $tgl_periksa, $balita['tgl_lahir'], $balita['jenis_kelamin'], 'bbu');
$status_tbu  = hitungStatusGizi($pdo, $tb, $bb, $tb, $tgl_periksa, $balita['tgl_lahir'], $balita['jenis_kelamin'], 'tbu');
$status_bbtb = hitungStatusGizi($pdo, $bb, $bb, $tb, $tgl_periksa, $balita['tgl_lahir'], $balita['jenis_kelamin'], 'bbtb');
$status_imtu = hitungStatusGizi($pdo, 0,  $bb, $tb, $tgl_periksa, $balita['tgl_lahir'], $balita['jenis_kelamin'], 'imtu');

function ambilRef($pdo, $balita, $tgl_periksa, $tb, $tipe) {

    $lahir = new DateTime($balita['tgl_lahir']);
    $periksa = new DateTime($tgl_periksa);
    $usia_bulan = ($periksa->diff($lahir)->y * 12) + $periksa->diff($lahir)->m;
    if ($usia_bulan > 60) $usia_bulan = 60;

    if ($tipe == 'bbu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$balita['jenis_kelamin'], $usia_bulan]);

    } elseif ($tipe == 'tbu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_tbu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$balita['jenis_kelamin'], $usia_bulan]);

    } elseif ($tipe == 'bbtb') {
        if ($usia_bulan <= 24) {
            $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbpb WHERE jenis_kelamin=? AND panjang_badan=? LIMIT 1");
            $stmt->execute([$balita['jenis_kelamin'], round($tb)]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbtb WHERE jenis_kelamin=? AND tinggi_badan=? LIMIT 1");
            $stmt->execute([$balita['jenis_kelamin'], round($tb)]);
        }

    } elseif ($tipe == 'imtu') {
        $stmt = $pdo->prepare("SELECT * FROM ref_zscore_imtu WHERE jenis_kelamin=? AND umur_bulan=? LIMIT 1");
        $stmt->execute([$balita['jenis_kelamin'], $usia_bulan]);
    }

    return $stmt->fetch();
}

$ref_bbu  = ambilRef($pdo, $balita, $tgl_periksa, $tb, 'bbu');
$ref_tbu  = ambilRef($pdo, $balita, $tgl_periksa, $tb, 'tbu');
$ref_bbtb = ambilRef($pdo, $balita, $tgl_periksa, $tb, 'bbtb');
$ref_imtu = ambilRef($pdo, $balita, $tgl_periksa, $tb, 'imtu');

$z_bbu  = hitungZScore($bb, $ref_bbu);
$z_tbu  = hitungZScore($tb, $ref_tbu);
$z_bbtb = hitungZScore($bb, $ref_bbtb);

$imt = $bb / pow(($tb / 100), 2);
$z_imtu = hitungZScore($imt, $ref_imtu);

    $sql = "UPDATE pemeriksaan_balita SET 
        tgl_periksa = ?, bb = ?, tb = ?, lika = ?, lila = ?, 
        vit_a = ?, obat_cacing = ?, imunisasi = ?, asi_eksklusif = ?, keterangan = ?,
        z_score_bbu = ?, status_stunting = ?, status_bbtb = ?, status_imtu = ?,
        z_bbu = ?, z_tbu = ?, z_bbtb = ?, z_imtu = ?
        WHERE id_periksa_balita = ?";

    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
    $tgl_periksa, $bb, $tb, $_POST['lika'], $_POST['lila'], 
    $_POST['vit_a'], $_POST['obat_cacing'], $_POST['imunisasi'], 
    $_POST['asi_eksklusif'], $_POST['keterangan'],
    $status_bbu, $status_tbu, $status_bbtb, $status_imtu,
    $z_bbu, $z_tbu, $z_bbtb, $z_imtu,
    $id_periksa
    ]);


    header("Location: balita_detail.php?id=$id_balita&msg=updated");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Pemeriksaan</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.0.0/css/all.min.css">
    <style>
        body { background-color: #f4f7f6; }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold mb-0 text-success">Edit Data Penimbangan</h4>
        <a href="balita_detail.php?id=<?= $id_balita ?>" class="btn btn-outline-secondary btn-sm">Batal</a>
    </div>

    <div class="card">
        <div class="card-body p-4">
            <div class="mb-4">
                <h6 class="text-muted mb-1">Nama Balita</h6>
                <h5 class="fw-bold"><?= htmlspecialchars($balita['nama_balita']) ?></h5>
            </div>

            <form method="POST">
                <div class="mb-3">
                    <label class="form-label">Tanggal Periksa</label>
                    <input type="date" name="tgl_periksa" class="form-control" value="<?= $periksa['tgl_periksa'] ?>" required>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-6">
                        <label class="form-label">Berat Badan (kg)</label>
                        <input type="number" step="0.01" name="bb" class="form-control" value="<?= $periksa['bb'] ?>" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label">Tinggi Badan (cm)</label>
                        <input type="number" step="0.1" name="tb" class="form-control" value="<?= $periksa['tb'] ?>" required>
                    </div>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-6">
                        <label class="form-label">Lingkar Kepala (cm)</label>
                        <input type="number" step="0.1" name="lika" class="form-control" value="<?= $periksa['lika'] ?>">
                    </div>
                    <div class="col-6">
                        <label class="form-label">Lingkar Lengan (cm)</label>
                        <input type="number" step="0.1" name="lila" class="form-control" value="<?= $periksa['lila'] ?>">
                    </div>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-6">
                        <label class="form-label">Vitamin A</label>
                        <select name="vit_a" class="form-select">
                            <option value="Tidak" <?= $periksa['vit_a'] == 'Tidak' ? 'selected' : '' ?>>Tidak</option>
                            <option value="Ya" <?= $periksa['vit_a'] == 'Ya' ? 'selected' : '' ?>>Ya</option>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label">Obat Cacing</label>
                        <select name="obat_cacing" class="form-select">
                            <option value="Tidak" <?= $periksa['obat_cacing'] == 'Tidak' ? 'selected' : '' ?>>Tidak</option>
                            <option value="Ya" <?= $periksa['obat_cacing'] == 'Ya' ? 'selected' : '' ?>>Ya</option>
                        </select>
                    </div>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-6">
                        <label class="form-label">Imunisasi</label>
                        <input type="text" name="imunisasi" class="form-control" value="<?= htmlspecialchars($periksa['imunisasi']) ?>" placeholder="Contoh: DPT-HB-HIB 3">
                    </div>
                    <div class="col-6">
                        <label class="form-label">ASI Eksklusif</label>
                        <select name="asi_eksklusif" class="form-select">
                            <option value="Ya" <?= $periksa['asi_eksklusif'] == 'Ya' ? 'selected' : '' ?>>Ya</option>
                            <option value="Tidak" <?= $periksa['asi_eksklusif'] == 'Tidak' ? 'selected' : '' ?>>Tidak</option>
                        </select>
                    </div>
                </div>
                <div class="mb-4">
                    <label class="form-label">Keterangan Tambahan</label>
                    <textarea name="keterangan" class="form-control" rows="2" placeholder="Contoh: Anak aktif, makan lahap"><?= htmlspecialchars($periksa['keterangan']) ?></textarea>
                </div>
                <button type="submit" class="btn btn-success w-100 py-3 fw-bold shadow">SIMPAN PERUBAHAN DATA</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>