<?php
require_once __DIR__ . '/../config/session.php';
requireLogin();
if (($_SESSION['role'] ?? '') !== 'user') {
    header('Location: ' . BASE_URL . '/admin/dashboard');
    exit;
}
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../functions/helper.php';

$db = getDB();
$ibu_hamil_id = $_SESSION['ibu_hamil_id'] ?? 0;

if (!$ibu_hamil_id) {
    $stmt = $db->prepare("SELECT ibu_hamil_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $ibu_hamil_id = (int)($stmt->fetchColumn() ?: 0);
    if ($ibu_hamil_id) {
        $_SESSION['ibu_hamil_id'] = $ibu_hamil_id;
    }
}

$kunjungan_list = [];
$terbaru = null;
if ($ibu_hamil_id) {
    $stmt = $db->prepare("SELECT * FROM kunjungan_posyandu WHERE ibu_hamil_id = ? ORDER BY tanggal_kunjungan DESC, id DESC");
    $stmt->execute([$ibu_hamil_id]);
    $kunjungan_list = $stmt->fetchAll();
    $terbaru = $kunjungan_list[0] ?? null;
}

$fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : null;
?>
<?php require_once '../includes/header_user.php'; ?>

<div class="mb-6">
    <h2 class="text-2xl font-bold text-gray-800">Riwayat Kunjungan</h2>
    <p class="text-gray-500">Catatan rekam medis dari setiap kunjungan Anda ke posyandu.</p>
</div>

<!-- Kunjungan Terbaru -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6">
    <div class="px-4 sm:px-6 py-4 border-b border-gray-100 bg-gray-50/50 flex items-center gap-3">
        <div class="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 flex items-center justify-center shrink-0">
            <i class="fas fa-heartbeat"></i>
        </div>
        <div class="min-w-0">
            <h3 class="text-base sm:text-lg font-bold text-gray-800">Data Terbaru</h3>
            <?php if ($terbaru): ?>
                <p class="text-xs text-gray-500 truncate">Kunjungan tanggal <strong><?= formatDate($terbaru['tanggal_kunjungan']) ?></strong><?= $terbaru['usia_kehamilan_minggu'] !== null ? ' &middot; Usia '.escape($terbaru['usia_kehamilan_minggu']).' minggu' : '' ?></p>
            <?php else: ?>
                <p class="text-xs text-gray-500">Belum ada data kunjungan.</p>
            <?php endif; ?>
        </div>
    </div>
    <div class="p-4 sm:p-6">
        <?php if ($terbaru): ?>
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
                    <?php
                    $cards = [
                        ['Tekanan Darah', $terbaru['tekanan_darah'] ? escape($terbaru['tekanan_darah']).' mmHg' : '-', 'fa-stethoscope', 'bg-red-50 border-red-100', 'text-red-500', 'text-red-600'],
                        ['Berat Badan', $terbaru['berat_badan'] !== null ? $fmtDec($terbaru['berat_badan']).' kg' : '-', 'fa-weight', 'bg-blue-50 border-blue-100', 'text-blue-500', 'text-blue-600'],
                        ['Tinggi Fundus', $terbaru['tinggi_fundus'] !== null ? $fmtDec($terbaru['tinggi_fundus']).' cm' : '-', 'fa-ruler-vertical', 'bg-purple-50 border-purple-100', 'text-purple-500', 'text-purple-600'],
                        ['Letak Janin', $terbaru['letak_janin'] ? escape($terbaru['letak_janin']) : '-', 'fa-baby', 'bg-yellow-50 border-yellow-100', 'text-yellow-600', 'text-yellow-700'],
                        ['DJJ', $terbaru['denyut_jantung_janin'] !== null ? escape($terbaru['denyut_jantung_janin']).' /menit' : '-', 'fa-heartbeat', 'bg-pink-50 border-pink-100', 'text-pink-500', 'text-pink-600'],
                    ];
                    foreach ($cards as [$label, $val, $icon, $bgClass, $iconClass, $labelClass]):
                    ?>
                        <div class="<?= $bgClass ?> border rounded-xl p-3 sm:p-4 text-center">
                            <i class="fas <?= $icon ?> <?= $iconClass ?> text-base sm:text-lg mb-1 sm:mb-2"></i>
                            <p class="text-[10px] font-bold uppercase tracking-wider <?= $labelClass ?> mb-1"><?= $label ?></p>
                            <p class="text-xs sm:text-sm font-bold text-gray-800"><?= $val ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php if (!empty($terbaru['catatan'])): ?>
                <div class="mt-3 sm:mt-4 bg-yellow-50 border border-yellow-200 rounded-xl p-3 sm:p-4 text-sm text-yellow-800">
                    <p class="text-xs font-bold uppercase tracking-wider mb-1"><i class="fas fa-sticky-note mr-1"></i> Catatan Bidan</p>
                    <?= nl2br(escape($terbaru['catatan'])) ?>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="text-center py-8 text-gray-400">
                <i class="fas fa-notes-medical text-4xl mb-3 text-gray-300 block"></i>
                <p class="text-sm">Data rekam medis belum tersedia. Silakan hubungi admin/bidan posyandu.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal Detail Kunjungan -->
<div x-data="kunjunganModal()" x-cloak>
    <div x-show="open" class="fixed inset-0 z-50 flex items-center justify-center p-4" x-transition.opacity>
        <div class="absolute inset-0 bg-black/50" @click="open = false"></div>
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto z-10">
            <!-- Header -->
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-gray-50/50">
                <div>
                    <h3 class="font-bold text-gray-800">Detail Kunjungan</h3>
                    <p class="text-xs text-gray-500" x-text="'Tanggal: ' + detail.tanggal"></p>
                </div>
                <button @click="open = false" class="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 transition-colors">
                    <i class="fas fa-times text-sm"></i>
                </button>
            </div>
            <!-- Body -->
            <div class="p-6 space-y-3">
                <div class="grid grid-cols-2 gap-3">
                    <div class="bg-red-50 border border-red-100 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-red-400 uppercase tracking-wide mb-1">Tekanan Darah</p>
                        <p class="font-bold text-gray-800" x-text="detail.tekanan_darah || '-'"></p>
                    </div>
                    <div class="bg-blue-50 border border-blue-100 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-blue-400 uppercase tracking-wide mb-1">Berat Badan</p>
                        <p class="font-bold text-gray-800" x-text="detail.berat_badan ? detail.berat_badan + ' kg' : '-'"></p>
                    </div>
                    <div class="bg-purple-50 border border-purple-100 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-purple-400 uppercase tracking-wide mb-1">Tinggi Fundus</p>
                        <p class="font-bold text-gray-800" x-text="detail.tinggi_fundus ? detail.tinggi_fundus + ' cm' : '-'"></p>
                    </div>
                    <div class="bg-yellow-50 border border-yellow-100 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-yellow-500 uppercase tracking-wide mb-1">Letak Janin</p>
                        <p class="font-bold text-gray-800" x-text="detail.letak_janin || '-'"></p>
                    </div>
                    <div class="bg-pink-50 border border-pink-100 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-pink-400 uppercase tracking-wide mb-1">DJJ</p>
                        <p class="font-bold text-gray-800" x-text="detail.djj ? detail.djj + ' /mnt' : '-'"></p>
                    </div>
                    <div class="bg-primary/5 border border-primary/10 rounded-xl p-3 text-center">
                        <p class="text-[10px] font-bold text-primary uppercase tracking-wide mb-1">Usia Kehamilan</p>
                        <p class="font-bold text-gray-800" x-text="detail.usia ? detail.usia + ' minggu' : '-'"></p>
                    </div>
                </div>
                <template x-if="detail.catatan">
                    <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-4 text-sm text-yellow-800">
                        <p class="text-xs font-bold uppercase tracking-wide text-yellow-500 mb-1"><i class="fas fa-sticky-note mr-1"></i> Catatan Bidan</p>
                        <p x-text="detail.catatan"></p>
                    </div>
                </template>
            </div>
            <!-- Footer -->
            <div class="px-6 pb-5 flex justify-end gap-2">
                <a :href="'cetak_kunjungan_pdf.php?id=' + detail.id" target="_blank"
                   class="inline-flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white font-medium rounded-lg text-sm transition-colors">
                    <i class="fas fa-file-pdf"></i> PDF
                </a>
                <a :href="'export_kunjungan_excel.php?id=' + detail.id" target="_blank"
                   class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg text-sm transition-colors">
                    <i class="fas fa-file-excel"></i> Excel
                </a>
            </div>
        </div>
    </div>

<!-- Tabel / Kartu Riwayat -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
    <div class="px-4 sm:px-6 py-4 border-b border-gray-100 bg-gray-50/50 flex items-center gap-3">
        <div class="w-10 h-10 rounded-xl bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0">
            <i class="fas fa-history"></i>
        </div>
        <div>
            <h3 class="text-base sm:text-lg font-bold text-gray-800">Riwayat Lengkap</h3>
            <p class="text-xs text-gray-500"><?= count($kunjungan_list) ?> kunjungan tercatat</p>
        </div>
    </div>

        <?php if (!empty($kunjungan_list)): ?>

            <!-- Desktop Table -->
            <div class="hidden md:block overflow-x-auto">
                <table class="w-full text-sm text-left whitespace-nowrap">
                    <thead class="text-xs text-gray-500 uppercase bg-gray-50 border-b border-gray-100">
                        <tr>
                            <th class="px-5 py-3 font-semibold">Tanggal</th>
                            <th class="px-5 py-3 font-semibold">Usia (mgg)</th>
                            <th class="px-5 py-3 font-semibold">Tekanan Darah</th>
                            <th class="px-5 py-3 font-semibold">Berat</th>
                            <th class="px-5 py-3 font-semibold">TFU</th>
                            <th class="px-5 py-3 font-semibold">Letak Janin</th>
                            <th class="px-5 py-3 font-semibold">DJJ</th>
                            <th class="px-5 py-3 font-semibold">Catatan</th>
                            <th class="px-5 py-3 font-semibold text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                    <?php foreach ($kunjungan_list as $kr): ?>
                        <?php $krJson = htmlspecialchars(json_encode([
                            'id'            => $kr['id'],
                            'tanggal'       => formatDate($kr['tanggal_kunjungan']),
                            'usia'          => $kr['usia_kehamilan_minggu'],
                            'tekanan_darah' => $kr['tekanan_darah'],
                            'berat_badan'   => $kr['berat_badan'] !== null ? $fmtDec($kr['berat_badan']) : null,
                            'tinggi_fundus' => $kr['tinggi_fundus'] !== null ? $fmtDec($kr['tinggi_fundus']) : null,
                            'letak_janin'   => $kr['letak_janin'],
                            'djj'           => $kr['denyut_jantung_janin'],
                            'catatan'       => $kr['catatan'],
                        ]), ENT_QUOTES); ?>
                        <tr class="hover:bg-gray-50 transition-colors">
                            <td class="px-5 py-3 font-medium text-gray-800"><?= formatDate($kr['tanggal_kunjungan']) ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['usia_kehamilan_minggu'] !== null ? escape($kr['usia_kehamilan_minggu']).' mgg' : '-' ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['tekanan_darah'] ? escape($kr['tekanan_darah']) : '-' ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['berat_badan'] !== null ? $fmtDec($kr['berat_badan']).' kg' : '-' ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['tinggi_fundus'] !== null ? $fmtDec($kr['tinggi_fundus']).' cm' : '-' ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['letak_janin'] ? escape($kr['letak_janin']) : '-' ?></td>
                            <td class="px-5 py-3 text-gray-700"><?= $kr['denyut_jantung_janin'] !== null ? escape($kr['denyut_jantung_janin']).' /mnt' : '-' ?></td>
                            <td class="px-5 py-3 text-gray-600 max-w-xs truncate"><?= $kr['catatan'] ? escape($kr['catatan']) : '-' ?></td>
                            <td class="px-5 py-3 text-center">
                                <div class="flex items-center justify-center gap-1">
                                    <button @click="show(<?= $krJson ?>)"
                                            class="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white transition-colors" title="Detail">
                                        <i class="fas fa-eye text-xs"></i>
                                    </button>
                                    <a href="cetak_kunjungan_pdf.php?id=<?= $kr['id'] ?>" target="_blank"
                                       class="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-red-50 text-red-500 hover:bg-red-500 hover:text-white transition-colors" title="Cetak PDF">
                                        <i class="fas fa-file-pdf text-xs"></i>
                                    </a>
                                    <a href="export_kunjungan_excel.php?id=<?= $kr['id'] ?>" target="_blank"
                                       class="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-emerald-50 text-emerald-600 hover:bg-emerald-600 hover:text-white transition-colors" title="Export Excel">
                                        <i class="fas fa-file-excel text-xs"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mobile Cards -->
            <div class="md:hidden divide-y divide-gray-100">
                <?php foreach ($kunjungan_list as $kr): ?>
                    <div class="p-4">
                        <?php $krJson = htmlspecialchars(json_encode([
                            'id'            => $kr['id'],
                            'tanggal'       => formatDate($kr['tanggal_kunjungan']),
                            'usia'          => $kr['usia_kehamilan_minggu'],
                            'tekanan_darah' => $kr['tekanan_darah'],
                            'berat_badan'   => $kr['berat_badan'] !== null ? $fmtDec($kr['berat_badan']) : null,
                            'tinggi_fundus' => $kr['tinggi_fundus'] !== null ? $fmtDec($kr['tinggi_fundus']) : null,
                            'letak_janin'   => $kr['letak_janin'],
                            'djj'           => $kr['denyut_jantung_janin'],
                            'catatan'       => $kr['catatan'],
                        ]), ENT_QUOTES); ?>
                        <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center text-xs">
                                    <i class="fas fa-calendar-check"></i>
                                </div>
                                <span class="font-bold text-gray-800 text-sm"><?= formatDate($kr['tanggal_kunjungan']) ?></span>
                            </div>
                            <?php if ($kr['usia_kehamilan_minggu'] !== null): ?>
                                <span class="text-xs font-bold bg-primary/10 text-primary px-2 py-0.5 rounded-full">
                                    <?= escape($kr['usia_kehamilan_minggu']) ?> minggu
                                </span>
                            <?php endif; ?>
                        </div>
                        <div class="grid grid-cols-3 gap-2 mb-2">
                            <div class="bg-red-50 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold text-red-400 uppercase tracking-wide mb-0.5">Tek. Darah</p>
                                <p class="text-xs font-bold text-gray-800"><?= $kr['tekanan_darah'] ? escape($kr['tekanan_darah']) : '-' ?></p>
                            </div>
                            <div class="bg-blue-50 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold text-blue-400 uppercase tracking-wide mb-0.5">Berat</p>
                                <p class="text-xs font-bold text-gray-800"><?= $kr['berat_badan'] !== null ? $fmtDec($kr['berat_badan']).' kg' : '-' ?></p>
                            </div>
                            <div class="bg-purple-50 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold text-purple-400 uppercase tracking-wide mb-0.5">TFU</p>
                                <p class="text-xs font-bold text-gray-800"><?= $kr['tinggi_fundus'] !== null ? $fmtDec($kr['tinggi_fundus']).' cm' : '-' ?></p>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-2">
                            <div class="bg-yellow-50 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold text-yellow-500 uppercase tracking-wide mb-0.5">Letak Janin</p>
                                <p class="text-xs font-bold text-gray-800"><?= $kr['letak_janin'] ? escape($kr['letak_janin']) : '-' ?></p>
                            </div>
                            <div class="bg-pink-50 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold text-pink-400 uppercase tracking-wide mb-0.5">DJJ</p>
                                <p class="text-xs font-bold text-gray-800"><?= $kr['denyut_jantung_janin'] !== null ? escape($kr['denyut_jantung_janin']).' /mnt' : '-' ?></p>
                            </div>
                        </div>
                        <?php if (!empty($kr['catatan'])): ?>
                            <div class="mt-2 bg-yellow-50 border border-yellow-100 rounded-xl p-3 text-xs text-yellow-800">
                                <p class="font-bold uppercase tracking-wide text-yellow-500 mb-0.5"><i class="fas fa-sticky-note mr-1"></i> Catatan</p>
                                <?= escape($kr['catatan']) ?>
                            </div>
                        <?php endif; ?>
                        <!-- Aksi mobile -->
                        <div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100">
                            <button @click="show(<?= $krJson ?>)"
                                    class="flex-1 inline-flex items-center justify-center gap-1.5 py-2 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white text-xs font-medium transition-colors">
                                <i class="fas fa-eye"></i> Detail
                            </button>
                            <a href="cetak_kunjungan_pdf.php?id=<?= $kr['id'] ?>" target="_blank"
                               class="flex-1 inline-flex items-center justify-center gap-1.5 py-2 rounded-lg bg-red-50 text-red-500 hover:bg-red-500 hover:text-white text-xs font-medium transition-colors">
                                <i class="fas fa-file-pdf"></i> PDF
                            </a>
                            <a href="export_kunjungan_excel.php?id=<?= $kr['id'] ?>" target="_blank"
                               class="flex-1 inline-flex items-center justify-center gap-1.5 py-2 rounded-lg bg-emerald-50 text-emerald-600 hover:bg-emerald-600 hover:text-white text-xs font-medium transition-colors">
                                <i class="fas fa-file-excel"></i> Excel
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

    <?php else: ?>
        <div class="p-8 sm:p-12 text-center text-gray-400">
            <i class="fas fa-inbox text-4xl mb-3 text-gray-300 block"></i>
            <p class="text-sm">Belum ada riwayat kunjungan tercatat.</p>
        </div>
    <?php endif; ?>
</div>
</div><!-- end x-data kunjunganModal -->

<script>
function kunjunganModal() {
    return {
        open: false,
        detail: { id:0, tanggal:'', usia:null, tekanan_darah:null, berat_badan:null, tinggi_fundus:null, letak_janin:null, djj:null, catatan:null },
        show(data) { this.detail = data; this.open = true; }
    };
}
</script>

<?php require_once '../includes/footer_user.php'; ?>
