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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    exit("Akses ditolak");
}

$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=Laporan_Lansia_".$bulan."_".$tahun.".xls");

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

$query = "SELECT l.*, p.*, pos.nama_posyandu 
          FROM lansia l 
          JOIN pemeriksaan_lansia p ON l.id_lansia = p.id_lansia 
          JOIN posyandu pos ON l.id_posyandu = pos.id_posyandu
          WHERE MONTH(p.tgl_periksa) = ? AND YEAR(p.tgl_periksa) = ? $sql_filter";

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

// --- LOGIKA HITUNG REKAP ---
$rekap = [
    'total' => 0, 'tensi' => 0, 'gula' => 0, 'asam' => 0, 'kol' => 0, 'imt' => 0,
    'm_a' => 0, 'm_b' => 0, 'm_c' => 0, 'mental_n' => 0, 'mental_g' => 0
];

foreach($data_lansia as $r) {
    $rekap['total']++;
    if((int)($r['tensi']??0) >= 140) $rekap['tensi']++;
    if((int)($r['gula_darah']??0) > 200) $rekap['gula']++;
    if((int)($r['asam_urat']??0) > 7) $rekap['asam']++;
    if((int)($r['kolesterol']??0) > 200) $rekap['kol']++;
    
    $val_imt = (float)($r['imt']??0);
    if($val_imt > 0 && ($val_imt < 18.5 || $val_imt > 25.0)) $rekap['imt']++;

    $k = trim(strtoupper($r['kemandirian'] ?? ''));
    if($k == 'A' || stripos($k, 'MANDIRI') !== false) $rekap['m_a']++;
    elseif($k == 'B' || stripos($k, 'SEBAGIAN') !== false || stripos($k, 'DIBANTU') !== false) $rekap['m_b']++;
    elseif($k == 'C' || stripos($k, 'TOTAL') !== false) $rekap['m_c']++;

    $m = trim(strtoupper($r['skrining_mental'] ?? ''));
    if($m == 'NORMAL' || $m == 'S' || $m == 'A') $rekap['mental_n']++;
    elseif($m != '' && $m != '-') $rekap['mental_g']++;
}
?>

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

<table border="1">
    <thead>
        <tr style="background-color: #198754; color: white;">
            <th rowspan="2">No</th><th rowspan="2">Posyandu</th><th rowspan="2">Nama Lansia</th><th rowspan="2">NIK</th><th rowspan="2">Umur</th>
            <th colspan="10">Hasil Pemeriksaan</th><th rowspan="2">Obat/Ket</th>
        </tr>
        <tr>
            <th>BB</th><th>TB</th><th>Perut</th><th>IMT</th><th>Tensi</th><th>GDS</th><th>AU</th><th>KOL</th><th>Mndr</th><th>Mntl</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($data_lansia as $idx => $r): 
            $tgl_l = new DateTime($r['tgl_lahir']);
            $tgl_p = new DateTime($r['tgl_periksa']);
            $umur = $tgl_p->diff($tgl_l)->y;
        ?>
        <tr>
            <td><?=($idx+1)?></td>
            <td><?=$r['nama_posyandu']?></td>
            <td><?=strtoupper($r['nama_lansia'])?></td>
            <td>'<?=$r['nik_lansia']?></td>
            <td><?=$umur?> Thn</td>
            <td><?=$r['bb']?></td><td><?=$r['tb']?></td><td><?=$r['lingkar_perut']?></td><td><?=$r['imt']?></td>
            <td><?=$r['tensi']?></td><td><?=$r['gula_darah']?></td><td><?=$r['asam_urat']?></td><td><?=$r['kolesterol']?></td>
            <td><?=$r['kemandirian']?></td><td><?=$r['skrining_mental']?></td>
            <td><?=$r['catatan_obat']?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<br>

<table border="1">
    <thead>
        <tr style="background-color: #198754; color: white;">
            <th colspan="2">REKAPITULASI INDIKATOR KESEHATAN</th>
            <th colspan="2">REKAPITULASI KEMANDIRIAN & MENTAL</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Total Lansia Diperiksa</td><td><?=$rekap['total']?></td>
            <td>Kemandirian: Mandiri (A)</td><td><?=$rekap['m_a']?></td>
        </tr>
        <tr>
            <td>Hipertensi (Tensi >= 140)</td><td><?=$rekap['tensi']?></td>
            <td>Kemandirian: Dibantu Sebagian (B)</td><td><?=$rekap['m_b']?></td>
        </tr>
        <tr>
            <td>Diabetes (GDS > 200)</td><td><?=$rekap['gula']?></td>
            <td>Kemandirian: Ketergantungan Total (C)</td><td><?=$rekap['m_c']?></td>
        </tr>
        <tr>
            <td>Asam Urat Tinggi (> 7)</td><td><?=$rekap['asam']?></td>
            <td>Skrining Mental: Normal</td><td><?=$rekap['mental_n']?></td>
        </tr>
        <tr>
            <td>Kolesterol Tinggi (> 200)</td><td><?=$rekap['kol']?></td>
            <td>Skrining Mental: Ada Gangguan</td><td><?=$rekap['mental_g']?></td>
        </tr>
        <tr>
            <td>Status Gizi (IMT Abnormal)</td><td><?=$rekap['imt']?></td>
            <td></td><td></td>
        </tr>
    </tbody>
</table>