<?php
if (!defined('MODE_PDF')) {
    session_start();
}
require_once '../config.php';

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

$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');
$id_posyandu = $_SESSION['posyandu'];

$nama_bulan = ["01"=>"Januari","02"=>"Februari","03"=>"Maret","04"=>"April","05"=>"Mei","06"=>"Juni","07"=>"Juli","08"=>"Agustus","09"=>"September","10"=>"Oktober","11"=>"November","12"=>"Desember"];

// Ambil Nama Posyandu
$stmt_p = $pdo->prepare("SELECT nama_posyandu FROM posyandu WHERE id_posyandu = ?");
$stmt_p->execute([$id_posyandu]);
$posyandu = $stmt_p->fetch();

// Total balita terdaftar (KMS)
$stmt_all = $pdo->prepare("SELECT id_balita, jenis_kelamin, tgl_lahir FROM balita WHERE id_posyandu = ?");
$stmt_all->execute([$id_posyandu]);
$balita_terdaftar = $stmt_all->fetchAll();

// AMBIL DATA PEMERIKSAAN BULAN INI
$query = "SELECT b.*, p.* FROM balita b 
          JOIN pemeriksaan_balita p ON b.id_balita = p.id_balita 
          WHERE b.id_posyandu = ? 
          AND MONTH(p.tgl_periksa) = ? 
          AND YEAR(p.tgl_periksa) = ? 
          ORDER BY TIMESTAMPDIFF(MONTH, b.tgl_lahir, p.tgl_periksa) DESC";
$stmt = $pdo->prepare($query);
$stmt->execute([$id_posyandu, $bulan, $tahun]);
$data_pemeriksaan = $stmt->fetchAll();

// Kelompok umur baru
$kategori_umur = [
    '0-5'   => [0,5],
    '6-11'  => [6,11],
    '12-23' => [12,23],
    '24-35' => [24,35],
    '36-60' => [36,60],
];

// Inisialisasi rekap
$keys = ['S','D','N','T','T2','O','B','A','C','I','OB','GL','RGL','GB','GK','GBR','BGM'];
$rekap = [];
foreach ($keys as $k) {
    foreach ($kategori_umur as $ku => $range) {
        $rekap[$k][$ku]['L'] = 0;
        $rekap[$k][$ku]['P'] = 0;
    }
}

function kbm_min_naik($jk, $usia_bulan) {
    $usia_bulan = (int)$usia_bulan;
    if ($usia_bulan < 1) $usia_bulan = 1;
    if ($usia_bulan > 60) $usia_bulan = 60;

    if ($jk == 'L') {
        if ($usia_bulan == 1) return 0.8;
        if ($usia_bulan == 2) return 0.9;
        if ($usia_bulan == 3) return 0.8;
        if ($usia_bulan == 4) return 0.6;
        if ($usia_bulan == 5) return 0.5;
        if ($usia_bulan == 6 || $usia_bulan == 7) return 0.4;
        if ($usia_bulan >= 8 && $usia_bulan <= 11) return 0.3;
        return 0.2;
    } else {
        if ($usia_bulan == 1) return 0.8;
        if ($usia_bulan == 2) return 0.9;
        if ($usia_bulan == 3) return 0.8;
        if ($usia_bulan == 4) return 0.6;
        if ($usia_bulan == 5) return 0.5;
        if ($usia_bulan == 6) return 0.4;
        if ($usia_bulan >= 7 && $usia_bulan <= 10) return 0.3;
        return 0.2;
    }
}
function get_kategori_umur($usia_bulan, $kategori_umur) {
    foreach ($kategori_umur as $k => $r) {
        if ($usia_bulan >= $r[0] && $usia_bulan <= $r[1]) {
            return $k;
        }
    }
    return null;
}

// HITUNG S = Balita terdaftar KMS
foreach ($balita_terdaftar as $b) {
    $usia = (new DateTime())->diff(new DateTime($b['tgl_lahir']));
    $usia_bulan = ($usia->y * 12) + $usia->m;
    $jk = $b['jenis_kelamin'] == 'L' ? 'L' : 'P';

    foreach ($kategori_umur as $k => $r) {
        if ($usia_bulan >= $r[0] && $usia_bulan <= $r[1]) {
            $rekap['S'][$k][$jk]++;
            break;
        }
    }
}

$hasil_status = [];

foreach ($data_pemeriksaan as $row) {

    $tgl_skrg = new DateTime($row['tgl_periksa']);
    $lahir = new DateTime($row['tgl_lahir']);
    $usia = ($tgl_skrg->diff($lahir)->y * 12) + $tgl_skrg->diff($lahir)->m;
    $jk = ($row['jenis_kelamin'] == 'L') ? 'L' : 'P';

    $kat = get_kategori_umur($usia, $kategori_umur);
    if (!$kat) continue;

    // D = ditimbang
    $rekap['D'][$kat][$jk]++;

    // Ambil BB bulan lalu
    $tgl_lalu = (clone $tgl_skrg)->modify('-1 month');
    $stmt_prev = $pdo->prepare("SELECT bb FROM pemeriksaan_balita 
        WHERE id_balita = ? AND MONTH(tgl_periksa) = ? AND YEAR(tgl_periksa) = ? LIMIT 1");
    $stmt_prev->execute([$row['id_balita'], $tgl_lalu->format('m'), $tgl_lalu->format('Y')]);
    $prev = $stmt_prev->fetch();

    // Ambil BB 2 bulan lalu
    $tgl_2bln = (clone $tgl_skrg)->modify('-2 month');
    $stmt_prev2 = $pdo->prepare("SELECT bb FROM pemeriksaan_balita 
        WHERE id_balita = ? AND MONTH(tgl_periksa) = ? AND YEAR(tgl_periksa) = ? LIMIT 1");
    $stmt_prev2->execute([$row['id_balita'], $tgl_2bln->format('m'), $tgl_2bln->format('Y')]);
    $prev2 = $stmt_prev2->fetch();

    $status_nt = '-';

    if (!$prev && !$prev2) {
        $rekap['B'][$kat][$jk]++;
        $status_nt = 'B';
    } elseif (!$prev && $prev2) {
        $rekap['O'][$kat][$jk]++;
        $status_nt = 'O';
    } else {
        $kenaikan = $row['bb'] - $prev['bb'];
        $kbm = kbm_min_naik($jk, $usia);

        if ($kenaikan >= $kbm) {
            $rekap['N'][$kat][$jk]++;
            $status_nt = 'N';
        } else {
            $rekap['T'][$kat][$jk]++;
            $status_nt = 'T';

            if ($prev2) {
                $kenaikan2 = $prev['bb'] - $prev2['bb'];
                if ($kenaikan2 < $kbm) {
                    $rekap['T2'][$kat][$jk]++;
                    $status_nt = 'T2';
                }
            }
        }
    }

    $hasil_status[$row['id_balita']] = $status_nt;

    if ($row['vit_a'] == 'Ya') $rekap['A'][$kat][$jk]++;
    if ($row['obat_cacing'] == 'Ya') $rekap['C'][$kat][$jk]++;
    if (!empty($row['imunisasi']) && $row['imunisasi'] != '-') $rekap['I'][$kat][$jk]++;

    if ($row['status_bbtb'] == 'Obesitas') $rekap['OB'][$kat][$jk]++;
    if ($row['status_bbtb'] == 'Gizi Lebih') $rekap['GL'][$kat][$jk]++;
    if ($row['status_bbtb'] == 'Resiko Gizi Lebih') $rekap['RGL'][$kat][$jk]++; 
    if ($row['status_bbtb'] == 'Gizi Baik') $rekap['GB'][$kat][$jk]++;
    if ($row['status_bbtb'] == 'Gizi Kurang') $rekap['GK'][$kat][$jk]++;
    if ($row['status_bbtb'] == 'Gizi Buruk') $rekap['GBR'][$kat][$jk]++;
    if ($row['z_score_bbu'] == 'BB Sangat Kurang') $rekap['BGM'][$kat][$jk]++;
}

?>

<!-- ======= TAMPILAN HTML TETAP SAMA, DITAMBAH 1 TABEL ASI EKSKLUSIF DI BAWAH ======= -->

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Laporan Posyandu</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background:#f4f7f6; font-size: 11px; color: #333; }
        .card-laporan { background: white; border-radius: 8px; padding: 10px; margin-top: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .scroll-area { overflow-x: auto; -webkit-overflow-scrolling: touch; border: 1px solid #ddd; }
        table { width: 100%; border-collapse: collapse; background: white; }
        th { background: #0d6efd !important; color: white !important; border: 1px solid #dee2e6; padding: 8px 4px; text-align: center; white-space: nowrap; }
        td { border: 1px solid #dee2e6; padding: 6px 4px; text-align: center; }
        .text-start { text-align: left; }
        .bg-jumlah { background: #e9ecef; font-weight: bold; }
        .no-print { margin-bottom: 10px; }
        @media print { .no-print { display: none; } }
    </style>
</head>
<body>

<div class="container-fluid pb-5">
    <div class="card p-3 mt-2 no-print shadow-sm">
        <form method="GET" class="row g-2">
            <div class="col-6">
                <select name="bulan" class="form-select form-select-sm">
                    <?php foreach($nama_bulan as $k=>$v) echo "<option value='$k'".($k==$bulan?' selected':'').">$v</option>"; ?>
                </select>
            </div>
            <div class="col-6">
                <select name="tahun" class="form-select form-select-sm">
                    <?php for($i=2024; $i<=2026; $i++) echo "<option value='$i'".($i==$tahun?' selected':'').">$i</option>"; ?>
                </select>
            </div>
            <div class="col-12 mt-2 d-flex gap-1">
                <button type="submit" class="btn btn-primary btn-sm flex-fill fw-bold">TAMPILKAN</button>
                <a href="export_excel_balita.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="btn btn-success btn-sm flex-fill fw-bold">UNDUH EXCEL</a>
                <a href="laporan_pdf.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>" 
   target="_blank"
   class="btn btn-danger btn-sm flex-fill fw-bold">
   UNDUH PDF
</a>
            </div>
        </form>
    </div>

    <div id="area-laporan">
        <div class="text-center mt-3">
            <h6 class="mb-0 fw-bold">LAPORAN PENIMBANGAN BULANAN</h6>
            <p class="small text-muted">Posyandu: <?= strtoupper($posyandu['nama_posyandu'] ?? '-') ?> | <?=$nama_bulan[$bulan]?> <?=$tahun?></p>
        </div>

        <div class="card-laporan">
            <div class="scroll-area">
                <table>
                    <thead>
                        <tr>
                            <th rowspan="2">NO</th>
                            <th rowspan="2">TGL PERIKSA</th>
                            <th colspan="11">IDENTITAS BALITA</th>
                            <th colspan="6">HASIL PENIMBANGAN</th>
                            <th rowspan="2">ASI</th>
                            <th rowspan="2">VIT A</th>
                            <th rowspan="2">IMUNISASI</th>
                            <th rowspan="2">O. CACING</th>
                            <th colspan="4">INDEKS</th>
                        </tr>
                        <tr>
                            <th>ANAK KE</th><th>TGL LAHIR</th><th>JK</th><th>NIK</th><th>NAMA ANAK</th><th>BBL</th><th>PBL</th><th>NAMA IBU</th><th>RT</th><th>RW</th><th>DUSUN</th>
                            <th>USIA</th><th>BB</th><th>TB</th><th>LILA</th><th>LIKA</th><th>STATUS</th>
                            <th>BB/U</th><th>TB/U</th><th>BB/TB</th><th>IMT/U</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $n=1; foreach($data_pemeriksaan as $r): 
    $tgl_lahir   = new DateTime($r['tgl_lahir']);
    $tgl_periksa = new DateTime($r['tgl_periksa']);
    $diff        = $tgl_lahir->diff($tgl_periksa);
    $usia_bulan  = ($diff->y * 12) + $diff->m;
?>
                        <tr>
                            <td><?=$n++?></td>
                            <td nowrap><?=date('d/m/y', strtotime($r['tgl_periksa']))?></td>
                            <td><?=$r['anak_ke']?></td>
                            <td nowrap><?=date('d/m/y', strtotime($r['tgl_lahir']))?></td>
                            <td><?=$r['jenis_kelamin']?></td>
                            <td>'<?=$r['nik_balita']?></td>
                            <td class="text-start" nowrap><?=strtoupper($r['nama_balita'])?></td>
                            <td><?=$r['bb_lahir']?></td>
                            <td><?=$r['pb_lahir']?></td>
                            <td class="text-start" nowrap><?=$r['nama_ibu']?></td>
                            <td><?=$r['rt']?></td>
                            <td><?=$r['rw']?></td>
                            <td nowrap><?=$r['dusun']?></td>
                            <td><?=$usia_bulan?></td>
                            <td class="fw-bold"><?=$r['bb']?></td>
                            <td><?=$r['tb']?></td>
                            <td><?=$r['lila']?></td>
                            <td><?=$r['lika']?></td>
                            <td class="fw-bold text-primary">
                                <?=$hasil_status[$r['id_balita']] ?? '-'?>
                            </td>
                            <td><?=$r['asi_eksklusif']?></td>
                            <td><?=$r['vit_a']?></td>
                            <td nowrap><?=$r['imunisasi']?></td>
                            <td nowrap><?=$r['obat_cacing']?></td>
                            <td nowrap><?=$r['z_score_bbu']?></td>
                            <td nowrap><?=$r['status_stunting']?></td>
                            <td nowrap><?=$r['status_bbtb']?></td>
                            <td nowrap><?=$r['status_imtu']?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card-laporan mt-4">
    <h6 class="fw-bold mb-3">REKAPITULASI (S, D, N, T, T2, O, B, A, C, I)</h6>
    <div class="scroll-area">
        <table>
            <thead>
                <tr>
                    <th rowspan="2">URAIAN</th>
                    <th colspan="3">0-5 bln</th>
                    <th colspan="3">6-11 bln</th>
                    <th colspan="3">12-23 bln</th>
                    <th colspan="3">24-35 bln</th>
                    <th colspan="3">36-60 bln</th>
                    <th colspan="3">TOTAL</th>
                </tr>
                <tr>
                    <?php for($i=0;$i<6;$i++) echo "<th>L</th><th>P</th><th>J</th>"; ?>
                </tr>
            </thead>
            <tbody>
                <?php 
                $labels = [
                    'S'   => 'Balita Terdaftar KMS (S)',
                    'D'   => 'Semua Balita Ditimbang (D)',
                    'N'   => 'Balita Naik Timbangan (N)',
                    'T'   => 'Balita Tidak Naik Timbangan (T)',
                    'T2'  => 'Balita 2x Tidak Naik Berturut (T2)',
                    'O'   => 'Balita Bulan Lalu Tidak Hadir (O)',
                    'B'   => 'Balita Baru Pertama Timbang (B)',
                    'A'   => 'Mendapat Vitamin A (A)',
                    'C'   => 'Mendapat Obat Cacing (C)',
                    'I'   => 'Mendapat Imunisasi (I)',
                    'OB'  => 'Balita Obesitas (BB/TB)',
                    'GL'  => 'Balita Dengan Gizi Lebih (BB/TB)',
                    'RGL' => 'Balita Dengan Resiko Gizi Lebih (BB/TB)',
                    'GB'  => 'Balita Dengan Gizi Baik (BB/TB)',
                    'GK'  => 'Balita Dengan Gizi Kurang (BB/TB)',
                    'GBR' => 'Balita Dengan Gizi Buruk (BB/TB)',
                    'BGM' => 'Balita Bawah Garis Merah (BB/U Sangat Kurang)'
                ];

                foreach($labels as $kd=>$txt): 
                    $tL=0; $tP=0; 
                ?>
                <tr>
                    <td class="text-start fw-bold" nowrap style="padding-left:10px;"><?=$txt?></td>
                    <?php foreach($kategori_umur as $ku => $range): 
                        $l = $rekap[$kd][$ku]['L'] ?? 0; 
                        $p = $rekap[$kd][$ku]['P'] ?? 0;
                        $j = $l + $p;
                        $tL += $l; 
                        $tP += $p;
                    ?>
                        <td><?=$l?></td>
                        <td><?=$p?></td>
                        <td class="bg-jumlah"><?=$j?></td>
                    <?php endforeach; ?>
                    <td class="fw-bold"><?=$tL?></td>
                    <td class="fw-bold"><?=$tP?></td>
                    <td class="bg-primary text-white fw-bold"><?=($tL+$tP)?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
// =====================
// REKAP ASI EKSKLUSIF (FORMAT SESUAI EXCEL POSYANDU)
// =====================

$rekap_asi = [];
for ($i=1; $i<=6; $i++) {
    $rekap_asi[$i] = [
        'kel_L' => 0, 'kel_P' => 0,
        'asi_L' => 0, 'asi_P' => 0
    ];
}

foreach ($data_pemeriksaan as $row) {
    $tgl_skrg = new DateTime($row['tgl_periksa']);
    $lahir = new DateTime($row['tgl_lahir']);
    $usia_bulan = ($tgl_skrg->diff($lahir)->y * 12) + $tgl_skrg->diff($lahir)->m;

    if ($usia_bulan >= 0 && $usia_bulan <= 5) {
        $kelompok = $usia_bulan + 1; // 0–1 = 1, 1–2 = 2, dst
        $jk = ($row['jenis_kelamin'] == 'L') ? 'L' : 'P';

        if ($jk == 'L') $rekap_asi[$kelompok]['kel_L']++;
        else $rekap_asi[$kelompok]['kel_P']++;

        if ($row['asi_eksklusif'] == 'Ya') {
            if ($jk == 'L') $rekap_asi[$kelompok]['asi_L']++;
            else $rekap_asi[$kelompok]['asi_P']++;
        }
    }
}
?>

<!-- ================== TABEL ASI EKSKLUSIF (FINAL SESUAI EXCEL) ================== -->
<div class="card-laporan mt-4">
    <h6 class="fw-bold mb-3">DATA PEMBERIAN ASI EKSKLUSIF</h6>
    <div class="scroll-area">
        <table>
            <thead>
                <tr>
                    <th rowspan="2">NO</th>
                    <th rowspan="2">KELOMPOK UMUR</th>
                    <th colspan="3">JUMLAH</th>
                    <th rowspan="2">PEMBERIAN ASI</th>
                    <th colspan="3">JUMLAH</th>
                </tr>
                <tr>
                    <th>L</th><th>P</th><th>J</th>
                    <th>L</th><th>P</th><th>J</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $totalKelL = $totalKelP = $totalAsiL = $totalAsiP = 0;
                for ($i=1; $i<=6; $i++):
                    $kl = $rekap_asi[$i]['kel_L'];
                    $kp = $rekap_asi[$i]['kel_P'];
                    $kj = $kl + $kp;

                    $al = $rekap_asi[$i]['asi_L'];
                    $ap = $rekap_asi[$i]['asi_P'];
                    $aj = $al + $ap;

                    $totalKelL += $kl;
                    $totalKelP += $kp;
                    $totalAsiL += $al;
                    $totalAsiP += $ap;
                ?>
                <tr>
                    <td><?=$i?></td>
                    <td>Jumlah Bayi Umur <?=($i-1)?>–<?=$i?> Bulan</td>
                    <td><?=$kl?></td>
                    <td><?=$kp?></td>
                    <td class="bg-jumlah"><?=$kj?></td>
                    <td>Jumlah Bayi Umur <?=$i?> Bulan Hanya Diberi ASI</td>
                    <td><?=$al?></td>
                    <td><?=$ap?></td>
                    <td class="bg-jumlah"><?=$aj?></td>
                </tr>
                <?php endfor; ?>
                <tr class="bg-jumlah fw-bold">
                    <td colspan="2">JUMLAH</td>
                    <td><?=$totalKelL?></td>
                    <td><?=$totalKelP?></td>
                    <td><?=($totalKelL + $totalKelP)?></td>
                    <td>JUMLAH</td>
                    <td><?=$totalAsiL?></td>
                    <td><?=$totalAsiP?></td>
                    <td><?=($totalAsiL + $totalAsiP)?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>


</body>
</html>