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

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

$id = $_GET['id'];
$id_posyandu = $_SESSION['posyandu'];

// 1. Ambil Data Identitas Ibu
$stmt = $pdo->prepare("SELECT * FROM ibu_hamil WHERE id_bumil = ? AND id_posyandu = ?");
$stmt->execute([$id, $id_posyandu]);
$b = $stmt->fetch();

if (!$b) { 
    die("Data ibu hamil tidak ditemukan."); 
}

// Hitung Usia Kehamilan (Bulan) dari HPHT
$tgl_hpht = new DateTime($b['hpht']);
$tgl_sekarang = new DateTime();
$diff = $tgl_hpht->diff($tgl_sekarang);
$usia_bulan = ($diff->y * 12) + $diff->m;

// 2. Ambil data untuk Grafik BB (Pemeriksaan 6 bulan terakhir)
$stmt_g = $pdo->prepare("SELECT tgl_periksa, bb FROM pemeriksaan_bumil WHERE id_bumil = ? ORDER BY tgl_periksa ASC LIMIT 6");
$stmt_g->execute([$id]);
$grafik = $stmt_g->fetchAll();

$labels = []; $data_bb = [];
foreach($grafik as $g) {
    $labels[] = date('d/m', strtotime($g['tgl_periksa']));
    $data_bb[] = $g['bb'];
}

// 3. Ambil Riwayat Pemeriksaan Lengkap
$stmt_r = $pdo->prepare("SELECT * FROM pemeriksaan_bumil WHERE id_bumil = ? ORDER BY tgl_periksa DESC");
$stmt_r->execute([$id]);
$riwayat = $stmt_r->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Ibu Hamil - <?= $b['nama_bumil'] ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background: #f8f9fa; font-family: 'Segoe UI', sans-serif; }
        .header-blue { background: #0d6efd; color: white; padding: 40px 20px; border-bottom-left-radius: 30px; border-bottom-right-radius: 30px; text-align: center; position: relative; }
        .btn-back { position: absolute; left: 20px; top: 20px; color: white; font-size: 24px; text-decoration: none; }
        .badge-custom { border-radius: 20px; padding: 6px 15px; font-weight: bold; font-size: 11px; display: inline-block; margin: 5px 2px; }
        .card-custom { border-radius: 20px; border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.05); padding: 20px; margin-top: 20px; }
        .btn-periksa { background: #0d6efd; color: white; border-radius: 15px; padding: 15px; font-weight: bold; width: 100%; border: none; text-transform: uppercase; margin-top: 20px; text-decoration: none; display: block; text-align: center; box-shadow: 0 4px 10px rgba(13, 110, 253, 0.3); }
        
        /* Gaya Riwayat */
        .riwayat-item { background: white; padding: 15px; border-radius: 15px; margin-bottom: 15px; border-left: 5px solid #0d6efd; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .table-res { overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .table-riwayat { min-width: 500px; margin-top: 10px; }
        .table-riwayat th { font-size: 10px; text-transform: uppercase; color: #888; text-align: center; border: none; padding-bottom: 5px; }
        .table-riwayat td { font-size: 13px; font-weight: bold; text-align: center; border: none; padding-top: 0; }
        .text-kek { color: #dc3545; }
    </style>
</head>
<body>

<div class="header-blue">
    <a href="bumil_index.php" class="btn-back"><i class="bi bi-arrow-left"></i></a>
    <h3 class="fw-bold mb-1"><?= strtoupper($b['nama_bumil']) ?></h3>
    <p class="mb-2 opacity-75">Suami: <?= $b['nama_suami'] ?></p>
    
    <div class="mt-2">
        <span class="badge bg-white text-primary badge-custom">HPL: <?= date('d/m/Y', strtotime($b['hpl'])) ?></span>
        <span class="badge bg-warning text-dark badge-custom">UK: <?= $usia_bulan ?> Bulan</span>
    </div>
</div>

<div class="container pb-5">
    <div class="card card-custom bg-white">
        <h6 class="fw-bold text-muted mb-3"><i class="bi bi-graph-up text-primary"></i> Grafik Berat Badan</h6>
        <?php if(empty($data_bb)): ?>
            <div class="text-center py-4">
                <i class="bi bi-bar-chart text-light" style="font-size: 40px;"></i>
                <p class="text-muted small">Belum ada data untuk grafik</p>
            </div>
        <?php else: ?>
            <canvas id="chartBB" style="max-height: 180px;"></canvas>
        <?php endif; ?>
    </div>

    <a href="bumil_tambah_periksa.php?id=<?= $id ?>" class="btn btn-periksa">
        <i class="bi bi-plus-circle-fill me-2"></i> Periksa Sekarang
    </a>

    <h6 class="fw-bold text-muted mt-4 mb-3">RIWAYAT PEMERIKSAAN</h6>
    
    <?php if(empty($riwayat)): ?>
        <div class="card p-4 text-center text-muted rounded-4 border-0 shadow-sm">
            <i class="bi bi-clipboard-x fs-1 opacity-25"></i>
            <p class="mb-0 mt-2 small">Belum ada riwayat periksa</p>
        </div>
    <?php endif; ?>

    <?php foreach($riwayat as $r): ?>
    <div class="riwayat-item">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <div class="fw-bold text-dark" style="font-size: 14px;">
                    <i class="bi bi-calendar-check text-primary me-1"></i> <?= date('d M Y', strtotime($r['tgl_periksa'])) ?>
                </div>
                <div class="mt-1">
                    <span class="badge bg-primary-subtle text-primary border-primary border" style="font-size: 9px;"><?= $r['status_k'] ?></span>
                    <span class="badge <?= $r['tablet_tambah_darah'] == 'Ya' ? 'bg-success-subtle text-success border-success' : 'bg-secondary-subtle text-secondary border-secondary' ?> border" style="font-size: 9px;">TTD: <?= $r['tablet_tambah_darah'] ?></span>
                </div>
            </div>
            <div class="dropdown">
                <button class="btn btn-light btn-sm rounded-circle shadow-sm" data-bs-toggle="dropdown"><i class="bi bi-three-dots-vertical"></i></button>
                <ul class="dropdown-menu dropdown-menu-end shadow border-0">
                    <li><a class="dropdown-item small" href="bumil_edit_periksa.php?id_periksa=<?= $r['id_periksa_bumil'] ?>"><i class="bi bi-pencil me-2"></i> Edit</a></li>
                    <li><a class="dropdown-item small text-danger" href="bumil_hapus_periksa.php?id_periksa=<?= $r['id_periksa_bumil'] ?>&id_bumil=<?= $id ?>" onclick="return confirm('Hapus data pemeriksaan ini?')"><i class="bi bi-trash me-2"></i> Hapus</a></li>
                </ul>
            </div>
        </div>

        <div class="table-res">
            <table class="table table-riwayat">
                <thead>
                    <tr>
                        <th>BB</th>
                        <th>LILA</th>
                        <th>Tensi</th>
                        <th>TFU</th>
                        <th>HB</th>
                        <th>UK</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><?= $r['bb'] ?> <small class="text-muted fw-normal">kg</small></td>
                        <td class="<?= $r['lila'] < 23.5 ? 'text-kek' : '' ?>">
                            <?= $r['lila'] ?> <small class="text-muted fw-normal">cm</small>
                            <?= $r['lila'] < 23.5 ? '<i class="bi bi-exclamation-triangle-fill"></i>' : '' ?>
                        </td>
                        <td><?= $r['tensi'] ?></td>
                        <td><?= $r['tfu'] ?> <small class="text-muted fw-normal">cm</small></td>
                        <td><?= $r['hb'] ?> <small class="text-muted fw-normal">g/dL</small></td>
                        <td><?= $r['usia_kehamilan'] ?> <small class="text-muted fw-normal">mgg</small></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <?php if(!empty($r['keterangan'])): ?>
            <div class="mt-2 p-2 bg-light rounded-3 small text-muted" style="font-size: 11px;">
                <i class="bi bi-info-circle me-1 text-primary"></i> <?= $r['keterangan'] ?>
            </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>

<script>
<?php if(!empty($data_bb)): ?>
const ctx = document.getElementById('chartBB').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [{
            label: 'BB (kg)',
            data: <?= json_encode($data_bb) ?>,
            borderColor: '#0d6efd',
            backgroundColor: 'rgba(13, 110, 253, 0.1)',
            fill: true,
            tension: 0.4,
            pointRadius: 4,
            pointBackgroundColor: '#0d6efd'
        }]
    },
    options: {
        plugins: { legend: { display: false } },
        scales: { 
            y: { display: true, grid: { display: false }, ticks: { font: { size: 10 } } },
            x: { grid: { display: false }, ticks: { font: { size: 10 } } }
        }
    }
});
<?php endif; ?>
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>