<?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();

$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 REKAPITULASI (PERBAIKAN MINOR) ---
$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']++;
    
    // Hitung Indikator Kesehatan
    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']++;

    // --- PERBAIKAN LOGIKA KEMANDIRIAN ---
    // Menggunakan trim dan strtoupper agar lebih akurat membaca database
    $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 || stripos($k, 'KETERGANTUNGAN') !== false) {
        $rekap['m_c']++;
    }

    // --- PERBAIKAN LOGIKA MENTAL ---
    $m = trim(strtoupper($r['skrining_mental'] ?? ''));
    if($m == 'NORMAL' || $m == 'S' || $m == 'A' || $m == 'TIDAK ADA GANGGUAN') {
        $rekap['mental_n']++;
    } elseif($m != '' && $m != '-') {
        // Jika tidak kosong dan bukan normal, maka masuk kategori gangguan
        $rekap['mental_g']++;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rekapitulasi Lansia</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: 11px; }
        .main-content { margin-left: 250px; padding: 20px; transition: 0.3s; }
        .table-custom thead th { background: #198754 !important; color: white !important; text-align: center; vertical-align: middle; border: 1px solid #dee2e6; }
        .table-custom td { border: 1px solid #dee2e6; text-align: center; vertical-align: middle; }
        .rekap-title { background: #e9f7ef; color: #198754; font-weight: bold; text-align: left !important; padding-left: 15px !important; }
        @media (max-width: 768px) { .main-content { margin-left: 0; padding: 15px; } }
    </style>
</head>
<body>
    <?php include 'sidebar.php'; ?>
    <div class="main-content">
        <div class="container-fluid">
            <h4 class="fw-bold mb-4">REKAPITULASI DATA LANSIA</h4>

            <div class="card p-3 mb-3 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-success w-100 shadow-none"><i class="fa fa-filter me-2"></i>Filter</button></div>
                </form>
            </div>

            <div class="mb-3">
                <a href="export_lansia.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>&id_posyandu=<?=$id_posyandu_filter?>" class="btn btn-sm btn-outline-success"><i class="fa fa-file-excel me-2"></i>Export Excel</a>
            </div>

            <div class="card border-0 shadow-sm rounded-3 mb-4">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle m-0 table-custom">
                            <thead>
                                <tr>
                                    <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 class="text-success fw-bold"><?=$r['nama_posyandu']?></td>
                                    <td class="text-start fw-bold"><?=strtoupper($r['nama_lansia'])?></td>
                                    <td>'<?=$r['nik_lansia']?></td>
                                    <td class="fw-bold"><?=$umur?> Thn</td>
                                    <td><?=$r['bb']?></td><td><?=$r['tb']?></td><td><?=$r['lingkar_perut']?></td><td><?=$r['imt']?></td>
                                    <td class="<?=((int)($r['tensi']??0) >= 140)?'text-danger fw-bold':''?>"><?=$r['tensi']?></td>
                                    <td class="<?=((int)($r['gula_darah']??0) > 200)?'text-danger fw-bold':''?>"><?=$r['gula_darah']?></td>
                                    <td class="<?=((int)($r['asam_urat']??0) > 7)?'text-danger fw-bold':''?>"><?=$r['asam_urat']?></td>
                                    <td class="<?=((int)($r['kolesterol']??0) > 200)?'text-danger fw-bold':''?>"><?=$r['kolesterol']?></td>
                                    <td><?=$r['kemandirian']?></td><td><?=$r['skrining_mental']?></td>
                                    <td class="text-start small"><?=$r['catatan_obat']?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm rounded-3">
                        <div class="card-body p-0">
                            <table class="table table-bordered align-middle m-0 table-custom">
                                <thead>
                                    <tr><th colspan="2">REKAPITULASI INDIKATOR KESEHATAN</th></tr>
                                </thead>
                                <tbody>
                                    <tr><td class="text-start ps-3">Total Lansia Diperiksa</td><td class="fw-bold text-primary"><?=$rekap['total']?></td></tr>
                                    <tr><td class="text-start ps-3">Hipertensi (Tensi >= 140)</td><td class="fw-bold text-danger"><?=$rekap['tensi']?></td></tr>
                                    <tr><td class="text-start ps-3">Diabetes (GDS > 200)</td><td class="fw-bold text-danger"><?=$rekap['gula']?></td></tr>
                                    <tr><td class="text-start ps-3">Asam Urat Tinggi (> 7)</td><td class="fw-bold text-danger"><?=$rekap['asam']?></td></tr>
                                    <tr><td class="text-start ps-3">Kolesterol Tinggi (> 200)</td><td class="fw-bold text-danger"><?=$rekap['kol']?></td></tr>
                                    <tr><td class="text-start ps-3">Status Gizi (IMT Abnormal)</td><td class="fw-bold text-warning"><?=$rekap['imt']?></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm rounded-3">
                        <div class="card-body p-0">
                            <table class="table table-bordered align-middle m-0 table-custom">
                                <thead>
                                    <tr><th colspan="2">REKAPITULASI KEMANDIRIAN & MENTAL</th></tr>
                                </thead>
                                <tbody>
                                    <tr><td class="text-start ps-3">Kemandirian: Mandiri (A)</td><td class="fw-bold"><?=$rekap['m_a']?></td></tr>
                                    <tr><td class="text-start ps-3">Kemandirian: Dibantu Sebagian (B)</td><td class="fw-bold"><?=$rekap['m_b']?></td></tr>
                                    <tr><td class="text-start ps-3">Kemandirian: Ketergantungan Total (C)</td><td class="fw-bold"><?=$rekap['m_c']?></td></tr>
                                    <tr><td class="text-start ps-3">Skrining Mental: Normal</td><td class="fw-bold text-success"><?=$rekap['mental_n']?></td></tr>
                                    <tr><td class="text-start ps-3">Skrining Mental: Ada Gangguan</td><td class="fw-bold text-danger"><?=$rekap['mental_g']?></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</body>
</html>