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

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

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

$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"];
$list_posyandu = $pdo->query("SELECT * FROM posyandu ORDER BY nama_posyandu ASC")->fetchAll();

// --- 1. QUERY DATA (TIDAK BERUBAH) ---
$sql_filter = ($id_posyandu_filter !== 'semua') ? " AND b.id_posyandu = ?" : "";
$params = ($id_posyandu_filter !== 'semua') ? [$bulan, $tahun, $id_posyandu_filter] : [$bulan, $tahun];

$query = "SELECT b.*, p.*, pos.nama_posyandu 
          FROM balita b 
          JOIN pemeriksaan_balita p ON b.id_balita = p.id_balita 
          JOIN posyandu pos ON b.id_posyandu = pos.id_posyandu
          WHERE MONTH(p.tgl_periksa) = ? AND YEAR(p.tgl_periksa) = ? $sql_filter
          ORDER BY pos.nama_posyandu ASC, b.nama_balita ASC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$data_balita = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- 2. LOGIKA HITUNG ASLI (TIDAK DISENTUH) ---
$kategori_umur = ['0-5', '6-11', '12-23', '24-59'];
$rekap_labels = [
    'S' => 'Semua Balita Terdaftar (S)', 'N' => 'Balita Naik Timbangan (N)', 'T' => 'Balita Tdk Naik / Tetap (T)',
    'T2' => 'Balita 2x Tdk Naik (T2)', 'O' => 'Balita Baru (O)', 'B' => 'Balita Baru Pertama Timbang (B)',
    'A' => 'Balita Mendapat Vit A (A)', 'ASI' => 'Balita Mendapat ASI Eksklusif', 'I' => 'Balita Mendapat Imunisasi',
    'BBU_SK' => 'Status BB/U Sangat Kurang', 'BBU_K' => 'Status BB/U Kurang',
    'STUNT_SP' => 'Status TB/U Sangat Pendek (Stunting)', 'STUNT_P' => 'Status TB/U Pendek'
];

$rekap = [];
foreach(array_keys($rekap_labels) as $key) {
    foreach($kategori_umur as $kat) { $rekap[$key][$kat] = ['L'=>0, 'P'=>0]; }
}

$data_final = [];
foreach ($data_balita as $r) {
    $tgl_l = new DateTime($r['tgl_lahir']);
    $tgl_p = new DateTime($r['tgl_periksa']);
    $usia = ($tgl_p->diff($tgl_l)->y * 12) + $tgl_p->diff($tgl_l)->m;
    $kat_umur = ($usia <= 5) ? '0-5' : (($usia <= 11) ? '6-11' : (($usia <= 23) ? '12-23' : '24-59'));
    $jk = ($r['jenis_kelamin'] == 'L') ? 'L' : 'P';

    $stmt_h = $pdo->prepare("SELECT bb FROM pemeriksaan_balita WHERE id_balita=? AND tgl_periksa < ? ORDER BY tgl_periksa DESC LIMIT 2");
    $stmt_h->execute([$r['id_balita'], $r['tgl_periksa']]);
    $history = $stmt_h->fetchAll();
    
    if (count($history) == 0) { $st = ($usia == 0) ? "O" : "B"; } 
    else {
        $bb_lalu = $history[0]['bb'];
        if ($r['bb'] > $bb_lalu) { $st = "N"; } 
        else { 
            $st = "T"; 
            if (count($history) >= 2 && $bb_lalu <= $history[1]['bb']) { $st = "T2"; }
        }
    }

    $rekap['S'][$kat_umur][$jk]++;
    if(isset($rekap[$st])) $rekap[$st][$kat_umur][$jk]++;
    if(($r['vit_a']??'') == 'Ya') $rekap['A'][$kat_umur][$jk]++;
    if(($r['asi_eksklusif']??'') == 'Ya') $rekap['ASI'][$kat_umur][$jk]++;
    if(!empty($r['imunisasi']) && $r['imunisasi'] != '-') $rekap['I'][$kat_umur][$jk]++;

    $bbu = $r['z_score_bbu'] ?? '';
    $tbu = $r['status_stunting'] ?? '';
    if(stripos($bbu, 'Sangat Kurang') !== false) $rekap['BBU_SK'][$kat_umur][$jk]++;
    elseif(stripos($bbu, 'Kurang') !== false) $rekap['BBU_K'][$kat_umur][$jk]++;
    if(stripos($tbu, 'Sangat Pendek') !== false) $rekap['STUNT_SP'][$kat_umur][$jk]++;
    elseif(stripos($tbu, 'Pendek') !== false && stripos($tbu, 'Sangat') === false) $rekap['STUNT_P'][$kat_umur][$jk]++;

    $r['usia_hitung'] = $usia;
    $r['st_timbang'] = $st;
    $data_final[] = $r;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rekap Balita Lengkap</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">
    <style>
        body { background: #f4f7f6; font-family: 'Segoe UI', sans-serif; font-size: 9px; }
        .main-content { margin-left: 250px; padding: 20px; transition: 0.3s; }
        th { background: #0d6efd !important; color: white !important; text-align: center; vertical-align: middle; border: 1px solid #dee2e6; }
        td { border: 1px solid #dee2e6; padding: 4px; text-align: center; vertical-align: middle; white-space: nowrap; }
        @media (max-width: 768px) { .main-content { margin-left: 0; padding: 10px; } }
    </style>
</head>
<body>
    <?php include 'sidebar.php'; ?>
    <div class="main-content">
        <div class="container-fluid">
            <h4 class="fw-bold mb-4">REKAPITULASI DATA BALITA</h4>

            <div class="card p-3 mb-4 border-0 shadow-sm rounded-3">
                <form method="GET" class="row g-2 align-items-end">
                    <div class="col-md-3"><label class="small fw-bold">Bulan</label><select name="bulan" class="form-select form-select-sm"><?php foreach($nama_bulan as $m=>$n) echo "<option value='$m' ".($bulan==$m?'selected':'').">$n</option>"; ?></select></div>
                    <div class="col-md-2"><label class="small fw-bold">Tahun</label><input type="number" name="tahun" class="form-control form-select-sm" value="<?=$tahun?>"></div>
                    <div class="col-md-4"><label class="small fw-bold">Posyandu</label><select name="id_posyandu" class="form-select form-select-sm"><option value="semua">Semua Posyandu</option><?php foreach($list_posyandu as $p) echo "<option value='".$p['id_posyandu']."' ".($id_posyandu_filter==$p['id_posyandu']?'selected':'').">".$p['nama_posyandu']."</option>"; ?></select></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-sm btn-primary w-100 shadow-none"><i class="fa fa-filter me-2"></i>Filter</button></div>
                </form>
            </div>
           
            <div class="mb-3">
                <a href="export_balita.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>&id_posyandu=<?=$id_posyandu_filter?>" class="btn btn-sm btn-outline-secondary shadow-none">
                    <i class="fa fa-file-excel me-2 text-success"></i>Export ke Excel (.xlsx)
                </a>
            </div>
            
            <div class="card border-0 shadow-sm rounded-3 mb-4">
                <div class="card-body p-2">
                    <div class="table-responsive">
                        <table class="table table-bordered align-middle">
                            <thead>
                                <tr>
                                    <th rowspan="2">NO</th><th rowspan="2">POSYANDU</th>
                                    <th colspan="11">IDENTITAS BALITA</th>
                                    <th colspan="7">HASIL PENIMBANGAN</th>
                                    <th rowspan="2">N/T/O/B</th><th colspan="2">INDEKS GIZI</th>
                                </tr>
                                <tr>
                                    <th>ANAK KE</th><th>NAMA ANAK</th><th>NIK</th><th>TGL LAHIR</th><th>L/P</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>VIT A</th><th>ASI</th><th>IMU</th><th>BB/U</th><th>TB/U</th>
                                </tr>
                            </thead>
                            <tbody>
    <?php $n=1; foreach($data_final as $r): ?>
    <tr>
        <td><?=$n++?></td>
        <td class="text-primary fw-bold"><?=$r['nama_posyandu']?></td>
        
        <td><?=$r['anak_ke'] ?? '-'?></td>
        <td class="text-start fw-bold"><?=strtoupper($r['nama_balita'])?></td>
        <td>'<?=$r['nik_balita']?></td>
        <td><?=$r['tgl_lahir']?></td>
        <td><?=$r['jenis_kelamin']?></td>
        
        <td><?=$r['bb_lahir'] ?? '-'?></td> 
        <td><?=$r['pb_lahir'] ?? '-'?></td>
        
        <td><?=$r['nama_ibu']?></td>
        <td><?=$r['rt']?></td>
        <td><?=$r['rw']?></td>
        <td><?=$r['dusun']?></td>

        <td class="fw-bold text-success"><?=$r['usia_hitung']?></td>
        <td><?=$r['bb']?></td>
        <td><?=$r['tb']?></td>
        <td><?=$r['lila']?></td>
        <td><?=$r['vit_a']?></td>
        <td><?=$r['asi_eksklusif']?></td>
        <td><?=$r['imunisasi']?></td>
        
        <td class="fw-bold"><?=$r['st_timbang']?></td>
        <td><?=$r['z_score_bbu']?></td>
        <td><?=$r['status_stunting']?></td>
    </tr>
    <?php endforeach; ?>
</tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm rounded-3">
                <div class="card-body p-2">
                    <div class="table-responsive">
                        <table class="table table-bordered align-middle m-0">
                            <thead>
                                <tr>
                                    <th rowspan="2">INDIKATOR PENIMBANGAN</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-59 bln</th><th colspan="3">TOTAL</th>
                                </tr>
                                <tr><?php for($i=0;$i<5;$i++) echo "<th>L</th><th>P</th><th>J</th>"; ?></tr>
                            </thead>
                            <tbody>
                                <?php foreach($rekap_labels as $kd=>$label): $tL=0; $tP=0; ?>
                                <tr>
                                    <td class="text-start fw-bold" nowrap><?=$label?></td>
                                    <?php foreach($kategori_umur as $k): 
                                        $l = $rekap[$kd][$k]['L']; $p = $rekap[$kd][$k]['P'];
                                        $tL += $l; $tP += $p;
                                    ?>
                                        <td><?=$l?></td><td><?=$p?></td><td class="bg-light"><?=($l+$p)?></td>
                                    <?php endforeach; ?>
                                    <td class="fw-bold text-primary"><?=$tL?></td><td class="fw-bold text-primary"><?=$tP?></td>
                                    <td class="bg-primary text-white fw-bold"><?=($tL+$tP)?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>