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

$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"];

// HEADER AGAR JADI EXCEL
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=Rekap_Balita_".$bulan."_".$tahun.".xls");

// --- QUERY DATA SAMA DENGAN REKAP ---
$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);

// --- LOGIKA HITUNG REKAP (IDENTIK) ---
$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) $rekap['STUNT_P'][$kat_umur][$jk]++;

    $r['usia_hitung'] = $usia; $r['st_timbang'] = $st;
    $data_final[] = $r;
}
?>

<h3>LAPORAN REKAPITULASI BALITA - <?=$nama_bulan[$bulan]?> <?=$tahun?></h3>

<table border="1">
    <thead>
        <tr style="background-color: #0d6efd; color: white;">
            <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><?=$r['nama_posyandu']?></td>
            <td><?=$r['anak_ke']?></td><td><?=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><?=$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><?=$r['st_timbang']?></td><td><?=$r['z_score_bbu']?></td><td><?=$r['status_stunting']?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<br>

<table border="1">
    <thead>
        <tr style="background-color: #0d6efd; color: white;">
            <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><th>L</th><th>P</th><th>J</th><th>L</th><th>P</th><th>J</th><th>L</th><th>P</th><th>J</th><th>L</th><th>P</th><th>J</th><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><?=$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><?=($l+$p)?></td>
            <?php endforeach; ?>
            <td><?=$tL?></td><td><?=$tP?></td><td><?=($tL+$tP)?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>