<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';
require_once __DIR__ . '/../../functions/csrf.php';

$db = getDB();

$q = trim($_GET['q'] ?? '');

$sql = "SELECT kp.*, ih.nama_lengkap, ih.nik
        FROM kunjungan_posyandu kp
        JOIN ibu_hamil ih ON kp.ibu_hamil_id = ih.id";
$params = [];
if ($q !== '') {
    $sql .= " WHERE ih.nama_lengkap LIKE ? OR ih.nik LIKE ?";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
$sql .= " ORDER BY kp.tanggal_kunjungan DESC, kp.id DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$kunjungan_list = $stmt->fetchAll();

$total_all = $db->query("SELECT COUNT(*) FROM kunjungan_posyandu")->fetchColumn();

$fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : '-';

require_once __DIR__ . '/../../includes/header_admin.php';
?>

<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
    <div>
        <h1 class="text-2xl font-bold text-gray-800">Rekam Medis Kunjungan</h1>
        <p class="text-gray-500 text-sm mt-1">Kelola seluruh data kunjungan posyandu semua ibu hamil.</p>
    </div>
    <div>
        <a href="tambah.php"
           class="inline-flex items-center justify-center px-4 py-2 bg-primary hover:bg-primary-dark text-white font-medium rounded-lg transition-colors shadow-sm focus:ring-2 focus:ring-offset-2 focus:ring-primary">
            <i class="fas fa-plus mr-2"></i> Tambah Kunjungan
        </a>
    </div>
</div>

<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6">
    <div class="p-6 border-b border-gray-100 bg-gray-50/50">
        <form method="GET" class="flex flex-col md:flex-row gap-4">
            <div class="flex-grow">
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fas fa-search text-gray-400"></i>
                    </div>
                    <input type="text" name="q" value="<?= escape($q) ?>"
                           class="pl-10 w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-sm"
                           placeholder="Cari Nama / NIK ibu hamil...">
                </div>
            </div>
            <?php if ($q !== ''): ?>
                <div>
                    <a href="<?= BASE_URL ?>/admin/kunjungan/"
                       class="w-full md:w-auto px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg text-sm transition-colors inline-flex justify-center items-center">
                        Reset
                    </a>
                </div>
            <?php endif; ?>
        </form>
    </div>

    <div class="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-6 py-4 font-semibold">No</th>
                    <th class="px-6 py-4 font-semibold">Tanggal</th>
                    <th class="px-6 py-4 font-semibold">Nama / NIK</th>
                    <th class="px-6 py-4 font-semibold text-center">Usia (mgg)</th>
                    <th class="px-6 py-4 font-semibold text-center">Tekanan Darah</th>
                    <th class="px-6 py-4 font-semibold text-center">Berat (kg)</th>
                    <th class="px-6 py-4 font-semibold text-center">TFU (cm)</th>
                    <th class="px-6 py-4 font-semibold text-center">Letak Janin</th>
                    <th class="px-6 py-4 font-semibold text-center">DJJ (/mnt)</th>
                    <th class="px-6 py-4 font-semibold text-center">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
            <?php if (!empty($kunjungan_list)): ?>
                <?php $no = 1; foreach ($kunjungan_list as $k): ?>
                    <tr class="hover:bg-gray-50 transition-colors">
                        <td class="px-6 py-4 text-gray-500"><?= $no++ ?></td>
                        <td class="px-6 py-4 font-medium text-gray-800"><?= formatDate($k['tanggal_kunjungan']) ?></td>
                        <td class="px-6 py-4">
                            <div class="font-bold text-gray-900"><?= escape($k['nama_lengkap']) ?></div>
                            <div class="text-xs text-gray-500 mt-1"><?= escape($k['nik']) ?></div>
                        </td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $k['usia_kehamilan_minggu'] !== null ? escape($k['usia_kehamilan_minggu']) : '-' ?></td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $k['tekanan_darah'] ? escape($k['tekanan_darah']) : '-' ?></td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $fmtDec($k['berat_badan']) ?></td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $fmtDec($k['tinggi_fundus']) ?></td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $k['letak_janin'] ? escape($k['letak_janin']) : '-' ?></td>
                        <td class="px-6 py-4 text-center text-gray-700"><?= $k['denyut_jantung_janin'] !== null ? escape($k['denyut_jantung_janin']) : '-' ?></td>
                        <td class="px-6 py-4 text-center space-x-1">
                            <a href="<?= BASE_URL ?>/admin/ibu_hamil/kunjungan/edit.php?id=<?= $k['id'] ?>&back=kunjungan"
                               class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-yellow-50 text-yellow-600 hover:bg-yellow-500 hover:text-white transition-colors" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <form method="POST" action="<?= BASE_URL ?>/admin/ibu_hamil/kunjungan/hapus.php"
                                  onsubmit="return confirm('Hapus kunjungan tanggal <?= formatDate($k['tanggal_kunjungan']) ?> untuk <?= escape(addslashes($k['nama_lengkap'])) ?>?')"
                                  class="inline-block">
                                <?= csrfField() ?>
                                <input type="hidden" name="id" value="<?= $k['id'] ?>">
                                <input type="hidden" name="ibu_hamil_id" value="<?= $k['ibu_hamil_id'] ?>">
                                <input type="hidden" name="back" value="kunjungan">
                                <button type="submit"
                                        class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-50 text-red-600 hover:bg-red-600 hover:text-white transition-colors" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="10" class="px-6 py-12 text-center text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-3 text-gray-300 block"></i>
                        <?= $q !== '' ? 'Tidak ada kunjungan ditemukan untuk "' . escape($q) . '".' : 'Belum ada data kunjungan tercatat.' ?>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer_admin.php'; ?>
