<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once '../config.php';
if (!isset($_SESSION['role'])) { header("Location: ../login.php"); exit; }

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 "-";
}

/**
 * HITUNG STATUS GIZI (SAMA PERSIS DENGAN balita_tambah_periksa.php)
 */
function hitungStatus($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);
        }
    }
}

function ambilRef($pdo, $b, $tgl, $tb, $tipe) {

    $lahir = new DateTime($b['tgl_lahir']);
    $periksa = new DateTime($tgl);
    $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([$b['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([$b['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([$b['jenis_kelamin'], round($tb)]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM ref_zscore_bbtb WHERE jenis_kelamin=? AND tinggi_badan=? LIMIT 1");
            $stmt->execute([$b['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([$b['jenis_kelamin'], $usia_bulan]);
    }

    return $stmt->fetch();
}
 
if (isset($_POST['import_timbang'])) {

    $file = $_FILES['file_csv']['tmp_name'];
    if (!is_uploaded_file($file)) die("File upload gagal.");

    $content = file_get_contents($file);
    $content = str_replace(chr(239).chr(187).chr(191), '', $content);
    $separator = (strpos($content, ";") !== false) ? ";" : ",";

    $tmp = tmpfile();
    fwrite($tmp, $content);
    rewind($tmp);

    $flag = true;
    $ok = 0;
    $fail = 0;

    try {
        $pdo->beginTransaction();

        while (($d = fgetcsv($tmp, 2000, $separator)) !== false) {
            if ($flag) { $flag=false; continue; }

            $nik = preg_replace('/[^0-9]/', '', $d[0] ?? '');
            if (strlen($nik) != 16) { $fail++; continue; }

            $q = $pdo->prepare("SELECT id_balita, tgl_lahir, jenis_kelamin FROM balita WHERE nik_balita=? LIMIT 1");
            $q->execute([$nik]);
            $b = $q->fetch();
            if (!$b) { $fail++; continue; }

            $tgl = str_replace('/', '-', $d[1] ?? '');
            $p = explode('-', $tgl);
            $tgl = (strlen($p[0])==4) ? $tgl : "$p[2]-$p[1]-$p[0]";

            $bb = (float)str_replace(',', '.', $d[2] ?? 0);
            $tb = (float)str_replace(',', '.', $d[3] ?? 0);
            if ($bb <= 0 || $tb <= 0) { $fail++; continue; }

            $cek = $pdo->prepare("SELECT COUNT(*) FROM pemeriksaan_balita 
                                  WHERE id_balita=? AND MONTH(tgl_periksa)=MONTH(?) AND YEAR(tgl_periksa)=YEAR(?)");
            $cek->execute([$b['id_balita'], $tgl, $tgl]);
            if ($cek->fetchColumn() > 0) { $fail++; continue; }

            $status_bbu  = hitungStatus($pdo, $bb, $bb, $tb, $tgl, $b['tgl_lahir'], $b['jenis_kelamin'], 'bbu');
            $status_tbu  = hitungStatus($pdo, $tb, $bb, $tb, $tgl, $b['tgl_lahir'], $b['jenis_kelamin'], 'tbu');
            $status_bbtb = hitungStatus($pdo, $bb, $bb, $tb, $tgl, $b['tgl_lahir'], $b['jenis_kelamin'], 'bbtb');
            $status_imtu = hitungStatus($pdo, 0,  $bb, $tb, $tgl, $b['tgl_lahir'], $b['jenis_kelamin'], 'imtu');

$ref_bbu  = ambilRef($pdo, $b, $tgl, $tb, 'bbu');
$ref_tbu  = ambilRef($pdo, $b, $tgl, $tb, 'tbu');
$ref_bbtb = ambilRef($pdo, $b, $tgl, $tb, 'bbtb');
$ref_imtu = ambilRef($pdo, $b, $tgl, $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);

            $stmt = $pdo->prepare("INSERT INTO pemeriksaan_balita 
    (id_balita, tgl_periksa, bb, tb, lika, lila, vit_a, obat_cacing, imunisasi, asi_eksklusif,
     z_score_bbu, status_stunting, status_bbtb, status_imtu,
     z_bbu, z_tbu, z_bbtb, z_imtu, keterangan)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

            $stmt->execute([
    $b['id_balita'], $tgl, $bb, $tb,
    str_replace(',', '.', $d[4] ?? 0),
    str_replace(',', '.', $d[5] ?? 0),
    $d[6] ?? 'Tidak',
    $d[7] ?? 'Tidak',
    $d[8] ?? '',
    $d[9] ?? 'Tidak',
    $status_bbu,
    $status_tbu,
    $status_bbtb,
    $status_imtu,
    $z_bbu,
    $z_tbu,
    $z_bbtb,
    $z_imtu,
    $d[10] ?? ''
    ]);

            $ok++;
        }

        $pdo->commit();
        echo "<script>alert('IMPORT SELESAI! Berhasil: $ok | Gagal: $fail'); window.location='manage_pemeriksaan.php';</script>";

    } catch (Exception $e) {
        $pdo->rollBack();
        die("ERROR: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Import Timbangan Balita</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-5">
<div class="card mx-auto shadow" style="max-width:600px">
<div class="card-header bg-primary text-white fw-bold text-center">IMPORT PENIMBANGAN BALITA</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file_csv" class="form-control mb-3" accept=".csv" required>
<button name="import_timbang" class="btn btn-success w-100 fw-bold">IMPORT SEKARANG</button>
</form>
</div>
</div>
</div>
</body>
</html>
