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

$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: ./');
    exit;
}

$db = getDB();
$stmt = $db->prepare("SELECT ih.*, u.nama_lengkap as nama_bidan FROM ibu_hamil ih LEFT JOIN users u ON ih.bidan_id = u.id WHERE ih.id = ?");
$stmt->execute([$id]);
$ih = $stmt->fetch();

if (!$ih) {
    setFlash('error', 'Data tidak ditemukan.');
    header('Location: ./');
    exit;
}

// Riwayat kunjungan
$stmt = $db->prepare("SELECT * FROM kunjungan_posyandu WHERE ibu_hamil_id = ? ORDER BY tanggal_kunjungan DESC, id DESC");
$stmt->execute([$id]);
$kunjungan_list = $stmt->fetchAll();
$kunjungan_terbaru = $kunjungan_list[0] ?? null;
require_once __DIR__ . '/../../functions/csrf.php';
$csrfDelete = generateCSRFToken();

$dob = new DateTime($ih['tanggal_lahir']);
$today = new DateTime();
$umur = $today->diff($dob)->y;

$diff = (new DateTime($ih['hpht']))->diff(new DateTime())->days;
$minggu = intdiv($diff, 7);
$trimester = getTrimester($minggu);

// Akun default pass
$default_pass = date('dmY', strtotime($ih['tanggal_lahir']));
?>
<?php require_once '../../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">Detail Rekam Medis</h1>
        <p class="text-gray-500 text-sm mt-1">Informasi lengkap ibu hamil atas nama <strong class="text-gray-700"><?= escape($ih['nama_lengkap']) ?></strong></p>
    </div>
    <div class="flex items-center gap-2">
        <a href="edit.php?id=<?= $ih['id'] ?>" class="inline-flex items-center justify-center px-4 py-2 bg-yellow-500 hover:bg-yellow-600 text-white font-medium rounded-lg transition-colors shadow-sm focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500">
            <i class="fas fa-edit mr-2"></i> Edit Data
        </a>
        <a href="./" class="inline-flex items-center justify-center px-4 py-2 bg-white border border-gray-300 hover:bg-gray-50 text-gray-700 font-medium rounded-lg transition-colors shadow-sm focus:ring-2 focus:ring-offset-2 focus:ring-gray-200">
            <i class="fas fa-arrow-left mr-2"></i> Kembali
        </a>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Left Column: Details -->
    <div class="lg:col-span-2 space-y-6">
        
        <!-- Identitas Pribadi -->
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center gap-3 bg-gray-50/50">
                <div class="w-8 h-8 rounded bg-primary/10 text-primary flex items-center justify-center">
                    <i class="fas fa-id-card"></i>
                </div>
                <h3 class="font-bold text-gray-800 text-lg">Identitas Pribadi</h3>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-4">
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">NIK</p>
                        <p class="font-bold text-gray-900 text-base"><?= escape($ih['nik']) ?></p>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Nama Lengkap</p>
                        <p class="font-semibold text-gray-900 text-base"><?= escape($ih['nama_lengkap']) ?></p>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Tanggal Lahir & Umur</p>
                        <p class="font-medium text-gray-800"><?= formatDate($ih['tanggal_lahir']) ?> <span class="text-gray-500 text-sm">(<?= $umur ?> Tahun)</span></p>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Golongan Darah</p>
                        <p class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-red-100 text-red-800 border border-red-200">
                            <?= escape($ih['golongan_darah']) ?>
                        </p>
                    </div>
                    <div class="md:col-span-2">
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Alamat Lengkap</p>
                        <p class="font-medium text-gray-800"><?= escape($ih['alamat']) ?></p>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">No. HP / WhatsApp</p>
                        <p class="font-medium text-gray-800"><?= escape($ih['no_hp']) ?></p>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Suami & Kontak Suami</p>
                        <p class="font-medium text-gray-800"><?= escape($ih['nama_suami']) ?> <span class="text-gray-500 text-sm">(<?= escape($ih['no_hp_suami'] ?: '-') ?>)</span></p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Informasi Kehamilan -->
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center gap-3 bg-gray-50/50">
                <div class="w-8 h-8 rounded bg-accent/10 text-accent flex items-center justify-center">
                    <i class="fas fa-stethoscope"></i>
                </div>
                <h3 class="font-bold text-gray-800 text-lg">Informasi Kehamilan</h3>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                    <!-- Left Side Kehamilan -->
                    <div class="space-y-4">
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Kehamilan Ke-</span>
                            <span class="font-bold text-gray-900"><?= escape($ih['kehamilan_ke']) ?></span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">HPHT</span>
                            <span class="font-medium text-gray-800"><?= formatDate($ih['hpht']) ?></span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Usia Kehamilan</span>
                            <span class="font-bold text-primary"><?= $minggu ?> Minggu</span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Trimester</span>
                            <span class="font-bold text-accent">Trimester <?= $trimester ?></span>
                        </div>
                    </div>
                    
                    <!-- Right Side Kehamilan -->
                    <div class="space-y-4">
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Perkiraan Lahir (HPL)</span>
                            <span class="font-bold text-red-500"><?= formatDate($ih['hpl']) ?></span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Status</span>
                            <?php 
                            $status_color = match($ih['status']) {
                                'Aktif' => 'bg-sky-100 text-sky-800 border-sky-200',
                                'Melahirkan' => 'bg-blue-100 text-blue-800 border-blue-200',
                                'Keguguran' => 'bg-red-100 text-red-800 border-red-200',
                                'Pindah' => 'bg-gray-100 text-gray-800 border-gray-200',
                                default => 'bg-gray-100 text-gray-800 border-gray-200'
                            };
                            ?>
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold border <?= $status_color ?>">
                                <?= escape($ih['status']) ?>
                            </span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Bidan Penanggungjawab</span>
                            <span class="font-medium text-gray-800"><?= escape($ih['nama_bidan']) ?></span>
                        </div>
                        <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                            <span class="text-sm font-medium text-gray-500">Tanggal Daftar</span>
                            <span class="font-medium text-gray-600 text-sm"><?= formatDate($ih['tanggal_daftar']) ?></span>
                        </div>
                    </div>
                    
                    <!-- Catatan -->
                    <div class="md:col-span-2 mt-2">
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Catatan Khusus</p>
                        <?php if($ih['catatan']): ?>
                            <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-4 text-sm text-yellow-800">
                                <?= nl2br(escape($ih['catatan'])) ?>
                            </div>
                        <?php else: ?>
                            <p class="text-sm text-gray-400 italic">Tidak ada catatan medis khusus.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rekam Medis Terbaru -->
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between gap-3 bg-gray-50/50">
                <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded bg-rose-100 text-rose-600 flex items-center justify-center">
                        <i class="fas fa-heartbeat"></i>
                    </div>
                    <h3 class="font-bold text-gray-800 text-lg">Rekam Medis Terbaru</h3>
                </div>
                <a href="kunjungan/tambah.php?ibu_hamil_id=<?= (int)$ih['id'] ?>" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors">
                    <i class="fas fa-plus"></i> Tambah Kunjungan
                </a>
            </div>
            <div class="p-6">
                <?php if ($kunjungan_terbaru): ?>
                    <p class="text-xs text-gray-500 mb-4">Kunjungan tanggal <strong class="text-gray-700"><?= formatDate($kunjungan_terbaru['tanggal_kunjungan']) ?></strong><?= $kunjungan_terbaru['usia_kehamilan_minggu'] !== null ? ' &middot; Usia '.escape($kunjungan_terbaru['usia_kehamilan_minggu']).' minggu' : '' ?></p>
                    <div class="grid grid-cols-2 md:grid-cols-5 gap-3">
                        <?php
                        $fmtDec = fn($v) => $v !== null ? rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.') : null;
                        $cards = [
                            ['Tekanan Darah', $kunjungan_terbaru['tekanan_darah'] ? escape($kunjungan_terbaru['tekanan_darah']).' mmHg' : '-', 'fa-stethoscope', 'bg-red-50 border-red-100', 'text-red-500', 'text-red-600'],
                            ['Berat Badan', $kunjungan_terbaru['berat_badan'] !== null ? $fmtDec($kunjungan_terbaru['berat_badan']).' kg' : '-', 'fa-weight', 'bg-blue-50 border-blue-100', 'text-blue-500', 'text-blue-600'],
                            ['Tinggi Fundus', $kunjungan_terbaru['tinggi_fundus'] !== null ? $fmtDec($kunjungan_terbaru['tinggi_fundus']).' cm' : '-', 'fa-ruler-vertical', 'bg-purple-50 border-purple-100', 'text-purple-500', 'text-purple-600'],
                            ['Letak Janin', $kunjungan_terbaru['letak_janin'] ? escape($kunjungan_terbaru['letak_janin']) : '-', 'fa-baby', 'bg-yellow-50 border-yellow-100', 'text-yellow-600', 'text-yellow-700'],
                            ['DJJ', $kunjungan_terbaru['denyut_jantung_janin'] !== null ? escape($kunjungan_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 text-center">
                                <i class="fas <?= $icon ?> <?= $iconClass ?> text-base mb-1.5"></i>
                                <p class="text-[10px] font-bold uppercase tracking-wider <?= $labelClass ?> mb-0.5"><?= $label ?></p>
                                <p class="text-sm font-bold text-gray-800"><?= $val ?></p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if (!empty($kunjungan_terbaru['catatan'])): ?>
                        <div class="mt-4 bg-yellow-50 border border-yellow-200 rounded-xl p-3 text-sm text-yellow-800">
                            <i class="fas fa-sticky-note mr-1"></i> <?= nl2br(escape($kunjungan_terbaru['catatan'])) ?>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="text-center py-8 text-gray-400">
                        <i class="fas fa-notes-medical text-3xl mb-3 text-gray-300 block"></i>
                        <p class="text-sm">Belum ada data rekam medis kunjungan.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Riwayat Kunjungan -->
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center gap-3 bg-gray-50/50">
                <div class="w-8 h-8 rounded bg-emerald-100 text-emerald-600 flex items-center justify-center">
                    <i class="fas fa-clock-rotate-left"></i>
                </div>
                <h3 class="font-bold text-gray-800 text-lg">Riwayat Kunjungan Posyandu</h3>
                <span class="ml-auto text-xs font-medium text-gray-500"><?= count($kunjungan_list) ?> kunjungan</span>
            </div>
            <?php if (!empty($kunjungan_list)): ?>
                <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-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">TD</th>
                                <th class="px-5 py-3 font-semibold">BB</th>
                                <th class="px-5 py-3 font-semibold">TFU</th>
                                <th class="px-5 py-3 font-semibold">Letak</th>
                                <th class="px-5 py-3 font-semibold">DJJ</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): ?>
                            <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']) : '-' ?></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 ? rtrim(rtrim(number_format((float)$kr['berat_badan'], 2, '.', ''), '0'), '.').' kg' : '-' ?></td>
                                <td class="px-5 py-3 text-gray-700"><?= $kr['tinggi_fundus'] !== null ? rtrim(rtrim(number_format((float)$kr['tinggi_fundus'], 2, '.', ''), '0'), '.').' 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']) : '-' ?></td>
                                <td class="px-5 py-3 text-center space-x-1">
                                    <a href="kunjungan/edit.php?id=<?= (int)$kr['id'] ?>" 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 action="kunjungan/hapus.php" method="POST" class="inline-block" onsubmit="return confirm('Hapus data kunjungan tanggal <?= formatDate($kr['tanggal_kunjungan']) ?>?');">
                                        <input type="hidden" name="csrf_token" value="<?= $csrfDelete ?>">
                                        <input type="hidden" name="id" value="<?= (int)$kr['id'] ?>">
                                        <input type="hidden" name="ibu_hamil_id" value="<?= (int)$ih['id'] ?>">
                                        <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; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="p-8 text-center text-gray-400">
                    <i class="fas fa-inbox text-3xl mb-3 text-gray-300 block"></i>
                    <p class="text-sm">Belum ada riwayat kunjungan.</p>
                </div>
            <?php endif; ?>
        </div>

    </div>
    
    <!-- Right Column: Sidebar Info -->
    <div class="lg:col-span-1 space-y-6">
        
        <!-- Akun User -->
        <div class="bg-primary-dark text-white rounded-2xl shadow-lg border-t-4 border-accent overflow-hidden relative">
            <div class="absolute -right-4 -top-4 opacity-10">
                <i class="fas fa-mobile-alt text-8xl"></i>
            </div>
            <div class="p-6 relative z-10">
                <div class="flex items-center gap-3 mb-4">
                    <i class="fas fa-user-lock text-xl text-accent"></i>
                    <h3 class="font-bold text-lg">Akses Login User</h3>
                </div>
                <p class="text-white/70 text-sm mb-4 border-b border-white/10 pb-4">Akun login untuk ibu hamil terbuat secara otomatis untuk memantau dashboard pribadinya.</p>
                
                <div class="space-y-3 mb-4">
                    <div>
                        <p class="text-white/50 text-xs uppercase tracking-wider mb-1">Username (NIK)</p>
                        <div class="bg-black/20 rounded px-3 py-2 font-mono font-bold tracking-wider text-accent border border-white/10">
                            <?= escape($ih['nik']) ?>
                        </div>
                    </div>
                    <div>
                        <p class="text-white/50 text-xs uppercase tracking-wider mb-1">Password Awal</p>
                        <div class="bg-black/20 rounded px-3 py-2 font-mono font-bold tracking-wider text-accent border border-white/10">
                            <?= $default_pass ?>
                        </div>
                    </div>
                </div>
                
                <div class="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-3 text-xs text-yellow-200 flex gap-2 items-start mt-4">
                    <i class="fas fa-info-circle mt-0.5"></i>
                    <p>Password awal menggunakan tanggal lahir dengan format DDMMYYYY. Ibu hamil dapat mengubahnya setelah login.</p>
                </div>
            </div>
        </div>

    </div>
</div>

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