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

// Proteksi Admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php"); exit;
}

try {
    // Ambil list posyandu untuk filter
    $posyandu_list = $pdo->query("SELECT id_posyandu, nama_posyandu FROM posyandu ORDER BY nama_posyandu ASC")->fetchAll();

    $filter_posyandu = isset($_GET['posyandu']) ? $_GET['posyandu'] : '';
    $where = $filter_posyandu != '' ? " WHERE t.id_posyandu = " . (int)$filter_posyandu : "";

    // 1. Query Data Balita
    // Saya hapus ORDER BY yang spesifik kolom agar tidak error jika nama kolom beda
    $sql_balita = "SELECT t.*, p.nama_posyandu FROM balita t 
                   LEFT JOIN posyandu p ON t.id_posyandu = p.id_posyandu $where";
    $balita = $pdo->query($sql_balita)->fetchAll();

    // 2. Query Data Ibu Hamil
    $sql_bumil = "SELECT t.*, p.nama_posyandu FROM ibu_hamil t 
                  LEFT JOIN posyandu p ON t.id_posyandu = p.id_posyandu $where";
    $bumil = $pdo->query($sql_bumil)->fetchAll();

    // 3. Query Data Lansia
    $sql_lansia = "SELECT t.*, p.nama_posyandu FROM lansia t 
                   LEFT JOIN posyandu p ON t.id_posyandu = p.id_posyandu $where";
    $lansia = $pdo->query($sql_lansia)->fetchAll();

} catch (PDOException $e) {
    die("Terjadi Kesalahan Database: " . $e->getMessage() . ". <br>Silakan cek apakah nama kolom di tabel sudah sesuai.");
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Admin - Rekapitulasi Lengkap</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print { .no-print { display: none; } .tab-pane { display: block !important; opacity: 1 !important; visibility: visible !important; } }
        .table-responsive { font-size: 11px; }
        .nav-pills .nav-link.active { background-color: #0d6efd; }
    </style>
</head>
<body class="bg-light">
<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <h3 class="fw-bold text-primary">Rekapitulasi Identitas Peserta</h3>
        <div>
            <button onclick="exportTableToExcel('rekap-data-all', 'Rekap_Posyandu_Keseluruhan')" class="btn btn-success">
                <i class="bi bi-file-earmark-excel"></i> Download Excel
            </button>
            <button onclick="window.print()" class="btn btn-danger">
                <i class="bi bi-printer"></i> Cetak PDF
            </button>
        </div>
    </div>

    <div class="card shadow-sm mb-4 no-print">
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-center">
                <div class="col-auto"><label class="fw-bold">Filter Posyandu:</label></div>
                <div class="col-md-4">
                    <select name="posyandu" class="form-select" onchange="this.form.submit()">
                        <option value="">-- Semua Posyandu --</option>
                        <?php foreach ($posyandu_list as $pl): ?>
                            <option value="<?= $pl['id_posyandu'] ?>" <?= ($filter_posyandu == $pl['id_posyandu']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($pl['nama_posyandu']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-auto">
                    <a href="admin_rekap_lengkap.php" class="btn btn-secondary">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <ul class="nav nav-pills mb-3 no-print" id="pills-tab">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#b">Balita (<?= count($balita) ?>)</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#i">Ibu Hamil (<?= count($bumil) ?>)</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#l">Lansia (<?= count($lansia) ?>)</button></li>
    </ul>

    <div class="tab-content bg-white p-4 shadow-sm rounded border" id="rekap-data-all">
        
        <div class="tab-pane fade show active" id="b">
            <h5 class="border-bottom pb-2">DATA BALITA</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm align-middle">
                    <thead class="table-primary text-center">
                        <tr>
                            <th>NIK</th><th>Nama Balita</th><th>Lahir</th><th>JK</th><th>Nama Ibu</th><th>Nama Ayah</th><th>Posyandu</th><th>Alamat</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($balita as $r): ?>
                        <tr>
                            <td>'<?= $r['nik_balita'] ?></td>
                            <td><?= $r['nama_balita'] ?></td>
                            <td><?= $r['tgl_lahir'] ?></td>
                            <td class="text-center"><?= $r['jenis_kelamin'] ?></td>
                            <td><?= isset($r['nama_ibu']) ? $r['nama_ibu'] : $r['ibu'] ?></td>
                            <td><?= isset($r['nama_ayah']) ? $r['nama_ayah'] : $r['ayah'] ?></td>
                            <td><?= $r['nama_posyandu'] ?></td>
                            <td><?= $r['dusun'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="tab-pane fade" id="i">
            <h5 class="border-bottom pb-2 text-success">DATA IBU HAMIL</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm align-middle">
                    <thead class="table-success text-center">
                        <tr>
                            <th>NIK</th><th>Nama Ibu</th><th>Suami</th><th>Tgl Lahir</th><th>HPHT</th><th>Hamil Ke</th><th>Posyandu</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bumil as $r): ?>
                        <tr>
                            <td>'<?= $r['nik'] ?></td>
                            <td><?= $r['nama_ibu'] ?></td>
                            <td><?= isset($r['nama_suami']) ? $r['nama_suami'] : $r['suami'] ?></td>
                            <td><?= $r['tgl_lahir'] ?></td>
                            <td><?= $r['hpht'] ?></td>
                            <td class="text-center"><?= $r['hamil_ke'] ?></td>
                            <td><?= $r['nama_posyandu'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="tab-pane fade" id="l">
            <h5 class="border-bottom pb-2 text-warning">DATA LANSIA</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm align-middle">
                    <thead class="table-warning text-center">
                        <tr>
                            <th>NIK</th><th>Nama Lengkap</th><th>JK</th><th>Tgl Lahir</th><th>Status</th><th>Posyandu</th><th>Alamat</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lansia as $r): ?>
                        <tr>
                            <td>'<?= $r['nik'] ?></td>
                            <td><?= $r['nama_lengkap'] ?></td>
                            <td class="text-center"><?= $r['jenis_kelamin'] ?></td>
                            <td><?= $r['tgl_lahir'] ?></td>
                            <td><?= $r['status_perkawinan'] ?></td>
                            <td><?= $r['nama_posyandu'] ?></td>
                            <td><?= $r['alamat'] ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<script>
function exportTableToExcel(tableID, filename = 'Rekap_Data'){
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    var downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], { type: dataType });
        navigator.msSaveOrOpenBlob( blob, filename + '.xls');
    } else {
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
        downloadLink.download = filename + '.xls';
        downloadLink.click();
    }
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>