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

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

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

$query = "SELECT l.nama_lansia, l.nik_lansia, l.jenis_kelamin, 
                 TIMESTAMPDIFF(YEAR, l.tgl_lahir, CURDATE()) AS umur,
                 p.* FROM pemeriksaan_lansia p
          JOIN lansia l ON p.id_lansia = l.id_lansia
          WHERE l.id_posyandu = ? AND MONTH(p.tgl_periksa) = ? AND YEAR(p.tgl_periksa) = ?
          ORDER BY p.tgl_periksa ASC";

$stmt = $pdo->prepare($query);
$stmt->execute([$id_posyandu, $bulan, $tahun]);
$data = $stmt->fetchAll();

$rekap = ['total' => count($data), 'hipertensi' => 0, 'gds' => 0, 'imt' => 0, 'au' => 0, 'kol' => 0];
foreach ($data as $d) {
    $t = explode('/', $d['tensi']);
    if (isset($t[0]) && $t[0] >= 140) $rekap['hipertensi']++;
    if ($d['gula_darah'] > 200) $rekap['gds']++;
    if ($d['imt'] > 0 && ($d['imt'] < 18.5 || $d['imt'] > 25)) $rekap['imt']++;
    if (($d['jenis_kelamin'] == 'L' && $d['asam_urat'] > 7) || ($d['jenis_kelamin'] == 'P' && $d['asam_urat'] > 6)) $rekap['au']++;
    if ($d['kolesterol'] > 200) $rekap['kol']++;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan 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://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background: #f4f7fe; font-family: 'Arial', sans-serif; padding-top: 20px; }
        .card-custom { border: none; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
        .btn-action { height: 45px; font-weight: bold; font-size: 11px; display: flex; align-items: center; justify-content: center; width: 100%; }
        
        /* Gaya Tabel (Ungu) */
        .table { font-size: 10px; border-collapse: collapse !important; width: 100%; }
        th { background-color: #6f42c1 !important; color: white !important; border: 1px solid #dee2e6 !important; text-align: center; padding: 8px 4px; }
        td { border: 1px solid #dee2e6 !important; vertical-align: middle; padding: 5px; }

        /* Klasifikasi khusus untuk PDF agar tidak bergaris */
        .pdf-fix table { border-collapse: collapse; }
        .pdf-fix th, .pdf-fix td { border: 0.1pt solid #dee2e6; }
        
        @media print { .no-print { display: none; } }
    </style>
</head>
<body>

<div class="container pb-5">
    <div class="card card-custom mb-3 no-print">
        <div class="card-body p-3">
            <form method="GET">
                <div class="row g-2 mb-2">
                    <div class="col-6">
                        <select name="bulan" class="form-select border-0 bg-light">
                            <?php foreach($nama_bulan as $k => $v) echo "<option value='$k' ".($bulan==$k?'selected':'').">$v</option>"; ?>
                        </select>
                    </div>
                    <div class="col-6">
                        <select name="tahun" class="form-select border-0 bg-light">
                            <?php for($y=date('Y'); $y>=2023; $y--) echo "<option value='$y' ".($tahun==$y?'selected':'').">$y</option>"; ?>
                        </select>
                    </div>
                </div>
                <div class="row g-2">
                    <div class="col-4"><button type="submit" class="btn btn-primary btn-action">TAMPILKAN</button></div>
                    <div class="col-4"><a href="laporan_lansia_excel.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="btn btn-success btn-action">UNDUH EXCEL</a></div>
                    <div class="col-4"><button type="button" onclick="unduhPDF()" class="btn btn-danger btn-action">UNDUH PDF</button></div>
                </div>
            </form>
        </div>
    </div>

    <div id="area-laporan">
        <div class="card card-custom">
            <div class="card-body p-3">
                <div class="text-center mb-3">
                    <h5 class="fw-bold mb-1">LAPORAN PEMERIKSAAN KESEHATAN LANSIA</h5>
                    <p class="mb-0 text-muted small">Posyandu: <?= strtoupper($posyandu['nama_posyandu']) ?> | Periode: <?= $nama_bulan[$bulan] ?> <?= $tahun ?></p>
                    <hr class="my-2">
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th rowspan="2">No</th>
                                <th rowspan="2">Nama / NIK</th>
                                <th rowspan="2">Umur</th>
                                <th colspan="3">Antropometri</th>
                                <th rowspan="2">Tensi</th>
                                <th colspan="3">Laboratorium</th>
                                <th colspan="2">Status</th>
                                <th rowspan="2">Keluhan / Obat</th>
                            </tr>
                            <tr>
                                <th>BB/TB</th><th>LP</th><th>IMT</th>
                                <th>GDS</th><th>AU</th><th>Kol</th>
                                <th>Mandiri</th><th>Mental</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($data) > 0): $no=1; foreach($data as $d): ?>
                            <tr>
                                <td class="text-center"><?=$no++?></td>
                                <td><strong><?= strtoupper($d['nama_lansia']) ?></strong><br><?=$d['nik_lansia']?></td>
                                <td class="text-center"><?=$d['umur']?> Th</td>
                                <td class="text-center"><?=$d['bb']?>/<?=$d['tb']?></td>
                                <td class="text-center"><?=$d['lingkar_perut']?></td>
                                <td class="text-center"><?=$d['imt']?></td>
                                <td class="text-center"><?=$d['tensi']?></td>
                                <td class="text-center"><?=$d['gula_darah']?></td>
                                <td class="text-center"><?=$d['asam_urat']?></td>
                                <td class="text-center"><?=$d['kolesterol']?></td>
                                <td class="text-center"><?=$d['kemandirian']?></td>
                                <td class="text-center"><?=$d['skrining_mental']?></td>
                                <td style="white-space: normal; min-width: 120px;"><small><?=$d['catatan_obat'] ?: '-'?></small></td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="13" class="text-center py-4">Tidak ada data.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4">
                    <h6 class="fw-bold mb-2 small text-primary"><i class="bi bi-info-circle"></i> RINGKASAN DATA</h6>
                    <table class="table table-bordered text-center" style="font-size: 9px;">
                        <tr class="bg-light">
                            <td><div class="text-muted small">TOTAL</div><div class="fw-bold"><?=$rekap['total']?></div></td>
                            <td><div class="text-danger small">TENSI HI</div><div class="fw-bold text-danger"><?=$rekap['hipertensi']?></div></td>
                            <td><div class="text-muted small">GDS > 200</div><div class="fw-bold"><?=$rekap['gds']?></div></td>
                            <td><div class="text-muted small">IMT ABNORM</div><div class="fw-bold"><?=$rekap['imt']?></div></td>
                            <td><div class="text-muted small">AU HI</div><div class="fw-bold"><?=$rekap['au']?></div></td>
                            <td><div class="text-info small">KOL > 200</div><div class="fw-bold text-info"><?=$rekap['kol']?></div></td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
function unduhPDF() {
    const element = document.getElementById('area-laporan');
    element.classList.add('pdf-fix'); // Paksa tabel bersih

    const opsi = {
        margin: [10, 5, 10, 5],
        filename: 'Laporan_Lansia_<?=$nama_bulan[$bulan]?>_<?=$tahun?>.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true, letterRendering: true },
        jsPDF: { unit: 'mm', format: [215.9, 330.2], orientation: 'landscape' }
    };
    
    html2pdf().set(opsi).from(element).save().then(() => {
        element.classList.remove('pdf-fix');
    });
}
</script>
</body>
</html>