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

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

// AMBIL DATA PEMERIKSAAN BUMIL
$query = "SELECT b.*, p.* FROM ibu_hamil b 
          JOIN pemeriksaan_bumil p ON b.id_bumil = p.id_bumil 
          WHERE b.id_posyandu = ? AND MONTH(p.tgl_periksa) = ? AND YEAR(p.tgl_periksa) = ? 
          ORDER BY b.nama_bumil ASC";
$stmt = $pdo->prepare($query);
$stmt->execute([$id_posyandu, $bulan, $tahun]);
$data_bumil = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Inisialisasi Rekap Sederhana Bumil
$rekap = ['K1'=>0, 'K2'=>0, 'K3'=>0, 'K4'=>0, 'K5'=>0, 'K6'=>0, 'KEK'=>0, 'ANEMIA'=>0];
foreach ($data_bumil as $r) {
    if(isset($rekap[$r['status_k']])) $rekap[$r['status_k']]++;
    if($r['lila'] < 23.5) $rekap['KEK']++;
    if($r['hb'] > 0 && $r['hb'] < 11) $rekap['ANEMIA']++;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Ibu Hamil</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background:#f4f7f6; font-size: 11px; color: #333; }
        .card-laporan { background: white; border-radius: 8px; padding: 10px; margin-top: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .scroll-area { overflow-x: auto; -webkit-overflow-scrolling: touch; border: 1px solid #ddd; }
        table { width: 100%; border-collapse: collapse; background: white; }
        th { background: #0d6efd !important; color: white !important; border: 1px solid #dee2e6; padding: 8px 4px; text-align: center; white-space: nowrap; }
        td { border: 1px solid #dee2e6; padding: 6px 4px; text-align: center; }
        .text-start { text-align: left; }
        .bg-kek { background: #fff3f3; color: #dc3545; }
        .no-print { margin-bottom: 10px; }
        @media print { .no-print { display: none; } }
    </style>
</head>
<body>

<div class="container-fluid pb-5">
    <div class="card p-3 mt-2 no-print shadow-sm">
        <form method="GET" class="row g-2">
            <div class="col-6">
                <select name="bulan" class="form-select form-select-sm">
                    <?php foreach($nama_bulan as $k=>$v) echo "<option value='$k'".($k==$bulan?' selected':'').">$v</option>"; ?>
                </select>
            </div>
            <div class="col-6">
                <select name="tahun" class="form-select form-select-sm">
                    <?php for($i=2024; $i<=2026; $i++) echo "<option value='$i'".($i==$tahun?' selected':'').">$i</option>"; ?>
                </select>
            </div>
            <div class="col-12 mt-2 d-flex gap-1">
                <button type="submit" class="btn btn-primary btn-sm flex-fill fw-bold">TAMPILKAN</button>
                <a href="export_excel_bumil.php?bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="btn btn-success btn-sm flex-fill fw-bold">UNDUH EXCEL</a>
                <button type="button" onclick="unduhPDF()" class="btn btn-danger btn-sm flex-fill fw-bold">UNDUH PDF</button>
            </div>
        </form>
    </div>

    <div id="area-laporan">
        <div class="text-center mt-3">
            <h6 class="mb-0 fw-bold">LAPORAN PEMERIKSAAN IBU HAMIL</h6>
            <p class="small text-muted">Posyandu: <?= strtoupper($posyandu['nama_posyandu'] ?? '-') ?> | <?=$nama_bulan[$bulan]?> <?=$tahun?></p>
        </div>

        <div class="card-laporan">
            <div class="scroll-area">
                <table>
                    <thead>
                        <tr>
                            <th rowspan="2">NO</th>
                            <th colspan="4">IDENTITAS IBU</th>
                            <th colspan="10">HASIL PEMERIKSAAN (10T)</th>
                        </tr>
                        <tr>
                            <th>NAMA BUMIL</th><th>NIK</th><th>NAMA SUAMI</th><th>TGL LAHIR</th>
                            <th>HPHT</th><th>HPL</th><th>UK (Mgg)</th><th>ST</th><th>BB</th><th>TENSI</th><th>LILA</th><th>TFU</th><th>HB</th><th>TTD</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $n=1; foreach($data_bumil as $r): ?>
                        <tr>
                            <td><?=$n++?></td>
                            <td class="text-start" nowrap><?=strtoupper($r['nama_bumil'])?></td>
                            <td>'<?=$r['nik_bumil']?></td>
                            <td class="text-start" nowrap><?=$r['nama_suami']?></td>
                            <td nowrap><?=date('d/m/y', strtotime($r['tgl_lahir']))?></td>
                            <td nowrap><?=date('d/m/y', strtotime($r['hpht']))?></td>
                            <td nowrap><?=date('d/m/y', strtotime($r['hpl']))?></td>
                            <td><?=$r['usia_kehamilan']?></td>
                            <td class="fw-bold text-primary"><?=$r['status_k']?></td>
                            <td><?=$r['bb']?> kg</td>
                            <td><?=$r['tensi']?></td>
                            <td class="<?= $r['lila'] < 23.5 ? 'bg-kek fw-bold' : '' ?>"><?=$r['lila']?> cm</td>
                            <td><?=$r['tfu'] > 0 ? $r['tfu'].' cm' : '-' ?></td>
                            <td class="<?= ($r['hb'] > 0 && $r['hb'] < 11) ? 'bg-kek fw-bold' : '' ?>"><?=$r['hb'] > 0 ? $r['hb'].' g/dL' : '-' ?></td>
                            <td><?=$r['tablet_tambah_darah']?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($data_bumil)): ?>
                            <tr><td colspan="15" class="py-3 text-muted">Tidak ada data pemeriksaan pada bulan ini.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="row mt-3 px-1">
            <div class="col-12">
                <div class="card p-2 shadow-sm border-0">
                    <h6 class="fw-bold mb-2 small text-primary"><i class="bi bi-info-circle"></i> RINGKASAN DATA</h6>
                    <div class="d-flex justify-content-between text-center">
                        <?php foreach(['K1','K4','K6'] as $k): ?>
                            <div class="border rounded p-2 flex-fill mx-1">
                                <div class="small text-muted"><?=$k?></div>
                                <div class="fw-bold fs-6"><?=$rekap[$k]?></div>
                            </div>
                        <?php endforeach; ?>
                        <div class="border rounded p-2 flex-fill mx-1 bg-danger-subtle border-danger">
                            <div class="small text-danger">KEK</div>
                            <div class="fw-bold fs-6 text-danger"><?=$rekap['KEK']?></div>
                        </div>
                    </div>
                </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');
    const opsi = {
        margin: [5, 5, 5, 5],
        filename: 'Laporan_Bumil_<?=$nama_bulan[$bulan]?>_<?=$tahun?>.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: 'mm', format: [215.9, 330.2], orientation: 'landscape' }
    };
    html2pdf().set(opsi).from(element).save();
}
</script>
</body>
</html>