<?php
// print_buku_besar_pkh.php - Buku Besar / Buku Induk Penerima Bantuan PKH
// Memuat data administrasi lengkap per keluarga: identitas, aset (foto rumah & koordinat),
// anggota keluarga, dan bantuan PKH yang diterima.

require_once 'config.php'; // Sertakan file konfigurasi database
require_once 'auth.php';   // Sertakan file fungsi autentikasi
check_login(); // Pastikan pengguna sudah login

$is_admin = is_admin();

// HANYA pengguna admin yang dapat mengakses halaman ini
if (!$is_admin) {
    header("location: dashboard.php");
    exit;
}

// --- Parameter filter (opsional) ---
$kelompok_id_filter = $_GET['kelompok_id'] ?? '';
$kk_id_filter = $_GET['kk_id'] ?? ''; // Cetak satu keluarga saja jika diisi
$desa_nama = $_GET['desa'] ?? 'Desa Bangorejo';

$nama_kelompok_filter = '';
if (!empty($kelompok_id_filter) && is_numeric($kelompok_id_filter)) {
    $sql_kf = "SELECT nama_kelompok FROM kelompok WHERE id = ?";
    if ($stmt_kf = mysqli_prepare($link, $sql_kf)) {
        mysqli_stmt_bind_param($stmt_kf, "i", $kelompok_id_filter);
        mysqli_stmt_execute($stmt_kf);
        mysqli_stmt_bind_result($stmt_kf, $kf_nama);
        if (mysqli_stmt_fetch($stmt_kf)) {
            $nama_kelompok_filter = $kf_nama;
        }
        mysqli_stmt_close($stmt_kf);
    }
}

// --- Ambil daftar Kepala Keluarga sesuai filter ---
$sql_kk = "SELECT kk.*, kel.nama_kelompok, p.nama_pengurus, p.nik_pengurus, p.jabatan, p.kontak
           FROM kepala_keluarga kk
           LEFT JOIN kelompok kel ON kk.kelompok_id = kel.id
           LEFT JOIN pengurus p ON kk.pengurus_id = p.id
           WHERE 1=1";
$params_kk = [];
$types_kk = "";

if (!empty($kk_id_filter) && is_numeric($kk_id_filter)) {
    $sql_kk .= " AND kk.id = ?";
    $params_kk[] = $kk_id_filter;
    $types_kk .= "i";
} elseif (!empty($kelompok_id_filter) && is_numeric($kelompok_id_filter)) {
    $sql_kk .= " AND kk.kelompok_id = ?";
    $params_kk[] = $kelompok_id_filter;
    $types_kk .= "i";
}

$sql_kk .= " ORDER BY kel.nama_kelompok ASC, kk.nama ASC";

$daftar_keluarga = [];
if ($stmt_kk = mysqli_prepare($link, $sql_kk)) {
    if (!empty($params_kk)) {
        mysqli_stmt_bind_param($stmt_kk, $types_kk, ...$params_kk);
    }
    mysqli_stmt_execute($stmt_kk);
    $result_kk = mysqli_stmt_get_result($stmt_kk);
    while ($row = mysqli_fetch_assoc($result_kk)) {
        $daftar_keluarga[] = $row;
    }
    mysqli_free_result($result_kk);
    mysqli_stmt_close($stmt_kk);
} else {
    die("ERROR: Tidak dapat menyiapkan query kepala keluarga. " . mysqli_error($link));
}

// --- Untuk setiap keluarga, ambil anggota keluarga & data bantuan PKH terkait ---
$total_anggota_keseluruhan = 0;
$total_bantuan_keseluruhan = 0.0;
$total_penerima_keseluruhan = 0;

foreach ($daftar_keluarga as $idx => $kel) {
    // Anggota keluarga
    $anggota = [];
    $sql_ang = "SELECT * FROM anggota_keluarga WHERE kepala_keluarga_id = ? ORDER BY id ASC";
    if ($stmt_ang = mysqli_prepare($link, $sql_ang)) {
        mysqli_stmt_bind_param($stmt_ang, "i", $kel['id']);
        mysqli_stmt_execute($stmt_ang);
        $res_ang = mysqli_stmt_get_result($stmt_ang);
        while ($a = mysqli_fetch_assoc($res_ang)) {
            $anggota[] = $a;
        }
        mysqli_free_result($res_ang);
        mysqli_stmt_close($stmt_ang);
    }
    $daftar_keluarga[$idx]['anggota_list'] = $anggota;
    $total_anggota_keseluruhan += count($anggota);

    // Kumpulkan semua NIK dalam keluarga ini (kepala + anggota) untuk dicocokkan ke data bansos
    $nik_list = [];
    if (!empty($kel['nik'])) {
        $nik_list[] = $kel['nik'];
    }
    foreach ($anggota as $a) {
        if (!empty($a['nik'])) {
            $nik_list[] = $a['nik'];
        }
    }
    $nik_list = array_values(array_unique($nik_list));

    // Data bantuan PKH yang diterima keluarga ini
    $bansos_list = [];
    $total_bantuan_keluarga = 0.0;
    if (!empty($nik_list)) {
        $placeholders = implode(',', array_fill(0, count($nik_list), '?'));
        $sql_bansos = "SELECT * FROM penerima_bansos WHERE nik IN ($placeholders) ORDER BY nama ASC";
        if ($stmt_bansos = mysqli_prepare($link, $sql_bansos)) {
            $types_bansos = str_repeat('s', count($nik_list));
            mysqli_stmt_bind_param($stmt_bansos, $types_bansos, ...$nik_list);
            mysqli_stmt_execute($stmt_bansos);
            $res_bansos = mysqli_stmt_get_result($stmt_bansos);
            while ($b = mysqli_fetch_assoc($res_bansos)) {
                $bansos_list[] = $b;
                $total_bantuan_keluarga += (float)$b['jumlah_uang'];
            }
            mysqli_free_result($res_bansos);
            mysqli_stmt_close($stmt_bansos);
        }
    }
    $daftar_keluarga[$idx]['bansos_list'] = $bansos_list;
    $daftar_keluarga[$idx]['total_bantuan_keluarga'] = $total_bantuan_keluarga;

    $total_bantuan_keseluruhan += $total_bantuan_keluarga;
    $total_penerima_keseluruhan += count($bansos_list);
}

mysqli_close($link);

function rupiah($angka) {
    return 'Rp ' . number_format((float)$angka, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buku Besar Penerima Bantuan PKH</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 15mm;
            font-size: 10.5pt;
            color: #222;
            line-height: 1.4;
        }
        .no-print { margin-bottom: 15px; }
        .no-print button, .no-print a.btn-back {
            padding: 8px 16px;
            font-size: 0.95em;
            border-radius: 6px;
            border: 1px solid #ccc;
            background: #f5f5f5;
            cursor: pointer;
            text-decoration: none;
            color: #222;
            display: inline-block;
            margin-right: 8px;
        }
        .cover-page {
            text-align: center;
            padding-top: 60px;
        }
        .cover-page .logo-row {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 40px;
            margin-bottom: 25px;
        }
        .cover-page .logo-row img { max-width: 100px; height: auto; }
        .cover-page h1 {
            font-size: 1.8em;
            text-transform: uppercase;
            margin: 10px 0;
        }
        .cover-page h2 {
            font-size: 1.3em;
            color: #444;
            margin: 5px 0 30px 0;
        }
        .cover-info {
            display: inline-block;
            text-align: left;
            margin: 30px auto;
        }
        .cover-info table td { padding: 3px 10px 3px 0; }
        .cover-info table td:first-child { font-weight: bold; width: 220px; }
        .summary-box {
            border: 1px solid #999;
            border-radius: 8px;
            padding: 15px 25px;
            display: inline-block;
            margin-top: 20px;
            text-align: left;
        }
        .summary-box table td { padding: 4px 15px 4px 0; }
        .toc-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 25px;
            font-size: 0.95em;
        }
        .toc-table th, .toc-table td {
            border: 1px solid #999;
            padding: 6px 8px;
            text-align: left;
        }
        .toc-table th { background: #eee; text-align: center; }
        .toc-table td.num { text-align: center; width: 30px; }
        .toc-table td.money { text-align: right; }

        .family-page {
            page-break-before: always;
            padding-top: 10px;
        }
        .family-header {
            border-bottom: 3px solid #333;
            margin-bottom: 15px;
            padding-bottom: 8px;
        }
        .family-header h2 {
            margin: 0;
            font-size: 1.25em;
            text-transform: uppercase;
        }
        .family-header .sub {
            color: #555;
            font-size: 0.9em;
        }
        .section-title {
            background: #f0f0f0;
            font-weight: bold;
            padding: 5px 10px;
            margin-top: 18px;
            margin-bottom: 8px;
            border-left: 4px solid #333;
            font-size: 0.95em;
            text-transform: uppercase;
        }
        .info-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 5px;
        }
        .info-table td {
            padding: 3px 6px;
            vertical-align: top;
        }
        .info-table td.label {
            width: 190px;
            font-weight: bold;
        }
        .info-table td.sep { width: 15px; }

        .asset-row {
            display: flex;
            gap: 20px;
            align-items: flex-start;
        }
        .asset-row .foto-rumah {
            flex-shrink: 0;
        }
        .asset-row .foto-rumah img {
            width: 160px;
            height: auto;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .asset-row .foto-rumah .no-foto {
            width: 160px;
            height: 120px;
            border: 1px dashed #bbb;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 0.85em;
            text-align: center;
        }

        table.data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 10px;
            font-size: 0.9em;
        }
        table.data-table th, table.data-table td {
            border: 1px solid #999;
            padding: 5px 7px;
            text-align: left;
        }
        table.data-table th { background: #f0f0f0; text-align: center; }
        table.data-table td.num { text-align: center; width: 28px; }
        table.data-table td.money { text-align: right; }
        table.data-table tfoot td { font-weight: bold; background: #fafafa; }

        .signature-block {
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
            font-size: 0.9em;
        }
        .signature-block .sig-col {
            width: 45%;
            text-align: center;
        }
        .signature-block .sig-line {
            margin-top: 60px;
            border-top: 1px solid #333;
        }
        .empty-note {
            font-style: italic;
            color: #777;
            padding: 6px 0;
        }

        @media print {
            body { margin: 12mm; }
            .no-print { display: none !important; }
            @page { size: auto; margin: 10mm; }
        }
    </style>
</head>
<body>

    <div class="no-print">
        <button onclick="window.print()">Cetak / Simpan sebagai PDF</button>
        <a href="dashboard.php" class="btn-back">Kembali ke Dashboard</a>
    </div>

    <!-- ===================== HALAMAN SAMPUL ===================== -->
    <div class="cover-page">
        <div class="logo-row">
            <img src="images/kemensos.jpeg" onerror="this.style.display='none';" alt="Logo Kemensos RI">
            <img src="images/selalu ada.png" onerror="this.style.display='none';" alt="Logo PKH">
        </div>
        <h1>Buku Besar Penerima Bantuan</h1>
        <h1>Program Keluarga Harapan (PKH)</h1>
        <h2><?php echo htmlspecialchars($desa_nama); ?><?php echo !empty($nama_kelompok_filter) ? ' &mdash; Kelompok: ' . htmlspecialchars($nama_kelompok_filter) : ''; ?></h2>

        <div class="cover-info">
            <table>
                <tr>
                    <td>Tanggal Cetak</td>
                    <td>: <?php echo date('d F Y'); ?></td>
                </tr>
                <tr>
                    <td>Jumlah Kepala Keluarga</td>
                    <td>: <?php echo count($daftar_keluarga); ?> keluarga</td>
                </tr>
                <tr>
                    <td>Jumlah Anggota Keluarga</td>
                    <td>: <?php echo $total_anggota_keseluruhan; ?> jiwa</td>
                </tr>
                <tr>
                    <td>Jumlah Penerima Bantuan PKH</td>
                    <td>: <?php echo $total_penerima_keseluruhan; ?> penerima</td>
                </tr>
                <tr>
                    <td>Total Nominal Bantuan Tercatat</td>
                    <td>: <strong><?php echo rupiah($total_bantuan_keseluruhan); ?></strong></td>
                </tr>
            </table>
        </div>

        <table class="toc-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama Kepala Keluarga</th>
                    <th>No. KK</th>
                    <th>Kelompok</th>
                    <th>Jml. Anggota</th>
                    <th>Total Bantuan</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($daftar_keluarga)): ?>
                    <?php foreach ($daftar_keluarga as $i => $kel): ?>
                        <tr>
                            <td class="num"><?php echo $i + 1; ?></td>
                            <td><?php echo htmlspecialchars($kel['nama']); ?></td>
                            <td><?php echo htmlspecialchars($kel['no_kk']); ?></td>
                            <td><?php echo htmlspecialchars($kel['nama_kelompok'] ?? '-'); ?></td>
                            <td class="num"><?php echo count($kel['anggota_list']); ?></td>
                            <td class="money"><?php echo rupiah($kel['total_bantuan_keluarga']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="6">Tidak ada data keluarga yang ditemukan untuk filter ini.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- ===================== HALAMAN PER KELUARGA ===================== -->
    <?php foreach ($daftar_keluarga as $i => $kel): ?>
    <div class="family-page">
        <div class="family-header">
            <h2><?php echo ($i + 1) . '. ' . htmlspecialchars($kel['nama']); ?></h2>
            <div class="sub">
                No. KK: <?php echo htmlspecialchars($kel['no_kk']); ?> &nbsp;|&nbsp;
                Kelompok: <?php echo htmlspecialchars($kel['nama_kelompok'] ?? '-'); ?>
            </div>
        </div>

        <!-- I. IDENTITAS KEPALA KELUARGA -->
        <div class="section-title">I. Identitas Kepala Keluarga</div>
        <table class="info-table">
            <tr>
                <td class="label">Nama Kepala Keluarga</td><td class="sep">:</td>
                <td><?php echo htmlspecialchars($kel['nama']); ?></td>
            </tr>
            <tr>
                <td class="label">NIK</td><td class="sep">:</td>
                <td><?php echo htmlspecialchars($kel['nik']); ?></td>
            </tr>
            <tr>
                <td class="label">No. Kartu Keluarga</td><td class="sep">:</td>
                <td><?php echo htmlspecialchars($kel['no_kk']); ?></td>
            </tr>
            <tr>
                <td class="label">Alamat</td><td class="sep">:</td>
                <td><?php echo nl2br(htmlspecialchars($kel['alamat'] ?? '-')); ?></td>
            </tr>
            <tr>
                <td class="label">Kelompok PKH</td><td class="sep">:</td>
                <td><?php echo htmlspecialchars($kel['nama_kelompok'] ?? '-'); ?></td>
            </tr>
            <tr>
                <td class="label">Pengurus / Pendamping Keluarga</td><td class="sep">:</td>
                <td>
                    <?php if (!empty($kel['nama_pengurus'])): ?>
                        <?php echo htmlspecialchars($kel['nama_pengurus']); ?>
                        (NIK: <?php echo htmlspecialchars($kel['nik_pengurus']); ?>)
                        <?php if (!empty($kel['jabatan'])): ?> &ndash; <?php echo htmlspecialchars($kel['jabatan']); ?><?php endif; ?>
                        <?php if (!empty($kel['kontak'])): ?> &ndash; Kontak: <?php echo htmlspecialchars($kel['kontak']); ?><?php endif; ?>
                    <?php else: ?>
                        -
                    <?php endif; ?>
                </td>
            </tr>
        </table>

        <!-- II. DATA ASET & LOKASI -->
        <div class="section-title">II. Data Aset &amp; Lokasi Rumah</div>
        <div class="asset-row">
            <div class="foto-rumah">
                <?php if (!empty($kel['foto_rumah']) && file_exists(__DIR__ . '/' . $kel['foto_rumah'])): ?>
                    <img src="<?php echo htmlspecialchars($kel['foto_rumah']); ?>" alt="Foto Rumah">
                <?php else: ?>
                    <div class="no-foto">Tidak ada foto rumah</div>
                <?php endif; ?>
            </div>
            <table class="info-table">
                <tr>
                    <td class="label">Titik Koordinat GPS</td><td class="sep">:</td>
                    <td><?php echo htmlspecialchars($kel['titik_koordinat'] ?? '-'); ?></td>
                </tr>
                <tr>
                    <td class="label">Alamat Tercatat</td><td class="sep">:</td>
                    <td><?php echo nl2br(htmlspecialchars($kel['alamat'] ?? '-')); ?></td>
                </tr>
            </table>
        </div>

        <!-- III. DAFTAR ANGGOTA KELUARGA -->
        <div class="section-title">III. Daftar Anggota Keluarga</div>
        <?php if (!empty($kel['anggota_list'])): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama</th>
                    <th>NIK</th>
                    <th>No. KIS</th>
                    <th>Hubungan</th>
                    <th>Jenjang Sekolah</th>
                    <th>Nama Sekolah</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($kel['anggota_list'] as $j => $a): ?>
                <tr>
                    <td class="num"><?php echo $j + 1; ?></td>
                    <td><?php echo htmlspecialchars($a['nama']); ?></td>
                    <td><?php echo htmlspecialchars($a['nik'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($a['no_kis'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($a['hubungan'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($a['jenjang_sekolah'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($a['nama_sekolah'] ?? '-'); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
            <div class="empty-note">Belum ada data anggota keluarga yang tercatat.</div>
        <?php endif; ?>

        <!-- IV. DATA BANTUAN PKH DITERIMA -->
        <div class="section-title">IV. Data Bantuan PKH yang Diterima</div>
        <?php if (!empty($kel['bansos_list'])): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama Penerima</th>
                    <th>NIK</th>
                    <th>Alamat</th>
                    <th>Jumlah Bantuan</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($kel['bansos_list'] as $j => $b): ?>
                <tr>
                    <td class="num"><?php echo $j + 1; ?></td>
                    <td><?php echo htmlspecialchars($b['nama']); ?></td>
                    <td><?php echo htmlspecialchars($b['nik']); ?></td>
                    <td><?php echo htmlspecialchars($b['alamat'] ?? '-'); ?></td>
                    <td class="money"><?php echo rupiah($b['jumlah_uang']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="4" style="text-align:right;">Total Bantuan Keluarga Ini</td>
                    <td class="money"><?php echo rupiah($kel['total_bantuan_keluarga']); ?></td>
                </tr>
            </tfoot>
        </table>
        <?php else: ?>
            <div class="empty-note">Belum ada data bantuan PKH yang tercatat untuk keluarga ini.</div>
        <?php endif; ?>

        <!-- TANDA TANGAN -->
        <div class="signature-block">
            <div class="sig-col">
                Mengetahui,<br>Pendamping / Pengurus PKH
                <div class="sig-line"></div>
                <?php echo htmlspecialchars($kel['nama_pengurus'] ?? '(...........................)'); ?>
            </div>
            <div class="sig-col">
                <?php echo htmlspecialchars($desa_nama); ?>, <?php echo date('d F Y'); ?><br>Kepala Keluarga
                <div class="sig-line"></div>
                <?php echo htmlspecialchars($kel['nama']); ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

</body>
</html>